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