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