only add addresses as valid from peerinfo if we have the respective plugin loaded
[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   if (NULL == GST_plugins_find (address->transport_name))
848   {
849     /* might have been valid in the past, but we don't have that
850        plugin loaded right now */
851     return GNUNET_OK;
852   }
853
854   ve = find_validation_entry (&public_key, address);
855   ve->valid_until = GNUNET_TIME_absolute_max (ve->valid_until,
856                                               expiration);
857   if (NULL == ve->revalidation_task)
858   {
859     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
860                 "Starting revalidations for valid address `%s'\n",
861                 GST_plugins_a2s (ve->address));
862     ve->next_validation = GNUNET_TIME_absolute_get();
863     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
864   }
865   validation_entry_changed (ve, GNUNET_TRANSPORT_VS_UPDATE);
866
867   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
868   ats.value = htonl (ve->network);
869   if (GNUNET_YES != ve->known_to_ats)
870   {
871     ve->known_to_ats = GNUNET_YES;
872     GST_ats_add_address (address, NULL, &ats, 1);
873   }
874   return GNUNET_OK;
875 }
876
877
878 /**
879  * Function called for any HELLO known to PEERINFO.
880  *
881  * @param cls unused
882  * @param peer id of the peer, NULL for last call
883  * @param hello hello message for the peer (can be NULL)
884  * @param err_msg error message
885  */
886 static void
887 process_peerinfo_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
888                         const struct GNUNET_HELLO_Message *hello,
889                         const char *err_msg)
890 {
891   GNUNET_assert (NULL != peer);
892   if (NULL == hello)
893     return;
894   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
895               "Handling HELLO for peer `%s'\n",
896               GNUNET_i2s (peer));
897   GNUNET_assert (NULL ==
898                  GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO,
899                                                  &add_valid_address,
900                                                  (void *) hello));
901 }
902
903
904 /**
905  * Start the validation subsystem.
906  *
907  * @param max_fds maximum number of fds to use
908  */
909 void
910 GST_validation_start (unsigned int max_fds)
911 {
912   /**
913    * Initialization for validation throttling
914    *
915    * We have a maximum number max_fds of connections we can use for validation
916    * We monitor the number of validations in parallel and start to throttle it
917    * when doing to many validations in parallel:
918    * if (running validations < (max_fds / 2))
919    * - "fast start": run validation immediately
920    * - have delay of (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us) / (max_fds / 2)
921    *   (300 sec / ~150 == ~2 sec.) between two validations
922    */
923
924   validation_next = GNUNET_TIME_absolute_get();
925   validation_delay.rel_value_us = (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us) / (max_fds / 2);
926   validations_fast_start_threshold = (max_fds / 2);
927   validations_running = 0;
928   GNUNET_STATISTICS_set (GST_stats,
929                          gettext_noop ("# validations running"),
930                          validations_running,
931                          GNUNET_NO);
932   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
933               "Validation uses a fast start threshold of %u connections and a delay between of %s\n ",
934               validations_fast_start_threshold,
935               GNUNET_STRINGS_relative_time_to_string (validation_delay,
936                                                       GNUNET_YES));
937   validation_map = GNUNET_CONTAINER_multipeermap_create (VALIDATION_MAP_SIZE,
938                                                          GNUNET_NO);
939   pnc = GNUNET_PEERINFO_notify (GST_cfg, GNUNET_YES,
940                                 &process_peerinfo_hello, NULL);
941 }
942
943
944 /**
945  * Stop the validation subsystem.
946  */
947 void
948 GST_validation_stop ()
949 {
950   struct CheckHelloValidatedContext *chvc;
951
952   GNUNET_CONTAINER_multipeermap_iterate (validation_map,
953                                          &cleanup_validation_entry, NULL);
954   GNUNET_CONTAINER_multipeermap_destroy (validation_map);
955   validation_map = NULL;
956   while (NULL != (chvc = chvc_head))
957   {
958     GNUNET_CONTAINER_DLL_remove (chvc_head, chvc_tail, chvc);
959     GNUNET_free (chvc);
960   }
961   GNUNET_PEERINFO_notify_cancel (pnc);
962 }
963
964
965 /**
966  * Send the given PONG to the given address.
967  *
968  * @param cls the PONG message
969  * @param public_key public key for the peer, never NULL
970  * @param valid_until is ZERO if we never validated the address,
971  *                    otherwise a time up to when we consider it (or was) valid
972  * @param validation_block  is FOREVER if the address is for an unsupported plugin (from PEERINFO)
973  *                          is ZERO if the address is considered valid (no validation needed)
974  *                          otherwise a time in the future if we're currently denying re-validation
975  * @param address target address
976  */
977 static void
978 multicast_pong (void *cls,
979                 const struct GNUNET_CRYPTO_EddsaPublicKey *public_key,
980                 struct GNUNET_TIME_Absolute valid_until,
981                 struct GNUNET_TIME_Absolute validation_block,
982                 const struct GNUNET_HELLO_Address *address)
983 {
984   struct TransportPongMessage *pong = cls;
985   struct GNUNET_TRANSPORT_PluginFunctions *papi;
986   struct Session *session;
987
988   papi = GST_plugins_find (address->transport_name);
989   if (NULL == papi)
990     return;
991
992   GNUNET_assert (NULL != papi->send);
993   GNUNET_assert (NULL != papi->get_session);
994   session = papi->get_session(papi->cls, address);
995   if (NULL == session)
996   {
997      GNUNET_break (0);
998      return;
999   }
1000   GST_ats_new_session (address, session);
1001   papi->send (papi->cls, session,
1002               (const char *) pong,
1003               ntohs (pong->header.size),
1004               PONG_PRIORITY,
1005               ACCEPTABLE_PING_DELAY,
1006               NULL, NULL);
1007   GST_neighbours_notify_data_sent (&address->peer,
1008                                    address,
1009                                    session,
1010                                    pong->header.size);
1011
1012 }
1013
1014
1015 /**
1016  * We've received a PING.  If appropriate, generate a PONG.
1017  *
1018  * @param sender peer sending the PING
1019  * @param hdr the PING
1020  * @param sender_address the sender address as we got it
1021  * @param session session we got the PING from
1022  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
1023  */
1024 int
1025 GST_validation_handle_ping (const struct GNUNET_PeerIdentity *sender,
1026                             const struct GNUNET_MessageHeader *hdr,
1027                             const struct GNUNET_HELLO_Address *sender_address,
1028                             struct Session *session)
1029 {
1030   const struct TransportPingMessage *ping;
1031   struct TransportPongMessage *pong;
1032   struct GNUNET_TRANSPORT_PluginFunctions *papi;
1033   struct GNUNET_CRYPTO_EddsaSignature *sig_cache;
1034   struct GNUNET_TIME_Absolute *sig_cache_exp;
1035   const char *addr;
1036   const char *addrend;
1037   char *plugin_name;
1038   char *pos;
1039   size_t len_address;
1040   size_t len_plugin;
1041   ssize_t ret;
1042   int buggy = GNUNET_NO;
1043   struct GNUNET_HELLO_Address address;
1044
1045   if (ntohs (hdr->size) < sizeof (struct TransportPingMessage))
1046   {
1047     GNUNET_break_op (0);
1048     return GNUNET_SYSERR;
1049   }
1050   ping = (const struct TransportPingMessage *) hdr;
1051   if (0 !=
1052       memcmp (&ping->target, &GST_my_identity,
1053               sizeof (struct GNUNET_PeerIdentity)))
1054   {
1055     GNUNET_STATISTICS_update (GST_stats,
1056                               gettext_noop
1057                               ("# PING message for different peer received"), 1,
1058                               GNUNET_NO);
1059     return GNUNET_SYSERR;
1060   }
1061   GNUNET_STATISTICS_update (GST_stats,
1062                             gettext_noop ("# PING messages received"), 1,
1063                             GNUNET_NO);
1064   addr = (const char *) &ping[1];
1065   len_address = ntohs (hdr->size) - sizeof (struct TransportPingMessage);
1066   /* peer wants to confirm that this is one of our addresses, this is what is
1067    * used for address validation */
1068
1069   sig_cache = NULL;
1070   sig_cache_exp = NULL;
1071   papi = NULL;
1072   if (len_address > 0)
1073   {
1074     addrend = memchr (addr, '\0', len_address);
1075     if (NULL == addrend)
1076     {
1077       GNUNET_break_op (0);
1078       return GNUNET_SYSERR;
1079     }
1080     addrend++;
1081     len_plugin = strlen (addr) + 1;
1082     len_address -= len_plugin;
1083     address.local_info = GNUNET_HELLO_ADDRESS_INFO_NONE;
1084     address.address = addrend;
1085     address.address_length = len_address;
1086     address.transport_name = addr;
1087     address.peer = GST_my_identity;
1088
1089     if (NULL == address.transport_name)
1090     {
1091       GNUNET_break (0);
1092     }
1093
1094     if (0 != strstr (address.transport_name, "_client"))
1095     {
1096       plugin_name = GNUNET_strdup (address.transport_name);
1097       pos = strstr (plugin_name, "_client");
1098       GNUNET_assert (NULL != pos);
1099       GNUNET_snprintf (pos, strlen ("_server") + 1, "%s", "_server");
1100     }
1101     else
1102       plugin_name = GNUNET_strdup (address.transport_name);
1103
1104     if (NULL == (papi = GST_plugins_find (plugin_name)))
1105     {
1106       /* we don't have the plugin for this address */
1107       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1108                   _("Plugin `%s' not available, cannot confirm having this address\n"),
1109                   plugin_name);
1110       GNUNET_free (plugin_name);
1111       return GNUNET_SYSERR;
1112     }
1113     GNUNET_free (plugin_name);
1114     if (GNUNET_OK != papi->check_address (papi->cls, addrend, len_address))
1115     {
1116       GNUNET_STATISTICS_update (GST_stats,
1117                                 gettext_noop
1118                                 ("# failed address checks during validation"), 1,
1119                                 GNUNET_NO);
1120       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1121                   _("Address `%s' is not one of my addresses, not confirming PING\n"),
1122                   GST_plugins_a2s (&address));
1123       return GNUNET_SYSERR;
1124     }
1125     else
1126     {
1127       GNUNET_STATISTICS_update (GST_stats,
1128                                 gettext_noop
1129                                 ("# successful address checks during validation"), 1,
1130                                 GNUNET_NO);
1131       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1132                   "Address `%s' is one of my addresses, confirming PING\n",
1133                   GST_plugins_a2s (&address));
1134     }
1135
1136     if (GNUNET_YES != GST_hello_test_address (&address, &sig_cache, &sig_cache_exp))
1137     {
1138       if (GNUNET_NO == buggy)
1139       {
1140         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1141                     _("Not confirming PING from peer `%s' with address `%s' since I cannot confirm having this address.\n"),
1142                     GNUNET_i2s (sender),
1143                     GST_plugins_a2s (&address));
1144         return GNUNET_SYSERR;
1145       }
1146       else
1147       {
1148         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1149                     _("Received a PING message with validation bug from `%s'\n"),
1150                     GNUNET_i2s (sender));
1151       }
1152     }
1153   }
1154   else
1155   {
1156     addrend = NULL;             /* make gcc happy */
1157     len_plugin = 0;
1158     static struct GNUNET_CRYPTO_EddsaSignature no_address_signature;
1159     static struct GNUNET_TIME_Absolute no_address_signature_expiration;
1160
1161     sig_cache = &no_address_signature;
1162     sig_cache_exp = &no_address_signature_expiration;
1163   }
1164
1165   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1166               "I am `%s', sending PONG to peer `%s'\n",
1167               GNUNET_i2s_full (&GST_my_identity),
1168               GNUNET_i2s (sender));
1169
1170   /* message with structure:
1171    * [TransportPongMessage][Transport name][Address] */
1172
1173   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + len_address + len_plugin);
1174   pong->header.size =
1175       htons (sizeof (struct TransportPongMessage) + len_address + len_plugin);
1176   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
1177   pong->purpose.size =
1178       htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
1179              sizeof (uint32_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1180              len_address + len_plugin);
1181   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
1182   memcpy (&pong->challenge, &ping->challenge, sizeof (ping->challenge));
1183   pong->addrlen = htonl (len_address + len_plugin);
1184   memcpy (&pong[1], addr, len_plugin);   /* Copy transport plugin */
1185   if (len_address > 0)
1186   {
1187     GNUNET_assert (NULL != addrend);
1188     memcpy (&((char *) &pong[1])[len_plugin], addrend, len_address);
1189   }
1190   if (GNUNET_TIME_absolute_get_remaining (*sig_cache_exp).rel_value_us <
1191       PONG_SIGNATURE_LIFETIME.rel_value_us / 4)
1192   {
1193     /* create / update cached sig */
1194     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1195                 "Creating PONG signature to indicate ownership.\n");
1196     *sig_cache_exp = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
1197     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
1198     if (GNUNET_OK !=
1199                    GNUNET_CRYPTO_eddsa_sign (GST_my_private_key, &pong->purpose,
1200                                            sig_cache))
1201     {
1202         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1203                 _("Failed to create PONG signature for peer `%s'\n"), GNUNET_i2s (sender));
1204     }
1205   }
1206   else
1207   {
1208     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
1209   }
1210   pong->signature = *sig_cache;
1211
1212   GNUNET_assert (sender_address != NULL);
1213
1214   /* first see if the session we got this PING from can be used to transmit
1215    * a response reliably */
1216   if (NULL == papi)
1217   {
1218     ret = -1;
1219   }
1220   else
1221   {
1222     GNUNET_assert (NULL != papi->send);
1223     GNUNET_assert (NULL != papi->get_session);
1224     if (NULL == session)
1225     {
1226       session = papi->get_session (papi->cls, sender_address);
1227     }
1228     if (NULL == session)
1229     {
1230       GNUNET_break (0);
1231       ret = -1;
1232     }
1233     else
1234     {
1235       ret = papi->send (papi->cls, session,
1236                         (const char *) pong, ntohs (pong->header.size),
1237                         PONG_PRIORITY, ACCEPTABLE_PING_DELAY,
1238                         NULL, NULL);
1239       if (-1 != ret)
1240         GST_neighbours_notify_data_sent (sender,
1241                                          sender_address, session,
1242                                          pong->header.size);
1243     }
1244   }
1245   if (-1 != ret)
1246   {
1247     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1248                 "Transmitted PONG to `%s' via reliable mechanism\n",
1249                 GNUNET_i2s (sender));
1250     /* done! */
1251     GNUNET_STATISTICS_update (GST_stats,
1252                               gettext_noop
1253                               ("# PONGs unicast via reliable transport"), 1,
1254                               GNUNET_NO);
1255     GNUNET_free (pong);
1256     return GNUNET_OK;
1257   }
1258
1259   /* no reliable method found, try transmission via all known addresses */
1260   GNUNET_STATISTICS_update (GST_stats,
1261                             gettext_noop
1262                             ("# PONGs multicast to all available addresses"), 1,
1263                             GNUNET_NO);
1264   GST_validation_get_addresses (sender,
1265                                 &multicast_pong, pong);
1266   GNUNET_free (pong);
1267   return GNUNET_OK;
1268 }
1269
1270
1271 /**
1272  * Context for the #validate_address_iterator() function
1273  */
1274 struct ValidateAddressContext
1275 {
1276   /**
1277    * Hash of the public key of the peer whose address is being validated.
1278    */
1279   struct GNUNET_PeerIdentity pid;
1280
1281   /**
1282    * Public key of the peer whose address is being validated.
1283    */
1284   struct GNUNET_CRYPTO_EddsaPublicKey public_key;
1285
1286 };
1287
1288
1289 /**
1290  * Iterator callback to go over all addresses and try to validate them
1291  * (unless blocked or already validated).
1292  *
1293  * @param cls pointer to a `struct ValidateAddressContext *`
1294  * @param address the address
1295  * @param expiration expiration time
1296  * @return #GNUNET_OK (keep the address)
1297  */
1298 static int
1299 validate_address_iterator (void *cls,
1300                            const struct GNUNET_HELLO_Address *address,
1301                            struct GNUNET_TIME_Absolute expiration)
1302 {
1303   const struct ValidateAddressContext *vac = cls;
1304   struct GNUNET_TRANSPORT_PluginFunctions * papi;
1305   struct ValidationEntry *ve;
1306   struct GNUNET_TIME_Relative canonical_delay;
1307
1308   if (0 == GNUNET_TIME_absolute_get_remaining (expiration).rel_value_us)
1309   {
1310     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1311                 "Skipping expired address from HELLO\n");
1312     return GNUNET_OK;           /* expired */
1313   }
1314   ve = find_validation_entry (&vac->public_key, address);
1315
1316   papi = GST_plugins_find (ve->address->transport_name);
1317   if (papi == NULL)
1318   {
1319     /* This plugin is currently unvailable ... retry later */
1320     if (NULL == ve->revalidation_task)
1321     {
1322       if (GNUNET_YES == ve->in_use)
1323         canonical_delay = CONNECTED_PING_FREQUENCY;
1324       else if (GNUNET_TIME_absolute_get_remaining (ve->valid_until).rel_value_us > 0)
1325         canonical_delay = VALIDATED_PING_FREQUENCY;
1326       else
1327         canonical_delay = UNVALIDATED_PING_KEEPALIVE;
1328
1329       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1330         "Plugin `%s' unavailable, validation process for peer `%s' delayed for %llu ms\n",
1331         ve->address->transport_name,
1332         GNUNET_i2s (&ve->address->peer),
1333         (long long unsigned) canonical_delay.rel_value_us / 1000);
1334
1335       ve->revalidation_task = GNUNET_SCHEDULER_add_delayed (canonical_delay,
1336           &revalidate_address, ve);
1337     }
1338     return GNUNET_OK;
1339   }
1340
1341
1342   if (NULL == ve->revalidation_task)
1343   {
1344     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1345                 "Validation process started for fresh address `%s'\n",
1346                 GST_plugins_a2s (ve->address));
1347     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
1348   }
1349   return GNUNET_OK;
1350 }
1351
1352
1353 /**
1354  * Add the validated peer address to the HELLO.
1355  *
1356  * @param cls the `struct ValidationEntry *` with the validated address
1357  * @param max space in @a buf
1358  * @param buf where to add the address
1359  * @return number of bytes written, #GNUNET_SYSERR to signal the
1360  *         end of the iteration.
1361  */
1362 static ssize_t
1363 add_valid_peer_address (void *cls,
1364                         size_t max,
1365                         void *buf)
1366 {
1367   struct ValidationEntry *ve = cls;
1368
1369   if (GNUNET_YES == ve->copied)
1370     return GNUNET_SYSERR; /* Done */
1371   ve->copied = GNUNET_YES;
1372   return GNUNET_HELLO_add_address (ve->address, ve->valid_until, buf, max);
1373 }
1374
1375
1376 /**
1377  * We've received a PONG.  Check if it matches a pending PING and
1378  * mark the respective address as confirmed.
1379  *
1380  * @param sender peer sending the PONG
1381  * @param hdr the PONG
1382  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
1383  */
1384 int
1385 GST_validation_handle_pong (const struct GNUNET_PeerIdentity *sender,
1386                             const struct GNUNET_MessageHeader *hdr)
1387 {
1388   const struct TransportPongMessage *pong;
1389   struct ValidationEntry *ve;
1390   const char *tname;
1391   const char *addr;
1392   size_t addrlen;
1393   size_t slen;
1394   size_t size;
1395   struct GNUNET_HELLO_Message *hello;
1396   struct GNUNET_HELLO_Address address;
1397   int sig_res;
1398   int do_verify;
1399
1400   if (ntohs (hdr->size) < sizeof (struct TransportPongMessage))
1401   {
1402     GNUNET_break_op (0);
1403     return GNUNET_SYSERR;
1404   }
1405   GNUNET_STATISTICS_update (GST_stats,
1406                             gettext_noop ("# PONG messages received"), 1,
1407                             GNUNET_NO);
1408
1409   /* message with structure:
1410    * [TransportPongMessage][Transport name][Address] */
1411
1412   pong = (const struct TransportPongMessage *) hdr;
1413   tname = (const char *) &pong[1];
1414   size = ntohs (hdr->size) - sizeof (struct TransportPongMessage);
1415   addr = memchr (tname, '\0', size);
1416   if (NULL == addr)
1417   {
1418     GNUNET_break_op (0);
1419     return GNUNET_SYSERR;
1420   }
1421   addr++;
1422   slen = strlen (tname) + 1;
1423   addrlen = size - slen;
1424   address.peer = *sender;
1425   address.address = addr;
1426   address.address_length = addrlen;
1427   address.transport_name = tname;
1428   address.local_info = GNUNET_HELLO_ADDRESS_INFO_NONE;
1429   ve = find_validation_entry (NULL, &address);
1430   if ((NULL == ve) || (GNUNET_NO == ve->expecting_pong))
1431   {
1432     GNUNET_STATISTICS_update (GST_stats,
1433                               gettext_noop
1434                               ("# PONGs dropped, no matching pending validation"),
1435                               1, GNUNET_NO);
1436     return GNUNET_OK;
1437   }
1438   /* now check that PONG is well-formed */
1439   if (0 != memcmp (&ve->pid, sender, sizeof (struct GNUNET_PeerIdentity)))
1440   {
1441     GNUNET_break_op (0);
1442     return GNUNET_SYSERR;
1443   }
1444   if (0 ==
1445       GNUNET_TIME_absolute_get_remaining
1446       (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value_us)
1447   {
1448     GNUNET_STATISTICS_update (GST_stats,
1449                               gettext_noop
1450                               ("# PONGs dropped, signature expired"), 1,
1451                               GNUNET_NO);
1452     return GNUNET_SYSERR;
1453   }
1454
1455   sig_res = GNUNET_SYSERR;
1456   do_verify = GNUNET_YES;
1457   if (0 != GNUNET_TIME_absolute_get_remaining (ve->pong_sig_valid_until).rel_value_us)
1458   {
1459     /* We have a cached and valid signature for this peer,
1460      * try to compare instead of verify */
1461     if (0 == memcmp (&ve->pong_sig_cache, &pong->signature, sizeof (struct GNUNET_CRYPTO_EddsaSignature)))
1462     {
1463       /* signatures are identical, we can skip verification */
1464       sig_res = GNUNET_OK;
1465       do_verify = GNUNET_NO;
1466     }
1467     else
1468     {
1469       sig_res = GNUNET_SYSERR;
1470       /* signatures do not match, we have to verify */
1471     }
1472   }
1473
1474   if (GNUNET_YES == do_verify)
1475   {
1476     /* Do expensive verification */
1477     sig_res = GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
1478                                           &pong->purpose, &pong->signature,
1479                                           &ve->public_key);
1480     if (sig_res == GNUNET_SYSERR)
1481     {
1482       GNUNET_break_op (0);
1483       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1484                   "Failed to verify: invalid signature on address `%s':%s from peer `%s'\n",
1485                   tname,
1486                   GST_plugins_a2s (ve->address),
1487                   GNUNET_i2s (sender));
1488     }
1489   }
1490   if (sig_res == GNUNET_SYSERR)
1491   {
1492     GNUNET_break_op (0);
1493     return GNUNET_SYSERR;
1494   }
1495
1496   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1497               "Validation process successful for peer `%s' with plugin `%s' address `%s'\n",
1498               GNUNET_i2s (sender),
1499               tname,
1500               GST_plugins_a2s (ve->address));
1501   GNUNET_STATISTICS_update (GST_stats,
1502                             gettext_noop ("# validations succeeded"),
1503                             1,
1504                             GNUNET_NO);
1505   /* validity achieved, remember it! */
1506   ve->expecting_pong = GNUNET_NO;
1507   ve->valid_until = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1508   ve->pong_sig_cache = pong->signature;
1509         ve->pong_sig_valid_until = GNUNET_TIME_absolute_ntoh (pong->expiration);
1510   ve->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1511   {
1512     struct GNUNET_ATS_Information ats[2];
1513
1514     ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1515     ats[0].value = htonl ((uint32_t) ve->latency.rel_value_us);
1516     ats[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1517     ats[1].value = htonl ((uint32_t) ve->network);
1518     if (GNUNET_YES == ve->known_to_ats)
1519     {
1520       GST_ats_update_metrics (ve->address, NULL, ats, 2);
1521     }
1522     else
1523     {
1524       ve->known_to_ats = GNUNET_YES;
1525       GST_ats_add_address (ve->address, NULL, ats, 2);
1526     }
1527   }
1528   if (validations_running > 0)
1529   {
1530     validations_running --;
1531     GNUNET_STATISTICS_set (GST_stats,
1532                            gettext_noop ("# validations running"),
1533                            validations_running,
1534                            GNUNET_NO);
1535     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1536                 "Validation finished, %u validation processes running\n",
1537                 validations_running);
1538   }
1539   else
1540   {
1541     GNUNET_break (0);
1542   }
1543
1544   /* Notify about new validity */
1545   validation_entry_changed (ve, GNUNET_TRANSPORT_VS_UPDATE);
1546
1547   /* build HELLO to store in PEERINFO */
1548   ve->copied = GNUNET_NO;
1549   hello = GNUNET_HELLO_create (&ve->public_key,
1550                                &add_valid_peer_address, ve,
1551                                GNUNET_NO);
1552   GNUNET_PEERINFO_add_peer (GST_peerinfo, hello, NULL, NULL);
1553   GNUNET_free (hello);
1554   return GNUNET_OK;
1555 }
1556
1557
1558 /**
1559  * We've received a HELLO, check which addresses are new and trigger
1560  * validation.
1561  *
1562  * @param hello the HELLO we received
1563  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
1564  */
1565 int
1566 GST_validation_handle_hello (const struct GNUNET_MessageHeader *hello)
1567 {
1568   const struct GNUNET_HELLO_Message *hm =
1569       (const struct GNUNET_HELLO_Message *) hello;
1570   struct ValidateAddressContext vac;
1571   struct GNUNET_HELLO_Message *h;
1572   int friend;
1573
1574   friend = GNUNET_HELLO_is_friend_only (hm);
1575   if ( ( (GNUNET_YES != friend) &&
1576          (GNUNET_NO != friend) ) ||
1577        (GNUNET_OK != GNUNET_HELLO_get_id (hm, &vac.pid)) ||
1578        (GNUNET_OK != GNUNET_HELLO_get_key (hm, &vac.public_key)))
1579   {
1580     /* malformed HELLO */
1581     GNUNET_break_op (0);
1582     return GNUNET_SYSERR;
1583   }
1584   if (0 ==
1585       memcmp (&GST_my_identity, &vac.pid, sizeof (struct GNUNET_PeerIdentity)))
1586     return GNUNET_OK;
1587   /* Add peer identity without addresses to peerinfo service */
1588   h = GNUNET_HELLO_create (&vac.public_key, NULL, NULL, friend);
1589   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1590               _("Validation received new %s message for peer `%s' with size %u\n"),
1591               "HELLO",
1592               GNUNET_i2s (&vac.pid),
1593               ntohs (hello->size));
1594   GNUNET_PEERINFO_add_peer (GST_peerinfo, h, NULL, NULL);
1595
1596   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1597               _("Adding `%s' without addresses for peer `%s'\n"), "HELLO",
1598               GNUNET_i2s (&vac.pid));
1599
1600   GNUNET_free (h);
1601   GNUNET_assert (NULL ==
1602                  GNUNET_HELLO_iterate_addresses (hm, GNUNET_NO,
1603                                                  &validate_address_iterator,
1604                                                  &vac));
1605   return GNUNET_OK;
1606 }
1607
1608
1609 /**
1610  * Closure for #iterate_addresses().
1611  */
1612 struct IteratorContext
1613 {
1614   /**
1615    * Function to call on each address.
1616    */
1617   GST_ValidationAddressCallback cb;
1618
1619   /**
1620    * Closure for @e cb.
1621    */
1622   void *cb_cls;
1623
1624 };
1625
1626
1627 /**
1628  * Call the callback in the closure for each validation entry.
1629  *
1630  * @param cls the `struct IteratorContext`
1631  * @param key the peer's identity
1632  * @param value the `struct ValidationEntry`
1633  * @return #GNUNET_OK (continue to iterate)
1634  */
1635 static int
1636 iterate_addresses (void *cls,
1637                    const struct GNUNET_PeerIdentity *key,
1638                    void *value)
1639 {
1640   struct IteratorContext *ic = cls;
1641   struct ValidationEntry *ve = value;
1642
1643   ic->cb (ic->cb_cls,
1644           &ve->public_key,
1645           ve->valid_until,
1646           ve->revalidation_block,
1647           ve->address);
1648   return GNUNET_OK;
1649 }
1650
1651
1652 /**
1653  * Call the given function for each address for the given target.
1654  * Can either give a snapshot (synchronous API) or be continuous.
1655  *
1656  * @param target peer information is requested for
1657  * @param cb function to call; will not be called after this function returns
1658  * @param cb_cls closure for @a cb
1659  */
1660 void
1661 GST_validation_get_addresses (const struct GNUNET_PeerIdentity *target,
1662                               GST_ValidationAddressCallback cb, void *cb_cls)
1663 {
1664   struct IteratorContext ic;
1665
1666   ic.cb = cb;
1667   ic.cb_cls = cb_cls;
1668   GNUNET_CONTAINER_multipeermap_get_multiple (validation_map,
1669                                               target,
1670                                               &iterate_addresses, &ic);
1671 }
1672
1673
1674 /**
1675  * Update if we are using an address for a connection actively right now.
1676  * Based on this, the validation module will measure latency for the
1677  * address more or less often.
1678  *
1679  * @param address the address
1680  * @param session the session
1681  * @param in_use #GNUNET_YES if we are now using the address for a connection,
1682  *               #GNUNET_NO if we are no longer using the address for a connection
1683  */
1684 void
1685 GST_validation_set_address_use (const struct GNUNET_HELLO_Address *address,
1686                                 struct Session *session,
1687                                 int in_use)
1688 {
1689   struct ValidationEntry *ve;
1690
1691   if (NULL != address)
1692     ve = find_validation_entry (NULL, address);
1693   else
1694     ve = NULL;                  /* FIXME: lookup based on session... */
1695   if (NULL == ve)
1696   {
1697     /* this can happen for inbound connections (sender_address_len == 0); */
1698     return;
1699   }
1700   if (ve->in_use == in_use)
1701   {
1702     if (GNUNET_YES == in_use)
1703     {
1704       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1705                   "Error setting address in use for peer `%s' `%s' to USED\n",
1706                   GNUNET_i2s (&address->peer), GST_plugins_a2s (address));
1707     }
1708     if (GNUNET_NO == in_use)
1709     {
1710       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1711                   "Error setting address in use for peer `%s' `%s' to NOT_USED\n",
1712                   GNUNET_i2s (&address->peer), GST_plugins_a2s (address));
1713     }
1714   }
1715
1716   GNUNET_break (ve->in_use != in_use);  /* should be different... */
1717   ve->in_use = in_use;
1718   if (in_use == GNUNET_YES)
1719   {
1720     /* from now on, higher frequeny, so reschedule now */
1721     GNUNET_SCHEDULER_cancel (ve->revalidation_task);
1722     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
1723   }
1724 }
1725
1726
1727 /**
1728  * Query validation about the latest observed latency on a given
1729  * address.
1730  *
1731  * @param sender peer
1732  * @param address the address
1733  * @param session session
1734  * @return observed latency of the address, FOREVER if the address was
1735  *         never successfully validated
1736  */
1737 struct GNUNET_TIME_Relative
1738 GST_validation_get_address_latency (const struct GNUNET_PeerIdentity *sender,
1739                                     const struct GNUNET_HELLO_Address *address,
1740                                     struct Session *session)
1741 {
1742   struct ValidationEntry *ve;
1743
1744   if (NULL == address)
1745   {
1746     GNUNET_break (0);           // FIXME: support having latency only with session...
1747     return GNUNET_TIME_UNIT_FOREVER_REL;
1748   }
1749   ve = find_validation_entry (NULL, address);
1750   if (NULL == ve)
1751     return GNUNET_TIME_UNIT_FOREVER_REL;
1752   return ve->latency;
1753 }
1754
1755 /**
1756  * Closure for the validation_entries_iterate function.
1757  */
1758 struct ValidationIteratorContext
1759 {
1760   /**
1761    * Function to call on each validation entry
1762    */
1763   GST_ValidationChangedCallback cb;
1764
1765   /**
1766    * Closure for @e cb.
1767    */
1768   void *cb_cls;
1769 };
1770
1771
1772 static int
1773 validation_entries_iterate (void *cls,
1774                            const struct GNUNET_PeerIdentity *key,
1775                            void *value)
1776 {
1777   struct ValidationIteratorContext *ic = cls;
1778   struct ValidationEntry *ve = value;
1779
1780   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Notifying about validation entry for peer `%s' address `%s' \n",
1781       GNUNET_i2s (&ve->pid), GST_plugins_a2s (ve->address));
1782   ic->cb (ic->cb_cls, &ve->pid, ve->address, ve->send_time,
1783       ve->valid_until, ve->next_validation, ve->state);
1784
1785   return GNUNET_OK;
1786 }
1787
1788 /**
1789  * Iterate over all iteration entries
1790  *
1791  * @param cb function to call
1792  * @param cb_cls closure for cb
1793  */
1794 void
1795 GST_validation_iterate (GST_ValidationChangedCallback cb,
1796                         void *cb_cls)
1797 {
1798   struct ValidationIteratorContext ic;
1799
1800   if (NULL == validation_map)
1801     return; /* can happen during shutdown */
1802   ic.cb = cb;
1803   ic.cb_cls = cb_cls;
1804   GNUNET_CONTAINER_multipeermap_iterate (validation_map,
1805                                          &validation_entries_iterate,
1806                                          &ic);
1807 }
1808
1809 /* end of file gnunet-service-transport_validation.c */