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