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