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