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