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