fix for 1819:
[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    * When passing the address in 'add_valid_peer_address', did we
222    * copy the address to the HELLO yet?
223    */
224   int copied;
225
226 };
227
228
229 /**
230  * Context of currently active requests to peerinfo
231  * for validation of HELLOs.
232  */
233 struct CheckHelloValidatedContext
234 {
235
236   /**
237    * This is a doubly-linked list.
238    */
239   struct CheckHelloValidatedContext *next;
240
241   /**
242    * This is a doubly-linked list.
243    */
244   struct CheckHelloValidatedContext *prev;
245
246   /**
247    * Hello that we are validating.
248    */
249   const struct GNUNET_HELLO_Message *hello;
250
251 };
252
253
254 /**
255  * Head of linked list of HELLOs awaiting validation.
256  */
257 static struct CheckHelloValidatedContext *chvc_head;
258
259 /**
260  * Tail of linked list of HELLOs awaiting validation
261  */
262 static struct CheckHelloValidatedContext *chvc_tail;
263
264 /**
265  * Map of PeerIdentities to 'struct ValidationEntry*'s (addresses
266  * of the given peer that we are currently validating, have validated
267  * or are blocked from re-validation for a while).
268  */
269 static struct GNUNET_CONTAINER_MultiHashMap *validation_map;
270
271 /**
272  * Context for peerinfo iteration.
273  */
274 static struct GNUNET_PEERINFO_NotifyContext *pnc;
275
276
277 /**
278  * Context for the validation entry match function.
279  */
280 struct ValidationEntryMatchContext
281 {
282   /**
283    * Where to store the result?
284    */
285   struct ValidationEntry *ve;
286
287   /**
288    * Transport name we're looking for.
289    */
290   const char *transport_name;
291
292   /**
293    * Address we're interested in.
294    */
295   const char *addr;
296
297   /**
298    * Number of bytes in 'addr'.
299    */
300   size_t addrlen;
301 };
302
303
304 /**
305  * Iterate over validation entries until a matching one is found.
306  *
307  * @param cls the 'struct ValidationEntryMatchContext'
308  * @param key peer identity (unused)
309  * @param value a 'struct ValidationEntry' to match
310  * @return GNUNET_YES if the entry does not match,
311  *         GNUNET_NO if the entry does match
312  */
313 static int
314 validation_entry_match (void *cls, const GNUNET_HashCode * key, void *value)
315 {
316   struct ValidationEntryMatchContext *vemc = cls;
317   struct ValidationEntry *ve = value;
318
319   if ((ve->addrlen == vemc->addrlen) &&
320       (0 == memcmp (ve->addr, vemc->addr, ve->addrlen)) &&
321       (0 == strcmp (ve->transport_name, vemc->transport_name)))
322   {
323     vemc->ve = ve;
324     return GNUNET_NO;
325   }
326   return GNUNET_YES;
327 }
328
329
330 /**
331  * Find a ValidationEntry entry for the given neighbour that matches
332  * the given address and transport.  If none exists, create one (but
333  * without starting any validation).
334  *
335  * @param public_key public key of the peer, NULL for unknown
336  * @param neighbour which peer we care about
337  * @param tname name of the transport plugin
338  * @param addr binary address
339  * @param addrlen length of addr
340  * @return validation entry matching the given specifications, NULL
341  *         if we don't have an existing entry and no public key was given
342  */
343 static struct ValidationEntry *
344 find_validation_entry (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
345                        *public_key, const struct GNUNET_PeerIdentity *neighbour,
346                        const char *tname, const char *addr, size_t addrlen)
347 {
348   struct ValidationEntryMatchContext vemc;
349   struct ValidationEntry *ve;
350
351   vemc.ve = NULL;
352   vemc.transport_name = tname;
353   vemc.addr = addr;
354   vemc.addrlen = addrlen;
355   GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
356                                               &neighbour->hashPubKey,
357                                               &validation_entry_match, &vemc);
358   if (NULL != (ve = vemc.ve))
359     return ve;
360   if (public_key == NULL)
361     return NULL;
362   ve = GNUNET_malloc (sizeof (struct ValidationEntry) + addrlen);
363   ve->transport_name = GNUNET_strdup (tname);
364   ve->addr = (void *) &ve[1];
365   ve->public_key = *public_key;
366   ve->pid = *neighbour;
367   ve->challenge =
368       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX);
369   memcpy (&ve[1], addr, addrlen);
370   ve->addrlen = addrlen;
371   GNUNET_CONTAINER_multihashmap_put (validation_map, &neighbour->hashPubKey, ve,
372                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
373   return ve;
374 }
375
376
377 /**
378  * Iterator which adds the given address to the set of validated
379  * addresses.
380  *
381  * @param cls original HELLO message
382  * @param tname name of the transport
383  * @param expiration expiration time
384  * @param addr the address
385  * @param addrlen length of the address
386  * @return GNUNET_OK (keep the address)
387  */
388 static int
389 add_valid_address (void *cls, const char *tname,
390                    struct GNUNET_TIME_Absolute expiration, const void *addr,
391                    uint16_t addrlen)
392 {
393   const struct GNUNET_HELLO_Message *hello = cls;
394   struct ValidationEntry *ve;
395   struct GNUNET_PeerIdentity pid;
396   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
397   struct GNUNET_TRANSPORT_ATS_Information ats;
398
399   if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value == 0)
400     return GNUNET_OK;           /* expired */
401   if ((GNUNET_OK != GNUNET_HELLO_get_id (hello, &pid)) ||
402       (GNUNET_OK != GNUNET_HELLO_get_key (hello, &public_key)))
403   {
404     GNUNET_break (0);
405     return GNUNET_OK;           /* invalid HELLO !? */
406   }
407   ve = find_validation_entry (&public_key, &pid, tname, addr, addrlen);
408   ve->valid_until = GNUNET_TIME_absolute_max (ve->valid_until, expiration);
409   ats.type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
410   ats.value = htonl (0);
411   GNUNET_ATS_address_update (GST_ats, &pid, ve->valid_until, tname, NULL, addr,
412                              addrlen, &ats, 1);
413   return GNUNET_OK;
414 }
415
416
417 /**
418  * Function called for any HELLO known to PEERINFO.
419  *
420  * @param cls unused
421  * @param peer id of the peer, NULL for last call
422  * @param hello hello message for the peer (can be NULL)
423  * @param err_msg error message
424  */
425 static void
426 process_peerinfo_hello (void *cls, const struct GNUNET_PeerIdentity *peer,
427                         const struct GNUNET_HELLO_Message *hello,
428                         const char *err_msg)
429 {
430   GNUNET_assert (NULL != peer);
431   if (NULL == hello)
432     return;
433   GNUNET_assert (NULL ==
434                  GNUNET_HELLO_iterate_addresses (hello, GNUNET_NO,
435                                                  &add_valid_address,
436                                                  (void *) hello));
437 }
438
439
440 /**
441  * Start the validation subsystem.
442  */
443 void
444 GST_validation_start ()
445 {
446   validation_map = GNUNET_CONTAINER_multihashmap_create (VALIDATION_MAP_SIZE);
447   pnc = GNUNET_PEERINFO_notify (GST_cfg, &process_peerinfo_hello, NULL);
448 }
449
450
451 /**
452  * Iterate over validation entries and free them.
453  *
454  * @param cls (unused)
455  * @param key peer identity (unused)
456  * @param value a 'struct ValidationEntry' to clean up
457  * @return GNUNET_YES (continue to iterate)
458  */
459 static int
460 cleanup_validation_entry (void *cls, const GNUNET_HashCode * key, void *value)
461 {
462   struct ValidationEntry *ve = value;
463
464   if (NULL != ve->bc)
465   {
466     GST_blacklist_test_cancel (ve->bc);
467     ve->bc = NULL;
468   }
469   GNUNET_break (GNUNET_OK ==
470                 GNUNET_CONTAINER_multihashmap_remove (validation_map,
471                                                       &ve->pid.hashPubKey, ve));
472   GNUNET_free (ve->transport_name);
473   if (GNUNET_SCHEDULER_NO_TASK != ve->timeout_task)
474   {
475     GNUNET_SCHEDULER_cancel (ve->timeout_task);
476     ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
477   }
478   GNUNET_free (ve);
479   return GNUNET_OK;
480 }
481
482
483 /**
484  * Stop the validation subsystem.
485  */
486 void
487 GST_validation_stop ()
488 {
489   struct CheckHelloValidatedContext *chvc;
490
491   GNUNET_CONTAINER_multihashmap_iterate (validation_map,
492                                          &cleanup_validation_entry, NULL);
493   GNUNET_CONTAINER_multihashmap_destroy (validation_map);
494   validation_map = NULL;
495   while (NULL != (chvc = chvc_head))
496   {
497     GNUNET_CONTAINER_DLL_remove (chvc_head, chvc_tail, chvc);
498     GNUNET_free (chvc);
499   }
500   GNUNET_PEERINFO_notify_cancel (pnc);
501 }
502
503
504 /**
505  * Address validation cleanup task (record no longer needed).
506  *
507  * @param cls the 'struct ValidationEntry'
508  * @param tc scheduler context (unused)
509  */
510 static void
511 timeout_hello_validation (void *cls,
512                           const struct GNUNET_SCHEDULER_TaskContext *tc)
513 {
514   struct ValidationEntry *ve = cls;
515
516   ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
517   GNUNET_STATISTICS_update (GST_stats,
518                             gettext_noop ("# address records discarded"), 1,
519                             GNUNET_NO);
520   cleanup_validation_entry (NULL, &ve->pid.hashPubKey, ve);
521 }
522
523
524 /**
525  * Send the given PONG to the given address.
526  *
527  * @param cls the PONG message
528  * @param public_key public key for the peer, never NULL
529  * @param target peer this change is about, never NULL
530  * @param valid_until is ZERO if we never validated the address,
531  *                    otherwise a time up to when we consider it (or was) valid
532  * @param validation_block  is FOREVER if the address is for an unsupported plugin (from PEERINFO)
533  *                          is ZERO if the address is considered valid (no validation needed)
534  *                          otherwise a time in the future if we're currently denying re-validation
535  * @param plugin_name name of the plugin
536  * @param plugin_address binary address
537  * @param plugin_address_len length of address
538  */
539 static void
540 multicast_pong (void *cls,
541                 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
542                 *public_key, const struct GNUNET_PeerIdentity *target,
543                 struct GNUNET_TIME_Absolute valid_until,
544                 struct GNUNET_TIME_Absolute validation_block,
545                 const char *plugin_name, const void *plugin_address,
546                 size_t plugin_address_len)
547 {
548   struct TransportPongMessage *pong = cls;
549   struct GNUNET_TRANSPORT_PluginFunctions *papi;
550
551   papi = GST_plugins_find (plugin_name);
552   if (papi == NULL)
553     return;
554   (void) papi->send (papi->cls, target, (const char *) pong,
555                      ntohs (pong->header.size), PONG_PRIORITY,
556                      HELLO_REVALIDATION_START_TIME, NULL, plugin_address,
557                      plugin_address_len, GNUNET_YES, NULL, NULL);
558 }
559
560
561 /**
562  * We've received a PING.  If appropriate, generate a PONG.
563  *
564  * @param sender peer sending the PING
565  * @param hdr the PING
566  * @param session session we got the PING from
567  * @param plugin_name name of plugin that received the PING
568  * @param sender_address address of the sender as known to the plugin, NULL
569  *                       if we did not initiate the connection
570  * @param sender_address_len number of bytes in sender_address
571  */
572 void
573 GST_validation_handle_ping (const struct GNUNET_PeerIdentity *sender,
574                             const struct GNUNET_MessageHeader *hdr,
575                             const char *plugin_name, struct Session *session,
576                             const void *sender_address,
577                             size_t sender_address_len)
578 {
579   const struct TransportPingMessage *ping;
580   struct TransportPongMessage *pong;
581   struct GNUNET_TRANSPORT_PluginFunctions *papi;
582   struct GNUNET_CRYPTO_RsaSignature *sig_cache;
583   struct GNUNET_TIME_Absolute *sig_cache_exp;
584   const char *addr;
585   const char *addrend;
586   size_t alen;
587   size_t slen;
588   ssize_t ret;
589
590   if (ntohs (hdr->size) < sizeof (struct TransportPingMessage))
591   {
592     GNUNET_break_op (0);
593     return;
594   }
595   ping = (const struct TransportPingMessage *) hdr;
596   if (0 !=
597       memcmp (&ping->target, &GST_my_identity,
598               sizeof (struct GNUNET_PeerIdentity)))
599   {
600     GNUNET_break_op (0);
601     return;
602   }
603   GNUNET_STATISTICS_update (GST_stats,
604                             gettext_noop ("# PING messages received"), 1,
605                             GNUNET_NO);
606   addr = (const char *) &ping[1];
607   alen = ntohs (hdr->size) - sizeof (struct TransportPingMessage);
608   /* peer wants to confirm that this is one of our addresses, this is what is
609    * used for address validation */
610
611   addrend = memchr (addr, '\0', alen);
612   if (NULL == addrend)
613   {
614     GNUNET_break_op (0);
615     return;
616   }
617   addrend++;
618   slen = strlen (addr) + 1;
619   alen -= slen;
620
621   if (GNUNET_YES !=
622       GST_hello_test_address (addr, addrend, alen, &sig_cache, &sig_cache_exp))
623   {
624     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
625                 _
626                 ("Not confirming PING with address `%s' since I cannot confirm having this address.\n"),
627                 GST_plugins_a2s (addr, addrend, alen));
628     return;
629   }
630
631   pong = GNUNET_malloc (sizeof (struct TransportPongMessage) + alen + slen);
632   pong->header.size =
633       htons (sizeof (struct TransportPongMessage) + alen + slen);
634   pong->header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PONG);
635   pong->purpose.size =
636       htonl (sizeof (struct GNUNET_CRYPTO_RsaSignaturePurpose) +
637              sizeof (uint32_t) + sizeof (struct GNUNET_TIME_AbsoluteNBO) +
638              alen + slen);
639   pong->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN);
640   pong->challenge = ping->challenge;
641   pong->addrlen = htonl (alen + slen);
642   memcpy (&pong[1], addr, slen);
643   memcpy (&((char *) &pong[1])[slen], addrend, alen);
644   if (GNUNET_TIME_absolute_get_remaining (*sig_cache_exp).rel_value <
645       PONG_SIGNATURE_LIFETIME.rel_value / 4)
646   {
647     /* create / update cached sig */
648 #if DEBUG_TRANSPORT
649     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
650                 "Creating PONG signature to indicate ownership.\n");
651 #endif
652     *sig_cache_exp = GNUNET_TIME_relative_to_absolute (PONG_SIGNATURE_LIFETIME);
653     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
654     GNUNET_assert (GNUNET_OK ==
655                    GNUNET_CRYPTO_rsa_sign (GST_my_private_key, &pong->purpose,
656                                            sig_cache));
657   }
658   else
659   {
660     pong->expiration = GNUNET_TIME_absolute_hton (*sig_cache_exp);
661   }
662   pong->signature = *sig_cache;
663
664   /* first see if the session we got this PING from can be used to transmit
665    * a response reliably */
666   papi = GST_plugins_find (plugin_name);
667   if (papi == NULL)
668     ret = -1;
669   else
670     ret =
671         papi->send (papi->cls, sender, (const char *) pong,
672                     ntohs (pong->header.size), PONG_PRIORITY,
673                     HELLO_REVALIDATION_START_TIME, session, sender_address,
674                     sender_address_len, GNUNET_SYSERR, NULL, NULL);
675   if (ret != -1)
676   {
677     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
678                 "Transmitted PONG to `%s' via reliable mechanism\n",
679                 GNUNET_i2s (sender));
680     /* done! */
681     GNUNET_STATISTICS_update (GST_stats,
682                               gettext_noop
683                               ("# PONGs unicast via reliable transport"), 1,
684                               GNUNET_NO);
685     GNUNET_free (pong);
686     return;
687   }
688
689   /* no reliable method found, try transmission via all known addresses */
690   GNUNET_STATISTICS_update (GST_stats,
691                             gettext_noop
692                             ("# PONGs multicast to all available addresses"), 1,
693                             GNUNET_NO);
694   GST_validation_get_addresses (sender, &multicast_pong, pong);
695   GNUNET_free (pong);
696 }
697
698
699 /**
700  * Context for the 'validate_address' function
701  */
702 struct ValidateAddressContext
703 {
704   /**
705    * Hash of the public key of the peer whose address is being validated.
706    */
707   struct GNUNET_PeerIdentity pid;
708
709   /**
710    * Public key of the peer whose address is being validated.
711    */
712   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded public_key;
713 };
714
715
716 /**
717  * Function called with the result from blacklisting.
718  * Send a PING to the other peer if a communication is allowed.
719  *
720  * @param cls ou r'struct ValidationEntry'
721  * @param pid identity of the other peer
722  * @param result GNUNET_OK if the connection is allowed, GNUNET_NO if not
723  */
724 static void
725 transmit_ping_if_allowed (void *cls, const struct GNUNET_PeerIdentity *pid,
726                           int result)
727 {
728   struct ValidationEntry *ve = cls;
729   struct TransportPingMessage ping;
730   struct GNUNET_TRANSPORT_PluginFunctions *papi;
731   const struct GNUNET_MessageHeader *hello;
732   ssize_t ret;
733   size_t tsize;
734   size_t slen;
735   uint16_t hsize;
736
737   ve->bc = NULL;
738   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Transmitting plain PING to `%s'\n",
739               GNUNET_i2s (pid));
740
741   slen = strlen (ve->transport_name) + 1;
742   hello = GST_hello_get ();
743   hsize = ntohs (hello->size);
744   tsize = sizeof (struct TransportPingMessage) + ve->addrlen + slen + hsize;
745
746   ping.header.size =
747       htons (sizeof (struct TransportPingMessage) + ve->addrlen + slen);
748   ping.header.type = htons (GNUNET_MESSAGE_TYPE_TRANSPORT_PING);
749   ping.challenge = htonl (ve->challenge);
750   ping.target = *pid;
751
752   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
753   {
754     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
755                 _
756                 ("Not transmitting `%s' with `%s', message too big (%u bytes!). This should not happen.\n"),
757                 "HELLO", "PING", (unsigned int) tsize);
758     /* message too big (!?), get rid of HELLO */
759     hsize = 0;
760     tsize = sizeof (struct TransportPingMessage) + ve->addrlen + slen + hsize;
761   }
762   {
763     char message_buf[tsize];
764
765     /* build message with structure:
766      *  [HELLO][TransportPingMessage][Transport name][Address] */
767     memcpy (message_buf, hello, hsize);
768     memcpy (&message_buf[hsize], &ping, sizeof (struct TransportPingMessage));
769     memcpy (&message_buf[sizeof (struct TransportPingMessage) + hsize],
770             ve->transport_name, slen);
771     memcpy (&message_buf[sizeof (struct TransportPingMessage) + slen + hsize],
772             ve->addr, ve->addrlen);
773     papi = GST_plugins_find (ve->transport_name);
774     if (papi == NULL)
775       ret = -1;
776     else
777     {
778       GNUNET_assert (papi->send != NULL);
779       ret =
780           papi->send (papi->cls, pid, message_buf, tsize, PING_PRIORITY,
781                       HELLO_REVALIDATION_START_TIME, NULL /* no session */ ,
782                       ve->addr, ve->addrlen, GNUNET_YES, NULL, NULL);
783     }
784   }
785   if (-1 != ret)
786   {
787     ve->send_time = GNUNET_TIME_absolute_get ();
788     GNUNET_STATISTICS_update (GST_stats,
789                               gettext_noop
790                               ("# PING without HELLO messages sent"), 1,
791                               GNUNET_NO);
792   }
793 }
794
795
796 /**
797  * Iterator callback to go over all addresses and try to validate them
798  * (unless blocked or already validated).
799  *
800  * @param cls pointer to a 'struct ValidateAddressContext'
801  * @param tname name of the transport
802  * @param expiration expiration time
803  * @param addr the address
804  * @param addrlen length of the address
805  * @return GNUNET_OK (keep the address)
806  */
807 static int
808 validate_address (void *cls, const char *tname,
809                   struct GNUNET_TIME_Absolute expiration, const void *addr,
810                   uint16_t addrlen)
811 {
812   const struct ValidateAddressContext *vac = cls;
813   const struct GNUNET_PeerIdentity *pid = &vac->pid;
814   struct ValidationEntry *ve;
815   struct GST_BlacklistCheck *bc;
816
817   if (GNUNET_TIME_absolute_get_remaining (expiration).rel_value == 0)
818     return GNUNET_OK;           /* expired */
819   ve = find_validation_entry (&vac->public_key, pid, tname, addr, addrlen);
820   if (GNUNET_TIME_absolute_get_remaining (ve->validation_block).rel_value > 0)
821     return GNUNET_OK;           /* blocked */
822   if ((GNUNET_SCHEDULER_NO_TASK != ve->timeout_task) &&
823       (GNUNET_TIME_absolute_get_remaining (ve->valid_until).rel_value > 0))
824     return GNUNET_OK;           /* revalidation task already scheduled & still  valid */
825   ve->validation_block =
826       GNUNET_TIME_relative_to_absolute (HELLO_REVALIDATION_START_TIME);
827   if (GNUNET_SCHEDULER_NO_TASK != ve->timeout_task)
828     GNUNET_SCHEDULER_cancel (ve->timeout_task);
829   ve->timeout_task =
830       GNUNET_SCHEDULER_add_delayed (HELLO_REVALIDATION_START_TIME,
831                                     &timeout_hello_validation, ve);
832   bc = GST_blacklist_test_allowed (pid, tname, &transmit_ping_if_allowed, ve);
833   if (NULL != bc)
834     ve->bc = bc;
835   return GNUNET_OK;
836 }
837
838
839 /**
840  * Do address validation again to keep address valid.
841  *
842  * @param cls the 'struct ValidationEntry'
843  * @param tc scheduler context (unused)
844  */
845 static void
846 revalidate_address (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
847 {
848   struct ValidationEntry *ve = cls;
849   struct GNUNET_TIME_Relative delay;
850   struct ValidateAddressContext vac;
851
852   ve->timeout_task = GNUNET_SCHEDULER_NO_TASK;
853   delay = GNUNET_TIME_absolute_get_remaining (ve->validation_block);
854   if (delay.rel_value > 0)
855   {
856     /* should wait a bit longer */
857     ve->timeout_task =
858         GNUNET_SCHEDULER_add_delayed (delay, &revalidate_address, ve);
859     return;
860   }
861   GNUNET_STATISTICS_update (GST_stats,
862                             gettext_noop ("# address revalidations started"), 1,
863                             GNUNET_NO);
864   vac.pid = ve->pid;
865   vac.public_key = ve->public_key;
866   validate_address (&vac, ve->transport_name, ve->valid_until, ve->addr,
867                     (uint16_t) ve->addrlen);
868 }
869
870
871 /**
872  * Add the validated peer address to the HELLO.
873  *
874  * @param cls the 'struct ValidationEntry' with the validated address
875  * @param max space in buf
876  * @param buf where to add the address
877  * @return number of bytes written, 0 to signal the
878  *         end of the iteration.
879  */
880 static size_t
881 add_valid_peer_address (void *cls, size_t max, void *buf)
882 {
883   struct ValidationEntry *ve = cls;
884
885   if (GNUNET_YES == ve->copied)
886     return 0;                   /* terminate */
887   ve->copied = GNUNET_YES;
888   return GNUNET_HELLO_add_address (ve->transport_name, ve->valid_until,
889                                    ve->addr, ve->addrlen, buf, max);
890 }
891
892
893 /**
894  * We've received a PONG.  Check if it matches a pending PING and
895  * mark the respective address as confirmed.
896  *
897  * @param sender peer sending the PONG
898  * @param hdr the PONG
899  */
900 void
901 GST_validation_handle_pong (const struct GNUNET_PeerIdentity *sender,
902                             const struct GNUNET_MessageHeader *hdr)
903 {
904   const struct TransportPongMessage *pong;
905   struct ValidationEntry *ve;
906   const char *tname;
907   const char *addr;
908   size_t addrlen;
909   size_t slen;
910   size_t size;
911   uint32_t rdelay;
912   struct GNUNET_TIME_Relative delay;
913   struct GNUNET_HELLO_Message *hello;
914
915   if (ntohs (hdr->size) < sizeof (struct TransportPongMessage))
916   {
917     GNUNET_break_op (0);
918     return;
919   }
920   GNUNET_STATISTICS_update (GST_stats,
921                             gettext_noop ("# PONG messages received"), 1,
922                             GNUNET_NO);
923
924   pong = (const struct TransportPongMessage *) hdr;
925   tname = (const char *) &pong[1];
926   size = ntohs (hdr->size) - sizeof (struct TransportPongMessage);
927   addr = memchr (tname, '\0', size);
928   if (NULL == addr)
929   {
930     GNUNET_break_op (0);
931     return;
932   }
933   addr++;
934   slen = strlen (tname) + 1;
935   addrlen = size - slen;
936
937   ve = find_validation_entry (NULL, sender, tname, addr, addrlen);
938
939   if (NULL == ve)
940   {
941     GNUNET_STATISTICS_update (GST_stats,
942                               gettext_noop
943                               ("# PONGs dropped, no matching pending validation"),
944                               1, GNUNET_NO);
945     return;
946   }
947   /* now check that PONG is well-formed */
948   if (0 != memcmp (&ve->pid, sender, sizeof (struct GNUNET_PeerIdentity)))
949   {
950     GNUNET_break_op (0);
951     return;
952   }
953
954   if (GNUNET_TIME_absolute_get_remaining
955       (GNUNET_TIME_absolute_ntoh (pong->expiration)).rel_value == 0)
956   {
957     GNUNET_STATISTICS_update (GST_stats,
958                               gettext_noop
959                               ("# PONGs dropped, signature expired"), 1,
960                               GNUNET_NO);
961     return;
962   }
963   if (GNUNET_OK !=
964       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
965                                 &pong->purpose, &pong->signature,
966                                 &ve->public_key))
967   {
968     GNUNET_break_op (0);
969     return;
970   }
971 #if DEBUG_TRANSPORT
972   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
973               "Address validated for peer `%s' with plugin `%s': `%s'\n",
974               GNUNET_i2s (sender), tname, GST_plugins_a2s (tname, addr,
975                                                            addrlen));
976 #endif
977
978   /* validity achieved, remember it! */
979   ve->valid_until = GNUNET_TIME_relative_to_absolute (HELLO_ADDRESS_EXPIRATION);
980   {
981     struct GNUNET_TRANSPORT_ATS_Information ats[2];
982
983     ats[0].type = htonl (GNUNET_TRANSPORT_ATS_QUALITY_NET_DELAY);
984     ats[0].value = htonl ((uint32_t) GNUNET_TIME_absolute_get_duration (ve->send_time).rel_value);
985     ats[1].type = htonl (GNUNET_TRANSPORT_ATS_ARRAY_TERMINATOR);
986     ats[1].value = htonl (0);
987     GNUNET_ATS_address_update (GST_ats, &ve->pid, ve->valid_until, 
988                                ve->transport_name, NULL, ve->addr, ve->addrlen, 
989                                ats, 2);
990   }
991   
992   /* build HELLO to store in PEERINFO */
993   ve->copied = GNUNET_NO;
994   hello = GNUNET_HELLO_create (&ve->public_key, &add_valid_peer_address, ve);
995   GNUNET_PEERINFO_add_peer (GST_peerinfo, hello);
996   GNUNET_free (hello);
997
998   if (GNUNET_SCHEDULER_NO_TASK != ve->timeout_task)
999     GNUNET_SCHEDULER_cancel (ve->timeout_task);
1000
1001   /* randomly delay by up to 1h to avoid   synchronous validations */
1002   rdelay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 60 * 60);
1003   delay =
1004       GNUNET_TIME_relative_add (HELLO_REVALIDATION_START_TIME,
1005                                 GNUNET_TIME_relative_multiply
1006                                 (GNUNET_TIME_UNIT_SECONDS, rdelay));
1007   ve->timeout_task =
1008       GNUNET_SCHEDULER_add_delayed (delay, &revalidate_address, ve);
1009 }
1010
1011
1012 /**
1013  * We've received a HELLO, check which addresses are new and trigger
1014  * validation.
1015  *
1016  * @param hello the HELLO we received
1017  */
1018 void
1019 GST_validation_handle_hello (const struct GNUNET_MessageHeader *hello)
1020 {
1021   const struct GNUNET_HELLO_Message *hm =
1022       (const struct GNUNET_HELLO_Message *) hello;
1023   struct ValidateAddressContext vac;
1024   struct GNUNET_HELLO_Message *h;
1025
1026   if ((GNUNET_OK != GNUNET_HELLO_get_id (hm, &vac.pid)) ||
1027       (GNUNET_OK != GNUNET_HELLO_get_key (hm, &vac.public_key)))
1028   {
1029     /* malformed HELLO */
1030     GNUNET_break (0);
1031     return;
1032   }
1033   /* Add peer identity without addresses to peerinfo service */
1034   h = GNUNET_HELLO_create (&vac.public_key, NULL, NULL);
1035   GNUNET_PEERINFO_add_peer (GST_peerinfo, h);
1036 #if VERBOSE_VALIDATION
1037   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1038               _
1039               ("Adding `%s' without addresses for peer `%s'\n"),
1040               "HELLO",
1041               GNUNET_i2s(&vac.pid));
1042 #endif
1043   GNUNET_free (h);
1044
1045   GNUNET_assert (NULL ==
1046                  GNUNET_HELLO_iterate_addresses (hm, GNUNET_NO,
1047                                                  &validate_address, &vac));
1048 }
1049
1050
1051 /**
1052  * Closure for 'iterate_addresses'
1053  */
1054 struct IteratorContext
1055 {
1056   /**
1057    * Function to call on each address.
1058    */
1059   GST_ValidationAddressCallback cb;
1060
1061   /**
1062    * Closure for 'cb'.
1063    */
1064   void *cb_cls;
1065
1066 };
1067
1068
1069 /**
1070  * Call the callback in the closure for each validation entry.
1071  *
1072  * @param cls the 'struct GST_ValidationIteratorContext'
1073  * @param key the peer's identity
1074  * @param value the 'struct ValidationEntry'
1075  * @return GNUNET_OK (continue to iterate)
1076  */
1077 static int
1078 iterate_addresses (void *cls, const GNUNET_HashCode * key, void *value)
1079 {
1080   struct IteratorContext *ic = cls;
1081   struct ValidationEntry *ve = value;
1082
1083   ic->cb (ic->cb_cls, &ve->public_key, &ve->pid, ve->valid_until,
1084           ve->validation_block, ve->transport_name, ve->addr, ve->addrlen);
1085   return GNUNET_OK;
1086 }
1087
1088
1089 /**
1090  * Call the given function for each address for the given target.
1091  * Can either give a snapshot (synchronous API) or be continuous.
1092  *
1093  * @param target peer information is requested for
1094  * @param cb function to call; will not be called after this function returns
1095  * @param cb_cls closure for 'cb'
1096  */
1097 void
1098 GST_validation_get_addresses (const struct GNUNET_PeerIdentity *target,
1099                               GST_ValidationAddressCallback cb, void *cb_cls)
1100 {
1101   struct IteratorContext ic;
1102
1103   ic.cb = cb;
1104   ic.cb_cls = cb_cls;
1105   GNUNET_CONTAINER_multihashmap_get_multiple (validation_map,
1106                                               &target->hashPubKey,
1107                                               &iterate_addresses, &ic);
1108 }
1109
1110
1111 /* end of file gnunet-service-transport_validation.c */