-fix URIs
[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, but with '(' and ')' instead of '[' and ']' (RFC2396 advises against using square brackets in URIs):
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/0430205UC7D56PTQK8NV05776671CNN44FK4TL6D0GQ35OMF8MEN4RNMKA5UF6AL3DQO8B1SC5AQF50SQ2MABIRU4HC8H2HAJKJ59JL1JVRJAK308F9GASRFLMGUBB5TQ5AKR94AS5T3MDG8B9O1EMPRKB0HVCG7T6QPP4CDJ913LAEHVJ2DI1TOBB15Q1JIT5ARBOD12U4SIGRFDV3Q7T66G4TBVSJJ90UQF1BG29TGJJKLGEIMSPHHKO544D6EALQ4F2K0416311JC22GVAD48R616I7VK03K7MP7N0RS2MBV1TE9JV8CK1LSQMR7KCDRTLDA6917UGA67DHTGHERIACCGQ54TGSR48RMSGS9BA5HLMOKASFC1I6V4TT09TUGCU8GNDHQF0JF3H7LPV59UL5I38QID040G000!20120302010059!TCP!192.168.0.1:2086!TCP!64.23.8.174:0
763  * gnunet://hello/0430205UC7D56PTQK8NV05776671CNN44FK4TL6D0GQ35OMF8MEN4RNMKA5UF6AL3DQO8B1SC5AQF50SQ2MABIRU4HC8H2HAJKJ59JL1JVRJAK308F9GASRFLMGUBB5TQ5AKR94AS5T3MDG8B9O1EMPRKB0HVCG7T6QPP4CDJ913LAEHVJ2DI1TOBB15Q1JIT5ARBOD12U4SIGRFDV3Q7T66G4TBVSJJ90UQF1BG29TGJJKLGEIMSPHHKO544D6EALQ4F2K0416311JC22GVAD48R616I7VK03K7MP7N0RS2MBV1TE9JV8CK1LSQMR7KCDRTLDA6917UGA67DHTGHERIACCGQ54TGSR48RMSGS9BA5HLMOKASFC1I6V4TT09TUGCU8GNDHQF0JF3H7LPV59UL5I38QID040G000!20120302010059!TCP!(2001:db8:85a3:8d3:1319:8a2e:370:7348):2086
764  *
765  * <p>
766  */
767
768
769 /* ************************* Compose HELLO URI ************************** */
770
771
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
805
806 /**
807  * Function that is called on each address of this peer.
808  * Expands the corresponding URI string.
809  *
810  * @param cls the 'GNUNET_HELLO_GetUriContext'
811  * @param address address to add
812  * @param expiration expiration time for the address
813  * @return GNUNET_OK (continue iteration).
814  */
815 static int
816 add_address_to_uri (void *cls, const struct GNUNET_HELLO_Address *address,
817                     struct GNUNET_TIME_Absolute expiration)
818 {
819   struct GNUNET_HELLO_ComposeUriContext *ctx = cls;
820   struct GNUNET_TRANSPORT_PluginFunctions *papi;
821   const char *addr;
822   char *uri_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    /* For URIs we use '(' and ')' instead of '[' and ']' as brackets are reserved
854       characters in URIs */
855   uri_addr = map_characters (addr_dup, "[]", "()");
856   GNUNET_free (addr_dup);
857   seconds = expiration.abs_value_us / 1000LL / 1000LL;
858   t = gmtime (&seconds);
859
860   GNUNET_asprintf (&ret,
861                    "%s!%s!%s!%s",
862                    ctx->uri,
863                    strftime (tbuf, sizeof (tbuf), "%Y%m%d%H%M%S", t) ? tbuf : "0",
864                    address->transport_name,
865                    uri_addr);
866   GNUNET_free (uri_addr);
867   GNUNET_free (ctx->uri);
868   ctx->uri = ret;
869   return GNUNET_OK;
870 }
871
872
873 /**
874  * Compose a hello URI string from a hello message.
875  *
876  * @param hello Hello message
877  * @param plugins_find Function to find transport plugins by name
878  * @return Hello URI string
879  */
880 char *
881 GNUNET_HELLO_compose_uri (const struct GNUNET_HELLO_Message *hello,
882                           GNUNET_HELLO_TransportPluginsFind plugins_find)
883 {
884   struct GNUNET_HELLO_ComposeUriContext ctx;
885   ctx.plugins_find = plugins_find;
886
887   char *pkey = GNUNET_CRYPTO_eddsa_public_key_to_string (&(hello->publicKey));
888
889   GNUNET_asprintf (&(ctx.uri),
890                    "%s%s",
891                    (GNUNET_YES == GNUNET_HELLO_is_friend_only (hello)) ? GNUNET_FRIEND_HELLO_URI_PREFIX : GNUNET_HELLO_URI_PREFIX,
892                    pkey);
893   GNUNET_free (pkey);
894
895   GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO, &add_address_to_uri, &ctx);
896   return ctx.uri;
897 }
898
899
900 /* ************************* Parse HELLO URI ********************* */
901
902
903 /**
904  * We're building a HELLO.  Parse the next address from the
905  * parsing context and append it.
906  *
907  * @param cls the 'struct GNUNET_HELLO_AddressParsingContext'
908  * @param max number of bytes available for HELLO construction
909  * @param buffer where to copy the next address (in binary format)
910  * @return number of bytes added to buffer, GNUNET_SYSERR on error
911  */
912 static ssize_t
913 add_address_to_hello (void *cls, size_t max, void *buffer)
914 {
915   struct GNUNET_HELLO_ParseUriContext *ctx = cls;
916   const char *tname;
917   const char *address;
918   char *uri_address;
919   char *plugin_address;
920   const char *end;
921   char *plugin_name;
922   struct tm expiration_time;
923   time_t expiration_seconds;
924   struct GNUNET_TIME_Absolute expire;
925   struct GNUNET_TRANSPORT_PluginFunctions *papi;
926   void *addr;
927   size_t addr_len;
928   struct GNUNET_HELLO_Address haddr;
929   ssize_t ret;
930
931
932   if (NULL == ctx->pos)
933     return GNUNET_SYSERR;
934   if ('!' != ctx->pos[0])
935   {
936     ctx->ret = GNUNET_SYSERR;
937     GNUNET_break (0);
938     return GNUNET_SYSERR;
939   }
940   ctx->pos++;
941
942   if ('0' == ctx->pos[0] && '!' == ctx->pos[1])
943   {
944     expire = GNUNET_TIME_UNIT_FOREVER_ABS;
945     tname = ctx->pos + 1;
946   }
947   else
948   {
949     memset (&expiration_time, 0, sizeof (expiration_time));
950     tname = strptime (ctx->pos,
951                       "%Y%m%d%H%M%S",
952                       &expiration_time);
953     if (NULL == tname)
954     {
955       ctx->ret = GNUNET_SYSERR;
956       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
957                   _("Failed to parse HELLO message: missing expiration time\n"));
958       GNUNET_break (0);
959       return GNUNET_SYSERR;
960     }
961
962     expiration_seconds = mktime (&expiration_time);
963     if (expiration_seconds == (time_t) -1)
964     {
965       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
966                   _("Failed to parse HELLO message: invalid expiration time\n"));
967       ctx->ret = GNUNET_SYSERR;
968       GNUNET_break (0);
969       return GNUNET_SYSERR;
970     }
971     expire.abs_value_us = expiration_seconds * 1000LL * 1000LL;
972   }
973   if ('!' != tname[0])
974   {
975     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
976                 _("Failed to parse HELLO message: malformed\n"));
977     ctx->ret = GNUNET_SYSERR;
978     GNUNET_break (0);
979     return GNUNET_SYSERR;
980   }
981   tname++;
982   address = strchr (tname, (int) '!');
983   if (NULL == address)
984   {
985     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
986                 _("Failed to parse HELLO message: missing transport plugin\n"));
987     ctx->ret = GNUNET_SYSERR;
988     GNUNET_break (0);
989     return GNUNET_SYSERR;
990   }
991   address++;
992   end = strchr (address, (int) '!');
993   ctx->pos = end;
994   ctx->counter_total ++;
995   plugin_name = GNUNET_strndup (tname, address - (tname+1));
996   papi = ctx->plugins_find (plugin_name);
997   if (NULL == papi)
998   {
999     /* Not an error - we might just not have the right plugin.
1000      * Skip this part, advance to the next one and recurse.
1001      * But only if this is not the end of string.
1002      */
1003     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1004                 _("Plugin `%s' not found, skipping address\n"),
1005                 plugin_name);
1006     GNUNET_free (plugin_name);
1007     return 0;
1008   }
1009   if (NULL == papi->string_to_address)
1010   {
1011     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1012                 _("Plugin `%s' does not support URIs yet\n"),
1013                 plugin_name);
1014     GNUNET_free (plugin_name);
1015     GNUNET_break (0);
1016     return 0;
1017   }
1018   uri_address = GNUNET_strndup (address, end - address);
1019   /* For URIs we use '(' and ')' instead of '[' and ']' as brackets are reserved
1020      characters in URIs; need to convert back to '[]' for the plugin */
1021    plugin_address = map_characters (uri_address, "()", "[]");
1022   GNUNET_free (uri_address);
1023   if (GNUNET_OK !=
1024       papi->string_to_address (papi->cls,
1025                                plugin_address,
1026                                strlen (plugin_address) + 1,
1027                                &addr,
1028                                &addr_len))
1029   {
1030     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1031                 _("Failed to parse `%s' as an address for plugin `%s'\n"),
1032                 plugin_address,
1033                 plugin_name);
1034     GNUNET_free (plugin_name);
1035     GNUNET_free (plugin_address);
1036     return 0;
1037   }
1038   GNUNET_free (plugin_address);
1039   /* address.peer is unset - not used by add_address() */
1040   haddr.address_length = addr_len;
1041   haddr.address = addr;
1042   haddr.transport_name = plugin_name;
1043   ret = GNUNET_HELLO_add_address (&haddr, expire, buffer, max);
1044   ctx->counter_added ++;
1045   GNUNET_free (addr);
1046   GNUNET_free (plugin_name);
1047   return ret;
1048 }
1049
1050
1051 /**
1052  * Parse a hello URI string to a hello message.
1053  *
1054  * @param uri URI string to parse
1055  * @param pubkey Pointer to struct where public key is parsed
1056  * @param hello Pointer to struct where hello message is parsed
1057  * @param plugins_find Function to find transport plugins by name
1058  * @return GNUNET_OK on success, GNUNET_SYSERR if the URI was invalid, GNUNET_NO on other errors
1059  */
1060 int
1061 GNUNET_HELLO_parse_uri (const char *uri,
1062                         struct GNUNET_CRYPTO_EddsaPublicKey *pubkey,
1063                         struct GNUNET_HELLO_Message **hello,
1064                         GNUNET_HELLO_TransportPluginsFind plugins_find)
1065 {
1066   const char *pks;
1067   const char *exc;
1068   int friend_only;
1069   struct GNUNET_HELLO_ParseUriContext ctx;
1070
1071   if (0 == strncmp (uri,
1072                     GNUNET_HELLO_URI_PREFIX,
1073                     strlen (GNUNET_HELLO_URI_PREFIX)))
1074   {
1075                 pks = &uri[strlen (GNUNET_HELLO_URI_PREFIX)];
1076                 friend_only = GNUNET_NO;
1077   }
1078   else if (0 == strncmp (uri,
1079             GNUNET_FRIEND_HELLO_URI_PREFIX,
1080             strlen (GNUNET_FRIEND_HELLO_URI_PREFIX)))
1081   {
1082         pks = &uri[strlen (GNUNET_FRIEND_HELLO_URI_PREFIX)];
1083         friend_only = GNUNET_YES;
1084   }
1085   else
1086         return GNUNET_SYSERR;
1087   exc = strstr (pks, "!");
1088
1089   if (GNUNET_OK !=
1090       GNUNET_STRINGS_string_to_data (pks,
1091                                      (NULL == exc) ? strlen (pks) : (exc - pks),
1092                                      (unsigned char *) pubkey,
1093                                      sizeof (*pubkey)))
1094     return GNUNET_SYSERR;
1095
1096   ctx.pos = exc;
1097   ctx.ret = GNUNET_OK;
1098   ctx.counter_total = 0;
1099   ctx.counter_added = 0;
1100   ctx.plugins_find = plugins_find;
1101   *hello = GNUNET_HELLO_create (pubkey, &add_address_to_hello, &ctx, friend_only);
1102
1103   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1104               _("HELLO URI contained %u addresses, added %u addresses\n"),
1105               ctx.counter_total, ctx.counter_added);
1106
1107   return ctx.ret;
1108 }
1109
1110
1111 /* end of hello.c */