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