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