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