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