put ifdefs around DEBUG logs
[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 #if DEBUG_DHT
527   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
528               "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
529               GNUNET_h2s (key),
530               ctx->bf_mutator);
531 #endif
532   GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
533   return GNUNET_YES;
534 }
535
536
537 /**
538  * Task to send a find peer message for our own peer identifier
539  * so that we can find the closest peers in the network to ourselves
540  * and attempt to connect to them.
541  *
542  * @param cls closure for this task
543  * @param tc the context under which the task is running
544  */
545 static void
546 send_find_peer_message (void *cls,
547                         const struct GNUNET_SCHEDULER_TaskContext *tc)
548 {
549   struct GNUNET_TIME_Relative next_send_time;
550   struct BloomConstructorContext bcc;
551   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
552
553   find_peer_task = GNUNET_SCHEDULER_NO_TASK;
554   if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
555     return;
556   if (newly_found_peers > bucket_size) 
557   {
558     /* If we are finding many peers already, no need to send out our request right now! */
559     find_peer_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
560                                                    &send_find_peer_message, NULL);
561     newly_found_peers = 0;
562     return;
563   }
564   bcc.bf_mutator = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
565   bcc.bloom =
566     GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, GNUNET_CONSTANTS_BLOOMFILTER_K);
567   GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, 
568                                          &add_known_to_bloom,
569                                          &bcc);
570   GNUNET_STATISTICS_update (GDS_stats,
571                             gettext_noop ("# FIND PEER messages initiated"), 1,
572                             GNUNET_NO);
573   peer_bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
574                                                DHT_BLOOM_SIZE,
575                                                GNUNET_CONSTANTS_BLOOMFILTER_K);
576   // FIXME: pass priority!?
577   GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
578                              GNUNET_DHT_RO_FIND_PEER,
579                              FIND_PEER_REPLICATION_LEVEL,
580                              0,
581                              &my_identity.hashPubKey,
582                              NULL, 0,
583                              bcc.bloom, bcc.bf_mutator, 
584                              peer_bf);
585   GNUNET_CONTAINER_bloomfilter_free (peer_bf);
586   GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
587   /* schedule next round */
588   next_send_time.rel_value =
589     DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
590     GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
591                               DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / (newly_found_peers+1));
592   newly_found_peers = 0;
593   find_peer_task = GNUNET_SCHEDULER_add_delayed (next_send_time, 
594                                                  &send_find_peer_message,
595                                                  NULL);  
596 }
597
598
599 /**
600  * Method called whenever a peer connects.
601  *
602  * @param cls closure
603  * @param peer peer identity this notification is about
604  * @param atsi performance data
605  * @param atsi_count number of records in 'atsi'
606  */
607 static void
608 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
609                      const struct GNUNET_ATS_Information *atsi,
610                      unsigned int atsi_count)
611 {
612   struct PeerInfo *ret;
613   int peer_bucket;
614
615   /* Check for connect to self message */
616   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
617     return;
618 #if DEBUG_DHT
619   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
620               "Connected %s to %s\n",
621               GNUNET_i2s (&my_identity),
622               GNUNET_h2s (&peer->hashPubKey));
623 #endif
624   if (GNUNET_YES ==
625       GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
626                                               &peer->hashPubKey))
627   {
628     GNUNET_break (0);
629     return;
630   }
631   GNUNET_STATISTICS_update (GDS_stats,
632                             gettext_noop ("# Peers connected"), 1,
633                             GNUNET_NO);
634   peer_bucket = find_bucket (&peer->hashPubKey);
635   GNUNET_assert ( (peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS) );
636   ret = GNUNET_malloc (sizeof (struct PeerInfo));
637 #if 0
638   ret->latency = latency;
639   ret->distance = distance;
640 #endif
641   ret->id = *peer;
642   GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
643                                     k_buckets[peer_bucket].tail, ret);
644   k_buckets[peer_bucket].peers_size++;
645   closest_bucket = GNUNET_MAX (closest_bucket,
646                                peer_bucket);
647   if ( (peer_bucket > 0) &&
648        (k_buckets[peer_bucket].peers_size <= bucket_size) )
649   {
650     ret->preference_task = GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
651     newly_found_peers++;
652   }
653   GNUNET_assert (GNUNET_OK ==
654                  GNUNET_CONTAINER_multihashmap_put (all_known_peers, 
655                                                     &peer->hashPubKey, ret,
656                                                     GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
657   if (1 == GNUNET_CONTAINER_multihashmap_size (all_known_peers))
658   {
659     /* got a first connection, good time to start with FIND PEER requests... */
660     find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message,
661                                                NULL);    
662   }
663 }
664
665
666 /**
667  * Method called whenever a peer disconnects.
668  *
669  * @param cls closure
670  * @param peer peer identity this notification is about
671  */
672 static void
673 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
674 {
675   struct PeerInfo *to_remove;
676   int current_bucket;
677   struct P2PPendingMessage *pos;
678   unsigned int discarded;
679
680   /* Check for disconnect from self message */
681   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
682     return;
683 #if DEBUG_DHT
684   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
685               "Disconnected %s from %s\n",
686               GNUNET_i2s (&my_identity),
687               GNUNET_h2s (&peer->hashPubKey));
688 #endif
689   to_remove =
690       GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
691   if (NULL == to_remove)
692     {
693       GNUNET_break (0);
694       return;
695     }
696   GNUNET_STATISTICS_update (GDS_stats,
697                             gettext_noop ("# Peers connected"), -1,
698                             GNUNET_NO);
699   GNUNET_assert (GNUNET_YES ==
700                  GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
701                                                        &peer->hashPubKey,
702                                                        to_remove));
703   if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
704   {
705     GNUNET_SCHEDULER_cancel (to_remove->preference_task);
706     to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
707   }
708   current_bucket = find_bucket (&to_remove->id.hashPubKey);
709   GNUNET_assert (current_bucket >= 0);
710   GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
711                                k_buckets[current_bucket].tail,
712                                to_remove);
713   GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
714   k_buckets[current_bucket].peers_size--;
715   while ( (closest_bucket > 0) &&
716           (k_buckets[closest_bucket].peers_size == 0) )
717     closest_bucket--;
718
719   if (to_remove->th != NULL) 
720   {
721     GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
722     to_remove->th = NULL;
723   }
724   discarded = 0;
725   while (NULL != (pos = to_remove->head))
726   {
727     GNUNET_CONTAINER_DLL_remove (to_remove->head,
728                                  to_remove->tail,
729                                  pos);
730     discarded++;
731     GNUNET_free (pos);
732   }
733   GNUNET_STATISTICS_update (GDS_stats,
734                             gettext_noop ("# Queued messages discarded (peer disconnected)"), discarded,
735                             GNUNET_NO);
736   GNUNET_free (to_remove);
737 }
738
739
740 /**
741  * Called when core is ready to send a message we asked for
742  * out to the destination.
743  *
744  * @param cls the 'struct PeerInfo' of the target peer
745  * @param size number of bytes available in buf
746  * @param buf where the callee should write the message
747  * @return number of bytes written to buf
748  */
749 static size_t
750 core_transmit_notify (void *cls, size_t size, void *buf)
751 {
752   struct PeerInfo *peer = cls;
753   char *cbuf = buf;
754   struct P2PPendingMessage *pending;
755   size_t off;
756   size_t msize;
757
758   peer->th = NULL;
759   while ( (NULL != (pending = peer->head)) &&
760           (GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value == 0) )
761   {
762     peer->pending_count--;
763     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
764     GNUNET_free (pending);
765   }
766   if (pending == NULL)
767   {
768     /* no messages pending */
769     return 0;
770   }
771   if (buf == NULL)
772   {
773     peer->th 
774       = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
775                                            pending->importance,
776                                            GNUNET_TIME_absolute_get_remaining (pending->timeout),
777                                            &peer->id, ntohs (pending->msg->size),
778                                            &core_transmit_notify, peer);
779     GNUNET_break (NULL != peer->th);
780     return 0;
781   }
782   off = 0;
783   while ( (NULL != (pending = peer->head)) &&
784           (size - off >= (msize = ntohs (pending->msg->size))) )
785   {
786     GNUNET_STATISTICS_update (GDS_stats,
787                               gettext_noop ("# Bytes transmitted to other peers"), msize,
788                               GNUNET_NO);
789     memcpy (&cbuf[off], pending->msg, msize);
790     off += msize;
791     peer->pending_count--;
792     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
793     GNUNET_free (pending);
794   }
795   if (peer->head != NULL)
796   {
797     peer->th 
798       = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
799                                            pending->importance,
800                                            GNUNET_TIME_absolute_get_remaining (pending->timeout),
801                                            &peer->id, msize,
802                                            &core_transmit_notify, peer);
803     GNUNET_break (NULL != peer->th);
804   }
805   return off;
806 }
807
808
809 /**
810  * Transmit all messages in the peer's message queue.
811  *
812  * @param peer message queue to process
813  */
814 static void
815 process_peer_queue (struct PeerInfo *peer)
816 {
817   struct P2PPendingMessage *pending;
818
819   if (NULL == (pending = peer->head))
820     return;
821   if (NULL != peer->th)
822     return;
823   GNUNET_STATISTICS_update (GDS_stats,
824                             gettext_noop ("# Bytes of bandwdith requested from core"),
825                             ntohs (pending->msg->size),
826                             GNUNET_NO);
827   peer->th 
828     = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
829                                          pending->importance,
830                                          GNUNET_TIME_absolute_get_remaining (pending->timeout),
831                                          &peer->id,
832                                          ntohs (pending->msg->size),
833                                          &core_transmit_notify, peer);
834   GNUNET_break (NULL != peer->th);
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 () * 6.0)
855   {
856     /* forcefully terminate */
857     return 0;
858   }
859   if (hop_count > GDS_NSE_get () * 4.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   GNUNET_assert (bucket_num >= 0);
966   bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
967   pos = k_buckets[bucket_num].head;
968   count = 0;
969   while ((pos != NULL) && (count < bucket_size))
970   {
971     if ((bloom != NULL) &&
972         (GNUNET_YES ==
973          GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
974     {
975       pos = pos->next;
976       continue;                 /* Skip already checked entries */
977     }
978     other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
979     if (other_bits > bits)
980       return GNUNET_NO;
981     if (other_bits == bits)        /* We match the same number of bits */
982       return GNUNET_YES;
983     pos = pos->next;
984   }
985   /* No peers closer, we are the closest! */
986   return GNUNET_YES;
987 }
988
989
990 /**
991  * Select a peer from the routing table that would be a good routing
992  * destination for sending a message for "key".  The resulting peer
993  * must not be in the set of blocked peers.<p>
994  *
995  * Note that we should not ALWAYS select the closest peer to the
996  * target, peers further away from the target should be chosen with
997  * exponentially declining probability.
998  *
999  * FIXME: double-check that this is fine
1000  * 
1001  *
1002  * @param key the key we are selecting a peer to route to
1003  * @param bloom a bloomfilter containing entries this request has seen already
1004  * @param hops how many hops has this message traversed thus far
1005  * @return Peer to route to, or NULL on error
1006  */
1007 static struct PeerInfo *
1008 select_peer (const GNUNET_HashCode *key,
1009              const struct GNUNET_CONTAINER_BloomFilter *bloom, 
1010              uint32_t hops)
1011 {
1012   unsigned int bc;
1013   unsigned int count;
1014   unsigned int selected;
1015   struct PeerInfo *pos;
1016   unsigned int dist;
1017   unsigned int smallest_distance;
1018   struct PeerInfo *chosen;
1019
1020   if (hops >= GDS_NSE_get ())
1021   {
1022     /* greedy selection (closest peer that is not in bloomfilter) */
1023     smallest_distance = UINT_MAX;
1024     chosen = NULL;
1025     for (bc = 0; bc < closest_bucket; bc++)
1026     {
1027       pos = k_buckets[bc].head;
1028       count = 0;
1029       while ((pos != NULL) && (count < bucket_size))
1030       {
1031         if ( (bloom == NULL) ||
1032              (GNUNET_NO ==
1033               GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1034         {
1035           dist = get_distance (key, &pos->id.hashPubKey);
1036           if (dist < smallest_distance)
1037           {
1038             chosen = pos;
1039             smallest_distance = dist;
1040           }
1041         }
1042         else
1043         {
1044 #if DEBUG_DHT
1045           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1046                       "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1047                       GNUNET_i2s (&pos->id),
1048                       GNUNET_h2s (key));
1049 #endif
1050           GNUNET_STATISTICS_update (GDS_stats,
1051                                     gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1052                                     GNUNET_NO);
1053         }
1054         count++;
1055         pos = pos->next;
1056       }
1057     }
1058     if (NULL == chosen)
1059       GNUNET_STATISTICS_update (GDS_stats,
1060                                 gettext_noop ("# Peer selection failed"), 1,
1061                                 GNUNET_NO);
1062     return chosen;
1063   }
1064
1065   /* select "random" peer */
1066   /* count number of peers that are available and not filtered */
1067   count = 0;
1068   for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1069   {
1070     pos = k_buckets[bc].head;
1071     while ((pos != NULL) && (count < bucket_size))
1072     {
1073       if ( (bloom != NULL) &&
1074            (GNUNET_YES ==
1075             GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1076       {
1077         GNUNET_STATISTICS_update (GDS_stats,
1078                                   gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1079                                   GNUNET_NO);
1080 #if DEBUG_DHT
1081         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1082                     "Excluded peer `%s' due to BF match in random routing for %s\n",
1083                     GNUNET_i2s (&pos->id),
1084                     GNUNET_h2s (key));
1085 #endif
1086         pos = pos->next;
1087         continue;               /* Ignore bloomfiltered peers */
1088       }
1089       count++;
1090       pos = pos->next;
1091     }
1092   }
1093   if (count == 0)               /* No peers to select from! */
1094   {
1095     GNUNET_STATISTICS_update (GDS_stats,
1096                               gettext_noop ("# Peer selection failed"), 1,
1097                               GNUNET_NO);
1098     return NULL;
1099   }
1100   /* Now actually choose a peer */
1101   selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1102   count = 0;
1103   for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1104   {
1105     pos = k_buckets[bc].head;
1106     while ((pos != NULL) && (count < bucket_size))
1107     {
1108       if ( (bloom != NULL) &&
1109            (GNUNET_YES ==
1110             GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1111       {
1112         pos = pos->next;
1113         continue;               /* Ignore bloomfiltered peers */
1114       }
1115       if (0 == selected--)
1116         return pos;
1117       pos = pos->next;
1118     }
1119   }
1120   GNUNET_break (0);
1121   return NULL;
1122 }
1123
1124
1125 /**
1126  * Compute the set of peers that the given request should be
1127  * forwarded to.
1128  *
1129  * @param key routing key
1130  * @param bloom bloom filter excluding peers as targets, all selected
1131  *        peers will be added to the bloom filter
1132  * @param hop_count number of hops the request has traversed so far
1133  * @param target_replication desired number of replicas
1134  * @param targets where to store an array of target peers (to be
1135  *         free'd by the caller)
1136  * @return number of peers returned in 'targets'.
1137  */
1138 static unsigned int
1139 get_target_peers (const GNUNET_HashCode *key,
1140                   struct GNUNET_CONTAINER_BloomFilter *bloom,
1141                   uint32_t hop_count,
1142                   uint32_t target_replication,
1143                   struct PeerInfo ***targets)
1144 {
1145   unsigned int ret;
1146   unsigned int off;
1147   struct PeerInfo **rtargets;
1148   struct PeerInfo *nxt;
1149
1150   GNUNET_assert (NULL != bloom);
1151   ret = get_forward_count (hop_count, target_replication);
1152   if (ret == 0)
1153   {
1154     *targets = NULL;
1155     return 0;
1156   }
1157   rtargets = GNUNET_malloc (sizeof (struct PeerInfo*) * ret);
1158   for (off = 0; off < ret; off++)
1159   {
1160     nxt = select_peer (key, bloom, hop_count);
1161     if (nxt == NULL)
1162       break;      
1163     rtargets[off] = nxt;
1164     GNUNET_break (GNUNET_NO ==
1165                   GNUNET_CONTAINER_bloomfilter_test (bloom, &nxt->id.hashPubKey));
1166     GNUNET_CONTAINER_bloomfilter_add (bloom, &rtargets[off]->id.hashPubKey);
1167   }
1168 #if DEBUG_DHT
1169   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1170               "Selected %u/%u peers at hop %u for %s (target was %u)\n",
1171               off,
1172               GNUNET_CONTAINER_multihashmap_size (all_known_peers),
1173               (unsigned int) hop_count,
1174               GNUNET_h2s (key),
1175               ret);
1176 #endif
1177   if (0 == off)
1178   {
1179     GNUNET_free (rtargets);
1180     *targets = NULL;
1181     return 0;
1182   }
1183   *targets = rtargets;
1184   return off;
1185 }
1186
1187
1188 /**
1189  * Perform a PUT operation.   Forwards the given request to other
1190  * peers.   Does not store the data locally.  Does not give the
1191  * data to local clients.  May do nothing if this is the only
1192  * peer in the network (or if we are the closest peer in the
1193  * network).
1194  *
1195  * @param type type of the block
1196  * @param options routing options
1197  * @param desired_replication_level desired replication count
1198  * @param expiration_time when does the content expire
1199  * @param hop_count how many hops has this message traversed so far
1200  * @param bf Bloom filter of peers this PUT has already traversed
1201  * @param key key for the content
1202  * @param put_path_length number of entries in put_path
1203  * @param put_path peers this request has traversed so far (if tracked)
1204  * @param data payload to store
1205  * @param data_size number of bytes in data
1206  */
1207 void
1208 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1209                            enum GNUNET_DHT_RouteOption options,
1210                            uint32_t desired_replication_level,
1211                            struct GNUNET_TIME_Absolute expiration_time,
1212                            uint32_t hop_count,
1213                            struct GNUNET_CONTAINER_BloomFilter *bf,
1214                            const GNUNET_HashCode *key,
1215                            unsigned int put_path_length,
1216                            struct GNUNET_PeerIdentity *put_path,
1217                            const void *data,
1218                            size_t data_size)
1219 {
1220   unsigned int target_count;
1221   unsigned int i;
1222   struct PeerInfo **targets;
1223   struct PeerInfo *target;
1224   struct P2PPendingMessage *pending;
1225   size_t msize;
1226   struct PeerPutMessage *ppm;
1227   struct GNUNET_PeerIdentity *pp;
1228   
1229   GNUNET_assert (NULL != bf);
1230 #if DEBUG_DHT
1231   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1232               "Adding myself (%s) to PUT bloomfilter for %s\n",
1233               GNUNET_i2s (&my_identity),
1234               GNUNET_h2s (key));
1235 #endif
1236   GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1237   GNUNET_STATISTICS_update (GDS_stats,
1238                             gettext_noop ("# PUT requests routed"), 1,
1239                             GNUNET_NO);
1240   target_count = get_target_peers (key, bf, hop_count,
1241                                    desired_replication_level,
1242                                    &targets);
1243   if (0 == target_count)
1244     { 
1245 #if DEBUG_DHT
1246       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1247                   "Routing PUT for %s terminates after %u hops at %s\n",
1248                   GNUNET_h2s (key),
1249                   (unsigned int) hop_count,
1250                   GNUNET_i2s (&my_identity));
1251 #endif
1252       return;
1253     }
1254   msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size + sizeof (struct PeerPutMessage);
1255   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1256   {
1257     put_path_length = 0;
1258     msize = data_size + sizeof (struct PeerPutMessage);
1259   }
1260   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1261   {
1262     GNUNET_break (0);
1263     GNUNET_free (targets);
1264     return;
1265   }
1266   GNUNET_STATISTICS_update (GDS_stats,
1267                             gettext_noop ("# PUT messages queued for transmission"), target_count,
1268                             GNUNET_NO);
1269   for (i=0;i<target_count;i++)
1270   {
1271     target = targets[i];
1272 #if DEBUG_DHT
1273     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1274                 "Routing PUT for %s after %u hops to %s\n",
1275                 GNUNET_h2s (key),
1276                 (unsigned int) hop_count,
1277                 GNUNET_i2s (&target->id));
1278 #endif
1279     pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1280     pending->importance = 0; /* FIXME */
1281     pending->timeout = expiration_time;   
1282     ppm = (struct PeerPutMessage*) &pending[1];
1283     pending->msg = &ppm->header;
1284     ppm->header.size = htons (msize);
1285     ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1286     ppm->options = htonl (options);
1287     ppm->type = htonl (type);
1288     ppm->hop_count = htonl (hop_count + 1);
1289     ppm->desired_replication_level = htonl (desired_replication_level);
1290     ppm->put_path_length = htonl (put_path_length);
1291     ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1292     GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &target->id.hashPubKey));
1293     GNUNET_assert (GNUNET_OK ==
1294                    GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1295                                                               ppm->bloomfilter,
1296                                                               DHT_BLOOM_SIZE));
1297     ppm->key = *key;
1298     pp = (struct GNUNET_PeerIdentity*) &ppm[1];
1299     memcpy (pp, put_path, sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1300     memcpy (&pp[put_path_length], data, data_size);
1301     GNUNET_CONTAINER_DLL_insert_tail (target->head,
1302                                       target->tail,
1303                                       pending);
1304     target->pending_count++;
1305     process_peer_queue (target);
1306   }
1307   GNUNET_free (targets);
1308 }
1309
1310
1311 /**
1312  * Perform a GET operation.  Forwards the given request to other
1313  * peers.  Does not lookup the key locally.  May do nothing if this is
1314  * the only peer in the network (or if we are the closest peer in the
1315  * network).
1316  *
1317  * @param type type of the block
1318  * @param options routing options
1319  * @param desired_replication_level desired replication count
1320  * @param hop_count how many hops did this request traverse so far?
1321  * @param key key for the content
1322  * @param xquery extended query
1323  * @param xquery_size number of bytes in xquery
1324  * @param reply_bf bloomfilter to filter duplicates
1325  * @param reply_bf_mutator mutator for reply_bf
1326  * @param peer_bf filter for peers not to select (again)
1327  */
1328 void
1329 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1330                            enum GNUNET_DHT_RouteOption options,
1331                            uint32_t desired_replication_level,
1332                            uint32_t hop_count,
1333                            const GNUNET_HashCode *key,
1334                            const void *xquery,
1335                            size_t xquery_size,
1336                            const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1337                            uint32_t reply_bf_mutator,
1338                            struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1339 {
1340   unsigned int target_count;
1341   unsigned int i;
1342   struct PeerInfo **targets;
1343   struct PeerInfo *target;
1344   struct P2PPendingMessage *pending;
1345   size_t msize;
1346   struct PeerGetMessage *pgm;
1347   char *xq;
1348   size_t reply_bf_size;
1349
1350   GNUNET_assert (NULL != peer_bf);  
1351   GNUNET_STATISTICS_update (GDS_stats,
1352                             gettext_noop ("# GET requests routed"), 1,
1353                             GNUNET_NO);
1354   target_count = get_target_peers (key, peer_bf, hop_count,
1355                                    desired_replication_level,
1356                                    &targets);
1357 #if DEBUG_DHT
1358   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1359               "Adding myself (%s) to GET bloomfilter for %s\n",
1360               GNUNET_i2s (&my_identity),
1361               GNUNET_h2s (key));
1362 #endif
1363   GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity.hashPubKey);
1364   if (0 == target_count)
1365   {
1366 #if DEBUG_DHT
1367     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1368                 "Routing GET for %s terminates after %u hops at %s\n",
1369                 GNUNET_h2s (key),
1370                 (unsigned int) hop_count,
1371                 GNUNET_i2s (&my_identity));
1372 #endif
1373     return;
1374   }
1375   reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1376   msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1377   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1378   {
1379     GNUNET_break (0);
1380     GNUNET_free (targets);
1381     return;
1382   }
1383   GNUNET_STATISTICS_update (GDS_stats,
1384                             gettext_noop ("# GET messages queued for transmission"), target_count,
1385                             GNUNET_NO);
1386   /* forward request */
1387   for (i=0;i<target_count;i++)
1388   {
1389     target = targets[i];
1390 #if DEBUG_DHT
1391     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1392                 "Routing GET for %s after %u hops to %s\n",
1393                 GNUNET_h2s (key),
1394                 (unsigned int) hop_count,
1395                 GNUNET_i2s (&target->id));
1396 #endif
1397     pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
1398     pending->importance = 0; /* FIXME */
1399     pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1400     pgm = (struct PeerGetMessage*) &pending[1];
1401     pending->msg = &pgm->header;
1402     pgm->header.size = htons (msize);
1403     pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1404     pgm->options = htonl (options);
1405     pgm->type = htonl (type);
1406     pgm->hop_count = htonl (hop_count + 1);
1407     pgm->desired_replication_level = htonl (desired_replication_level);
1408     pgm->xquery_size = htonl (xquery_size);
1409     pgm->bf_mutator = reply_bf_mutator; 
1410     GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &target->id.hashPubKey));
1411     GNUNET_assert (GNUNET_OK ==
1412                    GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1413                                                               pgm->bloomfilter,
1414                                                               DHT_BLOOM_SIZE));
1415     pgm->key = *key;
1416     xq = (char *) &pgm[1];
1417     memcpy (xq, xquery, xquery_size);
1418     if (NULL != reply_bf)
1419       GNUNET_assert (GNUNET_OK ==
1420                      GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1421                                                                 &xq[xquery_size],
1422                                                                 reply_bf_size));
1423     GNUNET_CONTAINER_DLL_insert_tail (target->head,
1424                                       target->tail,
1425                                       pending);
1426     target->pending_count++;
1427     process_peer_queue (target);
1428   }
1429   GNUNET_free (targets);
1430 }
1431
1432
1433 /**
1434  * Handle a reply (route to origin).  Only forwards the reply back to
1435  * the given peer.  Does not do local caching or forwarding to local
1436  * clients.
1437  *
1438  * @param target neighbour that should receive the block (if still connected)
1439  * @param type type of the block
1440  * @param expiration_time when does the content expire
1441  * @param key key for the content
1442  * @param put_path_length number of entries in put_path
1443  * @param put_path peers the original PUT traversed (if tracked)
1444  * @param get_path_length number of entries in put_path
1445  * @param get_path peers this reply has traversed so far (if tracked)
1446  * @param data payload of the reply
1447  * @param data_size number of bytes in data
1448  */
1449 void
1450 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1451                              enum GNUNET_BLOCK_Type type,
1452                              struct GNUNET_TIME_Absolute expiration_time,
1453                              const GNUNET_HashCode *key,
1454                              unsigned int put_path_length,
1455                              const struct GNUNET_PeerIdentity *put_path,
1456                              unsigned int get_path_length,
1457                              const struct GNUNET_PeerIdentity *get_path,
1458                              const void *data,
1459                              size_t data_size)
1460 {
1461   struct PeerInfo *pi;
1462   struct P2PPendingMessage *pending;
1463   size_t msize;
1464   struct PeerResultMessage *prm;
1465   struct GNUNET_PeerIdentity *paths;
1466   
1467   msize = data_size + sizeof (struct PeerResultMessage) + 
1468     (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity);
1469   if ( (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1470        (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1471        (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1472        (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE) )
1473   {
1474     GNUNET_break (0);
1475     return;
1476   }
1477   pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers,
1478                                           &target->hashPubKey);
1479   if (NULL == pi)
1480   {
1481     /* peer disconnected in the meantime, drop reply */
1482     return;
1483   }
1484   GNUNET_STATISTICS_update (GDS_stats,
1485                             gettext_noop ("# RESULT messages queued for transmission"), 1,
1486                             GNUNET_NO);
1487   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
1488   pending->importance = 0; /* FIXME */
1489   pending->timeout = expiration_time;
1490   prm = (struct PeerResultMessage*) &pending[1];
1491   pending->msg = &prm->header;
1492   prm->header.size = htons (msize);
1493   prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1494   prm->type = htonl (type);
1495   prm->put_path_length = htonl (put_path_length);
1496   prm->get_path_length = htonl (get_path_length);
1497   prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1498   prm->key = *key;
1499   paths = (struct GNUNET_PeerIdentity*) &prm[1];
1500   memcpy (paths, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
1501   memcpy (&paths[put_path_length],
1502           get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1503   memcpy (&paths[put_path_length + get_path_length],
1504           data, data_size);
1505   GNUNET_CONTAINER_DLL_insert (pi->head,
1506                                pi->tail,
1507                                pending);
1508   pi->pending_count++;
1509   process_peer_queue (pi);
1510 }
1511
1512
1513 /**
1514  * To be called on core init/fail.
1515  *
1516  * @param cls service closure
1517  * @param server handle to the server for this service
1518  * @param identity the public identity of this peer
1519  */
1520 static void
1521 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1522            const struct GNUNET_PeerIdentity *identity)
1523 {
1524   GNUNET_assert (server != NULL);
1525   my_identity = *identity;
1526 }
1527
1528
1529 /**
1530  * Core handler for p2p put requests.
1531  *
1532  * @param cls closure
1533  * @param peer sender of the request
1534  * @param message message
1535  * @param peer peer identity this notification is about
1536  * @param atsi performance data
1537  * @param atsi_count number of records in 'atsi'
1538  * @return GNUNET_OK to keep the connection open,
1539  *         GNUNET_SYSERR to close it (signal serious error)
1540  */
1541 static int
1542 handle_dht_p2p_put (void *cls,
1543                     const struct GNUNET_PeerIdentity *peer,
1544                     const struct GNUNET_MessageHeader *message,
1545                     const struct GNUNET_ATS_Information
1546                     *atsi,
1547                     unsigned int atsi_count)
1548 {
1549   const struct PeerPutMessage *put;
1550   const struct GNUNET_PeerIdentity *put_path;
1551   const void *payload;
1552   uint32_t putlen;
1553   uint16_t msize;
1554   size_t payload_size;
1555   enum GNUNET_DHT_RouteOption options;
1556   struct GNUNET_CONTAINER_BloomFilter *bf;
1557   GNUNET_HashCode test_key;
1558   
1559   msize = ntohs (message->size);
1560   if (msize < sizeof (struct PeerPutMessage))
1561   {
1562     GNUNET_break_op (0);
1563     return GNUNET_YES;
1564   }
1565   put = (const struct PeerPutMessage*) message;
1566   putlen = ntohl (put->put_path_length);
1567   if ( (msize < sizeof (struct PeerPutMessage) + putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1568        (putlen > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1569     {
1570       GNUNET_break_op (0);
1571       return GNUNET_YES;
1572     }
1573   GNUNET_STATISTICS_update (GDS_stats,
1574                             gettext_noop ("# P2P PUT requests received"), 1,
1575                             GNUNET_NO);
1576   put_path = (const struct GNUNET_PeerIdentity*) &put[1];  
1577   payload = &put_path[putlen];
1578   options = ntohl (put->options);
1579   payload_size = msize - (sizeof (struct PeerPutMessage) + 
1580                           putlen * sizeof (struct GNUNET_PeerIdentity));
1581   switch (GNUNET_BLOCK_get_key (GDS_block_context,
1582                                 ntohl (put->type),
1583                                 payload, payload_size,
1584                                 &test_key))
1585   {
1586   case GNUNET_YES:
1587     if (0 != memcmp (&test_key, &put->key, sizeof (GNUNET_HashCode)))
1588     {
1589       GNUNET_break_op (0);
1590       return GNUNET_YES;
1591     }
1592     break;
1593   case GNUNET_NO:
1594     GNUNET_break_op (0);
1595     return GNUNET_YES;
1596   case GNUNET_SYSERR:
1597     /* cannot verify, good luck */
1598     break;
1599   }
1600 #if DEBUG_DHT
1601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1602               "PUT for %s at %s\n",
1603               GNUNET_h2s (&put->key),
1604               GNUNET_i2s (&my_identity));
1605 #endif
1606   bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter,
1607                                           DHT_BLOOM_SIZE,
1608                                           GNUNET_CONSTANTS_BLOOMFILTER_K);
1609   GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1610   {
1611     struct GNUNET_PeerIdentity pp[putlen+1];
1612   
1613     /* extend 'put path' by sender */
1614     if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1615     {
1616       memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1617       pp[putlen] = *peer;
1618       putlen++;
1619     }
1620     else
1621       putlen = 0;
1622     
1623     /* give to local clients */
1624     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1625                              &put->key,
1626                              0, NULL,
1627                              putlen,
1628                              pp,
1629                              ntohl (put->type),
1630                              payload_size,
1631                              payload);
1632     /* store locally */
1633     if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1634          (am_closest_peer (&put->key,
1635                            bf) ) )
1636       GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1637                                 &put->key,
1638                                 putlen, pp,
1639                                 ntohl (put->type),
1640                                 payload_size,
1641                                 payload);
1642     /* route to other peers */
1643     GDS_NEIGHBOURS_handle_put (ntohl (put->type),
1644                                options,
1645                                ntohl (put->desired_replication_level),
1646                                GNUNET_TIME_absolute_ntoh (put->expiration_time),
1647                                ntohl (put->hop_count),
1648                                bf,
1649                                &put->key,
1650                                putlen, pp,
1651                                payload,
1652                                payload_size);
1653   }
1654   GNUNET_CONTAINER_bloomfilter_free (bf);
1655   return GNUNET_YES;
1656 }
1657
1658
1659 /**
1660  * We have received a FIND PEER request.  Send matching
1661  * HELLOs back.
1662  *
1663  * @param sender sender of the FIND PEER request
1664  * @param key peers close to this key are desired
1665  * @param bf peers matching this bf are excluded
1666  * @param bf_mutator mutator for bf
1667  */
1668 static void
1669 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1670                   const GNUNET_HashCode *key,
1671                   struct GNUNET_CONTAINER_BloomFilter *bf,
1672                   uint32_t bf_mutator)
1673 {
1674   int bucket_idx;
1675   struct PeerBucket *bucket;
1676   struct PeerInfo *peer;
1677   unsigned int choice;
1678   GNUNET_HashCode mhash;
1679   const struct GNUNET_HELLO_Message *hello;
1680
1681   /* first, check about our own HELLO */
1682   if (NULL != GDS_my_hello)
1683   {
1684     GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1685     if ( (NULL == bf) ||
1686          (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) )
1687     {
1688       GDS_NEIGHBOURS_handle_reply (sender,
1689                                    GNUNET_BLOCK_TYPE_DHT_HELLO,
1690                                    GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1691                                    key,
1692                                    0, NULL,
1693                                    0, NULL,
1694                                    GDS_my_hello,
1695                                    GNUNET_HELLO_size ((const struct GNUNET_HELLO_Message*) GDS_my_hello));
1696     }
1697     else
1698     {
1699       GNUNET_STATISTICS_update (GDS_stats,
1700                                 gettext_noop ("# FIND PEER requests ignored due to Bloomfilter"), 1,
1701                                 GNUNET_NO);
1702     }
1703   }
1704   else
1705   {
1706     GNUNET_STATISTICS_update (GDS_stats,
1707                               gettext_noop ("# FIND PEER requests ignored due to lack of HELLO"), 1,
1708                               GNUNET_NO);
1709   }
1710
1711   /* then, also consider sending a random HELLO from the closest bucket */
1712   if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
1713     bucket_idx = closest_bucket;
1714   else
1715     bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1716   if (bucket_idx == GNUNET_SYSERR)
1717     return;
1718   bucket = &k_buckets[bucket_idx];
1719   if (bucket->peers_size == 0)
1720     return;
1721   choice = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1722                                      bucket->peers_size);
1723   peer = bucket->head;
1724   while (choice > 0)
1725   {
1726     GNUNET_assert (peer != NULL);
1727     peer = peer->next;
1728     choice--;
1729   }
1730   choice = bucket->peers_size;
1731   do
1732     {
1733       peer = peer->next;
1734       if (choice-- == 0)
1735         return; /* no non-masked peer available */
1736       if (peer == NULL)
1737         peer = bucket->head;
1738       GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1739       hello = GDS_HELLO_get (&peer->id);
1740     }
1741   while ( (hello == NULL) ||
1742           (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) );
1743   GDS_NEIGHBOURS_handle_reply (sender,
1744                                GNUNET_BLOCK_TYPE_DHT_HELLO,
1745                                GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1746                                key,
1747                                0, NULL,
1748                                0, NULL,
1749                                hello,
1750                                GNUNET_HELLO_size (hello));    
1751 }
1752
1753
1754 /**
1755  * Core handler for p2p get requests.
1756  *
1757  * @param cls closure
1758  * @param peer sender of the request
1759  * @param message message
1760  * @param peer peer identity this notification is about
1761  * @param atsi performance data
1762  * @param atsi_count number of records in 'atsi'
1763  * @return GNUNET_OK to keep the connection open,
1764  *         GNUNET_SYSERR to close it (signal serious error)
1765  */
1766 static int
1767 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1768                     const struct GNUNET_MessageHeader *message,
1769                     const struct GNUNET_ATS_Information
1770                     *atsi,
1771                     unsigned int atsi_count)
1772 {
1773   struct PeerGetMessage *get;
1774   uint32_t xquery_size;
1775   size_t reply_bf_size;
1776   uint16_t msize;
1777   enum GNUNET_BLOCK_Type type;
1778   enum GNUNET_DHT_RouteOption options;
1779   enum GNUNET_BLOCK_EvaluationResult eval;
1780   struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1781   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1782   const char *xquery;
1783
1784   GNUNET_break (0 != memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)));
1785   /* parse and validate message */
1786   msize = ntohs (message->size);
1787   if (msize < sizeof (struct PeerGetMessage))
1788   {
1789     GNUNET_break_op (0);
1790     return GNUNET_YES;
1791   }
1792   get = (struct PeerGetMessage *) message;
1793   xquery_size = ntohl (get->xquery_size);
1794   if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1795   {
1796     GNUNET_break_op (0);
1797     return GNUNET_YES;
1798   }
1799   GNUNET_STATISTICS_update (GDS_stats,
1800                             gettext_noop ("# P2P GET requests received"), 1,
1801                             GNUNET_NO);
1802   reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1803   type = ntohl (get->type);
1804   options = ntohl (get->options);
1805   xquery = (const char*) &get[1];
1806   reply_bf = NULL;
1807   if (reply_bf_size > 0)
1808     reply_bf = GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size],
1809                                                   reply_bf_size,
1810                                                   GNUNET_CONSTANTS_BLOOMFILTER_K);
1811   eval = GNUNET_BLOCK_evaluate (GDS_block_context,
1812                                 type,
1813                                 &get->key,
1814                                 &reply_bf,
1815                                 get->bf_mutator,
1816                                 xquery, xquery_size,
1817                                 NULL, 0);
1818   if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1819   {
1820     /* request invalid or block type not supported */
1821     GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1822     if (NULL != reply_bf)
1823       GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1824     return GNUNET_YES;
1825   }
1826   peer_bf =
1827     GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, 
1828                                        DHT_BLOOM_SIZE,
1829                                        GNUNET_CONSTANTS_BLOOMFILTER_K);
1830   GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &peer->hashPubKey));
1831   /* remember request for routing replies */
1832   GDS_ROUTING_add (peer,
1833                    type,
1834                    options,
1835                    &get->key,
1836                    xquery, xquery_size,
1837                    reply_bf, get->bf_mutator);
1838 #if DEBUG_DHT
1839   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1840               "GET for %s at %s after %u hops\n",
1841               GNUNET_h2s (&get->key),
1842               GNUNET_i2s (&my_identity),
1843               (unsigned int) ntohl (get->hop_count));
1844 #endif
1845   /* local lookup (this may update the reply_bf) */
1846   if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1847        (am_closest_peer (&get->key,
1848                          peer_bf) ) )
1849     {
1850     if ( (0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1851     {
1852       GNUNET_STATISTICS_update (GDS_stats,
1853                                 gettext_noop ("# P2P FIND PEER requests processed"), 1,
1854                                 GNUNET_NO);
1855       handle_find_peer (peer,
1856                         &get->key,
1857                         reply_bf,
1858                         get->bf_mutator);
1859     }
1860     else
1861     {
1862       eval = GDS_DATACACHE_handle_get (&get->key,
1863                                        type,
1864                                        xquery, xquery_size,
1865                                        &reply_bf, 
1866                                        get->bf_mutator);
1867     }
1868   }
1869   else
1870   {
1871     GNUNET_STATISTICS_update (GDS_stats,
1872                               gettext_noop ("# P2P GET requests ONLY routed"), 1,
1873                               GNUNET_NO);
1874   }
1875   
1876   /* P2P forwarding */
1877   if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1878     GDS_NEIGHBOURS_handle_get (type,
1879                                options,
1880                                ntohl (get->desired_replication_level),
1881                                ntohl (get->hop_count),
1882                                &get->key,
1883                                xquery, xquery_size,
1884                                reply_bf,
1885                                get->bf_mutator,
1886                                peer_bf);
1887   /* clean up */
1888   if (NULL != reply_bf)
1889     GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1890   GNUNET_CONTAINER_bloomfilter_free (peer_bf);  
1891   return GNUNET_YES;
1892 }
1893
1894
1895 /**
1896  * Core handler for p2p result messages.
1897  *
1898  * @param cls closure
1899  * @param message message
1900  * @param peer peer identity this notification is about
1901  * @param atsi performance data
1902  * @param atsi_count number of records in 'atsi'
1903  * @return GNUNET_YES (do not cut p2p connection)
1904  */
1905 static int
1906 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1907                        const struct GNUNET_MessageHeader *message,
1908                        const struct GNUNET_ATS_Information
1909                        *atsi,
1910                        unsigned int atsi_count)
1911 {
1912   const struct PeerResultMessage *prm;
1913   const struct GNUNET_PeerIdentity *put_path;
1914   const struct GNUNET_PeerIdentity *get_path;
1915   const void *data;
1916   uint32_t get_path_length;
1917   uint32_t put_path_length;
1918   uint16_t msize;
1919   size_t data_size;
1920   enum GNUNET_BLOCK_Type type;
1921                        
1922   /* parse and validate message */
1923   msize = ntohs (message->size);
1924   if (msize < sizeof (struct PeerResultMessage))
1925   {
1926     GNUNET_break_op (0);
1927     return GNUNET_YES;
1928   }
1929   prm = (struct PeerResultMessage *) message;
1930   put_path_length = ntohl (prm->put_path_length);
1931   get_path_length = ntohl (prm->get_path_length);
1932   if ( (msize < sizeof (struct PeerResultMessage) + 
1933         (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity)) ||
1934        (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1935        (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1936   {
1937     GNUNET_break_op (0);
1938     return GNUNET_YES;
1939   } 
1940   GNUNET_STATISTICS_update (GDS_stats,
1941                             gettext_noop ("# P2P RESULTS received"), 1,
1942                             GNUNET_NO);
1943   put_path = (const struct GNUNET_PeerIdentity*) &prm[1];
1944   get_path = &put_path[put_path_length];
1945   type = ntohl (prm->type);
1946   data = (const void*) &get_path[get_path_length];
1947   data_size = msize - (sizeof (struct PeerResultMessage) + 
1948                        (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1949
1950   /* if we got a HELLO, consider it for our own routing table */
1951   if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
1952   {
1953     const struct GNUNET_MessageHeader *h;
1954     struct GNUNET_PeerIdentity pid;
1955     int bucket;
1956
1957     /* Should be a HELLO, validate and consider using it! */
1958     if (data_size < sizeof (struct GNUNET_MessageHeader))
1959     {
1960       GNUNET_break_op (0);
1961       return GNUNET_YES;
1962     }
1963     h = data;
1964     if (data_size != ntohs (h->size))
1965     {
1966       GNUNET_break_op (0);
1967       return GNUNET_YES;
1968     }
1969     if (GNUNET_OK !=
1970         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message*) h,
1971                              &pid))
1972     {
1973       GNUNET_break_op (0);
1974       return GNUNET_YES;
1975     }
1976     if (0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
1977     {
1978       bucket = find_bucket (&pid.hashPubKey);
1979       if ( (bucket >= 0) &&
1980            (k_buckets[bucket].peers_size < bucket_size) )
1981         {    
1982           if (NULL != GDS_transport_handle)
1983           {
1984             GNUNET_TRANSPORT_offer_hello (GDS_transport_handle,
1985                                           h, NULL, NULL);
1986             GNUNET_TRANSPORT_try_connect (GDS_transport_handle,
1987                                           &pid);
1988           }
1989         }   
1990     }
1991   }
1992
1993   /* append 'peer' to 'get_path' */
1994   {    
1995     struct GNUNET_PeerIdentity xget_path[get_path_length+1];
1996
1997     memcpy (xget_path, get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1998     xget_path[get_path_length] = *peer;
1999     get_path_length++;
2000
2001     /* forward to local clients */   
2002     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2003                              &prm->key,
2004                              get_path_length,
2005                              xget_path,
2006                              put_path_length,
2007                              put_path,
2008                              type,
2009                              data_size, 
2010                              data);
2011
2012     /* forward to other peers */
2013     GDS_ROUTING_process (type,
2014                          GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2015                          &prm->key,
2016                          put_path_length,
2017                          put_path,
2018                          get_path_length,
2019                          xget_path,
2020                          data,
2021                          data_size);                     
2022   }
2023   return GNUNET_YES;
2024 }
2025
2026
2027 /**
2028  * Initialize neighbours subsystem.
2029  *
2030  * @return GNUNET_OK on success, GNUNET_SYSERR on error
2031  */
2032 int
2033 GDS_NEIGHBOURS_init ()
2034 {
2035   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2036     {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2037     {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2038     {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2039     {NULL, 0, 0}
2040   };
2041   unsigned long long temp_config_num;
2042  
2043   if (GNUNET_OK ==
2044       GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2045                                              &temp_config_num))
2046     bucket_size = (unsigned int) temp_config_num;  
2047   atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2048   coreAPI = GNUNET_CORE_connect (GDS_cfg,
2049                                  1,
2050                                  NULL,
2051                                  &core_init,
2052                                  &handle_core_connect,
2053                                  &handle_core_disconnect, 
2054                                  NULL, GNUNET_NO,
2055                                  NULL, GNUNET_NO,
2056                                  core_handlers);
2057   if (coreAPI == NULL)
2058     return GNUNET_SYSERR;
2059   all_known_peers = GNUNET_CONTAINER_multihashmap_create (256);
2060   return GNUNET_OK;
2061 }
2062
2063
2064 /**
2065  * Shutdown neighbours subsystem.
2066  */
2067 void
2068 GDS_NEIGHBOURS_done ()
2069 {
2070   if (coreAPI == NULL)
2071     return;
2072   GNUNET_CORE_disconnect (coreAPI);
2073   coreAPI = NULL;    
2074   GNUNET_ATS_performance_done (atsAPI);
2075   atsAPI = NULL;    
2076   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2077   GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2078   all_known_peers = NULL;
2079   if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2080   {
2081     GNUNET_SCHEDULER_cancel (find_peer_task);
2082     find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2083   }
2084 }
2085
2086
2087 /* end of gnunet-service-dht_neighbours.c */