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