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