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