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