first steps to transport_api cleanup
[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   if (0 == memcmp(&GST_my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
632   {
633     /* Peerinfo returned own identity, skip validation */
634     return GNUNET_OK;
635   }
636
637   ve = find_validation_entry (&public_key, address);
638   ve->valid_until = GNUNET_TIME_absolute_max (ve->valid_until, expiration);
639
640   if (GNUNET_SCHEDULER_NO_TASK == ve->revalidation_task)
641     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
642   GNUNET_ATS_address_update (GST_ats, address, NULL, NULL,
643                              0);
644   return GNUNET_OK;
645 }
646
647
648 /**
649  * Function called for any HELLO known to PEERINFO.
650  *
651  * @param cls unused
652  * @param peer id of the peer, NULL for last call
653  * @param hello hello message for the peer (can be NULL)
654  * @param err_msg error message
655  */
656 static void
657 process_peerinfo_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
658                         const struct GNUNET_HELLO_Message *hello,
659                         const char *err_msg)
660 {
661   GNUNET_assert (NULL != peer);
662   if (NULL == hello)
663     return;
664   GNUNET_assert (NULL ==
665                  GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO,
666                                                  &add_valid_address,
667                                                  (void *) hello));
668 }
669
670
671 /**
672  * Start the validation subsystem.
673  */
674 void
675 GST_validation_start ()
676 {
677   validation_map = GNUNET_CONTAINER_multihashmap_create (VALIDATION_MAP_SIZE);
678   pnc = GNUNET_PEERINFO_notify (GST_cfg, &process_peerinfo_hello, NULL);
679 }
680
681
682 /**
683  * Stop the validation subsystem.
684  */
685 void
686 GST_validation_stop ()
687 {
688   struct CheckHelloValidatedContext *chvc;
689
690   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
691                                          &cleanup_validation_entry, NULL);
692   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
693   validation_map = NULL;
694   while (NULL != (chvc = chvc_head))
695   {
696     GNUNET_CONTAINER_DLL_remove (chvc_head, chvc_tail, chvc);
697     GNUNET_free (chvc);
698   }
699   GNUNET_PEERINFO_notify_cancel (pnc);
700 }
701
702
703 /**
704  * Send the given PONG to the given address.
705  *
706  * @param cls the PONG message
707  * @param public_key public key for the peer, never NULL
708  * @param target peer this change is about, never NULL
709  * @param valid_until is ZERO if we never validated the address,
710  *                    otherwise a time up to when we consider it (or was) valid
711  * @param validation_block  is FOREVER if the address is for an unsupported plugin (from PEERINFO)
712  *                          is ZERO if the address is considered valid (no validation needed)
713  *                          otherwise a time in the future if we're currently denying re-validation
714  * @param adress target address
715  */
716 static void
717 multicast_pong (void *cls,
718                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
719                 *public_key,
720                 struct GNUNET_TIME_Absolute valid_until,
721                 struct GNUNET_TIME_Absolute validation_block,
722                 const struct GNUNET_HELLO_Address *address)
723 {
724   struct TransportPongMessage *pong = cls;
725   struct GNUNET_TRANSPORT_PluginFunctions *papi;
726
727   papi = GST_plugins_find (address->transport_name);
728   if (papi == NULL)
729     return;
730   (void) papi->send (papi->cls, &address->peer, (const char *) pong,
731                      ntohs (pong->header.size), PONG_PRIORITY,
732                      ACCEPTABLE_PING_DELAY, NULL, 
733                      address->address,
734                      address->address_length, GNUNET_YES, NULL, NULL);
735 }
736
737
738 /**
739  * We've received a PING.  If appropriate, generate a PONG.
740  *
741  * @param sender peer sending the PING
742  * @param hdr the PING
743  * @param sender_address the sender address as we got it
744  * @param session session we got the PING from
745  */
746 void
747 GST_validation_handle_ping (const struct GNUNET_PeerIdentity *sender,
748                             const struct GNUNET_MessageHeader *hdr,
749                             const struct GNUNET_HELLO_Address *sender_address,
750                             struct Session *session)
751 {
752   const struct TransportPingMessage *ping;
753   struct TransportPongMessage *pong;
754   struct GNUNET_TRANSPORT_PluginFunctions *papi;
755   struct GNUNET_CRYPTO_RsaSignature *sig_cache;
756   struct GNUNET_TIME_Absolute *sig_cache_exp;
757   const char *addr;
758   const char *addrend;
759   size_t alen;
760   size_t slen;
761   ssize_t ret;
762   struct GNUNET_HELLO_Address address;
763
764   if (ntohs (hdr->size) < sizeof (struct TransportPingMessage))
765   {
766     GNUNET_break_op (0);
767     return;
768   }
769   ping = (const struct TransportPingMessage *) hdr;
770   if (0 !=
771       memcmp (&ping->target, &GST_my_identity,
772               sizeof (struct GNUNET_PeerIdentity)))
773   {
774     GNUNET_STATISTICS_update (GST_stats,
775                               gettext_noop
776                               ("# PING message for different peer received"), 1,
777                               GNUNET_NO);
778     return;
779   }
780   GNUNET_STATISTICS_update (GST_stats,
781                             gettext_noop ("# PING messages received"), 1,
782                             GNUNET_NO);
783   addr = (const char *) &ping[1];
784   alen = ntohs (hdr->size) - sizeof (struct TransportPingMessage);
785   /* peer wants to confirm that this is one of our addresses, this is what is
786    * used for address validation */
787
788   sig_cache = NULL;
789   sig_cache_exp = NULL;
790
791   if (0 < alen)
792   {
793     addrend = memchr (addr, '\0', alen);
794     if (NULL == addrend)
795     {
796       GNUNET_break_op (0);
797       return;
798     }
799     addrend++;
800     slen = strlen (addr) + 1;
801     alen -= slen;
802     address.address = addrend;
803     address.address_length = alen;
804     address.transport_name = addr;
805     address.peer = *sender;
806     if (GNUNET_YES !=
807         GST_hello_test_address (&address, &sig_cache,
808                                 &sig_cache_exp))
809     {
810       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
811                   _
812                   ("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
813                   GST_plugins_a2s (&address));
814       return;
815     }
816   }
817   else
818   {
819     addrend = NULL;             /* make gcc happy */
820     slen = 0;
821     static struct GNUNET_CRYPTO_RsaSignature no_address_signature;
822     static struct GNUNET_TIME_Absolute no_address_signature_expiration;
823
824     sig_cache = &no_address_signature;
825     sig_cache_exp = &no_address_signature_expiration;
826   }
827
828   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
829   pong->header.size =
830       htons (sizeof (struct TransportPongMessage) + alen + slen);
831   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
832   pong->purpose.size =
833       htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
834              sizeof (uint32_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO) +
835              alen + slen);
836   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
837   pong->challenge = ping->challenge;
838   pong->addrlen = htonl (alen + slen);
839   memcpy (&pong[1], addr, slen);
840   memcpy (&((char *) &pong[1])[slen], addrend, alen);
841   if (GNUNET_TIME_absolute_get_remaining (*sig_cache_exp).rel_value <
842       PONG_SIGNATURE_LIFETIME.rel_value / 4)
843   {
844     /* create / update cached sig */
845 #if DEBUG_TRANSPORT
846     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
847                 "Creating PONG signature to indicate ownership.\n");
848 #endif
849     *sig_cache_exp = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
850     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
851     GNUNET_assert (GNUNET_OK ==
852                    GNUNET_CRYPTO_rsa_sign (GST_my_private_key, &pong->purpose,
853                                            sig_cache));
854   }
855   else
856   {
857     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
858   }
859   pong->signature = *sig_cache;
860
861   /* first see if the session we got this PING from can be used to transmit
862    * a response reliably */
863   papi = GST_plugins_find (sender_address->transport_name);
864   if (papi == NULL)
865     ret = -1;
866   else
867     ret =
868         papi->send (papi->cls, sender, (const char *) pong,
869                     ntohs (pong->header.size), PONG_PRIORITY,
870                     ACCEPTABLE_PING_DELAY, session, 
871                     sender_address->address,
872                     sender_address->address_length,
873                     GNUNET_SYSERR, NULL, NULL);
874   if (ret != -1)
875   {
876     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
877                 "Transmitted PONG to `%s' via reliable mechanism\n",
878                 GNUNET_i2s (sender));
879     /* done! */
880     GNUNET_STATISTICS_update (GST_stats,
881                               gettext_noop
882                               ("# PONGs unicast via reliable transport"), 1,
883                               GNUNET_NO);
884     GNUNET_free (pong);
885     return;
886   }
887
888   /* no reliable method found, try transmission via all known addresses */
889   GNUNET_STATISTICS_update (GST_stats,
890                             gettext_noop
891                             ("# PONGs multicast to all available addresses"), 1,
892                             GNUNET_NO);
893   GST_validation_get_addresses (sender, &multicast_pong, pong);
894   GNUNET_free (pong);
895 }
896
897
898 /**
899  * Context for the 'validate_address' function
900  */
901 struct ValidateAddressContext
902 {
903   /**
904    * Hash of the public key of the peer whose address is being validated.
905    */
906   struct GNUNET_PeerIdentity pid;
907
908   /**
909    * Public key of the peer whose address is being validated.
910    */
911   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
912 };
913
914
915 /**
916  * Iterator callback to go over all addresses and try to validate them
917  * (unless blocked or already validated).
918  *
919  * @param cls pointer to a 'struct ValidateAddressContext'
920  * @param address the address
921  * @param expiration expiration time
922  * @return GNUNET_OK (keep the address)
923  */
924 static int
925 validate_address_iterator (void *cls, 
926                            const struct GNUNET_HELLO_Address *address,
927                            struct GNUNET_TIME_Absolute expiration)
928 {
929   const struct ValidateAddressContext *vac = cls;
930   struct ValidationEntry *ve;
931
932   if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value == 0)
933     return GNUNET_OK;           /* expired */
934   ve = find_validation_entry (&vac->public_key, address);
935   if (GNUNET_SCHEDULER_NO_TASK == ve->revalidation_task)
936     ve->revalidation_task = GNUNET_SCHEDULER_add_now (&revalidate_address,
937                                                       ve);
938   return GNUNET_OK;
939 }
940
941
942 /**
943  * Add the validated peer address to the HELLO.
944  *
945  * @param cls the 'struct ValidationEntry' with the validated address
946  * @param max space in buf
947  * @param buf where to add the address
948  * @return number of bytes written, 0 to signal the
949  *         end of the iteration.
950  */
951 static size_t
952 add_valid_peer_address (void *cls, size_t max, void *buf)
953 {
954   struct ValidationEntry *ve = cls;
955
956   if (GNUNET_YES == ve->copied)
957     return 0;                   /* terminate */
958   ve->copied = GNUNET_YES;
959   return GNUNET_HELLO_add_address (ve->address, ve->valid_until,
960                                    buf, max);
961 }
962
963
964 /**
965  * We've received a PONG.  Check if it matches a pending PING and
966  * mark the respective address as confirmed.
967  *
968  * @param sender peer sending the PONG
969  * @param hdr the PONG
970  */
971 void
972 GST_validation_handle_pong (const struct GNUNET_PeerIdentity *sender,
973                             const struct GNUNET_MessageHeader *hdr)
974 {
975   const struct TransportPongMessage *pong;
976   struct ValidationEntry *ve;
977   const char *tname;
978   const char *addr;
979   size_t addrlen;
980   size_t slen;
981   size_t size;
982   struct GNUNET_HELLO_Message *hello;
983   struct GNUNET_HELLO_Address address;
984
985   if (ntohs (hdr->size) < sizeof (struct TransportPongMessage))
986   {
987     GNUNET_break_op (0);
988     return;
989   }
990   GNUNET_STATISTICS_update (GST_stats,
991                             gettext_noop ("# PONG messages received"), 1,
992                             GNUNET_NO);
993
994   pong = (const struct TransportPongMessage *) hdr;
995   tname = (const char *) &pong[1];
996   size = ntohs (hdr->size) - sizeof (struct TransportPongMessage);
997   addr = memchr (tname, '\0', size);
998   if (NULL == addr)
999   {
1000     GNUNET_break_op (0);
1001     return;
1002   }
1003   addr++;
1004   slen = strlen (tname) + 1;
1005   addrlen = size - slen;
1006   address.peer = *sender;
1007   address.address = addr;
1008   address.address_length = addrlen;
1009   address.transport_name = tname;
1010   ve = find_validation_entry (NULL, &address);
1011   if ((NULL == ve) || (ve->expecting_pong == GNUNET_NO))
1012   {
1013     GNUNET_STATISTICS_update (GST_stats,
1014                               gettext_noop
1015                               ("# PONGs dropped, no matching pending validation"),
1016                               1, GNUNET_NO);
1017     return;
1018   }
1019   /* now check that PONG is well-formed */
1020   if (0 != memcmp (&ve->pid, sender, sizeof (struct GNUNET_PeerIdentity)))
1021   {
1022     GNUNET_break_op (0);
1023     return;
1024   }
1025
1026   if (GNUNET_OK !=
1027       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
1028                                 &pong->purpose, &pong->signature,
1029                                 &ve->public_key))
1030   {
1031     GNUNET_break_op (0);
1032     return;
1033   }
1034
1035   if (GNUNET_TIME_absolute_get_remaining
1036       (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
1037   {
1038     GNUNET_STATISTICS_update (GST_stats,
1039                               gettext_noop
1040                               ("# PONGs dropped, signature expired"), 1,
1041                               GNUNET_NO);
1042     return;
1043   }
1044 #if DEBUG_TRANSPORT
1045   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1046               "Address validated for peer `%s' with plugin `%s': `%s'\n",
1047               GNUNET_i2s (sender), tname, GST_plugins_a2s (tname, addr,
1048                                                            addrlen));
1049 #endif
1050
1051   /* validity achieved, remember it! */
1052   ve->expecting_pong = GNUNET_NO;
1053   ve->valid_until = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
1054   ve->latency = GNUNET_TIME_absolute_get_duration (ve->send_time);
1055   {
1056     struct GNUNET_ATS_Information ats;
1057
1058     ats.type = htonl (GNUNET_ATS_QUALITY_NET_DELAY);
1059     ats.value = htonl ((uint32_t) ve->latency.rel_value);               
1060     GNUNET_ATS_address_update (GST_ats, ve->address, NULL, &ats, 1);
1061   }
1062   /* build HELLO to store in PEERINFO */
1063   ve->copied = GNUNET_NO;
1064   hello = GNUNET_HELLO_create (&ve->public_key, &add_valid_peer_address, ve);
1065   GNUNET_PEERINFO_add_peer (GST_peerinfo, hello);
1066   GNUNET_free (hello);
1067 }
1068
1069
1070 /**
1071  * We've received a HELLO, check which addresses are new and trigger
1072  * validation.
1073  *
1074  * @param hello the HELLO we received
1075  */
1076 void
1077 GST_validation_handle_hello (const struct GNUNET_MessageHeader *hello)
1078 {
1079   const struct GNUNET_HELLO_Message *hm =
1080       (const struct GNUNET_HELLO_Message *) hello;
1081   struct ValidateAddressContext vac;
1082   struct GNUNET_HELLO_Message *h;
1083
1084   if ((GNUNET_OK != GNUNET_HELLO_get_id (hm, &vac.pid)) ||
1085       (GNUNET_OK != GNUNET_HELLO_get_key (hm, &vac.public_key)))
1086   {
1087     /* malformed HELLO */
1088     GNUNET_break (0);
1089     return;
1090   }
1091   if (0 ==
1092       memcmp (&GST_my_identity, &vac.pid, sizeof (struct GNUNET_PeerIdentity)))
1093     return;
1094   /* Add peer identity without addresses to peerinfo service */
1095   h = GNUNET_HELLO_create (&vac.public_key, NULL, NULL);
1096   GNUNET_PEERINFO_add_peer (GST_peerinfo, h);
1097 #if VERBOSE_VALIDATION
1098   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1099               _("Adding `%s' without addresses for peer `%s'\n"), "HELLO",
1100               GNUNET_i2s (&vac.pid));
1101 #endif
1102   GNUNET_free (h);
1103   GNUNET_assert (NULL ==
1104                  GNUNET_HELLO_iterate_addresses (hm, GNUNET_NO,
1105                                                  &validate_address_iterator, &vac));
1106 }
1107
1108
1109 /**
1110  * Closure for 'iterate_addresses'
1111  */
1112 struct IteratorContext
1113 {
1114   /**
1115    * Function to call on each address.
1116    */
1117   GST_ValidationAddressCallback cb;
1118
1119   /**
1120    * Closure for 'cb'.
1121    */
1122   void *cb_cls;
1123
1124 };
1125
1126
1127 /**
1128  * Call the callback in the closure for each validation entry.
1129  *
1130  * @param cls the 'struct GST_ValidationIteratorContext'
1131  * @param key the peer's identity
1132  * @param value the 'struct ValidationEntry'
1133  * @return GNUNET_OK (continue to iterate)
1134  */
1135 static int
1136 iterate_addresses (void *cls, const GNUNET_HashCode * key, void *value)
1137 {
1138   struct IteratorContext *ic = cls;
1139   struct ValidationEntry *ve = value;
1140
1141   ic->cb (ic->cb_cls, &ve->public_key, ve->valid_until,
1142           ve->revalidation_block, ve->address);
1143   return GNUNET_OK;
1144 }
1145
1146
1147 /**
1148  * Call the given function for each address for the given target.
1149  * Can either give a snapshot (synchronous API) or be continuous.
1150  *
1151  * @param target peer information is requested for
1152  * @param cb function to call; will not be called after this function returns
1153  * @param cb_cls closure for 'cb'
1154  */
1155 void
1156 GST_validation_get_addresses (const struct GNUNET_PeerIdentity *target,
1157                               GST_ValidationAddressCallback cb, void *cb_cls)
1158 {
1159   struct IteratorContext ic;
1160
1161   ic.cb = cb;
1162   ic.cb_cls = cb_cls;
1163   GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1164                                               &target->hashPubKey,
1165                                               &iterate_addresses, &ic);
1166 }
1167
1168
1169 /**
1170  * Update if we are using an address for a connection actively right now.
1171  * Based on this, the validation module will measure latency for the
1172  * address more or less often.
1173  *
1174  * @param sender peer FIXME: redundant!
1175  * @param address the address
1176  * @param in_use GNUNET_YES if we are now using the address for a connection,
1177  *               GNUNET_NO if we are no longer using the address for a connection
1178  */
1179 void
1180 GST_validation_set_address_use (const struct GNUNET_PeerIdentity *sender,
1181                                 const struct GNUNET_HELLO_Address *address,
1182                                 struct Session *session,
1183                                 int in_use)
1184 {
1185   struct ValidationEntry *ve;
1186
1187   if (NULL != address)
1188     ve = find_validation_entry (NULL, address);
1189   else
1190     ve = NULL; /* FIXME: lookup based on session... */
1191   if (NULL == ve)
1192   {
1193     /* this can happen for inbound connections (sender_address_len == 0); */
1194     return;
1195   }
1196   if (ve->in_use == in_use)
1197     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1198         "GST_validation_set_address_use: %s %s: ve->in_use %i <-> in_use %i",
1199         GNUNET_i2s(sender),
1200         GST_plugins_a2s(address),
1201         ve->in_use,
1202         in_use);
1203   GNUNET_break (ve->in_use != in_use); /* should be different... */
1204   ve->in_use = in_use;
1205   if (in_use == GNUNET_YES)
1206   {
1207     /* from now on, higher frequeny, so reschedule now */
1208     GNUNET_SCHEDULER_cancel (ve->revalidation_task);
1209     ve->revalidation_task =
1210       GNUNET_SCHEDULER_add_now (&revalidate_address, ve);
1211   }
1212 }
1213
1214
1215 /**
1216  * Query validation about the latest observed latency on a given
1217  * address.
1218  *
1219  * @param sender peer
1220  * @param address the address
1221  * @param session session 
1222  * @return observed latency of the address, FOREVER if the address was
1223  *         never successfully validated
1224  */
1225 struct GNUNET_TIME_Relative
1226 GST_validation_get_address_latency (const struct GNUNET_PeerIdentity *sender,
1227                                     const struct GNUNET_HELLO_Address *address,
1228                                     struct Session *session)
1229 {
1230   struct ValidationEntry *ve;
1231
1232   if (NULL == address)
1233   {
1234     GNUNET_break (0); // FIXME: support having latency only with session...
1235     return GNUNET_TIME_UNIT_FOREVER_REL;
1236   }
1237   ve = find_validation_entry (NULL, address);
1238   if (NULL == ve)
1239     return GNUNET_TIME_UNIT_FOREVER_REL;
1240   return ve->latency;
1241 }
1242
1243
1244 /* end of file gnunet-service-transport_validation.c */