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