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