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