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