LRN's big logging rewrite (#1805):
[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
709   /* Check for disconnect from self message */
710   if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
711     return;
712   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
713               "Disconnected %s from %s\n",
714               GNUNET_i2s (&my_identity),
715               GNUNET_h2s (&peer->hashPubKey));
716   to_remove =
717       GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
718   if (NULL == to_remove)
719     {
720       GNUNET_break (0);
721       return;
722     }
723   GNUNET_STATISTICS_update (GDS_stats,
724                             gettext_noop ("# Peers connected"), -1,
725                             GNUNET_NO);
726   GNUNET_assert (GNUNET_YES ==
727                  GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
728                                                        &peer->hashPubKey,
729                                                        to_remove));
730   if (NULL != to_remove->info_ctx)
731   {
732     GNUNET_CORE_peer_change_preference_cancel (to_remove->info_ctx);
733     to_remove->info_ctx = NULL;
734   }
735   if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
736   {
737     GNUNET_SCHEDULER_cancel (to_remove->preference_task);
738     to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
739   }
740   current_bucket = find_bucket (&to_remove->id.hashPubKey);
741   GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
742                                k_buckets[current_bucket].tail,
743                                to_remove);
744   GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
745   k_buckets[current_bucket].peers_size--;
746   while ( (closest_bucket > 0) &&
747           (k_buckets[closest_bucket].peers_size == 0) )
748     closest_bucket--;
749
750   if (to_remove->th != NULL) 
751   {
752     GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
753     to_remove->th = NULL;
754   }
755   while (NULL != (pos = to_remove->head))
756   {
757     GNUNET_CONTAINER_DLL_remove (to_remove->head,
758                                  to_remove->tail,
759                                  pos);
760     GNUNET_free (pos);
761   }
762 }
763
764
765 /**
766  * Called when core is ready to send a message we asked for
767  * out to the destination.
768  *
769  * @param cls the 'struct PeerInfo' of the target peer
770  * @param size number of bytes available in buf
771  * @param buf where the callee should write the message
772  * @return number of bytes written to buf
773  */
774 static size_t
775 core_transmit_notify (void *cls, size_t size, void *buf)
776 {
777   struct PeerInfo *peer = cls;
778   char *cbuf = buf;
779   struct P2PPendingMessage *pending;
780   size_t off;
781   size_t msize;
782
783   peer->th = NULL;
784   while ( (NULL != (pending = peer->head)) &&
785           (GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value == 0) )
786   {
787     peer->pending_count--;
788     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
789     GNUNET_free (pending);
790   }
791   if (pending == NULL)
792   {
793     /* no messages pending */
794     return 0;
795   }
796   if (buf == NULL)
797   {
798     peer->th 
799       = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
800                                            pending->importance,
801                                            GNUNET_TIME_absolute_get_remaining (pending->timeout),
802                                            &peer->id, ntohs (pending->msg->size),
803                                            &core_transmit_notify, peer);  
804     return 0;
805   }
806   off = 0;
807   while ( (NULL != (pending = peer->head)) &&
808           (size - off >= (msize = ntohs (pending->msg->size))) )
809   {
810     GNUNET_STATISTICS_update (GDS_stats,
811                               gettext_noop ("# Bytes transmitted to other peers"), msize,
812                               GNUNET_NO);
813     memcpy (&cbuf[off], pending->msg, msize);
814     off += msize;
815     peer->pending_count--;
816     GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
817     GNUNET_free (pending);
818   }
819   if (peer->head != NULL)
820     {
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, msize,
826                                              &core_transmit_notify, peer);
827     }
828   return off;
829 }
830
831
832 /**
833  * Transmit all messages in the peer's message queue.
834  *
835  * @param peer message queue to process
836  */
837 static void
838 process_peer_queue (struct PeerInfo *peer)
839 {
840   struct P2PPendingMessage *pending;
841
842   if (NULL == (pending = peer->head))
843     return;
844   if (NULL != peer->th)
845     return;
846   GNUNET_STATISTICS_update (GDS_stats,
847                             gettext_noop ("# Bytes of bandwdith requested from core"),
848                             ntohs (pending->msg->size),
849                             GNUNET_NO);
850   peer->th 
851     = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
852                                          pending->importance,
853                                          GNUNET_TIME_absolute_get_remaining (pending->timeout),
854                                          &peer->id,
855                                          ntohs (pending->msg->size),
856                                          &core_transmit_notify, peer);
857 }
858
859
860 /**
861  * To how many peers should we (on average) forward the request to
862  * obtain the desired target_replication count (on average).
863  *
864  * @param hop_count number of hops the message has traversed
865  * @param target_replication the number of total paths desired
866  * @return Some number of peers to forward the message to
867  */
868 static unsigned int
869 get_forward_count (uint32_t hop_count, 
870                    uint32_t target_replication)
871 {
872   uint32_t random_value;
873   uint32_t forward_count;
874   float target_value;
875
876   if (hop_count > GDS_NSE_get () * 6.0)
877   {
878     /* forcefully terminate */
879     return 0;
880   }
881   if (hop_count > GDS_NSE_get () * 4.0)
882   {
883     /* Once we have reached our ideal number of hops, only forward to 1 peer */
884     return 1;
885   }
886   /* bound by system-wide maximum */
887   target_replication = GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL,
888                                    target_replication);
889   target_value =
890     1 + (target_replication - 1.0) / (GDS_NSE_get () +
891                                       ((float) (target_replication - 1.0) *
892                                        hop_count));
893   /* Set forward count to floor of target_value */
894   forward_count = (uint32_t) target_value;
895   /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
896   target_value = target_value - forward_count;
897   random_value =
898     GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX); 
899   if (random_value < (target_value * UINT32_MAX))
900     forward_count++;
901   return forward_count;
902 }
903
904
905 /**
906  * Compute the distance between have and target as a 32-bit value.
907  * Differences in the lower bits must count stronger than differences
908  * in the higher bits.
909  *
910  * @return 0 if have==target, otherwise a number
911  *           that is larger as the distance between
912  *           the two hash codes increases
913  */
914 static unsigned int
915 get_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
916 {
917   unsigned int bucket;
918   unsigned int msb;
919   unsigned int lsb;
920   unsigned int i;
921
922   /* We have to represent the distance between two 2^9 (=512)-bit
923    * numbers as a 2^5 (=32)-bit number with "0" being used for the
924    * two numbers being identical; furthermore, we need to
925    * guarantee that a difference in the number of matching
926    * bits is always represented in the result.
927    *
928    * We use 2^32/2^9 numerical values to distinguish between
929    * hash codes that have the same LSB bit distance and
930    * use the highest 2^9 bits of the result to signify the
931    * number of (mis)matching LSB bits; if we have 0 matching
932    * and hence 512 mismatching LSB bits we return -1 (since
933    * 512 itself cannot be represented with 9 bits) */
934
935   /* first, calculate the most significant 9 bits of our
936    * result, aka the number of LSBs */
937   bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
938   /* bucket is now a value between 0 and 512 */
939   if (bucket == 512)
940     return 0;                   /* perfect match */
941   if (bucket == 0)
942     return (unsigned int) -1;   /* LSB differs; use max (if we did the bit-shifting
943                                  * below, we'd end up with max+1 (overflow)) */
944
945   /* calculate the most significant bits of the final result */
946   msb = (512 - bucket) << (32 - 9);
947   /* calculate the 32-9 least significant bits of the final result by
948    * looking at the differences in the 32-9 bits following the
949    * mismatching bit at 'bucket' */
950   lsb = 0;
951   for (i = bucket + 1;
952        (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
953   {
954     if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
955         GNUNET_CRYPTO_hash_get_bit (have, i))
956       lsb |= (1 << (bucket + 32 - 9 - i));      /* first bit set will be 10,
957                                                  * last bit set will be 31 -- if
958                                                  * i does not reach 512 first... */
959   }
960   return msb | lsb;
961 }
962
963
964 /**
965  * Check whether my identity is closer than any known peers.  If a
966  * non-null bloomfilter is given, check if this is the closest peer
967  * that hasn't already been routed to.
968  *
969  * @param key hash code to check closeness to
970  * @param bloom bloomfilter, exclude these entries from the decision
971  * @return GNUNET_YES if node location is closest,
972  *         GNUNET_NO otherwise.
973  */
974 static int
975 am_closest_peer (const GNUNET_HashCode *key,
976                  const struct GNUNET_CONTAINER_BloomFilter *bloom)
977 {
978   int bits;
979   int other_bits;
980   int bucket_num;
981   int count;
982   struct PeerInfo *pos;
983
984   if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
985     return GNUNET_YES;
986   bucket_num = find_bucket (key);
987   bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
988   pos = k_buckets[bucket_num].head;
989   count = 0;
990   while ((pos != NULL) && (count < bucket_size))
991   {
992     if ((bloom != NULL) &&
993         (GNUNET_YES ==
994          GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
995     {
996       pos = pos->next;
997       continue;                 /* Skip already checked entries */
998     }
999     other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
1000     if (other_bits > bits)
1001       return GNUNET_NO;
1002     if (other_bits == bits)        /* We match the same number of bits */
1003       return GNUNET_YES;
1004     pos = pos->next;
1005   }
1006   /* No peers closer, we are the closest! */
1007   return GNUNET_YES;
1008 }
1009
1010
1011 /**
1012  * Select a peer from the routing table that would be a good routing
1013  * destination for sending a message for "key".  The resulting peer
1014  * must not be in the set of blocked peers.<p>
1015  *
1016  * Note that we should not ALWAYS select the closest peer to the
1017  * target, peers further away from the target should be chosen with
1018  * exponentially declining probability.
1019  *
1020  * FIXME: double-check that this is fine
1021  * 
1022  *
1023  * @param key the key we are selecting a peer to route to
1024  * @param bloom a bloomfilter containing entries this request has seen already
1025  * @param hops how many hops has this message traversed thus far
1026  * @return Peer to route to, or NULL on error
1027  */
1028 static struct PeerInfo *
1029 select_peer (const GNUNET_HashCode *key,
1030              const struct GNUNET_CONTAINER_BloomFilter *bloom, 
1031              uint32_t hops)
1032 {
1033   unsigned int bc;
1034   unsigned int count;
1035   unsigned int selected;
1036   struct PeerInfo *pos;
1037   unsigned int dist;
1038   unsigned int smallest_distance;
1039   struct PeerInfo *chosen;
1040
1041   if (hops >= GDS_NSE_get ())
1042   {
1043     /* greedy selection (closest peer that is not in bloomfilter) */
1044     smallest_distance = UINT_MAX;
1045     chosen = NULL;
1046     for (bc = 0; bc < closest_bucket; bc++)
1047     {
1048       pos = k_buckets[bc].head;
1049       count = 0;
1050       while ((pos != NULL) && (count < bucket_size))
1051       {
1052         if ( (bloom == NULL) ||
1053              (GNUNET_NO ==
1054               GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1055         {
1056           dist = get_distance (key, &pos->id.hashPubKey);
1057           if (dist < smallest_distance)
1058           {
1059             chosen = pos;
1060             smallest_distance = dist;
1061           }
1062         }
1063         else
1064         {
1065           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1066                       "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1067                       GNUNET_i2s (&pos->id),
1068                       GNUNET_h2s (key));
1069           GNUNET_STATISTICS_update (GDS_stats,
1070                                     gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1071                                     GNUNET_NO);
1072         }
1073         count++;
1074         pos = pos->next;
1075       }
1076     }
1077     if (NULL == chosen)
1078       GNUNET_STATISTICS_update (GDS_stats,
1079                                 gettext_noop ("# Peer selection failed"), 1,
1080                                 GNUNET_NO);
1081     return chosen;
1082   }
1083
1084   /* select "random" peer */
1085   /* count number of peers that are available and not filtered */
1086   count = 0;
1087   for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1088   {
1089     pos = k_buckets[bc].head;
1090     while ((pos != NULL) && (count < bucket_size))
1091     {
1092       if ( (bloom != NULL) &&
1093            (GNUNET_YES ==
1094             GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1095       {
1096         GNUNET_STATISTICS_update (GDS_stats,
1097                                   gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1098                                   GNUNET_NO);
1099         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100                     "Excluded peer `%s' due to BF match in random routing for %s\n",
1101                     GNUNET_i2s (&pos->id),
1102                     GNUNET_h2s (key));
1103         pos = pos->next;
1104         continue;               /* Ignore bloomfiltered peers */
1105       }
1106       count++;
1107       pos = pos->next;
1108     }
1109   }
1110   if (count == 0)               /* No peers to select from! */
1111   {
1112     GNUNET_STATISTICS_update (GDS_stats,
1113                               gettext_noop ("# Peer selection failed"), 1,
1114                               GNUNET_NO);
1115     return NULL;
1116   }
1117   /* Now actually choose a peer */
1118   selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1119   count = 0;
1120   for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1121   {
1122     pos = k_buckets[bc].head;
1123     while ((pos != NULL) && (count < bucket_size))
1124     {
1125       if ( (bloom != NULL) &&
1126            (GNUNET_YES ==
1127             GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1128       {
1129         pos = pos->next;
1130         continue;               /* Ignore bloomfiltered peers */
1131       }
1132       if (0 == selected--)
1133         return pos;
1134       pos = pos->next;
1135     }
1136   }
1137   GNUNET_break (0);
1138   return NULL;
1139 }
1140
1141
1142 /**
1143  * Compute the set of peers that the given request should be
1144  * forwarded to.
1145  *
1146  * @param key routing key
1147  * @param bloom bloom filter excluding peers as targets, all selected
1148  *        peers will be added to the bloom filter
1149  * @param hop_count number of hops the request has traversed so far
1150  * @param target_replication desired number of replicas
1151  * @param targets where to store an array of target peers (to be
1152  *         free'd by the caller)
1153  * @return number of peers returned in 'targets'.
1154  */
1155 static unsigned int
1156 get_target_peers (const GNUNET_HashCode *key,
1157                   struct GNUNET_CONTAINER_BloomFilter *bloom,
1158                   uint32_t hop_count,
1159                   uint32_t target_replication,
1160                   struct PeerInfo ***targets)
1161 {
1162   unsigned int ret;
1163   unsigned int off;
1164   struct PeerInfo **rtargets;
1165   struct PeerInfo *nxt;
1166
1167   GNUNET_assert (NULL != bloom);
1168   ret = get_forward_count (hop_count, target_replication);
1169   if (ret == 0)
1170   {
1171     *targets = NULL;
1172     return 0;
1173   }
1174   rtargets = GNUNET_malloc (sizeof (struct PeerInfo*) * ret);
1175   for (off = 0; off < ret; off++)
1176   {
1177     nxt = select_peer (key, bloom, hop_count);
1178     if (nxt == NULL)
1179       break;      
1180     rtargets[off] = nxt;
1181     GNUNET_break (GNUNET_NO ==
1182                   GNUNET_CONTAINER_bloomfilter_test (bloom, &nxt->id.hashPubKey));
1183     GNUNET_CONTAINER_bloomfilter_add (bloom, &rtargets[off]->id.hashPubKey);
1184   }
1185   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1186               "Selected %u/%u peers at hop %u for %s (target was %u)\n",
1187               off,
1188               GNUNET_CONTAINER_multihashmap_size (all_known_peers),
1189               (unsigned int) hop_count,
1190               GNUNET_h2s (key),
1191               ret);
1192   if (0 == off)
1193   {
1194     GNUNET_free (rtargets);
1195     *targets = NULL;
1196     return 0;
1197   }
1198   *targets = rtargets;
1199   return off;
1200 }
1201
1202
1203 /**
1204  * Perform a PUT operation.   Forwards the given request to other
1205  * peers.   Does not store the data locally.  Does not give the
1206  * data to local clients.  May do nothing if this is the only
1207  * peer in the network (or if we are the closest peer in the
1208  * network).
1209  *
1210  * @param type type of the block
1211  * @param options routing options
1212  * @param desired_replication_level desired replication count
1213  * @param expiration_time when does the content expire
1214  * @param hop_count how many hops has this message traversed so far
1215  * @param bf Bloom filter of peers this PUT has already traversed
1216  * @param key key for the content
1217  * @param put_path_length number of entries in put_path
1218  * @param put_path peers this request has traversed so far (if tracked)
1219  * @param data payload to store
1220  * @param data_size number of bytes in data
1221  */
1222 void
1223 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1224                            enum GNUNET_DHT_RouteOption options,
1225                            uint32_t desired_replication_level,
1226                            struct GNUNET_TIME_Absolute expiration_time,
1227                            uint32_t hop_count,
1228                            struct GNUNET_CONTAINER_BloomFilter *bf,
1229                            const GNUNET_HashCode *key,
1230                            unsigned int put_path_length,
1231                            struct GNUNET_PeerIdentity *put_path,
1232                            const void *data,
1233                            size_t data_size)
1234 {
1235   unsigned int target_count;
1236   unsigned int i;
1237   struct PeerInfo **targets;
1238   struct PeerInfo *target;
1239   struct P2PPendingMessage *pending;
1240   size_t msize;
1241   struct PeerPutMessage *ppm;
1242   struct GNUNET_PeerIdentity *pp;
1243   
1244   GNUNET_assert (NULL != bf);
1245   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1246               "Adding myself (%s) to PUT bloomfilter for %s\n",
1247               GNUNET_i2s (&my_identity),
1248               GNUNET_h2s (key));
1249   GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1250   GNUNET_STATISTICS_update (GDS_stats,
1251                             gettext_noop ("# PUT requests routed"), 1,
1252                             GNUNET_NO);
1253   target_count = get_target_peers (key, bf, hop_count,
1254                                    desired_replication_level,
1255                                    &targets);
1256   if (0 == target_count)
1257     { 
1258       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1259                   "Routing PUT for %s terminates after %u hops at %s\n",
1260                   GNUNET_h2s (key),
1261                   (unsigned int) hop_count,
1262                   GNUNET_i2s (&my_identity));
1263       return;
1264     }
1265   msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size + sizeof (struct PeerPutMessage);
1266   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1267   {
1268     put_path_length = 0;
1269     msize = data_size + sizeof (struct PeerPutMessage);
1270   }
1271   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1272   {
1273     GNUNET_break (0);
1274     return;
1275   }
1276   GNUNET_STATISTICS_update (GDS_stats,
1277                             gettext_noop ("# PUT messages queued for transmission"), target_count,
1278                             GNUNET_NO);
1279   for (i=0;i<target_count;i++)
1280   {
1281     target = targets[i];
1282     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1283                 "Routing PUT for %s after %u hops to %s\n",
1284                 GNUNET_h2s (key),
1285                 (unsigned int) hop_count,
1286                 GNUNET_i2s (&target->id));
1287     pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1288     pending->importance = 0; /* FIXME */
1289     pending->timeout = expiration_time;   
1290     ppm = (struct PeerPutMessage*) &pending[1];
1291     pending->msg = &ppm->header;
1292     ppm->header.size = htons (msize);
1293     ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1294     ppm->options = htonl (options);
1295     ppm->type = htonl (type);
1296     ppm->hop_count = htonl (hop_count + 1);
1297     ppm->desired_replication_level = htonl (desired_replication_level);
1298     ppm->put_path_length = htonl (put_path_length);
1299     ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1300     GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &target->id.hashPubKey));
1301     GNUNET_assert (GNUNET_OK ==
1302                    GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1303                                                               ppm->bloomfilter,
1304                                                               DHT_BLOOM_SIZE));
1305     ppm->key = *key;
1306     pp = (struct GNUNET_PeerIdentity*) &ppm[1];
1307     memcpy (pp, put_path, sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1308     memcpy (&pp[put_path_length], data, data_size);
1309     GNUNET_CONTAINER_DLL_insert_tail (target->head,
1310                                       target->tail,
1311                                       pending);
1312     target->pending_count++;
1313     process_peer_queue (target);
1314   }
1315   GNUNET_free (targets);
1316 }
1317
1318
1319 /**
1320  * Perform a GET operation.  Forwards the given request to other
1321  * peers.  Does not lookup the key locally.  May do nothing if this is
1322  * the only peer in the network (or if we are the closest peer in the
1323  * network).
1324  *
1325  * @param type type of the block
1326  * @param options routing options
1327  * @param desired_replication_level desired replication count
1328  * @param hop_count how many hops did this request traverse so far?
1329  * @param key key for the content
1330  * @param xquery extended query
1331  * @param xquery_size number of bytes in xquery
1332  * @param reply_bf bloomfilter to filter duplicates
1333  * @param reply_bf_mutator mutator for reply_bf
1334  * @param peer_bf filter for peers not to select (again)
1335  */
1336 void
1337 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1338                            enum GNUNET_DHT_RouteOption options,
1339                            uint32_t desired_replication_level,
1340                            uint32_t hop_count,
1341                            const GNUNET_HashCode *key,
1342                            const void *xquery,
1343                            size_t xquery_size,
1344                            const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1345                            uint32_t reply_bf_mutator,
1346                            struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1347 {
1348   unsigned int target_count;
1349   unsigned int i;
1350   struct PeerInfo **targets;
1351   struct PeerInfo *target;
1352   struct P2PPendingMessage *pending;
1353   size_t msize;
1354   struct PeerGetMessage *pgm;
1355   char *xq;
1356   size_t reply_bf_size;
1357
1358   GNUNET_assert (NULL != peer_bf);  
1359   GNUNET_STATISTICS_update (GDS_stats,
1360                             gettext_noop ("# GET requests routed"), 1,
1361                             GNUNET_NO);
1362   target_count = get_target_peers (key, peer_bf, hop_count,
1363                                    desired_replication_level,
1364                                    &targets);
1365   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1366               "Adding myself (%s) to GET bloomfilter for %s\n",
1367               GNUNET_i2s (&my_identity),
1368               GNUNET_h2s (key));
1369   GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity.hashPubKey);
1370   if (0 == target_count)
1371     {
1372       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1373                   "Routing GET for %s terminates after %u hops at %s\n",
1374                   GNUNET_h2s (key),
1375                   (unsigned int) hop_count,
1376                   GNUNET_i2s (&my_identity));
1377       return;
1378     }
1379   reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1380   msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1381   if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1382   {
1383     GNUNET_break (0);
1384     return;
1385   }
1386   GNUNET_STATISTICS_update (GDS_stats,
1387                             gettext_noop ("# GET messages queued for transmission"), target_count,
1388                             GNUNET_NO);
1389   /* forward request */
1390   for (i=0;i<target_count;i++)
1391   {
1392     target = targets[i];
1393     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1394                 "Routing GET for %s after %u hops to %s\n",
1395                 GNUNET_h2s (key),
1396                 (unsigned int) hop_count,
1397                 GNUNET_i2s (&target->id));
1398     pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
1399     pending->importance = 0; /* FIXME */
1400     pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1401     pgm = (struct PeerGetMessage*) &pending[1];
1402     pending->msg = &pgm->header;
1403     pgm->header.size = htons (msize);
1404     pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1405     pgm->options = htonl (options);
1406     pgm->type = htonl (type);
1407     pgm->hop_count = htonl (hop_count + 1);
1408     pgm->desired_replication_level = htonl (desired_replication_level);
1409     pgm->xquery_size = htonl (xquery_size);
1410     pgm->bf_mutator = reply_bf_mutator; 
1411     GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &target->id.hashPubKey));
1412     GNUNET_assert (GNUNET_OK ==
1413                    GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1414                                                               pgm->bloomfilter,
1415                                                               DHT_BLOOM_SIZE));
1416     pgm->key = *key;
1417     xq = (char *) &pgm[1];
1418     memcpy (xq, xquery, xquery_size);
1419     if (NULL != reply_bf)
1420       GNUNET_assert (GNUNET_OK ==
1421                      GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1422                                                                 &xq[xquery_size],
1423                                                                 reply_bf_size));
1424     GNUNET_CONTAINER_DLL_insert_tail (target->head,
1425                                       target->tail,
1426                                       pending);
1427     target->pending_count++;
1428     process_peer_queue (target);
1429   }
1430   GNUNET_free (targets);
1431 }
1432
1433
1434 /**
1435  * Handle a reply (route to origin).  Only forwards the reply back to
1436  * the given peer.  Does not do local caching or forwarding to local
1437  * clients.
1438  *
1439  * @param target neighbour that should receive the block (if still connected)
1440  * @param type type of the block
1441  * @param expiration_time when does the content expire
1442  * @param key key for the content
1443  * @param put_path_length number of entries in put_path
1444  * @param put_path peers the original PUT traversed (if tracked)
1445  * @param get_path_length number of entries in put_path
1446  * @param get_path peers this reply has traversed so far (if tracked)
1447  * @param data payload of the reply
1448  * @param data_size number of bytes in data
1449  */
1450 void
1451 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1452                              enum GNUNET_BLOCK_Type type,
1453                              struct GNUNET_TIME_Absolute expiration_time,
1454                              const GNUNET_HashCode *key,
1455                              unsigned int put_path_length,
1456                              const struct GNUNET_PeerIdentity *put_path,
1457                              unsigned int get_path_length,
1458                              const struct GNUNET_PeerIdentity *get_path,
1459                              const void *data,
1460                              size_t data_size)
1461 {
1462   struct PeerInfo *pi;
1463   struct P2PPendingMessage *pending;
1464   size_t msize;
1465   struct PeerResultMessage *prm;
1466   struct GNUNET_PeerIdentity *paths;
1467   
1468   msize = data_size + sizeof (struct PeerResultMessage) + 
1469     (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity);
1470   if ( (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1471        (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1472        (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1473        (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE) )
1474   {
1475     GNUNET_break (0);
1476     return;
1477   }
1478   pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers,
1479                                           &target->hashPubKey);
1480   if (NULL == pi)
1481   {
1482     /* peer disconnected in the meantime, drop reply */
1483     return;
1484   }
1485   GNUNET_STATISTICS_update (GDS_stats,
1486                             gettext_noop ("# RESULT messages queued for transmission"), 1,
1487                             GNUNET_NO);
1488   pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize); 
1489   pending->importance = 0; /* FIXME */
1490   pending->timeout = expiration_time;
1491   prm = (struct PeerResultMessage*) &pending[1];
1492   pending->msg = &prm->header;
1493   prm->header.size = htons (msize);
1494   prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1495   prm->type = htonl (type);
1496   prm->put_path_length = htonl (put_path_length);
1497   prm->get_path_length = htonl (get_path_length);
1498   prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1499   prm->key = *key;
1500   paths = (struct GNUNET_PeerIdentity*) &prm[1];
1501   memcpy (paths, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
1502   memcpy (&paths[put_path_length],
1503           get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1504   memcpy (&paths[put_path_length + get_path_length],
1505           data, data_size);
1506   GNUNET_CONTAINER_DLL_insert (pi->head,
1507                                pi->tail,
1508                                pending);
1509   pi->pending_count++;
1510   process_peer_queue (pi);
1511 }
1512
1513
1514 /**
1515  * To be called on core init/fail.
1516  *
1517  * @param cls service closure
1518  * @param server handle to the server for this service
1519  * @param identity the public identity of this peer
1520  * @param publicKey the public key of this peer
1521  */
1522 static void
1523 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1524            const struct GNUNET_PeerIdentity *identity,
1525            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1526 {
1527   GNUNET_assert (server != NULL);
1528   my_identity = *identity;
1529 }
1530
1531
1532 /**
1533  * Core handler for p2p put requests.
1534  *
1535  * @param cls closure
1536  * @param peer sender of the request
1537  * @param message message
1538  * @param peer peer identity this notification is about
1539  * @param atsi performance data
1540  * @return GNUNET_OK to keep the connection open,
1541  *         GNUNET_SYSERR to close it (signal serious error)
1542  */
1543 static int
1544 handle_dht_p2p_put (void *cls,
1545                     const struct GNUNET_PeerIdentity *peer,
1546                     const struct GNUNET_MessageHeader *message,
1547                     const struct GNUNET_TRANSPORT_ATS_Information
1548                     *atsi)
1549 {
1550   const struct PeerPutMessage *put;
1551   const struct GNUNET_PeerIdentity *put_path;
1552   const void *payload;
1553   uint32_t putlen;
1554   uint16_t msize;
1555   size_t payload_size;
1556   enum GNUNET_DHT_RouteOption options;
1557   struct GNUNET_CONTAINER_BloomFilter *bf;
1558   GNUNET_HashCode test_key;
1559   
1560   msize = ntohs (message->size);
1561   if (msize < sizeof (struct PeerPutMessage))
1562   {
1563     GNUNET_break_op (0);
1564     return GNUNET_YES;
1565   }
1566   put = (const struct PeerPutMessage*) message;
1567   putlen = ntohl (put->put_path_length);
1568   if ( (msize < sizeof (struct PeerPutMessage) + putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1569        (putlen > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1570     {
1571       GNUNET_break_op (0);
1572       return GNUNET_YES;
1573     }
1574   GNUNET_STATISTICS_update (GDS_stats,
1575                             gettext_noop ("# P2P PUT requests received"), 1,
1576                             GNUNET_NO);
1577   put_path = (const struct GNUNET_PeerIdentity*) &put[1];  
1578   payload = &put_path[putlen];
1579   options = ntohl (put->options);
1580   payload_size = msize - (sizeof (struct PeerPutMessage) + 
1581                           putlen * sizeof (struct GNUNET_PeerIdentity));
1582   switch (GNUNET_BLOCK_get_key (GDS_block_context,
1583                                 ntohl (put->type),
1584                                 payload, payload_size,
1585                                 &test_key))
1586   {
1587   case GNUNET_YES:
1588     if (0 != memcmp (&test_key, &put->key, sizeof (GNUNET_HashCode)))
1589     {
1590       GNUNET_break_op (0);
1591       return GNUNET_YES;
1592     }
1593     break;
1594   case GNUNET_NO:
1595     GNUNET_break_op (0);
1596     return GNUNET_YES;
1597   case GNUNET_SYSERR:
1598     /* cannot verify, good luck */
1599     break;
1600   }
1601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1602               "PUT for %s at %s\n",
1603               GNUNET_h2s (&put->key),
1604               GNUNET_i2s (&my_identity));
1605   bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter,
1606                                           DHT_BLOOM_SIZE,
1607                                           GNUNET_CONSTANTS_BLOOMFILTER_K);
1608   GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1609   {
1610     struct GNUNET_PeerIdentity pp[putlen+1];
1611   
1612     /* extend 'put path' by sender */
1613     if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1614     {
1615       memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1616       pp[putlen] = *peer;
1617       putlen++;
1618     }
1619     else
1620       putlen = 0;
1621     
1622     /* give to local clients */
1623     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1624                              &put->key,
1625                              0, NULL,
1626                              putlen,
1627                              pp,
1628                              ntohl (put->type),
1629                              payload_size,
1630                              payload);
1631     /* store locally */
1632     if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1633          (am_closest_peer (&put->key,
1634                            bf) ) )
1635       GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1636                                 &put->key,
1637                                 putlen, pp,
1638                                 ntohl (put->type),
1639                                 payload_size,
1640                                 payload);
1641     /* route to other peers */
1642     GDS_NEIGHBOURS_handle_put (ntohl (put->type),
1643                                options,
1644                                ntohl (put->desired_replication_level),
1645                                GNUNET_TIME_absolute_ntoh (put->expiration_time),
1646                                ntohl (put->hop_count),
1647                                bf,
1648                                &put->key,
1649                                putlen, pp,
1650                                payload,
1651                                payload_size);
1652   }
1653   GNUNET_CONTAINER_bloomfilter_free (bf);
1654   return GNUNET_YES;
1655 }
1656
1657
1658 /**
1659  * We have received a FIND PEER request.  Send matching
1660  * HELLOs back.
1661  *
1662  * @param sender sender of the FIND PEER request
1663  * @param key peers close to this key are desired
1664  * @param bf peers matching this bf are excluded
1665  * @param bf_mutator mutator for bf
1666  */
1667 static void
1668 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1669                   const GNUNET_HashCode *key,
1670                   struct GNUNET_CONTAINER_BloomFilter *bf,
1671                   uint32_t bf_mutator)
1672 {
1673   int bucket_idx;
1674   struct PeerBucket *bucket;
1675   struct PeerInfo *peer;
1676   unsigned int choice;
1677   GNUNET_HashCode mhash;
1678   const struct GNUNET_HELLO_Message *hello;
1679
1680   /* first, check about our own HELLO */
1681   if (NULL != GDS_my_hello)
1682   {
1683     GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1684     if ( (NULL == bf) ||
1685          (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) )
1686     {
1687       GDS_NEIGHBOURS_handle_reply (sender,
1688                                    GNUNET_BLOCK_TYPE_DHT_HELLO,
1689                                    GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1690                                    key,
1691                                    0, NULL,
1692                                    0, NULL,
1693                                    GDS_my_hello,
1694                                    GNUNET_HELLO_size ((const struct GNUNET_HELLO_Message*) GDS_my_hello));
1695     }
1696     else
1697     {
1698       GNUNET_STATISTICS_update (GDS_stats,
1699                                 gettext_noop ("# FIND PEER requests ignored due to Bloomfilter"), 1,
1700                                 GNUNET_NO);
1701     }
1702   }
1703   else
1704   {
1705     GNUNET_STATISTICS_update (GDS_stats,
1706                               gettext_noop ("# FIND PEER requests ignored due to lack of HELLO"), 1,
1707                               GNUNET_NO);
1708   }
1709
1710   /* then, also consider sending a random HELLO from the closest bucket */
1711   if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
1712     bucket_idx = closest_bucket;
1713   else
1714     bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1715   if (bucket_idx == GNUNET_SYSERR)
1716     return;
1717   bucket = &k_buckets[bucket_idx];
1718   if (bucket->peers_size == 0)
1719     return;
1720   choice = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1721                                      bucket->peers_size);
1722   peer = bucket->head;
1723   while (choice > 0)
1724   {
1725     GNUNET_assert (peer != NULL);
1726     peer = peer->next;
1727     choice--;
1728   }
1729   choice = bucket->peers_size;
1730   do
1731     {
1732       peer = peer->next;
1733       if (choice-- == 0)
1734         return; /* no non-masked peer available */
1735       if (peer == NULL)
1736         peer = bucket->head;
1737       GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1738       hello = GDS_HELLO_get (&peer->id);
1739     }
1740   while ( (hello == NULL) ||
1741           (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) );
1742   GDS_NEIGHBOURS_handle_reply (sender,
1743                                GNUNET_BLOCK_TYPE_DHT_HELLO,
1744                                GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1745                                key,
1746                                0, NULL,
1747                                0, NULL,
1748                                hello,
1749                                GNUNET_HELLO_size (hello));    
1750 }
1751
1752
1753 /**
1754  * Core handler for p2p get requests.
1755  *
1756  * @param cls closure
1757  * @param peer sender of the request
1758  * @param message message
1759  * @param peer peer identity this notification is about
1760  * @param atsi performance data
1761  * @return GNUNET_OK to keep the connection open,
1762  *         GNUNET_SYSERR to close it (signal serious error)
1763  */
1764 static int
1765 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1766                     const struct GNUNET_MessageHeader *message,
1767                     const struct GNUNET_TRANSPORT_ATS_Information
1768                     *atsi)
1769 {
1770   struct PeerGetMessage *get;
1771   uint32_t xquery_size;
1772   size_t reply_bf_size;
1773   uint16_t msize;
1774   enum GNUNET_BLOCK_Type type;
1775   enum GNUNET_DHT_RouteOption options;
1776   enum GNUNET_BLOCK_EvaluationResult eval;
1777   struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1778   struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1779   const char *xquery;
1780
1781   GNUNET_break (0 != memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)));
1782   /* parse and validate message */
1783   msize = ntohs (message->size);
1784   if (msize < sizeof (struct PeerGetMessage))
1785   {
1786     GNUNET_break_op (0);
1787     return GNUNET_YES;
1788   }
1789   get = (struct PeerGetMessage *) message;
1790   xquery_size = ntohl (get->xquery_size);
1791   if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1792   {
1793     GNUNET_break_op (0);
1794     return GNUNET_YES;
1795   }
1796   GNUNET_STATISTICS_update (GDS_stats,
1797                             gettext_noop ("# P2P GET requests received"), 1,
1798                             GNUNET_NO);
1799   reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1800   type = ntohl (get->type);
1801   options = ntohl (get->options);
1802   xquery = (const char*) &get[1];
1803   reply_bf = NULL;
1804   if (reply_bf_size > 0)
1805     reply_bf = GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size],
1806                                                   reply_bf_size,
1807                                                   GNUNET_CONSTANTS_BLOOMFILTER_K);
1808   eval = GNUNET_BLOCK_evaluate (GDS_block_context,
1809                                 type,
1810                                 &get->key,
1811                                 &reply_bf,
1812                                 get->bf_mutator,
1813                                 xquery, xquery_size,
1814                                 NULL, 0);
1815   if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1816   {
1817     /* request invalid or block type not supported */
1818     GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1819     if (NULL != reply_bf)
1820       GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1821     return GNUNET_YES;
1822   }
1823   peer_bf =
1824     GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, 
1825                                        DHT_BLOOM_SIZE,
1826                                        GNUNET_CONSTANTS_BLOOMFILTER_K);
1827   GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &peer->hashPubKey));
1828   /* remember request for routing replies */
1829   GDS_ROUTING_add (peer,
1830                    type,
1831                    options,
1832                    &get->key,
1833                    xquery, xquery_size,
1834                    reply_bf, get->bf_mutator);
1835   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1836               "GET for %s at %s after %u hops\n",
1837               GNUNET_h2s (&get->key),
1838               GNUNET_i2s (&my_identity),
1839               (unsigned int) ntohl (get->hop_count));
1840   /* local lookup (this may update the reply_bf) */
1841   if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1842        (am_closest_peer (&get->key,
1843                          peer_bf) ) )
1844     {
1845     if ( (0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1846     {
1847       GNUNET_STATISTICS_update (GDS_stats,
1848                                 gettext_noop ("# P2P FIND PEER requests processed"), 1,
1849                                 GNUNET_NO);
1850       handle_find_peer (peer,
1851                         &get->key,
1852                         reply_bf,
1853                         get->bf_mutator);
1854     }
1855     else
1856     {
1857       eval = GDS_DATACACHE_handle_get (&get->key,
1858                                        type,
1859                                        xquery, xquery_size,
1860                                        &reply_bf, 
1861                                        get->bf_mutator);
1862     }
1863   }
1864   else
1865   {
1866     GNUNET_STATISTICS_update (GDS_stats,
1867                               gettext_noop ("# P2P GET requests ONLY routed"), 1,
1868                               GNUNET_NO);
1869   }
1870   
1871   /* P2P forwarding */
1872   if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1873     GDS_NEIGHBOURS_handle_get (type,
1874                                options,
1875                                ntohl (get->desired_replication_level),
1876                                ntohl (get->hop_count),
1877                                &get->key,
1878                                xquery, xquery_size,
1879                                reply_bf,
1880                                get->bf_mutator,
1881                                peer_bf);
1882   /* clean up */
1883   if (NULL != reply_bf)
1884     GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1885   GNUNET_CONTAINER_bloomfilter_free (peer_bf);  
1886   return GNUNET_YES;
1887 }
1888
1889
1890 /**
1891  * Core handler for p2p result messages.
1892  *
1893  * @param cls closure
1894  * @param message message
1895  * @param peer peer identity this notification is about
1896  * @param atsi performance data
1897  * @return GNUNET_YES (do not cut p2p connection)
1898  */
1899 static int
1900 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1901                        const struct GNUNET_MessageHeader *message,
1902                        const struct GNUNET_TRANSPORT_ATS_Information
1903                        *atsi)
1904 {
1905   const struct PeerResultMessage *prm;
1906   const struct GNUNET_PeerIdentity *put_path;
1907   const struct GNUNET_PeerIdentity *get_path;
1908   const void *data;
1909   uint32_t get_path_length;
1910   uint32_t put_path_length;
1911   uint16_t msize;
1912   size_t data_size;
1913   enum GNUNET_BLOCK_Type type;
1914                        
1915   /* parse and validate message */
1916   msize = ntohs (message->size);
1917   if (msize < sizeof (struct PeerResultMessage))
1918   {
1919     GNUNET_break_op (0);
1920     return GNUNET_YES;
1921   }
1922   prm = (struct PeerResultMessage *) message;
1923   put_path_length = ntohl (prm->put_path_length);
1924   get_path_length = ntohl (prm->get_path_length);
1925   if ( (msize < sizeof (struct PeerResultMessage) + 
1926         (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity)) ||
1927        (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1928        (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1929   {
1930     GNUNET_break_op (0);
1931     return GNUNET_YES;
1932   } 
1933   GNUNET_STATISTICS_update (GDS_stats,
1934                             gettext_noop ("# P2P RESULTS received"), 1,
1935                             GNUNET_NO);
1936   put_path = (const struct GNUNET_PeerIdentity*) &prm[1];
1937   get_path = &put_path[put_path_length];
1938   type = ntohl (prm->type);
1939   data = (const void*) &get_path[get_path_length];
1940   data_size = msize - (sizeof (struct PeerResultMessage) + 
1941                        (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1942
1943   /* if we got a HELLO, consider it for our own routing table */
1944   if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
1945   {
1946     const struct GNUNET_MessageHeader *h;
1947     struct GNUNET_PeerIdentity pid;
1948     int bucket;
1949
1950     /* Should be a HELLO, validate and consider using it! */
1951     if (data_size < sizeof (struct GNUNET_MessageHeader))
1952     {
1953       GNUNET_break_op (0);
1954       return GNUNET_YES;
1955     }
1956     h = data;
1957     if (data_size != ntohs (h->size))
1958     {
1959       GNUNET_break_op (0);
1960       return GNUNET_YES;
1961     }
1962     if (GNUNET_OK !=
1963         GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message*) h,
1964                              &pid))
1965     {
1966       GNUNET_break_op (0);
1967       return GNUNET_YES;
1968     }
1969     if (0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
1970     {
1971       bucket = find_bucket (&pid.hashPubKey);
1972       if ( (bucket >= 0) &&
1973            (k_buckets[bucket].peers_size < bucket_size) )
1974         {    
1975           if (NULL != GDS_transport_handle)
1976             GNUNET_TRANSPORT_offer_hello (GDS_transport_handle,
1977                                           h, NULL, NULL);
1978           (void) GNUNET_CORE_peer_request_connect (coreAPI,
1979                                                    &pid, 
1980                                                    NULL, NULL);
1981         }   
1982     }
1983   }
1984
1985   /* append 'peer' to 'get_path' */
1986   {    
1987     struct GNUNET_PeerIdentity xget_path[get_path_length+1];
1988
1989     memcpy (xget_path, get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1990     xget_path[get_path_length] = *peer;
1991     get_path_length++;
1992
1993     /* forward to local clients */   
1994     GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
1995                              &prm->key,
1996                              get_path_length,
1997                              xget_path,
1998                              put_path_length,
1999                              put_path,
2000                              type,
2001                              data_size, 
2002                              data);
2003
2004     /* forward to other peers */
2005     GDS_ROUTING_process (type,
2006                          GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2007                          &prm->key,
2008                          put_path_length,
2009                          put_path,
2010                          get_path_length,
2011                          xget_path,
2012                          data,
2013                          data_size);                     
2014   }
2015   return GNUNET_YES;
2016 }
2017
2018
2019 /**
2020  * Initialize neighbours subsystem.
2021  *
2022  * @return GNUNET_OK on success, GNUNET_SYSERR on error
2023  */
2024 int
2025 GDS_NEIGHBOURS_init ()
2026 {
2027   static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2028     {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2029     {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2030     {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2031     {NULL, 0, 0}
2032   };
2033   unsigned long long temp_config_num;
2034  
2035   if (GNUNET_OK ==
2036       GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2037                                              &temp_config_num))
2038     bucket_size = (unsigned int) temp_config_num;  
2039   coreAPI = GNUNET_CORE_connect (GDS_cfg,
2040                                  1,
2041                                  NULL,
2042                                  &core_init,
2043                                  &handle_core_connect,
2044                                  &handle_core_disconnect, 
2045                                  NULL,  /* Do we care about "status" updates? */
2046                                  NULL, GNUNET_NO,
2047                                  NULL, GNUNET_NO,
2048                                  core_handlers);
2049   if (coreAPI == NULL)
2050     return GNUNET_SYSERR;
2051   all_known_peers = GNUNET_CONTAINER_multihashmap_create (256);
2052   return GNUNET_OK;
2053 }
2054
2055
2056 /**
2057  * Shutdown neighbours subsystem.
2058  */
2059 void
2060 GDS_NEIGHBOURS_done ()
2061 {
2062   if (coreAPI == NULL)
2063     return;
2064   GNUNET_CORE_disconnect (coreAPI);
2065   coreAPI = NULL;    
2066   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2067   GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2068   all_known_peers = NULL;
2069   if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2070   {
2071     GNUNET_SCHEDULER_cancel (find_peer_task);
2072     find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2073   }
2074 }
2075
2076
2077 /* end of gnunet-service-dht_neighbours.c */