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