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