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