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