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