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