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