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