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