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