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