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