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