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