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