remove output
[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_EccPublicKey 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   enum GNUNET_ATS_Network_Type network;
271 };
272
273
274 /**
275  * Context of currently active requests to peerinfo
276  * for validation of HELLOs.
277  */
278 struct CheckHelloValidatedContext
279 {
280
281   /**
282    * This is a doubly-linked list.
283    */
284   struct CheckHelloValidatedContext *next;
285
286   /**
287    * This is a doubly-linked list.
288    */
289   struct CheckHelloValidatedContext *prev;
290
291   /**
292    * Hello that we are validating.
293    */
294   const struct GNUNET_HELLO_Message *hello;
295
296 };
297
298
299 /**
300  * Head of linked list of HELLOs awaiting validation.
301  */
302 static struct CheckHelloValidatedContext *chvc_head;
303
304 /**
305  * Tail of linked list of HELLOs awaiting validation
306  */
307 static struct CheckHelloValidatedContext *chvc_tail;
308
309 /**
310  * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
311  * of the given peer that we are currently validating, have validated
312  * or are blocked from re-validation for a while).
313  */
314 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
315
316 /**
317  * Context for peerinfo iteration.
318  */
319 static struct GNUNET_PEERINFO_NotifyContext *pnc;
320
321
322 /**
323  * Minimum delay between to validations
324  */
325 static struct GNUNET_TIME_Relative validation_delay;
326
327 /**
328  * Number of validations running
329  */
330 static unsigned int validations_running;
331
332 /**
333  * Validition fast start threshold
334  */
335 static unsigned int validations_fast_start_threshold;
336
337 /**
338  * When is next validation allowed
339  */
340 static struct GNUNET_TIME_Absolute validation_next;
341
342 /**
343  * Context for the validation entry match function.
344  */
345 struct ValidationEntryMatchContext
346 {
347   /**
348    * Where to store the result?
349    */
350   struct ValidationEntry *ve;
351
352   /**
353    * Address we're interested in.
354    */
355   const struct GNUNET_HELLO_Address *address;
356
357 };
358
359
360 /**
361  * Iterate over validation entries until a matching one is found.
362  *
363  * @param cls the 'struct ValidationEntryMatchContext'
364  * @param key peer identity (unused)
365  * @param value a 'struct ValidationEntry' to match
366  * @return GNUNET_YES if the entry does not match,
367  *         GNUNET_NO if the entry does match
368  */
369 static int
370 validation_entry_match (void *cls, const struct GNUNET_HashCode * key, void *value)
371 {
372   struct ValidationEntryMatchContext *vemc = cls;
373   struct ValidationEntry *ve = value;
374
375   if (0 == GNUNET_HELLO_address_cmp (ve->address, vemc->address))
376   {
377     vemc->ve = ve;
378     return GNUNET_NO;
379   }
380   return GNUNET_YES;
381 }
382
383
384 /**
385  * Iterate over validation entries and free them.
386  *
387  * @param cls (unused)
388  * @param key peer identity (unused)
389  * @param value a 'struct ValidationEntry' to clean up
390  * @return GNUNET_YES (continue to iterate)
391  */
392 static int
393 cleanup_validation_entry (void *cls, const struct GNUNET_HashCode * key, void *value)
394 {
395   struct ValidationEntry *ve = value;
396
397   if (NULL != ve->bc)
398   {
399     GST_blacklist_test_cancel (ve->bc);
400     ve->bc = NULL;
401   }
402   GNUNET_break (GNUNET_OK ==
403                 GNUNET_CONTAINER_multihashmap_remove (validation_map,
404                                                       &ve->pid.hashPubKey, ve));
405   GNUNET_HELLO_address_free (ve->address);
406   if (GNUNET_SCHEDULER_NO_TASK != ve->timeout_task)
407   {
408     GNUNET_SCHEDULER_cancel (ve->timeout_task);
409     ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
410   }
411   if (GNUNET_SCHEDULER_NO_TASK != ve->revalidation_task)
412   {
413     GNUNET_SCHEDULER_cancel (ve->revalidation_task);
414     ve->revalidation_task = GNUNET_SCHEDULER_NO_TASK;
415   }
416   if ((GNUNET_YES == ve->expecting_pong) &&
417                 (validations_running > 0))
418   {
419                 validations_running --;
420           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
421                       "Validation finished, %u validation processes running\n",
422                       validations_running);
423   }
424   GNUNET_free (ve);
425   return GNUNET_OK;
426 }
427
428
429 /**
430  * Address validation cleanup task.  Assesses if the record is no
431  * longer valid and then possibly triggers its removal.
432  *
433  * @param cls the 'struct ValidationEntry'
434  * @param tc scheduler context (unused)
435  */
436 static void
437 timeout_hello_validation (void *cls,
438                           const struct GNUNET_SCHEDULER_TaskContext *tc)
439 {
440   struct ValidationEntry *ve = cls;
441   struct GNUNET_TIME_Absolute max;
442   struct GNUNET_TIME_Relative left;
443
444   ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
445   max = GNUNET_TIME_absolute_max (ve->valid_until, ve->revalidation_block);
446   left = GNUNET_TIME_absolute_get_remaining (max);
447   if (left.rel_value > 0)
448   {
449     /* should wait a bit longer */
450     ve->timeout_task =
451         GNUNET_SCHEDULER_add_delayed (left, &timeout_hello_validation, ve);
452     return;
453   }
454   GNUNET_STATISTICS_update (GST_stats,
455                             gettext_noop ("# address records discarded"), 1,
456                             GNUNET_NO);
457   cleanup_validation_entry (NULL, &ve->pid.hashPubKey, ve);
458 }
459
460
461 /**
462  * Function called with the result from blacklisting.
463  * Send a PING to the other peer if a communication is allowed.
464  *
465  * @param cls our 'struct ValidationEntry'
466  * @param pid identity of the other peer
467  * @param result GNUNET_OK if the connection is allowed, GNUNET_NO if not
468  */
469 static void
470 transmit_ping_if_allowed (void *cls, const struct GNUNET_PeerIdentity *pid,
471                           int result)
472 {
473   struct ValidationEntry *ve = cls;
474   struct TransportPingMessage ping;
475   struct GNUNET_TRANSPORT_PluginFunctions *papi;
476   struct GNUNET_TIME_Absolute next;
477   const struct GNUNET_MessageHeader *hello;
478   enum GNUNET_ATS_Network_Type network;
479   ssize_t ret;
480   size_t tsize;
481   size_t slen;
482   uint16_t hsize;
483
484   ve->bc = NULL;
485
486   if (GNUNET_NO == result)
487   {
488           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Blacklist denies to send PING to `%s' %s %s\n",
489                       GNUNET_i2s (pid), GST_plugins_a2s (ve->address), ve->address->transport_name);
490                 return;
491   }
492
493   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting plain PING to `%s' %s %s\n",
494               GNUNET_i2s (pid), GST_plugins_a2s (ve->address), ve->address->transport_name);
495
496   next = GNUNET_TIME_absolute_add (GNUNET_TIME_absolute_get(), validation_delay);
497   if (next.abs_value > validation_next.abs_value)
498         validation_next = next; /* We're going to send a PING so delay next validation */
499
500   slen = strlen (ve->address->transport_name) + 1;
501   hello = GST_hello_get ();
502   hsize = ntohs (hello->size);
503   tsize =
504       sizeof (struct TransportPingMessage) + ve->address->address_length +
505       slen + hsize;
506
507   ping.header.size =
508       htons (sizeof (struct TransportPingMessage) +
509              ve->address->address_length + slen);
510   ping.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
511   ping.challenge = htonl (ve->challenge);
512   ping.target = *pid;
513
514   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
515   {
516     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
517                 _
518                 ("Not transmitting `%s' with `%s', message too big (%u bytes!). This should not happen.\n"),
519                 "HELLO", "PING", (unsigned int) tsize);
520     /* message too big (!?), get rid of HELLO */
521     hsize = 0;
522     tsize =
523         sizeof (struct TransportPingMessage) + ve->address->address_length +
524         slen + hsize;
525   }
526   {
527     char message_buf[tsize];
528
529     /* build message with structure:
530      *  [HELLO][TransportPingMessage][Transport name][Address] */
531     memcpy (message_buf, hello, hsize);
532     memcpy (&message_buf[hsize], &ping, sizeof (struct TransportPingMessage));
533     memcpy (&message_buf[sizeof (struct TransportPingMessage) + hsize],
534             ve->address->transport_name, slen);
535     memcpy (&message_buf[sizeof (struct TransportPingMessage) + slen + hsize],
536             ve->address->address, ve->address->address_length);
537     papi = GST_plugins_find (ve->address->transport_name);
538     if (papi == NULL)
539       ret = -1;
540     else
541     {
542       GNUNET_assert (papi->send != NULL);
543       GNUNET_assert (papi->get_session != NULL);
544       struct Session * session = papi->get_session(papi->cls, ve->address);
545
546       if (session != NULL)
547       {
548         ret = papi->send (papi->cls, session,
549                           message_buf, tsize,
550                           PING_PRIORITY, ACCEPTABLE_PING_DELAY,
551                           NULL, NULL);
552         network = papi->get_network (ve->address, session);
553         if (GNUNET_ATS_NET_UNSPECIFIED == network)
554         {
555           GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
556                                                         "Could not obtain a valid network for `%s' %s\n",
557                       GNUNET_i2s (pid), GST_plugins_a2s (ve->address));
558                 GNUNET_break (0);
559         }
560       }
561       else
562       {
563         /* Could not get a valid session */
564         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Could not get a valid session for `%s' %s\n",
565                     GNUNET_i2s (pid), GST_plugins_a2s (ve->address));
566         ret = -1;
567       }
568     }
569   }
570   if (-1 != ret)
571   {
572     ve->send_time = GNUNET_TIME_absolute_get ();
573     GNUNET_STATISTICS_update (GST_stats,
574                               gettext_noop
575                               ("# PING without HELLO messages sent"), 1,
576                               GNUNET_NO);
577
578     ve->network = network;
579     ve->expecting_pong = GNUNET_YES;
580     validations_running ++;
581           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
582                       "Validation started, %u validation processes running\n",
583                       validations_running);
584   }
585 }
586
587
588 /**
589  * Do address validation again to keep address valid.
590  *
591  * @param cls the 'struct ValidationEntry'
592  * @param tc scheduler context (unused)
593  */
594 static void
595 revalidate_address (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
596 {
597   struct ValidationEntry *ve = cls;
598   struct GNUNET_TIME_Relative canonical_delay;
599   struct GNUNET_TIME_Relative delay;
600   struct GNUNET_TIME_Relative blocked_for;
601   struct GST_BlacklistCheck *bc;
602   uint32_t rdelay;
603
604   ve->revalidation_task = GNUNET_SCHEDULER_NO_TASK;
605   delay = GNUNET_TIME_absolute_get_remaining (ve->revalidation_block);
606   /* How long until we can possibly permit the next PING? */
607   canonical_delay =
608       (ve->in_use ==
609        GNUNET_YES) ? CONNECTED_PING_FREQUENCY
610       : ((GNUNET_TIME_absolute_get_remaining (ve->valid_until).rel_value >
611           0) ? VALIDATED_PING_FREQUENCY : UNVALIDATED_PING_KEEPALIVE);
612   if (delay.rel_value > canonical_delay.rel_value * 2)
613   {
614     /* situation changed, recalculate delay */
615     delay = canonical_delay;
616     ve->revalidation_block = GNUNET_TIME_relative_to_absolute (delay);
617   }
618   if (delay.rel_value > 0)
619   {
620     /* should wait a bit longer */
621     ve->revalidation_task =
622         GNUNET_SCHEDULER_add_delayed (delay, &revalidate_address, ve);
623     return;
624   }
625   blocked_for = GNUNET_TIME_absolute_get_remaining(validation_next);
626   if ((validations_running > validations_fast_start_threshold) &&
627                 (blocked_for.rel_value > 0))
628   {
629     /* Validations are blocked, have to wait for blocked_for time */
630     ve->revalidation_task =
631       GNUNET_SCHEDULER_add_delayed (blocked_for, &revalidate_address, ve);
632     return;
633   }
634   ve->revalidation_block = GNUNET_TIME_relative_to_absolute (canonical_delay);
635
636   /* schedule next PINGing with some extra random delay to avoid synchronous re-validations */
637   rdelay =
638       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
639                                 canonical_delay.rel_value);
640
641   /* Debug code for mantis 0002726*/
642   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value ==
643       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, rdelay).rel_value)
644   {
645     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
646                 "Revalidation interval for peer `%s' for is FOREVER (debug: rdelay: %llu, canonical delay %llu)\n",
647                 GNUNET_i2s (&ve->pid),
648                 (unsigned long long) delay.rel_value,
649                 (unsigned long long) canonical_delay.rel_value);
650     delay = canonical_delay;
651   }
652   else
653   {
654       delay = GNUNET_TIME_relative_add (canonical_delay,
655                                 GNUNET_TIME_relative_multiply
656                                 (GNUNET_TIME_UNIT_MILLISECONDS, rdelay));
657   }
658   /* End debug code for mantis 0002726*/
659   ve->revalidation_task =
660       GNUNET_SCHEDULER_add_delayed (delay, &revalidate_address, ve);
661
662   /* start PINGing by checking blacklist */
663   GNUNET_STATISTICS_update (GST_stats,
664                             gettext_noop ("# address revalidations started"), 1,
665                             GNUNET_NO);
666   bc = GST_blacklist_test_allowed (&ve->pid, ve->address->transport_name,
667                                    &transmit_ping_if_allowed, ve);
668   if (NULL != bc)
669     ve->bc = bc;                /* only set 'bc' if 'transmit_ping_if_allowed' was not already
670                                  * called... */
671 }
672
673
674 /**
675  * Find a ValidationEntry entry for the given neighbour that matches
676  * the given address and transport.  If none exists, create one (but
677  * without starting any validation).
678  *
679  * @param public_key public key of the peer, NULL for unknown
680  * @param address address to find
681  * @return validation entry matching the given specifications, NULL
682  *         if we don't have an existing entry and no public key was given
683  */
684 static struct ValidationEntry *
685 find_validation_entry (const struct GNUNET_CRYPTO_EccPublicKey *public_key,
686                        const struct GNUNET_HELLO_Address *address)
687 {
688   struct ValidationEntryMatchContext vemc;
689   struct ValidationEntry *ve;
690
691   vemc.ve = NULL;
692   vemc.address = address;
693   GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
694                                               &address->peer.hashPubKey,
695                                               &validation_entry_match, &vemc);
696   if (NULL != (ve = vemc.ve))
697     return ve;
698   if (public_key == NULL)
699     return NULL;
700   ve = GNUNET_malloc (sizeof (struct ValidationEntry));
701   ve->in_use = GNUNET_SYSERR; /* not defined */
702   ve->last_line_set_to_no  = 0;
703   ve->last_line_set_to_yes  = 0;
704   ve->address = GNUNET_HELLO_address_copy (address);
705   ve->public_key = *public_key;
706   ve->pid = address->peer;
707   ve->pong_sig_valid_until = GNUNET_TIME_absolute_get_zero_();
708   memset (&ve->pong_sig_cache, '\0', sizeof (struct GNUNET_CRYPTO_EccSignature));
709   ve->latency = GNUNET_TIME_UNIT_FOREVER_REL;
710   ve->challenge =
711       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
712   ve->timeout_task =
713       GNUNET_SCHEDULER_add_delayed (UNVALIDATED_PING_KEEPALIVE,
714                                     &timeout_hello_validation, ve);
715   GNUNET_CONTAINER_multihashmap_put (validation_map, &address->peer.hashPubKey,
716                                      ve,
717                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
718   ve->expecting_pong = GNUNET_NO;
719   return ve;
720 }
721
722
723 /**
724  * Iterator which adds the given address to the set of validated
725  * addresses.
726  *
727  * @param cls original HELLO message
728  * @param address the address
729  * @param expiration expiration time
730  * @return GNUNET_OK (keep the address)
731  */
732 static int
733 add_valid_address (void *cls, const struct GNUNET_HELLO_Address *address,
734                    struct GNUNET_TIME_Absolute expiration)
735 {
736   const struct GNUNET_HELLO_Message *hello = cls;
737   struct ValidationEntry *ve;
738   struct GNUNET_PeerIdentity pid;
739   struct GNUNET_ATS_Information ats;
740   struct GNUNET_CRYPTO_EccPublicKey public_key;
741
742   if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value == 0)
743     return GNUNET_OK;           /* expired */
744   if ((GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid)) ||
745       (GNUNET_OK != GNUNET_HELLO_get_key (hello, &public_key)))
746   {
747     GNUNET_break (0);
748     return GNUNET_OK;           /* invalid HELLO !? */
749   }
750   if (0 == memcmp (&GST_my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
751   {
752     /* Peerinfo returned own identity, skip validation */
753     return GNUNET_OK;
754   }
755
756   ve = find_validation_entry (&public_key, address);
757   ve->valid_until = GNUNET_TIME_absolute_max (ve->valid_until, expiration);
758
759   if (GNUNET_SCHEDULER_NO_TASK == ve->revalidation_task)
760     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
761
762   ats.type = htonl (GNUNET_ATS_NETWORK_TYPE);
763   ats.value = htonl (ve->network);
764   GNUNET_ATS_address_add (GST_ats, address, NULL, &ats, 1);
765
766   return GNUNET_OK;
767 }
768
769
770 /**
771  * Function called for any HELLO known to PEERINFO.
772  *
773  * @param cls unused
774  * @param peer id of the peer, NULL for last call
775  * @param hello hello message for the peer (can be NULL)
776  * @param err_msg error message
777  */
778 static void
779 process_peerinfo_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
780                         const struct GNUNET_HELLO_Message *hello,
781                         const char *err_msg)
782 {
783   GNUNET_assert (NULL != peer);
784   if (NULL == hello)
785     return;
786   GNUNET_assert (NULL ==
787                  GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO,
788                                                  &add_valid_address,
789                                                  (void *) hello));
790 }
791
792
793 /**
794  * Start the validation subsystem.
795  *
796  * @param max_fds maximum number of fds to use
797  */
798 void
799 GST_validation_start (unsigned int max_fds)
800 {
801         /**
802          * Initialization for validation throttling
803          *
804          * We have a maximum number max_fds of connections we can use for validation
805          * We monitor the number of validations in parallel and start to throttle it
806          * when doing to many validations in parallel:
807          * if (running validations < (max_fds / 2))
808          * - "fast start": run validation immediately
809          * - have delay of (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) / (max_fds / 2)
810          *   (300 sec / ~150 == ~2 sec.) between two validations
811          */
812
813         validation_next = GNUNET_TIME_absolute_get();
814         validation_delay.rel_value = (GNUNET_CONSTANTS_IDLE_CONNECTION_TIMEOUT.rel_value) /  (max_fds / 2);
815         validations_fast_start_threshold = (max_fds / 2);
816         validations_running = 0;
817         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Validation uses a fast start threshold of %u connections and a delay between of %u ms\n ",
818                         validations_fast_start_threshold, validation_delay.rel_value);
819   validation_map = GNUNET_CONTAINER_multihashmap_create (VALIDATION_MAP_SIZE,
820                                                          GNUNET_NO);
821   pnc = GNUNET_PEERINFO_notify (GST_cfg, GNUNET_YES, &process_peerinfo_hello, NULL);
822 }
823
824
825 /**
826  * Stop the validation subsystem.
827  */
828 void
829 GST_validation_stop ()
830 {
831   struct CheckHelloValidatedContext *chvc;
832
833   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
834                                          &cleanup_validation_entry, NULL);
835   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
836   validation_map = NULL;
837   while (NULL != (chvc = chvc_head))
838   {
839     GNUNET_CONTAINER_DLL_remove (chvc_head, chvc_tail, chvc);
840     GNUNET_free (chvc);
841   }
842   GNUNET_PEERINFO_notify_cancel (pnc);
843 }
844
845
846 /**
847  * Send the given PONG to the given address.
848  *
849  * @param cls the PONG message
850  * @param public_key public key for the peer, never NULL
851  * @param valid_until is ZERO if we never validated the address,
852  *                    otherwise a time up to when we consider it (or was) valid
853  * @param validation_block  is FOREVER if the address is for an unsupported plugin (from PEERINFO)
854  *                          is ZERO if the address is considered valid (no validation needed)
855  *                          otherwise a time in the future if we're currently denying re-validation
856  * @param address target address
857  */
858 static void
859 multicast_pong (void *cls,
860                 const struct GNUNET_CRYPTO_EccPublicKey *public_key, 
861                 struct GNUNET_TIME_Absolute valid_until,
862                 struct GNUNET_TIME_Absolute validation_block,
863                 const struct GNUNET_HELLO_Address *address)
864 {
865   struct TransportPongMessage *pong = cls;
866   struct GNUNET_TRANSPORT_PluginFunctions *papi;
867
868   papi = GST_plugins_find (address->transport_name);
869   if (papi == NULL)
870     return;
871
872   GNUNET_assert (papi->send != NULL);
873   GNUNET_assert (papi->get_session != NULL);
874
875   struct Session * session = papi->get_session(papi->cls, address);
876   if (session == NULL)
877   {
878      GNUNET_break (0);
879      return;
880   }
881
882   papi->send (papi->cls, session,
883               (const char *) pong, ntohs (pong->header.size),
884               PONG_PRIORITY, ACCEPTABLE_PING_DELAY,
885               NULL, NULL);
886 }
887
888
889 /**
890  * We've received a PING.  If appropriate, generate a PONG.
891  *
892  * @param sender peer sending the PING
893  * @param hdr the PING
894  * @param sender_address the sender address as we got it
895  * @param session session we got the PING from
896  */
897 void
898 GST_validation_handle_ping (const struct GNUNET_PeerIdentity *sender,
899                             const struct GNUNET_MessageHeader *hdr,
900                             const struct GNUNET_HELLO_Address *sender_address,
901                             struct Session *session)
902 {
903   const struct TransportPingMessage *ping;
904   struct TransportPongMessage *pong;
905   struct GNUNET_TRANSPORT_PluginFunctions *papi;
906   struct GNUNET_CRYPTO_EccSignature *sig_cache;
907   struct GNUNET_TIME_Absolute *sig_cache_exp;
908   const char *addr;
909   const char *addrend;
910   char *plugin_name;
911   char *pos;
912   size_t alen;
913   size_t slen;
914   ssize_t ret;
915   int buggy = GNUNET_NO;
916   struct GNUNET_HELLO_Address address;
917
918   if (ntohs (hdr->size) < sizeof (struct TransportPingMessage))
919   {
920     GNUNET_break_op (0);
921     return;
922   }
923   ping = (const struct TransportPingMessage *) hdr;
924   if (0 !=
925       memcmp (&ping->target, &GST_my_identity,
926               sizeof (struct GNUNET_PeerIdentity)))
927   {
928     GNUNET_STATISTICS_update (GST_stats,
929                               gettext_noop
930                               ("# PING message for different peer received"), 1,
931                               GNUNET_NO);
932     return;
933   }
934   GNUNET_STATISTICS_update (GST_stats,
935                             gettext_noop ("# PING messages received"), 1,
936                             GNUNET_NO);
937   addr = (const char *) &ping[1];
938   alen = ntohs (hdr->size) - sizeof (struct TransportPingMessage);
939   /* peer wants to confirm that this is one of our addresses, this is what is
940    * used for address validation */
941
942   sig_cache = NULL;
943   sig_cache_exp = NULL;
944   papi = NULL;
945   if (alen > 0)
946   {
947     addrend = memchr (addr, '\0', alen);
948     if (NULL == addrend)
949     {
950       GNUNET_break_op (0);
951       return;
952     }
953     addrend++;
954     slen = strlen (addr) + 1;
955     alen -= slen;
956     address.address = addrend;
957     address.address_length = alen;
958     address.transport_name = addr;
959     address.peer = GST_my_identity;
960
961     if (NULL == address.transport_name)
962     {
963         GNUNET_break (0);
964     }
965
966     if (0 != strstr (address.transport_name, "_client"))
967                 {
968         plugin_name = GNUNET_strdup (address.transport_name);
969         pos = strstr (plugin_name, "_client");
970         GNUNET_assert (NULL != pos);
971         GNUNET_snprintf (pos, strlen ("_server") + 1, "%s", "_server");
972                 }
973     else
974         plugin_name = GNUNET_strdup (address.transport_name);
975
976     if (NULL == (papi = GST_plugins_find (plugin_name)))
977     {
978       /* we don't have the plugin for this address */
979       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Plugin `%s' not available, cannot confirm having this address \n",
980                 plugin_name);
981       GNUNET_free (plugin_name);
982       return;
983     }
984     GNUNET_free (plugin_name);
985     if (GNUNET_OK != papi->check_address (papi->cls, addrend, alen))
986                 {
987       GNUNET_STATISTICS_update (GST_stats,
988                                 gettext_noop
989                                 ("# failed address checks during validation"), 1,
990                                 GNUNET_NO);
991         GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Address `%s' is not one of my addresses, not confirming PING\n",
992                 GST_plugins_a2s (&address));
993         return;
994                 }
995     else
996     {
997       GNUNET_STATISTICS_update (GST_stats,
998                                 gettext_noop
999                                 ("# successful address checks during validation"), 1,
1000                                 GNUNET_NO);
1001         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Address `%s' is one of my addresses, confirming PING\n",
1002                         GST_plugins_a2s (&address));
1003     }
1004
1005     if (GNUNET_YES != GST_hello_test_address (&address, &sig_cache, &sig_cache_exp))
1006     {
1007       if (GNUNET_NO == buggy)
1008       {
1009         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1010                     "Not confirming PING from peer `%s' with address `%s' since I cannot confirm having this address.\n",
1011                     GNUNET_i2s (sender),
1012                     GST_plugins_a2s (&address));
1013         return;
1014       }
1015       else
1016       {
1017         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1018                     _("Received a PING message with validation bug from `%s'\n"),
1019                     GNUNET_i2s (sender));
1020       }
1021     }
1022   }
1023   else
1024   {
1025     addrend = NULL;             /* make gcc happy */
1026     slen = 0;
1027     static struct GNUNET_CRYPTO_EccSignature no_address_signature;
1028     static struct GNUNET_TIME_Absolute no_address_signature_expiration;
1029
1030     sig_cache = &no_address_signature;
1031     sig_cache_exp = &no_address_signature_expiration;
1032   }
1033
1034   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1035               "I am `%s', sending PONG to peer `%s'\n",
1036               GNUNET_h2s (&GST_my_identity.hashPubKey),
1037               GNUNET_i2s (sender));
1038
1039   /* message with structure:
1040    * [TransportPongMessage][Transport name][Address] */
1041
1042   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
1043   pong->header.size =
1044       htons (sizeof (struct TransportPongMessage) + alen + slen);
1045   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
1046   pong->purpose.size =
1047       htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) +
1048              sizeof (uint32_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO) +
1049              alen + slen);
1050   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
1051   memcpy (&pong->challenge, &ping->challenge, sizeof (ping->challenge));
1052   pong->addrlen = htonl (alen + slen);
1053   memcpy (&pong[1], addr, slen);   /* Copy transport plugin */
1054   if (alen > 0)
1055   {
1056     GNUNET_assert (NULL != addrend);
1057     memcpy (&((char *) &pong[1])[slen], addrend, alen);
1058   }
1059   if (GNUNET_TIME_absolute_get_remaining (*sig_cache_exp).rel_value <
1060       PONG_SIGNATURE_LIFETIME.rel_value / 4)
1061   {
1062     /* create / update cached sig */
1063     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1064                 "Creating PONG signature to indicate ownership.\n");
1065     *sig_cache_exp = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
1066     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
1067     if (GNUNET_OK !=
1068                    GNUNET_CRYPTO_ecc_sign (GST_my_private_key, &pong->purpose,
1069                                            sig_cache))
1070     {
1071         GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1072                 _("Failed to create PONG signature for peer `%s'\n"), GNUNET_i2s (sender));
1073     }
1074   }
1075   else
1076   {
1077     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
1078   }
1079   pong->signature = *sig_cache;
1080   
1081   GNUNET_assert (sender_address != NULL);
1082
1083   /* first see if the session we got this PING from can be used to transmit
1084    * a response reliably */
1085   if (papi == NULL)
1086     ret = -1;
1087   else
1088   {
1089     GNUNET_assert (papi->send != NULL);
1090     GNUNET_assert (papi->get_session != NULL);
1091
1092     if (session == NULL)
1093     {
1094       session = papi->get_session (papi->cls, sender_address);
1095     }
1096     if (session == NULL)
1097     {
1098       GNUNET_break (0);
1099       ret = -1;
1100     }
1101     else
1102     {
1103       ret = papi->send (papi->cls, session,
1104                         (const char *) pong, ntohs (pong->header.size),
1105                         PONG_PRIORITY, ACCEPTABLE_PING_DELAY,
1106                         NULL, NULL);
1107     }
1108   }
1109   if (ret != -1)
1110   {
1111     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1112                 "Transmitted PONG to `%s' via reliable mechanism\n",
1113                 GNUNET_i2s (sender));
1114     /* done! */
1115     GNUNET_STATISTICS_update (GST_stats,
1116                               gettext_noop
1117                               ("# PONGs unicast via reliable transport"), 1,
1118                               GNUNET_NO);
1119     GNUNET_free (pong);
1120     return;
1121   }
1122
1123   /* no reliable method found, try transmission via all known addresses */
1124   GNUNET_STATISTICS_update (GST_stats,
1125                             gettext_noop
1126                             ("# PONGs multicast to all available addresses"), 1,
1127                             GNUNET_NO);
1128   GST_validation_get_addresses (sender, &multicast_pong, pong);
1129   GNUNET_free (pong);
1130 }
1131
1132
1133 /**
1134  * Context for the 'validate_address' function
1135  */
1136 struct ValidateAddressContext
1137 {
1138   /**
1139    * Hash of the public key of the peer whose address is being validated.
1140    */
1141   struct GNUNET_PeerIdentity pid;
1142
1143   /**
1144    * Public key of the peer whose address is being validated.
1145    */
1146   struct GNUNET_CRYPTO_EccPublicKey public_key;
1147 };
1148
1149
1150 /**
1151  * Iterator callback to go over all addresses and try to validate them
1152  * (unless blocked or already validated).
1153  *
1154  * @param cls pointer to a 'struct ValidateAddressContext'
1155  * @param address the address
1156  * @param expiration expiration time
1157  * @return GNUNET_OK (keep the address)
1158  */
1159 static int
1160 validate_address_iterator (void *cls,
1161                            const struct GNUNET_HELLO_Address *address,
1162                            struct GNUNET_TIME_Absolute expiration)
1163 {
1164   const struct ValidateAddressContext *vac = cls;
1165   struct ValidationEntry *ve;
1166
1167   if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value == 0)
1168     return GNUNET_OK;           /* expired */
1169   ve = find_validation_entry (&vac->public_key, address);
1170   if (GNUNET_SCHEDULER_NO_TASK == ve->revalidation_task)
1171     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
1172   return GNUNET_OK;
1173 }
1174
1175
1176 /**
1177  * Add the validated peer address to the HELLO.
1178  *
1179  * @param cls the 'struct ValidationEntry' with the validated address
1180  * @param max space in buf
1181  * @param buf where to add the address
1182  * @return number of bytes written, 0 to signal the
1183  *         end of the iteration.
1184  */
1185 static size_t
1186 add_valid_peer_address (void *cls, size_t max, void *buf)
1187 {
1188   struct ValidationEntry *ve = cls;
1189
1190   if (GNUNET_YES == ve->copied)
1191     return 0;                   /* terminate */
1192   ve->copied = GNUNET_YES;
1193   return GNUNET_HELLO_add_address (ve->address, ve->valid_until, buf, max);
1194 }
1195
1196
1197 /**
1198  * We've received a PONG.  Check if it matches a pending PING and
1199  * mark the respective address as confirmed.
1200  *
1201  * @param sender peer sending the PONG
1202  * @param hdr the PONG
1203  */
1204 void
1205 GST_validation_handle_pong (const struct GNUNET_PeerIdentity *sender,
1206                             const struct GNUNET_MessageHeader *hdr)
1207 {
1208   const struct TransportPongMessage *pong;
1209   struct ValidationEntry *ve;
1210   const char *tname;
1211   const char *addr;
1212   size_t addrlen;
1213   size_t slen;
1214   size_t size;
1215   struct GNUNET_HELLO_Message *hello;
1216   struct GNUNET_HELLO_Address address;
1217   int sig_res;
1218   int do_verify;
1219
1220   if (ntohs (hdr->size) < sizeof (struct TransportPongMessage))
1221   {
1222     GNUNET_break_op (0);
1223     return;
1224   }
1225   GNUNET_STATISTICS_update (GST_stats,
1226                             gettext_noop ("# PONG messages received"), 1,
1227                             GNUNET_NO);
1228
1229   /* message with structure:
1230    * [TransportPongMessage][Transport name][Address] */
1231
1232   pong = (const struct TransportPongMessage *) hdr;
1233   tname = (const char *) &pong[1];
1234   size = ntohs (hdr->size) - sizeof (struct TransportPongMessage);
1235   addr = memchr (tname, '\0', size);
1236   if (NULL == addr)
1237   {
1238     GNUNET_break_op (0);
1239     return;
1240   }
1241   addr++;
1242   slen = strlen (tname) + 1;
1243   addrlen = size - slen;
1244   address.peer = *sender;
1245   address.address = addr;
1246   address.address_length = addrlen;
1247   address.transport_name = tname;
1248   ve = find_validation_entry (NULL, &address);
1249   if ((NULL == ve) || (GNUNET_NO == ve->expecting_pong))
1250   {
1251     GNUNET_STATISTICS_update (GST_stats,
1252                               gettext_noop
1253                               ("# PONGs dropped, no matching pending validation"),
1254                               1, GNUNET_NO);
1255     return;
1256   }
1257   /* now check that PONG is well-formed */
1258   if (0 != memcmp (&ve->pid, sender, sizeof (struct GNUNET_PeerIdentity)))
1259   {
1260     GNUNET_break_op (0);
1261     return;
1262   }
1263   if (GNUNET_TIME_absolute_get_remaining
1264       (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
1265   {
1266     GNUNET_STATISTICS_update (GST_stats,
1267                               gettext_noop
1268                               ("# PONGs dropped, signature expired"), 1,
1269                               GNUNET_NO);
1270     return;
1271   }
1272
1273   sig_res = GNUNET_SYSERR;
1274   do_verify = GNUNET_YES;
1275   if (0 != GNUNET_TIME_absolute_get_remaining(ve->pong_sig_valid_until).rel_value)
1276   {
1277                 /* We have a cached and valid signature for this peer,
1278                  * try to compare instead of verify */
1279                 if (0 == memcmp (&ve->pong_sig_cache, &pong->signature, sizeof (struct GNUNET_CRYPTO_EccSignature)))
1280                 {
1281                         /* signatures are identical, we can skip verification */
1282                         sig_res = GNUNET_OK;
1283                         do_verify = GNUNET_NO;
1284                 }
1285                 else
1286                 {
1287                         sig_res = GNUNET_SYSERR;
1288                         /* signatures do not match, we have to verify */
1289                 }
1290   }
1291
1292   if (GNUNET_YES == do_verify)
1293   {
1294                         /* Do expensive verification */
1295                 sig_res = GNUNET_CRYPTO_ecc_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
1296                                 &pong->purpose, &pong->signature,
1297                                 &ve->public_key);
1298                 if (sig_res == GNUNET_SYSERR)
1299                         GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1300                                         "Failed to verify: invalid signature on address %s:%s from peer `%s'\n",
1301                                         tname, GST_plugins_a2s (ve->address),GNUNET_i2s (sender));
1302   }
1303
1304   if (sig_res == GNUNET_SYSERR)
1305     return;
1306
1307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1308               "Address validated for peer `%s' with plugin `%s': `%s'\n",
1309               GNUNET_i2s (sender), tname, GST_plugins_a2s (ve->address));
1310   /* validity achieved, remember it! */
1311   ve->expecting_pong = GNUNET_NO;
1312   ve->valid_until = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1313   ve->pong_sig_cache = pong->signature;
1314         ve->pong_sig_valid_until = GNUNET_TIME_absolute_ntoh (pong->expiration);
1315   ve->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1316   {
1317     struct GNUNET_ATS_Information ats[2];
1318     ats[0].type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1319     ats[0].value = htonl ((uint32_t) ve->latency.rel_value);
1320     ats[1].type = htonl (GNUNET_ATS_NETWORK_TYPE);
1321     ats[1].value = htonl ((uint32_t) ve->network);
1322     GNUNET_ATS_address_add (GST_ats, ve->address, NULL, ats, 2);
1323   }
1324   if (validations_running > 0)
1325   {
1326         validations_running --;
1327           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1328                       "Validation finished, %u validation processes running\n",
1329                       validations_running);
1330   }
1331   else
1332         GNUNET_break (0);
1333
1334   /* build HELLO to store in PEERINFO */
1335   ve->copied = GNUNET_NO;
1336   hello = GNUNET_HELLO_create (&ve->public_key, &add_valid_peer_address, ve, GNUNET_NO);
1337   GNUNET_PEERINFO_add_peer (GST_peerinfo, hello, NULL, NULL);
1338   GNUNET_free (hello);
1339 }
1340
1341
1342 /**
1343  * We've received a HELLO, check which addresses are new and trigger
1344  * validation.
1345  *
1346  * @param hello the HELLO we received
1347  */
1348 void
1349 GST_validation_handle_hello (const struct GNUNET_MessageHeader *hello)
1350 {
1351   const struct GNUNET_HELLO_Message *hm =
1352       (const struct GNUNET_HELLO_Message *) hello;
1353   struct ValidateAddressContext vac;
1354   struct GNUNET_HELLO_Message *h;
1355   int friend;
1356
1357   friend = GNUNET_HELLO_is_friend_only (hm);
1358   if (((GNUNET_YES != friend) && (GNUNET_NO != friend)) ||
1359                 (GNUNET_OK != GNUNET_HELLO_get_id (hm, &vac.pid)) ||
1360       (GNUNET_OK != GNUNET_HELLO_get_key (hm, &vac.public_key)))
1361   {
1362     /* malformed HELLO */
1363     GNUNET_break (0);
1364     return;
1365   }
1366   if (0 ==
1367       memcmp (&GST_my_identity, &vac.pid, sizeof (struct GNUNET_PeerIdentity)))
1368     return;
1369   /* Add peer identity without addresses to peerinfo service */
1370   h = GNUNET_HELLO_create (&vac.public_key, NULL, NULL, friend);
1371   GNUNET_PEERINFO_add_peer (GST_peerinfo, h, NULL, NULL);
1372
1373   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1374               _("Adding `%s' without addresses for peer `%s'\n"), "HELLO",
1375               GNUNET_i2s (&vac.pid));
1376
1377   GNUNET_free (h);
1378   GNUNET_assert (NULL ==
1379                  GNUNET_HELLO_iterate_addresses (hm, GNUNET_NO,
1380                                                  &validate_address_iterator,
1381                                                  &vac));
1382 }
1383
1384
1385 /**
1386  * Closure for 'iterate_addresses'
1387  */
1388 struct IteratorContext
1389 {
1390   /**
1391    * Function to call on each address.
1392    */
1393   GST_ValidationAddressCallback cb;
1394
1395   /**
1396    * Closure for 'cb'.
1397    */
1398   void *cb_cls;
1399
1400 };
1401
1402
1403 /**
1404  * Call the callback in the closure for each validation entry.
1405  *
1406  * @param cls the 'struct GST_ValidationIteratorContext'
1407  * @param key the peer's identity
1408  * @param value the 'struct ValidationEntry'
1409  * @return GNUNET_OK (continue to iterate)
1410  */
1411 static int
1412 iterate_addresses (void *cls, const struct GNUNET_HashCode * key, void *value)
1413 {
1414   struct IteratorContext *ic = cls;
1415   struct ValidationEntry *ve = value;
1416
1417   ic->cb (ic->cb_cls, &ve->public_key, ve->valid_until, ve->revalidation_block,
1418           ve->address);
1419   return GNUNET_OK;
1420 }
1421
1422
1423 /**
1424  * Call the given function for each address for the given target.
1425  * Can either give a snapshot (synchronous API) or be continuous.
1426  *
1427  * @param target peer information is requested for
1428  * @param cb function to call; will not be called after this function returns
1429  * @param cb_cls closure for 'cb'
1430  */
1431 void
1432 GST_validation_get_addresses (const struct GNUNET_PeerIdentity *target,
1433                               GST_ValidationAddressCallback cb, void *cb_cls)
1434 {
1435   struct IteratorContext ic;
1436
1437   ic.cb = cb;
1438   ic.cb_cls = cb_cls;
1439   GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1440                                               &target->hashPubKey,
1441                                               &iterate_addresses, &ic);
1442 }
1443
1444
1445 /**
1446  * Update if we are using an address for a connection actively right now.
1447  * Based on this, the validation module will measure latency for the
1448  * address more or less often.
1449  *
1450  * @param address the address
1451  * @param session the session
1452  * @param in_use GNUNET_YES if we are now using the address for a connection,
1453  *               GNUNET_NO if we are no longer using the address for a connection
1454  * @param line line of caller just for DEBUGGING!
1455  */
1456 void
1457 GST_validation_set_address_use (const struct GNUNET_HELLO_Address *address,
1458                                 struct Session *session,
1459                                 int in_use,
1460                                 int line)
1461 {
1462   struct ValidationEntry *ve;
1463
1464   if (NULL != address)
1465     ve = find_validation_entry (NULL, address);
1466   else
1467     ve = NULL;                  /* FIXME: lookup based on session... */
1468   if (NULL == ve)
1469   {
1470     /* this can happen for inbound connections (sender_address_len == 0); */
1471     return;
1472   }
1473   if (ve->in_use == in_use)
1474   {
1475
1476     if (GNUNET_YES == in_use)
1477     {
1478       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1479                   "Error setting address in use for peer `%s' `%s' to USED: set last time by %i, called now by %i\n",
1480                   GNUNET_i2s (&address->peer), GST_plugins_a2s (address),
1481                   ve->last_line_set_to_yes, line);
1482     }
1483     if (GNUNET_NO == in_use)
1484     {
1485       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1486                   "Error setting address in use for peer `%s' `%s' to NOT_USED: set last time by %i, called now by %i\n",
1487                   GNUNET_i2s (&address->peer), GST_plugins_a2s (address),
1488                   ve->last_line_set_to_no, line);
1489     }
1490   }
1491
1492   if (GNUNET_YES == in_use)
1493   {
1494     ve->last_line_set_to_yes = line;
1495   }
1496   if (GNUNET_NO == in_use)
1497   {
1498     ve->last_line_set_to_no = line;
1499   }
1500
1501   GNUNET_break (ve->in_use != in_use);  /* should be different... */
1502   ve->in_use = in_use;
1503   if (in_use == GNUNET_YES)
1504   {
1505     /* from now on, higher frequeny, so reschedule now */
1506     GNUNET_SCHEDULER_cancel (ve->revalidation_task);
1507     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
1508   }
1509 }
1510
1511
1512 /**
1513  * Query validation about the latest observed latency on a given
1514  * address.
1515  *
1516  * @param sender peer
1517  * @param address the address
1518  * @param session session
1519  * @return observed latency of the address, FOREVER if the address was
1520  *         never successfully validated
1521  */
1522 struct GNUNET_TIME_Relative
1523 GST_validation_get_address_latency (const struct GNUNET_PeerIdentity *sender,
1524                                     const struct GNUNET_HELLO_Address *address,
1525                                     struct Session *session)
1526 {
1527   struct ValidationEntry *ve;
1528
1529   if (NULL == address)
1530   {
1531     GNUNET_break (0);           // FIXME: support having latency only with session...
1532     return GNUNET_TIME_UNIT_FOREVER_REL;
1533   }
1534   ve = find_validation_entry (NULL, address);
1535   if (NULL == ve)
1536     return GNUNET_TIME_UNIT_FOREVER_REL;
1537   return ve->latency;
1538 }
1539
1540
1541 /* end of file gnunet-service-transport_validation.c */