d0a731789f070f4b1a9d8a7786c7e4032bf1a63a
[oweals/gnunet.git] / src / transport / gnunet-service-transport_validation.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010-2015 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_ats.h"
28 #include "gnunet-service-transport_blacklist.h"
29 #include "gnunet-service-transport_clients.h"
30 #include "gnunet-service-transport_hello.h"
31 #include "gnunet-service-transport_neighbours.h"
32 #include "gnunet-service-transport_plugins.h"
33 #include "gnunet-service-transport_validation.h"
34 #include "gnunet-service-transport.h"
35 #include "gnunet_hello_lib.h"
36 #include "gnunet_ats_service.h"
37 #include "gnunet_peerinfo_service.h"
38 #include "gnunet_signatures.h"
39
40
41 /**
42  * How long is a PONG signature valid?  We'll recycle a signature until
43  * 1/4 of this time is remaining.  PONGs should expire so that if our
44  * external addresses change an adversary cannot replay them indefinitely.
45  * OTOH, we don't want to spend too much time generating PONG signatures,
46  * so they must have some lifetime to reduce our CPU usage.
47  */
48 #define PONG_SIGNATURE_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
49
50 /**
51  * After how long do we expire an address in a HELLO that we just
52  * validated?  This value is also used for our own addresses when we
53  * create a HELLO.
54  */
55 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
56
57 /**
58  * How often do we allow PINGing an address that we have not yet
59  * validated?  This also determines how long we track an address that
60  * we cannot validate (because after this time we can destroy the
61  * validation record).
62  */
63 #define UNVALIDATED_PING_KEEPALIVE GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
64
65 /**
66  * How often do we PING an address that we have successfully validated
67  * in the past but are not actively using?  Should be (significantly)
68  * smaller than HELLO_ADDRESS_EXPIRATION.
69  */
70 #define VALIDATED_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
71
72 /**
73  * How often do we PING an address that we are currently using?
74  */
75 #define CONNECTED_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
76
77 /**
78  * How much delay is acceptable for sending the PING or PONG?
79  */
80 #define ACCEPTABLE_PING_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
81
82 /**
83  * Size of the validation map hashmap.
84  */
85 #define VALIDATION_MAP_SIZE 256
86
87 /**
88  * Priority to use for PINGs
89  */
90 #define PING_PRIORITY 2
91
92 /**
93  * Priority to use for PONGs
94  */
95 #define PONG_PRIORITY 4
96
97
98 GNUNET_NETWORK_STRUCT_BEGIN
99
100 /**
101  * Message used to ask a peer to validate receipt (to check an address
102  * from a HELLO).  Followed by the address we are trying to validate,
103  * or an empty address if we are just sending a PING to confirm that a
104  * connection which the receiver (of the PING) initiated is still valid.
105  */
106 struct TransportPingMessage
107 {
108
109   /**
110    * Type will be #GNUNET_MESSAGE_TYPE_TRANSPORT_PING
111    */
112   struct GNUNET_MessageHeader header;
113
114   /**
115    * Challenge code (to ensure fresh reply).
116    */
117   uint32_t challenge GNUNET_PACKED;
118
119   /**
120    * Who is the intended recipient?
121    */
122   struct GNUNET_PeerIdentity target;
123
124 };
125
126
127 /**
128  * Message used to validate a HELLO.  The challenge is included in the
129  * confirmation to make matching of replies to requests possible.  The
130  * signature signs our public key, an expiration time and our address.<p>
131  *
132  * This message is followed by our transport address that the PING tried
133  * to confirm (if we liked it).  The address can be empty (zero bytes)
134  * if the PING had not address either (and we received the request via
135  * a connection that we initiated).
136  */
137 struct TransportPongMessage
138 {
139
140   /**
141    * Type will be #GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
142    */
143   struct GNUNET_MessageHeader header;
144
145   /**
146    * Challenge code from PING (showing freshness).  Not part of what
147    * is signed so that we can re-use signatures.
148    */
149   uint32_t challenge GNUNET_PACKED;
150
151   /**
152    * Signature.
153    */
154   struct GNUNET_CRYPTO_EddsaSignature signature;
155
156   /**
157    * #GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN to confirm that this is a
158    * plausible address for the signing peer.
159    */
160   struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
161
162   /**
163    * When does this signature expire?
164    */
165   struct GNUNET_TIME_AbsoluteNBO expiration;
166
167   /**
168    * Size of address appended to this message (part of what is
169    * being signed, hence not redundant).
170    */
171   uint32_t addrlen GNUNET_PACKED;
172
173 };
174 GNUNET_NETWORK_STRUCT_END
175
176 /**
177  * Information about an address under validation
178  */
179 struct ValidationEntry
180 {
181
182   /**
183    * The address.
184    */
185   struct GNUNET_HELLO_Address *address;
186
187   /**
188    * Handle to the blacklist check (if we're currently in it).
189    */
190   struct GST_BlacklistCheck *bc;
191
192   /**
193    * Cached PONG signature
194    */
195   struct GNUNET_CRYPTO_EddsaSignature pong_sig_cache;
196
197   /**
198    * ID of task that will clean up this entry if nothing happens.
199    */
200   struct GNUNET_SCHEDULER_Task *timeout_task;
201
202   /**
203    * ID of task that will trigger address revalidation.
204    */
205   struct GNUNET_SCHEDULER_Task *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    * At what time do we send the next validation request (PING)?
214    */
215   struct GNUNET_TIME_Absolute next_validation;
216
217   /**
218    * Until when is this address valid?
219    * ZERO if it is not currently considered valid.
220    */
221   struct GNUNET_TIME_Absolute valid_until;
222
223   /**
224    * Until when is the cached PONG signature valid?
225    * ZERO if it is not currently considered valid.
226    */
227   struct GNUNET_TIME_Absolute pong_sig_valid_until;
228
229   /**
230    * How long until we can try to validate this address again?
231    * FOREVER if the address is for an unsupported plugin (from PEERINFO)
232    * ZERO if the address is considered valid (no validation needed)
233    * otherwise a time in the future if we're currently denying re-validation
234    */
235   struct GNUNET_TIME_Absolute revalidation_block;
236
237   /**
238    * Last observed latency for this address (round-trip), delay between
239    * last PING sent and PONG received; FOREVER if we never got a PONG.
240    */
241   struct GNUNET_TIME_Relative latency;
242
243   /**
244    * Current state of this validation entry
245    */
246   enum GNUNET_TRANSPORT_ValidationState state;
247
248   /**
249    * Challenge number we used.
250    */
251   uint32_t challenge;
252
253   /**
254    * When passing the address in 'add_valid_peer_address', did we
255    * copy the address to the HELLO yet?
256    */
257   int copied;
258
259   /**
260    * Are we currently using this address for a connection?
261    */
262   int in_use;
263
264   /**
265    * Are we expecting a PONG message for this validation entry?
266    */
267   int expecting_pong;
268
269   /**
270    * Is this address known to ATS as valid right now?
271    */
272   int known_to_ats;
273
274   /**
275    * Which network type does our address belong to?
276    */
277   enum GNUNET_ATS_Network_Type network;
278 };
279
280
281 /**
282  * Context of currently active requests to peerinfo
283  * for validation of HELLOs.
284  */
285 struct CheckHelloValidatedContext
286 {
287
288   /**
289    * This is a doubly-linked list.
290    */
291   struct CheckHelloValidatedContext *next;
292
293   /**
294    * This is a doubly-linked list.
295    */
296   struct CheckHelloValidatedContext *prev;
297
298   /**
299    * Hello that we are validating.
300    */
301   const struct GNUNET_HELLO_Message *hello;
302
303 };
304
305
306 /**
307  * Head of linked list of HELLOs awaiting validation.
308  */
309 static struct CheckHelloValidatedContext *chvc_head;
310
311 /**
312  * Tail of linked list of HELLOs awaiting validation
313  */
314 static struct CheckHelloValidatedContext *chvc_tail;
315
316 /**
317  * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
318  * of the given peer that we are currently validating, have validated
319  * or are blocked from re-validation for a while).
320  */
321 static struct GNUNET_CONTAINER_MultiPeerMap *validation_map;
322
323 /**
324  * Context for peerinfo iteration.
325  */
326 static struct GNUNET_PEERINFO_NotifyContext *pnc;
327
328 /**
329  * Minimum delay between to validations
330  */
331 static struct GNUNET_TIME_Relative validation_delay;
332
333 /**
334  * Number of validations running; any PING that was not yet
335  * matched by a PONG and for which we have not yet hit the
336  * timeout is considered a running 'validation'.
337  */
338 static unsigned int validations_running;
339
340 /**
341  * Validition fast start threshold
342  */
343 static unsigned int validations_fast_start_threshold;
344
345 /**
346  * When is next validation allowed
347  */
348 static struct GNUNET_TIME_Absolute validation_next;
349
350
351 /**
352  * Context for the validation entry match function.
353  */
354 struct ValidationEntryMatchContext
355 {
356   /**
357    * Where to store the result?
358    */
359   struct ValidationEntry *ve;
360
361   /**
362    * Address we're interested in.
363    */
364   const struct GNUNET_HELLO_Address *address;
365
366 };
367
368
369 /**
370  * Iterate over validation entries until a matching one is found.
371  *
372  * @param cls the `struct ValidationEntryMatchContext *`
373  * @param key peer identity (unused)
374  * @param value a `struct ValidationEntry *` to match
375  * @return #GNUNET_YES if the entry does not match,
376  *         #GNUNET_NO if the entry does match
377  */
378 static int
379 validation_entry_match (void *cls,
380                         const struct GNUNET_PeerIdentity *key,
381                         void *value)
382 {
383   struct ValidationEntryMatchContext *vemc = cls;
384   struct ValidationEntry *ve = value;
385
386   if (0 == GNUNET_HELLO_address_cmp (ve->address,
387                                      vemc->address))
388   {
389     vemc->ve = ve;
390     return GNUNET_NO;
391   }
392   return GNUNET_YES;
393 }
394
395
396 /**
397  * A validation entry changed.  Update the state and notify
398  * monitors.
399  *
400  * @param ve validation entry that changed
401  * @param state new state
402  */
403 static void
404 validation_entry_changed (struct ValidationEntry *ve,
405                           enum GNUNET_TRANSPORT_ValidationState state)
406 {
407   ve->state = state;
408   GST_clients_broadcast_validation_notification (&ve->address->peer,
409                                                  ve->address,
410                                                  ve->send_time,
411                                                  ve->valid_until,
412                                                  ve->next_validation,
413                                                  state);
414 }
415
416
417 /**
418  * Iterate over validation entries and free them.
419  *
420  * @param cls (unused)
421  * @param key peer identity (unused)
422  * @param value a `struct ValidationEntry *` to clean up
423  * @return #GNUNET_YES (continue to iterate)
424  */
425 static int
426 cleanup_validation_entry (void *cls,
427                           const struct GNUNET_PeerIdentity *key,
428                           void *value)
429 {
430   struct ValidationEntry *ve = value;
431
432   ve->next_validation = GNUNET_TIME_UNIT_ZERO_ABS;
433   ve->valid_until = GNUNET_TIME_UNIT_ZERO_ABS;
434
435   /* Notify about deleted entry */
436   validation_entry_changed (ve, GNUNET_TRANSPORT_VS_REMOVE);
437
438   if (NULL != ve->bc)
439   {
440     GST_blacklist_test_cancel (ve->bc);
441     ve->bc = NULL;
442   }
443   GNUNET_break (GNUNET_OK ==
444                 GNUNET_CONTAINER_multipeermap_remove (validation_map,
445                                                       &ve->address->peer,
446                                                       ve));
447   if (GNUNET_YES == ve->known_to_ats)
448   {
449     GST_ats_expire_address (ve->address);
450     ve->known_to_ats = GNUNET_NO;
451   }
452   GNUNET_HELLO_address_free (ve->address);
453   if (NULL != ve->timeout_task)
454   {
455     GNUNET_SCHEDULER_cancel (ve->timeout_task);
456     ve->timeout_task = NULL;
457   }
458   if (NULL != ve->revalidation_task)
459   {
460     GNUNET_SCHEDULER_cancel (ve->revalidation_task);
461     ve->revalidation_task = NULL;
462   }
463   if ( (GNUNET_YES == ve->expecting_pong) &&
464        (validations_running > 0) )
465   {
466     validations_running --;
467     GNUNET_STATISTICS_set (GST_stats,
468                            gettext_noop ("# validations running"),
469                            validations_running,
470                            GNUNET_NO);
471     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
472                 "Validation finished, %u validation processes running\n",
473                 validations_running);
474   }
475   GNUNET_free (ve);
476   return GNUNET_OK;
477 }
478
479
480 /**
481  * Address validation cleanup task.  Assesses if the record is no
482  * longer valid and then possibly triggers its removal.
483  *
484  * @param cls the `struct ValidationEntry`
485  * @param tc scheduler context (unused)
486  */
487 static void
488 timeout_hello_validation (void *cls,
489                           const struct GNUNET_SCHEDULER_TaskContext *tc)
490 {
491   struct ValidationEntry *ve = cls;
492   struct GNUNET_TIME_Absolute max;
493   struct GNUNET_TIME_Relative left;
494
495   ve->timeout_task = NULL;
496   max = GNUNET_TIME_absolute_max (ve->valid_until,
497                                   ve->revalidation_block);
498   left = GNUNET_TIME_absolute_get_remaining (max);
499   if (left.rel_value_us > 0)
500   {
501     /* should wait a bit longer */
502     ve->timeout_task =
503         GNUNET_SCHEDULER_add_delayed (left, &timeout_hello_validation, ve);
504     return;
505   }
506   GNUNET_STATISTICS_update (GST_stats,
507                             gettext_noop ("# address records discarded"), 1,
508                             GNUNET_NO);
509   cleanup_validation_entry (NULL, &ve->address->peer, ve);
510 }
511
512
513 /**
514  * Function called with the result from blacklisting.
515  * Send a PING to the other peer if a communication is allowed.
516  *
517  * @param cls our `struct ValidationEntry`
518  * @param pid identity of the other peer
519  * @param result #GNUNET_OK if the connection is allowed, #GNUNET_NO if not
520  */
521 static void
522 transmit_ping_if_allowed (void *cls,
523                           const struct GNUNET_PeerIdentity *pid,
524                           int result)
525 {
526   struct ValidationEntry *ve = cls;
527   struct TransportPingMessage ping;
528   struct GNUNET_TRANSPORT_PluginFunctions *papi;
529   struct GNUNET_TIME_Absolute next;
530   const struct GNUNET_MessageHeader *hello;
531   enum GNUNET_ATS_Network_Type network;
532   ssize_t ret;
533   size_t tsize;
534   size_t slen;
535   uint16_t hsize;
536
537   ve->bc = NULL;
538   if (GNUNET_NO == result)
539   {
540     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
541                 "Blacklist denies to send PING to `%s' `%s' `%s'\n",
542                 GNUNET_i2s (pid),
543                 GST_plugins_a2s (ve->address),
544                 ve->address->transport_name);
545     return;
546   }
547
548   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
549               "Transmitting plain PING to `%s' `%s' `%s'\n",
550               GNUNET_i2s (pid),
551               GST_plugins_a2s (ve->address),
552               ve->address->transport_name);
553
554   slen = strlen (ve->address->transport_name) + 1;
555   hello = GST_hello_get ();
556   hsize = ntohs (hello->size);
557   tsize =
558       sizeof (struct TransportPingMessage) + ve->address->address_length +
559       slen + hsize;
560
561   ping.header.size =
562       htons (sizeof (struct TransportPingMessage) +
563              ve->address->address_length + slen);
564   ping.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
565   ping.challenge = htonl (ve->challenge);
566   ping.target = *pid;
567
568   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
569   {
570     GNUNET_break (0);
571     hsize = 0;
572     tsize =
573         sizeof (struct TransportPingMessage) + ve->address->address_length +
574         slen + hsize;
575   }
576   {
577     char message_buf[tsize];
578
579     /* build message with structure:
580      *  [HELLO][TransportPingMessage][Transport name][Address] */
581     memcpy (message_buf, hello, hsize);
582     memcpy (&message_buf[hsize],
583             &ping,
584             sizeof (struct TransportPingMessage));
585     memcpy (&message_buf[sizeof (struct TransportPingMessage) + hsize],
586             ve->address->transport_name,
587             slen);
588     memcpy (&message_buf[sizeof (struct TransportPingMessage) + slen + hsize],
589             ve->address->address,
590             ve->address->address_length);
591     papi = GST_plugins_find (ve->address->transport_name);
592     if (NULL == papi)
593     {
594       ret = -1;
595       GNUNET_STATISTICS_update (GST_stats,
596                                 gettext_noop ("# validations not attempted (no plugin)"),
597                                 1,
598                                 GNUNET_NO);
599     }
600     else
601     {
602       GNUNET_assert (NULL != papi->send);
603       struct Session *session = papi->get_session (papi->cls,
604                                                    ve->address);
605
606       if (NULL != session)
607       {
608         ret = papi->send (papi->cls, session,
609                           message_buf, tsize,
610                           PING_PRIORITY,
611                           ACCEPTABLE_PING_DELAY,
612                           NULL, NULL);
613         network = papi->get_network (papi->cls, session);
614         if (GNUNET_ATS_NET_UNSPECIFIED == network)
615         {
616           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
617                       "Could not obtain a valid network for `%s' `%s'\n",
618                       GNUNET_i2s (pid),
619                       GST_plugins_a2s (ve->address));
620           GNUNET_break(0);
621         }
622         GST_neighbours_notify_data_sent (ve->address, session, tsize);
623       }
624       else
625       {
626         /* Could not get a valid session */
627         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
628                     "Could not get a valid session for `%s' `%s'\n",
629                     GNUNET_i2s (pid),
630                     GST_plugins_a2s (ve->address));
631         ret = -1;
632       }
633     }
634   }
635   if (-1 != ret)
636   {
637     next = GNUNET_TIME_relative_to_absolute (validation_delay);
638     validation_next = GNUNET_TIME_absolute_max (next,
639                                                 validation_next);
640     ve->send_time = GNUNET_TIME_absolute_get ();
641     GNUNET_STATISTICS_update (GST_stats,
642                               gettext_noop ("# PINGs for address validation sent"),
643                               1,
644                               GNUNET_NO);
645     ve->network = network;
646     ve->expecting_pong = GNUNET_YES;
647     validations_running++;
648     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
649                 "Validation started, %u validation processes running\n",
650                 validations_running);
651     GNUNET_STATISTICS_set (GST_stats,
652                            gettext_noop ("# validations running"),
653                            validations_running,
654                            GNUNET_NO);
655     /*  Notify about PING sent */
656     validation_entry_changed (ve, GNUNET_TRANSPORT_VS_UPDATE);
657   }
658 }
659
660
661 /**
662  * Do address validation again to keep address valid.
663  *
664  * @param cls the `struct ValidationEntry`
665  * @param tc scheduler context (unused)
666  */
667 static void
668 revalidate_address (void *cls,
669                     const struct GNUNET_SCHEDULER_TaskContext *tc)
670 {
671   struct ValidationEntry *ve = cls;
672   struct GNUNET_TIME_Relative canonical_delay;
673   struct GNUNET_TIME_Relative delay;
674   struct GNUNET_TIME_Relative blocked_for;
675   struct GST_BlacklistCheck *bc;
676   uint32_t rdelay;
677
678   ve->revalidation_task = NULL;
679   delay = GNUNET_TIME_absolute_get_remaining (ve->revalidation_block);
680   /* Considering current connectivity situation, what is the maximum
681      block period permitted? */
682   if (GNUNET_YES == ve->in_use)
683     canonical_delay = CONNECTED_PING_FREQUENCY;
684   else if (GNUNET_TIME_absolute_get_remaining (ve->valid_until).rel_value_us > 0)
685     canonical_delay = VALIDATED_PING_FREQUENCY;
686   else
687     canonical_delay = UNVALIDATED_PING_KEEPALIVE;
688   /* Use delay that is MIN of original delay and possibly adjusted
689      new maximum delay (which may be lower); the real delay
690      is originally randomized between "canonical_delay" and "2 * canonical_delay",
691      so continue to permit that window for the operation. */
692   delay = GNUNET_TIME_relative_min (delay,
693                                     GNUNET_TIME_relative_multiply (canonical_delay,
694                                                                    2));
695   ve->revalidation_block = GNUNET_TIME_relative_to_absolute (delay);
696   if (delay.rel_value_us > 0)
697   {
698     /* should wait a bit longer */
699     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
700                 "Waiting for %s longer before validating address `%s'\n",
701                 GNUNET_STRINGS_relative_time_to_string (delay,
702                                                         GNUNET_YES),
703                 GST_plugins_a2s (ve->address));
704     ve->revalidation_task =
705         GNUNET_SCHEDULER_add_delayed (delay,
706                                       &revalidate_address, ve);
707     ve->next_validation = GNUNET_TIME_relative_to_absolute (delay);
708     return;
709   }
710   /* check if globally we have too many active validations at a
711      too high rate, if so, delay ours */
712   blocked_for = GNUNET_TIME_absolute_get_remaining (validation_next);
713   if ( (validations_running > validations_fast_start_threshold) &&
714        (blocked_for.rel_value_us > 0) )
715   {
716     /* Validations are blocked, have to wait for blocked_for time */
717     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
718                 "Validations blocked for another %s, delaying validating address `%s'\n",
719                 GNUNET_STRINGS_relative_time_to_string (blocked_for,
720                                                         GNUNET_YES),
721                 GST_plugins_a2s (ve->address));
722     ve->revalidation_task =
723       GNUNET_SCHEDULER_add_delayed (blocked_for, &revalidate_address, ve);
724     ve->next_validation = GNUNET_TIME_relative_to_absolute (blocked_for);
725     return;
726   }
727
728   /* We are good to go; remember to not go again for `canonical_delay` time;
729      add up to `canonical_delay` to randomize start time */
730   ve->revalidation_block = GNUNET_TIME_relative_to_absolute (canonical_delay);
731   /* schedule next PINGing with some extra random delay to avoid synchronous re-validations */
732   rdelay =
733       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
734                                 canonical_delay.rel_value_us);
735
736   delay = GNUNET_TIME_relative_add (canonical_delay,
737                                     GNUNET_TIME_relative_multiply
738                                     (GNUNET_TIME_UNIT_MICROSECONDS, rdelay));
739
740   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
741               "Validating now, next scheduled for %s, now validating address `%s'\n",
742               GNUNET_STRINGS_relative_time_to_string (blocked_for,
743                                                       GNUNET_YES),
744               GST_plugins_a2s (ve->address));
745   ve->revalidation_task =
746       GNUNET_SCHEDULER_add_delayed (delay, &revalidate_address, ve);
747   ve->next_validation = GNUNET_TIME_relative_to_absolute (delay);
748
749   /* start PINGing by checking blacklist */
750   GNUNET_STATISTICS_update (GST_stats,
751                             gettext_noop ("# address revalidations started"), 1,
752                             GNUNET_NO);
753   bc = GST_blacklist_test_allowed (&ve->address->peer,
754                                    ve->address->transport_name,
755                                    &transmit_ping_if_allowed, ve);
756   if (NULL != bc)
757     ve->bc = bc;                /* only set 'bc' if 'transmit_ping_if_allowed' was not already
758                                  * called... */
759 }
760
761
762 /**
763  * Find a ValidationEntry entry for the given neighbour that matches
764  * the given address and transport.  If none exists, create one (but
765  * without starting any validation).
766  *
767  * @param address address to find
768  * @return validation entry matching the given specifications, NULL
769  *         if we don't have an existing entry and no public key was given
770  */
771 static struct ValidationEntry *
772 find_validation_entry (const struct GNUNET_HELLO_Address *address)
773 {
774   struct ValidationEntryMatchContext vemc;
775   struct ValidationEntry *ve;
776
777   vemc.ve = NULL;
778   vemc.address = address;
779   GNUNET_CONTAINER_multipeermap_get_multiple (validation_map,
780                                               &address->peer,
781                                               &validation_entry_match, &vemc);
782   if (NULL != (ve = vemc.ve))
783     return ve;
784   ve = GNUNET_new (struct ValidationEntry);
785   ve->in_use = GNUNET_SYSERR; /* not defined */
786   ve->address = GNUNET_HELLO_address_copy (address);
787   ve->pong_sig_valid_until = GNUNET_TIME_absolute_get_zero_();
788   memset (&ve->pong_sig_cache, '\0', sizeof (struct GNUNET_CRYPTO_EddsaSignature));
789   ve->latency = GNUNET_TIME_UNIT_FOREVER_REL;
790   ve->challenge =
791       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
792   ve->timeout_task =
793       GNUNET_SCHEDULER_add_delayed (UNVALIDATED_PING_KEEPALIVE,
794                                     &timeout_hello_validation, ve);
795   GNUNET_CONTAINER_multipeermap_put (validation_map, &address->peer,
796                                      ve,
797                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
798   validation_entry_changed (ve, GNUNET_TRANSPORT_VS_NEW);
799   return ve;
800 }
801
802
803 /**
804  * Iterator which adds the given address to the set of validated
805  * addresses.
806  *
807  * @param cls original HELLO message
808  * @param address the address
809  * @param expiration expiration time
810  * @return #GNUNET_OK (keep the address)
811  */
812 static int
813 add_valid_address (void *cls,
814                    const struct GNUNET_HELLO_Address *address,
815                    struct GNUNET_TIME_Absolute expiration)
816 {
817   const struct GNUNET_HELLO_Message *hello = cls;
818   struct ValidationEntry *ve;
819   struct GNUNET_PeerIdentity pid;
820   struct GNUNET_ATS_Information ats;
821
822   if (0 == GNUNET_TIME_absolute_get_remaining (expiration).rel_value_us)
823     return GNUNET_OK;           /* expired */
824   if (GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid))
825   {
826     GNUNET_break (0);
827     return GNUNET_OK;           /* invalid HELLO !? */
828   }
829   if (0 == memcmp (&GST_my_identity,
830                    &pid,
831                    sizeof (struct GNUNET_PeerIdentity)))
832   {
833     /* Peerinfo returned own identity, skip validation */
834     return GNUNET_OK;
835   }
836   if (NULL == GST_plugins_find (address->transport_name))
837   {
838     /* might have been valid in the past, but we don't have that
839        plugin loaded right now */
840     return GNUNET_OK;
841   }
842
843   ve = find_validation_entry (address);
844   ve->valid_until = GNUNET_TIME_absolute_max (ve->valid_until,
845                                               expiration);
846   if (NULL == ve->revalidation_task)
847   {
848     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
849                 "Starting revalidations for valid address `%s'\n",
850                 GST_plugins_a2s (ve->address));
851     ve->next_validation = GNUNET_TIME_absolute_get();
852     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
853   }
854   validation_entry_changed (ve, GNUNET_TRANSPORT_VS_UPDATE);
855
856   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
857   ats.value = htonl (ve->network);
858   if (GNUNET_YES != ve->known_to_ats)
859   {
860     ve->known_to_ats = GNUNET_YES;
861     GST_ats_add_address (address, NULL, &ats, 1);
862   }
863   return GNUNET_OK;
864 }
865
866
867 /**
868  * Function called for any HELLO known to PEERINFO.
869  *
870  * @param cls unused
871  * @param peer id of the peer, NULL for last call
872  * @param hello hello message for the peer (can be NULL)
873  * @param err_msg error message
874  */
875 static void
876 process_peerinfo_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
877                         const struct GNUNET_HELLO_Message *hello,
878                         const char *err_msg)
879 {
880   GNUNET_assert (NULL != peer);
881   if (NULL == hello)
882     return;
883   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
884               "Handling HELLO for peer `%s'\n",
885               GNUNET_i2s (peer));
886   GNUNET_assert (NULL ==
887                  GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO,
888                                                  &add_valid_address,
889                                                  (void *) hello));
890 }
891
892
893 /**
894  * Start the validation subsystem.
895  *
896  * @param max_fds maximum number of fds to use
897  */
898 void
899 GST_validation_start (unsigned int max_fds)
900 {
901   /**
902    * Initialization for validation throttling
903    *
904    * We have a maximum number max_fds of connections we can use for validation
905    * We monitor the number of validations in parallel and start to throttle it
906    * when doing to many validations in parallel:
907    * if (running validations < (max_fds / 2))
908    * - "fast start": run validation immediately
909    * - have delay of (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us) / (max_fds / 2)
910    *   (300 sec / ~150 == ~2 sec.) between two validations
911    */
912
913   validation_next = GNUNET_TIME_absolute_get();
914   validation_delay.rel_value_us = (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us) / (max_fds / 2);
915   validations_fast_start_threshold = (max_fds / 2);
916   validations_running = 0;
917   GNUNET_STATISTICS_set (GST_stats,
918                          gettext_noop ("# validations running"),
919                          validations_running,
920                          GNUNET_NO);
921   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
922               "Validation uses a fast start threshold of %u connections and a delay between of %s\n ",
923               validations_fast_start_threshold,
924               GNUNET_STRINGS_relative_time_to_string (validation_delay,
925                                                       GNUNET_YES));
926   validation_map = GNUNET_CONTAINER_multipeermap_create (VALIDATION_MAP_SIZE,
927                                                          GNUNET_NO);
928   pnc = GNUNET_PEERINFO_notify (GST_cfg, GNUNET_YES,
929                                 &process_peerinfo_hello, NULL);
930 }
931
932
933 /**
934  * Stop the validation subsystem.
935  */
936 void
937 GST_validation_stop ()
938 {
939   struct CheckHelloValidatedContext *chvc;
940
941   GNUNET_CONTAINER_multipeermap_iterate (validation_map,
942                                          &cleanup_validation_entry, NULL);
943   GNUNET_CONTAINER_multipeermap_destroy (validation_map);
944   validation_map = NULL;
945   while (NULL != (chvc = chvc_head))
946   {
947     GNUNET_CONTAINER_DLL_remove (chvc_head, chvc_tail, chvc);
948     GNUNET_free (chvc);
949   }
950   GNUNET_PEERINFO_notify_cancel (pnc);
951 }
952
953
954 /**
955  * Send the given PONG to the given address.
956  *
957  * @param cls the PONG message
958  * @param valid_until is ZERO if we never validated the address,
959  *                    otherwise a time up to when we consider it (or was) valid
960  * @param validation_block  is FOREVER if the address is for an unsupported plugin (from PEERINFO)
961  *                          is ZERO if the address is considered valid (no validation needed)
962  *                          otherwise a time in the future if we're currently denying re-validation
963  * @param address target address
964  */
965 static void
966 multicast_pong (void *cls,
967                 struct GNUNET_TIME_Absolute valid_until,
968                 struct GNUNET_TIME_Absolute validation_block,
969                 const struct GNUNET_HELLO_Address *address)
970 {
971   struct TransportPongMessage *pong = cls;
972   struct GNUNET_TRANSPORT_PluginFunctions *papi;
973   struct Session *session;
974
975   papi = GST_plugins_find (address->transport_name);
976   if (NULL == papi)
977     return;
978
979   GNUNET_assert (NULL != papi->send);
980   GNUNET_assert (NULL != papi->get_session);
981   session = papi->get_session(papi->cls, address);
982   if (NULL == session)
983   {
984      GNUNET_break (0);
985      return;
986   }
987   GST_ats_new_session (address, session);
988   papi->send (papi->cls, session,
989               (const char *) pong,
990               ntohs (pong->header.size),
991               PONG_PRIORITY,
992               ACCEPTABLE_PING_DELAY,
993               NULL, NULL);
994   GST_neighbours_notify_data_sent (address,
995                                    session,
996                                    pong->header.size);
997
998 }
999
1000
1001 /**
1002  * We've received a PING.  If appropriate, generate a PONG.
1003  *
1004  * @param sender peer sending the PING
1005  * @param hdr the PING
1006  * @param sender_address the sender address as we got it
1007  * @param session session we got the PING from
1008  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
1009  */
1010 int
1011 GST_validation_handle_ping (const struct GNUNET_PeerIdentity *sender,
1012                             const struct GNUNET_MessageHeader *hdr,
1013                             const struct GNUNET_HELLO_Address *sender_address,
1014                             struct Session *session)
1015 {
1016   const struct TransportPingMessage *ping;
1017   struct TransportPongMessage *pong;
1018   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1019   struct GNUNET_CRYPTO_EddsaSignature *sig_cache;
1020   struct GNUNET_TIME_Absolute *sig_cache_exp;
1021   const char *addr;
1022   const char *addrend;
1023   char *plugin_name;
1024   char *pos;
1025   size_t len_address;
1026   size_t len_plugin;
1027   ssize_t ret;
1028   int buggy = GNUNET_NO;
1029   struct GNUNET_HELLO_Address address;
1030
1031   if (ntohs (hdr->size) < sizeof (struct TransportPingMessage))
1032   {
1033     GNUNET_break_op (0);
1034     return GNUNET_SYSERR;
1035   }
1036   ping = (const struct TransportPingMessage *) hdr;
1037   if (0 !=
1038       memcmp (&ping->target, &GST_my_identity,
1039               sizeof (struct GNUNET_PeerIdentity)))
1040   {
1041     GNUNET_STATISTICS_update (GST_stats,
1042                               gettext_noop
1043                               ("# PING message for different peer received"), 1,
1044                               GNUNET_NO);
1045     return GNUNET_SYSERR;
1046   }
1047   GNUNET_STATISTICS_update (GST_stats,
1048                             gettext_noop ("# PING messages received"), 1,
1049                             GNUNET_NO);
1050   addr = (const char *) &ping[1];
1051   len_address = ntohs (hdr->size) - sizeof (struct TransportPingMessage);
1052   /* peer wants to confirm that this is one of our addresses, this is what is
1053    * used for address validation */
1054
1055   sig_cache = NULL;
1056   sig_cache_exp = NULL;
1057   papi = NULL;
1058   if (len_address > 0)
1059   {
1060     addrend = memchr (addr, '\0', len_address);
1061     if (NULL == addrend)
1062     {
1063       GNUNET_break_op (0);
1064       return GNUNET_SYSERR;
1065     }
1066     addrend++;
1067     len_plugin = strlen (addr) + 1;
1068     len_address -= len_plugin;
1069     address.local_info = GNUNET_HELLO_ADDRESS_INFO_NONE;
1070     address.address = addrend;
1071     address.address_length = len_address;
1072     address.transport_name = addr;
1073     address.peer = GST_my_identity;
1074
1075     if (NULL == address.transport_name)
1076     {
1077       GNUNET_break (0);
1078     }
1079
1080     if (0 != strstr (address.transport_name, "_client"))
1081     {
1082       plugin_name = GNUNET_strdup (address.transport_name);
1083       pos = strstr (plugin_name, "_client");
1084       GNUNET_assert (NULL != pos);
1085       GNUNET_snprintf (pos, strlen ("_server") + 1, "%s", "_server");
1086     }
1087     else
1088       plugin_name = GNUNET_strdup (address.transport_name);
1089
1090     if (NULL == (papi = GST_plugins_find (plugin_name)))
1091     {
1092       /* we don't have the plugin for this address */
1093       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1094                   _("Plugin `%s' not available, cannot confirm having this address\n"),
1095                   plugin_name);
1096       GNUNET_free (plugin_name);
1097       return GNUNET_SYSERR;
1098     }
1099     GNUNET_free (plugin_name);
1100     if (GNUNET_OK != papi->check_address (papi->cls, addrend, len_address))
1101     {
1102       GNUNET_STATISTICS_update (GST_stats,
1103                                 gettext_noop
1104                                 ("# failed address checks during validation"), 1,
1105                                 GNUNET_NO);
1106       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1107                   _("Address `%s' is not one of my addresses, not confirming PING\n"),
1108                   GST_plugins_a2s (&address));
1109       return GNUNET_SYSERR;
1110     }
1111     else
1112     {
1113       GNUNET_STATISTICS_update (GST_stats,
1114                                 gettext_noop
1115                                 ("# successful address checks during validation"), 1,
1116                                 GNUNET_NO);
1117       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1118                   "Address `%s' is one of my addresses, confirming PING\n",
1119                   GST_plugins_a2s (&address));
1120     }
1121
1122     if (GNUNET_YES != GST_hello_test_address (&address, &sig_cache, &sig_cache_exp))
1123     {
1124       if (GNUNET_NO == buggy)
1125       {
1126         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1127                     _("Not confirming PING from peer `%s' with address `%s' since I cannot confirm having this address.\n"),
1128                     GNUNET_i2s (sender),
1129                     GST_plugins_a2s (&address));
1130         return GNUNET_SYSERR;
1131       }
1132       else
1133       {
1134         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1135                     _("Received a PING message with validation bug from `%s'\n"),
1136                     GNUNET_i2s (sender));
1137       }
1138     }
1139   }
1140   else
1141   {
1142     addrend = NULL;             /* make gcc happy */
1143     len_plugin = 0;
1144     static struct GNUNET_CRYPTO_EddsaSignature no_address_signature;
1145     static struct GNUNET_TIME_Absolute no_address_signature_expiration;
1146
1147     sig_cache = &no_address_signature;
1148     sig_cache_exp = &no_address_signature_expiration;
1149   }
1150
1151   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1152               "I am `%s', sending PONG to peer `%s'\n",
1153               GNUNET_i2s_full (&GST_my_identity),
1154               GNUNET_i2s (sender));
1155
1156   /* message with structure:
1157    * [TransportPongMessage][Transport name][Address] */
1158
1159   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + len_address + len_plugin);
1160   pong->header.size =
1161       htons (sizeof (struct TransportPongMessage) + len_address + len_plugin);
1162   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
1163   pong->purpose.size =
1164       htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
1165              sizeof (uint32_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1166              len_address + len_plugin);
1167   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
1168   memcpy (&pong->challenge, &ping->challenge, sizeof (ping->challenge));
1169   pong->addrlen = htonl (len_address + len_plugin);
1170   memcpy (&pong[1], addr, len_plugin);   /* Copy transport plugin */
1171   if (len_address > 0)
1172   {
1173     GNUNET_assert (NULL != addrend);
1174     memcpy (&((char *) &pong[1])[len_plugin], addrend, len_address);
1175   }
1176   if (GNUNET_TIME_absolute_get_remaining (*sig_cache_exp).rel_value_us <
1177       PONG_SIGNATURE_LIFETIME.rel_value_us / 4)
1178   {
1179     /* create / update cached sig */
1180     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1181                 "Creating PONG signature to indicate ownership.\n");
1182     *sig_cache_exp = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
1183     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
1184     if (GNUNET_OK !=
1185                    GNUNET_CRYPTO_eddsa_sign (GST_my_private_key, &pong->purpose,
1186                                            sig_cache))
1187     {
1188         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1189                 _("Failed to create PONG signature for peer `%s'\n"), GNUNET_i2s (sender));
1190     }
1191   }
1192   else
1193   {
1194     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
1195   }
1196   pong->signature = *sig_cache;
1197
1198   GNUNET_assert (sender_address != NULL);
1199
1200   /* first see if the session we got this PING from can be used to transmit
1201    * a response reliably */
1202   if (NULL == papi)
1203   {
1204     ret = -1;
1205   }
1206   else
1207   {
1208     GNUNET_assert (NULL != papi->send);
1209     GNUNET_assert (NULL != papi->get_session);
1210     if (NULL == session)
1211     {
1212       session = papi->get_session (papi->cls, sender_address);
1213     }
1214     if (NULL == session)
1215     {
1216       GNUNET_break (0);
1217       ret = -1;
1218     }
1219     else
1220     {
1221       ret = papi->send (papi->cls, session,
1222                         (const char *) pong,
1223                         ntohs (pong->header.size),
1224                         PONG_PRIORITY, ACCEPTABLE_PING_DELAY,
1225                         NULL, NULL);
1226       if (-1 != ret)
1227         GST_neighbours_notify_data_sent (sender_address,
1228                                          session,
1229                                          pong->header.size);
1230     }
1231   }
1232   if (-1 != ret)
1233   {
1234     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1235                 "Transmitted PONG to `%s' via reliable mechanism\n",
1236                 GNUNET_i2s (sender));
1237     /* done! */
1238     GNUNET_STATISTICS_update (GST_stats,
1239                               gettext_noop
1240                               ("# PONGs unicast via reliable transport"), 1,
1241                               GNUNET_NO);
1242     GNUNET_free (pong);
1243     return GNUNET_OK;
1244   }
1245
1246   /* no reliable method found, try transmission via all known addresses */
1247   GNUNET_STATISTICS_update (GST_stats,
1248                             gettext_noop
1249                             ("# PONGs multicast to all available addresses"), 1,
1250                             GNUNET_NO);
1251   GST_validation_get_addresses (sender,
1252                                 &multicast_pong, pong);
1253   GNUNET_free (pong);
1254   return GNUNET_OK;
1255 }
1256
1257
1258 /**
1259  * Iterator callback to go over all addresses and try to validate them
1260  * (unless blocked or already validated).
1261  *
1262  * @param cls NULL
1263  * @param address the address
1264  * @param expiration expiration time
1265  * @return #GNUNET_OK (keep the address)
1266  */
1267 static int
1268 validate_address_iterator (void *cls,
1269                            const struct GNUNET_HELLO_Address *address,
1270                            struct GNUNET_TIME_Absolute expiration)
1271 {
1272   struct GNUNET_TRANSPORT_PluginFunctions * papi;
1273   struct ValidationEntry *ve;
1274
1275   if (0 == GNUNET_TIME_absolute_get_remaining (expiration).rel_value_us)
1276   {
1277     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1278                 "Skipping expired address from HELLO\n");
1279     return GNUNET_OK;           /* expired */
1280   }
1281   papi = GST_plugins_find (address->transport_name);
1282   if (NULL == papi)
1283   {
1284     /* This plugin is currently unvailable ... ignore */
1285     return GNUNET_OK;
1286   }
1287   ve = find_validation_entry (address);
1288   if (NULL == ve->revalidation_task)
1289   {
1290     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1291                 "Validation process started for fresh address `%s'\n",
1292                 GST_plugins_a2s (ve->address));
1293     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
1294   }
1295   return GNUNET_OK;
1296 }
1297
1298
1299 /**
1300  * Add the validated peer address to the HELLO.
1301  *
1302  * @param cls the `struct ValidationEntry *` with the validated address
1303  * @param max space in @a buf
1304  * @param buf where to add the address
1305  * @return number of bytes written, #GNUNET_SYSERR to signal the
1306  *         end of the iteration.
1307  */
1308 static ssize_t
1309 add_valid_peer_address (void *cls,
1310                         size_t max,
1311                         void *buf)
1312 {
1313   struct ValidationEntry *ve = cls;
1314
1315   if (GNUNET_YES == ve->copied)
1316     return GNUNET_SYSERR; /* Done */
1317   ve->copied = GNUNET_YES;
1318   return GNUNET_HELLO_add_address (ve->address, ve->valid_until, buf, max);
1319 }
1320
1321
1322 /**
1323  * We've received a PONG.  Check if it matches a pending PING and
1324  * mark the respective address as confirmed.
1325  *
1326  * @param sender peer sending the PONG
1327  * @param hdr the PONG
1328  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
1329  */
1330 int
1331 GST_validation_handle_pong (const struct GNUNET_PeerIdentity *sender,
1332                             const struct GNUNET_MessageHeader *hdr)
1333 {
1334   const struct TransportPongMessage *pong;
1335   struct ValidationEntry *ve;
1336   const char *tname;
1337   const char *addr;
1338   size_t addrlen;
1339   size_t slen;
1340   size_t size;
1341   struct GNUNET_HELLO_Message *hello;
1342   struct GNUNET_HELLO_Address address;
1343   int sig_res;
1344   int do_verify;
1345
1346   if (ntohs (hdr->size) < sizeof (struct TransportPongMessage))
1347   {
1348     GNUNET_break_op (0);
1349     return GNUNET_SYSERR;
1350   }
1351   GNUNET_STATISTICS_update (GST_stats,
1352                             gettext_noop ("# PONG messages received"), 1,
1353                             GNUNET_NO);
1354
1355   /* message with structure:
1356    * [TransportPongMessage][Transport name][Address] */
1357
1358   pong = (const struct TransportPongMessage *) hdr;
1359   tname = (const char *) &pong[1];
1360   size = ntohs (hdr->size) - sizeof (struct TransportPongMessage);
1361   addr = memchr (tname, '\0', size);
1362   if (NULL == addr)
1363   {
1364     GNUNET_break_op (0);
1365     return GNUNET_SYSERR;
1366   }
1367   addr++;
1368   slen = strlen (tname) + 1;
1369   addrlen = size - slen;
1370   address.peer = *sender;
1371   address.address = addr;
1372   address.address_length = addrlen;
1373   address.transport_name = tname;
1374   address.local_info = GNUNET_HELLO_ADDRESS_INFO_NONE;
1375   ve = find_validation_entry (&address);
1376   if ((NULL == ve) || (GNUNET_NO == ve->expecting_pong))
1377   {
1378     GNUNET_STATISTICS_update (GST_stats,
1379                               gettext_noop
1380                               ("# PONGs dropped, no matching pending validation"),
1381                               1, GNUNET_NO);
1382     return GNUNET_OK;
1383   }
1384   /* now check that PONG is well-formed */
1385   if (0 != memcmp (&ve->address->peer,
1386                    sender,
1387                    sizeof (struct GNUNET_PeerIdentity)))
1388   {
1389     GNUNET_break_op (0);
1390     return GNUNET_SYSERR;
1391   }
1392   if (0 ==
1393       GNUNET_TIME_absolute_get_remaining
1394       (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value_us)
1395   {
1396     GNUNET_STATISTICS_update (GST_stats,
1397                               gettext_noop
1398                               ("# PONGs dropped, signature expired"), 1,
1399                               GNUNET_NO);
1400     return GNUNET_SYSERR;
1401   }
1402
1403   sig_res = GNUNET_SYSERR;
1404   do_verify = GNUNET_YES;
1405   if (0 != GNUNET_TIME_absolute_get_remaining (ve->pong_sig_valid_until).rel_value_us)
1406   {
1407     /* We have a cached and valid signature for this peer,
1408      * try to compare instead of verify */
1409     if (0 == memcmp (&ve->pong_sig_cache, &pong->signature, sizeof (struct GNUNET_CRYPTO_EddsaSignature)))
1410     {
1411       /* signatures are identical, we can skip verification */
1412       sig_res = GNUNET_OK;
1413       do_verify = GNUNET_NO;
1414     }
1415     else
1416     {
1417       sig_res = GNUNET_SYSERR;
1418       /* signatures do not match, we have to verify */
1419     }
1420   }
1421
1422   if (GNUNET_YES == do_verify)
1423   {
1424     /* Do expensive verification */
1425     sig_res = GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
1426                                           &pong->purpose, &pong->signature,
1427                                           &ve->address->peer.public_key);
1428     if (sig_res == GNUNET_SYSERR)
1429     {
1430       GNUNET_break_op (0);
1431       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1432                   "Failed to verify: invalid signature on address `%s':%s from peer `%s'\n",
1433                   tname,
1434                   GST_plugins_a2s (ve->address),
1435                   GNUNET_i2s (sender));
1436     }
1437   }
1438   if (sig_res == GNUNET_SYSERR)
1439   {
1440     GNUNET_break_op (0);
1441     return GNUNET_SYSERR;
1442   }
1443
1444   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1445               "Validation process successful for peer `%s' with plugin `%s' address `%s'\n",
1446               GNUNET_i2s (sender),
1447               tname,
1448               GST_plugins_a2s (ve->address));
1449   GNUNET_STATISTICS_update (GST_stats,
1450                             gettext_noop ("# validations succeeded"),
1451                             1,
1452                             GNUNET_NO);
1453   /* validity achieved, remember it! */
1454   ve->expecting_pong = GNUNET_NO;
1455   ve->valid_until = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1456   ve->pong_sig_cache = pong->signature;
1457         ve->pong_sig_valid_until = GNUNET_TIME_absolute_ntoh (pong->expiration);
1458   ve->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1459   {
1460     struct GNUNET_ATS_Information ats[2];
1461
1462     ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1463     ats[0].value = htonl ((uint32_t) ve->latency.rel_value_us);
1464     ats[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1465     ats[1].value = htonl ((uint32_t) ve->network);
1466     if (GNUNET_YES == ve->known_to_ats)
1467     {
1468       GST_ats_update_metrics (ve->address, NULL, ats, 2);
1469     }
1470     else
1471     {
1472       ve->known_to_ats = GNUNET_YES;
1473       GST_ats_add_address (ve->address, NULL, ats, 2);
1474     }
1475   }
1476   if (validations_running > 0)
1477   {
1478     validations_running --;
1479     GNUNET_STATISTICS_set (GST_stats,
1480                            gettext_noop ("# validations running"),
1481                            validations_running,
1482                            GNUNET_NO);
1483     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1484                 "Validation finished, %u validation processes running\n",
1485                 validations_running);
1486   }
1487   else
1488   {
1489     GNUNET_break (0);
1490   }
1491
1492   /* Notify about new validity */
1493   validation_entry_changed (ve, GNUNET_TRANSPORT_VS_UPDATE);
1494
1495   /* build HELLO to store in PEERINFO */
1496   ve->copied = GNUNET_NO;
1497   hello = GNUNET_HELLO_create (&ve->address->peer.public_key,
1498                                &add_valid_peer_address, ve,
1499                                GNUNET_NO);
1500   GNUNET_PEERINFO_add_peer (GST_peerinfo, hello, NULL, NULL);
1501   GNUNET_free (hello);
1502   return GNUNET_OK;
1503 }
1504
1505
1506 /**
1507  * We've received a HELLO, check which addresses are new and trigger
1508  * validation.
1509  *
1510  * @param hello the HELLO we received
1511  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
1512  */
1513 int
1514 GST_validation_handle_hello (const struct GNUNET_MessageHeader *hello)
1515 {
1516   const struct GNUNET_HELLO_Message *hm =
1517       (const struct GNUNET_HELLO_Message *) hello;
1518   struct GNUNET_PeerIdentity pid;
1519   struct GNUNET_HELLO_Message *h;
1520   int friend;
1521
1522   friend = GNUNET_HELLO_is_friend_only (hm);
1523   if ( ( (GNUNET_YES != friend) &&
1524          (GNUNET_NO != friend) ) ||
1525        (GNUNET_OK != GNUNET_HELLO_get_id (hm, &pid)) )
1526   {
1527     /* malformed HELLO */
1528     GNUNET_break_op (0);
1529     return GNUNET_SYSERR;
1530   }
1531   if (0 ==
1532       memcmp (&GST_my_identity,
1533               &pid,
1534               sizeof (struct GNUNET_PeerIdentity)))
1535     return GNUNET_OK;
1536   /* Add peer identity without addresses to peerinfo service */
1537   h = GNUNET_HELLO_create (&pid.public_key, NULL, NULL, friend);
1538   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1539               _("Validation received new %s message for peer `%s' with size %u\n"),
1540               "HELLO",
1541               GNUNET_i2s (&pid),
1542               ntohs (hello->size));
1543   GNUNET_PEERINFO_add_peer (GST_peerinfo, h, NULL, NULL);
1544
1545   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1546               _("Adding `%s' without addresses for peer `%s'\n"), "HELLO",
1547               GNUNET_i2s (&pid));
1548
1549   GNUNET_free (h);
1550   GNUNET_assert (NULL ==
1551                  GNUNET_HELLO_iterate_addresses (hm,
1552                                                  GNUNET_NO,
1553                                                  &validate_address_iterator,
1554                                                  NULL));
1555   return GNUNET_OK;
1556 }
1557
1558
1559 /**
1560  * Closure for #iterate_addresses().
1561  */
1562 struct IteratorContext
1563 {
1564   /**
1565    * Function to call on each address.
1566    */
1567   GST_ValidationAddressCallback cb;
1568
1569   /**
1570    * Closure for @e cb.
1571    */
1572   void *cb_cls;
1573
1574 };
1575
1576
1577 /**
1578  * Call the callback in the closure for each validation entry.
1579  *
1580  * @param cls the `struct IteratorContext`
1581  * @param key the peer's identity
1582  * @param value the `struct ValidationEntry`
1583  * @return #GNUNET_OK (continue to iterate)
1584  */
1585 static int
1586 iterate_addresses (void *cls,
1587                    const struct GNUNET_PeerIdentity *key,
1588                    void *value)
1589 {
1590   struct IteratorContext *ic = cls;
1591   struct ValidationEntry *ve = value;
1592
1593   ic->cb (ic->cb_cls,
1594           ve->valid_until,
1595           ve->revalidation_block,
1596           ve->address);
1597   return GNUNET_OK;
1598 }
1599
1600
1601 /**
1602  * Call the given function for each address for the given target.
1603  * Can either give a snapshot (synchronous API) or be continuous.
1604  *
1605  * @param target peer information is requested for
1606  * @param cb function to call; will not be called after this function returns
1607  * @param cb_cls closure for @a cb
1608  */
1609 void
1610 GST_validation_get_addresses (const struct GNUNET_PeerIdentity *target,
1611                               GST_ValidationAddressCallback cb,
1612                               void *cb_cls)
1613 {
1614   struct IteratorContext ic;
1615
1616   ic.cb = cb;
1617   ic.cb_cls = cb_cls;
1618   GNUNET_CONTAINER_multipeermap_get_multiple (validation_map,
1619                                               target,
1620                                               &iterate_addresses, &ic);
1621 }
1622
1623
1624 /**
1625  * Update if we are using an address for a connection actively right now.
1626  * Based on this, the validation module will measure latency for the
1627  * address more or less often.
1628  *
1629  * @param address the address
1630  * @param session the session
1631  * @param in_use #GNUNET_YES if we are now using the address for a connection,
1632  *               #GNUNET_NO if we are no longer using the address for a connection
1633  */
1634 void
1635 GST_validation_set_address_use (const struct GNUNET_HELLO_Address *address,
1636                                 struct Session *session,
1637                                 int in_use)
1638 {
1639   struct ValidationEntry *ve;
1640
1641   if (GNUNET_HELLO_address_check_option (address,
1642                                          GNUNET_HELLO_ADDRESS_INFO_INBOUND))
1643     return; /* ignore inbound for validation */
1644   if (NULL != address)
1645     ve = find_validation_entry (address);
1646   else
1647     ve = NULL;                  /* FIXME: lookup based on session... */
1648   if (NULL == ve)
1649   {
1650     /* this can happen for inbound connections (sender_address_len == 0); */
1651     return;
1652   }
1653   if (ve->in_use == in_use)
1654   {
1655     if (GNUNET_YES == in_use)
1656     {
1657       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1658                   "Error setting address in use for peer `%s' `%s' to USED\n",
1659                   GNUNET_i2s (&address->peer), GST_plugins_a2s (address));
1660     }
1661     if (GNUNET_NO == in_use)
1662     {
1663       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1664                   "Error setting address in use for peer `%s' `%s' to NOT_USED\n",
1665                   GNUNET_i2s (&address->peer), GST_plugins_a2s (address));
1666     }
1667   }
1668
1669   GNUNET_break (ve->in_use != in_use);  /* should be different... */
1670   ve->in_use = in_use;
1671   if (in_use == GNUNET_YES)
1672   {
1673     /* from now on, higher frequeny, so reschedule now */
1674     if (NULL != ve->revalidation_task)
1675       GNUNET_SCHEDULER_cancel (ve->revalidation_task);
1676     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
1677   }
1678 }
1679
1680
1681 /**
1682  * Query validation about the latest observed latency on a given
1683  * address.
1684  *
1685  * @param address the address
1686  * @param session session
1687  * @return observed latency of the address, FOREVER if the address was
1688  *         never successfully validated
1689  */
1690 struct GNUNET_TIME_Relative
1691 GST_validation_get_address_latency (const struct GNUNET_HELLO_Address *address,
1692                                     struct Session *session)
1693 {
1694   struct ValidationEntry *ve;
1695
1696   if (NULL == address)
1697   {
1698     GNUNET_break (0);           // FIXME: support having latency only with session...
1699     return GNUNET_TIME_UNIT_FOREVER_REL;
1700   }
1701   ve = find_validation_entry (address);
1702   if (NULL == ve)
1703     return GNUNET_TIME_UNIT_FOREVER_REL;
1704   return ve->latency;
1705 }
1706
1707 /**
1708  * Closure for the validation_entries_iterate function.
1709  */
1710 struct ValidationIteratorContext
1711 {
1712   /**
1713    * Function to call on each validation entry
1714    */
1715   GST_ValidationChangedCallback cb;
1716
1717   /**
1718    * Closure for @e cb.
1719    */
1720   void *cb_cls;
1721 };
1722
1723
1724 /**
1725  * Function called on each entry in the validation map.
1726  * Passes the information from the validation entry to
1727  * the callback given in the closure.
1728  *
1729  * @param cls the `struct ValidationIteratorContext`
1730  * @param key peer this is about
1731  * @param value the `struct ValidationEntry`
1732  * @return #GNUNET_OK (continue to iterate)
1733  */
1734 static int
1735 validation_entries_iterate (void *cls,
1736                             const struct GNUNET_PeerIdentity *key,
1737                             void *value)
1738 {
1739   struct ValidationIteratorContext *ic = cls;
1740   struct ValidationEntry *ve = value;
1741
1742   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1743               "Notifying about validation entry for peer `%s' address `%s' \n",
1744               GNUNET_i2s (&ve->address->peer),
1745               GST_plugins_a2s (ve->address));
1746   ic->cb (ic->cb_cls,
1747           ve->address,
1748           ve->send_time,
1749           ve->valid_until,
1750           ve->next_validation,
1751           ve->state);
1752   return GNUNET_OK;
1753 }
1754
1755
1756 /**
1757  * Iterate over all iteration entries
1758  *
1759  * @param cb function to call
1760  * @param cb_cls closure for cb
1761  */
1762 void
1763 GST_validation_iterate (GST_ValidationChangedCallback cb,
1764                         void *cb_cls)
1765 {
1766   struct ValidationIteratorContext ic;
1767
1768   if (NULL == validation_map)
1769     return; /* can happen during shutdown */
1770   ic.cb = cb;
1771   ic.cb_cls = cb_cls;
1772   GNUNET_CONTAINER_multipeermap_iterate (validation_map,
1773                                          &validation_entries_iterate,
1774                                          &ic);
1775 }
1776
1777 /* end of file gnunet-service-transport_validation.c */