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