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