profiler
[oweals/gnunet.git] / src / transport / gnunet-service-transport_validation.c
1 /*
2      This file is part of GNUnet.
3      (C) 2010-2014 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file transport/gnunet-service-transport_validation.c
23  * @brief address validation subsystem
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include "gnunet-service-transport_clients.h"
28 #include "gnunet-service-transport_validation.h"
29 #include "gnunet-service-transport_plugins.h"
30 #include "gnunet-service-transport_hello.h"
31 #include "gnunet-service-transport_blacklist.h"
32 #include "gnunet-service-transport_neighbours.h"
33 #include "gnunet-service-transport.h"
34 #include "gnunet_hello_lib.h"
35 #include "gnunet_ats_service.h"
36 #include "gnunet_peerinfo_service.h"
37 #include "gnunet_signatures.h"
38
39
40 /**
41  * How long is a PONG signature valid?  We'll recycle a signature until
42  * 1/4 of this time is remaining.  PONGs should expire so that if our
43  * external addresses change an adversary cannot replay them indefinitely.
44  * OTOH, we don't want to spend too much time generating PONG signatures,
45  * so they must have some lifetime to reduce our CPU usage.
46  */
47 #define PONG_SIGNATURE_LIFETIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 1)
48
49 /**
50  * After how long do we expire an address in a HELLO that we just
51  * validated?  This value is also used for our own addresses when we
52  * create a HELLO.
53  */
54 #define HELLO_ADDRESS_EXPIRATION GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_HOURS, 12)
55
56 /**
57  * How often do we allow PINGing an address that we have not yet
58  * validated?  This also determines how long we track an address that
59  * we cannot validate (because after this time we can destroy the
60  * validation record).
61  */
62 #define UNVALIDATED_PING_KEEPALIVE GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 5)
63
64 /**
65  * How often do we PING an address that we have successfully validated
66  * in the past but are not actively using?  Should be (significantly)
67  * smaller than HELLO_ADDRESS_EXPIRATION.
68  */
69 #define VALIDATED_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 15)
70
71 /**
72  * How often do we PING an address that we are currently using?
73  */
74 #define CONNECTED_PING_FREQUENCY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 2)
75
76 /**
77  * How much delay is acceptable for sending the PING or PONG?
78  */
79 #define ACCEPTABLE_PING_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
80
81 /**
82  * Size of the validation map hashmap.
83  */
84 #define VALIDATION_MAP_SIZE 256
85
86 /**
87  * Priority to use for PINGs
88  */
89 #define PING_PRIORITY 2
90
91 /**
92  * Priority to use for PONGs
93  */
94 #define PONG_PRIORITY 4
95
96
97 GNUNET_NETWORK_STRUCT_BEGIN
98
99 /**
100  * Message used to ask a peer to validate receipt (to check an address
101  * from a HELLO).  Followed by the address we are trying to validate,
102  * or an empty address if we are just sending a PING to confirm that a
103  * connection which the receiver (of the PING) initiated is still valid.
104  */
105 struct TransportPingMessage
106 {
107
108   /**
109    * Type will be #GNUNET_MESSAGE_TYPE_TRANSPORT_PING
110    */
111   struct GNUNET_MessageHeader header;
112
113   /**
114    * Challenge code (to ensure fresh reply).
115    */
116   uint32_t challenge GNUNET_PACKED;
117
118   /**
119    * Who is the intended recipient?
120    */
121   struct GNUNET_PeerIdentity target;
122
123 };
124
125
126 /**
127  * Message used to validate a HELLO.  The challenge is included in the
128  * confirmation to make matching of replies to requests possible.  The
129  * signature signs our public key, an expiration time and our address.<p>
130  *
131  * This message is followed by our transport address that the PING tried
132  * to confirm (if we liked it).  The address can be empty (zero bytes)
133  * if the PING had not address either (and we received the request via
134  * a connection that we initiated).
135  */
136 struct TransportPongMessage
137 {
138
139   /**
140    * Type will be #GNUNET_MESSAGE_TYPE_TRANSPORT_PONG
141    */
142   struct GNUNET_MessageHeader header;
143
144   /**
145    * Challenge code from PING (showing freshness).  Not part of what
146    * is signed so that we can re-use signatures.
147    */
148   uint32_t challenge GNUNET_PACKED;
149
150   /**
151    * Signature.
152    */
153   struct GNUNET_CRYPTO_EddsaSignature signature;
154
155   /**
156    * #GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN to confirm that this is a
157    * plausible address for the signing peer.
158    */
159   struct GNUNET_CRYPTO_EccSignaturePurpose purpose;
160
161   /**
162    * When does this signature expire?
163    */
164   struct GNUNET_TIME_AbsoluteNBO expiration;
165
166   /**
167    * Size of address appended to this message (part of what is
168    * being signed, hence not redundant).
169    */
170   uint32_t addrlen GNUNET_PACKED;
171
172 };
173 GNUNET_NETWORK_STRUCT_END
174
175 /**
176  * Information about an address under validation
177  */
178 struct ValidationEntry
179 {
180
181   /**
182    * The address.
183    */
184   struct GNUNET_HELLO_Address *address;
185
186   /**
187    * Handle to the blacklist check (if we're currently in it).
188    */
189   struct GST_BlacklistCheck *bc;
190
191   /**
192    * Public key of the peer.
193    */
194   struct GNUNET_CRYPTO_EddsaPublicKey public_key;
195
196   /**
197    * The identity of the peer. FIXME: duplicated (also in 'address')
198    */
199   struct GNUNET_PeerIdentity pid;
200
201   /**
202    * Cached PONG signature
203    */
204   struct GNUNET_CRYPTO_EddsaSignature pong_sig_cache;
205
206   /**
207    * ID of task that will clean up this entry if nothing happens.
208    */
209   GNUNET_SCHEDULER_TaskIdentifier timeout_task;
210
211   /**
212    * ID of task that will trigger address revalidation.
213    */
214   GNUNET_SCHEDULER_TaskIdentifier revalidation_task;
215
216   /**
217    * At what time did we send the latest validation request (PING)?
218    */
219   struct GNUNET_TIME_Absolute send_time;
220
221   /**
222    * At what time do we send the next validation request (PING)?
223    */
224   struct GNUNET_TIME_Absolute next_validation;
225
226   /**
227    * Until when is this address valid?
228    * ZERO if it is not currently considered valid.
229    */
230   struct GNUNET_TIME_Absolute valid_until;
231
232   /**
233    * Until when is the cached PONG signature valid?
234    * ZERO if it is not currently considered valid.
235    */
236   struct GNUNET_TIME_Absolute pong_sig_valid_until;
237
238   /**
239    * How long until we can try to validate this address again?
240    * FOREVER if the address is for an unsupported plugin (from PEERINFO)
241    * ZERO if the address is considered valid (no validation needed)
242    * otherwise a time in the future if we're currently denying re-validation
243    */
244   struct GNUNET_TIME_Absolute revalidation_block;
245
246   /**
247    * Last observed latency for this address (round-trip), delay between
248    * last PING sent and PONG received; FOREVER if we never got a PONG.
249    */
250   struct GNUNET_TIME_Relative latency;
251
252   /**
253    * Current state of this validation entry
254    */
255   enum GNUNET_TRANSPORT_ValidationState state;
256   /**
257    * Challenge number we used.
258    */
259   uint32_t challenge;
260
261   /**
262    * When passing the address in 'add_valid_peer_address', did we
263    * copy the address to the HELLO yet?
264    */
265   int copied;
266
267   /**
268    * Are we currently using this address for a connection?
269    */
270   int in_use;
271
272   /**
273    * Are we expecting a PONG message for this validation entry?
274    */
275   int expecting_pong;
276
277   enum GNUNET_ATS_Network_Type network;
278 };
279
280
281 /**
282  * Context of currently active requests to peerinfo
283  * for validation of HELLOs.
284  */
285 struct CheckHelloValidatedContext
286 {
287
288   /**
289    * This is a doubly-linked list.
290    */
291   struct CheckHelloValidatedContext *next;
292
293   /**
294    * This is a doubly-linked list.
295    */
296   struct CheckHelloValidatedContext *prev;
297
298   /**
299    * Hello that we are validating.
300    */
301   const struct GNUNET_HELLO_Message *hello;
302
303 };
304
305
306 /**
307  * Head of linked list of HELLOs awaiting validation.
308  */
309 static struct CheckHelloValidatedContext *chvc_head;
310
311 /**
312  * Tail of linked list of HELLOs awaiting validation
313  */
314 static struct CheckHelloValidatedContext *chvc_tail;
315
316 /**
317  * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
318  * of the given peer that we are currently validating, have validated
319  * or are blocked from re-validation for a while).
320  */
321 static struct GNUNET_CONTAINER_MultiPeerMap *validation_map;
322
323 /**
324  * Context for peerinfo iteration.
325  */
326 static struct GNUNET_PEERINFO_NotifyContext *pnc;
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
349 /**
350  * Context for the validation entry match function.
351  */
352 struct ValidationEntryMatchContext
353 {
354   /**
355    * Where to store the result?
356    */
357   struct ValidationEntry *ve;
358
359   /**
360    * Address we're interested in.
361    */
362   const struct GNUNET_HELLO_Address *address;
363
364 };
365
366
367 /**
368  * Iterate over validation entries until a matching one is found.
369  *
370  * @param cls the `struct ValidationEntryMatchContext *`
371  * @param key peer identity (unused)
372  * @param value a `struct ValidationEntry *` to match
373  * @return #GNUNET_YES if the entry does not match,
374  *         #GNUNET_NO if the entry does match
375  */
376 static int
377 validation_entry_match (void *cls,
378                         const struct GNUNET_PeerIdentity *key,
379                         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
393 /**
394  * A validation entry changed.  Update the state and notify
395  * monitors.
396  *
397  * @param ve validation entry that changed
398  * @param state new state
399  */
400 static void
401 validation_entry_changed (struct ValidationEntry *ve,
402                           enum GNUNET_TRANSPORT_ValidationState state)
403 {
404   ve->state = state;
405   GST_clients_broadcast_validation_notification (&ve->pid,
406                                                  ve->address,
407                                                  ve->send_time,
408                                                  ve->valid_until,
409                                                  ve->next_validation,
410                                                  state);
411 }
412
413
414 /**
415  * Iterate over validation entries and free them.
416  *
417  * @param cls (unused)
418  * @param key peer identity (unused)
419  * @param value a `struct ValidationEntry *` to clean up
420  * @return #GNUNET_YES (continue to iterate)
421  */
422 static int
423 cleanup_validation_entry (void *cls,
424                           const struct GNUNET_PeerIdentity *key,
425                           void *value)
426 {
427   struct ValidationEntry *ve = value;
428
429   ve->next_validation = GNUNET_TIME_absolute_get_zero_();
430   ve->valid_until = GNUNET_TIME_UNIT_ZERO_ABS;
431
432   /* Notify about deleted entry */
433   validation_entry_changed (ve, GNUNET_TRANSPORT_VS_REMOVE);
434
435   if (NULL != ve->bc)
436   {
437     GST_blacklist_test_cancel (ve->bc);
438     ve->bc = NULL;
439   }
440   GNUNET_break (GNUNET_OK ==
441                 GNUNET_CONTAINER_multipeermap_remove (validation_map,
442                                                       &ve->pid, ve));
443   GNUNET_HELLO_address_free (ve->address);
444   if (GNUNET_SCHEDULER_NO_TASK != ve->timeout_task)
445   {
446     GNUNET_SCHEDULER_cancel (ve->timeout_task);
447     ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
448   }
449   if (GNUNET_SCHEDULER_NO_TASK != ve->revalidation_task)
450   {
451     GNUNET_SCHEDULER_cancel (ve->revalidation_task);
452     ve->revalidation_task = GNUNET_SCHEDULER_NO_TASK;
453   }
454   if ((GNUNET_YES == ve->expecting_pong) &&
455                 (validations_running > 0))
456   {
457                 validations_running --;
458           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
459                       "Validation finished, %u validation processes running\n",
460                       validations_running);
461   }
462   GNUNET_free (ve);
463   return GNUNET_OK;
464 }
465
466
467 /**
468  * Address validation cleanup task.  Assesses if the record is no
469  * longer valid and then possibly triggers its removal.
470  *
471  * @param cls the 'struct ValidationEntry'
472  * @param tc scheduler context (unused)
473  */
474 static void
475 timeout_hello_validation (void *cls,
476                           const struct GNUNET_SCHEDULER_TaskContext *tc)
477 {
478   struct ValidationEntry *ve = cls;
479   struct GNUNET_TIME_Absolute max;
480   struct GNUNET_TIME_Relative left;
481
482   ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
483   max = GNUNET_TIME_absolute_max (ve->valid_until, ve->revalidation_block);
484   left = GNUNET_TIME_absolute_get_remaining (max);
485   if (left.rel_value_us > 0)
486   {
487     /* should wait a bit longer */
488     ve->timeout_task =
489         GNUNET_SCHEDULER_add_delayed (left, &timeout_hello_validation, ve);
490     return;
491   }
492   GNUNET_STATISTICS_update (GST_stats,
493                             gettext_noop ("# address records discarded"), 1,
494                             GNUNET_NO);
495   cleanup_validation_entry (NULL, &ve->pid, ve);
496 }
497
498
499 /**
500  * Function called with the result from blacklisting.
501  * Send a PING to the other peer if a communication is allowed.
502  *
503  * @param cls our 'struct ValidationEntry'
504  * @param pid identity of the other peer
505  * @param result #GNUNET_OK if the connection is allowed, #GNUNET_NO if not
506  */
507 static void
508 transmit_ping_if_allowed (void *cls,
509                           const struct GNUNET_PeerIdentity *pid,
510                           int result)
511 {
512   struct ValidationEntry *ve = cls;
513   struct TransportPingMessage ping;
514   struct GNUNET_TRANSPORT_PluginFunctions *papi;
515   struct GNUNET_TIME_Absolute next;
516   const struct GNUNET_MessageHeader *hello;
517   enum GNUNET_ATS_Network_Type network;
518   ssize_t ret;
519   size_t tsize;
520   size_t slen;
521   uint16_t hsize;
522
523   ve->bc = NULL;
524   if (GNUNET_NO == result)
525   {
526     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
527                 "Blacklist denies to send PING to `%s' `%s' `%s'\n",
528                 GNUNET_i2s (pid),
529                 GST_plugins_a2s (ve->address),
530                 ve->address->transport_name);
531     return;
532   }
533
534   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
535               "Transmitting plain PING to `%s' `%s' `%s'\n",
536               GNUNET_i2s (pid),
537               GST_plugins_a2s (ve->address),
538               ve->address->transport_name);
539
540   next = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(),
541                                    validation_delay);
542   if (next.abs_value_us > validation_next.abs_value_us)
543     validation_next = next; /* We're going to send a PING so delay next validation */
544
545   slen = strlen (ve->address->transport_name) + 1;
546   hello = GST_hello_get ();
547   hsize = ntohs (hello->size);
548   tsize =
549       sizeof (struct TransportPingMessage) + ve->address->address_length +
550       slen + hsize;
551
552   ping.header.size =
553       htons (sizeof (struct TransportPingMessage) +
554              ve->address->address_length + slen);
555   ping.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
556   ping.challenge = htonl (ve->challenge);
557   ping.target = *pid;
558
559   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
560   {
561     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
562                 _
563                 ("Not transmitting `%s' with `%s', message too big (%u bytes!). This should not happen.\n"),
564                 "HELLO", "PING", (unsigned int) tsize);
565     /* message too big (!?), get rid of HELLO */
566     hsize = 0;
567     tsize =
568         sizeof (struct TransportPingMessage) + ve->address->address_length +
569         slen + hsize;
570   }
571   {
572     char message_buf[tsize];
573
574     /* build message with structure:
575      *  [HELLO][TransportPingMessage][Transport name][Address] */
576     memcpy (message_buf, hello, hsize);
577     memcpy (&message_buf[hsize], &ping, sizeof (struct TransportPingMessage));
578     memcpy (&message_buf[sizeof (struct TransportPingMessage) + hsize],
579             ve->address->transport_name, slen);
580     memcpy (&message_buf[sizeof (struct TransportPingMessage) + slen + hsize],
581             ve->address->address, ve->address->address_length);
582     papi = GST_plugins_find (ve->address->transport_name);
583     if (papi == NULL)
584       ret = -1;
585     else
586     {
587       GNUNET_assert (NULL != papi->send);
588       GNUNET_assert (NULL != papi->get_session);
589       struct Session * session = papi->get_session(papi->cls, ve->address);
590
591       if (session != NULL)
592       {
593         ret = papi->send (papi->cls, session,
594                           message_buf, tsize,
595                           PING_PRIORITY, ACCEPTABLE_PING_DELAY,
596                           NULL, NULL);
597         network = papi->get_network (papi->cls, session);
598         if (GNUNET_ATS_NET_UNSPECIFIED == network)
599         {
600           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
601                       "Could not obtain a valid network for `%s' `%s'\n",
602                       GNUNET_i2s (pid),
603                       GST_plugins_a2s (ve->address));
604           GNUNET_break(0);
605         }
606         GST_neighbours_notify_data_sent (pid, ve->address, session, tsize);
607       }
608       else
609       {
610         /* Could not get a valid session */
611         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
612                     "Could not get a valid session for `%s' `%s'\n",
613                     GNUNET_i2s (pid),
614                     GST_plugins_a2s (ve->address));
615         ret = -1;
616       }
617     }
618   }
619   if (-1 != ret)
620   {
621     ve->send_time = GNUNET_TIME_absolute_get ();
622     GNUNET_STATISTICS_update (GST_stats,
623                               gettext_noop
624                               ("# PING without HELLO messages sent"), 1,
625                               GNUNET_NO);
626
627     ve->network = network;
628     ve->expecting_pong = GNUNET_YES;
629     validations_running++;
630     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
631                 "Validation started, %u validation processes running\n",
632                 validations_running);
633     /*  Notify about PING sent */
634     validation_entry_changed (ve, GNUNET_TRANSPORT_VS_UPDATE);
635   }
636 }
637
638
639 /**
640  * Do address validation again to keep address valid.
641  *
642  * @param cls the 'struct ValidationEntry'
643  * @param tc scheduler context (unused)
644  */
645 static void
646 revalidate_address (void *cls,
647                     const struct GNUNET_SCHEDULER_TaskContext *tc)
648 {
649   struct ValidationEntry *ve = cls;
650   struct GNUNET_TIME_Relative canonical_delay;
651   struct GNUNET_TIME_Relative delay;
652   struct GNUNET_TIME_Relative blocked_for;
653   struct GST_BlacklistCheck *bc;
654   uint32_t rdelay;
655
656   ve->revalidation_task = GNUNET_SCHEDULER_NO_TASK;
657   delay = GNUNET_TIME_absolute_get_remaining (ve->revalidation_block);
658   /* How long until we can possibly permit the next PING? */
659   if (GNUNET_YES == ve->in_use)
660     canonical_delay = CONNECTED_PING_FREQUENCY;
661   else if (GNUNET_TIME_absolute_get_remaining (ve->valid_until).rel_value_us > 0)
662     canonical_delay = VALIDATED_PING_FREQUENCY;
663   else
664     canonical_delay = UNVALIDATED_PING_KEEPALIVE;
665
666   if (delay.rel_value_us > canonical_delay.rel_value_us * 2)
667   {
668     /* situation changed, recalculate delay */
669     delay = canonical_delay;
670     ve->revalidation_block = GNUNET_TIME_relative_to_absolute (delay);
671   }
672   if (delay.rel_value_us > 0)
673   {
674     /* should wait a bit longer */
675     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
676                 "Waiting for %s longer before validating address `%s'\n",
677                 GNUNET_STRINGS_relative_time_to_string (delay,
678                                                         GNUNET_YES),
679                 GST_plugins_a2s (ve->address));
680     ve->revalidation_task =
681         GNUNET_SCHEDULER_add_delayed (delay, &revalidate_address, ve);
682     ve->next_validation =  GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), delay);
683     return;
684   }
685   blocked_for = GNUNET_TIME_absolute_get_remaining(validation_next);
686   if ((validations_running > validations_fast_start_threshold) &&
687                 (blocked_for.rel_value_us > 0))
688   {
689     /* Validations are blocked, have to wait for blocked_for time */
690     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
691                 "Validations blocked for another %s, delaying validating address `%s'\n",
692                 GNUNET_STRINGS_relative_time_to_string (blocked_for,
693                                                         GNUNET_YES),
694                 GST_plugins_a2s (ve->address));
695     ve->revalidation_task =
696       GNUNET_SCHEDULER_add_delayed (blocked_for, &revalidate_address, ve);
697     ve->next_validation =  GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), blocked_for);
698     return;
699   }
700   ve->revalidation_block = GNUNET_TIME_relative_to_absolute (canonical_delay);
701
702   /* schedule next PINGing with some extra random delay to avoid synchronous re-validations */
703   rdelay =
704       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
705                                 canonical_delay.rel_value_us);
706
707   delay = GNUNET_TIME_relative_add (canonical_delay,
708                                     GNUNET_TIME_relative_multiply
709                                     (GNUNET_TIME_UNIT_MICROSECONDS, rdelay));
710
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 max_fds maximum number of fds to use
867  */
868 void
869 GST_validation_start (unsigned int max_fds)
870 {
871   /**
872    * Initialization for validation throttling
873    *
874    * We have a maximum number max_fds of connections we can use for validation
875    * We monitor the number of validations in parallel and start to throttle it
876    * when doing to many validations in parallel:
877    * if (running validations < (max_fds / 2))
878    * - "fast start": run validation immediately
879    * - have delay of (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us) / (max_fds / 2)
880    *   (300 sec / ~150 == ~2 sec.) between two validations
881    */
882
883   validation_next = GNUNET_TIME_absolute_get();
884   validation_delay.rel_value_us = (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us) / (max_fds / 2);
885   validations_fast_start_threshold = (max_fds / 2);
886   validations_running = 0;
887   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
888               "Validation uses a fast start threshold of %u connections and a delay between of %s\n ",
889               validations_fast_start_threshold,
890               GNUNET_STRINGS_relative_time_to_string (validation_delay,
891                                                       GNUNET_YES));
892   validation_map = GNUNET_CONTAINER_multipeermap_create (VALIDATION_MAP_SIZE,
893                                                          GNUNET_NO);
894   pnc = GNUNET_PEERINFO_notify (GST_cfg, GNUNET_YES,
895                                 &process_peerinfo_hello, NULL);
896 }
897
898
899 /**
900  * Stop the validation subsystem.
901  */
902 void
903 GST_validation_stop ()
904 {
905   struct CheckHelloValidatedContext *chvc;
906
907   GNUNET_CONTAINER_multipeermap_iterate (validation_map,
908                                          &cleanup_validation_entry, NULL);
909   GNUNET_CONTAINER_multipeermap_destroy (validation_map);
910   validation_map = NULL;
911   while (NULL != (chvc = chvc_head))
912   {
913     GNUNET_CONTAINER_DLL_remove (chvc_head, chvc_tail, chvc);
914     GNUNET_free (chvc);
915   }
916   GNUNET_PEERINFO_notify_cancel (pnc);
917 }
918
919
920 /**
921  * Send the given PONG to the given address.
922  *
923  * @param cls the PONG message
924  * @param public_key public key for the peer, never NULL
925  * @param valid_until is ZERO if we never validated the address,
926  *                    otherwise a time up to when we consider it (or was) valid
927  * @param validation_block  is FOREVER if the address is for an unsupported plugin (from PEERINFO)
928  *                          is ZERO if the address is considered valid (no validation needed)
929  *                          otherwise a time in the future if we're currently denying re-validation
930  * @param address target address
931  */
932 static void
933 multicast_pong (void *cls,
934                 const struct GNUNET_CRYPTO_EddsaPublicKey *public_key,
935                 struct GNUNET_TIME_Absolute valid_until,
936                 struct GNUNET_TIME_Absolute validation_block,
937                 const struct GNUNET_HELLO_Address *address)
938 {
939   struct TransportPongMessage *pong = cls;
940   struct GNUNET_TRANSPORT_PluginFunctions *papi;
941   struct Session *session;
942
943   papi = GST_plugins_find (address->transport_name);
944   if (NULL == papi)
945     return;
946
947   GNUNET_assert (NULL != papi->send);
948   GNUNET_assert (NULL != papi->get_session);
949   session = papi->get_session(papi->cls, address);
950   if (NULL == session)
951   {
952      GNUNET_break (0);
953      return;
954   }
955   papi->send (papi->cls, session,
956               (const char *) pong,
957               ntohs (pong->header.size),
958               PONG_PRIORITY,
959               ACCEPTABLE_PING_DELAY,
960               NULL, NULL);
961   GST_neighbours_notify_data_sent (&address->peer,
962                                    address,
963                                    session,
964                                    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 len_address;
994   size_t len_plugin;
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   len_address = 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 (len_address > 0)
1027   {
1028     addrend = memchr (addr, '\0', len_address);
1029     if (NULL == addrend)
1030     {
1031       GNUNET_break_op (0);
1032       return GNUNET_SYSERR;
1033     }
1034     addrend++;
1035     len_plugin = strlen (addr) + 1;
1036     len_address -= len_plugin;
1037     address.local_info = GNUNET_HELLO_ADDRESS_INFO_NONE;
1038     address.address = addrend;
1039     address.address_length = len_address;
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, len_address))
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     len_plugin = 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) + len_address + len_plugin);
1128   pong->header.size =
1129       htons (sizeof (struct TransportPongMessage) + len_address + len_plugin);
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              len_address + len_plugin);
1135   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
1136   memcpy (&pong->challenge, &ping->challenge, sizeof (ping->challenge));
1137   pong->addrlen = htonl (len_address + len_plugin);
1138   memcpy (&pong[1], addr, len_plugin);   /* Copy transport plugin */
1139   if (len_address > 0)
1140   {
1141     GNUNET_assert (NULL != addrend);
1142     memcpy (&((char *) &pong[1])[len_plugin], addrend, len_address);
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 (-1 != ret)
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 GNUNET_TRANSPORT_PluginFunctions * papi;
1258   struct ValidationEntry *ve;
1259   struct GNUNET_TIME_Relative canonical_delay;
1260
1261   if (0 == GNUNET_TIME_absolute_get_remaining (expiration).rel_value_us)
1262   {
1263     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1264                 "Skipping expired address from HELLO\n");
1265     return GNUNET_OK;           /* expired */
1266   }
1267   ve = find_validation_entry (&vac->public_key, address);
1268
1269   papi = GST_plugins_find (ve->address->transport_name);
1270   if (papi == NULL)
1271   {
1272     /* This plugin is currently unvailable ... retry later */
1273     if (GNUNET_SCHEDULER_NO_TASK == ve->revalidation_task)
1274     {
1275       if (GNUNET_YES == ve->in_use)
1276         canonical_delay = CONNECTED_PING_FREQUENCY;
1277       else if (GNUNET_TIME_absolute_get_remaining (ve->valid_until).rel_value_us > 0)
1278         canonical_delay = VALIDATED_PING_FREQUENCY;
1279       else
1280         canonical_delay = UNVALIDATED_PING_KEEPALIVE;
1281
1282       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1283         "Plugin `%s' unavailable, validation process for peer `%s' delayed for %llu ms\n",
1284         ve->address->transport_name,
1285         GNUNET_i2s (&ve->address->peer),
1286         (long long unsigned) canonical_delay.rel_value_us / 1000);
1287
1288       ve->revalidation_task = GNUNET_SCHEDULER_add_delayed (canonical_delay,
1289           &revalidate_address, ve);
1290     }
1291     return GNUNET_OK;
1292   }
1293
1294
1295   if (GNUNET_SCHEDULER_NO_TASK == ve->revalidation_task)
1296   {
1297     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1298                 "Validation process started for fresh address `%s'\n",
1299                 GST_plugins_a2s (ve->address));
1300     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
1301   }
1302   return GNUNET_OK;
1303 }
1304
1305
1306 /**
1307  * Add the validated peer address to the HELLO.
1308  *
1309  * @param cls the `struct ValidationEntry *` with the validated address
1310  * @param max space in @a buf
1311  * @param buf where to add the address
1312  * @return number of bytes written, #GNUNET_SYSERR to signal the
1313  *         end of the iteration.
1314  */
1315 static ssize_t
1316 add_valid_peer_address (void *cls,
1317                         size_t max,
1318                         void *buf)
1319 {
1320   struct ValidationEntry *ve = cls;
1321
1322   if (GNUNET_YES == ve->copied)
1323     return GNUNET_SYSERR; /* Done */
1324   ve->copied = GNUNET_YES;
1325   return GNUNET_HELLO_add_address (ve->address, ve->valid_until, buf, max);
1326 }
1327
1328
1329 /**
1330  * We've received a PONG.  Check if it matches a pending PING and
1331  * mark the respective address as confirmed.
1332  *
1333  * @param sender peer sending the PONG
1334  * @param hdr the PONG
1335  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
1336  */
1337 int
1338 GST_validation_handle_pong (const struct GNUNET_PeerIdentity *sender,
1339                             const struct GNUNET_MessageHeader *hdr)
1340 {
1341   const struct TransportPongMessage *pong;
1342   struct ValidationEntry *ve;
1343   const char *tname;
1344   const char *addr;
1345   size_t addrlen;
1346   size_t slen;
1347   size_t size;
1348   struct GNUNET_HELLO_Message *hello;
1349   struct GNUNET_HELLO_Address address;
1350   int sig_res;
1351   int do_verify;
1352
1353   if (ntohs (hdr->size) < sizeof (struct TransportPongMessage))
1354   {
1355     GNUNET_break_op (0);
1356     return GNUNET_SYSERR;
1357   }
1358   GNUNET_STATISTICS_update (GST_stats,
1359                             gettext_noop ("# PONG messages received"), 1,
1360                             GNUNET_NO);
1361
1362   /* message with structure:
1363    * [TransportPongMessage][Transport name][Address] */
1364
1365   pong = (const struct TransportPongMessage *) hdr;
1366   tname = (const char *) &pong[1];
1367   size = ntohs (hdr->size) - sizeof (struct TransportPongMessage);
1368   addr = memchr (tname, '\0', size);
1369   if (NULL == addr)
1370   {
1371     GNUNET_break_op (0);
1372     return GNUNET_SYSERR;
1373   }
1374   addr++;
1375   slen = strlen (tname) + 1;
1376   addrlen = size - slen;
1377   address.peer = *sender;
1378   address.address = addr;
1379   address.address_length = addrlen;
1380   address.transport_name = tname;
1381   address.local_info = GNUNET_HELLO_ADDRESS_INFO_NONE;
1382   ve = find_validation_entry (NULL, &address);
1383   if ((NULL == ve) || (GNUNET_NO == ve->expecting_pong))
1384   {
1385     GNUNET_STATISTICS_update (GST_stats,
1386                               gettext_noop
1387                               ("# PONGs dropped, no matching pending validation"),
1388                               1, GNUNET_NO);
1389     return GNUNET_OK;
1390   }
1391   /* now check that PONG is well-formed */
1392   if (0 != memcmp (&ve->pid, sender, sizeof (struct GNUNET_PeerIdentity)))
1393   {
1394     GNUNET_break_op (0);
1395     return GNUNET_SYSERR;
1396   }
1397   if (GNUNET_TIME_absolute_get_remaining
1398       (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value_us == 0)
1399   {
1400     GNUNET_STATISTICS_update (GST_stats,
1401                               gettext_noop
1402                               ("# PONGs dropped, signature expired"), 1,
1403                               GNUNET_NO);
1404     return GNUNET_SYSERR;
1405   }
1406
1407   sig_res = GNUNET_SYSERR;
1408   do_verify = GNUNET_YES;
1409   if (0 != GNUNET_TIME_absolute_get_remaining (ve->pong_sig_valid_until).rel_value_us)
1410   {
1411     /* We have a cached and valid signature for this peer,
1412      * try to compare instead of verify */
1413     if (0 == memcmp (&ve->pong_sig_cache, &pong->signature, sizeof (struct GNUNET_CRYPTO_EddsaSignature)))
1414     {
1415       /* signatures are identical, we can skip verification */
1416       sig_res = GNUNET_OK;
1417       do_verify = GNUNET_NO;
1418     }
1419     else
1420     {
1421       sig_res = GNUNET_SYSERR;
1422       /* signatures do not match, we have to verify */
1423     }
1424   }
1425
1426   if (GNUNET_YES == do_verify)
1427   {
1428     /* Do expensive verification */
1429     sig_res = GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
1430                                           &pong->purpose, &pong->signature,
1431                                           &ve->public_key);
1432     if (sig_res == GNUNET_SYSERR)
1433     {
1434       GNUNET_break_op (0);
1435       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1436                   "Failed to verify: invalid signature on address `%s':%s from peer `%s'\n",
1437                   tname,
1438                   GST_plugins_a2s (ve->address),
1439                   GNUNET_i2s (sender));
1440     }
1441   }
1442   if (sig_res == GNUNET_SYSERR)
1443   {
1444     GNUNET_break_op (0);
1445     return GNUNET_SYSERR;
1446   }
1447
1448   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1449               "Validation process successful for peer `%s' with plugin `%s' address `%s'\n",
1450               GNUNET_i2s (sender),
1451               tname,
1452               GST_plugins_a2s (ve->address));
1453   /* validity achieved, remember it! */
1454   ve->expecting_pong = GNUNET_NO;
1455   ve->valid_until = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1456   ve->pong_sig_cache = pong->signature;
1457         ve->pong_sig_valid_until = GNUNET_TIME_absolute_ntoh (pong->expiration);
1458   ve->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1459   {
1460     struct GNUNET_ATS_Information ats[2];
1461
1462     ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1463     ats[0].value = htonl ((uint32_t) ve->latency.rel_value_us);
1464     ats[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1465     ats[1].value = htonl ((uint32_t) ve->network);
1466     GNUNET_ATS_address_add (GST_ats, ve->address, NULL, ats, 2);
1467   }
1468   if (validations_running > 0)
1469   {
1470     validations_running --;
1471     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1472                 "Validation finished, %u validation processes running\n",
1473                 validations_running);
1474   }
1475   else
1476   {
1477     GNUNET_break (0);
1478   }
1479
1480   /* Notify about new validity */
1481   validation_entry_changed (ve, GNUNET_TRANSPORT_VS_UPDATE);
1482
1483   /* build HELLO to store in PEERINFO */
1484   ve->copied = GNUNET_NO;
1485   hello = GNUNET_HELLO_create (&ve->public_key,
1486                                &add_valid_peer_address, ve,
1487                                GNUNET_NO);
1488   GNUNET_PEERINFO_add_peer (GST_peerinfo, hello, NULL, NULL);
1489   GNUNET_free (hello);
1490   return GNUNET_OK;
1491 }
1492
1493
1494 /**
1495  * We've received a HELLO, check which addresses are new and trigger
1496  * validation.
1497  *
1498  * @param hello the HELLO we received
1499  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
1500  */
1501 int
1502 GST_validation_handle_hello (const struct GNUNET_MessageHeader *hello)
1503 {
1504   const struct GNUNET_HELLO_Message *hm =
1505       (const struct GNUNET_HELLO_Message *) hello;
1506   struct ValidateAddressContext vac;
1507   struct GNUNET_HELLO_Message *h;
1508   int friend;
1509
1510   friend = GNUNET_HELLO_is_friend_only (hm);
1511   if ( ( (GNUNET_YES != friend) &&
1512          (GNUNET_NO != friend) ) ||
1513        (GNUNET_OK != GNUNET_HELLO_get_id (hm, &vac.pid)) ||
1514        (GNUNET_OK != GNUNET_HELLO_get_key (hm, &vac.public_key)))
1515   {
1516     /* malformed HELLO */
1517     GNUNET_break_op (0);
1518     return GNUNET_SYSERR;
1519   }
1520   if (0 ==
1521       memcmp (&GST_my_identity, &vac.pid, sizeof (struct GNUNET_PeerIdentity)))
1522     return GNUNET_OK;
1523   /* Add peer identity without addresses to peerinfo service */
1524   h = GNUNET_HELLO_create (&vac.public_key, NULL, NULL, friend);
1525   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1526               _("Validation received new %s message for peer `%s' with size %u\n"),
1527               "HELLO",
1528               GNUNET_i2s (&vac.pid),
1529               ntohs (hello->size));
1530   GNUNET_PEERINFO_add_peer (GST_peerinfo, h, NULL, NULL);
1531
1532   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1533               _("Adding `%s' without addresses for peer `%s'\n"), "HELLO",
1534               GNUNET_i2s (&vac.pid));
1535
1536   GNUNET_free (h);
1537   GNUNET_assert (NULL ==
1538                  GNUNET_HELLO_iterate_addresses (hm, GNUNET_NO,
1539                                                  &validate_address_iterator,
1540                                                  &vac));
1541   return GNUNET_OK;
1542 }
1543
1544
1545 /**
1546  * Closure for #iterate_addresses().
1547  */
1548 struct IteratorContext
1549 {
1550   /**
1551    * Function to call on each address.
1552    */
1553   GST_ValidationAddressCallback cb;
1554
1555   /**
1556    * Closure for @e cb.
1557    */
1558   void *cb_cls;
1559
1560 };
1561
1562
1563 /**
1564  * Call the callback in the closure for each validation entry.
1565  *
1566  * @param cls the `struct IteratorContext`
1567  * @param key the peer's identity
1568  * @param value the `struct ValidationEntry`
1569  * @return #GNUNET_OK (continue to iterate)
1570  */
1571 static int
1572 iterate_addresses (void *cls,
1573                    const struct GNUNET_PeerIdentity *key,
1574                    void *value)
1575 {
1576   struct IteratorContext *ic = cls;
1577   struct ValidationEntry *ve = value;
1578
1579   ic->cb (ic->cb_cls, &ve->public_key, ve->valid_until, ve->revalidation_block,
1580           ve->address);
1581   return GNUNET_OK;
1582 }
1583
1584
1585 /**
1586  * Call the given function for each address for the given target.
1587  * Can either give a snapshot (synchronous API) or be continuous.
1588  *
1589  * @param target peer information is requested for
1590  * @param cb function to call; will not be called after this function returns
1591  * @param cb_cls closure for @a cb
1592  */
1593 void
1594 GST_validation_get_addresses (const struct GNUNET_PeerIdentity *target,
1595                               GST_ValidationAddressCallback cb, void *cb_cls)
1596 {
1597   struct IteratorContext ic;
1598
1599   ic.cb = cb;
1600   ic.cb_cls = cb_cls;
1601   GNUNET_CONTAINER_multipeermap_get_multiple (validation_map,
1602                                               target,
1603                                               &iterate_addresses, &ic);
1604 }
1605
1606
1607 /**
1608  * Update if we are using an address for a connection actively right now.
1609  * Based on this, the validation module will measure latency for the
1610  * address more or less often.
1611  *
1612  * @param address the address
1613  * @param session the session
1614  * @param in_use #GNUNET_YES if we are now using the address for a connection,
1615  *               #GNUNET_NO if we are no longer using the address for a connection
1616  */
1617 void
1618 GST_validation_set_address_use (const struct GNUNET_HELLO_Address *address,
1619                                 struct Session *session,
1620                                 int in_use)
1621 {
1622   struct ValidationEntry *ve;
1623
1624   if (NULL != address)
1625     ve = find_validation_entry (NULL, address);
1626   else
1627     ve = NULL;                  /* FIXME: lookup based on session... */
1628   if (NULL == ve)
1629   {
1630     /* this can happen for inbound connections (sender_address_len == 0); */
1631     return;
1632   }
1633   if (ve->in_use == in_use)
1634   {
1635
1636     if (GNUNET_YES == in_use)
1637     {
1638       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1639                   "Error setting address in use for peer `%s' `%s' to USED\n",
1640                   GNUNET_i2s (&address->peer), GST_plugins_a2s (address));
1641     }
1642     if (GNUNET_NO == in_use)
1643     {
1644       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1645                   "Error setting address in use for peer `%s' `%s' to NOT_USED\n",
1646                   GNUNET_i2s (&address->peer), GST_plugins_a2s (address));
1647     }
1648   }
1649
1650   GNUNET_break (ve->in_use != in_use);  /* should be different... */
1651   ve->in_use = in_use;
1652   if (in_use == GNUNET_YES)
1653   {
1654     /* from now on, higher frequeny, so reschedule now */
1655     GNUNET_SCHEDULER_cancel (ve->revalidation_task);
1656     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
1657   }
1658 }
1659
1660
1661 /**
1662  * Query validation about the latest observed latency on a given
1663  * address.
1664  *
1665  * @param sender peer
1666  * @param address the address
1667  * @param session session
1668  * @return observed latency of the address, FOREVER if the address was
1669  *         never successfully validated
1670  */
1671 struct GNUNET_TIME_Relative
1672 GST_validation_get_address_latency (const struct GNUNET_PeerIdentity *sender,
1673                                     const struct GNUNET_HELLO_Address *address,
1674                                     struct Session *session)
1675 {
1676   struct ValidationEntry *ve;
1677
1678   if (NULL == address)
1679   {
1680     GNUNET_break (0);           // FIXME: support having latency only with session...
1681     return GNUNET_TIME_UNIT_FOREVER_REL;
1682   }
1683   ve = find_validation_entry (NULL, address);
1684   if (NULL == ve)
1685     return GNUNET_TIME_UNIT_FOREVER_REL;
1686   return ve->latency;
1687 }
1688
1689 /**
1690  * Closure for the validation_entries_iterate function.
1691  */
1692 struct ValidationIteratorContext
1693 {
1694   /**
1695    * Function to call on each validation entry
1696    */
1697   GST_ValidationChangedCallback cb;
1698
1699   /**
1700    * Closure for @e cb.
1701    */
1702   void *cb_cls;
1703 };
1704
1705
1706 static int
1707 validation_entries_iterate (void *cls,
1708                            const struct GNUNET_PeerIdentity *key,
1709                            void *value)
1710 {
1711   struct ValidationIteratorContext *ic = cls;
1712   struct ValidationEntry *ve = value;
1713
1714   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Notifying about validation entry for peer `%s' address `%s' \n",
1715       GNUNET_i2s (&ve->pid), GST_plugins_a2s (ve->address));
1716   ic->cb (ic->cb_cls, &ve->pid, ve->address, ve->send_time,
1717       ve->valid_until, ve->next_validation, ve->state);
1718
1719   return GNUNET_OK;
1720 }
1721
1722 /**
1723  * Iterate over all iteration entries
1724  *
1725  * @param cb function to call
1726  * @param cb_cls closure for cb
1727  */
1728 void
1729 GST_validation_iterate (GST_ValidationChangedCallback cb,
1730                         void *cb_cls)
1731 {
1732   struct ValidationIteratorContext ic;
1733
1734   if (NULL == validation_map)
1735     return; /* can happen during shutdown */
1736   ic.cb = cb;
1737   ic.cb_cls = cb_cls;
1738   GNUNET_CONTAINER_multipeermap_iterate (validation_map,
1739                                          &validation_entries_iterate,
1740                                          &ic);
1741 }
1742
1743 /* end of file gnunet-service-transport_validation.c */