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