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