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