paragraph for gnunet devs that don't know how to use the web
[oweals/gnunet.git] / src / hello / hello.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2015 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      Affero General Public License for more details.
14     
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 /**
20  * @file hello/hello.c
21  * @brief helper library for handling HELLOs
22  * @author Christian Grothoff
23  * @author Matthias Wachs
24  */
25 #include "platform.h"
26 #include "gnunet_hello_lib.h"
27 #include "gnunet_protocols.h"
28 #include "gnunet_util_lib.h"
29 #include "gnunet_transport_plugin.h"
30
31 /**
32  * Context used for building our own URI.
33  */
34 struct GNUNET_HELLO_ComposeUriContext
35 {
36   /**
37    * Final URI.
38    */
39   char *uri;
40
41   /**
42    * Function for finding transport plugins by name.
43    */
44   GNUNET_HELLO_TransportPluginsFind plugins_find;
45 };
46
47
48 /**
49  * Context for #add_address_to_hello().
50  */
51 struct GNUNET_HELLO_ParseUriContext
52 {
53   /**
54    * Position in the URI with the next address to parse.
55    */
56   const char *pos;
57
58   /**
59    * Set to #GNUNET_SYSERR to indicate parse errors.
60    */
61   int ret;
62
63   /**
64    * Counter
65    */
66   unsigned int counter_total;
67
68   /**
69    * Counter skipped addresses
70    */
71   unsigned int counter_added;
72
73   /**
74    * Function for finding transport plugins by name.
75    */
76   GNUNET_HELLO_TransportPluginsFind plugins_find;
77 };
78
79
80 /**
81  * Return HELLO type
82  *
83  * @param h HELLO Message to test
84  * @return #GNUNET_YES for friend-only or #GNUNET_NO otherwise
85  */
86 int
87 GNUNET_HELLO_is_friend_only (const struct GNUNET_HELLO_Message *h)
88 {
89   if (GNUNET_YES == ntohl(h->friend_only))
90     return GNUNET_YES;
91   return GNUNET_NO;
92 }
93
94
95 /**
96  * Copy the given address information into
97  * the given buffer using the format of HELLOs.
98  *
99  * @param address the address
100  * @param expiration expiration for the @a address
101  * @param target where to copy the @a address
102  * @param max maximum number of bytes to copy to target
103  * @return number of bytes copied, 0 if
104  *         the target buffer was not big enough.
105  */
106 size_t
107 GNUNET_HELLO_add_address (const struct GNUNET_HELLO_Address *address,
108                           struct GNUNET_TIME_Absolute expiration,
109                           char *target,
110                           size_t max)
111 {
112   uint16_t alen;
113   size_t slen;
114   struct GNUNET_TIME_AbsoluteNBO exp;
115
116   slen = strlen (address->transport_name) + 1;
117   if (slen + sizeof (uint16_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO) +
118       address->address_length > max)
119     return 0;
120   exp = GNUNET_TIME_absolute_hton (expiration);
121   alen = htons ((uint16_t) address->address_length);
122   GNUNET_memcpy (target, address->transport_name, slen);
123   GNUNET_memcpy (&target[slen], &alen, sizeof (uint16_t));
124   slen += sizeof (uint16_t);
125   GNUNET_memcpy (&target[slen], &exp, sizeof (struct GNUNET_TIME_AbsoluteNBO));
126   slen += sizeof (struct GNUNET_TIME_AbsoluteNBO);
127   GNUNET_memcpy (&target[slen], address->address, address->address_length);
128   slen += address->address_length;
129   return slen;
130 }
131
132
133 /**
134  * Get the size of an address entry in a HELLO message.
135  *
136  * @param buf pointer to the start of the address entry
137  * @param max maximum size of the entry (end of @a buf)
138  * @param ralen set to the address length
139  * @return size of the entry, or 0 if @a max is not large enough
140  */
141 static size_t
142 get_hello_address_size (const char *buf,
143                         size_t max,
144                         uint16_t *ralen)
145 {
146   const char *pos;
147   uint16_t alen;
148   size_t left;
149   size_t slen;
150
151   left = max;
152   pos = buf;
153   slen = 1;
154   while ((left > 0) && ('\0' != *pos))
155   {
156     left--;
157     pos++;
158     slen++;
159   }
160   if (0 == left)
161   {
162     /* 0-termination not found */
163     GNUNET_break_op (0);
164     return 0;
165   }
166   pos++;
167   if (left < sizeof (uint16_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO))
168   {
169     /* not enough space for addrlen */
170     GNUNET_break_op (0);
171     return 0;
172   }
173   GNUNET_memcpy (&alen, pos, sizeof (uint16_t));
174   alen = ntohs (alen);
175   *ralen = alen;
176   slen += alen + sizeof (uint16_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO);
177   if (max < slen)
178   {
179     /* not enough space for addr */
180     GNUNET_break_op (0);
181     return 0;
182   }
183   return slen;
184 }
185
186
187 /**
188  * Construct a HELLO message given the public key,
189  * expiration time and an iterator that spews the
190  * transport addresses.
191  *
192  * If friend only is set to #GNUNET_YES we create a FRIEND_HELLO which
193  * will not be gossiped to other peers.
194  *
195  * @param public_key public key to include in the HELLO
196  * @param addrgen callback to invoke to get addresses
197  * @param addrgen_cls closure for @a addrgen
198  * @param friend_only should the returned HELLO be only visible to friends?
199  * @return the hello message
200  */
201 struct GNUNET_HELLO_Message *
202 GNUNET_HELLO_create (const struct GNUNET_CRYPTO_EddsaPublicKey *public_key,
203                      GNUNET_HELLO_GenerateAddressListCallback addrgen,
204                      void *addrgen_cls,
205                      int friend_only)
206 {
207   char buffer[GNUNET_MAX_MESSAGE_SIZE - 1 - 256 -
208               sizeof (struct GNUNET_HELLO_Message)];
209   size_t max;
210   size_t used;
211   size_t ret;
212   struct GNUNET_HELLO_Message *hello;
213
214   GNUNET_assert (NULL != public_key);
215   GNUNET_assert ( (GNUNET_YES == friend_only) ||
216                   (GNUNET_NO == friend_only) );
217   max = sizeof (buffer);
218   used = 0;
219   if (NULL != addrgen)
220   {
221     while (GNUNET_SYSERR != (ret = addrgen (addrgen_cls,
222                                             max,
223                                             &buffer[used])))
224     {
225       max -= ret;
226       used += ret;
227     }
228   }
229   hello = GNUNET_malloc (sizeof (struct GNUNET_HELLO_Message) + used);
230   hello->header.type = htons (GNUNET_MESSAGE_TYPE_HELLO);
231   hello->header.size = htons (sizeof (struct GNUNET_HELLO_Message) + used);
232   hello->friend_only = htonl (friend_only);
233   hello->publicKey = *public_key;
234   GNUNET_memcpy (&hello[1],
235           buffer,
236           used);
237   return hello;
238 }
239
240
241 /**
242  * Iterate over all of the addresses in the HELLO.
243  *
244  * @param msg HELLO to iterate over
245  * @param return_modified if a modified copy should be returned,
246  *         otherwise NULL will be returned
247  * @param it iterator to call on each address
248  * @param it_cls closure for @a it
249  * @return modified HELLO message
250  */
251 struct GNUNET_HELLO_Message *
252 GNUNET_HELLO_iterate_addresses (const struct GNUNET_HELLO_Message *msg,
253                                 int return_modified,
254                                 GNUNET_HELLO_AddressIterator it,
255                                 void *it_cls)
256 {
257   struct GNUNET_HELLO_Address address;
258   uint16_t msize;
259   struct GNUNET_HELLO_Message *ret;
260   const char *inptr;
261   size_t insize;
262   size_t esize;
263   size_t wpos;
264   char *woff;
265   uint16_t alen;
266   struct GNUNET_TIME_AbsoluteNBO expire;
267   int iret;
268
269   msize = GNUNET_HELLO_size (msg);
270   if ((msize < sizeof (struct GNUNET_HELLO_Message)) ||
271       (ntohs (msg->header.type) != GNUNET_MESSAGE_TYPE_HELLO))
272   {
273     GNUNET_break_op (0);
274     return NULL;
275   }
276   ret = NULL;
277   if (return_modified)
278   {
279     ret = GNUNET_malloc (msize);
280     GNUNET_memcpy (ret,
281             msg,
282             msize);
283   }
284   inptr = (const char *) &msg[1];
285   insize = msize - sizeof (struct GNUNET_HELLO_Message);
286   wpos = 0;
287   woff = (NULL != ret) ? (char *) &ret[1] : NULL;
288   address.peer.public_key = msg->publicKey;
289   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
290               "HELLO has %u bytes of address data\n",
291               (unsigned int) insize);
292   
293   while (insize > 0)
294   {
295     esize = get_hello_address_size (inptr,
296                                     insize,
297                                     &alen);
298     if (0 == esize)
299     {
300       GNUNET_break (0);
301       GNUNET_free_non_null (ret);
302       return NULL;
303     }
304     /* need GNUNET_memcpy() due to possibility of misalignment */
305     GNUNET_memcpy (&expire,
306             &inptr[esize - alen - sizeof (struct GNUNET_TIME_AbsoluteNBO)],
307             sizeof (struct GNUNET_TIME_AbsoluteNBO));
308     address.address = &inptr[esize - alen];
309     address.address_length = alen;
310     address.transport_name = inptr;
311     address.local_info = GNUNET_HELLO_ADDRESS_INFO_NONE;
312     iret = it (it_cls,
313                &address,
314                GNUNET_TIME_absolute_ntoh (expire));
315     if (GNUNET_SYSERR == iret)
316       break;
317     if ( (GNUNET_OK == iret) &&
318          (NULL != ret) )
319     {
320       /* copy address over */
321       GNUNET_memcpy (woff,
322               inptr,
323               esize);
324       woff += esize;
325       wpos += esize;
326     }
327     insize -= esize;
328     inptr += esize;
329   }
330   if (NULL != ret)
331     ret->header.size = ntohs (sizeof (struct GNUNET_HELLO_Message) + wpos);
332   return ret;
333 }
334
335
336 /**
337  * Closure for #get_match_exp().
338  */
339 struct ExpireContext
340 {
341   /**
342    * Address we are looking for.
343    */
344   const struct GNUNET_HELLO_Address *address;
345
346   /**
347    * Set to #GNUNET_YES if we found the @e address.
348    */
349   int found;
350
351   /**
352    * Set to the expiration of the match if @e found is #GNUNET_YES.
353    */
354   struct GNUNET_TIME_Absolute expiration;
355 };
356
357
358 /**
359  * Store the expiration time of an address that matches the template.
360  *
361  * @param cls the `struct ExpireContext`
362  * @param address address to match against the template
363  * @param expiration expiration time of @a address, to store in @a cls
364  * @return #GNUNET_SYSERR if we found a matching address, #GNUNET_OK otherwise
365  */
366 static int
367 get_match_exp (void *cls,
368                const struct GNUNET_HELLO_Address *address,
369                struct GNUNET_TIME_Absolute expiration)
370 {
371   struct ExpireContext *ec = cls;
372
373   if (0 != GNUNET_HELLO_address_cmp (address,
374                                      ec->address))
375     return GNUNET_OK;
376   ec->found = GNUNET_YES;
377   ec->expiration = expiration;
378   return GNUNET_SYSERR;       /* done here */
379 }
380
381
382 /**
383  * Context for a #GNUNET_HELLO_Merge operation.
384  */
385 struct MergeContext
386 {
387   /**
388    * First HELLO we are merging.
389    */
390   const struct GNUNET_HELLO_Message *h1;
391
392   /**
393    * Second HELLO we are merging.
394    */
395   const struct GNUNET_HELLO_Message *h2;
396
397   /**
398    * Either @e h1 or @e h2, used when copying
399    * to compare against (so we only copy the
400    * most recent entry).
401    */
402   const struct GNUNET_HELLO_Message *other;
403
404   /**
405    * Buffer where we copy to.
406    */
407   char *buf;
408
409   /**
410    * Number of bytes allocated in @e buf
411    */
412   size_t max;
413
414   /**
415    * Current (write) offset in @e buf.
416    */
417   size_t ret;
418
419   /**
420    * Should we copy addresses with an identical value
421    * and expiration time in @e other, or do we only
422    * copy addresses with strictly later expiration times?
423    */
424   int take_equal;
425
426 };
427
428
429 /**
430  * Append the address @a address to the buffer from
431  * the merge context IF it is more recent than equivalent
432  * addresses in `other`.
433  *
434  * @param cls the `struct MergeContext`
435  * @param address the HELLO address we might copy
436  * @param expiration expiration time for @a address
437  * @return always #GNUNET_OK
438  */
439 static int
440 copy_latest (void *cls,
441              const struct GNUNET_HELLO_Address *address,
442              struct GNUNET_TIME_Absolute expiration)
443 {
444   struct MergeContext *mc = cls;
445   struct ExpireContext ec;
446
447   ec.address = address;
448   ec.found = GNUNET_NO;
449   /* check if address exists in other */
450   GNUNET_HELLO_iterate_addresses (mc->other,
451                                   GNUNET_NO,
452                                   &get_match_exp,
453                                   &ec);
454   if ( (GNUNET_NO == ec.found) ||
455        (ec.expiration.abs_value_us < expiration.abs_value_us) ||
456        ( (ec.expiration.abs_value_us == expiration.abs_value_us) &&
457          (GNUNET_YES == mc->take_equal) ) )
458   {
459     /* copy address to buffer */
460     mc->ret +=
461         GNUNET_HELLO_add_address (address,
462                                   expiration,
463                                   &mc->buf[mc->ret],
464                                   mc->max - mc->ret);
465   }
466   return GNUNET_OK;
467 }
468
469
470 /**
471  * Function called to build the HELLO during
472  * #GNUNET_HELLO_merge() by merging addresses from
473  * two original HELLOs.
474  *
475  * @param cls the `struct MergeContext`
476  * @param max number of bytes we can write at most in @a buf
477  * @param buf where to copy the addresses
478  * @return #GNUNET_SYSERR to end iteration, otherwise number of bytes written to @a buf
479  */
480 static ssize_t
481 merge_addr (void *cls,
482             size_t max,
483             void *buf)
484 {
485   struct MergeContext *mc = cls;
486
487   if (NULL == mc->h1)
488     return GNUNET_SYSERR; /* Stop iteration */
489   mc->ret = 0;
490   mc->max = max;
491   mc->buf = buf;
492   mc->take_equal = GNUNET_NO;
493   mc->other = mc->h2;
494   /* copy addresses from h1, if strictly larger expiration than h2 */
495   GNUNET_HELLO_iterate_addresses (mc->h1,
496                                   GNUNET_NO,
497                                   &copy_latest,
498                                   mc);
499   mc->take_equal = GNUNET_YES;
500   mc->other = mc->h1;
501   /* copy addresses from h2, if larger or equal expiration than h1 */
502   GNUNET_HELLO_iterate_addresses (mc->h2,
503                                   GNUNET_NO,
504                                   &copy_latest,
505                                   mc);
506   /* set marker to stop iteration */
507   mc->h1 = NULL;
508   return mc->ret;
509 }
510
511
512 /**
513  * Construct a HELLO message by merging the
514  * addresses in two existing HELLOs (which
515  * must be for the same peer).
516  *
517  * @param h1 first HELLO message
518  * @param h2 the second HELLO message
519  * @return the combined HELLO message
520  */
521 struct GNUNET_HELLO_Message *
522 GNUNET_HELLO_merge (const struct GNUNET_HELLO_Message *h1,
523                     const struct GNUNET_HELLO_Message *h2)
524 {
525   struct MergeContext mc = { h1, h2, NULL, NULL, 0, 0, 0 };
526   int friend_only;
527
528   if (h1->friend_only != h2->friend_only)
529     friend_only = GNUNET_YES; /* One of the HELLOs is friend only */
530   else
531     friend_only = ntohl (h1->friend_only); /* Both HELLO's have the same type */
532
533   return GNUNET_HELLO_create (&h1->publicKey,
534                               &merge_addr,
535                               &mc,
536                               friend_only);
537 }
538
539
540 /**
541  * Context used in #GNUNET_HELLO_iterate_new_addresses() to
542  * figure out which addresses are in fact 'new'.
543  */
544 struct DeltaContext
545 {
546   /**
547    * We should ignore addresses that expire before this time.
548    */
549   struct GNUNET_TIME_Absolute expiration_limit;
550
551   /**
552    * Function to call on addresses that are indeed new.
553    */
554   GNUNET_HELLO_AddressIterator it;
555
556   /**
557    * Closure for @e it.
558    */
559   void *it_cls;
560
561   /**
562    * HELLO with known addresses, addresses in this HELLO
563    * we must always ignore.
564    */
565   const struct GNUNET_HELLO_Message *old_hello;
566 };
567
568
569 /**
570  * Check if the given address is 'new', and if so, call
571  * the iterator.  Compares the existing address against
572  * addresses in the context's `old_hello` and calls the
573  * iterator on those that are new (and not expired).
574  *
575  * @param cls the `struct DeltaContext`
576  * @param address an address to check whether it is new
577  * @param expiration expiration time for @a address
578  * @return #GNUNET_YES if the address is ignored, otherwise
579  *         whatever the iterator returned.
580  */
581 static int
582 delta_match (void *cls,
583              const struct GNUNET_HELLO_Address *address,
584              struct GNUNET_TIME_Absolute expiration)
585 {
586   struct DeltaContext *dc = cls;
587   int ret;
588   struct ExpireContext ec;
589
590   ec.address = address;
591   ec.found = GNUNET_NO;
592   GNUNET_HELLO_iterate_addresses (dc->old_hello,
593                                   GNUNET_NO,
594                                   &get_match_exp,
595                                   &ec);
596   if ( (GNUNET_YES == ec.found) &&
597        ( (ec.expiration.abs_value_us > expiration.abs_value_us) ||
598          (ec.expiration.abs_value_us >= dc->expiration_limit.abs_value_us)))
599     return GNUNET_YES;          /* skip: found and boring */
600   ret = dc->it (dc->it_cls,
601                 address,
602                 expiration);
603   return ret;
604 }
605
606
607 /**
608  * Iterate over addresses in @a new_hello that are NOT already present
609  * in @a old_hello.  Note that if the address is present in @a old_hello
610  * but the expiration time in @a new_hello is more recent, the iterator
611  * is also called.
612  *
613  * @param new_hello a HELLO message
614  * @param old_hello a HELLO message
615  * @param expiration_limit ignore addresses in @a old_hello
616  *        that expired before the given time stamp
617  * @param it iterator to call on each address
618  * @param it_cls closure for @a it
619  */
620 void
621 GNUNET_HELLO_iterate_new_addresses (const struct GNUNET_HELLO_Message *new_hello,
622                                     const struct GNUNET_HELLO_Message *old_hello,
623                                     struct GNUNET_TIME_Absolute expiration_limit,
624                                     GNUNET_HELLO_AddressIterator it,
625                                     void *it_cls)
626 {
627   struct DeltaContext dc;
628
629   dc.expiration_limit = expiration_limit;
630   dc.it = it;
631   dc.it_cls = it_cls;
632   dc.old_hello = old_hello;
633   GNUNET_assert (NULL ==
634                  GNUNET_HELLO_iterate_addresses (new_hello,
635                                                  GNUNET_NO,
636                                                  &delta_match,
637                                                  &dc));
638 }
639
640
641 /**
642  * Return the size of the given HELLO message.
643  * @param hello to inspect
644  * @return the size, 0 if HELLO is invalid
645  */
646 uint16_t
647 GNUNET_HELLO_size (const struct GNUNET_HELLO_Message *hello)
648 {
649   uint16_t ret = ntohs (hello->header.size);
650
651   if ((ret < sizeof (struct GNUNET_HELLO_Message)) ||
652       (ntohs (hello->header.type) != GNUNET_MESSAGE_TYPE_HELLO))
653     return 0;
654   return ret;
655 }
656
657
658 /**
659  * Get the peer identity from a HELLO message.
660  *
661  * @param hello the hello message
662  * @param peer where to store the peer's identity
663  * @return #GNUNET_SYSERR if the HELLO was malformed
664  */
665 int
666 GNUNET_HELLO_get_id (const struct GNUNET_HELLO_Message *hello,
667                      struct GNUNET_PeerIdentity *peer)
668 {
669   uint16_t ret = ntohs (hello->header.size);
670
671   if ((ret < sizeof (struct GNUNET_HELLO_Message)) ||
672       (ntohs (hello->header.type) != GNUNET_MESSAGE_TYPE_HELLO))
673     return GNUNET_SYSERR;
674   peer->public_key = hello->publicKey;
675   return GNUNET_OK;
676 }
677
678
679 /**
680  * Get the header from a HELLO message, used so other code
681  * can correctly send HELLO messages.
682  *
683  * @param hello the hello message
684  *
685  * @return header or NULL if the HELLO was malformed
686  */
687 struct GNUNET_MessageHeader *
688 GNUNET_HELLO_get_header (struct GNUNET_HELLO_Message *hello)
689 {
690   uint16_t ret = ntohs (hello->header.size);
691
692   if ((ret < sizeof (struct GNUNET_HELLO_Message)) ||
693       (ntohs (hello->header.type) != GNUNET_MESSAGE_TYPE_HELLO))
694     return NULL;
695
696   return &hello->header;
697 }
698
699
700 /**
701  * Context used for comparing HELLOs in #GNUNET_HELLO_equals().
702  */
703 struct EqualsContext
704 {
705   /**
706    * Addresses that expired before this date are ignored for
707    * the comparisson.
708    */
709   struct GNUNET_TIME_Absolute expiration_limit;
710
711   /**
712    * Earliest expiration time for which we found a match
713    * with a difference in expiration times.
714    * At this time, the two HELLOs may start to diverge.
715    */
716   struct GNUNET_TIME_Absolute result;
717
718   /**
719    * HELLO message to compare against. (First set to the second
720    * HELLO, then set to the first HELLO.)
721    */
722   const struct GNUNET_HELLO_Message *ref;
723
724   /**
725    * Address we are currently looking for.
726    */
727   const struct GNUNET_HELLO_Address *address;
728
729   /**
730    * Expiration time of @e address.
731    */
732   struct GNUNET_TIME_Absolute expiration;
733
734   /**
735    * Did we find the address we were looking for?
736    */
737   int found;
738
739 };
740
741
742 /**
743  * Check if the given address matches the address we are currently
744  * looking for. If so, sets `found` to #GNUNET_YES and, if the
745  * expiration times for the two addresses differ, updates `result` to
746  * the minimum of our @a expiration and the existing value
747  *
748  * @param cls the `struct EqualsContext`
749  * @param address address from the reference HELLO
750  * @param expiration expiration time for @a address
751  * @return #GNUNET_YES if the address is expired or does not match
752  *         #GNUNET_SYSERR if the address does match.
753  */
754 static int
755 find_other_matching (void *cls,
756                      const struct GNUNET_HELLO_Address *address,
757                      struct GNUNET_TIME_Absolute expiration)
758 {
759   struct EqualsContext *ec = cls;
760
761   if (expiration.abs_value_us < ec->expiration_limit.abs_value_us)
762     return GNUNET_YES;
763   if (0 == GNUNET_HELLO_address_cmp (address, ec->address))
764   {
765     ec->found = GNUNET_YES;
766     if (expiration.abs_value_us < ec->expiration.abs_value_us)
767       ec->result = GNUNET_TIME_absolute_min (expiration,
768                                              ec->result);
769     return GNUNET_SYSERR;
770   }
771   return GNUNET_YES;
772 }
773
774
775 /**
776  * Helper function for #GNUNET_HELLO_equals().  Checks
777  * if the given @a address exists also in the other HELLO;
778  * if not, the result time is set to zero and the iteration
779  * is aborted.
780  *
781  * @param cls the `struct EqualsContext`
782  * @param address address to locate
783  * @param expiration expiration time of the current address
784  * @return #GNUNET_OK if the address exists or is expired,
785  *         #GNUNET_SYSERR if it was not found
786  */
787 static int
788 find_matching (void *cls,
789                const struct GNUNET_HELLO_Address *address,
790                struct GNUNET_TIME_Absolute expiration)
791 {
792   struct EqualsContext *ec = cls;
793
794   if (expiration.abs_value_us < ec->expiration_limit.abs_value_us)
795     return GNUNET_OK; /* expired, we don't care */
796   ec->address = address;
797   ec->expiration = expiration;
798   ec->found = GNUNET_NO;
799   GNUNET_HELLO_iterate_addresses (ec->ref,
800                                   GNUNET_NO,
801                                   &find_other_matching,
802                                   ec);
803   if (GNUNET_NO == ec->found)
804   {
805     /* not found, we differ *now* */
806     ec->result = GNUNET_TIME_UNIT_ZERO_ABS;
807     return GNUNET_SYSERR;
808   }
809   return GNUNET_OK;
810 }
811
812
813 /**
814  * Test if two HELLO messages contain the same addresses.
815  * If they only differ in expiration time, the lowest
816  * expiration time larger than @a now where they differ
817  * is returned.
818  *
819  * @param h1 first HELLO message
820  * @param h2 the second HELLO message
821  * @param now time to use for deciding which addresses have
822  *            expired and should not be considered at all
823  * @return absolute time forever if the two HELLOs are
824  *         totally identical; smallest timestamp >= @a now if
825  *         they only differ in timestamps;
826  *         zero if the some addresses with expirations >= @a now
827  *         do not match at all
828  */
829 struct GNUNET_TIME_Absolute
830 GNUNET_HELLO_equals (const struct GNUNET_HELLO_Message *h1,
831                      const struct GNUNET_HELLO_Message *h2,
832                      struct GNUNET_TIME_Absolute now)
833 {
834   struct EqualsContext ec;
835
836   if (h1->header.type != h2->header.type)
837     return GNUNET_TIME_UNIT_ZERO_ABS;
838   if (0 !=
839       memcmp (&h1->publicKey,
840               &h2->publicKey,
841               sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)))
842     return GNUNET_TIME_UNIT_ZERO_ABS;
843   ec.expiration_limit = now;
844   ec.result = GNUNET_TIME_UNIT_FOREVER_ABS;
845   ec.ref = h2;
846   GNUNET_HELLO_iterate_addresses (h1,
847                                   GNUNET_NO,
848                                   &find_matching,
849                                   &ec);
850   if (ec.result.abs_value_us == GNUNET_TIME_UNIT_ZERO.rel_value_us)
851     return ec.result;
852   ec.ref = h1;
853   GNUNET_HELLO_iterate_addresses (h2,
854                                   GNUNET_NO,
855                                   &find_matching,
856                                   &ec);
857   return ec.result;
858 }
859
860
861 /**
862  * Iterator to find the time when the last address will expire.
863  * Updates the maximum value stored in @a cls.
864  *
865  * @param cls where to store the max, a `struct GNUNET_TIME_Absolute`
866  * @param address an address (ignored)
867  * @param expiration expiration time for @a address
868  * @return #GNUNET_OK (always)
869  */
870 static int
871 find_max_expire (void *cls,
872                  const struct GNUNET_HELLO_Address *address,
873                  struct GNUNET_TIME_Absolute expiration)
874 {
875   struct GNUNET_TIME_Absolute *max = cls;
876
877   *max = GNUNET_TIME_absolute_max (*max, expiration);
878   return GNUNET_OK;
879 }
880
881
882 /**
883  * When does the last address in the given HELLO expire?
884  *
885  * @param msg HELLO to inspect
886  * @return time the last address expires, 0 if there are no addresses in the HELLO
887  */
888 struct GNUNET_TIME_Absolute
889 GNUNET_HELLO_get_last_expiration (const struct GNUNET_HELLO_Message *msg)
890 {
891   struct GNUNET_TIME_Absolute ret;
892
893   ret = GNUNET_TIME_UNIT_ZERO_ABS;
894   GNUNET_HELLO_iterate_addresses (msg,
895                                   GNUNET_NO,
896                                   &find_max_expire,
897                                   &ret);
898   return ret;
899 }
900
901
902 /**
903  * GNUnet URIs are of the general form "gnunet://MODULE/IDENTIFIER".
904  * The specific structure of "IDENTIFIER" depends on the module and
905  * maybe differenciated into additional subcategories if applicable.
906  * This module only deals with hello identifiers (MODULE = "hello").
907  * <p>
908  *
909  * The concrete URI format is:
910  *
911  * "gnunet://hello/PEER[+YYYYMMDDHHMMSS+<TYPE>+<ADDRESS>]...".
912  * These URIs can be used to add a peer record to peerinfo service.
913  * PEER is the string representation of peer's public key.
914  * YYYYMMDDHHMMSS is the expiration date.
915  * TYPE is a transport type.
916  * ADDRESS is the address, its format depends upon the transport type.
917  * The concrete transport types and corresponding address formats are:
918  *
919  * <ul><li>
920  *
921  * <TCP|UDP>!IPADDRESS
922  * IPVDDRESS is either IPV4 .-delimited address in form of XXX.XXX.XXX.XXX:PPPPP
923  * or IPV6 :-delimited address  with '[' and ']' (according to RFC2732):
924  * [XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX]:PPPPP
925  * PPPPP is the port number. May be 0.
926  *
927  * </li><li>
928  *
929  * [add SMTP, HTTP and other addresses here]
930  *
931  * </li></ul>
932  *
933  * The encoding for hexadecimal values is defined in the crypto_hash.c
934  * module in the gnunetutil library and discussed there.
935  *
936  * Examples:
937  *
938  * gnunet://hello/V8XXK9GAN5ZJFRFQP8MQX3D83BZTSBQVHKWWD0JPE63Z821906EG+20120302010059+TCP+192.168.0.1:2086+TCP+64.23.8.174:0
939  * gnunet://hello/V8XXK9GAN5ZJFRFQP8MQX3D83BZTSBQVHKWWD0JPE63Z821906EG+20120302010059+TCP+[2001:db8:85a3:8d3:1319:8a2e:370:7348]:2086
940  *
941  * <p>
942  */
943
944
945
946 /**
947  * Function that is called on each address of this peer.
948  * Expands the corresponding URI string.
949  *
950  * @param cls the `struct GNUNET_HELLO_ComposeUriContext`
951  * @param address address to add
952  * @param expiration expiration time for the address
953  * @return #GNUNET_OK (continue iteration).
954  */
955 static int
956 add_address_to_uri (void *cls,
957                     const struct GNUNET_HELLO_Address *address,
958                     struct GNUNET_TIME_Absolute expiration)
959 {
960   struct GNUNET_HELLO_ComposeUriContext *ctx = cls;
961   struct GNUNET_TRANSPORT_PluginFunctions *papi;
962   const char *addr;
963   char *ret;
964   char *addr_dup;
965   char *pos;
966   char tbuf[16] = "";
967   char *client_str = "_client";
968   struct tm *t;
969   time_t seconds;
970
971   papi = ctx->plugins_find (address->transport_name);
972   if (NULL == papi)
973   {
974     /* Not an error - we might just not have the right plugin. */
975     return GNUNET_OK;
976   }
977   if (NULL == papi->address_to_string)
978   {
979     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
980                 "URI conversion not implemented for plugin `%s'\n",
981                 address->transport_name);
982     return GNUNET_OK;
983   }
984   addr = papi->address_to_string (papi->cls,
985                                   address->address,
986                                   address->address_length);
987   if ( (NULL == addr) ||
988        (0 == strlen(addr)) )
989     return GNUNET_OK;
990
991   addr_dup = GNUNET_strdup (addr);
992   if (NULL != (pos = strstr (addr_dup, "_server")))
993     GNUNET_memcpy (pos,
994             client_str,
995             strlen (client_str)); /* Replace all server addresses with client addresses */
996
997   seconds = expiration.abs_value_us / 1000LL / 1000LL;
998   t = gmtime (&seconds);
999
1000   GNUNET_asprintf (&ret,
1001                    "%s%c%s%c%s%c%s",
1002                    ctx->uri,
1003                    GNUNET_HELLO_URI_SEP,
1004                    strftime (tbuf,
1005                              sizeof (tbuf),
1006                              "%Y%m%d%H%M%S",
1007                              t) ? tbuf : "0",
1008                    GNUNET_HELLO_URI_SEP,
1009                    address->transport_name,
1010                    GNUNET_HELLO_URI_SEP,
1011                    addr_dup);
1012   GNUNET_free (addr_dup);
1013   GNUNET_free (ctx->uri);
1014   ctx->uri = ret;
1015   return GNUNET_OK;
1016 }
1017
1018
1019 /**
1020  * Compose a hello URI string from a hello message.
1021  *
1022  * @param hello Hello message
1023  * @param plugins_find Function to find transport plugins by name
1024  * @return Hello URI string
1025  */
1026 char *
1027 GNUNET_HELLO_compose_uri (const struct GNUNET_HELLO_Message *hello,
1028                           GNUNET_HELLO_TransportPluginsFind plugins_find)
1029 {
1030   struct GNUNET_HELLO_ComposeUriContext ctx;
1031   char *pkey;
1032
1033   ctx.plugins_find = plugins_find;
1034   pkey = GNUNET_CRYPTO_eddsa_public_key_to_string (&hello->publicKey);
1035   GNUNET_asprintf (&ctx.uri,
1036                    "%s%s",
1037                    (GNUNET_YES == GNUNET_HELLO_is_friend_only (hello))
1038                    ? GNUNET_FRIEND_HELLO_URI_PREFIX
1039                    : GNUNET_HELLO_URI_PREFIX,
1040                    pkey);
1041   GNUNET_free (pkey);
1042   GNUNET_HELLO_iterate_addresses (hello,
1043                                   GNUNET_NO,
1044                                   &add_address_to_uri,
1045                                   &ctx);
1046   return ctx.uri;
1047 }
1048
1049
1050 /* ************************* Parse HELLO URI ********************* */
1051
1052
1053 /**
1054  * We're building a HELLO.  Parse the next address from the
1055  * parsing context and append it.
1056  *
1057  * @param cls the `struct GNUNET_HELLO_ParseUriContext`
1058  * @param max number of bytes available for HELLO construction
1059  * @param buffer where to copy the next address (in binary format)
1060  * @return number of bytes added to buffer, #GNUNET_SYSERR on error
1061  */
1062 static ssize_t
1063 add_address_to_hello (void *cls,
1064                       size_t max,
1065                       void *buffer)
1066 {
1067   struct GNUNET_HELLO_ParseUriContext *ctx = cls;
1068   const char *tname;
1069   const char *address;
1070   char *uri_address;
1071   const char *end;
1072   char *plugin_name;
1073   struct tm expiration_time;
1074   time_t expiration_seconds;
1075   struct GNUNET_TIME_Absolute expire;
1076   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1077   void *addr;
1078   size_t addr_len;
1079   struct GNUNET_HELLO_Address haddr;
1080   ssize_t ret;
1081
1082   if (NULL == ctx->pos)
1083     return GNUNET_SYSERR;
1084   if (GNUNET_HELLO_URI_SEP != ctx->pos[0])
1085   {
1086     ctx->ret = GNUNET_SYSERR;
1087     GNUNET_break (0);
1088     return GNUNET_SYSERR;
1089   }
1090   ctx->pos++;
1091
1092   if ( ('0' == ctx->pos[0]) &&
1093        (GNUNET_HELLO_URI_SEP == ctx->pos[1]) )
1094   {
1095     expire = GNUNET_TIME_UNIT_FOREVER_ABS;
1096     tname = ctx->pos + 1;
1097   }
1098   else
1099   {
1100     memset (&expiration_time, 0, sizeof (expiration_time));
1101     tname = strptime (ctx->pos,
1102                       "%Y%m%d%H%M%S",
1103                       &expiration_time);
1104     if (NULL == tname)
1105     {
1106       ctx->ret = GNUNET_SYSERR;
1107       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1108                   _("Failed to parse HELLO message: missing expiration time\n"));
1109       GNUNET_break (0);
1110       return GNUNET_SYSERR;
1111     }
1112
1113     expiration_seconds = mktime (&expiration_time);
1114     if (expiration_seconds == (time_t) -1)
1115     {
1116       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1117                   _("Failed to parse HELLO message: invalid expiration time\n"));
1118       ctx->ret = GNUNET_SYSERR;
1119       GNUNET_break (0);
1120       return GNUNET_SYSERR;
1121     }
1122     expire.abs_value_us = expiration_seconds * 1000LL * 1000LL;
1123   }
1124   if (GNUNET_HELLO_URI_SEP != tname[0])
1125   {
1126     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1127                 _("Failed to parse HELLO message: malformed\n"));
1128     ctx->ret = GNUNET_SYSERR;
1129     GNUNET_break (0);
1130     return GNUNET_SYSERR;
1131   }
1132   tname++;
1133   address = strchr (tname,
1134                     (int) GNUNET_HELLO_URI_SEP);
1135   if (NULL == address)
1136   {
1137     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1138                 _("Failed to parse HELLO message: missing transport plugin\n"));
1139     ctx->ret = GNUNET_SYSERR;
1140     GNUNET_break (0);
1141     return GNUNET_SYSERR;
1142   }
1143   address++;
1144   end = strchr (address, (int) GNUNET_HELLO_URI_SEP);
1145   ctx->pos = end;
1146   ctx->counter_total ++;
1147   plugin_name = GNUNET_strndup (tname, address - (tname+1));
1148   papi = ctx->plugins_find (plugin_name);
1149   if (NULL == papi)
1150   {
1151     /* Not an error - we might just not have the right plugin.
1152      * Skip this part, advance to the next one and recurse.
1153      * But only if this is not the end of string.
1154      */
1155     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1156                 _("Plugin `%s' not found, skipping address\n"),
1157                 plugin_name);
1158     GNUNET_free (plugin_name);
1159     return 0;
1160   }
1161   if (NULL == papi->string_to_address)
1162   {
1163     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1164                 _("Plugin `%s' does not support URIs yet\n"),
1165                 plugin_name);
1166     GNUNET_free (plugin_name);
1167     GNUNET_break (0);
1168     return 0;
1169   }
1170   uri_address = GNUNET_strndup (address, end - address);
1171   if (GNUNET_OK !=
1172       papi->string_to_address (papi->cls,
1173                                uri_address,
1174                                strlen (uri_address) + 1,
1175                                &addr,
1176                                &addr_len))
1177   {
1178     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1179                 _("Failed to parse `%s' as an address for plugin `%s'\n"),
1180                 uri_address,
1181                 plugin_name);
1182     GNUNET_free (plugin_name);
1183     GNUNET_free (uri_address);
1184     return 0;
1185   }
1186   GNUNET_free (uri_address);
1187   /* address.peer is unset - not used by add_address() */
1188   haddr.address_length = addr_len;
1189   haddr.address = addr;
1190   haddr.transport_name = plugin_name;
1191   ret = GNUNET_HELLO_add_address (&haddr,
1192                                   expire,
1193                                   buffer,
1194                                   max);
1195   ctx->counter_added ++;
1196   GNUNET_free (addr);
1197   GNUNET_free (plugin_name);
1198   return ret;
1199 }
1200
1201
1202 /**
1203  * Parse a hello URI string to a hello message.
1204  *
1205  * @param uri URI string to parse
1206  * @param pubkey Pointer to struct where public key is parsed
1207  * @param hello Pointer to struct where hello message is parsed
1208  * @param plugins_find Function to find transport plugins by name
1209  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the URI was invalid, #GNUNET_NO on other errors
1210  */
1211 int
1212 GNUNET_HELLO_parse_uri (const char *uri,
1213                         struct GNUNET_CRYPTO_EddsaPublicKey *pubkey,
1214                         struct GNUNET_HELLO_Message **hello,
1215                         GNUNET_HELLO_TransportPluginsFind plugins_find)
1216 {
1217   const char *pks;
1218   const char *exc;
1219   int friend_only;
1220   struct GNUNET_HELLO_ParseUriContext ctx;
1221
1222   if (0 == strncmp (uri,
1223                     GNUNET_HELLO_URI_PREFIX,
1224                     strlen (GNUNET_HELLO_URI_PREFIX)))
1225   {
1226     pks = &uri[strlen (GNUNET_HELLO_URI_PREFIX)];
1227     friend_only = GNUNET_NO;
1228   }
1229   else if (0 == strncmp (uri,
1230             GNUNET_FRIEND_HELLO_URI_PREFIX,
1231             strlen (GNUNET_FRIEND_HELLO_URI_PREFIX)))
1232   {
1233     pks = &uri[strlen (GNUNET_FRIEND_HELLO_URI_PREFIX)];
1234     friend_only = GNUNET_YES;
1235   }
1236   else
1237     return GNUNET_SYSERR;
1238   exc = strchr (pks, GNUNET_HELLO_URI_SEP);
1239
1240   if (GNUNET_OK !=
1241       GNUNET_STRINGS_string_to_data (pks,
1242                                      (NULL == exc) ? strlen (pks) : (exc - pks),
1243                                      (unsigned char *) pubkey,
1244                                      sizeof (*pubkey)))
1245     return GNUNET_SYSERR;
1246
1247   ctx.pos = exc;
1248   ctx.ret = GNUNET_OK;
1249   ctx.counter_total = 0;
1250   ctx.counter_added = 0;
1251   ctx.plugins_find = plugins_find;
1252   *hello = GNUNET_HELLO_create (pubkey,
1253                                 &add_address_to_hello,
1254                                 &ctx,
1255                                 friend_only);
1256
1257   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1258               "HELLO URI contained %u addresses, added %u addresses\n",
1259               ctx.counter_total,
1260               ctx.counter_added);
1261
1262   return ctx.ret;
1263 }
1264
1265
1266 /* end of hello.c */