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