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