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