LRN: Fix deps in transport
[oweals/gnunet.git] / src / transport / gnunet-service-transport_validation.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010,2011 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 transport/gnunet-service-transport_validation.c
23  * @brief address validation subsystem
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet-service-transport_validation.h"
28 #include "gnunet-service-transport_plugins.h"
29 #include "gnunet-service-transport_hello.h"
30 #include "gnunet-service-transport.h"
31 #include "gnunet_hello_lib.h"
32 #include "gnunet_ats_service.h"
33 #include "gnunet_peerinfo_service.h"
34 #include "gnunet_signatures.h"
35
36 // TODO: observe latency between PING/PONG and give information to ATS!
37
38 /**
39  * How long is a PONG signature valid?  We'll recycle a signature until
40  * 1/4 of this time is remaining.  PONGs should expire so that if our
41  * external addresses change an adversary cannot replay them indefinitely.
42  * OTOH, we don't want to spend too much time generating PONG signatures,
43  * so they must have some lifetime to reduce our CPU usage.
44  */
45 #define PONG_SIGNATURE_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
46
47 /**
48  * After how long do we expire an address in a HELLO that we just
49  * validated?  This value is also used for our own addresses when we
50  * create a HELLO.
51  */
52 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
53
54 /**
55  * How long before an existing address expires should we again try to
56  * validate it?  Must be (significantly) smaller than
57  * HELLO_ADDRESS_EXPIRATION.
58  */
59 #define HELLO_REVALIDATION_START_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
60
61 /**
62  * Size of the validation map hashmap.
63  */
64 #define VALIDATION_MAP_SIZE 256
65
66 /**
67  * Priority to use for PINGs
68  */ 
69 #define PING_PRIORITY 2
70
71 /**
72  * Priority to use for PONGs
73  */ 
74 #define PONG_PRIORITY 4
75
76
77 /**
78  * Message used to ask a peer to validate receipt (to check an address
79  * from a HELLO).  Followed by the address we are trying to validate,
80  * or an empty address if we are just sending a PING to confirm that a
81  * connection which the receiver (of the PING) initiated is still valid.
82  */
83 struct TransportPingMessage
84 {
85
86   /**
87    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PING
88    */
89   struct GNUNET_MessageHeader header;
90
91   /**
92    * Challenge code (to ensure fresh reply).
93    */
94   uint32_t challenge GNUNET_PACKED;
95
96   /**
97    * Who is the intended recipient?
98    */
99   struct GNUNET_PeerIdentity target;
100
101 };
102
103
104 /**
105  * Message used to validate a HELLO.  The challenge is included in the
106  * confirmation to make matching of replies to requests possible.  The
107  * signature signs our public key, an expiration time and our address.<p>
108  *
109  * This message is followed by our transport address that the PING tried
110  * to confirm (if we liked it).  The address can be empty (zero bytes)
111  * if the PING had not address either (and we received the request via
112  * a connection that we initiated).
113  */
114 struct TransportPongMessage
115 {
116
117   /**
118    * Type will be GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
119    */
120   struct GNUNET_MessageHeader header;
121
122   /**
123    * Challenge code from PING (showing freshness).  Not part of what
124    * is signed so that we can re-use signatures.
125    */
126   uint32_t challenge GNUNET_PACKED;
127
128   /**
129    * Signature.
130    */
131   struct GNUNET_CRYPTO_RsaSignature signature;
132
133   /**
134    * What are we signing and why?  Two possible reason codes can be here:
135    * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN to confirm that this is a
136    * plausible address for this peer (pid is set to identity of signer); or
137    * GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_USING to confirm that this is
138    * an address we used to connect to the peer with the given pid.
139    */
140   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
141
142   /**
143    * When does this signature expire?
144    */
145   struct GNUNET_TIME_AbsoluteNBO expiration;
146
147   /**
148    * Either the identity of the peer Who signed this message, or the
149    * identity of the peer that we're connected to using the given
150    * address (depending on purpose.type).
151    */
152   struct GNUNET_PeerIdentity pid;
153
154   /**
155    * Size of address appended to this message (part of what is
156    * being signed, hence not redundant).
157    */
158   uint32_t addrlen GNUNET_PACKED;
159
160 };
161
162
163 /**
164  * Information about an address under validation
165  */
166 struct ValidationEntry 
167 {
168
169   /**
170    * Name of the transport.
171    */
172   char *transport_name;
173
174   /**
175    * The address, actually a pointer to the end
176    * of this struct.  Do not free!
177    */
178   const void *addr;
179
180   /**
181    * Handle to the blacklist check (if we're currently in it).
182    */
183   struct GST_BlacklistCheck *bc;
184
185   /**
186    * Public key of the peer.
187    */
188   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;                                                
189
190   /**
191    * The identity of the peer.
192    */
193   struct GNUNET_PeerIdentity pid;
194
195   /**
196    * ID of task that will clean up this entry if nothing happens.
197    */
198   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
199
200   /**
201    * At what time did we send the latest validation request?
202    */
203   struct GNUNET_TIME_Absolute send_time;
204
205   /**
206    * Until when is this address valid?
207    * ZERO if it is not currently considered valid.
208    */
209   struct GNUNET_TIME_Absolute valid_until;
210
211   /**
212    * How long until we can try to validate this address again?
213    * FOREVER if the address is for an unsupported plugin (from PEERINFO)
214    * ZERO if the address is considered valid (no validation needed)
215    * otherwise a time in the future if we're currently denying re-validation
216    */
217   struct GNUNET_TIME_Absolute validation_block;
218                                             
219   /**
220    * Challenge number we used.
221    */
222   uint32_t challenge;
223
224   /**
225    * Length of addr.
226    */
227   size_t addrlen;
228
229 };
230
231
232 /**
233  * Context of currently active requests to peerinfo
234  * for validation of HELLOs.
235  */
236 struct CheckHelloValidatedContext
237 {
238
239   /**
240    * This is a doubly-linked list.
241    */
242   struct CheckHelloValidatedContext *next;
243
244   /**
245    * This is a doubly-linked list.
246    */
247   struct CheckHelloValidatedContext *prev;
248
249   /**
250    * Hello that we are validating.
251    */
252   const struct GNUNET_HELLO_Message *hello;
253
254 };
255
256
257 /**
258  * Head of linked list of HELLOs awaiting validation.
259  */
260 static struct CheckHelloValidatedContext *chvc_head;
261
262 /**
263  * Tail of linked list of HELLOs awaiting validation
264  */
265 static struct CheckHelloValidatedContext *chvc_tail;
266
267 /**
268  * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
269  * of the given peer that we are currently validating, have validated
270  * or are blocked from re-validation for a while).
271  */
272 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
273
274 /**
275  * Context for peerinfo iteration.
276  */
277 static struct GNUNET_PEERINFO_NotifyContext *pnc;
278
279
280 /**
281  * Context for the validation entry match function.
282  */
283 struct ValidationEntryMatchContext
284 {
285   /**
286    * Where to store the result?
287    */
288   struct ValidationEntry *ve;
289   
290   /**
291    * Transport name we're looking for.
292    */
293   const char *transport_name;
294
295   /**
296    * Address we're interested in.
297    */
298   const char *addr;
299
300   /**
301    * Number of bytes in 'addr'.
302    */
303   size_t addrlen;
304 };
305
306
307 /**
308  * Iterate over validation entries until a matching one is found.
309  *
310  * @param cls the 'struct ValidationEntryMatchContext'
311  * @param key peer identity (unused)
312  * @param value a 'struct ValidationEntry' to match
313  * @return GNUNET_YES if the entry does not match,
314  *         GNUNET_NO if the entry does match
315  */
316 static int
317 validation_entry_match (void *cls,
318                         const GNUNET_HashCode *key,
319                         void *value)
320 {
321   struct ValidationEntryMatchContext *vemc = cls;
322   struct ValidationEntry *ve = value;
323
324   if ( (ve->addrlen == vemc->addrlen) &&
325        (0 == memcmp (ve->addr, vemc->addr, ve->addrlen)) &&
326        (0 == strcmp (ve->transport_name, vemc->transport_name)) )
327     {
328       vemc->ve = ve;
329       return GNUNET_NO;
330     }
331   return GNUNET_YES;
332 }
333
334
335 /**
336  * Find a ValidationEntry entry for the given neighbour that matches
337  * the given address and transport.  If none exists, create one (but
338  * without starting any validation).
339  *
340  * @param public_key public key of the peer, NULL for unknown
341  * @param neighbour which peer we care about
342  * @param tname name of the transport plugin
343  * @param session session to look for, NULL for 'any'; otherwise
344  *        can be used for the service to "learn" this session ID
345  *        if 'addr' matches
346  * @param addr binary address
347  * @param addrlen length of addr
348  * @return validation entry matching the given specifications, NULL
349  *         if we don't have an existing entry and no public key was given
350  */
351 static struct ValidationEntry *
352 find_validation_entry (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key,
353                        const struct GNUNET_PeerIdentity *neighbour,
354                        const char *tname,
355                        const char *addr,
356                        size_t addrlen)
357 {
358   struct ValidationEntryMatchContext vemc;
359   struct ValidationEntry *ve;
360
361   vemc.ve = NULL;
362   vemc.transport_name = tname;
363   vemc.addr = addr;
364   vemc.addrlen = addrlen;
365   GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
366                                               &neighbour->hashPubKey,
367                                               &validation_entry_match,
368                                               &vemc);
369   if (NULL != (ve = vemc.ve))
370     return ve;
371   if (public_key == NULL)
372     return NULL;
373   ve = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
374   ve->transport_name = GNUNET_strdup (tname);
375   ve->addr = (void*) &ve[1];
376   ve->public_key = *public_key;
377   ve->pid = *neighbour;
378   ve->challenge = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE,
379                                             UINT32_MAX);
380   memcpy (&ve[1], addr, addrlen);
381   ve->addrlen = addrlen;
382   GNUNET_CONTAINER_multihashmap_put (validation_map,
383                                      &neighbour->hashPubKey,
384                                      ve,
385                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
386   return ve;
387 }
388
389
390 /**
391  * Iterator which adds the given address to the set of validated
392  * addresses.
393  *
394  * @param cls original HELLO message
395  * @param tname name of the transport
396  * @param expiration expiration time
397  * @param addr the address
398  * @param addrlen length of the address
399  * @return GNUNET_OK (keep the address)
400  */
401 static int
402 add_valid_address (void *cls,
403                    const char *tname,
404                    struct GNUNET_TIME_Absolute expiration,
405                    const void *addr, 
406                    uint16_t addrlen)
407 {
408   const struct GNUNET_HELLO_Message *hello = cls;
409   struct ValidationEntry *ve;
410   struct GNUNET_PeerIdentity pid;
411   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
412
413   if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value == 0)
414     return GNUNET_OK; /* expired */
415   if ( (GNUNET_OK !=
416         GNUNET_HELLO_get_id (hello, &pid)) ||
417        (GNUNET_OK !=
418         GNUNET_HELLO_get_key (hello, &public_key)) )
419     {
420       GNUNET_break (0);
421       return GNUNET_OK; /* invalid HELLO !? */
422     }
423   ve = find_validation_entry (&public_key, &pid, tname, addr, addrlen);
424   ve->valid_until = GNUNET_TIME_absolute_max (ve->valid_until,
425                                               expiration);
426   GNUNET_ATS_address_update (GST_ats,
427                              &pid,
428                              ve->valid_until,
429                              tname,
430                              NULL,
431                              addr,
432                              addrlen,
433                              NULL, 0);
434   return GNUNET_OK;
435 }
436
437
438 /**
439  * Function called for any HELLO known to PEERINFO. 
440  *
441  * @param cls unused
442  * @param peer id of the peer, NULL for last call
443  * @param hello hello message for the peer (can be NULL)
444  * @param error message
445  */
446 static void
447 process_peerinfo_hello (void *cls,
448                         const struct GNUNET_PeerIdentity *peer,
449                         const struct GNUNET_HELLO_Message *hello,
450                         const char *err_msg)
451 {
452   GNUNET_assert (NULL != peer);
453   if (NULL == hello)
454     return;
455   GNUNET_assert (NULL ==
456                  GNUNET_HELLO_iterate_addresses (hello,
457                                                  GNUNET_NO,
458                                                  &add_valid_address,
459                                                  (void*) hello));  
460 }
461
462
463 /**
464  * Start the validation subsystem.
465  */
466 void 
467 GST_validation_start ()
468 {
469   validation_map = GNUNET_CONTAINER_multihashmap_create (VALIDATION_MAP_SIZE);
470   pnc = GNUNET_PEERINFO_notify (GST_cfg,
471                                 &process_peerinfo_hello,
472                                 NULL);
473 }
474
475
476 /**
477  * Iterate over validation entries and free them.
478  *
479  * @param cls (unused)
480  * @param key peer identity (unused)
481  * @param value a 'struct ValidationEntry' to clean up
482  * @return GNUNET_YES (continue to iterate)
483  */
484 static int
485 cleanup_validation_entry (void *cls,
486                           const GNUNET_HashCode *key,
487                           void *value)
488 {
489   struct ValidationEntry *ve = value;
490     
491   if (NULL != ve->bc)
492     {
493       GST_blacklist_test_cancel (ve->bc);
494       ve->bc = NULL;
495     }
496   GNUNET_break (GNUNET_OK ==
497                 GNUNET_CONTAINER_multihashmap_remove (validation_map,
498                                                       &va->pid.hashPubKey,
499                                                       va));
500   GNUNET_free (ve->transport_name);
501   if (GNUNET_SCHEDULER_NO_TASK != ve->timeout_task)
502     {
503       GNUNET_SCHEDULER_cancel (ve->timeout_task);
504       ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
505     }
506   GNUNET_free (ve);
507   return GNUNET_OK;
508 }
509
510
511 /**
512  * Stop the validation subsystem.
513  */
514 void
515 GST_validation_stop ()
516 {
517   struct CheckHelloValidatedContext *chvc;
518
519   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
520                                          &cleanup_validation_entry,
521                                          NULL);
522   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
523   validation_map = NULL;
524   while (NULL != (chvc = chvc_head))
525     {
526       GNUNET_CONTAINER_DLL_remove (chvc_head,
527                                    chvc_tail,
528                                    chvc);
529       GNUNET_free (chvc);
530     }
531   GNUNET_PEERINFO_notify_cancel (pnc);
532 }
533
534
535 /**
536  * Address validation cleanup task (record no longer needed).
537  *
538  * @param cls the 'struct ValidationEntry'
539  * @param tc scheduler context (unused)
540  */
541 static void
542 timeout_hello_validation (void *cls, 
543                           const struct GNUNET_SCHEDULER_TaskContext *tc)
544 {
545   struct ValidationEntry *ve = cls;
546
547   ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
548   GNUNET_STATISTICS_update (GST_stats,
549                             gettext_noop ("# address records discarded"),
550                             1,
551                             GNUNET_NO);
552   cleanup_validation_entry (NULL, &ve->pid.hashPubKey, ve);
553 }
554
555
556 /**
557  * Send the given PONG to the given address.
558  *
559  * @param cls the PONG message
560  * @param public_key public key for the peer, never NULL
561  * @param target peer this change is about, never NULL
562  * @param valid_until is ZERO if we never validated the address,
563  *                    otherwise a time up to when we consider it (or was) valid
564  * @param validation_block  is FOREVER if the address is for an unsupported plugin (from PEERINFO)
565  *                          is ZERO if the address is considered valid (no validation needed)
566  *                          otherwise a time in the future if we're currently denying re-validation
567  * @param plugin_name name of the plugin
568  * @param plugin_address binary address
569  * @param plugin_address_len length of address
570  */
571 static void
572 multicast_pong (void *cls,
573                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *public_key,
574                 const struct GNUNET_PeerIdentity *target,
575                 struct GNUNET_TIME_Absolute valid_until,
576                 struct GNUNET_TIME_Absolute validation_block,
577                 const char *plugin_name,
578                 const void *plugin_address,
579                 size_t plugin_address_len)
580 {
581   struct TransportPongMessage *pong = cls;
582   struct GNUNET_TRANSPORT_PluginFunctions *papi;
583
584   papi = GST_plugins_find (plugin_name);
585   if (papi == NULL)
586     return;
587   (void) papi->send (papi->cls,
588                      target,
589                      (const char*) pong,
590                      ntohs (pong->header.size),
591                      PONG_PRIORITY,
592                      HELLO_REVALIDATION_START_TIME,
593                      NULL,
594                      plugin_address,
595                      plugin_address_len,
596                      GNUNET_YES,
597                      NULL, NULL);
598 }
599
600
601 /**
602  * We've received a PING.  If appropriate, generate a PONG.
603  *
604  * @param sender peer sending the PING
605  * @param hdr the PING
606  * @param session session we got the PING from
607  * @param plugin_name name of plugin that received the PING
608  * @param sender_address address of the sender as known to the plugin, NULL
609  *                       if we did not initiate the connection
610  * @param sender_address_len number of bytes in sender_address
611  */
612 void
613 GST_validation_handle_ping (const struct GNUNET_PeerIdentity *sender,
614                             const struct GNUNET_MessageHeader *hdr,
615                             const char *plugin_name,
616                             struct Session *session,
617                             const void *sender_address,
618                             size_t sender_address_len)
619 {
620
621   const struct TransportPingMessage *ping;
622   struct TransportPongMessage *pong;
623   struct GNUNET_TRANSPORT_PluginFunctions *papi;
624   struct GNUNET_CRYPTO_RsaSignature *sig_cache;
625   struct GNUNET_TIME_Absolute *sig_cache_exp;
626   const char *addr;
627   const char *addrend;
628   size_t alen;
629   size_t slen;
630   ssize_t ret;
631
632   if (ntohs (hdr->size) < sizeof (struct TransportPingMessage))
633     {
634       GNUNET_break_op (0);
635       return;
636     }
637   ping = (const struct TransportPingMessage *) hdr;
638   if (0 != memcmp (&ping->target,
639                    &GST_my_identity,
640                    sizeof (struct GNUNET_PeerIdentity)))
641     {
642       GNUNET_break_op (0);
643       return;
644     }
645 #if DEBUG_TRANSPORT
646   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
647               "Processing `%s' from `%s'\n",
648               "PING",
649               (sender_address != NULL)
650               ? GST_plugin_a2s (plugin_name,
651                                 sender_address,
652                                 sender_address_len)
653               : "<inbound>");
654 #endif
655   GNUNET_STATISTICS_update (GST_stats,
656                             gettext_noop ("# PING messages received"),
657                             1,
658                             GNUNET_NO);
659   addr = (const char*) &ping[1];
660   alen = ntohs (hdr->size) - sizeof (struct TransportPingMessage);
661   /* peer wants to confirm that this is one of our addresses, this is what is
662      used for address validation */
663   
664   addrend = memchr (addr, '\0', alen);
665   if (NULL == addrend)
666     {
667       GNUNET_break_op (0);
668       return;
669     }
670   addrend++;
671   slen = strlen(addr);
672   alen -= slen;
673   
674   if (GNUNET_YES !=
675       GST_hello_test_address (addr,
676                               addrend,
677                               alen,
678                               &sig_cache,
679                               &sig_cache_exp))
680     {
681       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
682                   _("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
683                   GST_plugins_a2s (addr,
684                                    addrend,
685                                    alen));
686       return;
687     }
688   
689   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
690   pong->header.size = htons (sizeof (struct TransportPongMessage) + alen + slen);
691   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
692   pong->purpose.size =
693     htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
694            sizeof (uint32_t) +
695            sizeof (struct GNUNET_TIME_AbsoluteNBO) +
696            sizeof (struct GNUNET_PeerIdentity) + alen + slen);
697   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
698   pong->challenge = ping->challenge;
699   pong->addrlen = htonl(alen + slen);
700   pong->pid = GST_my_identity;
701   memcpy (&pong[1], addr, slen);
702   memcpy (&((char*)&pong[1])[slen], addrend, alen);
703   if (GNUNET_TIME_absolute_get_remaining (*sig_cache_exp).rel_value < PONG_SIGNATURE_LIFETIME.rel_value / 4)
704     {
705       /* create / update cached sig */
706 #if DEBUG_TRANSPORT
707       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
708                   "Creating PONG signature to indicate ownership.\n");
709 #endif
710       *sig_cache_exp = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
711       pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
712       GNUNET_assert (GNUNET_OK ==
713                      GNUNET_CRYPTO_rsa_sign (GST_my_private_key,
714                                              &pong->purpose,
715                                              sig_cache));
716     }
717   else
718     {
719       pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
720     }
721   pong->signature = *sig_cache;
722
723   /* first see if the session we got this PING from can be used to transmit
724      a response reliably */
725   papi = GST_plugins_find (plugin_name);
726   if (papi == NULL)
727     ret = -1;
728   else
729     ret = papi->send (papi->cls,
730                       sender,
731                       (const char*) pong,
732                       ntohs (pong->header.size),
733                       PONG_PRIORITY,
734                       HELLO_REVALIDATION_START_TIME,
735                       session,
736                       sender_address,
737                       sender_address_len,
738                       GNUNET_SYSERR,
739                       NULL, NULL);
740   if (ret != -1)
741     {
742       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
743                   "Transmitted PONG to `%s' via reliable mechanism\n",
744                   GNUNET_i2s (sender));
745       /* done! */
746       GNUNET_STATISTICS_update (GST_stats,
747                                 gettext_noop ("# PONGs unicast via reliable transport"),
748                                 1,
749                                 GNUNET_NO);
750       GNUNET_free (pong);
751       return;
752     }
753   
754   /* no reliable method found, try transmission via all known addresses */
755   GNUNET_STATISTICS_update (GST_stats,
756                             gettext_noop ("# PONGs multicast to all available addresses"),
757                             1,
758                             GNUNET_NO);
759   GST_validation_get_addresses (sender,
760                                 &multicast_pong,
761                                 pong);
762   GNUNET_free (pong);
763 }
764
765
766 /**
767  * Context for the 'validate_address' function
768  */
769 struct ValidateAddressContext
770 {
771   /**
772    * Hash of the public key of the peer whose address is being validated.
773    */ 
774   struct GNUNET_PeerIdentity pid;
775
776   /**
777    * Public key of the peer whose address is being validated.
778    */
779   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
780 };
781
782
783 /**
784  * Function called with the result from blacklisting.
785  * Send a PING to the other peer if a communication is allowed.
786  *
787  * @param cls ou r'struct ValidationEntry'
788  * @param pid identity of the other peer
789  * @param result GNUNET_OK if the connection is allowed, GNUNET_NO if not
790  */
791 static void
792 transmit_ping_if_allowed (void *cls,
793                           const struct GNUNET_PeerIdentity *pid,
794                           int result)
795 {
796   struct ValidationEntry *ve = cls;
797   struct TransportPingMessage ping;
798   struct GNUNET_TRANSPORT_PluginFunctions *papi;
799   const struct GNUNET_MessageHeader *hello;
800   ssize_t ret;
801   size_t tsize;
802   size_t slen;
803   uint16_t hsize;
804
805   ve->bc = NULL;
806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
807               "Transmitting plain PING to `%s'\n",
808               GNUNET_i2s (pid));  
809   ping.header.size = htons(sizeof(struct TransportPingMessage));
810   ping.header.type = htons(GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
811   ping.challenge = htonl(ve->challenge);
812   ping.target = *pid;
813   
814   slen = strlen(ve->transport_name) + 1;
815   hello = GST_hello_get ();
816   hsize = ntohs (hello->size);
817   tsize = sizeof(struct TransportPingMessage) + ve->addrlen + slen + hsize;
818   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
819     {
820       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
821                   _("Not transmitting `%s' with `%s', message too big (%u bytes!). This should not happen.\n"),
822                   "HELLO",
823                   "PING",
824                   (unsigned int) tsize);
825       /* message too big (!?), get rid of HELLO */
826       hsize = 0;
827       tsize = sizeof(struct TransportPingMessage) + ve->addrlen + slen + hsize;
828     }
829   {
830     char message_buf[tsize];
831
832     memcpy(message_buf, hello, hsize);
833     memcpy(&message_buf[hsize], &ping, sizeof (struct TransportPingMessage));
834     memcpy(&message_buf[sizeof (struct TransportPingMessage) + hsize],
835            ve->transport_name,
836            slen);
837     memcpy(&message_buf[sizeof (struct TransportPingMessage) + slen + hsize],
838            ve->addr,
839            ve->addrlen);
840     papi = GST_plugins_find (ve->transport_name);
841     if (papi == NULL)
842       ret = -1;
843     else
844       ret = papi->send (papi->cls,
845                         pid,
846                         message_buf,
847                         tsize,
848                         PING_PRIORITY,
849                         HELLO_REVALIDATION_START_TIME,
850                         NULL /* no session */,
851                         ve->addr,
852                         ve->addrlen,
853                         GNUNET_YES,
854                         NULL, NULL);
855   }
856   if (-1 != ret)
857     {
858       ve->send_time = GNUNET_TIME_absolute_get ();
859       GNUNET_STATISTICS_update (GST_stats,
860                                 gettext_noop ("# PING without HELLO messages sent"),
861                                 1,
862                                 GNUNET_NO);
863     }
864 }
865
866
867 /**
868  * Iterator callback to go over all addresses and try to validate them
869  * (unless blocked or already validated).
870  *
871  * @param cls pointer to a 'struct ValidateAddressContext'
872  * @param tname name of the transport
873  * @param expiration expiration time
874  * @param addr the address
875  * @param addrlen length of the address
876  * @return GNUNET_OK (keep the address)
877  */
878 static int
879 validate_address (void *cls,
880                   const char *tname,
881                   struct GNUNET_TIME_Absolute expiration,
882                   const void *addr, 
883                   uint16_t addrlen)
884 {
885   const struct ValidateAddressContext *vac = cls;
886   const struct GNUNET_PeerIdentity *pid = &vac->pid;
887   struct ValidationEntry *ve;
888
889   if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value == 0)
890     return GNUNET_OK; /* expired */
891   ve = find_validation_entry (&vac->public_key, pid, tname, addr, addrlen);
892   if (GNUNET_TIME_absolute_get_remaining (ve->validation_block).rel_value > 0)
893     return GNUNET_OK; /* blocked */
894   if ( (GNUNET_SCHEDULER_NO_TASK != ve->timeout_task) &&
895        (GNUNET_TIME_absolute_get_remaining (ve->valid_until).rel_value > 0) )
896     return GNUNET_OK; /* revalidation task already scheduled & still  valid */  
897   ve->validation_block = GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME);
898   if (GNUNET_SCHEDULER_NO_TASK != ve->timeout_task)
899     GNUNET_SCHEDULER_cancel (ve->timeout_task);
900   ve->timeout_task = GNUNET_SCHEDULER_add_delayed (HELLO_REVALIDATION_START_TIME,
901                                                    &timeout_hello_validation,
902                                                    ve);
903   ve->bc = GST_blacklist_test_allowed (pid,
904                                        tname,
905                                        &transmit_ping_if_allowed,
906                                        ve);
907   return GNUNET_OK;
908 }
909
910
911 /**
912  * Do address validation again to keep address valid.
913  *
914  * @param cls the 'struct ValidationEntry'
915  * @param tc scheduler context (unused)
916  */
917 static void
918 revalidate_address (void *cls, 
919                     const struct GNUNET_SCHEDULER_TaskContext *tc)
920 {
921   struct ValidationEntry *ve = cls;
922   struct GNUNET_TIME_Relative delay;
923   struct ValidateAddressContext vac;
924
925   ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
926   delay = GNUNET_TIME_absolute_get_remaining (ve->validation_block);
927   if (delay.rel_value > 0)
928     {
929       /* should wait a bit longer */
930       ve->timeout_task = GNUNET_SCHEDULER_add_delayed (delay,
931                                                        &revalidate_address,
932                                                        ve);
933       return;
934     }
935   GNUNET_STATISTICS_update (GST_stats,
936                             gettext_noop ("# address revalidations started"),
937                             1,
938                             GNUNET_NO);
939   vac.pid = ve->pid;
940   vac.public_key = ve->public_key;
941   validate_address (&vac,
942                     ve->transport_name,
943                     ve->valid_until,
944                     ve->addr,
945                     (uint16_t) ve->addrlen);
946 }
947
948
949 /**
950  * Add the validated peer address to the HELLO.
951  *
952  * @param cls the 'struct ValidationEntry' with the validated address
953  * @param max space in buf
954  * @param buf where to add the address
955  */
956 static size_t
957 add_valid_peer_address (void *cls,
958                         size_t max,
959                         void *buf)
960 {
961   struct ValidationEntry *ve = cls;
962
963   return GNUNET_HELLO_add_address (ve->transport_name,
964                                    ve->valid_until,
965                                    ve->addr,
966                                    ve->addrlen,
967                                    buf,
968                                    max);
969 }
970
971
972 /**
973  * We've received a PONG.  Check if it matches a pending PING and
974  * mark the respective address as confirmed.
975  *
976  * @param sender peer sending the PONG
977  * @param hdr the PONG
978  * @param plugin_name name of plugin that received the PONG
979  * @param sender_address address of the sender as known to the plugin, NULL
980  *                       if we did not initiate the connection
981  * @param sender_address_len number of bytes in sender_address
982  */
983 void
984 GST_validation_handle_pong (const struct GNUNET_PeerIdentity *sender,
985                             const struct GNUNET_MessageHeader *hdr,
986                             const char *plugin_name,
987                             const void *sender_address,
988                             size_t sender_address_len)
989 {
990   const struct TransportPongMessage *pong;
991   struct ValidationEntry *ve;
992   const char *addr;
993   const char *addrend;
994   size_t alen;
995   size_t slen;
996   uint32_t rdelay;
997   struct GNUNET_TIME_Relative delay;
998   struct GNUNET_HELLO_Message *hello;
999
1000   if (ntohs (hdr->size) < sizeof (struct TransportPongMessage))
1001     {
1002       GNUNET_break_op (0);
1003       return;
1004     }
1005   GNUNET_STATISTICS_update (GST_stats,
1006                             gettext_noop ("# PONG messages received"),
1007                             1,
1008                             GNUNET_NO);
1009   pong = (const struct TransportPongMessage *) hdr;
1010   if (0 != memcmp (&pong->pid,
1011                    sender,
1012                    sizeof (struct GNUNET_PeerIdentity)))
1013     {
1014       GNUNET_break_op (0);
1015       return;
1016     }
1017 #if DEBUG_TRANSPORT
1018   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
1019               "Processing `%s' from `%s'\n",
1020               "PONG",
1021               (sender_address != NULL)
1022               ? GST_plugin_a2s (plugin_name,
1023                                 sender_address,
1024                                 sender_address_len)
1025               : "<inbound>");
1026 #endif
1027   addr = (const char*) &pong[1];
1028   alen = ntohs (hdr->size) - sizeof (struct TransportPongMessage);
1029   addrend = memchr (addr, '\0', alen);
1030   if (NULL == addrend)
1031     {
1032       GNUNET_break_op (0);
1033       return;
1034     }
1035   addrend++;
1036   slen = strlen(addr);
1037   alen -= slen;
1038   ve = find_validation_entry (NULL,
1039                               sender,
1040                               addr,
1041                               addrend,
1042                               alen);
1043   if (NULL == ve)
1044     {
1045       GNUNET_STATISTICS_update (GST_stats,
1046                                 gettext_noop ("# PONGs dropped, no matching pending validation"),
1047                                 1,
1048                                 GNUNET_NO);
1049       return;
1050     }
1051   /* now check that PONG is well-formed */
1052   if (GNUNET_TIME_absolute_get_remaining (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
1053     {
1054       GNUNET_STATISTICS_update (GST_stats,
1055                                 gettext_noop ("# PONGs dropped, signature expired"),
1056                                 1,
1057                                 GNUNET_NO);
1058       return;
1059     }
1060   if (GNUNET_OK !=
1061       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
1062                                 &pong->purpose,
1063                                 &pong->signature,
1064                                 &ve->public_key))
1065     {
1066       GNUNET_break_op (0);
1067       return;
1068     }
1069   
1070   /* validity achieved, remember it! */
1071   ve->valid_until = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1072   GNUNET_ATS_address_update (GST_ats,
1073                              &ve->pid,
1074                              ve->valid_until,
1075                              ve->transport_name,
1076                              NULL,
1077                              ve->addr,
1078                              ve->addrlen,
1079                              NULL, 0); /* FIXME: compute and add latency here... */
1080
1081   /* build HELLO to store in PEERINFO */
1082   hello = GNUNET_HELLO_create (&ve->public_key,
1083                                &add_valid_peer_address,
1084                                ve);
1085   GNUNET_PEERINFO_add_peer (GST_peerinfo,
1086                             hello);
1087   GNUNET_free (hello);
1088
1089   if (GNUNET_SCHEDULER_NO_TASK != ve->timeout_task)
1090     GNUNET_SCHEDULER_cancel (ve->timeout_task);
1091
1092   /* randomly delay by up to 1h to avoid synchronous validations */
1093   rdelay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1094                                      60 * 60);
1095   delay = GNUNET_TIME_relative_add (HELLO_REVALIDATION_START_TIME,
1096                                     GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
1097                                                                    rdelay));
1098   ve->timeout_task = GNUNET_SCHEDULER_add_delayed (delay,
1099                                                    &revalidate_address,
1100                                                    ve);
1101 }
1102
1103
1104 /**
1105  * We've received a HELLO, check which addresses are new and trigger
1106  * validation.
1107  *
1108  * @param hello the HELLO we received
1109  */
1110 void
1111 GST_validation_handle_hello (const struct GNUNET_MessageHeader *hello)
1112 {
1113   const struct GNUNET_HELLO_Message* hm = (const struct GNUNET_HELLO_Message*) hello;
1114   struct ValidateAddressContext vac;
1115
1116   if ( (GNUNET_OK !=
1117         GNUNET_HELLO_get_id (hm, &vac.pid)) ||
1118        (GNUNET_OK !=
1119         GNUNET_HELLO_get_key (hm, &vac.public_key)) )
1120     {
1121       /* malformed HELLO */
1122       GNUNET_break (0);
1123       return; 
1124     }
1125   GNUNET_assert (NULL ==
1126                  GNUNET_HELLO_iterate_addresses (hm,
1127                                                  GNUNET_NO,
1128                                                  &validate_address,
1129                                                  &vac));
1130 }
1131
1132
1133 /**
1134  * Closure for 'iterate_addresses'
1135  */
1136 struct IteratorContext
1137 {
1138   /**
1139    * Function to call on each address.
1140    */
1141   GST_ValidationAddressCallback cb;
1142
1143   /**
1144    * Closure for 'cb'.
1145    */
1146   void *cb_cls;
1147
1148 };
1149
1150
1151 /**
1152  * Call the callback in the closure for each validation entry.
1153  *
1154  * @param cls the 'struct GST_ValidationIteratorContext'
1155  * @param key the peer's identity
1156  * @param value the 'struct ValidationEntry'
1157  * @return GNUNET_OK (continue to iterate)
1158  */
1159 static int
1160 iterate_addresses (void *cls,
1161                    const GNUNET_HashCode *key,
1162                    void *value)
1163 {
1164   struct IteratorContext *ic = cls;
1165   struct ValidationEntry *ve = value;
1166
1167   ic->cb (ic->cb_cls,
1168           &ve->public_key,
1169           &ve->pid,
1170           ve->valid_until,
1171           ve->validation_block,
1172           ve->transport_name,
1173           ve->addr,
1174           ve->addrlen);
1175   return GNUNET_OK;
1176 }
1177
1178
1179 /**
1180  * Call the given function for each address for the given target.
1181  * Can either give a snapshot (synchronous API) or be continuous.
1182  *
1183  * @param target peer information is requested for
1184  * @param snapshot_only GNUNET_YES to iterate over addresses once, GNUNET_NO to
1185  *                      continue to give information about addresses as it evolves
1186  * @param cb function to call; will not be called after this function returns
1187  *                             if snapshot_only is GNUNET_YES
1188  * @param cb_cls closure for 'cb'
1189  * @return context to cancel, NULL if 'snapshot_only' is GNUNET_YES
1190  */
1191 void
1192 GST_validation_get_addresses (const struct GNUNET_PeerIdentity *target,
1193                               GST_ValidationAddressCallback cb,
1194                               void *cb_cls)
1195 {
1196   struct IteratorContext  ic;
1197
1198   ic.cb = cb;
1199   ic.cb_cls = cb_cls;
1200   GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1201                                               &target->hashPubKey,
1202                                               &iterate_addresses,
1203                                               &ic);
1204 }
1205
1206
1207 /* end of file gnunet-service-transport_validation.c */