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