changing time measurement from milliseconds to microseconds
[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_block_lib.h"
30 #include "gnunet_util_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  * Should routing details be logged to stderr (for debugging)?
383  */
384 static int log_route_details_stderr;
385
386 /**
387  * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
388  */
389 static unsigned int closest_bucket;
390
391 /**
392  * How many peers have we added since we sent out our last
393  * find peer request?
394  */
395 static unsigned int newly_found_peers;
396
397 /**
398  * Option for testing that disables the 'connect' function of the DHT.
399  */
400 static int disable_try_connect;
401
402 /**
403  * The buckets.  Array of size MAX_BUCKET_SIZE.  Offset 0 means 0 bits matching.
404  */
405 static struct PeerBucket k_buckets[MAX_BUCKETS];
406
407 /**
408  * Hash map of all known peers, for easy removal from k_buckets on disconnect.
409  */
410 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
411
412 /**
413  * Maximum size for each bucket.
414  */
415 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
416
417 /**
418  * Task that sends FIND PEER requests.
419  */
420 static GNUNET_SCHEDULER_TaskIdentifier find_peer_task;
421
422 /**
423  * Identity of this peer.
424  */
425 static struct GNUNET_PeerIdentity my_identity;
426
427 /**
428  * Handle to CORE.
429  */
430 static struct GNUNET_CORE_Handle *coreAPI;
431
432 /**
433  * Handle to ATS.
434  */
435 static struct GNUNET_ATS_PerformanceHandle *atsAPI;
436
437
438
439 /**
440  * Find the optimal bucket for this key.
441  *
442  * @param hc the hashcode to compare our identity to
443  * @return the proper bucket index, or GNUNET_SYSERR
444  *         on error (same hashcode)
445  */
446 static int
447 find_bucket (const struct GNUNET_HashCode * hc)
448 {
449   unsigned int bits;
450
451   bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
452   if (bits == MAX_BUCKETS)
453   {
454     /* How can all bits match? Got my own ID? */
455     GNUNET_break (0);
456     return GNUNET_SYSERR;
457   }
458   return MAX_BUCKETS - bits - 1;
459 }
460
461
462 /**
463  * Let GNUnet core know that we like the given peer.
464  *
465  * @param cls the 'struct PeerInfo' of the peer
466  * @param tc scheduler context.
467  */
468 static void
469 update_core_preference (void *cls,
470                         const struct GNUNET_SCHEDULER_TaskContext *tc)
471 {
472   struct PeerInfo *peer = cls;
473   uint64_t preference;
474   unsigned int matching;
475   int bucket;
476
477   peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
478   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
479     return;
480   matching =
481       GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
482                                         &peer->id.hashPubKey);
483   if (matching >= 64)
484     matching = 63;
485   bucket = find_bucket (&peer->id.hashPubKey);
486   if (bucket == GNUNET_SYSERR)
487     preference = 0;
488   else
489   {
490     GNUNET_assert (k_buckets[bucket].peers_size != 0);
491     preference = (1LL << matching) / k_buckets[bucket].peers_size;
492   }
493   if (preference == 0)
494   {
495     peer->preference_task =
496         GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
497                                       &update_core_preference, peer);
498     return;
499   }
500   GNUNET_STATISTICS_update (GDS_stats,
501                             gettext_noop ("# Preference updates given to core"),
502                             1, GNUNET_NO);
503   GNUNET_ATS_change_preference (atsAPI, &peer->id,
504                                 GNUNET_ATS_PREFERENCE_BANDWIDTH,
505                                 (double) preference, GNUNET_ATS_PREFERENCE_END);
506   peer->preference_task =
507       GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
508                                     &update_core_preference, peer);
509
510
511 }
512
513
514 /**
515  * Closure for 'add_known_to_bloom'.
516  */
517 struct BloomConstructorContext
518 {
519   /**
520    * Bloom filter under construction.
521    */
522   struct GNUNET_CONTAINER_BloomFilter *bloom;
523
524   /**
525    * Mutator to use.
526    */
527   uint32_t bf_mutator;
528 };
529
530
531 /**
532  * Add each of the peers we already know to the bloom filter of
533  * the request so that we don't get duplicate HELLOs.
534  *
535  * @param cls the 'struct BloomConstructorContext'.
536  * @param key peer identity to add to the bloom filter
537  * @param value value the peer information (unused)
538  * @return GNUNET_YES (we should continue to iterate)
539  */
540 static int
541 add_known_to_bloom (void *cls, const struct GNUNET_HashCode * key, void *value)
542 {
543   struct BloomConstructorContext *ctx = cls;
544   struct GNUNET_HashCode mh;
545
546   GNUNET_BLOCK_mingle_hash (key, ctx->bf_mutator, &mh);
547   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
548               "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
549               GNUNET_h2s (key), ctx->bf_mutator);
550   GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
551   return GNUNET_YES;
552 }
553
554
555 /**
556  * Task to send a find peer message for our own peer identifier
557  * so that we can find the closest peers in the network to ourselves
558  * and attempt to connect to them.
559  *
560  * @param cls closure for this task
561  * @param tc the context under which the task is running
562  */
563 static void
564 send_find_peer_message (void *cls,
565                         const struct GNUNET_SCHEDULER_TaskContext *tc)
566 {
567   struct GNUNET_TIME_Relative next_send_time;
568   struct BloomConstructorContext bcc;
569   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
570
571   find_peer_task = GNUNET_SCHEDULER_NO_TASK;
572   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
573     return;
574   if (newly_found_peers > bucket_size)
575   {
576     /* If we are finding many peers already, no need to send out our request right now! */
577     find_peer_task =
578         GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
579                                       &send_find_peer_message, NULL);
580     newly_found_peers = 0;
581     return;
582   }
583   bcc.bf_mutator =
584       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
585   bcc.bloom =
586       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
587                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
588   GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
589                                          &bcc);
590   GNUNET_STATISTICS_update (GDS_stats,
591                             gettext_noop ("# FIND PEER messages initiated"), 1,
592                             GNUNET_NO);
593   peer_bf =
594       GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
595                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
596   // FIXME: pass priority!?
597   GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
598                              GNUNET_DHT_RO_FIND_PEER,
599                              FIND_PEER_REPLICATION_LEVEL, 0,
600                              &my_identity.hashPubKey, NULL, 0, bcc.bloom,
601                              bcc.bf_mutator, peer_bf);
602   GNUNET_CONTAINER_bloomfilter_free (peer_bf);
603   GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
604   /* schedule next round */
605   next_send_time.rel_value_us =
606       DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value_us +
607       GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
608                                 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value_us /
609                                 (newly_found_peers + 1));
610   newly_found_peers = 0;
611   find_peer_task =
612       GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
613                                     NULL);
614 }
615
616
617 /**
618  * Method called whenever a peer connects.
619  *
620  * @param cls closure
621  * @param peer peer identity this notification is about
622  */
623 static void
624 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
625 {
626   struct PeerInfo *ret;
627   int peer_bucket;
628
629   /* Check for connect to self message */
630   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
631     return;
632   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected %s to %s\n",
633               GNUNET_i2s (&my_identity), GNUNET_h2s (&peer->hashPubKey));
634   if (GNUNET_YES ==
635       GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
636                                               &peer->hashPubKey))
637   {
638     GNUNET_break (0);
639     return;
640   }
641   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), 1,
642                             GNUNET_NO);
643   peer_bucket = find_bucket (&peer->hashPubKey);
644   GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
645   ret = GNUNET_malloc (sizeof (struct PeerInfo));
646 #if 0
647   ret->latency = latency;
648   ret->distance = distance;
649 #endif
650   ret->id = *peer;
651   GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
652                                     k_buckets[peer_bucket].tail, ret);
653   k_buckets[peer_bucket].peers_size++;
654   closest_bucket = GNUNET_MAX (closest_bucket, peer_bucket);
655   if ((peer_bucket > 0) && (k_buckets[peer_bucket].peers_size <= bucket_size))
656   {
657     ret->preference_task =
658         GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
659     newly_found_peers++;
660   }
661   GNUNET_assert (GNUNET_OK ==
662                  GNUNET_CONTAINER_multihashmap_put (all_known_peers,
663                                                     &peer->hashPubKey, ret,
664                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
665   if (1 == GNUNET_CONTAINER_multihashmap_size (all_known_peers) &&
666       (GNUNET_YES != disable_try_connect))
667   {
668     /* got a first connection, good time to start with FIND PEER requests... */
669     find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
670   }
671 }
672
673
674 /**
675  * Method called whenever a peer disconnects.
676  *
677  * @param cls closure
678  * @param peer peer identity this notification is about
679  */
680 static void
681 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
682 {
683   struct PeerInfo *to_remove;
684   int current_bucket;
685   struct P2PPendingMessage *pos;
686   unsigned int discarded;
687
688   /* Check for disconnect from self message */
689   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
690     return;
691   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnected %s from %s\n",
692               GNUNET_i2s (&my_identity), GNUNET_h2s (&peer->hashPubKey));
693   to_remove =
694       GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
695   if (NULL == to_remove)
696   {
697     GNUNET_break (0);
698     return;
699   }
700   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), -1,
701                             GNUNET_NO);
702   GNUNET_assert (GNUNET_YES ==
703                  GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
704                                                        &peer->hashPubKey,
705                                                        to_remove));
706   if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
707   {
708     GNUNET_SCHEDULER_cancel (to_remove->preference_task);
709     to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
710   }
711   current_bucket = find_bucket (&to_remove->id.hashPubKey);
712   GNUNET_assert (current_bucket >= 0);
713   GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
714                                k_buckets[current_bucket].tail, to_remove);
715   GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
716   k_buckets[current_bucket].peers_size--;
717   while ((closest_bucket > 0) && (k_buckets[closest_bucket].peers_size == 0))
718     closest_bucket--;
719
720   if (to_remove->th != NULL)
721   {
722     GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
723     to_remove->th = NULL;
724   }
725   discarded = 0;
726   while (NULL != (pos = to_remove->head))
727   {
728     GNUNET_CONTAINER_DLL_remove (to_remove->head, to_remove->tail, pos);
729     discarded++;
730     GNUNET_free (pos);
731   }
732   GNUNET_STATISTICS_update (GDS_stats,
733                             gettext_noop
734                             ("# Queued messages discarded (peer disconnected)"),
735                             discarded, GNUNET_NO);
736   GNUNET_free (to_remove);
737 }
738
739
740 /**
741  * Called when core is ready to send a message we asked for
742  * out to the destination.
743  *
744  * @param cls the 'struct PeerInfo' of the target peer
745  * @param size number of bytes available in buf
746  * @param buf where the callee should write the message
747  * @return number of bytes written to buf
748  */
749 static size_t
750 core_transmit_notify (void *cls, size_t size, void *buf)
751 {
752   struct PeerInfo *peer = cls;
753   char *cbuf = buf;
754   struct P2PPendingMessage *pending;
755   size_t off;
756   size_t msize;
757
758   peer->th = NULL;
759   while ((NULL != (pending = peer->head)) &&
760          (0 == GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value_us))
761   {
762     peer->pending_count--;
763     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
764     GNUNET_free (pending);
765   }
766   if (pending == NULL)
767   {
768     /* no messages pending */
769     return 0;
770   }
771   if (buf == NULL)
772   {
773     peer->th =
774         GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO,
775                                            pending->importance,
776                                            GNUNET_TIME_absolute_get_remaining
777                                            (pending->timeout), &peer->id,
778                                            ntohs (pending->msg->size),
779                                            &core_transmit_notify, peer);
780     GNUNET_break (NULL != peer->th);
781     return 0;
782   }
783   off = 0;
784   while ((NULL != (pending = peer->head)) &&
785          (size - off >= (msize = ntohs (pending->msg->size))))
786   {
787     GNUNET_STATISTICS_update (GDS_stats,
788                               gettext_noop
789                               ("# Bytes transmitted to other peers"), msize,
790                               GNUNET_NO);
791     memcpy (&cbuf[off], pending->msg, msize);
792     off += msize;
793     peer->pending_count--;
794     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
795     GNUNET_free (pending);
796   }
797   if (peer->head != NULL)
798   {
799     peer->th =
800         GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO,
801                                            pending->importance,
802                                            GNUNET_TIME_absolute_get_remaining
803                                            (pending->timeout), &peer->id, msize,
804                                            &core_transmit_notify, peer);
805     GNUNET_break (NULL != peer->th);
806   }
807   return off;
808 }
809
810
811 /**
812  * Transmit all messages in the peer's message queue.
813  *
814  * @param peer message queue to process
815  */
816 static void
817 process_peer_queue (struct PeerInfo *peer)
818 {
819   struct P2PPendingMessage *pending;
820
821   if (NULL == (pending = peer->head))
822     return;
823   if (NULL != peer->th)
824     return;
825   GNUNET_STATISTICS_update (GDS_stats,
826                             gettext_noop
827                             ("# Bytes of bandwidth requested from core"),
828                             ntohs (pending->msg->size), GNUNET_NO);
829   peer->th =
830       GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO,
831                                          pending->importance,
832                                          GNUNET_TIME_absolute_get_remaining
833                                          (pending->timeout), &peer->id,
834                                          ntohs (pending->msg->size),
835                                          &core_transmit_notify, peer);
836   GNUNET_break (NULL != peer->th);
837 }
838
839
840 /**
841  * To how many peers should we (on average) forward the request to
842  * obtain the desired target_replication count (on average).
843  *
844  * @param hop_count number of hops the message has traversed
845  * @param target_replication the number of total paths desired
846  * @return Some number of peers to forward the message to
847  */
848 static unsigned int
849 get_forward_count (uint32_t hop_count, uint32_t target_replication)
850 {
851   uint32_t random_value;
852   uint32_t forward_count;
853   float target_value;
854
855   if (hop_count > GDS_NSE_get () * 4.0)
856   {
857     /* forcefully terminate */
858     GNUNET_STATISTICS_update (GDS_stats,
859                               gettext_noop ("# requests TTL-dropped"),
860                               1, GNUNET_NO);
861     return 0;
862   }
863   if (hop_count > GDS_NSE_get () * 2.0)
864   {
865     /* Once we have reached our ideal number of hops, only forward to 1 peer */
866     return 1;
867   }
868   /* bound by system-wide maximum */
869   target_replication =
870       GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
871   target_value =
872       1 + (target_replication - 1.0) / (GDS_NSE_get () +
873                                         ((float) (target_replication - 1.0) *
874                                          hop_count));
875   /* Set forward count to floor of target_value */
876   forward_count = (uint32_t) target_value;
877   /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
878   target_value = target_value - forward_count;
879   random_value =
880       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
881   if (random_value < (target_value * UINT32_MAX))
882     forward_count++;
883   return forward_count;
884 }
885
886
887 /**
888  * Compute the distance between have and target as a 32-bit value.
889  * Differences in the lower bits must count stronger than differences
890  * in the higher bits.
891  *
892  * @return 0 if have==target, otherwise a number
893  *           that is larger as the distance between
894  *           the two hash codes increases
895  */
896 static unsigned int
897 get_distance (const struct GNUNET_HashCode * target, const struct GNUNET_HashCode * have)
898 {
899   unsigned int bucket;
900   unsigned int msb;
901   unsigned int lsb;
902   unsigned int i;
903
904   /* We have to represent the distance between two 2^9 (=512)-bit
905    * numbers as a 2^5 (=32)-bit number with "0" being used for the
906    * two numbers being identical; furthermore, we need to
907    * guarantee that a difference in the number of matching
908    * bits is always represented in the result.
909    *
910    * We use 2^32/2^9 numerical values to distinguish between
911    * hash codes that have the same LSB bit distance and
912    * use the highest 2^9 bits of the result to signify the
913    * number of (mis)matching LSB bits; if we have 0 matching
914    * and hence 512 mismatching LSB bits we return -1 (since
915    * 512 itself cannot be represented with 9 bits) */
916
917   /* first, calculate the most significant 9 bits of our
918    * result, aka the number of LSBs */
919   bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
920   /* bucket is now a value between 0 and 512 */
921   if (bucket == 512)
922     return 0;                   /* perfect match */
923   if (bucket == 0)
924     return (unsigned int) -1;   /* LSB differs; use max (if we did the bit-shifting
925                                  * below, we'd end up with max+1 (overflow)) */
926
927   /* calculate the most significant bits of the final result */
928   msb = (512 - bucket) << (32 - 9);
929   /* calculate the 32-9 least significant bits of the final result by
930    * looking at the differences in the 32-9 bits following the
931    * mismatching bit at 'bucket' */
932   lsb = 0;
933   for (i = bucket + 1;
934        (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
935   {
936     if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
937         GNUNET_CRYPTO_hash_get_bit (have, i))
938       lsb |= (1 << (bucket + 32 - 9 - i));      /* first bit set will be 10,
939                                                  * last bit set will be 31 -- if
940                                                  * i does not reach 512 first... */
941   }
942   return msb | lsb;
943 }
944
945
946 /**
947  * Check whether my identity is closer than any known peers.  If a
948  * non-null bloomfilter is given, check if this is the closest peer
949  * that hasn't already been routed to.
950  *
951  * @param key hash code to check closeness to
952  * @param bloom bloomfilter, exclude these entries from the decision
953  * @return GNUNET_YES if node location is closest,
954  *         GNUNET_NO otherwise.
955  */
956 static int
957 am_closest_peer (const struct GNUNET_HashCode * key,
958                  const struct GNUNET_CONTAINER_BloomFilter *bloom)
959 {
960   int bits;
961   int other_bits;
962   int bucket_num;
963   int count;
964   struct PeerInfo *pos;
965
966   if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (struct GNUNET_HashCode)))
967     return GNUNET_YES;
968   bucket_num = find_bucket (key);
969   GNUNET_assert (bucket_num >= 0);
970   bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
971   pos = k_buckets[bucket_num].head;
972   count = 0;
973   while ((pos != NULL) && (count < bucket_size))
974   {
975     if ((bloom != NULL) &&
976         (GNUNET_YES ==
977          GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
978     {
979       pos = pos->next;
980       continue;                 /* Skip already checked entries */
981     }
982     other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
983     if (other_bits > bits)
984       return GNUNET_NO;
985     if (other_bits == bits)     /* We match the same number of bits */
986       return GNUNET_YES;
987     pos = pos->next;
988   }
989   /* No peers closer, we are the closest! */
990   return GNUNET_YES;
991 }
992
993
994 /**
995  * Select a peer from the routing table that would be a good routing
996  * destination for sending a message for "key".  The resulting peer
997  * must not be in the set of blocked peers.<p>
998  *
999  * Note that we should not ALWAYS select the closest peer to the
1000  * target, peers further away from the target should be chosen with
1001  * exponentially declining probability.
1002  *
1003  * FIXME: double-check that this is fine
1004  *
1005  *
1006  * @param key the key we are selecting a peer to route to
1007  * @param bloom a bloomfilter containing entries this request has seen already
1008  * @param hops how many hops has this message traversed thus far
1009  * @return Peer to route to, or NULL on error
1010  */
1011 static struct PeerInfo *
1012 select_peer (const struct GNUNET_HashCode * key,
1013              const struct GNUNET_CONTAINER_BloomFilter *bloom, uint32_t hops)
1014 {
1015   unsigned int bc;
1016   unsigned int count;
1017   unsigned int selected;
1018   struct PeerInfo *pos;
1019   unsigned int dist;
1020   unsigned int smallest_distance;
1021   struct PeerInfo *chosen;
1022
1023   if (hops >= GDS_NSE_get ())
1024   {
1025     /* greedy selection (closest peer that is not in bloomfilter) */
1026     smallest_distance = UINT_MAX;
1027     chosen = NULL;
1028     for (bc = 0; bc <= closest_bucket; bc++)
1029     {
1030       pos = k_buckets[bc].head;
1031       count = 0;
1032       while ((pos != NULL) && (count < bucket_size))
1033       {
1034         if ((bloom == NULL) ||
1035             (GNUNET_NO ==
1036              GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1037         {
1038           dist = get_distance (key, &pos->id.hashPubKey);
1039           if (dist < smallest_distance)
1040           {
1041             chosen = pos;
1042             smallest_distance = dist;
1043           }
1044         }
1045         else
1046         {
1047           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1048                       "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1049                       GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1050           GNUNET_STATISTICS_update (GDS_stats,
1051                                     gettext_noop
1052                                     ("# Peers excluded from routing due to Bloomfilter"),
1053                                     1, GNUNET_NO);
1054           dist = get_distance (key, &pos->id.hashPubKey);
1055           if (dist < smallest_distance)
1056           {
1057             chosen = NULL;
1058             smallest_distance = dist;
1059           }
1060         }
1061         count++;
1062         pos = pos->next;
1063       }
1064     }
1065     if (NULL == chosen)
1066       GNUNET_STATISTICS_update (GDS_stats,
1067                                 gettext_noop ("# Peer selection failed"), 1,
1068                                 GNUNET_NO);
1069     return chosen;
1070   }
1071
1072   /* select "random" peer */
1073   /* count number of peers that are available and not filtered */
1074   count = 0;
1075   for (bc = 0; bc <= closest_bucket; bc++)
1076   {
1077     pos = k_buckets[bc].head;
1078     while ((pos != NULL) && (count < bucket_size))
1079     {
1080       if ((bloom != NULL) &&
1081           (GNUNET_YES ==
1082            GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1083       {
1084         GNUNET_STATISTICS_update (GDS_stats,
1085                                   gettext_noop
1086                                   ("# Peers excluded from routing due to Bloomfilter"),
1087                                   1, GNUNET_NO);
1088         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1089                     "Excluded peer `%s' due to BF match in random routing for %s\n",
1090                     GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1091         pos = pos->next;
1092         continue;               /* Ignore bloomfiltered peers */
1093       }
1094       count++;
1095       pos = pos->next;
1096     }
1097   }
1098   if (0 == count)               /* No peers to select from! */
1099   {
1100     GNUNET_STATISTICS_update (GDS_stats,
1101                               gettext_noop ("# Peer selection failed"), 1,
1102                               GNUNET_NO);
1103     return NULL;
1104   }
1105   /* Now actually choose a peer */
1106   selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1107   count = 0;
1108   for (bc = 0; bc <= closest_bucket; bc++)
1109   {
1110     for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next)
1111     {
1112       if ((bloom != NULL) &&
1113           (GNUNET_YES ==
1114            GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1115       {
1116         continue;               /* Ignore bloomfiltered peers */
1117       }
1118       if (0 == selected--)
1119         return pos;
1120     }
1121   }
1122   GNUNET_break (0);
1123   return NULL;
1124 }
1125
1126
1127 /**
1128  * Compute the set of peers that the given request should be
1129  * forwarded to.
1130  *
1131  * @param key routing key
1132  * @param bloom bloom filter excluding peers as targets, all selected
1133  *        peers will be added to the bloom filter
1134  * @param hop_count number of hops the request has traversed so far
1135  * @param target_replication desired number of replicas
1136  * @param targets where to store an array of target peers (to be
1137  *         free'd by the caller)
1138  * @return number of peers returned in 'targets'.
1139  */
1140 static unsigned int
1141 get_target_peers (const struct GNUNET_HashCode *key,
1142                   struct GNUNET_CONTAINER_BloomFilter *bloom,
1143                   uint32_t hop_count, uint32_t target_replication,
1144                   struct PeerInfo ***targets)
1145 {
1146   unsigned int ret;
1147   unsigned int off;
1148   struct PeerInfo **rtargets;
1149   struct PeerInfo *nxt;
1150
1151   GNUNET_assert (NULL != bloom);
1152   ret = get_forward_count (hop_count, target_replication);  
1153   if (0 == ret)
1154   {
1155     *targets = NULL;
1156     return 0;
1157   }
1158   rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1159   for (off = 0; off < ret; off++)
1160   {
1161     nxt = select_peer (key, bloom, hop_count);
1162     if (NULL == nxt)
1163       break;
1164     rtargets[off] = nxt;
1165     GNUNET_break (GNUNET_NO ==
1166                   GNUNET_CONTAINER_bloomfilter_test (bloom,
1167                                                      &nxt->id.hashPubKey));
1168     GNUNET_CONTAINER_bloomfilter_add (bloom, &rtargets[off]->id.hashPubKey);
1169   }
1170   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1171               "Selected %u/%u peers at hop %u for %s (target was %u)\n", off,
1172               GNUNET_CONTAINER_multihashmap_size (all_known_peers),
1173               (unsigned int) hop_count, GNUNET_h2s (key), ret);
1174   if (0 == off)
1175   {
1176     GNUNET_free (rtargets);
1177     *targets = NULL;
1178     return 0;
1179   }
1180   *targets = rtargets;
1181   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1182               "Forwarding query `%s' to %u peers (goal was %u peers)\n",
1183               GNUNET_h2s (key), 
1184               off,
1185               ret);
1186   return off;
1187 }
1188
1189
1190 /**
1191  * Perform a PUT operation.   Forwards the given request to other
1192  * peers.   Does not store the data locally.  Does not give the
1193  * data to local clients.  May do nothing if this is the only
1194  * peer in the network (or if we are the closest peer in the
1195  * network).
1196  *
1197  * @param type type of the block
1198  * @param options routing options
1199  * @param desired_replication_level desired replication count
1200  * @param expiration_time when does the content expire
1201  * @param hop_count how many hops has this message traversed so far
1202  * @param bf Bloom filter of peers this PUT has already traversed
1203  * @param key key for the content
1204  * @param put_path_length number of entries in put_path
1205  * @param put_path peers this request has traversed so far (if tracked)
1206  * @param data payload to store
1207  * @param data_size number of bytes in data
1208  */
1209 void
1210 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1211                            enum GNUNET_DHT_RouteOption options,
1212                            uint32_t desired_replication_level,
1213                            struct GNUNET_TIME_Absolute expiration_time,
1214                            uint32_t hop_count,
1215                            struct GNUNET_CONTAINER_BloomFilter *bf,
1216                            const struct GNUNET_HashCode * key,
1217                            unsigned int put_path_length,
1218                            struct GNUNET_PeerIdentity *put_path,
1219                            const void *data, size_t data_size)
1220 {
1221   unsigned int target_count;
1222   unsigned int i;
1223   struct PeerInfo **targets;
1224   struct PeerInfo *target;
1225   struct P2PPendingMessage *pending;
1226   size_t msize;
1227   struct PeerPutMessage *ppm;
1228   struct GNUNET_PeerIdentity *pp;
1229
1230   GNUNET_assert (NULL != bf);
1231   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1232               "Adding myself (%s) to PUT bloomfilter for %s\n",
1233               GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1234   GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1235   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1236                             1, GNUNET_NO);
1237   target_count =
1238       get_target_peers (key, bf, hop_count, desired_replication_level,
1239                         &targets);
1240   if (0 == target_count)
1241   {
1242     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1243                 "Routing PUT for %s terminates after %u hops at %s\n",
1244                 GNUNET_h2s (key), (unsigned int) hop_count,
1245                 GNUNET_i2s (&my_identity));
1246     return;
1247   }
1248   msize =
1249       put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1250       sizeof (struct PeerPutMessage);
1251   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1252   {
1253     put_path_length = 0;
1254     msize = data_size + sizeof (struct PeerPutMessage);
1255   }
1256   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1257   {
1258     GNUNET_break (0);
1259     GNUNET_free (targets);
1260     return;
1261   }
1262   GNUNET_STATISTICS_update (GDS_stats,
1263                             gettext_noop
1264                             ("# PUT messages queued for transmission"),
1265                             target_count, GNUNET_NO);
1266   for (i = 0; i < target_count; i++)
1267   {
1268     target = targets[i];
1269     if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1270     {
1271       GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1272                                 1, GNUNET_NO);
1273       continue; /* skip */
1274     }
1275     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1276                 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1277                 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1278     pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1279     pending->importance = 0;    /* FIXME */
1280     pending->timeout = expiration_time;
1281     ppm = (struct PeerPutMessage *) &pending[1];
1282     pending->msg = &ppm->header;
1283     ppm->header.size = htons (msize);
1284     ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1285     ppm->options = htonl (options);
1286     ppm->type = htonl (type);
1287     ppm->hop_count = htonl (hop_count + 1);
1288     ppm->desired_replication_level = htonl (desired_replication_level);
1289     ppm->put_path_length = htonl (put_path_length);
1290     ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1291     GNUNET_break (GNUNET_YES ==
1292                   GNUNET_CONTAINER_bloomfilter_test (bf,
1293                                                      &target->id.hashPubKey));
1294     GNUNET_assert (GNUNET_OK ==
1295                    GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1296                                                               ppm->bloomfilter,
1297                                                               DHT_BLOOM_SIZE));
1298     ppm->key = *key;
1299     pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1300     memcpy (pp, put_path,
1301             sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1302     memcpy (&pp[put_path_length], data, data_size);
1303     GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1304     target->pending_count++;
1305     process_peer_queue (target);
1306   }
1307   GNUNET_free (targets);
1308 }
1309
1310
1311 /**
1312  * Perform a GET operation.  Forwards the given request to other
1313  * peers.  Does not lookup the key locally.  May do nothing if this is
1314  * the only peer in the network (or if we are the closest peer in the
1315  * network).
1316  *
1317  * @param type type of the block
1318  * @param options routing options
1319  * @param desired_replication_level desired replication count
1320  * @param hop_count how many hops did this request traverse so far?
1321  * @param key key for the content
1322  * @param xquery extended query
1323  * @param xquery_size number of bytes in xquery
1324  * @param reply_bf bloomfilter to filter duplicates
1325  * @param reply_bf_mutator mutator for reply_bf
1326  * @param peer_bf filter for peers not to select (again)
1327  */
1328 void
1329 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1330                            enum GNUNET_DHT_RouteOption options,
1331                            uint32_t desired_replication_level,
1332                            uint32_t hop_count, const struct GNUNET_HashCode * key,
1333                            const void *xquery, size_t xquery_size,
1334                            const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1335                            uint32_t reply_bf_mutator,
1336                            struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1337 {
1338   unsigned int target_count;
1339   unsigned int i;
1340   struct PeerInfo **targets;
1341   struct PeerInfo *target;
1342   struct P2PPendingMessage *pending;
1343   size_t msize;
1344   struct PeerGetMessage *pgm;
1345   char *xq;
1346   size_t reply_bf_size;
1347
1348   GNUNET_assert (NULL != peer_bf);
1349   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1350                             1, GNUNET_NO);
1351   target_count =
1352       get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1353                         &targets);
1354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1355               "Adding myself (%s) to GET bloomfilter for %s\n",
1356               GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1357   GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity.hashPubKey);
1358   if (0 == target_count)
1359   {
1360     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1361                 "Routing GET for %s terminates after %u hops at %s\n",
1362                 GNUNET_h2s (key), (unsigned int) hop_count,
1363                 GNUNET_i2s (&my_identity));
1364     return;
1365   }
1366   reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1367   msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1368   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1369   {
1370     GNUNET_break (0);
1371     GNUNET_free (targets);
1372     return;
1373   }
1374   GNUNET_STATISTICS_update (GDS_stats,
1375                             gettext_noop
1376                             ("# GET messages queued for transmission"),
1377                             target_count, GNUNET_NO);
1378   /* forward request */
1379   for (i = 0; i < target_count; i++)
1380   {
1381     target = targets[i];
1382     if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1383     {
1384       GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1385                                 1, GNUNET_NO);
1386       continue; /* skip */
1387     }
1388     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1389                 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1390                 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1391     pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1392     pending->importance = 0;    /* FIXME */
1393     pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1394     pgm = (struct PeerGetMessage *) &pending[1];
1395     pending->msg = &pgm->header;
1396     pgm->header.size = htons (msize);
1397     pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1398     pgm->options = htonl (options);
1399     pgm->type = htonl (type);
1400     pgm->hop_count = htonl (hop_count + 1);
1401     pgm->desired_replication_level = htonl (desired_replication_level);
1402     pgm->xquery_size = htonl (xquery_size);
1403     pgm->bf_mutator = reply_bf_mutator;
1404     GNUNET_break (GNUNET_YES ==
1405                   GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1406                                                      &target->id.hashPubKey));
1407     GNUNET_assert (GNUNET_OK ==
1408                    GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1409                                                               pgm->bloomfilter,
1410                                                               DHT_BLOOM_SIZE));
1411     pgm->key = *key;
1412     xq = (char *) &pgm[1];
1413     memcpy (xq, xquery, xquery_size);
1414     if (NULL != reply_bf)
1415       GNUNET_assert (GNUNET_OK ==
1416                      GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1417                                                                 &xq
1418                                                                 [xquery_size],
1419                                                                 reply_bf_size));
1420     GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1421     target->pending_count++;
1422     process_peer_queue (target);
1423   }
1424   GNUNET_free (targets);
1425 }
1426
1427
1428 /**
1429  * Handle a reply (route to origin).  Only forwards the reply back to
1430  * the given peer.  Does not do local caching or forwarding to local
1431  * clients.
1432  *
1433  * @param target neighbour that should receive the block (if still connected)
1434  * @param type type of the block
1435  * @param expiration_time when does the content expire
1436  * @param key key for the content
1437  * @param put_path_length number of entries in put_path
1438  * @param put_path peers the original PUT traversed (if tracked)
1439  * @param get_path_length number of entries in put_path
1440  * @param get_path peers this reply has traversed so far (if tracked)
1441  * @param data payload of the reply
1442  * @param data_size number of bytes in data
1443  */
1444 void
1445 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1446                              enum GNUNET_BLOCK_Type type,
1447                              struct GNUNET_TIME_Absolute expiration_time,
1448                              const struct GNUNET_HashCode * key,
1449                              unsigned int put_path_length,
1450                              const struct GNUNET_PeerIdentity *put_path,
1451                              unsigned int get_path_length,
1452                              const struct GNUNET_PeerIdentity *get_path,
1453                              const void *data, size_t data_size)
1454 {
1455   struct PeerInfo *pi;
1456   struct P2PPendingMessage *pending;
1457   size_t msize;
1458   struct PeerResultMessage *prm;
1459   struct GNUNET_PeerIdentity *paths;
1460
1461   msize =
1462       data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1463                                                        put_path_length) *
1464       sizeof (struct GNUNET_PeerIdentity);
1465   if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1466       (get_path_length >
1467        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1468       (put_path_length >
1469        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1470       (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1471   {
1472     GNUNET_break (0);
1473     return;
1474   }
1475   pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers, &target->hashPubKey);
1476   if (NULL == pi)
1477   {
1478     /* peer disconnected in the meantime, drop reply */
1479     return;
1480   }
1481   if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1482   {
1483     /* skip */
1484     GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1485                               1, GNUNET_NO);
1486     return;
1487   }
1488
1489   GNUNET_STATISTICS_update (GDS_stats,
1490                             gettext_noop
1491                             ("# RESULT messages queued for transmission"), 1,
1492                             GNUNET_NO);
1493   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1494   pending->importance = 0;      /* FIXME */
1495   pending->timeout = expiration_time;
1496   prm = (struct PeerResultMessage *) &pending[1];
1497   pending->msg = &prm->header;
1498   prm->header.size = htons (msize);
1499   prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1500   prm->type = htonl (type);
1501   prm->put_path_length = htonl (put_path_length);
1502   prm->get_path_length = htonl (get_path_length);
1503   prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1504   prm->key = *key;
1505   paths = (struct GNUNET_PeerIdentity *) &prm[1];
1506   memcpy (paths, put_path,
1507           put_path_length * sizeof (struct GNUNET_PeerIdentity));
1508   memcpy (&paths[put_path_length], get_path,
1509           get_path_length * sizeof (struct GNUNET_PeerIdentity));
1510   memcpy (&paths[put_path_length + get_path_length], data, data_size);
1511   GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1512   pi->pending_count++;
1513   process_peer_queue (pi);
1514 }
1515
1516
1517 /**
1518  * To be called on core init/fail.
1519  *
1520  * @param cls service closure
1521  * @param server handle to the server for this service
1522  * @param identity the public identity of this peer
1523  */
1524 static void
1525 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1526            const struct GNUNET_PeerIdentity *identity)
1527 {
1528   GNUNET_assert (server != NULL);
1529   my_identity = *identity;
1530 }
1531
1532
1533 /**
1534  * Core handler for p2p put requests.
1535  *
1536  * @param cls closure
1537  * @param peer sender of the request
1538  * @param message message
1539  * @param peer peer identity this notification is about
1540  * @return GNUNET_OK to keep the connection open,
1541  *         GNUNET_SYSERR to close it (signal serious error)
1542  */
1543 static int
1544 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1545                     const struct GNUNET_MessageHeader *message)
1546 {
1547   const struct PeerPutMessage *put;
1548   const struct GNUNET_PeerIdentity *put_path;
1549   const void *payload;
1550   uint32_t putlen;
1551   uint16_t msize;
1552   size_t payload_size;
1553   enum GNUNET_DHT_RouteOption options;
1554   struct GNUNET_CONTAINER_BloomFilter *bf;
1555   struct GNUNET_HashCode test_key;
1556
1557   msize = ntohs (message->size);
1558   if (msize < sizeof (struct PeerPutMessage))
1559   {
1560     GNUNET_break_op (0);
1561     return GNUNET_YES;
1562   }
1563   put = (const struct PeerPutMessage *) message;
1564   putlen = ntohl (put->put_path_length);
1565   if ((msize <
1566        sizeof (struct PeerPutMessage) +
1567        putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1568       (putlen >
1569        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1570   {
1571     GNUNET_break_op (0);
1572     return GNUNET_YES;
1573   }
1574   GNUNET_STATISTICS_update (GDS_stats,
1575                             gettext_noop ("# P2P PUT requests received"), 1,
1576                             GNUNET_NO);
1577   GNUNET_STATISTICS_update (GDS_stats,
1578                             gettext_noop ("# P2P PUT bytes received"), msize,
1579                             GNUNET_NO);
1580   put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1581   payload = &put_path[putlen];
1582   options = ntohl (put->options);
1583   payload_size =
1584       msize - (sizeof (struct PeerPutMessage) +
1585                putlen * sizeof (struct GNUNET_PeerIdentity));
1586   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1587               GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1588   if (GNUNET_YES == log_route_details_stderr)
1589   {
1590     char *tmp;
1591
1592     tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1593     LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, "XDHT PUT %s: %s->%s (%u, %u=>%u)\n", 
1594                  GNUNET_h2s (&put->key), GNUNET_i2s (peer), tmp,
1595                  ntohl(put->hop_count),
1596                  GNUNET_CRYPTO_hash_matching_bits (&peer->hashPubKey, &put->key),
1597                  GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, &put->key)
1598                 );
1599     GNUNET_free (tmp);
1600   }
1601   switch (GNUNET_BLOCK_get_key
1602           (GDS_block_context, ntohl (put->type), payload, payload_size,
1603            &test_key))
1604   {
1605   case GNUNET_YES:
1606     if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1607     {
1608       GNUNET_break_op (0);
1609       return GNUNET_YES;
1610     }
1611     break;
1612   case GNUNET_NO:
1613     GNUNET_break_op (0);
1614     return GNUNET_YES;
1615   case GNUNET_SYSERR:
1616     /* cannot verify, good luck */
1617     break;
1618   }
1619   if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
1620   {
1621     switch (GNUNET_BLOCK_evaluate (GDS_block_context,
1622                                    ntohl (put->type),
1623                                    NULL,    /* query */
1624                                    NULL, 0, /* bloom filer */
1625                                    NULL, 0, /* xquery */
1626                                    payload, payload_size))
1627     {
1628     case GNUNET_BLOCK_EVALUATION_OK_MORE:
1629     case GNUNET_BLOCK_EVALUATION_OK_LAST:
1630       break;
1631
1632     case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1633     case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1634     case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1635     case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1636     case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1637     case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1638     default:
1639       GNUNET_break_op (0);
1640       return GNUNET_OK;
1641     }
1642   }
1643
1644   bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1645                                           GNUNET_CONSTANTS_BLOOMFILTER_K);
1646   GNUNET_break_op (GNUNET_YES ==
1647                    GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1648   {
1649     struct GNUNET_PeerIdentity pp[putlen + 1];
1650
1651     /* extend 'put path' by sender */
1652     if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1653     {
1654       memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1655       pp[putlen] = *peer;
1656       putlen++;
1657     }
1658     else
1659       putlen = 0;
1660
1661     /* give to local clients */
1662     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1663                               &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1664                               payload_size, payload);
1665     /* store locally */
1666     if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1667         (am_closest_peer (&put->key, bf)))
1668       GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1669                                 (put->expiration_time), &put->key, putlen, pp,
1670                                 ntohl (put->type), payload_size, payload);
1671     /* route to other peers */
1672     GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1673                                ntohl (put->desired_replication_level),
1674                                GNUNET_TIME_absolute_ntoh (put->expiration_time),
1675                                ntohl (put->hop_count), bf, &put->key, putlen,
1676                                pp, payload, payload_size);
1677     /* notify monitoring clients */
1678     GDS_CLIENTS_process_put (options,
1679                              ntohl (put->type),
1680                              ntohl (put->hop_count),
1681                              ntohl (put->desired_replication_level),
1682                              putlen, pp,
1683                              GNUNET_TIME_absolute_ntoh (put->expiration_time),
1684                              &put->key,
1685                              payload,
1686                              payload_size);
1687   }
1688   GNUNET_CONTAINER_bloomfilter_free (bf);
1689   return GNUNET_YES;
1690 }
1691
1692
1693 /**
1694  * We have received a FIND PEER request.  Send matching
1695  * HELLOs back.
1696  *
1697  * @param sender sender of the FIND PEER request
1698  * @param key peers close to this key are desired
1699  * @param bf peers matching this bf are excluded
1700  * @param bf_mutator mutator for bf
1701  */
1702 static void
1703 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1704                   const struct GNUNET_HashCode * key,
1705                   struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1706 {
1707   int bucket_idx;
1708   struct PeerBucket *bucket;
1709   struct PeerInfo *peer;
1710   unsigned int choice;
1711   struct GNUNET_HashCode mhash;
1712   const struct GNUNET_HELLO_Message *hello;
1713
1714   /* first, check about our own HELLO */
1715   if (NULL != GDS_my_hello)
1716   {
1717     GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1718     if ((NULL == bf) ||
1719         (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1720     {
1721       GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1722                                    GNUNET_TIME_relative_to_absolute
1723                                    (hello_expiration),
1724                                    key, 0, NULL, 0, NULL, GDS_my_hello,
1725                                    GNUNET_HELLO_size ((const struct
1726                                                        GNUNET_HELLO_Message *)
1727                                                       GDS_my_hello));
1728     }
1729     else
1730     {
1731       GNUNET_STATISTICS_update (GDS_stats,
1732                                 gettext_noop
1733                                 ("# FIND PEER requests ignored due to Bloomfilter"),
1734                                 1, GNUNET_NO);
1735     }
1736   }
1737   else
1738   {
1739     GNUNET_STATISTICS_update (GDS_stats,
1740                               gettext_noop
1741                               ("# FIND PEER requests ignored due to lack of HELLO"),
1742                               1, GNUNET_NO);
1743   }
1744
1745   /* then, also consider sending a random HELLO from the closest bucket */
1746   if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (struct GNUNET_HashCode)))
1747     bucket_idx = closest_bucket;
1748   else
1749     bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1750   if (bucket_idx == GNUNET_SYSERR)
1751     return;
1752   bucket = &k_buckets[bucket_idx];
1753   if (bucket->peers_size == 0)
1754     return;
1755   choice =
1756       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1757   peer = bucket->head;
1758   while (choice > 0)
1759   {
1760     GNUNET_assert (peer != NULL);
1761     peer = peer->next;
1762     choice--;
1763   }
1764   choice = bucket->peers_size;
1765   do
1766   {
1767     peer = peer->next;
1768     if (choice-- == 0)
1769       return;                   /* no non-masked peer available */
1770     if (peer == NULL)
1771       peer = bucket->head;
1772     GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1773     hello = GDS_HELLO_get (&peer->id);
1774   }
1775   while ((hello == NULL) ||
1776          (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1777   GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1778                                GNUNET_TIME_relative_to_absolute
1779                                (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1780                                0, NULL, 0, NULL, hello,
1781                                GNUNET_HELLO_size (hello));
1782 }
1783
1784
1785 /**
1786  * Core handler for p2p get requests.
1787  *
1788  * @param cls closure
1789  * @param peer sender of the request
1790  * @param message message
1791  * @return GNUNET_OK to keep the connection open,
1792  *         GNUNET_SYSERR to close it (signal serious error)
1793  */
1794 static int
1795 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1796                     const struct GNUNET_MessageHeader *message)
1797 {
1798   struct PeerGetMessage *get;
1799   uint32_t xquery_size;
1800   size_t reply_bf_size;
1801   uint16_t msize;
1802   enum GNUNET_BLOCK_Type type;
1803   enum GNUNET_DHT_RouteOption options;
1804   enum GNUNET_BLOCK_EvaluationResult eval;
1805   struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1806   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1807   const char *xquery;
1808
1809   GNUNET_break (0 !=
1810                 memcmp (peer, &my_identity,
1811                         sizeof (struct GNUNET_PeerIdentity)));
1812   /* parse and validate message */
1813   msize = ntohs (message->size);
1814   if (msize < sizeof (struct PeerGetMessage))
1815   {
1816     GNUNET_break_op (0);
1817     return GNUNET_YES;
1818   }
1819   get = (struct PeerGetMessage *) message;
1820   xquery_size = ntohl (get->xquery_size);
1821   if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1822   {
1823     GNUNET_break_op (0);
1824     return GNUNET_YES;
1825   }
1826   reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1827   type = ntohl (get->type);
1828   options = ntohl (get->options);
1829   xquery = (const char *) &get[1];
1830   reply_bf = NULL;
1831   GNUNET_STATISTICS_update (GDS_stats,
1832                             gettext_noop ("# P2P GET requests received"), 1,
1833                             GNUNET_NO);
1834   GNUNET_STATISTICS_update (GDS_stats,
1835                             gettext_noop ("# P2P GET bytes received"), msize,
1836                             GNUNET_NO);
1837   if (GNUNET_YES == log_route_details_stderr)
1838   {
1839     char *tmp;
1840
1841     tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1842     LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1843                  "XDHT GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n", 
1844                  GNUNET_h2s (&get->key), GNUNET_i2s (peer), tmp,
1845                  ntohl(get->hop_count),
1846                  GNUNET_CRYPTO_hash_matching_bits (&peer->hashPubKey, &get->key),
1847                  GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, &get->key),
1848                  ntohl(get->xquery_size), xquery
1849                 );
1850     GNUNET_free (tmp);
1851   }
1852
1853   if (reply_bf_size > 0)
1854     reply_bf =
1855         GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1856                                            GNUNET_CONSTANTS_BLOOMFILTER_K);
1857   eval =
1858       GNUNET_BLOCK_evaluate (GDS_block_context, type, &get->key, &reply_bf,
1859                              get->bf_mutator, xquery, xquery_size, NULL, 0);
1860   if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1861   {
1862     /* request invalid or block type not supported */
1863     GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1864     if (NULL != reply_bf)
1865       GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1866     return GNUNET_YES;
1867   }
1868   peer_bf =
1869       GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1870                                          GNUNET_CONSTANTS_BLOOMFILTER_K);
1871   GNUNET_break_op (GNUNET_YES ==
1872                    GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1873                                                       &peer->hashPubKey));
1874   /* remember request for routing replies */
1875   GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1876                    reply_bf, get->bf_mutator);
1877   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GET for %s at %s after %u hops\n",
1878               GNUNET_h2s (&get->key), GNUNET_i2s (&my_identity),
1879               (unsigned int) ntohl (get->hop_count));
1880   /* local lookup (this may update the reply_bf) */
1881   if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1882       (am_closest_peer (&get->key, peer_bf)))
1883   {
1884     if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1885     {
1886       GNUNET_STATISTICS_update (GDS_stats,
1887                                 gettext_noop
1888                                 ("# P2P FIND PEER requests processed"), 1,
1889                                 GNUNET_NO);
1890       handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
1891     }
1892     else
1893     {
1894       eval =
1895           GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
1896                                     &reply_bf, get->bf_mutator);
1897     }
1898   }
1899   else
1900   {
1901     GNUNET_STATISTICS_update (GDS_stats,
1902                               gettext_noop ("# P2P GET requests ONLY routed"),
1903                               1, GNUNET_NO);
1904   }
1905
1906   GDS_CLIENTS_process_get (options,
1907                            type,
1908                            ntohl(get->hop_count),
1909                            ntohl(get->desired_replication_level),
1910                            0, NULL,
1911                            &get->key);
1912
1913   /* P2P forwarding */
1914   if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1915     GDS_NEIGHBOURS_handle_get (type, options,
1916                                ntohl (get->desired_replication_level),
1917                                ntohl (get->hop_count), &get->key, xquery,
1918                                xquery_size, reply_bf, get->bf_mutator, peer_bf);
1919   /* clean up */
1920   if (NULL != reply_bf)
1921     GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1922   GNUNET_CONTAINER_bloomfilter_free (peer_bf);
1923   return GNUNET_YES;
1924 }
1925
1926
1927 /**
1928  * Core handler for p2p result messages.
1929  *
1930  * @param cls closure
1931  * @param message message
1932  * @param peer peer identity this notification is about
1933  * @return GNUNET_YES (do not cut p2p connection)
1934  */
1935 static int
1936 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1937                        const struct GNUNET_MessageHeader *message)
1938 {
1939   const struct PeerResultMessage *prm;
1940   const struct GNUNET_PeerIdentity *put_path;
1941   const struct GNUNET_PeerIdentity *get_path;
1942   const void *data;
1943   uint32_t get_path_length;
1944   uint32_t put_path_length;
1945   uint16_t msize;
1946   size_t data_size;
1947   enum GNUNET_BLOCK_Type type;
1948
1949   /* parse and validate message */
1950   msize = ntohs (message->size);
1951   if (msize < sizeof (struct PeerResultMessage))
1952   {
1953     GNUNET_break_op (0);
1954     return GNUNET_YES;
1955   }
1956   prm = (struct PeerResultMessage *) message;
1957   put_path_length = ntohl (prm->put_path_length);
1958   get_path_length = ntohl (prm->get_path_length);
1959   if ((msize <
1960        sizeof (struct PeerResultMessage) + (get_path_length +
1961                                             put_path_length) *
1962        sizeof (struct GNUNET_PeerIdentity)) ||
1963       (get_path_length >
1964        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1965       (put_path_length >
1966        GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1967   {
1968     GNUNET_break_op (0);
1969     return GNUNET_YES;
1970   }
1971   put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
1972   get_path = &put_path[put_path_length];
1973   type = ntohl (prm->type);
1974   data = (const void *) &get_path[get_path_length];
1975   data_size =
1976       msize - (sizeof (struct PeerResultMessage) +
1977                (get_path_length +
1978                 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1979   GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
1980                             1, GNUNET_NO);
1981   GNUNET_STATISTICS_update (GDS_stats,
1982                             gettext_noop ("# P2P RESULT bytes received"),
1983                             msize, GNUNET_NO);
1984   if (GNUNET_YES == log_route_details_stderr)
1985   {
1986     char *tmp;
1987
1988     tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1989     LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, "XDHT RESULT %s: %s->%s (%u)\n", 
1990                  GNUNET_h2s (&prm->key), GNUNET_i2s (peer), tmp,
1991                  get_path_length + 1);
1992     GNUNET_free (tmp);
1993   }
1994   /* if we got a HELLO, consider it for our own routing table */
1995   if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
1996   {
1997     const struct GNUNET_MessageHeader *h;
1998     struct GNUNET_PeerIdentity pid;
1999     int bucket;
2000
2001     /* Should be a HELLO, validate and consider using it! */
2002     if (data_size < sizeof (struct GNUNET_MessageHeader))
2003     {
2004       GNUNET_break_op (0);
2005       return GNUNET_YES;
2006     }
2007     h = data;
2008     if (data_size != ntohs (h->size))
2009     {
2010       GNUNET_break_op (0);
2011       return GNUNET_YES;
2012     }
2013     if (GNUNET_OK !=
2014         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
2015     {
2016       GNUNET_break_op (0);
2017       return GNUNET_YES;
2018     }
2019     if ((GNUNET_YES != disable_try_connect) &&
2020         0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
2021     {
2022       bucket = find_bucket (&pid.hashPubKey);
2023       if ((bucket >= 0) &&
2024           (k_buckets[bucket].peers_size < bucket_size) &&
2025           (NULL != GDS_transport_handle))
2026       {
2027         GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
2028         GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid, NULL, NULL); /*FIXME TRY_CONNECT change */
2029       }
2030     }
2031   }
2032
2033   /* append 'peer' to 'get_path' */
2034   {
2035     struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
2036
2037     memcpy (xget_path, get_path,
2038             get_path_length * sizeof (struct GNUNET_PeerIdentity));
2039     xget_path[get_path_length] = *peer;
2040     get_path_length++;
2041
2042     /* forward to local clients */
2043     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2044                               &prm->key, get_path_length, xget_path,
2045                               put_path_length, put_path, type, data_size, data);
2046     GDS_CLIENTS_process_get_resp (type,
2047                                   xget_path, get_path_length,
2048                                   put_path, put_path_length,
2049                                   GNUNET_TIME_absolute_ntoh (
2050                                     prm->expiration_time),
2051                                   &prm->key,
2052                                   data,
2053                                   data_size);
2054
2055     /* forward to other peers */
2056     GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2057                          &prm->key, put_path_length, put_path, get_path_length,
2058                          xget_path, data, data_size);
2059   }
2060
2061   return GNUNET_YES;
2062 }
2063
2064
2065 /**
2066  * Initialize neighbours subsystem.
2067  *
2068  * @return GNUNET_OK on success, GNUNET_SYSERR on error
2069  */
2070 int
2071 GDS_NEIGHBOURS_init ()
2072 {
2073   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2074     {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2075     {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2076     {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2077     {NULL, 0, 0}
2078   };
2079   unsigned long long temp_config_num;
2080
2081   disable_try_connect
2082     = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2083   if (GNUNET_OK ==
2084       GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2085                                              &temp_config_num))
2086     bucket_size = (unsigned int) temp_config_num;
2087   log_route_details_stderr =
2088     (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO;
2089   atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2090   coreAPI =
2091       GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
2092                            &handle_core_disconnect, NULL, GNUNET_NO, NULL,
2093                            GNUNET_NO, core_handlers);
2094   if (coreAPI == NULL)
2095     return GNUNET_SYSERR;
2096   all_known_peers = GNUNET_CONTAINER_multihashmap_create (256, GNUNET_NO);
2097   return GNUNET_OK;
2098 }
2099
2100
2101 /**
2102  * Shutdown neighbours subsystem.
2103  */
2104 void
2105 GDS_NEIGHBOURS_done ()
2106 {
2107   if (coreAPI == NULL)
2108     return;
2109   GNUNET_CORE_disconnect (coreAPI);
2110   coreAPI = NULL;
2111   GNUNET_ATS_performance_done (atsAPI);
2112   atsAPI = NULL;
2113   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2114   GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2115   all_known_peers = NULL;
2116   if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2117   {
2118     GNUNET_SCHEDULER_cancel (find_peer_task);
2119     find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2120   }
2121 }
2122
2123 /**
2124  * Get the ID of the local node.
2125  * 
2126  * @return identity of the local node
2127  */
2128 struct GNUNET_PeerIdentity *
2129 GDS_NEIGHBOURS_get_id ()
2130 {
2131     return &my_identity;
2132 }
2133
2134
2135 /* end of gnunet-service-dht_neighbours.c */