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