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