6621ecc6759152a3a9c90ee02ef3f76d805f6fd1
[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_ERROR,
601               "Could not obtain a valid network for `%s' `%s'\n",
602               GNUNET_i2s (pid), GST_plugins_a2s (ve->address));
603           GNUNET_break(0);
604         }
605         GST_neighbours_notify_data_sent (pid, ve->address, session, tsize);
606       }
607       else
608       {
609         /* Could not get a valid session */
610         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Could not get a valid session for `%s' `%s'\n",
611                     GNUNET_i2s (pid), GST_plugins_a2s (ve->address));
612         ret = -1;
613       }
614     }
615   }
616   if (-1 != ret)
617   {
618     ve->send_time = GNUNET_TIME_absolute_get ();
619     GNUNET_STATISTICS_update (GST_stats,
620                               gettext_noop
621                               ("# PING without HELLO messages sent"), 1,
622                               GNUNET_NO);
623
624     ve->network = network;
625     ve->expecting_pong = GNUNET_YES;
626     validations_running ++;
627           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
628                       "Validation started, %u validation processes running\n",
629                       validations_running);
630     /*  Notify about PING sent */
631     validation_entry_changed (ve, GNUNET_TRANSPORT_VS_UPDATE);
632   }
633 }
634
635
636 /**
637  * Do address validation again to keep address valid.
638  *
639  * @param cls the 'struct ValidationEntry'
640  * @param tc scheduler context (unused)
641  */
642 static void
643 revalidate_address (void *cls,
644                     const struct GNUNET_SCHEDULER_TaskContext *tc)
645 {
646   struct ValidationEntry *ve = cls;
647   struct GNUNET_TIME_Relative canonical_delay;
648   struct GNUNET_TIME_Relative delay;
649   struct GNUNET_TIME_Relative blocked_for;
650   struct GST_BlacklistCheck *bc;
651   uint32_t rdelay;
652
653   ve->revalidation_task = GNUNET_SCHEDULER_NO_TASK;
654   delay = GNUNET_TIME_absolute_get_remaining (ve->revalidation_block);
655   /* How long until we can possibly permit the next PING? */
656   canonical_delay =
657       (ve->in_use ==
658        GNUNET_YES) ? CONNECTED_PING_FREQUENCY
659       : ((GNUNET_TIME_absolute_get_remaining (ve->valid_until).rel_value_us >
660           0) ? VALIDATED_PING_FREQUENCY : UNVALIDATED_PING_KEEPALIVE);
661   if (delay.rel_value_us > canonical_delay.rel_value_us * 2)
662   {
663     /* situation changed, recalculate delay */
664     delay = canonical_delay;
665     ve->revalidation_block = GNUNET_TIME_relative_to_absolute (delay);
666   }
667   if (delay.rel_value_us > 0)
668   {
669     /* should wait a bit longer */
670     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
671                 "Waiting for %s longer before validating address `%s'\n",
672                 GNUNET_STRINGS_relative_time_to_string (delay,
673                                                         GNUNET_YES),
674                 GST_plugins_a2s (ve->address));
675     ve->revalidation_task =
676         GNUNET_SCHEDULER_add_delayed (delay, &revalidate_address, ve);
677     ve->next_validation =  GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), delay);
678     return;
679   }
680   blocked_for = GNUNET_TIME_absolute_get_remaining(validation_next);
681   if ((validations_running > validations_fast_start_threshold) &&
682                 (blocked_for.rel_value_us > 0))
683   {
684     /* Validations are blocked, have to wait for blocked_for time */
685     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
686                 "Validations blocked for another %s, delaying validating address `%s'\n",
687                 GNUNET_STRINGS_relative_time_to_string (blocked_for,
688                                                         GNUNET_YES),
689                 GST_plugins_a2s (ve->address));
690     ve->revalidation_task =
691       GNUNET_SCHEDULER_add_delayed (blocked_for, &revalidate_address, ve);
692     ve->next_validation =  GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), blocked_for);
693     return;
694   }
695   ve->revalidation_block = GNUNET_TIME_relative_to_absolute (canonical_delay);
696
697   /* schedule next PINGing with some extra random delay to avoid synchronous re-validations */
698   rdelay =
699       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
700                                 canonical_delay.rel_value_us);
701
702   /* Debug code for mantis 0002726 */
703   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us ==
704       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MICROSECONDS, rdelay).rel_value_us)
705   {
706     GNUNET_break (0);
707     delay = canonical_delay;
708   }
709   else
710   {
711     delay = GNUNET_TIME_relative_add (canonical_delay,
712                                       GNUNET_TIME_relative_multiply
713                                       (GNUNET_TIME_UNIT_MICROSECONDS, rdelay));
714   }
715   /* End debug code for mantis 0002726*/
716   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
717               "Validating now, next scheduled for %s, now validating address `%s'\n",
718               GNUNET_STRINGS_relative_time_to_string (blocked_for,
719                                                       GNUNET_YES),
720               GST_plugins_a2s (ve->address));
721   ve->revalidation_task =
722       GNUNET_SCHEDULER_add_delayed (delay, &revalidate_address, ve);
723   ve->next_validation =  GNUNET_TIME_absolute_add(GNUNET_TIME_absolute_get(), delay);
724
725   /* start PINGing by checking blacklist */
726   GNUNET_STATISTICS_update (GST_stats,
727                             gettext_noop ("# address revalidations started"), 1,
728                             GNUNET_NO);
729   bc = GST_blacklist_test_allowed (&ve->pid, ve->address->transport_name,
730                                    &transmit_ping_if_allowed, ve);
731   if (NULL != bc)
732     ve->bc = bc;                /* only set 'bc' if 'transmit_ping_if_allowed' was not already
733                                  * called... */
734 }
735
736
737 /**
738  * Find a ValidationEntry entry for the given neighbour that matches
739  * the given address and transport.  If none exists, create one (but
740  * without starting any validation).
741  *
742  * @param public_key public key of the peer, NULL for unknown
743  * @param address address to find
744  * @return validation entry matching the given specifications, NULL
745  *         if we don't have an existing entry and no public key was given
746  */
747 static struct ValidationEntry *
748 find_validation_entry (const struct GNUNET_CRYPTO_EddsaPublicKey *public_key,
749                        const struct GNUNET_HELLO_Address *address)
750 {
751   struct ValidationEntryMatchContext vemc;
752   struct ValidationEntry *ve;
753
754   vemc.ve = NULL;
755   vemc.address = address;
756   GNUNET_CONTAINER_multipeermap_get_multiple (validation_map,
757                                               &address->peer,
758                                               &validation_entry_match, &vemc);
759   if (NULL != (ve = vemc.ve))
760     return ve;
761   if (public_key == NULL)
762     return NULL;
763   ve = GNUNET_new (struct ValidationEntry);
764   ve->in_use = GNUNET_SYSERR; /* not defined */
765   ve->address = GNUNET_HELLO_address_copy (address);
766   ve->public_key = *public_key;
767   ve->pid = address->peer;
768   ve->pong_sig_valid_until = GNUNET_TIME_absolute_get_zero_();
769   memset (&ve->pong_sig_cache, '\0', sizeof (struct GNUNET_CRYPTO_EddsaSignature));
770   ve->latency = GNUNET_TIME_UNIT_FOREVER_REL;
771   ve->challenge =
772       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
773   ve->timeout_task =
774       GNUNET_SCHEDULER_add_delayed (UNVALIDATED_PING_KEEPALIVE,
775                                     &timeout_hello_validation, ve);
776   GNUNET_CONTAINER_multipeermap_put (validation_map, &address->peer,
777                                      ve,
778                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
779   validation_entry_changed (ve, GNUNET_TRANSPORT_VS_NEW);
780   ve->expecting_pong = GNUNET_NO;
781   return ve;
782 }
783
784
785 /**
786  * Iterator which adds the given address to the set of validated
787  * addresses.
788  *
789  * @param cls original HELLO message
790  * @param address the address
791  * @param expiration expiration time
792  * @return #GNUNET_OK (keep the address)
793  */
794 static int
795 add_valid_address (void *cls,
796                    const struct GNUNET_HELLO_Address *address,
797                    struct GNUNET_TIME_Absolute expiration)
798 {
799   const struct GNUNET_HELLO_Message *hello = cls;
800   struct ValidationEntry *ve;
801   struct GNUNET_PeerIdentity pid;
802   struct GNUNET_ATS_Information ats;
803   struct GNUNET_CRYPTO_EddsaPublicKey public_key;
804
805   if (0 == GNUNET_TIME_absolute_get_remaining (expiration).rel_value_us)
806     return GNUNET_OK;           /* expired */
807   if ((GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid)) ||
808       (GNUNET_OK != GNUNET_HELLO_get_key (hello, &public_key)))
809   {
810     GNUNET_break (0);
811     return GNUNET_OK;           /* invalid HELLO !? */
812   }
813   if (0 == memcmp (&GST_my_identity,
814                    &pid,
815                    sizeof (struct GNUNET_PeerIdentity)))
816   {
817     /* Peerinfo returned own identity, skip validation */
818     return GNUNET_OK;
819   }
820
821   ve = find_validation_entry (&public_key, address);
822   ve->valid_until = GNUNET_TIME_absolute_max (ve->valid_until, expiration);
823
824   if (GNUNET_SCHEDULER_NO_TASK == ve->revalidation_task)
825   {
826     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
827                 "Starting revalidations for valid address `%s'\n",
828               GST_plugins_a2s (ve->address));
829     ve->next_validation = GNUNET_TIME_absolute_get();
830     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
831   }
832   validation_entry_changed (ve, GNUNET_TRANSPORT_VS_UPDATE);
833
834   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
835   ats.value = htonl (ve->network);
836   GNUNET_ATS_address_add (GST_ats, address, NULL, &ats, 1);
837
838   return GNUNET_OK;
839 }
840
841
842 /**
843  * Function called for any HELLO known to PEERINFO.
844  *
845  * @param cls unused
846  * @param peer id of the peer, NULL for last call
847  * @param hello hello message for the peer (can be NULL)
848  * @param err_msg error message
849  */
850 static void
851 process_peerinfo_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
852                         const struct GNUNET_HELLO_Message *hello,
853                         const char *err_msg)
854 {
855   GNUNET_assert (NULL != peer);
856   if (NULL == hello)
857     return;
858   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
859               "Handling HELLO for peer `%s'\n",
860               GNUNET_i2s (peer));
861   GNUNET_assert (NULL ==
862                  GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO,
863                                                  &add_valid_address,
864                                                  (void *) hello));
865 }
866
867
868 /**
869  * Start the validation subsystem.
870  *
871  * @param max_fds maximum number of fds to use
872  */
873 void
874 GST_validation_start (unsigned int max_fds)
875 {
876   /**
877    * Initialization for validation throttling
878    *
879    * We have a maximum number max_fds of connections we can use for validation
880    * We monitor the number of validations in parallel and start to throttle it
881    * when doing to many validations in parallel:
882    * if (running validations < (max_fds / 2))
883    * - "fast start": run validation immediately
884    * - have delay of (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us) / (max_fds / 2)
885    *   (300 sec / ~150 == ~2 sec.) between two validations
886    */
887
888   validation_next = GNUNET_TIME_absolute_get();
889   validation_delay.rel_value_us = (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value_us) / (max_fds / 2);
890   validations_fast_start_threshold = (max_fds / 2);
891   validations_running = 0;
892   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
893               "Validation uses a fast start threshold of %u connections and a delay between of %s\n ",
894               validations_fast_start_threshold,
895               GNUNET_STRINGS_relative_time_to_string (validation_delay,
896                                                       GNUNET_YES));
897   validation_map = GNUNET_CONTAINER_multipeermap_create (VALIDATION_MAP_SIZE,
898                                                          GNUNET_NO);
899   pnc = GNUNET_PEERINFO_notify (GST_cfg, GNUNET_YES,
900                                 &process_peerinfo_hello, NULL);
901 }
902
903
904 /**
905  * Stop the validation subsystem.
906  */
907 void
908 GST_validation_stop ()
909 {
910   struct CheckHelloValidatedContext *chvc;
911
912   GNUNET_CONTAINER_multipeermap_iterate (validation_map,
913                                          &cleanup_validation_entry, NULL);
914   GNUNET_CONTAINER_multipeermap_destroy (validation_map);
915   validation_map = NULL;
916   while (NULL != (chvc = chvc_head))
917   {
918     GNUNET_CONTAINER_DLL_remove (chvc_head, chvc_tail, chvc);
919     GNUNET_free (chvc);
920   }
921   GNUNET_PEERINFO_notify_cancel (pnc);
922 }
923
924
925 /**
926  * Send the given PONG to the given address.
927  *
928  * @param cls the PONG message
929  * @param public_key public key for the peer, never NULL
930  * @param valid_until is ZERO if we never validated the address,
931  *                    otherwise a time up to when we consider it (or was) valid
932  * @param validation_block  is FOREVER if the address is for an unsupported plugin (from PEERINFO)
933  *                          is ZERO if the address is considered valid (no validation needed)
934  *                          otherwise a time in the future if we're currently denying re-validation
935  * @param address target address
936  */
937 static void
938 multicast_pong (void *cls,
939                 const struct GNUNET_CRYPTO_EddsaPublicKey *public_key,
940                 struct GNUNET_TIME_Absolute valid_until,
941                 struct GNUNET_TIME_Absolute validation_block,
942                 const struct GNUNET_HELLO_Address *address)
943 {
944   struct TransportPongMessage *pong = cls;
945   struct GNUNET_TRANSPORT_PluginFunctions *papi;
946
947   papi = GST_plugins_find (address->transport_name);
948   if (papi == NULL)
949     return;
950
951   GNUNET_assert (papi->send != NULL);
952   GNUNET_assert (papi->get_session != NULL);
953
954   struct Session * session = papi->get_session(papi->cls, address);
955   if (session == NULL)
956   {
957      GNUNET_break (0);
958      return;
959   }
960
961   papi->send (papi->cls, session,
962               (const char *) pong, ntohs (pong->header.size),
963               PONG_PRIORITY, ACCEPTABLE_PING_DELAY,
964               NULL, NULL);
965   GST_neighbours_notify_data_sent (&address->peer,
966       address, session, pong->header.size);
967
968 }
969
970
971 /**
972  * We've received a PING.  If appropriate, generate a PONG.
973  *
974  * @param sender peer sending the PING
975  * @param hdr the PING
976  * @param sender_address the sender address as we got it
977  * @param session session we got the PING from
978  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
979  */
980 int
981 GST_validation_handle_ping (const struct GNUNET_PeerIdentity *sender,
982                             const struct GNUNET_MessageHeader *hdr,
983                             const struct GNUNET_HELLO_Address *sender_address,
984                             struct Session *session)
985 {
986   const struct TransportPingMessage *ping;
987   struct TransportPongMessage *pong;
988   struct GNUNET_TRANSPORT_PluginFunctions *papi;
989   struct GNUNET_CRYPTO_EddsaSignature *sig_cache;
990   struct GNUNET_TIME_Absolute *sig_cache_exp;
991   const char *addr;
992   const char *addrend;
993   char *plugin_name;
994   char *pos;
995   size_t alen;
996   size_t slen;
997   ssize_t ret;
998   int buggy = GNUNET_NO;
999   struct GNUNET_HELLO_Address address;
1000
1001   if (ntohs (hdr->size) < sizeof (struct TransportPingMessage))
1002   {
1003     GNUNET_break_op (0);
1004     return GNUNET_SYSERR;
1005   }
1006   ping = (const struct TransportPingMessage *) hdr;
1007   if (0 !=
1008       memcmp (&ping->target, &GST_my_identity,
1009               sizeof (struct GNUNET_PeerIdentity)))
1010   {
1011     GNUNET_STATISTICS_update (GST_stats,
1012                               gettext_noop
1013                               ("# PING message for different peer received"), 1,
1014                               GNUNET_NO);
1015     return GNUNET_SYSERR;
1016   }
1017   GNUNET_STATISTICS_update (GST_stats,
1018                             gettext_noop ("# PING messages received"), 1,
1019                             GNUNET_NO);
1020   addr = (const char *) &ping[1];
1021   alen = ntohs (hdr->size) - sizeof (struct TransportPingMessage);
1022   /* peer wants to confirm that this is one of our addresses, this is what is
1023    * used for address validation */
1024
1025   sig_cache = NULL;
1026   sig_cache_exp = NULL;
1027   papi = NULL;
1028   if (alen > 0)
1029   {
1030     addrend = memchr (addr, '\0', alen);
1031     if (NULL == addrend)
1032     {
1033       GNUNET_break_op (0);
1034       return GNUNET_SYSERR;
1035     }
1036     addrend++;
1037     slen = strlen (addr) + 1;
1038     alen -= slen;
1039     address.local_info = GNUNET_HELLO_ADDRESS_INFO_NONE;
1040     address.address = addrend;
1041     address.address_length = alen;
1042     address.transport_name = addr;
1043     address.peer = GST_my_identity;
1044
1045     if (NULL == address.transport_name)
1046     {
1047       GNUNET_break (0);
1048     }
1049
1050     if (0 != strstr (address.transport_name, "_client"))
1051     {
1052       plugin_name = GNUNET_strdup (address.transport_name);
1053       pos = strstr (plugin_name, "_client");
1054       GNUNET_assert (NULL != pos);
1055       GNUNET_snprintf (pos, strlen ("_server") + 1, "%s", "_server");
1056     }
1057     else
1058       plugin_name = GNUNET_strdup (address.transport_name);
1059
1060     if (NULL == (papi = GST_plugins_find (plugin_name)))
1061     {
1062       /* we don't have the plugin for this address */
1063       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1064                   _("Plugin `%s' not available, cannot confirm having this address\n"),
1065                   plugin_name);
1066       GNUNET_free (plugin_name);
1067       return GNUNET_SYSERR;
1068     }
1069     GNUNET_free (plugin_name);
1070     if (GNUNET_OK != papi->check_address (papi->cls, addrend, alen))
1071     {
1072       GNUNET_STATISTICS_update (GST_stats,
1073                                 gettext_noop
1074                                 ("# failed address checks during validation"), 1,
1075                                 GNUNET_NO);
1076       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1077                   _("Address `%s' is not one of my addresses, not confirming PING\n"),
1078                   GST_plugins_a2s (&address));
1079       return GNUNET_SYSERR;
1080     }
1081     else
1082     {
1083       GNUNET_STATISTICS_update (GST_stats,
1084                                 gettext_noop
1085                                 ("# successful address checks during validation"), 1,
1086                                 GNUNET_NO);
1087       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1088                   "Address `%s' is one of my addresses, confirming PING\n",
1089                   GST_plugins_a2s (&address));
1090     }
1091
1092     if (GNUNET_YES != GST_hello_test_address (&address, &sig_cache, &sig_cache_exp))
1093     {
1094       if (GNUNET_NO == buggy)
1095       {
1096         GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1097                     _("Not confirming PING from peer `%s' with address `%s' since I cannot confirm having this address.\n"),
1098                     GNUNET_i2s (sender),
1099                     GST_plugins_a2s (&address));
1100         return GNUNET_SYSERR;
1101       }
1102       else
1103       {
1104         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1105                     _("Received a PING message with validation bug from `%s'\n"),
1106                     GNUNET_i2s (sender));
1107       }
1108     }
1109   }
1110   else
1111   {
1112     addrend = NULL;             /* make gcc happy */
1113     slen = 0;
1114     static struct GNUNET_CRYPTO_EddsaSignature no_address_signature;
1115     static struct GNUNET_TIME_Absolute no_address_signature_expiration;
1116
1117     sig_cache = &no_address_signature;
1118     sig_cache_exp = &no_address_signature_expiration;
1119   }
1120
1121   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1122               "I am `%s', sending PONG to peer `%s'\n",
1123               GNUNET_i2s_full (&GST_my_identity),
1124               GNUNET_i2s (sender));
1125
1126   /* message with structure:
1127    * [TransportPongMessage][Transport name][Address] */
1128
1129   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
1130   pong->header.size =
1131       htons (sizeof (struct TransportPongMessage) + alen + slen);
1132   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
1133   pong->purpose.size =
1134       htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
1135              sizeof (uint32_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1136              alen + slen);
1137   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
1138   memcpy (&pong->challenge, &ping->challenge, sizeof (ping->challenge));
1139   pong->addrlen = htonl (alen + slen);
1140   memcpy (&pong[1], addr, slen);   /* Copy transport plugin */
1141   if (alen > 0)
1142   {
1143     GNUNET_assert (NULL != addrend);
1144     memcpy (&((char *) &pong[1])[slen], addrend, alen);
1145   }
1146   if (GNUNET_TIME_absolute_get_remaining (*sig_cache_exp).rel_value_us <
1147       PONG_SIGNATURE_LIFETIME.rel_value_us / 4)
1148   {
1149     /* create / update cached sig */
1150     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1151                 "Creating PONG signature to indicate ownership.\n");
1152     *sig_cache_exp = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
1153     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
1154     if (GNUNET_OK !=
1155                    GNUNET_CRYPTO_eddsa_sign (GST_my_private_key, &pong->purpose,
1156                                            sig_cache))
1157     {
1158         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1159                 _("Failed to create PONG signature for peer `%s'\n"), GNUNET_i2s (sender));
1160     }
1161   }
1162   else
1163   {
1164     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
1165   }
1166   pong->signature = *sig_cache;
1167
1168   GNUNET_assert (sender_address != NULL);
1169
1170   /* first see if the session we got this PING from can be used to transmit
1171    * a response reliably */
1172   if (papi == NULL)
1173     ret = -1;
1174   else
1175   {
1176     GNUNET_assert (papi->send != NULL);
1177     GNUNET_assert (papi->get_session != NULL);
1178
1179     if (session == NULL)
1180     {
1181       session = papi->get_session (papi->cls, sender_address);
1182     }
1183     if (session == NULL)
1184     {
1185       GNUNET_break (0);
1186       ret = -1;
1187     }
1188     else
1189     {
1190       ret = papi->send (papi->cls, session,
1191                         (const char *) pong, ntohs (pong->header.size),
1192                         PONG_PRIORITY, ACCEPTABLE_PING_DELAY,
1193                         NULL, NULL);
1194       if (-1 != ret)
1195         GST_neighbours_notify_data_sent (sender,
1196                                          sender_address, session,
1197                                          pong->header.size);
1198     }
1199   }
1200   if (ret != -1)
1201   {
1202     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1203                 "Transmitted PONG to `%s' via reliable mechanism\n",
1204                 GNUNET_i2s (sender));
1205     /* done! */
1206     GNUNET_STATISTICS_update (GST_stats,
1207                               gettext_noop
1208                               ("# PONGs unicast via reliable transport"), 1,
1209                               GNUNET_NO);
1210     GNUNET_free (pong);
1211     return GNUNET_OK;
1212   }
1213
1214   /* no reliable method found, try transmission via all known addresses */
1215   GNUNET_STATISTICS_update (GST_stats,
1216                             gettext_noop
1217                             ("# PONGs multicast to all available addresses"), 1,
1218                             GNUNET_NO);
1219   GST_validation_get_addresses (sender,
1220                                 &multicast_pong, pong);
1221   GNUNET_free (pong);
1222   return GNUNET_OK;
1223 }
1224
1225
1226 /**
1227  * Context for the #validate_address_iterator() function
1228  */
1229 struct ValidateAddressContext
1230 {
1231   /**
1232    * Hash of the public key of the peer whose address is being validated.
1233    */
1234   struct GNUNET_PeerIdentity pid;
1235
1236   /**
1237    * Public key of the peer whose address is being validated.
1238    */
1239   struct GNUNET_CRYPTO_EddsaPublicKey public_key;
1240
1241 };
1242
1243
1244 /**
1245  * Iterator callback to go over all addresses and try to validate them
1246  * (unless blocked or already validated).
1247  *
1248  * @param cls pointer to a `struct ValidateAddressContext *`
1249  * @param address the address
1250  * @param expiration expiration time
1251  * @return #GNUNET_OK (keep the address)
1252  */
1253 static int
1254 validate_address_iterator (void *cls,
1255                            const struct GNUNET_HELLO_Address *address,
1256                            struct GNUNET_TIME_Absolute expiration)
1257 {
1258   const struct ValidateAddressContext *vac = cls;
1259   struct ValidationEntry *ve;
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   if (GNUNET_SCHEDULER_NO_TASK == ve->revalidation_task)
1269   {
1270     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1271                 "Validation process started for fresh address `%s'\n",
1272                 GST_plugins_a2s (ve->address));
1273     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
1274   }
1275   return GNUNET_OK;
1276 }
1277
1278
1279 /**
1280  * Add the validated peer address to the HELLO.
1281  *
1282  * @param cls the `struct ValidationEntry *` with the validated address
1283  * @param max space in @a buf
1284  * @param buf where to add the address
1285  * @return number of bytes written, #GNUNET_SYSERR to signal the
1286  *         end of the iteration.
1287  */
1288 static ssize_t
1289 add_valid_peer_address (void *cls,
1290                         size_t max,
1291                         void *buf)
1292 {
1293   struct ValidationEntry *ve = cls;
1294
1295   if (GNUNET_YES == ve->copied)
1296     return GNUNET_SYSERR; /* Done */
1297   ve->copied = GNUNET_YES;
1298   return GNUNET_HELLO_add_address (ve->address, ve->valid_until, buf, max);
1299 }
1300
1301
1302 /**
1303  * We've received a PONG.  Check if it matches a pending PING and
1304  * mark the respective address as confirmed.
1305  *
1306  * @param sender peer sending the PONG
1307  * @param hdr the PONG
1308  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
1309  */
1310 int
1311 GST_validation_handle_pong (const struct GNUNET_PeerIdentity *sender,
1312                             const struct GNUNET_MessageHeader *hdr)
1313 {
1314   const struct TransportPongMessage *pong;
1315   struct ValidationEntry *ve;
1316   const char *tname;
1317   const char *addr;
1318   size_t addrlen;
1319   size_t slen;
1320   size_t size;
1321   struct GNUNET_HELLO_Message *hello;
1322   struct GNUNET_HELLO_Address address;
1323   int sig_res;
1324   int do_verify;
1325
1326   if (ntohs (hdr->size) < sizeof (struct TransportPongMessage))
1327   {
1328     GNUNET_break_op (0);
1329     return GNUNET_SYSERR;
1330   }
1331   GNUNET_STATISTICS_update (GST_stats,
1332                             gettext_noop ("# PONG messages received"), 1,
1333                             GNUNET_NO);
1334
1335   /* message with structure:
1336    * [TransportPongMessage][Transport name][Address] */
1337
1338   pong = (const struct TransportPongMessage *) hdr;
1339   tname = (const char *) &pong[1];
1340   size = ntohs (hdr->size) - sizeof (struct TransportPongMessage);
1341   addr = memchr (tname, '\0', size);
1342   if (NULL == addr)
1343   {
1344     GNUNET_break_op (0);
1345     return GNUNET_SYSERR;
1346   }
1347   addr++;
1348   slen = strlen (tname) + 1;
1349   addrlen = size - slen;
1350   address.peer = *sender;
1351   address.address = addr;
1352   address.address_length = addrlen;
1353   address.transport_name = tname;
1354   address.local_info = GNUNET_HELLO_ADDRESS_INFO_NONE;
1355   ve = find_validation_entry (NULL, &address);
1356   if ((NULL == ve) || (GNUNET_NO == ve->expecting_pong))
1357   {
1358     GNUNET_STATISTICS_update (GST_stats,
1359                               gettext_noop
1360                               ("# PONGs dropped, no matching pending validation"),
1361                               1, GNUNET_NO);
1362     return GNUNET_OK;
1363   }
1364   /* now check that PONG is well-formed */
1365   if (0 != memcmp (&ve->pid, sender, sizeof (struct GNUNET_PeerIdentity)))
1366   {
1367     GNUNET_break_op (0);
1368     return GNUNET_SYSERR;
1369   }
1370   if (GNUNET_TIME_absolute_get_remaining
1371       (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value_us == 0)
1372   {
1373     GNUNET_STATISTICS_update (GST_stats,
1374                               gettext_noop
1375                               ("# PONGs dropped, signature expired"), 1,
1376                               GNUNET_NO);
1377     return GNUNET_SYSERR;
1378   }
1379
1380   sig_res = GNUNET_SYSERR;
1381   do_verify = GNUNET_YES;
1382   if (0 != GNUNET_TIME_absolute_get_remaining (ve->pong_sig_valid_until).rel_value_us)
1383   {
1384     /* We have a cached and valid signature for this peer,
1385      * try to compare instead of verify */
1386     if (0 == memcmp (&ve->pong_sig_cache, &pong->signature, sizeof (struct GNUNET_CRYPTO_EddsaSignature)))
1387     {
1388       /* signatures are identical, we can skip verification */
1389       sig_res = GNUNET_OK;
1390       do_verify = GNUNET_NO;
1391     }
1392     else
1393     {
1394       sig_res = GNUNET_SYSERR;
1395       /* signatures do not match, we have to verify */
1396     }
1397   }
1398
1399   if (GNUNET_YES == do_verify)
1400   {
1401     /* Do expensive verification */
1402     sig_res = GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
1403                                           &pong->purpose, &pong->signature,
1404                                           &ve->public_key);
1405     if (sig_res == GNUNET_SYSERR)
1406     {
1407       GNUNET_break_op (0);
1408       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1409                   "Failed to verify: invalid signature on address `%s':%s from peer `%s'\n",
1410                   tname,
1411                   GST_plugins_a2s (ve->address),
1412                   GNUNET_i2s (sender));
1413     }
1414   }
1415   if (sig_res == GNUNET_SYSERR)
1416   {
1417     GNUNET_break_op (0);
1418     return GNUNET_SYSERR;
1419   }
1420
1421   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1422               "Validation process successful for peer `%s' with plugin `%s' address `%s'\n",
1423               GNUNET_i2s (sender),
1424               tname,
1425               GST_plugins_a2s (ve->address));
1426   /* validity achieved, remember it! */
1427   ve->expecting_pong = GNUNET_NO;
1428   ve->valid_until = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1429   ve->pong_sig_cache = pong->signature;
1430         ve->pong_sig_valid_until = GNUNET_TIME_absolute_ntoh (pong->expiration);
1431   ve->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1432   {
1433     struct GNUNET_ATS_Information ats[2];
1434
1435     ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1436     ats[0].value = htonl ((uint32_t) ve->latency.rel_value_us);
1437     ats[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1438     ats[1].value = htonl ((uint32_t) ve->network);
1439     GNUNET_ATS_address_add (GST_ats, ve->address, NULL, ats, 2);
1440   }
1441   if (validations_running > 0)
1442   {
1443     validations_running --;
1444     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1445                 "Validation finished, %u validation processes running\n",
1446                 validations_running);
1447   }
1448   else
1449   {
1450     GNUNET_break (0);
1451   }
1452
1453   /* Notify about new validity */
1454   validation_entry_changed (ve, GNUNET_TRANSPORT_VS_UPDATE);
1455
1456   /* build HELLO to store in PEERINFO */
1457   ve->copied = GNUNET_NO;
1458   hello = GNUNET_HELLO_create (&ve->public_key,
1459                                &add_valid_peer_address, ve,
1460                                GNUNET_NO);
1461   GNUNET_PEERINFO_add_peer (GST_peerinfo, hello, NULL, NULL);
1462   GNUNET_free (hello);
1463   return GNUNET_OK;
1464 }
1465
1466
1467 /**
1468  * We've received a HELLO, check which addresses are new and trigger
1469  * validation.
1470  *
1471  * @param hello the HELLO we received
1472  * @return #GNUNET_OK if the message was fine, #GNUNET_SYSERR on serious error
1473  */
1474 int
1475 GST_validation_handle_hello (const struct GNUNET_MessageHeader *hello)
1476 {
1477   const struct GNUNET_HELLO_Message *hm =
1478       (const struct GNUNET_HELLO_Message *) hello;
1479   struct ValidateAddressContext vac;
1480   struct GNUNET_HELLO_Message *h;
1481   int friend;
1482
1483   friend = GNUNET_HELLO_is_friend_only (hm);
1484   if ( ( (GNUNET_YES != friend) &&
1485          (GNUNET_NO != friend) ) ||
1486        (GNUNET_OK != GNUNET_HELLO_get_id (hm, &vac.pid)) ||
1487        (GNUNET_OK != GNUNET_HELLO_get_key (hm, &vac.public_key)))
1488   {
1489     /* malformed HELLO */
1490     GNUNET_break_op (0);
1491     return GNUNET_SYSERR;
1492   }
1493   if (0 ==
1494       memcmp (&GST_my_identity, &vac.pid, sizeof (struct GNUNET_PeerIdentity)))
1495     return GNUNET_OK;
1496   /* Add peer identity without addresses to peerinfo service */
1497   h = GNUNET_HELLO_create (&vac.public_key, NULL, NULL, friend);
1498   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1499               _("Validation received new %s message for peer `%s' with size %u\n"),
1500               "HELLO",
1501               GNUNET_i2s (&vac.pid),
1502               ntohs (hello->size));
1503   GNUNET_PEERINFO_add_peer (GST_peerinfo, h, NULL, NULL);
1504
1505   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1506               _("Adding `%s' without addresses for peer `%s'\n"), "HELLO",
1507               GNUNET_i2s (&vac.pid));
1508
1509   GNUNET_free (h);
1510   GNUNET_assert (NULL ==
1511                  GNUNET_HELLO_iterate_addresses (hm, GNUNET_NO,
1512                                                  &validate_address_iterator,
1513                                                  &vac));
1514   return GNUNET_OK;
1515 }
1516
1517
1518 /**
1519  * Closure for #iterate_addresses().
1520  */
1521 struct IteratorContext
1522 {
1523   /**
1524    * Function to call on each address.
1525    */
1526   GST_ValidationAddressCallback cb;
1527
1528   /**
1529    * Closure for @e cb.
1530    */
1531   void *cb_cls;
1532
1533 };
1534
1535
1536 /**
1537  * Call the callback in the closure for each validation entry.
1538  *
1539  * @param cls the `struct IteratorContext`
1540  * @param key the peer's identity
1541  * @param value the `struct ValidationEntry`
1542  * @return #GNUNET_OK (continue to iterate)
1543  */
1544 static int
1545 iterate_addresses (void *cls,
1546                    const struct GNUNET_PeerIdentity *key,
1547                    void *value)
1548 {
1549   struct IteratorContext *ic = cls;
1550   struct ValidationEntry *ve = value;
1551
1552   ic->cb (ic->cb_cls, &ve->public_key, ve->valid_until, ve->revalidation_block,
1553           ve->address);
1554   return GNUNET_OK;
1555 }
1556
1557
1558 /**
1559  * Call the given function for each address for the given target.
1560  * Can either give a snapshot (synchronous API) or be continuous.
1561  *
1562  * @param target peer information is requested for
1563  * @param cb function to call; will not be called after this function returns
1564  * @param cb_cls closure for @a cb
1565  */
1566 void
1567 GST_validation_get_addresses (const struct GNUNET_PeerIdentity *target,
1568                               GST_ValidationAddressCallback cb, void *cb_cls)
1569 {
1570   struct IteratorContext ic;
1571
1572   ic.cb = cb;
1573   ic.cb_cls = cb_cls;
1574   GNUNET_CONTAINER_multipeermap_get_multiple (validation_map,
1575                                               target,
1576                                               &iterate_addresses, &ic);
1577 }
1578
1579
1580 /**
1581  * Update if we are using an address for a connection actively right now.
1582  * Based on this, the validation module will measure latency for the
1583  * address more or less often.
1584  *
1585  * @param address the address
1586  * @param session the session
1587  * @param in_use #GNUNET_YES if we are now using the address for a connection,
1588  *               #GNUNET_NO if we are no longer using the address for a connection
1589  */
1590 void
1591 GST_validation_set_address_use (const struct GNUNET_HELLO_Address *address,
1592                                 struct Session *session,
1593                                 int in_use)
1594 {
1595   struct ValidationEntry *ve;
1596
1597   if (NULL != address)
1598     ve = find_validation_entry (NULL, address);
1599   else
1600     ve = NULL;                  /* FIXME: lookup based on session... */
1601   if (NULL == ve)
1602   {
1603     /* this can happen for inbound connections (sender_address_len == 0); */
1604     return;
1605   }
1606   if (ve->in_use == in_use)
1607   {
1608
1609     if (GNUNET_YES == in_use)
1610     {
1611       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1612                   "Error setting address in use for peer `%s' `%s' to USED\n",
1613                   GNUNET_i2s (&address->peer), GST_plugins_a2s (address));
1614     }
1615     if (GNUNET_NO == in_use)
1616     {
1617       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1618                   "Error setting address in use for peer `%s' `%s' to NOT_USED\n",
1619                   GNUNET_i2s (&address->peer), GST_plugins_a2s (address));
1620     }
1621   }
1622
1623   GNUNET_break (ve->in_use != in_use);  /* should be different... */
1624   ve->in_use = in_use;
1625   if (in_use == GNUNET_YES)
1626   {
1627     /* from now on, higher frequeny, so reschedule now */
1628     GNUNET_SCHEDULER_cancel (ve->revalidation_task);
1629     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
1630   }
1631 }
1632
1633
1634 /**
1635  * Query validation about the latest observed latency on a given
1636  * address.
1637  *
1638  * @param sender peer
1639  * @param address the address
1640  * @param session session
1641  * @return observed latency of the address, FOREVER if the address was
1642  *         never successfully validated
1643  */
1644 struct GNUNET_TIME_Relative
1645 GST_validation_get_address_latency (const struct GNUNET_PeerIdentity *sender,
1646                                     const struct GNUNET_HELLO_Address *address,
1647                                     struct Session *session)
1648 {
1649   struct ValidationEntry *ve;
1650
1651   if (NULL == address)
1652   {
1653     GNUNET_break (0);           // FIXME: support having latency only with session...
1654     return GNUNET_TIME_UNIT_FOREVER_REL;
1655   }
1656   ve = find_validation_entry (NULL, address);
1657   if (NULL == ve)
1658     return GNUNET_TIME_UNIT_FOREVER_REL;
1659   return ve->latency;
1660 }
1661
1662 /**
1663  * Closure for the validation_entries_iterate function.
1664  */
1665 struct ValidationIteratorContext
1666 {
1667   /**
1668    * Function to call on each validation entry
1669    */
1670   GST_ValidationChangedCallback cb;
1671
1672   /**
1673    * Closure for @e cb.
1674    */
1675   void *cb_cls;
1676 };
1677
1678
1679 static int
1680 validation_entries_iterate (void *cls,
1681                            const struct GNUNET_PeerIdentity *key,
1682                            void *value)
1683 {
1684   struct ValidationIteratorContext *ic = cls;
1685   struct ValidationEntry *ve = value;
1686
1687   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Notifying about validation entry for peer `%s' address `%s' \n",
1688       GNUNET_i2s (&ve->pid), GST_plugins_a2s (ve->address));
1689   ic->cb (ic->cb_cls, &ve->pid, ve->address, ve->send_time,
1690       ve->valid_until, ve->next_validation, ve->state);
1691
1692   return GNUNET_OK;
1693 }
1694
1695 /**
1696  * Iterate over all iteration entries
1697  *
1698  * @param cb function to call
1699  * @param cb_cls closure for cb
1700  */
1701 void
1702 GST_validation_iterate (GST_ValidationChangedCallback cb,
1703                         void *cb_cls)
1704 {
1705   struct ValidationIteratorContext ic;
1706
1707   if (NULL == validation_map)
1708     return; /* can happen during shutdown */
1709   ic.cb = cb;
1710   ic.cb_cls = cb_cls;
1711   GNUNET_CONTAINER_multipeermap_iterate (validation_map,
1712                                          &validation_entries_iterate,
1713                                          &ic);
1714 }
1715
1716 /* end of file gnunet-service-transport_validation.c */