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