-actually enable logic to drop part of path to fit message size, check against correc...
[oweals/gnunet.git] / src / dht / gnunet-service-dht_neighbours.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009-2013 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 dht/gnunet-service-dht_neighbours.c
23  * @brief GNUnet DHT service's bucket and neighbour management code
24  * @author Christian Grothoff
25  * @author Nathan Evans
26  */
27
28 #include "platform.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet_block_lib.h"
31 #include "gnunet_hello_lib.h"
32 #include "gnunet_constants.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_nse_service.h"
35 #include "gnunet_ats_service.h"
36 #include "gnunet_core_service.h"
37 #include "gnunet_datacache_lib.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_hello_lib.h"
40 #include "gnunet_dht_service.h"
41 #include "gnunet_statistics_service.h"
42 #include "gnunet-service-dht.h"
43 #include "gnunet-service-dht_clients.h"
44 #include "gnunet-service-dht_datacache.h"
45 #include "gnunet-service-dht_hello.h"
46 #include "gnunet-service-dht_neighbours.h"
47 #include "gnunet-service-dht_nse.h"
48 #include "gnunet-service-dht_routing.h"
49 #include <fenv.h>
50 #include "dht.h"
51
52 #define LOG_TRAFFIC(kind,...) GNUNET_log_from (kind, "dht-traffic",__VA_ARGS__)
53
54 /**
55  * How many buckets will we allow total.
56  */
57 #define MAX_BUCKETS sizeof (struct GNUNET_HashCode) * 8
58
59 /**
60  * What is the maximum number of peers in a given bucket.
61  */
62 #define DEFAULT_BUCKET_SIZE 8
63
64 /**
65  * Desired replication level for FIND PEER requests
66  */
67 #define FIND_PEER_REPLICATION_LEVEL 4
68
69 /**
70  * Maximum allowed replication level for all requests.
71  */
72 #define MAXIMUM_REPLICATION_LEVEL 16
73
74 /**
75  * Maximum allowed number of pending messages per peer.
76  */
77 #define MAXIMUM_PENDING_PER_PEER 64
78
79 /**
80  * How often to update our preference levels for peers in our routing tables.
81  */
82 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
83
84 /**
85  * How long at least to wait before sending another find peer request.
86  */
87 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
88
89 /**
90  * How long at most to wait before sending another find peer request.
91  */
92 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10)
93
94 /**
95  * How long at most to wait for transmission of a GET request to another peer?
96  */
97 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
98
99 /**
100  * Hello address expiration
101  */
102 extern struct GNUNET_TIME_Relative hello_expiration;
103
104
105 GNUNET_NETWORK_STRUCT_BEGIN
106
107 /**
108  * P2P PUT message
109  */
110 struct PeerPutMessage
111 {
112   /**
113    * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
114    */
115   struct GNUNET_MessageHeader header;
116
117   /**
118    * Processing options
119    */
120   uint32_t options GNUNET_PACKED;
121
122   /**
123    * Content type.
124    */
125   uint32_t type GNUNET_PACKED;
126
127   /**
128    * Hop count
129    */
130   uint32_t hop_count GNUNET_PACKED;
131
132   /**
133    * Replication level for this message
134    */
135   uint32_t desired_replication_level GNUNET_PACKED;
136
137   /**
138    * Length of the PUT path that follows (if tracked).
139    */
140   uint32_t put_path_length GNUNET_PACKED;
141
142   /**
143    * When does the content expire?
144    */
145   struct GNUNET_TIME_AbsoluteNBO expiration_time;
146
147   /**
148    * Bloomfilter (for peer identities) to stop circular routes
149    */
150   char bloomfilter[DHT_BLOOM_SIZE];
151
152   /**
153    * The key we are storing under.
154    */
155   struct GNUNET_HashCode key;
156
157   /* put path (if tracked) */
158
159   /* Payload */
160
161 };
162
163
164 /**
165  * P2P Result message
166  */
167 struct PeerResultMessage
168 {
169   /**
170    * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
171    */
172   struct GNUNET_MessageHeader header;
173
174   /**
175    * Content type.
176    */
177   uint32_t type GNUNET_PACKED;
178
179   /**
180    * Length of the PUT path that follows (if tracked).
181    */
182   uint32_t put_path_length GNUNET_PACKED;
183
184   /**
185    * Length of the GET path that follows (if tracked).
186    */
187   uint32_t get_path_length GNUNET_PACKED;
188
189   /**
190    * When does the content expire?
191    */
192   struct GNUNET_TIME_AbsoluteNBO expiration_time;
193
194   /**
195    * The key of the corresponding GET request.
196    */
197   struct GNUNET_HashCode key;
198
199   /* put path (if tracked) */
200
201   /* get path (if tracked) */
202
203   /* Payload */
204
205 };
206
207
208 /**
209  * P2P GET message
210  */
211 struct PeerGetMessage
212 {
213   /**
214    * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_GET
215    */
216   struct GNUNET_MessageHeader header;
217
218   /**
219    * Processing options
220    */
221   uint32_t options GNUNET_PACKED;
222
223   /**
224    * Desired content type.
225    */
226   uint32_t type GNUNET_PACKED;
227
228   /**
229    * Hop count
230    */
231   uint32_t hop_count GNUNET_PACKED;
232
233   /**
234    * Desired replication level for this request.
235    */
236   uint32_t desired_replication_level GNUNET_PACKED;
237
238   /**
239    * Size of the extended query.
240    */
241   uint32_t xquery_size;
242
243   /**
244    * Bloomfilter mutator.
245    */
246   uint32_t bf_mutator;
247
248   /**
249    * Bloomfilter (for peer identities) to stop circular routes
250    */
251   char bloomfilter[DHT_BLOOM_SIZE];
252
253   /**
254    * The key we are looking for.
255    */
256   struct GNUNET_HashCode key;
257
258   /* xquery */
259
260   /* result bloomfilter */
261
262 };
263 GNUNET_NETWORK_STRUCT_END
264
265 /**
266  * Linked list of messages to send to a particular other peer.
267  */
268 struct P2PPendingMessage
269 {
270   /**
271    * Pointer to next item in the list
272    */
273   struct P2PPendingMessage *next;
274
275   /**
276    * Pointer to previous item in the list
277    */
278   struct P2PPendingMessage *prev;
279
280   /**
281    * Message importance level.  FIXME: used? useful?
282    */
283   unsigned int importance;
284
285   /**
286    * When does this message time out?
287    */
288   struct GNUNET_TIME_Absolute timeout;
289
290   /**
291    * Actual message to be sent, allocated at the end of the struct:
292    * // msg = (cast) &pm[1];
293    * // memcpy (&pm[1], data, len);
294    */
295   const struct GNUNET_MessageHeader *msg;
296
297 };
298
299
300 /**
301  * Entry for a peer in a bucket.
302  */
303 struct PeerInfo
304 {
305   /**
306    * Next peer entry (DLL)
307    */
308   struct PeerInfo *next;
309
310   /**
311    *  Prev peer entry (DLL)
312    */
313   struct PeerInfo *prev;
314
315   /**
316    * Count of outstanding messages for peer.
317    */
318   unsigned int pending_count;
319
320   /**
321    * Head of pending messages to be sent to this peer.
322    */
323   struct P2PPendingMessage *head;
324
325   /**
326    * Tail of pending messages to be sent to this peer.
327    */
328   struct P2PPendingMessage *tail;
329
330   /**
331    * Core handle for sending messages to this peer.
332    */
333   struct GNUNET_CORE_TransmitHandle *th;
334
335   /**
336    * Task for scheduling preference updates
337    */
338   GNUNET_SCHEDULER_TaskIdentifier preference_task;
339
340   /**
341    * What is the identity of the peer?
342    */
343   struct GNUNET_PeerIdentity id;
344
345 #if 0
346   /**
347    * What is the average latency for replies received?
348    */
349   struct GNUNET_TIME_Relative latency;
350
351   /**
352    * Transport level distance to peer.
353    */
354   unsigned int distance;
355 #endif
356
357 };
358
359
360 /**
361  * Peers are grouped into buckets.
362  */
363 struct PeerBucket
364 {
365   /**
366    * Head of DLL
367    */
368   struct PeerInfo *head;
369
370   /**
371    * Tail of DLL
372    */
373   struct PeerInfo *tail;
374
375   /**
376    * Number of peers in the bucket.
377    */
378   unsigned int peers_size;
379 };
380
381
382 /**
383  * Do we cache all results that we are routing in the local datacache?
384  */
385 static int cache_results;
386
387 /**
388  * Should routing details be logged to stderr (for debugging)?
389  */
390 static int log_route_details_stderr;
391
392 /**
393  * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
394  */
395 static unsigned int closest_bucket;
396
397 /**
398  * How many peers have we added since we sent out our last
399  * find peer request?
400  */
401 static unsigned int newly_found_peers;
402
403 /**
404  * Option for testing that disables the 'connect' function of the DHT.
405  */
406 static int disable_try_connect;
407
408 /**
409  * The buckets.  Array of size MAX_BUCKET_SIZE.  Offset 0 means 0 bits matching.
410  */
411 static struct PeerBucket k_buckets[MAX_BUCKETS];
412
413 /**
414  * Hash map of all known peers, for easy removal from k_buckets on disconnect.
415  */
416 static struct GNUNET_CONTAINER_MultiPeerMap *all_known_peers;
417
418 /**
419  * Maximum size for each bucket.
420  */
421 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
422
423 /**
424  * Task that sends FIND PEER requests.
425  */
426 static GNUNET_SCHEDULER_TaskIdentifier find_peer_task;
427
428 /**
429  * Identity of this peer.
430  */
431 static struct GNUNET_PeerIdentity my_identity;
432
433 /**
434  * Hash of the identity of this peer.
435  */
436 static struct GNUNET_HashCode my_identity_hash;
437
438 /**
439  * Handle to CORE.
440  */
441 static struct GNUNET_CORE_Handle *core_api;
442
443 /**
444  * Handle to ATS.
445  */
446 static struct GNUNET_ATS_PerformanceHandle *atsAPI;
447
448
449
450 /**
451  * Find the optimal bucket for this key.
452  *
453  * @param hc the hashcode to compare our identity to
454  * @return the proper bucket index, or GNUNET_SYSERR
455  *         on error (same hashcode)
456  */
457 static int
458 find_bucket (const struct GNUNET_HashCode *hc)
459 {
460   unsigned int bits;
461
462   bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, hc);
463   if (bits == MAX_BUCKETS)
464   {
465     /* How can all bits match? Got my own ID? */
466     GNUNET_break (0);
467     return GNUNET_SYSERR;
468   }
469   return MAX_BUCKETS - bits - 1;
470 }
471
472
473 /**
474  * Let GNUnet core know that we like the given peer.
475  *
476  * @param cls the `struct PeerInfo` of the peer
477  * @param tc scheduler context.
478  */
479 static void
480 update_core_preference (void *cls,
481                         const struct GNUNET_SCHEDULER_TaskContext *tc)
482 {
483   struct PeerInfo *peer = cls;
484   uint64_t preference;
485   unsigned int matching;
486   int bucket;
487   struct GNUNET_HashCode phash;
488
489   peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
490   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
491     return;
492   GNUNET_CRYPTO_hash (&peer->id,
493                       sizeof (struct GNUNET_PeerIdentity),
494                       &phash);
495   matching =
496       GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash,
497                                         &phash);
498   if (matching >= 64)
499     matching = 63;
500   bucket = find_bucket (&phash);
501   if (bucket == GNUNET_SYSERR)
502     preference = 0;
503   else
504   {
505     GNUNET_assert (k_buckets[bucket].peers_size != 0);
506     preference = (1LL << matching) / k_buckets[bucket].peers_size;
507   }
508   if (preference == 0)
509   {
510     peer->preference_task =
511         GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
512                                       &update_core_preference, peer);
513     return;
514   }
515   GNUNET_STATISTICS_update (GDS_stats,
516                             gettext_noop ("# Preference updates given to core"),
517                             1, GNUNET_NO);
518   GNUNET_ATS_performance_change_preference (atsAPI, &peer->id,
519                                 GNUNET_ATS_PREFERENCE_BANDWIDTH,
520                                 (double) preference, GNUNET_ATS_PREFERENCE_END);
521   peer->preference_task =
522       GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
523                                     &update_core_preference, peer);
524
525
526 }
527
528
529 /**
530  * Closure for 'add_known_to_bloom'.
531  */
532 struct BloomConstructorContext
533 {
534   /**
535    * Bloom filter under construction.
536    */
537   struct GNUNET_CONTAINER_BloomFilter *bloom;
538
539   /**
540    * Mutator to use.
541    */
542   uint32_t bf_mutator;
543 };
544
545
546 /**
547  * Add each of the peers we already know to the bloom filter of
548  * the request so that we don't get duplicate HELLOs.
549  *
550  * @param cls the 'struct BloomConstructorContext'.
551  * @param key peer identity to add to the bloom filter
552  * @param value value the peer information (unused)
553  * @return #GNUNET_YES (we should continue to iterate)
554  */
555 static int
556 add_known_to_bloom (void *cls,
557                     const struct GNUNET_PeerIdentity *key,
558                     void *value)
559 {
560   struct BloomConstructorContext *ctx = cls;
561   struct GNUNET_HashCode key_hash;
562   struct GNUNET_HashCode mh;
563
564   GNUNET_CRYPTO_hash (key, sizeof (struct GNUNET_PeerIdentity), &key_hash);
565   GNUNET_BLOCK_mingle_hash (&key_hash, ctx->bf_mutator, &mh);
566   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
567               "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
568               GNUNET_i2s (key), ctx->bf_mutator);
569   GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
570   return GNUNET_YES;
571 }
572
573
574 /**
575  * Task to send a find peer message for our own peer identifier
576  * so that we can find the closest peers in the network to ourselves
577  * and attempt to connect to them.
578  *
579  * @param cls closure for this task
580  * @param tc the context under which the task is running
581  */
582 static void
583 send_find_peer_message (void *cls,
584                         const struct GNUNET_SCHEDULER_TaskContext *tc)
585 {
586   struct GNUNET_TIME_Relative next_send_time;
587   struct BloomConstructorContext bcc;
588   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
589
590   find_peer_task = GNUNET_SCHEDULER_NO_TASK;
591   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
592     return;
593   if (newly_found_peers > bucket_size)
594   {
595     /* If we are finding many peers already, no need to send out our request right now! */
596     find_peer_task =
597         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
598                                       &send_find_peer_message, NULL);
599     newly_found_peers = 0;
600     return;
601   }
602   bcc.bf_mutator =
603       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
604   bcc.bloom =
605       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
606                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
607   GNUNET_CONTAINER_multipeermap_iterate (all_known_peers, &add_known_to_bloom,
608                                          &bcc);
609   GNUNET_STATISTICS_update (GDS_stats,
610                             gettext_noop ("# FIND PEER messages initiated"), 1,
611                             GNUNET_NO);
612   peer_bf =
613       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
614                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
615   // FIXME: pass priority!?
616   GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
617                              GNUNET_DHT_RO_FIND_PEER,
618                              FIND_PEER_REPLICATION_LEVEL, 0,
619                              &my_identity_hash, NULL, 0, bcc.bloom,
620                              bcc.bf_mutator, peer_bf);
621   GNUNET_CONTAINER_bloomfilter_free (peer_bf);
622   GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
623   /* schedule next round */
624   next_send_time.rel_value_us =
625       DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value_us +
626       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
627                                 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value_us /
628                                 (newly_found_peers + 1));
629   newly_found_peers = 0;
630   find_peer_task =
631       GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
632                                     NULL);
633 }
634
635
636 /**
637  * Method called whenever a peer connects.
638  *
639  * @param cls closure
640  * @param peer peer identity this notification is about
641  */
642 static void
643 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
644 {
645   struct PeerInfo *ret;
646   struct GNUNET_HashCode phash;
647   int peer_bucket;
648
649   /* Check for connect to self message */
650   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
651     return;
652   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
653               "Connected to %s\n",
654               GNUNET_i2s (peer));
655   if (GNUNET_YES ==
656       GNUNET_CONTAINER_multipeermap_contains (all_known_peers,
657                                               peer))
658   {
659     GNUNET_break (0);
660     return;
661   }
662   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), 1,
663                             GNUNET_NO);
664   GNUNET_CRYPTO_hash (peer,
665                       sizeof (struct GNUNET_PeerIdentity),
666                       &phash);
667   peer_bucket = find_bucket (&phash);
668   GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
669   ret = GNUNET_new (struct PeerInfo);
670 #if 0
671   ret->latency = latency;
672   ret->distance = distance;
673 #endif
674   ret->id = *peer;
675   GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
676                                     k_buckets[peer_bucket].tail, ret);
677   k_buckets[peer_bucket].peers_size++;
678   closest_bucket = GNUNET_MAX (closest_bucket, peer_bucket);
679   if ((peer_bucket > 0) && (k_buckets[peer_bucket].peers_size <= bucket_size))
680   {
681     ret->preference_task =
682         GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
683     newly_found_peers++;
684   }
685   GNUNET_assert (GNUNET_OK ==
686                  GNUNET_CONTAINER_multipeermap_put (all_known_peers,
687                                                     peer, ret,
688                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
689   if (1 == GNUNET_CONTAINER_multipeermap_size (all_known_peers) &&
690       (GNUNET_YES != disable_try_connect))
691   {
692     /* got a first connection, good time to start with FIND PEER requests... */
693     find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
694   }
695 }
696
697
698 /**
699  * Method called whenever a peer disconnects.
700  *
701  * @param cls closure
702  * @param peer peer identity this notification is about
703  */
704 static void
705 handle_core_disconnect (void *cls,
706                         const struct GNUNET_PeerIdentity *peer)
707 {
708   struct PeerInfo *to_remove;
709   int current_bucket;
710   struct P2PPendingMessage *pos;
711   unsigned int discarded;
712   struct GNUNET_HashCode phash;
713
714   /* Check for disconnect from self message */
715   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
716     return;
717   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
718               "Disconnected %s\n",
719               GNUNET_i2s (peer));
720   to_remove =
721       GNUNET_CONTAINER_multipeermap_get (all_known_peers, peer);
722   if (NULL == to_remove)
723   {
724     GNUNET_break (0);
725     return;
726   }
727   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), -1,
728                             GNUNET_NO);
729   GNUNET_assert (GNUNET_YES ==
730                  GNUNET_CONTAINER_multipeermap_remove (all_known_peers,
731                                                        peer,
732                                                        to_remove));
733   if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
734   {
735     GNUNET_SCHEDULER_cancel (to_remove->preference_task);
736     to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
737   }
738   GNUNET_CRYPTO_hash (peer,
739                       sizeof (struct GNUNET_PeerIdentity),
740                       &phash);
741   current_bucket = find_bucket (&phash);
742   GNUNET_assert (current_bucket >= 0);
743   GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
744                                k_buckets[current_bucket].tail, to_remove);
745   GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
746   k_buckets[current_bucket].peers_size--;
747   while ((closest_bucket > 0) && (k_buckets[closest_bucket].peers_size == 0))
748     closest_bucket--;
749
750   if (to_remove->th != NULL)
751   {
752     GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
753     to_remove->th = NULL;
754   }
755   discarded = 0;
756   while (NULL != (pos = to_remove->head))
757   {
758     GNUNET_CONTAINER_DLL_remove (to_remove->head, to_remove->tail, pos);
759     discarded++;
760     GNUNET_free (pos);
761   }
762   GNUNET_STATISTICS_update (GDS_stats,
763                             gettext_noop
764                             ("# Queued messages discarded (peer disconnected)"),
765                             discarded, GNUNET_NO);
766   GNUNET_free (to_remove);
767 }
768
769
770 /**
771  * Called when core is ready to send a message we asked for
772  * out to the destination.
773  *
774  * @param cls the 'struct PeerInfo' of the target peer
775  * @param size number of bytes available in buf
776  * @param buf where the callee should write the message
777  * @return number of bytes written to buf
778  */
779 static size_t
780 core_transmit_notify (void *cls, size_t size, void *buf)
781 {
782   struct PeerInfo *peer = cls;
783   char *cbuf = buf;
784   struct P2PPendingMessage *pending;
785   size_t off;
786   size_t msize;
787
788   peer->th = NULL;
789   while ((NULL != (pending = peer->head)) &&
790          (0 == GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value_us))
791   {
792     peer->pending_count--;
793     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
794     GNUNET_free (pending);
795   }
796   if (NULL == pending)
797   {
798     /* no messages pending */
799     return 0;
800   }
801   if (NULL == buf)
802   {
803     peer->th =
804         GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
805                                            GNUNET_CORE_PRIO_BEST_EFFORT,
806                                            GNUNET_TIME_absolute_get_remaining
807                                            (pending->timeout), &peer->id,
808                                            ntohs (pending->msg->size),
809                                            &core_transmit_notify, peer);
810     GNUNET_break (NULL != peer->th);
811     return 0;
812   }
813   off = 0;
814   while ((NULL != (pending = peer->head)) &&
815          (size - off >= (msize = ntohs (pending->msg->size))))
816   {
817     GNUNET_STATISTICS_update (GDS_stats,
818                               gettext_noop
819                               ("# Bytes transmitted to other peers"), msize,
820                               GNUNET_NO);
821     memcpy (&cbuf[off], pending->msg, msize);
822     off += msize;
823     peer->pending_count--;
824     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
825     GNUNET_free (pending);
826   }
827   if (peer->head != NULL)
828   {
829     peer->th =
830         GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
831                                            GNUNET_CORE_PRIO_BEST_EFFORT,
832                                            GNUNET_TIME_absolute_get_remaining
833                                            (pending->timeout), &peer->id, msize,
834                                            &core_transmit_notify, peer);
835     GNUNET_break (NULL != peer->th);
836   }
837   return off;
838 }
839
840
841 /**
842  * Transmit all messages in the peer's message queue.
843  *
844  * @param peer message queue to process
845  */
846 static void
847 process_peer_queue (struct PeerInfo *peer)
848 {
849   struct P2PPendingMessage *pending;
850
851   if (NULL == (pending = peer->head))
852     return;
853   if (NULL != peer->th)
854     return;
855   GNUNET_STATISTICS_update (GDS_stats,
856                             gettext_noop
857                             ("# Bytes of bandwidth requested from core"),
858                             ntohs (pending->msg->size), GNUNET_NO);
859   peer->th =
860       GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
861                                          GNUNET_CORE_PRIO_BEST_EFFORT,
862                                          GNUNET_TIME_absolute_get_remaining
863                                          (pending->timeout), &peer->id,
864                                          ntohs (pending->msg->size),
865                                          &core_transmit_notify, peer);
866   GNUNET_break (NULL != peer->th);
867 }
868
869
870 /**
871  * To how many peers should we (on average) forward the request to
872  * obtain the desired target_replication count (on average).
873  *
874  * @param hop_count number of hops the message has traversed
875  * @param target_replication the number of total paths desired
876  * @return Some number of peers to forward the message to
877  */
878 static unsigned int
879 get_forward_count (uint32_t hop_count, uint32_t target_replication)
880 {
881   uint32_t random_value;
882   uint32_t forward_count;
883   float target_value;
884
885   if (hop_count > GDS_NSE_get () * 4.0)
886   {
887     /* forcefully terminate */
888     GNUNET_STATISTICS_update (GDS_stats,
889                               gettext_noop ("# requests TTL-dropped"),
890                               1, GNUNET_NO);
891     return 0;
892   }
893   if (hop_count > GDS_NSE_get () * 2.0)
894   {
895     /* Once we have reached our ideal number of hops, only forward to 1 peer */
896     return 1;
897   }
898   /* bound by system-wide maximum */
899   target_replication =
900       GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
901   target_value =
902       1 + (target_replication - 1.0) / (GDS_NSE_get () +
903                                         ((float) (target_replication - 1.0) *
904                                          hop_count));
905   /* Set forward count to floor of target_value */
906   forward_count = (uint32_t) target_value;
907   /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
908   target_value = target_value - forward_count;
909   random_value =
910       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
911   if (random_value < (target_value * UINT32_MAX))
912     forward_count++;
913   return forward_count;
914 }
915
916
917 /**
918  * Compute the distance between have and target as a 32-bit value.
919  * Differences in the lower bits must count stronger than differences
920  * in the higher bits.
921  *
922  * @param target
923  * @param have
924  * @return 0 if have==target, otherwise a number
925  *           that is larger as the distance between
926  *           the two hash codes increases
927  */
928 static unsigned int
929 get_distance (const struct GNUNET_HashCode *target,
930               const struct GNUNET_HashCode *have)
931 {
932   unsigned int bucket;
933   unsigned int msb;
934   unsigned int lsb;
935   unsigned int i;
936
937   /* We have to represent the distance between two 2^9 (=512)-bit
938    * numbers as a 2^5 (=32)-bit number with "0" being used for the
939    * two numbers being identical; furthermore, we need to
940    * guarantee that a difference in the number of matching
941    * bits is always represented in the result.
942    *
943    * We use 2^32/2^9 numerical values to distinguish between
944    * hash codes that have the same LSB bit distance and
945    * use the highest 2^9 bits of the result to signify the
946    * number of (mis)matching LSB bits; if we have 0 matching
947    * and hence 512 mismatching LSB bits we return -1 (since
948    * 512 itself cannot be represented with 9 bits) */
949
950   /* first, calculate the most significant 9 bits of our
951    * result, aka the number of LSBs */
952   bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
953   /* bucket is now a value between 0 and 512 */
954   if (bucket == 512)
955     return 0;                   /* perfect match */
956   if (bucket == 0)
957     return (unsigned int) -1;   /* LSB differs; use max (if we did the bit-shifting
958                                  * below, we'd end up with max+1 (overflow)) */
959
960   /* calculate the most significant bits of the final result */
961   msb = (512 - bucket) << (32 - 9);
962   /* calculate the 32-9 least significant bits of the final result by
963    * looking at the differences in the 32-9 bits following the
964    * mismatching bit at 'bucket' */
965   lsb = 0;
966   for (i = bucket + 1;
967        (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
968   {
969     if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
970         GNUNET_CRYPTO_hash_get_bit (have, i))
971       lsb |= (1 << (bucket + 32 - 9 - i));      /* first bit set will be 10,
972                                                  * last bit set will be 31 -- if
973                                                  * i does not reach 512 first... */
974   }
975   return msb | lsb;
976 }
977
978
979 /**
980  * Check whether my identity is closer than any known peers.  If a
981  * non-null bloomfilter is given, check if this is the closest peer
982  * that hasn't already been routed to.
983  *
984  * @param key hash code to check closeness to
985  * @param bloom bloomfilter, exclude these entries from the decision
986  * @return #GNUNET_YES if node location is closest,
987  *         #GNUNET_NO otherwise.
988  */
989 static int
990 am_closest_peer (const struct GNUNET_HashCode *key,
991                  const struct GNUNET_CONTAINER_BloomFilter *bloom)
992 {
993   int bits;
994   int other_bits;
995   int bucket_num;
996   int count;
997   struct PeerInfo *pos;
998   struct GNUNET_HashCode phash;
999
1000   if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1001     return GNUNET_YES;
1002   bucket_num = find_bucket (key);
1003   GNUNET_assert (bucket_num >= 0);
1004   bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, key);
1005   pos = k_buckets[bucket_num].head;
1006   count = 0;
1007   while ((pos != NULL) && (count < bucket_size))
1008   {
1009     GNUNET_CRYPTO_hash (&pos->id,
1010                         sizeof (struct GNUNET_PeerIdentity),
1011                         &phash);
1012     if ((bloom != NULL) &&
1013         (GNUNET_YES ==
1014          GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1015     {
1016       pos = pos->next;
1017       continue;                 /* Skip already checked entries */
1018     }
1019     other_bits = GNUNET_CRYPTO_hash_matching_bits (&phash, key);
1020     if (other_bits > bits)
1021       return GNUNET_NO;
1022     if (other_bits == bits)     /* We match the same number of bits */
1023       return GNUNET_YES;
1024     pos = pos->next;
1025   }
1026   /* No peers closer, we are the closest! */
1027   return GNUNET_YES;
1028 }
1029
1030
1031 /**
1032  * Select a peer from the routing table that would be a good routing
1033  * destination for sending a message for "key".  The resulting peer
1034  * must not be in the set of blocked peers.<p>
1035  *
1036  * Note that we should not ALWAYS select the closest peer to the
1037  * target, peers further away from the target should be chosen with
1038  * exponentially declining probability.
1039  *
1040  * FIXME: double-check that this is fine
1041  *
1042  *
1043  * @param key the key we are selecting a peer to route to
1044  * @param bloom a bloomfilter containing entries this request has seen already
1045  * @param hops how many hops has this message traversed thus far
1046  * @return Peer to route to, or NULL on error
1047  */
1048 static struct PeerInfo *
1049 select_peer (const struct GNUNET_HashCode * key,
1050              const struct GNUNET_CONTAINER_BloomFilter *bloom, uint32_t hops)
1051 {
1052   unsigned int bc;
1053   unsigned int count;
1054   unsigned int selected;
1055   struct PeerInfo *pos;
1056   unsigned int dist;
1057   unsigned int smallest_distance;
1058   struct PeerInfo *chosen;
1059   struct GNUNET_HashCode phash;
1060
1061   if (hops >= GDS_NSE_get ())
1062   {
1063     /* greedy selection (closest peer that is not in bloomfilter) */
1064     smallest_distance = UINT_MAX;
1065     chosen = NULL;
1066     for (bc = 0; bc <= closest_bucket; bc++)
1067     {
1068       pos = k_buckets[bc].head;
1069       count = 0;
1070       while ((pos != NULL) && (count < bucket_size))
1071       {
1072         GNUNET_CRYPTO_hash (&pos->id,
1073                             sizeof (struct GNUNET_PeerIdentity),
1074                             &phash);
1075         if ((bloom == NULL) ||
1076             (GNUNET_NO ==
1077              GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1078         {
1079           dist = get_distance (key, &phash);
1080           if (dist < smallest_distance)
1081           {
1082             chosen = pos;
1083             smallest_distance = dist;
1084           }
1085         }
1086         else
1087         {
1088           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1089                       "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1090                       GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1091           GNUNET_STATISTICS_update (GDS_stats,
1092                                     gettext_noop
1093                                     ("# Peers excluded from routing due to Bloomfilter"),
1094                                     1, GNUNET_NO);
1095           dist = get_distance (key, &phash);
1096           if (dist < smallest_distance)
1097           {
1098             chosen = NULL;
1099             smallest_distance = dist;
1100           }
1101         }
1102         count++;
1103         pos = pos->next;
1104       }
1105     }
1106     if (NULL == chosen)
1107       GNUNET_STATISTICS_update (GDS_stats,
1108                                 gettext_noop ("# Peer selection failed"), 1,
1109                                 GNUNET_NO);
1110     return chosen;
1111   }
1112
1113   /* select "random" peer */
1114   /* count number of peers that are available and not filtered */
1115   count = 0;
1116   for (bc = 0; bc <= closest_bucket; bc++)
1117   {
1118     pos = k_buckets[bc].head;
1119     while ((pos != NULL) && (count < bucket_size))
1120     {
1121       GNUNET_CRYPTO_hash (&pos->id,
1122                           sizeof (struct GNUNET_PeerIdentity),
1123                           &phash);
1124       if ((bloom != NULL) &&
1125           (GNUNET_YES ==
1126            GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1127       {
1128         GNUNET_STATISTICS_update (GDS_stats,
1129                                   gettext_noop
1130                                   ("# Peers excluded from routing due to Bloomfilter"),
1131                                   1, GNUNET_NO);
1132         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1133                     "Excluded peer `%s' due to BF match in random routing for %s\n",
1134                     GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1135         pos = pos->next;
1136         continue;               /* Ignore bloomfiltered peers */
1137       }
1138       count++;
1139       pos = pos->next;
1140     }
1141   }
1142   if (0 == count)               /* No peers to select from! */
1143   {
1144     GNUNET_STATISTICS_update (GDS_stats,
1145                               gettext_noop ("# Peer selection failed"), 1,
1146                               GNUNET_NO);
1147     return NULL;
1148   }
1149   /* Now actually choose a peer */
1150   selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1151   count = 0;
1152   for (bc = 0; bc <= closest_bucket; bc++)
1153   {
1154     for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next)
1155     {
1156       GNUNET_CRYPTO_hash (&pos->id,
1157                           sizeof (struct GNUNET_PeerIdentity),
1158                           &phash);
1159       if ((bloom != NULL) &&
1160           (GNUNET_YES ==
1161            GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1162       {
1163         continue;               /* Ignore bloomfiltered peers */
1164       }
1165       if (0 == selected--)
1166         return pos;
1167     }
1168   }
1169   GNUNET_break (0);
1170   return NULL;
1171 }
1172
1173
1174 /**
1175  * Compute the set of peers that the given request should be
1176  * forwarded to.
1177  *
1178  * @param key routing key
1179  * @param bloom bloom filter excluding peers as targets, all selected
1180  *        peers will be added to the bloom filter
1181  * @param hop_count number of hops the request has traversed so far
1182  * @param target_replication desired number of replicas
1183  * @param targets where to store an array of target peers (to be
1184  *         free'd by the caller)
1185  * @return number of peers returned in 'targets'.
1186  */
1187 static unsigned int
1188 get_target_peers (const struct GNUNET_HashCode *key,
1189                   struct GNUNET_CONTAINER_BloomFilter *bloom,
1190                   uint32_t hop_count, uint32_t target_replication,
1191                   struct PeerInfo ***targets)
1192 {
1193   unsigned int ret;
1194   unsigned int off;
1195   struct PeerInfo **rtargets;
1196   struct PeerInfo *nxt;
1197   struct GNUNET_HashCode nhash;
1198
1199   GNUNET_assert (NULL != bloom);
1200   ret = get_forward_count (hop_count, target_replication);
1201   if (0 == ret)
1202   {
1203     *targets = NULL;
1204     return 0;
1205   }
1206   rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1207   for (off = 0; off < ret; off++)
1208   {
1209     nxt = select_peer (key, bloom, hop_count);
1210     if (NULL == nxt)
1211       break;
1212     rtargets[off] = nxt;
1213     GNUNET_CRYPTO_hash (&nxt->id,
1214                         sizeof (struct GNUNET_PeerIdentity),
1215                         &nhash);
1216     GNUNET_break (GNUNET_NO ==
1217                   GNUNET_CONTAINER_bloomfilter_test (bloom,
1218                                                      &nhash));
1219     GNUNET_CONTAINER_bloomfilter_add (bloom, &nhash);
1220   }
1221   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1222               "Selected %u/%u peers at hop %u for %s (target was %u)\n", off,
1223               GNUNET_CONTAINER_multipeermap_size (all_known_peers),
1224               (unsigned int) hop_count, GNUNET_h2s (key), ret);
1225   if (0 == off)
1226   {
1227     GNUNET_free (rtargets);
1228     *targets = NULL;
1229     return 0;
1230   }
1231   *targets = rtargets;
1232   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1233               "Forwarding query `%s' to %u peers (goal was %u peers)\n",
1234               GNUNET_h2s (key),
1235               off,
1236               ret);
1237   return off;
1238 }
1239
1240
1241 /**
1242  * Perform a PUT operation.   Forwards the given request to other
1243  * peers.   Does not store the data locally.  Does not give the
1244  * data to local clients.  May do nothing if this is the only
1245  * peer in the network (or if we are the closest peer in the
1246  * network).
1247  *
1248  * @param type type of the block
1249  * @param options routing options
1250  * @param desired_replication_level desired replication count
1251  * @param expiration_time when does the content expire
1252  * @param hop_count how many hops has this message traversed so far
1253  * @param bf Bloom filter of peers this PUT has already traversed
1254  * @param key key for the content
1255  * @param put_path_length number of entries in @a put_path
1256  * @param put_path peers this request has traversed so far (if tracked)
1257  * @param data payload to store
1258  * @param data_size number of bytes in @a data
1259  * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1260  */
1261 int
1262 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1263                            enum GNUNET_DHT_RouteOption options,
1264                            uint32_t desired_replication_level,
1265                            struct GNUNET_TIME_Absolute expiration_time,
1266                            uint32_t hop_count,
1267                            struct GNUNET_CONTAINER_BloomFilter *bf,
1268                            const struct GNUNET_HashCode *key,
1269                            unsigned int put_path_length,
1270                            struct GNUNET_PeerIdentity *put_path,
1271                            const void *data, size_t data_size)
1272 {
1273   unsigned int target_count;
1274   unsigned int i;
1275   struct PeerInfo **targets;
1276   struct PeerInfo *target;
1277   struct P2PPendingMessage *pending;
1278   size_t msize;
1279   struct PeerPutMessage *ppm;
1280   struct GNUNET_PeerIdentity *pp;
1281   struct GNUNET_HashCode thash;
1282   unsigned int skip_count;
1283
1284   GNUNET_assert (NULL != bf);
1285   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1286               "Adding myself (%s) to PUT bloomfilter for %s\n",
1287               GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1288   GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity_hash);
1289   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1290                             1, GNUNET_NO);
1291   target_count =
1292       get_target_peers (key, bf, hop_count, desired_replication_level,
1293                         &targets);
1294   if (0 == target_count)
1295   {
1296     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1297                 "Routing PUT for %s terminates after %u hops at %s\n",
1298                 GNUNET_h2s (key), (unsigned int) hop_count,
1299                 GNUNET_i2s (&my_identity));
1300     return GNUNET_NO;
1301   }
1302   msize =
1303       put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1304       sizeof (struct PeerPutMessage);
1305   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1306   {
1307     put_path_length = 0;
1308     msize = data_size + sizeof (struct PeerPutMessage);
1309   }
1310   if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1311   {
1312     GNUNET_break (0);
1313     GNUNET_free (targets);
1314     return GNUNET_NO;
1315   }
1316   GNUNET_STATISTICS_update (GDS_stats,
1317                             gettext_noop
1318                             ("# PUT messages queued for transmission"),
1319                             target_count, GNUNET_NO);
1320   skip_count = 0;
1321   for (i = 0; i < target_count; i++)
1322   {
1323     target = targets[i];
1324     if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1325     {
1326       /* skip */
1327       GNUNET_STATISTICS_update (GDS_stats,
1328                                 gettext_noop ("# P2P messages dropped due to full queue"),
1329                                 1, GNUNET_NO);
1330       skip_count++;
1331       continue;
1332     }
1333     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1334                 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1335                 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1336     pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1337     pending->importance = 0;    /* FIXME */
1338     pending->timeout = expiration_time;
1339     ppm = (struct PeerPutMessage *) &pending[1];
1340     pending->msg = &ppm->header;
1341     ppm->header.size = htons (msize);
1342     ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1343     ppm->options = htonl (options);
1344     ppm->type = htonl (type);
1345     ppm->hop_count = htonl (hop_count + 1);
1346     ppm->desired_replication_level = htonl (desired_replication_level);
1347     ppm->put_path_length = htonl (put_path_length);
1348     ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1349     GNUNET_CRYPTO_hash (&target->id,
1350                         sizeof (struct GNUNET_PeerIdentity),
1351                         &thash);
1352     GNUNET_break (GNUNET_YES ==
1353                   GNUNET_CONTAINER_bloomfilter_test (bf,
1354                                                      &thash));
1355     GNUNET_assert (GNUNET_OK ==
1356                    GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1357                                                               ppm->bloomfilter,
1358                                                               DHT_BLOOM_SIZE));
1359     ppm->key = *key;
1360     pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1361     memcpy (pp, put_path,
1362             sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1363     memcpy (&pp[put_path_length], data, data_size);
1364     GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1365     target->pending_count++;
1366     process_peer_queue (target);
1367   }
1368   GNUNET_free (targets);
1369   return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1370 }
1371
1372
1373 /**
1374  * Perform a GET operation.  Forwards the given request to other
1375  * peers.  Does not lookup the key locally.  May do nothing if this is
1376  * the only peer in the network (or if we are the closest peer in the
1377  * network).
1378  *
1379  * @param type type of the block
1380  * @param options routing options
1381  * @param desired_replication_level desired replication count
1382  * @param hop_count how many hops did this request traverse so far?
1383  * @param key key for the content
1384  * @param xquery extended query
1385  * @param xquery_size number of bytes in @a xquery
1386  * @param reply_bf bloomfilter to filter duplicates
1387  * @param reply_bf_mutator mutator for @a reply_bf
1388  * @param peer_bf filter for peers not to select (again)
1389  * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1390  */
1391 int
1392 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1393                            enum GNUNET_DHT_RouteOption options,
1394                            uint32_t desired_replication_level,
1395                            uint32_t hop_count, const struct GNUNET_HashCode * key,
1396                            const void *xquery, size_t xquery_size,
1397                            const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1398                            uint32_t reply_bf_mutator,
1399                            struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1400 {
1401   unsigned int target_count;
1402   unsigned int i;
1403   struct PeerInfo **targets;
1404   struct PeerInfo *target;
1405   struct P2PPendingMessage *pending;
1406   size_t msize;
1407   struct PeerGetMessage *pgm;
1408   char *xq;
1409   size_t reply_bf_size;
1410   struct GNUNET_HashCode thash;
1411   unsigned int skip_count;
1412
1413   GNUNET_assert (NULL != peer_bf);
1414   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1415                             1, GNUNET_NO);
1416   target_count =
1417       get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1418                         &targets);
1419   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1420               "Adding myself (%s) to GET bloomfilter for %s\n",
1421               GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1422   GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity_hash);
1423   if (0 == target_count)
1424   {
1425     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1426                 "Routing GET for %s terminates after %u hops at %s\n",
1427                 GNUNET_h2s (key), (unsigned int) hop_count,
1428                 GNUNET_i2s (&my_identity));
1429     return GNUNET_NO;
1430   }
1431   reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1432   msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1433   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1434   {
1435     GNUNET_break (0);
1436     GNUNET_free (targets);
1437     return GNUNET_NO;
1438   }
1439   GNUNET_STATISTICS_update (GDS_stats,
1440                             gettext_noop
1441                             ("# GET messages queued for transmission"),
1442                             target_count, GNUNET_NO);
1443   /* forward request */
1444   skip_count = 0;
1445   for (i = 0; i < target_count; i++)
1446   {
1447     target = targets[i];
1448     if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1449     {
1450       /* skip */
1451       GNUNET_STATISTICS_update (GDS_stats,
1452                                 gettext_noop ("# P2P messages dropped due to full queue"),
1453                                 1, GNUNET_NO);
1454       skip_count++;
1455       continue;
1456     }
1457     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1458                 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1459                 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1460     pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1461     pending->importance = 0;    /* FIXME */
1462     pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1463     pgm = (struct PeerGetMessage *) &pending[1];
1464     pending->msg = &pgm->header;
1465     pgm->header.size = htons (msize);
1466     pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1467     pgm->options = htonl (options);
1468     pgm->type = htonl (type);
1469     pgm->hop_count = htonl (hop_count + 1);
1470     pgm->desired_replication_level = htonl (desired_replication_level);
1471     pgm->xquery_size = htonl (xquery_size);
1472     pgm->bf_mutator = reply_bf_mutator;
1473     GNUNET_CRYPTO_hash (&target->id,
1474                         sizeof (struct GNUNET_PeerIdentity),
1475                         &thash);
1476     GNUNET_break (GNUNET_YES ==
1477                   GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1478                                                      &thash));
1479     GNUNET_assert (GNUNET_OK ==
1480                    GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1481                                                               pgm->bloomfilter,
1482                                                               DHT_BLOOM_SIZE));
1483     pgm->key = *key;
1484     xq = (char *) &pgm[1];
1485     memcpy (xq, xquery, xquery_size);
1486     if (NULL != reply_bf)
1487       GNUNET_assert (GNUNET_OK ==
1488                      GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1489                                                                 &xq
1490                                                                 [xquery_size],
1491                                                                 reply_bf_size));
1492     GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1493     target->pending_count++;
1494     process_peer_queue (target);
1495   }
1496   GNUNET_free (targets);
1497   return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1498 }
1499
1500
1501 /**
1502  * Handle a reply (route to origin).  Only forwards the reply back to
1503  * the given peer.  Does not do local caching or forwarding to local
1504  * clients.
1505  *
1506  * @param target neighbour that should receive the block (if still connected)
1507  * @param type type of the block
1508  * @param expiration_time when does the content expire
1509  * @param key key for the content
1510  * @param put_path_length number of entries in @a put_path
1511  * @param put_path peers the original PUT traversed (if tracked)
1512  * @param get_path_length number of entries in @a get_path
1513  * @param get_path peers this reply has traversed so far (if tracked)
1514  * @param data payload of the reply
1515  * @param data_size number of bytes in @a data
1516  */
1517 void
1518 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1519                              enum GNUNET_BLOCK_Type type,
1520                              struct GNUNET_TIME_Absolute expiration_time,
1521                              const struct GNUNET_HashCode * key,
1522                              unsigned int put_path_length,
1523                              const struct GNUNET_PeerIdentity *put_path,
1524                              unsigned int get_path_length,
1525                              const struct GNUNET_PeerIdentity *get_path,
1526                              const void *data, size_t data_size)
1527 {
1528   struct PeerInfo *pi;
1529   struct P2PPendingMessage *pending;
1530   size_t msize;
1531   struct PeerResultMessage *prm;
1532   struct GNUNET_PeerIdentity *paths;
1533
1534   msize =
1535       data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1536                                                        put_path_length) *
1537       sizeof (struct GNUNET_PeerIdentity);
1538   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1539       (get_path_length >
1540        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1541       (put_path_length >
1542        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1543       (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1544   {
1545     GNUNET_break (0);
1546     return;
1547   }
1548   pi = GNUNET_CONTAINER_multipeermap_get (all_known_peers, target);
1549   if (NULL == pi)
1550   {
1551     /* peer disconnected in the meantime, drop reply */
1552     return;
1553   }
1554   if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1555   {
1556     /* skip */
1557     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1558                               1, GNUNET_NO);
1559     return;
1560   }
1561
1562   GNUNET_STATISTICS_update (GDS_stats,
1563                             gettext_noop
1564                             ("# RESULT messages queued for transmission"), 1,
1565                             GNUNET_NO);
1566   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1567   pending->importance = 0;      /* FIXME */
1568   pending->timeout = expiration_time;
1569   prm = (struct PeerResultMessage *) &pending[1];
1570   pending->msg = &prm->header;
1571   prm->header.size = htons (msize);
1572   prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1573   prm->type = htonl (type);
1574   prm->put_path_length = htonl (put_path_length);
1575   prm->get_path_length = htonl (get_path_length);
1576   prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1577   prm->key = *key;
1578   paths = (struct GNUNET_PeerIdentity *) &prm[1];
1579   memcpy (paths, put_path,
1580           put_path_length * sizeof (struct GNUNET_PeerIdentity));
1581   memcpy (&paths[put_path_length], get_path,
1582           get_path_length * sizeof (struct GNUNET_PeerIdentity));
1583   memcpy (&paths[put_path_length + get_path_length], data, data_size);
1584   GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1585   pi->pending_count++;
1586   process_peer_queue (pi);
1587 }
1588
1589
1590 /**
1591  * To be called on core init/fail.
1592  *
1593  * @param cls service closure
1594  * @param identity the public identity of this peer
1595  */
1596 static void
1597 core_init (void *cls,
1598            const struct GNUNET_PeerIdentity *identity)
1599 {
1600   my_identity = *identity;
1601   GNUNET_CRYPTO_hash (identity,
1602                       sizeof (struct GNUNET_PeerIdentity),
1603                       &my_identity_hash);
1604 }
1605
1606
1607 /**
1608  * Core handler for p2p put requests.
1609  *
1610  * @param cls closure
1611  * @param peer sender of the request
1612  * @param message message
1613  * @param peer peer identity this notification is about
1614  * @return #GNUNET_OK to keep the connection open,
1615  *         #GNUNET_SYSERR to close it (signal serious error)
1616  */
1617 static int
1618 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1619                     const struct GNUNET_MessageHeader *message)
1620 {
1621   const struct PeerPutMessage *put;
1622   const struct GNUNET_PeerIdentity *put_path;
1623   const void *payload;
1624   uint32_t putlen;
1625   uint16_t msize;
1626   size_t payload_size;
1627   enum GNUNET_DHT_RouteOption options;
1628   struct GNUNET_CONTAINER_BloomFilter *bf;
1629   struct GNUNET_HashCode test_key;
1630   struct GNUNET_HashCode phash;
1631   int forwarded;
1632
1633   msize = ntohs (message->size);
1634   if (msize < sizeof (struct PeerPutMessage))
1635   {
1636     GNUNET_break_op (0);
1637     return GNUNET_YES;
1638   }
1639   put = (const struct PeerPutMessage *) message;
1640   putlen = ntohl (put->put_path_length);
1641   if ((msize <
1642        sizeof (struct PeerPutMessage) +
1643        putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1644       (putlen >
1645        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1646   {
1647     GNUNET_break_op (0);
1648     return GNUNET_YES;
1649   }
1650   GNUNET_STATISTICS_update (GDS_stats,
1651                             gettext_noop ("# P2P PUT requests received"), 1,
1652                             GNUNET_NO);
1653   GNUNET_STATISTICS_update (GDS_stats,
1654                             gettext_noop ("# P2P PUT bytes received"), msize,
1655                             GNUNET_NO);
1656   put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1657   payload = &put_path[putlen];
1658   options = ntohl (put->options);
1659   payload_size =
1660       msize - (sizeof (struct PeerPutMessage) +
1661                putlen * sizeof (struct GNUNET_PeerIdentity));
1662
1663   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1664               GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1665   GNUNET_CRYPTO_hash (peer, sizeof (struct GNUNET_PeerIdentity), &phash);
1666   if (GNUNET_YES == log_route_details_stderr)
1667   {
1668     char *tmp;
1669
1670     tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1671     LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1672                  "R5N PUT %s: %s->%s (%u, %u=>%u)\n",
1673                  GNUNET_h2s (&put->key), GNUNET_i2s (peer), tmp,
1674                  ntohl(put->hop_count),
1675                  GNUNET_CRYPTO_hash_matching_bits (&phash, &put->key),
1676                  GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &put->key)
1677                 );
1678     GNUNET_free (tmp);
1679   }
1680   switch (GNUNET_BLOCK_get_key
1681           (GDS_block_context, ntohl (put->type), payload, payload_size,
1682            &test_key))
1683   {
1684   case GNUNET_YES:
1685     if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1686     {
1687       char *put_s = GNUNET_strdup (GNUNET_h2s_full (&put->key));
1688       GNUNET_break_op (0);
1689       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1690                   "PUT with key `%s' for block with key %s\n",
1691                   put_s, GNUNET_h2s_full (&test_key));
1692       GNUNET_free (put_s);
1693       return GNUNET_YES;
1694     }
1695     break;
1696   case GNUNET_NO:
1697     GNUNET_break_op (0);
1698     return GNUNET_YES;
1699   case GNUNET_SYSERR:
1700     /* cannot verify, good luck */
1701     break;
1702   }
1703   if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
1704   {
1705     switch (GNUNET_BLOCK_evaluate (GDS_block_context,
1706                                    ntohl (put->type),
1707                                    NULL,    /* query */
1708                                    NULL, 0, /* bloom filer */
1709                                    NULL, 0, /* xquery */
1710                                    payload, payload_size))
1711     {
1712     case GNUNET_BLOCK_EVALUATION_OK_MORE:
1713     case GNUNET_BLOCK_EVALUATION_OK_LAST:
1714       break;
1715
1716     case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1717     case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1718     case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1719     case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1720     case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1721     case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1722     default:
1723       GNUNET_break_op (0);
1724       return GNUNET_OK;
1725     }
1726   }
1727
1728   bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1729                                           GNUNET_CONSTANTS_BLOOMFILTER_K);
1730   GNUNET_break_op (GNUNET_YES ==
1731                    GNUNET_CONTAINER_bloomfilter_test (bf, &phash));
1732   {
1733     struct GNUNET_PeerIdentity pp[putlen + 1];
1734
1735     /* extend 'put path' by sender */
1736     if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1737     {
1738       memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1739       pp[putlen] = *peer;
1740       putlen++;
1741     }
1742     else
1743       putlen = 0;
1744
1745     /* give to local clients */
1746     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1747                               &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1748                               payload_size, payload);
1749     /* store locally */
1750     if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1751         (am_closest_peer (&put->key, bf)))
1752       GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1753                                 (put->expiration_time), &put->key, putlen, pp,
1754                                 ntohl (put->type), payload_size, payload);
1755     /* route to other peers */
1756     forwarded = GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1757                                            ntohl (put->desired_replication_level),
1758                                            GNUNET_TIME_absolute_ntoh (put->expiration_time),
1759                                            ntohl (put->hop_count), bf,
1760                                            &put->key, putlen,
1761                                            pp, payload, payload_size);
1762     /* notify monitoring clients */
1763     GDS_CLIENTS_process_put (options
1764                              | (GNUNET_OK == forwarded)
1765                              ? GNUNET_DHT_RO_LAST_HOP : 0,
1766                              ntohl (put->type),
1767                              ntohl (put->hop_count),
1768                              ntohl (put->desired_replication_level),
1769                              putlen, pp,
1770                              GNUNET_TIME_absolute_ntoh (put->expiration_time),
1771                              &put->key,
1772                              payload,
1773                              payload_size);
1774   }
1775   GNUNET_CONTAINER_bloomfilter_free (bf);
1776   return GNUNET_YES;
1777 }
1778
1779
1780 /**
1781  * We have received a FIND PEER request.  Send matching
1782  * HELLOs back.
1783  *
1784  * @param sender sender of the FIND PEER request
1785  * @param key peers close to this key are desired
1786  * @param bf peers matching this bf are excluded
1787  * @param bf_mutator mutator for bf
1788  */
1789 static void
1790 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1791                   const struct GNUNET_HashCode * key,
1792                   struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1793 {
1794   int bucket_idx;
1795   struct PeerBucket *bucket;
1796   struct PeerInfo *peer;
1797   unsigned int choice;
1798   struct GNUNET_HashCode phash;
1799   struct GNUNET_HashCode mhash;
1800   const struct GNUNET_HELLO_Message *hello;
1801
1802   /* first, check about our own HELLO */
1803   if (NULL != GDS_my_hello)
1804   {
1805     GNUNET_BLOCK_mingle_hash (&my_identity_hash, bf_mutator, &mhash);
1806     if ((NULL == bf) ||
1807         (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1808     {
1809       GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1810                                    GNUNET_TIME_relative_to_absolute
1811                                    (hello_expiration),
1812                                    key, 0, NULL, 0, NULL, GDS_my_hello,
1813                                    GNUNET_HELLO_size ((const struct
1814                                                        GNUNET_HELLO_Message *)
1815                                                       GDS_my_hello));
1816     }
1817     else
1818     {
1819       GNUNET_STATISTICS_update (GDS_stats,
1820                                 gettext_noop
1821                                 ("# FIND PEER requests ignored due to Bloomfilter"),
1822                                 1, GNUNET_NO);
1823     }
1824   }
1825   else
1826   {
1827     GNUNET_STATISTICS_update (GDS_stats,
1828                               gettext_noop
1829                               ("# FIND PEER requests ignored due to lack of HELLO"),
1830                               1, GNUNET_NO);
1831   }
1832
1833   /* then, also consider sending a random HELLO from the closest bucket */
1834   if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1835     bucket_idx = closest_bucket;
1836   else
1837     bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1838   if (bucket_idx == GNUNET_SYSERR)
1839     return;
1840   bucket = &k_buckets[bucket_idx];
1841   if (bucket->peers_size == 0)
1842     return;
1843   choice =
1844       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1845   peer = bucket->head;
1846   while (choice > 0)
1847   {
1848     GNUNET_assert (NULL != peer);
1849     peer = peer->next;
1850     choice--;
1851   }
1852   choice = bucket->peers_size;
1853   do
1854   {
1855     peer = peer->next;
1856     if (choice-- == 0)
1857       return;                   /* no non-masked peer available */
1858     if (peer == NULL)
1859       peer = bucket->head;
1860     GNUNET_CRYPTO_hash (&peer->id, sizeof (struct GNUNET_PeerIdentity), &phash);
1861     GNUNET_BLOCK_mingle_hash (&phash, bf_mutator, &mhash);
1862     hello = GDS_HELLO_get (&peer->id);
1863   }
1864   while ((hello == NULL) ||
1865          (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1866   GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1867                                GNUNET_TIME_relative_to_absolute
1868                                (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1869                                0, NULL, 0, NULL, hello,
1870                                GNUNET_HELLO_size (hello));
1871 }
1872
1873
1874 /**
1875  * Core handler for p2p get requests.
1876  *
1877  * @param cls closure
1878  * @param peer sender of the request
1879  * @param message message
1880  * @return #GNUNET_OK to keep the connection open,
1881  *         #GNUNET_SYSERR to close it (signal serious error)
1882  */
1883 static int
1884 handle_dht_p2p_get (void *cls,
1885                     const struct GNUNET_PeerIdentity *peer,
1886                     const struct GNUNET_MessageHeader *message)
1887 {
1888   struct PeerGetMessage *get;
1889   uint32_t xquery_size;
1890   size_t reply_bf_size;
1891   uint16_t msize;
1892   enum GNUNET_BLOCK_Type type;
1893   enum GNUNET_DHT_RouteOption options;
1894   enum GNUNET_BLOCK_EvaluationResult eval;
1895   struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1896   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1897   const char *xquery;
1898   struct GNUNET_HashCode phash;
1899   int forwarded;
1900
1901   GNUNET_break (0 !=
1902                 memcmp (peer, &my_identity,
1903                         sizeof (struct GNUNET_PeerIdentity)));
1904   /* parse and validate message */
1905   msize = ntohs (message->size);
1906   if (msize < sizeof (struct PeerGetMessage))
1907   {
1908     GNUNET_break_op (0);
1909     return GNUNET_YES;
1910   }
1911   get = (struct PeerGetMessage *) message;
1912   xquery_size = ntohl (get->xquery_size);
1913   if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1914   {
1915     GNUNET_break_op (0);
1916     return GNUNET_YES;
1917   }
1918   reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1919   type = ntohl (get->type);
1920   options = ntohl (get->options);
1921   xquery = (const char *) &get[1];
1922   reply_bf = NULL;
1923   GNUNET_STATISTICS_update (GDS_stats,
1924                             gettext_noop ("# P2P GET requests received"), 1,
1925                             GNUNET_NO);
1926   GNUNET_STATISTICS_update (GDS_stats,
1927                             gettext_noop ("# P2P GET bytes received"), msize,
1928                             GNUNET_NO);
1929   GNUNET_CRYPTO_hash (peer,
1930                       sizeof (struct GNUNET_PeerIdentity),
1931                       &phash);
1932   if (GNUNET_YES == log_route_details_stderr)
1933   {
1934     char *tmp;
1935
1936     tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1937     LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1938                  "R5N GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n",
1939                  GNUNET_h2s (&get->key), GNUNET_i2s (peer), tmp,
1940                  ntohl(get->hop_count),
1941                  GNUNET_CRYPTO_hash_matching_bits (&phash, &get->key),
1942                  GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &get->key),
1943                  ntohl(get->xquery_size), xquery);
1944     GNUNET_free (tmp);
1945   }
1946
1947   if (reply_bf_size > 0)
1948     reply_bf =
1949         GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1950                                            GNUNET_CONSTANTS_BLOOMFILTER_K);
1951   eval =
1952       GNUNET_BLOCK_evaluate (GDS_block_context, type, &get->key, &reply_bf,
1953                              get->bf_mutator, xquery, xquery_size, NULL, 0);
1954   if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1955   {
1956     /* request invalid or block type not supported */
1957     GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1958     if (NULL != reply_bf)
1959       GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1960     return GNUNET_YES;
1961   }
1962   peer_bf =
1963       GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1964                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
1965   GNUNET_break_op (GNUNET_YES ==
1966                    GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1967                                                       &phash));
1968   /* remember request for routing replies */
1969   GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1970                    reply_bf, get->bf_mutator);
1971   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1972               "GET for %s at %s after %u hops\n",
1973               GNUNET_h2s (&get->key),
1974               GNUNET_i2s (&my_identity),
1975               (unsigned int) ntohl (get->hop_count));
1976   /* local lookup (this may update the reply_bf) */
1977   if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1978       (am_closest_peer (&get->key, peer_bf)))
1979   {
1980     if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1981     {
1982       GNUNET_STATISTICS_update (GDS_stats,
1983                                 gettext_noop
1984                                 ("# P2P FIND PEER requests processed"), 1,
1985                                 GNUNET_NO);
1986       handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
1987     }
1988     else
1989     {
1990       eval =
1991           GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
1992                                     &reply_bf, get->bf_mutator);
1993     }
1994   }
1995   else
1996   {
1997     GNUNET_STATISTICS_update (GDS_stats,
1998                               gettext_noop ("# P2P GET requests ONLY routed"),
1999                               1, GNUNET_NO);
2000   }
2001
2002   /* P2P forwarding */
2003   forwarded = GNUNET_NO;
2004   if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
2005     forwarded = GDS_NEIGHBOURS_handle_get (type, options,
2006                                            ntohl (get->desired_replication_level),
2007                                            ntohl (get->hop_count),
2008                                            &get->key,
2009                                            xquery,
2010                                            xquery_size,
2011                                            reply_bf,
2012                                            get->bf_mutator, peer_bf);
2013   GDS_CLIENTS_process_get (options
2014                            | (GNUNET_OK == forwarded)
2015                            ? GNUNET_DHT_RO_LAST_HOP : 0,
2016                            type,
2017                            ntohl (get->hop_count),
2018                            ntohl (get->desired_replication_level),
2019                            0, NULL,
2020                            &get->key);
2021
2022
2023   /* clean up */
2024   if (NULL != reply_bf)
2025     GNUNET_CONTAINER_bloomfilter_free (reply_bf);
2026   GNUNET_CONTAINER_bloomfilter_free (peer_bf);
2027   return GNUNET_YES;
2028 }
2029
2030
2031 /**
2032  * Core handler for p2p result messages.
2033  *
2034  * @param cls closure
2035  * @param message message
2036  * @param peer peer identity this notification is about
2037  * @return #GNUNET_YES (do not cut p2p connection)
2038  */
2039 static int
2040 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
2041                        const struct GNUNET_MessageHeader *message)
2042 {
2043   const struct PeerResultMessage *prm;
2044   const struct GNUNET_PeerIdentity *put_path;
2045   const struct GNUNET_PeerIdentity *get_path;
2046   const void *data;
2047   uint32_t get_path_length;
2048   uint32_t put_path_length;
2049   uint16_t msize;
2050   size_t data_size;
2051   enum GNUNET_BLOCK_Type type;
2052
2053   /* parse and validate message */
2054   msize = ntohs (message->size);
2055   if (msize < sizeof (struct PeerResultMessage))
2056   {
2057     GNUNET_break_op (0);
2058     return GNUNET_YES;
2059   }
2060   prm = (struct PeerResultMessage *) message;
2061   put_path_length = ntohl (prm->put_path_length);
2062   get_path_length = ntohl (prm->get_path_length);
2063   if ((msize <
2064        sizeof (struct PeerResultMessage) + (get_path_length +
2065                                             put_path_length) *
2066        sizeof (struct GNUNET_PeerIdentity)) ||
2067       (get_path_length >
2068        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
2069       (put_path_length >
2070        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
2071   {
2072     GNUNET_break_op (0);
2073     return GNUNET_YES;
2074   }
2075   put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
2076   get_path = &put_path[put_path_length];
2077   type = ntohl (prm->type);
2078   data = (const void *) &get_path[get_path_length];
2079   data_size =
2080       msize - (sizeof (struct PeerResultMessage) +
2081                (get_path_length +
2082                 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
2083   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
2084                             1, GNUNET_NO);
2085   GNUNET_STATISTICS_update (GDS_stats,
2086                             gettext_noop ("# P2P RESULT bytes received"),
2087                             msize, GNUNET_NO);
2088   if (GNUNET_YES == log_route_details_stderr)
2089   {
2090     char *tmp;
2091
2092     tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
2093     LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, "R5N RESULT %s: %s->%s (%u)\n",
2094                  GNUNET_h2s (&prm->key), GNUNET_i2s (peer), tmp,
2095                  get_path_length + 1);
2096     GNUNET_free (tmp);
2097   }
2098   /* if we got a HELLO, consider it for our own routing table */
2099   if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
2100   {
2101     const struct GNUNET_MessageHeader *h;
2102     struct GNUNET_PeerIdentity pid;
2103     int bucket;
2104
2105     /* Should be a HELLO, validate and consider using it! */
2106     if (data_size < sizeof (struct GNUNET_MessageHeader))
2107     {
2108       GNUNET_break_op (0);
2109       return GNUNET_YES;
2110     }
2111     h = data;
2112     if (data_size != ntohs (h->size))
2113     {
2114       GNUNET_break_op (0);
2115       return GNUNET_YES;
2116     }
2117     if (GNUNET_OK !=
2118         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
2119     {
2120       GNUNET_break_op (0);
2121       return GNUNET_YES;
2122     }
2123     if ((GNUNET_YES != disable_try_connect) &&
2124         0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
2125     {
2126       struct GNUNET_HashCode pid_hash;
2127
2128       GNUNET_CRYPTO_hash (&pid, sizeof (struct GNUNET_PeerIdentity), &pid_hash);
2129       bucket = find_bucket (&pid_hash);
2130       if ((bucket >= 0) &&
2131           (k_buckets[bucket].peers_size < bucket_size) &&
2132           (NULL != GDS_transport_handle))
2133       {
2134         GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
2135         GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid, NULL, NULL); /*FIXME TRY_CONNECT change */
2136       }
2137     }
2138   }
2139
2140   /* append 'peer' to 'get_path' */
2141   {
2142     struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
2143
2144     memcpy (xget_path, get_path,
2145             get_path_length * sizeof (struct GNUNET_PeerIdentity));
2146     xget_path[get_path_length] = *peer;
2147     get_path_length++;
2148
2149     /* forward to local clients */
2150     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2151                               &prm->key, get_path_length, xget_path,
2152                               put_path_length, put_path, type, data_size, data);
2153     GDS_CLIENTS_process_get_resp (type,
2154                                   xget_path, get_path_length,
2155                                   put_path, put_path_length,
2156                                   GNUNET_TIME_absolute_ntoh (
2157                                     prm->expiration_time),
2158                                   &prm->key,
2159                                   data,
2160                                   data_size);
2161     if (GNUNET_YES == cache_results)
2162     {
2163       struct GNUNET_PeerIdentity xput_path[get_path_length + 1 + put_path_length];
2164
2165       memcpy (xput_path, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
2166       memcpy (&xput_path[put_path_length],
2167               xget_path,
2168               get_path_length * sizeof (struct GNUNET_PeerIdentity));
2169
2170       GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2171                                 &prm->key,
2172                                 get_path_length + put_path_length, xput_path,
2173                                 type, data_size, data);
2174     }
2175     /* forward to other peers */
2176     GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2177                          &prm->key, put_path_length, put_path, get_path_length,
2178                          xget_path, data, data_size);
2179   }
2180
2181   return GNUNET_YES;
2182 }
2183
2184
2185 /**
2186  * Initialize neighbours subsystem.
2187  *
2188  * @return GNUNET_OK on success, GNUNET_SYSERR on error
2189  */
2190 int
2191 GDS_NEIGHBOURS_init ()
2192 {
2193   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2194     {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2195     {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2196     {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2197     {NULL, 0, 0}
2198   };
2199   unsigned long long temp_config_num;
2200
2201   disable_try_connect
2202     = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2203   if (GNUNET_OK ==
2204       GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2205                                              &temp_config_num))
2206     bucket_size = (unsigned int) temp_config_num;
2207   cache_results
2208     = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "CACHE_RESULTS");
2209
2210   log_route_details_stderr =
2211     (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO;
2212   atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2213   core_api =
2214       GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
2215                            &handle_core_disconnect, NULL, GNUNET_NO, NULL,
2216                            GNUNET_NO, core_handlers);
2217   if (core_api == NULL)
2218     return GNUNET_SYSERR;
2219   all_known_peers = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
2220   return GNUNET_OK;
2221 }
2222
2223
2224 /**
2225  * Shutdown neighbours subsystem.
2226  */
2227 void
2228 GDS_NEIGHBOURS_done ()
2229 {
2230   if (NULL == core_api)
2231     return;
2232   GNUNET_CORE_disconnect (core_api);
2233   core_api = NULL;
2234   GNUNET_ATS_performance_done (atsAPI);
2235   atsAPI = NULL;
2236   GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (all_known_peers));
2237   GNUNET_CONTAINER_multipeermap_destroy (all_known_peers);
2238   all_known_peers = NULL;
2239   if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2240   {
2241     GNUNET_SCHEDULER_cancel (find_peer_task);
2242     find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2243   }
2244 }
2245
2246 /**
2247  * Get the ID of the local node.
2248  *
2249  * @return identity of the local node
2250  */
2251 struct GNUNET_PeerIdentity *
2252 GDS_NEIGHBOURS_get_id ()
2253 {
2254   return &my_identity;
2255 }
2256
2257
2258 /* end of gnunet-service-dht_neighbours.c */