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