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