lots of little things, mainly report statistics at end of dht profiling testcase
[oweals/gnunet.git] / src / dht / gnunet-service-dht.c
1 /*
2      This file is part of GNUnet.
3      (C) 2009, 2010 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.c
23  * @brief main DHT service shell, building block for DHT implementations
24  * @author Christian Grothoff
25  * @author Nathan Evans
26  */
27
28 #include "platform.h"
29 #include "gnunet_client_lib.h"
30 #include "gnunet_getopt_lib.h"
31 #include "gnunet_os_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_core_service.h"
35 #include "gnunet_signal_lib.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_datacache_lib.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_hello_lib.h"
40 #include "gnunet_dht_service.h"
41 #include "gnunet_statistics_service.h"
42 #include "dhtlog.h"
43 #include "dht.h"
44
45 #define PRINT_TABLES GNUNET_NO
46
47 #define EXTRA_CHECKS GNUNET_YES
48 /**
49  * How many buckets will we allow total.
50  */
51 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
52
53 /**
54  * Should the DHT issue FIND_PEER requests to get better routing tables?
55  */
56 #define DO_FIND_PEER GNUNET_YES
57
58 /**
59  * What is the maximum number of peers in a given bucket.
60  */
61 #define DEFAULT_BUCKET_SIZE 8
62
63 /**
64  * Minimum number of peers we need for "good" routing,
65  * any less than this and we will allow messages to
66  * travel much further through the network!
67  */
68 #define MINIMUM_PEER_THRESHOLD 20
69
70 #define DHT_DEFAULT_FIND_PEER_REPLICATION 20
71
72 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
73
74 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
75 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
76
77 /*
78  * Default frequency for sending malicious get messages
79  */
80 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1 /* Number of seconds */
81
82 /*
83  * Default frequency for sending malicious put messages
84  */
85 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1 /* Default is seconds */
86
87 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
88
89 /**
90  * Real maximum number of hops, at which point we refuse
91  * to forward the message.
92  */
93 #define MAX_HOPS 20
94
95 /**
96  * Linked list of messages to send to clients.
97  */
98 struct P2PPendingMessage
99 {
100   /**
101    * Pointer to next item in the list
102    */
103   struct P2PPendingMessage *next;
104
105   /**
106    * Pointer to previous item in the list
107    */
108   struct P2PPendingMessage *prev;
109
110   /**
111    * Message importance level.
112    */
113   unsigned int importance;
114
115   /**
116    * How long to wait before sending message.
117    */
118   struct GNUNET_TIME_Relative timeout;
119
120   /**
121    * Actual message to be sent; // avoid allocation
122    */
123   const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
124
125 };
126
127
128 /**
129  * Per-peer information.
130  */
131 struct PeerInfo
132 {
133   /**
134    * Next peer entry (DLL)
135    */
136   struct PeerInfo *next;
137
138   /**
139    *  Prev peer entry (DLL)
140    */
141   struct PeerInfo *prev;
142
143   /**
144    * Head of pending messages to be sent to this peer.
145    */
146   struct P2PPendingMessage *head;
147
148   /**
149    * Tail of pending messages to be sent to this peer.
150    */
151   struct P2PPendingMessage *tail;
152
153   /**
154    * Core handle for sending messages to this peer.
155    */
156   struct GNUNET_CORE_TransmitHandle *th;
157
158   /**
159    * Task for scheduling message sends.
160    */
161   GNUNET_SCHEDULER_TaskIdentifier send_task;
162
163   /**
164    * What is the average latency for replies received?
165    */
166   struct GNUNET_TIME_Relative latency;
167
168   /**
169    * Number of responses received
170    */
171   unsigned long long response_count;
172
173   /**
174    * Number of requests sent
175    */
176   unsigned long long request_count;
177
178   /**
179    * What is the identity of the peer?
180    */
181   struct GNUNET_PeerIdentity id;
182
183   /**
184    * Transport level distance to peer.
185    */
186   unsigned int distance;
187
188   /**
189    * Task for scheduling periodic ping messages for this peer.
190    */
191   GNUNET_SCHEDULER_TaskIdentifier ping_task;
192
193 };
194
195 /**
196  * Peers are grouped into buckets.
197  */
198 struct PeerBucket
199 {
200   /**
201    * Head of DLL
202    */
203   struct PeerInfo *head;
204
205   /**
206    * Tail of DLL
207    */
208   struct PeerInfo *tail;
209
210   /**
211    * Number of peers in the bucket.
212    */
213   unsigned int peers_size;
214 };
215
216 /**
217  * Linked list of messages to send to clients.
218  */
219 struct PendingMessage
220 {
221   /**
222    * Pointer to next item in the list
223    */
224   struct PendingMessage *next;
225
226   /**
227    * Pointer to previous item in the list
228    */
229   struct PendingMessage *prev;
230
231   /**
232    * Actual message to be sent; // avoid allocation
233    */
234   const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
235
236 };
237
238 /**
239  * Struct containing information about a client,
240  * handle to connect to it, and any pending messages
241  * that need to be sent to it.
242  */
243 struct ClientList
244 {
245   /**
246    * Linked list of active clients
247    */
248   struct ClientList *next;
249
250   /**
251    * The handle to this client
252    */
253   struct GNUNET_SERVER_Client *client_handle;
254
255   /**
256    * Handle to the current transmission request, NULL
257    * if none pending.
258    */
259   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
260
261   /**
262    * Linked list of pending messages for this client
263    */
264   struct PendingMessage *pending_head;
265
266   /**
267    * Tail of linked list of pending messages for this client
268    */
269   struct PendingMessage *pending_tail;
270
271 };
272
273
274 /**
275  * Context containing information about a DHT message received.
276  */
277 struct DHT_MessageContext
278 {
279   /**
280    * The client this request was received from.
281    * (NULL if received from another peer)
282    */
283   struct ClientList *client;
284
285   /**
286    * The peer this request was received from.
287    * (NULL if received from local client)
288    */
289   const struct GNUNET_PeerIdentity *peer;
290
291   /**
292    * The key this request was about
293    */
294   const GNUNET_HashCode *key;
295
296   /**
297    * The unique identifier of this request
298    */
299   uint64_t unique_id;
300
301   /**
302    * Desired replication level
303    */
304   uint32_t replication;
305
306   /**
307    * Network size estimate, either ours or the sum of
308    * those routed to thus far. =~ Log of number of peers
309    * chosen from for this request.
310    */
311   uint32_t network_size;
312
313   /**
314    * Any message options for this request
315    */
316   uint32_t msg_options;
317
318   /**
319    * How many hops has the message already traversed?
320    */
321   uint32_t hop_count;
322
323   /**
324    * Bloomfilter for this routing request.
325    */
326   struct GNUNET_CONTAINER_BloomFilter *bloom;
327
328   /**
329    * Did we forward this message? (may need to remember it!)
330    */
331   int forwarded;
332
333   /**
334    * Are we the closest known peer to this key (out of our neighbors?)
335    */
336   int closest;
337 };
338
339 /**
340  * Record used for remembering what peers are waiting for what
341  * responses (based on search key).
342  */
343 struct DHTRouteSource
344 {
345
346   /**
347    * This is a DLL.
348    */
349   struct DHTRouteSource *next;
350
351   /**
352    * This is a DLL.
353    */
354   struct DHTRouteSource *prev;
355
356   /**
357    * Source of the request.  Replies should be forwarded to
358    * this peer.
359    */
360   struct GNUNET_PeerIdentity source;
361
362   /**
363    * If this was a local request, remember the client; otherwise NULL.
364    */
365   struct ClientList *client;
366
367   /**
368    * Pointer to this nodes heap location (for removal)
369    */
370   struct GNUNET_CONTAINER_HeapNode *hnode;
371
372   /**
373    * Back pointer to the record storing this information.
374    */
375   struct DHTQueryRecord *record;
376
377   /**
378    * Task to remove this entry on timeout.
379    */
380   GNUNET_SCHEDULER_TaskIdentifier delete_task;
381 };
382
383 /**
384  * Entry in the DHT routing table.
385  */
386 struct DHTQueryRecord
387 {
388   /**
389    * Head of DLL for result forwarding.
390    */
391   struct DHTRouteSource *head;
392
393   /**
394    * Tail of DLL for result forwarding.
395    */
396   struct DHTRouteSource *tail;
397
398   /**
399    * Key that the record concerns.
400    */
401   GNUNET_HashCode key;
402
403   /**
404    * GET message of this record (what we already forwarded?).
405    */
406   //DV_DHT_MESSAGE get; Try to get away with not saving this.
407
408   /**
409    * Bloomfilter of the peers we've replied to so far
410    */
411   //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
412
413 };
414
415 /**
416  * DHT Routing results structure
417  */
418 struct DHTResults
419 {
420   /*
421    * Min heap for removal upon reaching limit
422    */
423   struct GNUNET_CONTAINER_Heap *minHeap;
424
425   /*
426    * Hashmap for fast key based lookup
427    */
428   struct GNUNET_CONTAINER_MultiHashMap *hashmap;
429
430 };
431
432 /**
433  * Routing option to end routing when closest peer found.
434  */
435 static int stop_on_closest;
436
437 /**
438  * Routing option to end routing when data is found.
439  */
440 static int stop_on_found;
441
442 /**
443  * Container of active queries we should remember
444  */
445 static struct DHTResults forward_list;
446
447 /**
448  * Handle to the datacache service (for inserting/retrieving data)
449  */
450 static struct GNUNET_DATACACHE_Handle *datacache;
451
452 /**
453  * Handle for the statistics service.
454  */
455 struct GNUNET_STATISTICS_Handle *stats;
456
457 /**
458  * The main scheduler to use for the DHT service
459  */
460 static struct GNUNET_SCHEDULER_Handle *sched;
461
462 /**
463  * The configuration the DHT service is running with
464  */
465 static const struct GNUNET_CONFIGURATION_Handle *cfg;
466
467 /**
468  * Handle to the core service
469  */
470 static struct GNUNET_CORE_Handle *coreAPI;
471
472 /**
473  * Handle to the transport service, for getting our hello
474  */
475 static struct GNUNET_TRANSPORT_Handle *transport_handle;
476
477 /**
478  * The identity of our peer.
479  */
480 static struct GNUNET_PeerIdentity my_identity;
481
482 /**
483  * Short id of the peer, for printing
484  */
485 static char *my_short_id;
486
487 /**
488  * Our HELLO
489  */
490 static struct GNUNET_MessageHeader *my_hello;
491
492 /**
493  * Task to run when we shut down, cleaning up all our trash
494  */
495 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
496
497 /**
498  * The lowest currently used bucket.
499  */
500 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
501
502 /**
503  * The buckets (Kademlia routing table, complete with growth).
504  * Array of size MAX_BUCKET_SIZE.
505  */
506 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
507
508 /**
509  * Hash map of all known peers, for easy removal from k_buckets on disconnect.
510  */
511 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
512
513 /**
514  * Maximum size for each bucket.
515  */
516 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
517
518 /**
519  * List of active clients.
520  */
521 static struct ClientList *client_list;
522
523 /**
524  * Handle to the DHT logger.
525  */
526 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
527
528 /*
529  * Whether or not to send routing debugging information
530  * to the dht logging server
531  */
532 static unsigned int debug_routes;
533
534 /*
535  * Whether or not to send FULL route information to
536  * logging server
537  */
538 static unsigned int debug_routes_extended;
539
540 /*
541  * GNUNET_YES or GNUNET_NO, whether or not to act as
542  * a malicious node which drops all messages
543  */
544 static unsigned int malicious_dropper;
545
546 /*
547  * GNUNET_YES or GNUNET_NO, whether or not to act as
548  * a malicious node which sends out lots of GETS
549  */
550 static unsigned int malicious_getter;
551
552 /*
553  * GNUNET_YES or GNUNET_NO, whether or not to act as
554  * a malicious node which sends out lots of PUTS
555  */
556 static unsigned int malicious_putter;
557
558 static unsigned long long malicious_get_frequency;
559
560 static unsigned long long malicious_put_frequency;
561
562 /**
563  * Forward declaration.
564  */
565 static size_t send_generic_reply (void *cls, size_t size, void *buf);
566
567 /* Declare here so retry_core_send is aware of it */
568 size_t core_transmit_notify (void *cls,
569                              size_t size, void *buf);
570
571 static void
572 increment_stats(const char *value)
573 {
574   if (stats != NULL)
575     {
576       GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
577     }
578 }
579
580 /**
581  *  Try to send another message from our core send list
582  */
583 static void
584 try_core_send (void *cls,
585                const struct GNUNET_SCHEDULER_TaskContext *tc)
586 {
587   struct PeerInfo *peer = cls;
588   struct P2PPendingMessage *pending;
589   size_t ssize;
590
591   peer->send_task = GNUNET_SCHEDULER_NO_TASK;
592
593   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
594     return;
595
596   if (peer->th != NULL)
597     return; /* Message send already in progress */
598
599   pending = peer->head;
600   if (pending != NULL)
601     {
602       ssize = ntohs(pending->msg->size);
603 #if DEBUG_DHT > 1
604      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
605                 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
606                 "DHT", ssize, GNUNET_i2s(&peer->id));
607 #endif
608       peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
609                                                    pending->timeout, &peer->id,
610                                                    ssize, &core_transmit_notify, peer);
611     }
612 }
613
614 /**
615  * Function called to send a request out to another peer.
616  * Called both for locally initiated requests and those
617  * received from other peers.
618  *
619  * @param cls DHT service closure argument
620  * @param msg the encapsulated message
621  * @param peer the peer to forward the message to
622  * @param msg_ctx the context of the message (hop count, bloom, etc.)
623  */
624 static void forward_result_message (void *cls,
625                                     const struct GNUNET_MessageHeader *msg,
626                                     struct PeerInfo *peer,
627                                     struct DHT_MessageContext *msg_ctx)
628 {
629   struct GNUNET_DHT_P2PRouteResultMessage *result_message;
630   struct P2PPendingMessage *pending;
631   size_t msize;
632   size_t psize;
633
634   increment_stats(STAT_RESULT_FORWARDS);
635   msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
636   GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
637   psize = sizeof(struct P2PPendingMessage) + msize;
638   pending = GNUNET_malloc(psize);
639   pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
640   pending->importance = DHT_SEND_PRIORITY;
641   pending->timeout = GNUNET_TIME_relative_get_forever();
642   result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
643   result_message->header.size = htons(msize);
644   result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
645   result_message->options = htonl(msg_ctx->msg_options);
646   result_message->hop_count = htonl(msg_ctx->hop_count + 1);
647   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
648   result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
649   memcpy(&result_message->key, msg_ctx->key, sizeof(GNUNET_HashCode));
650   memcpy(&result_message[1], msg, ntohs(msg->size));
651 #if DEBUG_DHT > 1
652   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Adding pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
653 #endif
654   GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
655   if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
656     peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
657 }
658 /**
659  * Called when core is ready to send a message we asked for
660  * out to the destination.
661  *
662  * @param cls closure (NULL)
663  * @param size number of bytes available in buf
664  * @param buf where the callee should write the message
665  * @return number of bytes written to buf
666  */
667 size_t core_transmit_notify (void *cls,
668                              size_t size, void *buf)
669 {
670   struct PeerInfo *peer = cls;
671   char *cbuf = buf;
672   struct P2PPendingMessage *pending;
673
674   size_t off;
675   size_t msize;
676
677   if (buf == NULL)
678     {
679       /* client disconnected */
680 #if DEBUG_DHT
681       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
682 #endif
683       return 0;
684     }
685
686   if (peer->head == NULL)
687     return 0;
688
689   peer->th = NULL;
690   off = 0;
691   pending = peer->head;
692   msize = ntohs(pending->msg->size);
693   if (msize <= size)
694     {
695       off = msize;
696       memcpy (cbuf, pending->msg, msize);
697       GNUNET_CONTAINER_DLL_remove (peer->head,
698                                    peer->tail,
699                                    pending);
700 #if DEBUG_DHT > 1
701       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Removing pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
702 #endif
703       GNUNET_free (pending);
704     }
705 #if SMART
706   while (NULL != pending &&
707           (size - off >= (msize = ntohs (pending->msg->size))))
708     {
709 #if DEBUG_DHT_ROUTING
710       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s:%s' : transmit_notify (core) called with size %d, available %d\n", my_short_id, "dht service", msize, size);
711 #endif
712       memcpy (&cbuf[off], pending->msg, msize);
713       off += msize;
714       GNUNET_CONTAINER_DLL_remove (peer->head,
715                                    peer->tail,
716                                    pending);
717       GNUNET_free (pending);
718       pending = peer->head;
719     }
720 #endif
721   if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
722     peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
723 #if DEBUG_DHT > 1
724   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s:%s' : transmit_notify (core) called with size %d, available %d, returning %d\n", my_short_id, "dht service", msize, size, off);
725 #endif
726   return off;
727 }
728
729 /**
730  * Determine how many low order bits match in two
731  * GNUNET_HashCodes.  i.e. - 010011 and 011111 share
732  * the first two lowest order bits, and therefore the
733  * return value is two (NOT XOR distance, nor how many
734  * bits match absolutely!).
735  *
736  * @param first the first hashcode
737  * @param second the hashcode to compare first to
738  *
739  * @return the number of bits that match
740  */
741 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
742 {
743   unsigned int i;
744
745   for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
746     if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
747       return i;
748   return sizeof (GNUNET_HashCode) * 8;
749 }
750
751 /**
752  * Compute the distance between have and target as a 32-bit value.
753  * Differences in the lower bits must count stronger than differences
754  * in the higher bits.
755  *
756  * @return 0 if have==target, otherwise a number
757  *           that is larger as the distance between
758  *           the two hash codes increases
759  */
760 static unsigned int
761 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
762 {
763   unsigned int bucket;
764   unsigned int msb;
765   unsigned int lsb;
766   unsigned int i;
767
768   /* We have to represent the distance between two 2^9 (=512)-bit
769      numbers as a 2^5 (=32)-bit number with "0" being used for the
770      two numbers being identical; furthermore, we need to
771      guarantee that a difference in the number of matching
772      bits is always represented in the result.
773
774      We use 2^32/2^9 numerical values to distinguish between
775      hash codes that have the same LSB bit distance and
776      use the highest 2^9 bits of the result to signify the
777      number of (mis)matching LSB bits; if we have 0 matching
778      and hence 512 mismatching LSB bits we return -1 (since
779      512 itself cannot be represented with 9 bits) */
780
781   /* first, calculate the most significant 9 bits of our
782      result, aka the number of LSBs */
783   bucket = matching_bits (target, have);
784   /* bucket is now a value between 0 and 512 */
785   if (bucket == 512)
786     return 0;                   /* perfect match */
787   if (bucket == 0)
788     return (unsigned int) -1;   /* LSB differs; use max (if we did the bit-shifting
789                                    below, we'd end up with max+1 (overflow)) */
790
791   /* calculate the most significant bits of the final result */
792   msb = (512 - bucket) << (32 - 9);
793   /* calculate the 32-9 least significant bits of the final result by
794      looking at the differences in the 32-9 bits following the
795      mismatching bit at 'bucket' */
796   lsb = 0;
797   for (i = bucket + 1;
798        (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
799     {
800       if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
801         lsb |= (1 << (bucket + 32 - 9 - i));    /* first bit set will be 10,
802                                                    last bit set will be 31 -- if
803                                                    i does not reach 512 first... */
804     }
805   return msb | lsb;
806 }
807
808 /**
809  * Return a number that is larger the closer the
810  * "have" GNUNET_hash code is to the "target".
811  *
812  * @return inverse distance metric, non-zero.
813  *         Must fudge the value if NO bits match.
814  */
815 static unsigned int
816 inverse_distance (const GNUNET_HashCode * target,
817                   const GNUNET_HashCode * have)
818 {
819   if (matching_bits(target, have) == 0)
820     return 1; /* Never return 0! */
821   return ((unsigned int) -1) - distance (target, have);
822 }
823
824 /**
825  * Find the optimal bucket for this key, regardless
826  * of the current number of buckets in use.
827  *
828  * @param hc the hashcode to compare our identity to
829  *
830  * @return the proper bucket index, or GNUNET_SYSERR
831  *         on error (same hashcode)
832  */
833 static int find_bucket(const GNUNET_HashCode *hc)
834 {
835   unsigned int bits;
836
837   bits = matching_bits(&my_identity.hashPubKey, hc);
838   if (bits == MAX_BUCKETS)
839     return GNUNET_SYSERR;
840   return MAX_BUCKETS - bits - 1;
841 }
842
843 /**
844  * Find which k-bucket this peer should go into,
845  * taking into account the size of the k-bucket
846  * array.  This means that if more bits match than
847  * there are currently buckets, lowest_bucket will
848  * be returned.
849  *
850  * @param hc GNUNET_HashCode we are finding the bucket for.
851  *
852  * @return the proper bucket index for this key,
853  *         or GNUNET_SYSERR on error (same hashcode)
854  */
855 static int find_current_bucket(const GNUNET_HashCode *hc)
856 {
857   int actual_bucket;
858   actual_bucket = find_bucket(hc);
859
860   if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
861     return GNUNET_SYSERR;
862   else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
863     return lowest_bucket;
864   else
865     return actual_bucket;
866 }
867
868 /**
869  * Find a routing table entry from a peer identity
870  *
871  * @param peer the peer to look up
872  *
873  * @return the bucket number holding the peer, GNUNET_SYSERR if not found
874  */
875 static int
876 find_bucket_by_peer(const struct PeerInfo *peer)
877 {
878   int bucket;
879   struct PeerInfo *pos;
880
881   for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
882     {
883       pos = k_buckets[bucket].head;
884       while (pos != NULL)
885         {
886           if (peer == pos)
887             return bucket;
888           pos = pos->next;
889         }
890     }
891
892   return GNUNET_SYSERR; /* No such peer. */
893 }
894
895 #if PRINT_TABLES
896 /**
897  * Print the complete routing table for this peer.
898  */
899 static void
900 print_routing_table ()
901 {
902   int bucket;
903   struct PeerInfo *pos;
904   char char_buf[30000];
905   int char_pos;
906   memset(char_buf, 0, sizeof(char_buf));
907   char_pos = 0;
908   char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
909   //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
910   for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
911     {
912       pos = k_buckets[bucket].head;
913       char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
914       //fprintf(stderr, "Bucket %d:\n", bucket);
915       while (pos != NULL)
916         {
917           //fprintf(stderr, "\tPeer %s, best bucket %d, %d bits match\n", GNUNET_i2s(&pos->id), find_bucket(&pos->id.hashPubKey), matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey));
918           char_pos += sprintf(&char_buf[char_pos], "\tPeer %s, best bucket %d, %d bits match\n", GNUNET_i2s(&pos->id), find_bucket(&pos->id.hashPubKey), matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey));
919           pos = pos->next;
920         }
921     }
922   fprintf(stderr, "%s", char_buf);
923   fflush(stderr);
924 }
925 #endif
926
927 /**
928  * Find a routing table entry from a peer identity
929  *
930  * @param peer the peer identity to look up
931  *
932  * @return the routing table entry, or NULL if not found
933  */
934 static struct PeerInfo *
935 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
936 {
937   int bucket;
938   struct PeerInfo *pos;
939   bucket = find_current_bucket(&peer->hashPubKey);
940
941   if (bucket == GNUNET_SYSERR)
942     return NULL;
943
944   pos = k_buckets[bucket].head;
945   while (pos != NULL)
946     {
947       if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
948         return pos;
949       pos = pos->next;
950     }
951   return NULL; /* No such peer. */
952 }
953
954 /**
955  * Really add a peer to a bucket (only do assertions
956  * on size, etc.)
957  *
958  * @param peer GNUNET_PeerIdentity of the peer to add
959  * @param bucket the already figured out bucket to add
960  *        the peer to
961  * @param latency the core reported latency of this peer
962  * @param distance the transport level distance to this peer
963  *
964  * @return the newly added PeerInfo
965  */
966 static struct PeerInfo *
967 add_peer(const struct GNUNET_PeerIdentity *peer,
968          unsigned int bucket,
969          struct GNUNET_TIME_Relative latency,
970          unsigned int distance)
971 {
972   struct PeerInfo *new_peer;
973   GNUNET_assert(bucket < MAX_BUCKETS);
974   GNUNET_assert(peer != NULL);
975   new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
976   new_peer->latency = latency;
977   new_peer->distance = distance;
978   memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
979
980   GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
981                                     k_buckets[bucket].tail,
982                                     k_buckets[bucket].tail,
983                                     new_peer);
984   k_buckets[bucket].peers_size++;
985
986   return new_peer;
987 }
988
989 /**
990  * Given a peer and its corresponding bucket,
991  * remove it from that bucket.  Does not free
992  * the PeerInfo struct, nor cancel messages
993  * or free messages waiting to be sent to this
994  * peer!
995  *
996  * @param peer the peer to remove
997  * @param bucket the bucket the peer belongs to
998  */
999 static void remove_peer (struct PeerInfo *peer,
1000                          unsigned int bucket)
1001 {
1002   GNUNET_assert(k_buckets[bucket].peers_size > 0);
1003   GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1004                               k_buckets[bucket].tail,
1005                               peer);
1006   k_buckets[bucket].peers_size--;
1007   if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1008     lowest_bucket++;
1009 }
1010
1011 /**
1012  * Removes peer from a bucket, then frees associated
1013  * resources and frees peer.
1014  *
1015  * @param peer peer to be removed and freed
1016  * @param bucket which bucket this peer belongs to
1017  */
1018 static void delete_peer (struct PeerInfo *peer,
1019                          unsigned int bucket)
1020 {
1021   struct P2PPendingMessage *pos;
1022   struct P2PPendingMessage *next;
1023 #if EXTRA_CHECKS
1024   struct PeerInfo *peer_pos;
1025
1026   peer_pos = k_buckets[bucket].head;
1027   while ((peer_pos != NULL) && (peer_pos != peer))
1028     peer_pos = peer_pos->next;
1029   if (peer_pos == NULL)
1030     {
1031       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1032       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Lowest bucket: %d, find_current_bucket: %d, peer resides in bucket: %d\n", my_short_id, "DHT", lowest_bucket, find_current_bucket(&peer->id.hashPubKey), find_bucket_by_peer(peer));
1033     }
1034   GNUNET_assert(peer_pos != NULL);
1035 #endif
1036   remove_peer(peer, bucket); /* First remove the peer from its bucket */
1037
1038   if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1039     GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1040   if (peer->th != NULL)
1041     GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1042
1043   pos = peer->head;
1044   while (pos != NULL) /* Remove any pending messages for this peer */
1045     {
1046       next = pos->next;
1047       GNUNET_free(pos);
1048       pos = next;
1049     }
1050
1051   GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1052   GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1053   GNUNET_free(peer);
1054 }
1055
1056
1057 /**
1058  * Iterator over hash map entries.
1059  *
1060  * @param cls closure
1061  * @param key current key code
1062  * @param value PeerInfo of the peer to move to new lowest bucket
1063  * @return GNUNET_YES if we should continue to
1064  *         iterate,
1065  *         GNUNET_NO if not.
1066  */
1067 static int move_lowest_bucket (void *cls,
1068                                const GNUNET_HashCode * key,
1069                                void *value)
1070 {
1071   struct PeerInfo *peer = value;
1072   int new_bucket;
1073
1074   new_bucket = lowest_bucket - 1;
1075   remove_peer(peer, lowest_bucket);
1076   GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1077                                     k_buckets[new_bucket].tail,
1078                                     k_buckets[new_bucket].tail,
1079                                     peer);
1080   k_buckets[new_bucket].peers_size++;
1081   return GNUNET_YES;
1082 }
1083
1084
1085 /**
1086  * The current lowest bucket is full, so change the lowest
1087  * bucket to the next lower down, and move any appropriate
1088  * entries in the current lowest bucket to the new bucket.
1089  */
1090 static void enable_next_bucket()
1091 {
1092   struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1093   struct PeerInfo *pos;
1094   GNUNET_assert(lowest_bucket > 0);
1095   to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1096   pos = k_buckets[lowest_bucket].head;
1097
1098 #if PRINT_TABLES
1099   fprintf(stderr, "Printing RT before new bucket\n");
1100   print_routing_table();
1101 #endif
1102   /* Populate the array of peers which should be in the next lowest bucket */
1103   while (pos != NULL)
1104     {
1105       if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1106         GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1107       pos = pos->next;
1108     }
1109
1110   /* Remove peers from lowest bucket, insert into next lowest bucket */
1111   GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1112   GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1113   lowest_bucket = lowest_bucket - 1;
1114 #if PRINT_TABLES
1115   fprintf(stderr, "Printing RT after new bucket\n");
1116   print_routing_table();
1117 #endif
1118 }
1119
1120 /**
1121  * Function called to send a request out to another peer.
1122  * Called both for locally initiated requests and those
1123  * received from other peers.
1124  *
1125  * @param cls DHT service closure argument (unused)
1126  * @param msg the encapsulated message
1127  * @param peer the peer to forward the message to
1128  * @param msg_ctx the context of the message (hop count, bloom, etc.)
1129  */
1130 static void forward_message (void *cls,
1131                              const struct GNUNET_MessageHeader *msg,
1132                              struct PeerInfo *peer,
1133                              struct DHT_MessageContext *msg_ctx)
1134 {
1135   struct GNUNET_DHT_P2PRouteMessage *route_message;
1136   struct P2PPendingMessage *pending;
1137   size_t msize;
1138   size_t psize;
1139
1140   increment_stats(STAT_ROUTE_FORWARDS);
1141   msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1142   GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1143   psize = sizeof(struct P2PPendingMessage) + msize;
1144   pending = GNUNET_malloc(psize);
1145   pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1146   pending->importance = DHT_SEND_PRIORITY;
1147   pending->timeout = GNUNET_TIME_relative_get_forever();
1148   route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1149   route_message->header.size = htons(msize);
1150   route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1151   route_message->options = htonl(msg_ctx->msg_options);
1152   route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1153   route_message->network_size = htonl(msg_ctx->network_size);
1154   route_message->desired_replication_level = htonl(msg_ctx->replication);
1155   route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1156   if (msg_ctx->bloom != NULL)
1157     GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1158   if (msg_ctx->key != NULL)
1159     memcpy(&route_message->key, msg_ctx->key, sizeof(GNUNET_HashCode));
1160   memcpy(&route_message[1], msg, ntohs(msg->size));
1161 #if DEBUG_DHT > 1
1162   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Adding pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
1163 #endif
1164   GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1165   if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1166     peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1167 }
1168
1169 #if DO_PING
1170 /**
1171  * Task used to send ping messages to peers so that
1172  * they don't get disconnected.
1173  *
1174  * @param cls the peer to send a ping message to
1175  * @param tc context, reason, etc.
1176  */
1177 static void
1178 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1179 {
1180   struct PeerInfo *peer = cls;
1181   struct GNUNET_MessageHeader ping_message;
1182   struct DHT_MessageContext message_context;
1183
1184   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1185     return;
1186
1187   ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1188   ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1189
1190   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1191 #if DEBUG_PING
1192   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1193 #endif
1194   forward_message(NULL, &ping_message, peer, &message_context);
1195   peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1196 }
1197
1198 /**
1199  * Schedule PING messages for the top X peers in each
1200  * bucket of the routing table (so core won't disconnect them!)
1201  */
1202 void schedule_ping_messages()
1203 {
1204   unsigned int bucket;
1205   unsigned int count;
1206   struct PeerInfo *pos;
1207   for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1208     {
1209       pos = k_buckets[bucket].head;
1210       count = 0;
1211       while (pos != NULL)
1212         {
1213           if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1214             GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1215           else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1216             {
1217               GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1218               pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1219             }
1220           pos = pos->next;
1221           count++;
1222         }
1223     }
1224 }
1225 #endif
1226
1227 /**
1228  * Attempt to add a peer to our k-buckets.
1229  *
1230  * @param peer, the peer identity of the peer being added
1231  *
1232  * @return NULL if the peer was not added,
1233  *         pointer to PeerInfo for new peer otherwise
1234  */
1235 static struct PeerInfo *
1236 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1237              unsigned int bucket,
1238              struct GNUNET_TIME_Relative latency,
1239              unsigned int distance)
1240 {
1241   int peer_bucket;
1242   struct PeerInfo *new_peer;
1243   peer_bucket = find_current_bucket(&peer->hashPubKey);
1244   if (peer_bucket == GNUNET_SYSERR)
1245     return NULL;
1246
1247   GNUNET_assert(peer_bucket >= lowest_bucket);
1248   new_peer = add_peer(peer, peer_bucket, latency, distance);
1249
1250   if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1251     enable_next_bucket();
1252 #if DO_PING
1253   schedule_ping_messages();
1254 #endif
1255   return new_peer;
1256 }
1257
1258
1259 /**
1260  * Task run to check for messages that need to be sent to a client.
1261  *
1262  * @param client a ClientList, containing the client and any messages to be sent to it
1263  */
1264 static void
1265 process_pending_messages (struct ClientList *client)
1266
1267   if (client->pending_head == NULL) 
1268     return;    
1269   if (client->transmit_handle != NULL) 
1270     return;
1271   client->transmit_handle =
1272     GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1273                                          ntohs (client->pending_head->msg->
1274                                                 size),
1275                                          GNUNET_TIME_UNIT_FOREVER_REL,
1276                                          &send_generic_reply, client);
1277 }
1278
1279 /**
1280  * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1281  * request.  A ClientList is passed as closure, take the head of the list
1282  * and copy it into buf, which has the result of sending the message to the
1283  * client.
1284  *
1285  * @param cls closure to this call
1286  * @param size maximum number of bytes available to send
1287  * @param buf where to copy the actual message to
1288  *
1289  * @return the number of bytes actually copied, 0 indicates failure
1290  */
1291 static size_t
1292 send_generic_reply (void *cls, size_t size, void *buf)
1293 {
1294   struct ClientList *client = cls;
1295   char *cbuf = buf;
1296   struct PendingMessage *reply;
1297   size_t off;
1298   size_t msize;
1299
1300   client->transmit_handle = NULL;
1301   if (buf == NULL)             
1302     {
1303       /* client disconnected */
1304       return 0;
1305     }
1306   off = 0;
1307   while ( (NULL != (reply = client->pending_head)) &&
1308           (size >= off + (msize = ntohs (reply->msg->size))))
1309     {
1310       GNUNET_CONTAINER_DLL_remove (client->pending_head,
1311                                    client->pending_tail,
1312                                    reply);
1313       memcpy (&cbuf[off], reply->msg, msize);
1314       GNUNET_free (reply);
1315       off += msize;
1316     }
1317   process_pending_messages (client);
1318   return off;
1319 }
1320
1321
1322 /**
1323  * Add a PendingMessage to the clients list of messages to be sent
1324  *
1325  * @param client the active client to send the message to
1326  * @param pending_message the actual message to send
1327  */
1328 static void
1329 add_pending_message (struct ClientList *client,
1330                      struct PendingMessage *pending_message)
1331 {
1332   GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1333                                      client->pending_tail,
1334                                      client->pending_tail,
1335                                      pending_message);
1336   process_pending_messages (client);
1337 }
1338
1339
1340
1341
1342 /**
1343  * Called when a reply needs to be sent to a client, as
1344  * a result it found to a GET or FIND PEER request.
1345  *
1346  * @param client the client to send the reply to
1347  * @param message the encapsulated message to send
1348  * @param uid the unique identifier of this request
1349  */
1350 static void
1351 send_reply_to_client (struct ClientList *client,
1352                       const struct GNUNET_MessageHeader *message,
1353                       unsigned long long uid)
1354 {
1355   struct GNUNET_DHT_RouteResultMessage *reply;
1356   struct PendingMessage *pending_message;
1357   uint16_t msize;
1358   size_t tsize;
1359 #if DEBUG_DHT
1360   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1361               "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1362 #endif
1363   msize = ntohs (message->size);
1364   tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1365   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1366     {
1367       GNUNET_break_op (0);
1368       return;
1369     }
1370
1371   pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1372   pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1373   reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1374   reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1375   reply->header.size = htons (tsize);
1376   reply->unique_id = GNUNET_htonll (uid);
1377   memcpy (&reply[1], message, msize);
1378
1379   add_pending_message (client, pending_message);
1380 }
1381
1382 /**
1383  * Consider whether or not we would like to have this peer added to
1384  * our routing table.  Check whether bucket for this peer is full,
1385  * if so return negative; if not return positive.  Since peers are
1386  * only added on CORE level connect, this doesn't actually add the
1387  * peer to the routing table.
1388  *
1389  * @param peer the peer we are considering adding
1390  *
1391  * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1392  *         already full)
1393  *
1394  * FIXME: Think about making a context for this call so that we can
1395  *        ping the oldest peer in the current bucket and consider
1396  *        removing it in lieu of the new peer.
1397  */
1398 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1399 {
1400   int bucket;
1401
1402   if (GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1403     return GNUNET_NO; /* We already know this peer (are connected even!) */
1404   bucket = find_current_bucket(&peer->hashPubKey);
1405   if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1406     return GNUNET_YES;
1407
1408   return GNUNET_NO;
1409 }
1410
1411 /**
1412  * Main function that handles whether or not to route a result
1413  * message to other peers, or to send to our local client.
1414  *
1415  * @param msg the result message to be routed
1416  * @return the number of peers the message was routed to,
1417  *         GNUNET_SYSERR on failure
1418  */
1419 static int route_result_message(void *cls,
1420                                 struct GNUNET_MessageHeader *msg,
1421                                 struct DHT_MessageContext *message_context)
1422 {
1423   struct GNUNET_PeerIdentity new_peer;
1424   struct DHTQueryRecord *record;
1425   struct DHTRouteSource *pos;
1426   struct PeerInfo *peer_info;
1427   const struct GNUNET_MessageHeader *hello_msg;
1428
1429   increment_stats(STAT_RESULTS);
1430   /**
1431    * If a find peer result message is received and contains a valid
1432    * HELLO for another peer, offer it to the transport service.
1433    */
1434   if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1435     {
1436       if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1437         GNUNET_break_op(0);
1438
1439       hello_msg = &msg[1];
1440       if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1441       {
1442         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1443         GNUNET_break_op(0);
1444       }
1445       else /* We have a valid hello, and peer id stored in new_peer */
1446       {
1447         increment_stats(STAT_FIND_PEER_REPLY);
1448         if (GNUNET_YES == consider_peer(&new_peer))
1449         {
1450           GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1451           /* GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_UNIT_FOREVER_REL, &new_peer, NULL, NULL); */
1452           /* peer_request_connect call causes service to segfault */
1453           /* FIXME: Do we need this (peer_request_connect call)??? */
1454         }
1455       }
1456
1457     }
1458   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, message_context->key);
1459   if (record == NULL) /* No record of this message! */
1460     {
1461 #if DEBUG_DHT
1462     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1463                 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1464                 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1465 #endif
1466 #if DEBUG_DHT_ROUTING
1467
1468       if ((debug_routes_extended) && (dhtlog_handle != NULL))
1469         {
1470           dhtlog_handle->insert_route (NULL,
1471                                        message_context->unique_id,
1472                                        DHTLOG_RESULT,
1473                                        message_context->hop_count,
1474                                        GNUNET_SYSERR,
1475                                        &my_identity,
1476                                        message_context->key,
1477                                        message_context->peer, NULL);
1478         }
1479 #endif
1480       if (message_context->bloom != NULL)
1481         {
1482           GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1483           message_context->bloom = NULL;
1484         }
1485       return 0;
1486     }
1487
1488   pos = record->head;
1489   while (pos != NULL)
1490     {
1491       if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1492         {
1493 #if DEBUG_DHT
1494           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1495                       "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
1496                       "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1497 #endif
1498 #if DEBUG_DHT_ROUTING
1499           if ((debug_routes_extended) && (dhtlog_handle != NULL))
1500             {
1501               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
1502                                            message_context->hop_count,
1503                                            GNUNET_YES, &my_identity, message_context->key,
1504                                            message_context->peer, NULL);
1505             }
1506 #endif
1507           increment_stats(STAT_RESULTS_TO_CLIENT);
1508           if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
1509             increment_stats(STAT_GET_REPLY);
1510
1511           send_reply_to_client(pos->client, msg, message_context->unique_id);
1512         }
1513       else /* Send to peer */
1514         {
1515           peer_info = find_peer_by_id(&pos->source);
1516           if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
1517             {
1518               pos = pos->next;
1519               continue;
1520             }
1521
1522           if (message_context->bloom == NULL)
1523             message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1524           GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
1525           if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey))
1526             {
1527 #if DEBUG_DHT
1528               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1529                           "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
1530                           "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1531 #endif
1532 #if DEBUG_DHT_ROUTING
1533               if ((debug_routes_extended) && (dhtlog_handle != NULL))
1534                 {
1535                   dhtlog_handle->insert_route (NULL, message_context->unique_id,
1536                                                DHTLOG_RESULT,
1537                                                message_context->hop_count,
1538                                                GNUNET_NO, &my_identity, message_context->key,
1539                                                message_context->peer, &pos->source);
1540                 }
1541 #endif
1542               forward_result_message(cls, msg, peer_info, message_context);
1543             }
1544           else
1545             {
1546 #if DEBUG_DHT
1547               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1548                           "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
1549                           "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1550 #endif
1551             }
1552         }
1553       pos = pos->next;
1554     }
1555   if (message_context->bloom != NULL)
1556     GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1557   return 0;
1558 }
1559
1560 /**
1561  * Iterator for local get request results,
1562  *
1563  * @param cls closure for iterator, a DatacacheGetContext
1564  * @param exp when does this value expire?
1565  * @param key the key this data is stored under
1566  * @param size the size of the data identified by key
1567  * @param data the actual data
1568  * @param type the type of the data
1569  *
1570  * @return GNUNET_OK to continue iteration, anything else
1571  * to stop iteration.
1572  */
1573 static int
1574 datacache_get_iterator (void *cls,
1575                         struct GNUNET_TIME_Absolute exp,
1576                         const GNUNET_HashCode * key,
1577                         uint32_t size, const char *data, uint32_t type)
1578 {
1579   struct DHT_MessageContext *msg_ctx = cls;
1580   struct DHT_MessageContext *new_msg_ctx;
1581   struct GNUNET_DHT_GetResultMessage *get_result;
1582 #if DEBUG_DHT
1583   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1584               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
1585 #endif
1586   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
1587   memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
1588   get_result =
1589     GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
1590   get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
1591   get_result->header.size =
1592     htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
1593   get_result->expiration = GNUNET_TIME_absolute_hton(exp);
1594   get_result->type = htons (type);
1595   memcpy (&get_result[1], data, size);
1596   new_msg_ctx->peer = &my_identity;
1597   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1598   new_msg_ctx->hop_count = 0;
1599   increment_stats(STAT_GET_RESPONSE_START);
1600   route_result_message(cls, &get_result->header, new_msg_ctx);
1601   GNUNET_free(new_msg_ctx);
1602   //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
1603   //                      datacache_get_ctx->unique_id);
1604   GNUNET_free (get_result);
1605   return GNUNET_OK;
1606 }
1607
1608
1609 /**
1610  * Server handler for all dht get requests, look for data,
1611  * if found, send response either to clients or other peers.
1612  *
1613  * @param cls closure for service
1614  * @param msg the actual get message
1615  * @param message_context struct containing pertinent information about the get request
1616  *
1617  * @return number of items found for GET request
1618  */
1619 static unsigned int
1620 handle_dht_get (void *cls, 
1621                 const struct GNUNET_MessageHeader *msg,
1622                 struct DHT_MessageContext *message_context)
1623 {
1624   const struct GNUNET_DHT_GetMessage *get_msg;
1625   uint16_t get_type;
1626   unsigned int results;
1627
1628   get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
1629   if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
1630     {
1631       GNUNET_break (0);
1632       return 0;
1633     }
1634
1635   get_type = ntohs (get_msg->type);
1636 #if DEBUG_DHT
1637   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1638               "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
1639               "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
1640               message_context->unique_id);
1641 #endif
1642   increment_stats(STAT_GETS);
1643   results = 0;
1644   if (datacache != NULL)
1645     results =
1646       GNUNET_DATACACHE_get (datacache, message_context->key, get_type,
1647                             &datacache_get_iterator, message_context);
1648
1649   if (results >= 1)
1650     {
1651 #if DEBUG_DHT
1652       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1653                   "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
1654                   results, "GET", message_context->unique_id);
1655 #endif
1656 #if DEBUG_DHT_ROUTING
1657       if ((debug_routes) && (dhtlog_handle != NULL))
1658         {
1659           dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
1660                                 message_context->hop_count, GNUNET_YES, &my_identity,
1661                                 message_context->key);
1662         }
1663
1664       if ((debug_routes_extended) && (dhtlog_handle != NULL))
1665         {
1666           dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
1667                                        message_context->hop_count, GNUNET_YES,
1668                                        &my_identity, message_context->key, message_context->peer,
1669                                        NULL);
1670         }
1671 #endif
1672     }
1673
1674   if (message_context->hop_count == 0) /* Locally initiated request */
1675     {
1676 #if DEBUG_DHT_ROUTING
1677     if ((debug_routes) && (dhtlog_handle != NULL))
1678       {
1679         dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
1680                                       message_context->hop_count, GNUNET_NO, &my_identity,
1681                                       message_context->key);
1682       }
1683 #endif
1684     }
1685
1686   return results;
1687 }
1688
1689
1690 /**
1691  * Server handler for initiating local dht find peer requests
1692  *
1693  * @param cls closure for service
1694  * @param find_msg the actual find peer message
1695  * @param message_context struct containing pertinent information about the request
1696  *
1697  */
1698 static void
1699 handle_dht_find_peer (void *cls, 
1700                       const struct GNUNET_MessageHeader *find_msg,
1701                       struct DHT_MessageContext *message_context)
1702 {
1703   struct GNUNET_MessageHeader *find_peer_result;
1704   struct DHT_MessageContext *new_msg_ctx;
1705   size_t hello_size;
1706   size_t tsize;
1707
1708 #if DEBUG_DHT
1709   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1710               "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
1711               my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
1712               ntohs (find_msg->size),
1713               sizeof (struct GNUNET_MessageHeader));
1714 #endif
1715   if (my_hello == NULL)
1716   {
1717 #if DEBUG_DHT
1718     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1719                 "`%s': Our HELLO is null, can't return.\n",
1720                 "DHT");
1721 #endif
1722     return;
1723   }
1724   /* Simplistic find_peer functionality, always return our hello */
1725   hello_size = ntohs(my_hello->size);
1726   tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
1727
1728   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1729     {
1730       GNUNET_break_op (0);
1731       return;
1732     }
1733
1734   find_peer_result = GNUNET_malloc (tsize);
1735   find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
1736   find_peer_result->size = htons (tsize);
1737   memcpy (&find_peer_result[1], my_hello, hello_size);
1738
1739   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1740               "`%s': Sending hello size %d to requesting peer.\n",
1741               "DHT", hello_size);
1742
1743   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
1744   memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
1745   new_msg_ctx->peer = &my_identity;
1746   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1747   new_msg_ctx->hop_count = 0;
1748   increment_stats(STAT_FIND_PEER_ANSWER);
1749   route_result_message(cls, find_peer_result, new_msg_ctx);
1750   GNUNET_free(new_msg_ctx);
1751 #if DEBUG_DHT_ROUTING
1752   if ((debug_routes) && (dhtlog_handle != NULL))
1753     {
1754       dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
1755                                    message_context->hop_count, GNUNET_YES, &my_identity,
1756                                    message_context->key);
1757     }
1758 #endif
1759   //send_reply_to_client(message_context->client, find_peer_result, message_context->unique_id);
1760   GNUNET_free(find_peer_result);
1761 }
1762
1763
1764 /**
1765  * Server handler for initiating local dht put requests
1766  *
1767  * @param cls closure for service
1768  * @param msg the actual put message
1769  * @param message_context struct containing pertinent information about the request
1770  */
1771 static void
1772 handle_dht_put (void *cls,
1773                 const struct GNUNET_MessageHeader *msg,
1774                 struct DHT_MessageContext *message_context)
1775 {
1776   struct GNUNET_DHT_PutMessage *put_msg;
1777   size_t put_type;
1778   size_t data_size;
1779
1780   GNUNET_assert (ntohs (msg->size) >=
1781                  sizeof (struct GNUNET_DHT_PutMessage));
1782   put_msg = (struct GNUNET_DHT_PutMessage *)msg;
1783   put_type = ntohs (put_msg->type);
1784   data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
1785 #if DEBUG_DHT
1786   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1787               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
1788               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
1789 #endif
1790   increment_stats(STAT_PUTS_INSERTED);
1791 #if DEBUG_DHT_ROUTING
1792   if ((debug_routes) && (dhtlog_handle != NULL))
1793     {
1794       dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
1795                                    message_context->hop_count, GNUNET_YES, &my_identity,
1796                                    message_context->key);
1797     }
1798 #endif
1799
1800   if (datacache != NULL)
1801     GNUNET_DATACACHE_put (datacache, message_context->key, data_size,
1802                           (char *) &put_msg[1], put_type,
1803                           GNUNET_TIME_absolute_ntoh(put_msg->expiration));
1804   else
1805     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1806                 "`%s:%s': %s request received, but have no datacache!\n",
1807                 my_short_id, "DHT", "PUT");
1808 }
1809
1810 /**
1811  * Estimate the diameter of the network based
1812  * on how many buckets are currently in use.
1813  * Concept here is that the diameter of the network
1814  * is roughly the distance a message must travel in
1815  * order to reach its intended destination.  Since
1816  * at each hop we expect to get one bit closer, and
1817  * we have one bit per bucket, the number of buckets
1818  * in use should be the largest number of hops for
1819  * a sucessful message. (of course, this assumes we
1820  * know all peers in the network!)
1821  *
1822  * @return ballpark diameter figure
1823  */
1824 static unsigned int estimate_diameter()
1825 {
1826   return MAX_BUCKETS - lowest_bucket;
1827 }
1828
1829 /**
1830  * To how many peers should we (on average)
1831  * forward the request to obtain the desired
1832  * target_replication count (on average).
1833  *
1834  * Always 0, 1 or 2 (don't send, send once, split)
1835  */
1836 static unsigned int
1837 get_forward_count (unsigned int hop_count, size_t target_replication)
1838 {
1839   double target_count;
1840   unsigned int target_value;
1841   unsigned int diameter;
1842
1843   /* FIXME: the smaller we think the network is the more lenient we should be for
1844    * routing right?  The estimation below only works if we think we have reasonably
1845    * full routing tables, which for our RR topologies may not be the case!
1846    */
1847   diameter = estimate_diameter ();
1848   if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
1849     {
1850 #if DEBUG_DHT
1851       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1852                   "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
1853                   "DHT", estimate_diameter(), lowest_bucket);
1854 #endif
1855       return 0;
1856     }
1857   else if (hop_count > MAX_HOPS)
1858     {
1859 #if DEBUG_DHT
1860       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1861                   "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
1862                   "DHT");
1863 #endif
1864       return 0;
1865     }
1866   target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
1867     target_replication / (target_replication * (hop_count + 1) + diameter);
1868   target_value = 0;
1869
1870 #if NONSENSE
1871   while (target_value < target_count)
1872     target_value++; /* target_value is ALWAYS 1 after this "loop" */
1873 #else
1874   target_value = 1;
1875 #endif
1876   if ((target_count + 1 - target_value) >
1877       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1878                                 RAND_MAX) / RAND_MAX)
1879     target_value++;
1880   return target_value;
1881 }
1882
1883 /**
1884  * Find the closest peer in our routing table to the
1885  * given hashcode.
1886  *
1887  * @return The closest peer in our routing table to the
1888  *         key, or NULL on error.
1889  */
1890 static struct PeerInfo *
1891 find_closest_peer (const GNUNET_HashCode *hc)
1892 {
1893   struct PeerInfo *pos;
1894   struct PeerInfo *current_closest;
1895   unsigned int lowest_distance;
1896   unsigned int temp_distance;
1897   int bucket;
1898   int count;
1899
1900   lowest_distance = -1;
1901
1902   if (k_buckets[lowest_bucket].peers_size == 0)
1903     return NULL;
1904
1905   current_closest = NULL;
1906   for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1907     {
1908       pos = k_buckets[bucket].head;
1909       count = 0;
1910       while ((pos != NULL) && (count < bucket_size))
1911         {
1912           temp_distance = distance(&pos->id.hashPubKey, hc);
1913           if (temp_distance <= lowest_distance)
1914             {
1915               lowest_distance = temp_distance;
1916               current_closest = pos;
1917             }
1918           pos = pos->next;
1919           count++;
1920         }
1921     }
1922   GNUNET_assert(current_closest != NULL);
1923   return current_closest;
1924 }
1925
1926 /*
1927  * Check whether my identity is closer than any known peers.
1928  *
1929  * @param target hash code to check closeness to
1930  *
1931  * Return GNUNET_YES if node location is closest, GNUNET_NO
1932  * otherwise.
1933  */
1934 int
1935 am_closest_peer (const GNUNET_HashCode * target)
1936 {
1937   int bits;
1938   int other_bits;
1939   int bucket_num;
1940   int count;
1941   struct PeerInfo *pos;
1942   unsigned int my_distance;
1943
1944   bucket_num = find_current_bucket(target);
1945   if (bucket_num == GNUNET_SYSERR) /* Same key! */
1946     return GNUNET_YES;
1947
1948   bits = matching_bits(&my_identity.hashPubKey, target);
1949   my_distance = distance(&my_identity.hashPubKey, target);
1950
1951   pos = k_buckets[bucket_num].head;
1952   count = 0;
1953   while ((pos != NULL) && (count < bucket_size))
1954     {
1955       other_bits = matching_bits(&pos->id.hashPubKey, target);
1956       if (other_bits > bits)
1957         return GNUNET_NO;
1958       else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
1959         {
1960           return GNUNET_YES;
1961           /* FIXME: why not just return GNUNET_YES here?  We are certainly close. */
1962           /*if (distance(&pos->id.hashPubKey, target) < my_distance)
1963             return GNUNET_NO;*/
1964         }
1965       pos = pos->next;
1966     }
1967
1968 #if DEBUG_TABLE
1969   GNUNET_GE_LOG (coreAPI->ectx,
1970                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
1971                  GNUNET_GE_BULK, "closest peer\n");
1972   printPeerBits (&closest);
1973   GNUNET_GE_LOG (coreAPI->ectx,
1974                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
1975                  GNUNET_GE_BULK, "me\n");
1976   printPeerBits (coreAPI->my_identity);
1977   GNUNET_GE_LOG (coreAPI->ectx,
1978                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
1979                  GNUNET_GE_BULK, "key\n");
1980   printKeyBits (target);
1981   GNUNET_GE_LOG (coreAPI->ectx,
1982                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
1983                  GNUNET_GE_BULK,
1984                  "closest peer inverse distance is %u, mine is %u\n",
1985                  inverse_distance (target, &closest.hashPubKey),
1986                  inverse_distance (target,
1987                                    &coreAPI->my_identity->hashPubKey));
1988 #endif
1989
1990   /* No peers closer, we are the closest! */
1991   return GNUNET_YES;
1992
1993 }
1994
1995
1996 /**
1997  * Select a peer from the routing table that would be a good routing
1998  * destination for sending a message for "target".  The resulting peer
1999  * must not be in the set of blocked peers.<p>
2000  *
2001  * Note that we should not ALWAYS select the closest peer to the
2002  * target, peers further away from the target should be chosen with
2003  * exponentially declining probability.
2004  *
2005  * @param target the key we are selecting a peer to route to
2006  * @param bloom a bloomfilter containing entries this request has seen already
2007  *
2008  * @return Peer to route to, or NULL on error
2009  */
2010 static struct PeerInfo *
2011 select_peer (const GNUNET_HashCode * target,
2012              struct GNUNET_CONTAINER_BloomFilter *bloom)
2013 {
2014   unsigned int distance;
2015   unsigned int bc;
2016   unsigned int count;
2017   struct PeerInfo *pos;
2018 #if USE_KADEMLIA
2019   const struct PeerInfo *chosen;
2020   unsigned long long largest_distance;
2021 #else
2022   unsigned long long total_distance;
2023   unsigned long long selected;
2024 #endif
2025
2026 #if USE_KADEMLIA
2027   largest_distance = 0;
2028   chosen = NULL;
2029   for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2030     {
2031       pos = k_buckets[bc].head;
2032       while (pos != NULL)
2033         {
2034           if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2035             {
2036               distance = inverse_distance (target, &pos->id.hashPubKey);
2037               if (distance > largest_distance)
2038                 {
2039                   chosen = pos;
2040                   largest_distance = distance;
2041                 }
2042             }
2043           pos = pos->next;
2044         }
2045     }
2046
2047   if ((largest_distance > 0) && (chosen != NULL))
2048     {
2049       GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2050       return chosen;
2051     }
2052   else
2053     {
2054       return NULL;
2055     }
2056 #else
2057   /* GNUnet-style */
2058   total_distance = 0;
2059   for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2060     {
2061       pos = k_buckets[bc].head;
2062       count = 0;
2063       while ((pos != NULL) && (count < bucket_size))
2064         {
2065           if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2066             total_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2067 #if DEBUG_DHT > 1
2068           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2069                       "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2070                       my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2071 #endif
2072           pos = pos->next;
2073           count++;
2074         }
2075     }
2076   if (total_distance == 0)
2077     {
2078       return NULL;
2079     }
2080
2081   selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2082   for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2083     {
2084       pos = k_buckets[bc].head;
2085       count = 0;
2086       while ((pos != NULL) && (count < bucket_size))
2087         {
2088           if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2089             {
2090               distance = inverse_distance (target, &pos->id.hashPubKey);
2091               if (distance > selected)
2092                 return pos;
2093               selected -= distance;
2094             }
2095           else
2096             {
2097 #if DEBUG_DHT
2098               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2099                           "`%s:%s': peer %s matches bloomfilter.\n",
2100                           my_short_id, "DHT", GNUNET_i2s(&pos->id));
2101 #endif
2102             }
2103           pos = pos->next;
2104           count++;
2105         }
2106     }
2107 #if DEBUG_DHT
2108     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2109                 "`%s:%s': peer %s matches bloomfilter.\n",
2110                 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2111 #endif
2112   return NULL;
2113 #endif
2114 }
2115
2116
2117 /**
2118  * Task used to remove forwarding entries, either
2119  * after timeout, when full, or on shutdown.
2120  *
2121  * @param cls the entry to remove
2122  * @param tc context, reason, etc.
2123  */
2124 static void
2125 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2126 {
2127   struct DHTRouteSource *source_info = cls;
2128   struct DHTQueryRecord *record;
2129   source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2130   record = source_info->record;
2131   GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2132
2133   if (record->head == NULL) /* No more entries in DLL */
2134     {
2135       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2136       GNUNET_free(record);
2137     }
2138   GNUNET_free(source_info);
2139 }
2140
2141 /**
2142  * Remember this routing request so that if a reply is
2143  * received we can either forward it to the correct peer
2144  * or return the result locally.
2145  *
2146  * @param cls DHT service closure
2147  * @param msg_ctx Context of the route request
2148  *
2149  * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2150  */
2151 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2152 {
2153   struct DHTQueryRecord *record;
2154   struct DHTRouteSource *source_info;
2155   struct DHTRouteSource *pos;
2156   struct GNUNET_TIME_Absolute now;
2157   unsigned int current_size;
2158
2159   current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2160   while (current_size >= MAX_OUTSTANDING_FORWARDS)
2161     {
2162       source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2163       record = source_info->record;
2164       GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2165       if (record->head == NULL) /* No more entries in DLL */
2166         {
2167           GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2168           GNUNET_free(record);
2169         }
2170       GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2171       GNUNET_free(source_info);
2172       current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2173     }
2174   now = GNUNET_TIME_absolute_get();
2175   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, msg_ctx->key);
2176   if (record != NULL) /* Already know this request! */
2177     {
2178       pos = record->head;
2179       while (pos != NULL)
2180         {
2181           if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
2182             break; /* Already have this peer in reply list! */
2183           pos = pos->next;
2184         }
2185       if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
2186         {
2187           GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
2188           return GNUNET_NO;
2189         }
2190     }
2191   else
2192     {
2193       record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
2194       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2195       memcpy(&record->key, msg_ctx->key, sizeof(GNUNET_HashCode));
2196     }
2197
2198   source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
2199   source_info->record = record;
2200   source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
2201   memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
2202   GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
2203   if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
2204     {
2205       source_info->client = msg_ctx->client;
2206       now = GNUNET_TIME_absolute_get_forever();
2207     }
2208   source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
2209 #if DEBUG_DHT > 1
2210       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2211                   "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
2212                   "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
2213 #endif
2214   return GNUNET_YES;
2215 }
2216
2217
2218 /**
2219  * Main function that handles whether or not to route a message to other
2220  * peers.
2221  *
2222  * @param msg the message to be routed
2223  *
2224  * @return the number of peers the message was routed to,
2225  *         GNUNET_SYSERR on failure
2226  */
2227 static int route_message(void *cls,
2228                          const struct GNUNET_MessageHeader *msg,
2229                          struct DHT_MessageContext *message_context)
2230 {
2231   int i;
2232   struct PeerInfo *selected;
2233   struct PeerInfo *nearest;
2234   unsigned int forward_count;
2235 #if DEBUG_DHT
2236   char *nearest_buf;
2237 #endif
2238 #if DEBUG_DHT_ROUTING
2239   int ret;
2240 #endif
2241
2242   increment_stats(STAT_ROUTES);
2243   message_context->closest = am_closest_peer(message_context->key);
2244   forward_count = get_forward_count(message_context->hop_count, message_context->replication);
2245   nearest = find_closest_peer(message_context->key);
2246
2247   if (message_context->bloom == NULL)
2248     message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2249   GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2250
2251   if ((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
2252     forward_count = 0;
2253
2254 #if DEBUG_DHT_ROUTING
2255   if (forward_count == 0)
2256     ret = GNUNET_SYSERR;
2257   else
2258     ret = GNUNET_NO;
2259
2260   if ((debug_routes_extended) && (dhtlog_handle != NULL))
2261     {
2262       dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2263                                    message_context->hop_count, ret,
2264                                    &my_identity, message_context->key, message_context->peer,
2265                                    NULL);
2266     }
2267 #endif
2268
2269   switch (ntohs(msg->type))
2270     {
2271     case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
2272       cache_response (cls, message_context);
2273       if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
2274         forward_count = 0;
2275       break;
2276     case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
2277       increment_stats(STAT_PUTS);
2278       if (message_context->closest == GNUNET_YES)
2279         {
2280 #if DEBUG_DHT_ROUTING
2281           if ((debug_routes_extended) && (dhtlog_handle != NULL))
2282             {
2283               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2284                                            message_context->hop_count, GNUNET_YES,
2285                                            &my_identity, message_context->key, message_context->peer,
2286                                            NULL);
2287             }
2288 #endif
2289           handle_dht_put (cls, msg, message_context);
2290         }
2291 #if DEBUG_DHT_ROUTING
2292         if (message_context->hop_count == 0) /* Locally initiated request */
2293           {
2294             if ((debug_routes) && (dhtlog_handle != NULL))
2295               {
2296                 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2297                                              message_context->hop_count, GNUNET_NO, &my_identity,
2298                                              message_context->key);
2299               }
2300           }
2301 #endif
2302       break;
2303     case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
2304       increment_stats(STAT_FIND_PEER);
2305       if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
2306       {
2307         cache_response (cls, message_context);
2308         if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
2309           handle_dht_find_peer (cls, msg, message_context);
2310       }
2311 #if DEBUG_DHT_ROUTING
2312       if (message_context->hop_count == 0) /* Locally initiated request */
2313         {
2314           if ((debug_routes) && (dhtlog_handle != NULL))
2315             {
2316               dhtlog_handle->insert_dhtkey(NULL, message_context->key);
2317               dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2318                                            message_context->hop_count, GNUNET_NO, &my_identity,
2319                                            message_context->key);
2320             }
2321         }
2322 #endif
2323       break;
2324     default:
2325       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2326                   "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
2327     }
2328
2329   for (i = 0; i < forward_count; i++)
2330     {
2331       selected = select_peer(message_context->key, message_context->bloom);
2332       /* FIXME: either log to sql or log to stats or both when selected is NULL at this point! */
2333       if (selected != NULL)
2334         {
2335           GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
2336 #if DEBUG_DHT_ROUTING > 1
2337           nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
2338           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2339                       "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
2340                       "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&selected->id), nearest_buf, matching_bits(&nearest->id.hashPubKey, message_context->key), distance(&nearest->id.hashPubKey, message_context->key));
2341           GNUNET_free(nearest_buf);
2342 #endif
2343           /* FIXME: statistics */
2344           if ((debug_routes_extended) && (dhtlog_handle != NULL))
2345             {
2346               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2347                                            message_context->hop_count, GNUNET_NO,
2348                                            &my_identity, message_context->key, message_context->peer,
2349                                            &selected->id);
2350             }
2351           forward_message(cls, msg, selected, message_context);
2352         }
2353       else
2354         {
2355 #if DEBUG_DHT
2356           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2357                       "`%s:%s': No peers selected for forwarding.\n", my_short_id,
2358                       "DHT");
2359 #endif
2360         }
2361     }
2362 #if DEBUG_DHT_ROUTING > 1
2363   if (forward_count == 0)
2364     {
2365       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2366                   "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
2367                   "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2368     }
2369 #endif
2370
2371   if (message_context->bloom != NULL)
2372     GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2373
2374   return forward_count;
2375 }
2376
2377 /**
2378  * Find a client if it exists, add it otherwise.
2379  *
2380  * @param client the server handle to the client
2381  *
2382  * @return the client if found, a new client otherwise
2383  */
2384 static struct ClientList *
2385 find_active_client (struct GNUNET_SERVER_Client *client)
2386 {
2387   struct ClientList *pos = client_list;
2388   struct ClientList *ret;
2389
2390   while (pos != NULL)
2391     {
2392       if (pos->client_handle == client)
2393         return pos;
2394       pos = pos->next;
2395     }
2396
2397   ret = GNUNET_malloc (sizeof (struct ClientList));
2398   ret->client_handle = client;
2399   ret->next = client_list;
2400   client_list = ret;
2401   return ret;
2402 }
2403
2404 /**
2405  * Task to send a find peer message for our own peer identifier
2406  * so that we can find the closest peers in the network to ourselves
2407  * and attempt to connect to them.
2408  *
2409  * @param cls closure for this task
2410  * @param tc the context under which the task is running
2411  */
2412 static void
2413 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2414 {
2415   struct GNUNET_MessageHeader *find_peer_msg;
2416   struct DHT_MessageContext message_context;
2417   int ret;
2418   struct GNUNET_TIME_Relative next_send_time;
2419
2420   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2421     return;
2422
2423   increment_stats(STAT_FIND_PEER_START);
2424
2425   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_MessageHeader));
2426   find_peer_msg->size = htons(sizeof(struct GNUNET_MessageHeader));
2427   find_peer_msg->type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
2428   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2429   message_context.key = &my_identity.hashPubKey;
2430   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
2431   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2432   message_context.msg_options = ntohl (DHT_DEFAULT_FIND_PEER_OPTIONS);
2433   message_context.network_size = estimate_diameter();
2434   message_context.peer = &my_identity;
2435
2436   ret = route_message(NULL, find_peer_msg, &message_context);
2437   GNUNET_free(find_peer_msg);
2438   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2439               "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
2440               "FIND PEER", ret);
2441   next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
2442                          GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
2443                                                   DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
2444   GNUNET_SCHEDULER_add_delayed (sched,
2445                                 next_send_time,
2446                                 &send_find_peer_message, NULL);
2447 }
2448
2449 /**
2450  * Handler for any generic DHT messages, calls the appropriate handler
2451  * depending on message type, sends confirmation if responses aren't otherwise
2452  * expected.
2453  *
2454  * @param cls closure for the service
2455  * @param client the client we received this message from
2456  * @param message the actual message received
2457  */
2458 static void
2459 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
2460                                 const struct GNUNET_MessageHeader *message)
2461 {
2462   const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
2463   const struct GNUNET_MessageHeader *enc_msg;
2464   struct DHT_MessageContext message_context;
2465   size_t enc_type;
2466
2467   enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
2468   enc_type = ntohs (enc_msg->type);
2469
2470 #if DEBUG_DHT
2471   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2472               "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
2473               my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
2474               GNUNET_ntohll (dht_msg->unique_id));
2475 #endif
2476 #if DEBUG_DHT_ROUTING
2477   if (dhtlog_handle != NULL)
2478     dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
2479 #endif
2480   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2481   message_context.client = find_active_client (client);
2482   message_context.key = &dht_msg->key;
2483   message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
2484   message_context.replication = ntohl (dht_msg->desired_replication_level);
2485   message_context.msg_options = ntohl (dht_msg->options);
2486   message_context.network_size = estimate_diameter();
2487   message_context.peer = &my_identity;
2488
2489   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
2490     increment_stats(STAT_GET_START);
2491   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
2492     increment_stats(STAT_PUT_START);
2493   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
2494     increment_stats(STAT_FIND_PEER_START);
2495
2496   route_message(cls, enc_msg, &message_context);
2497
2498   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2499
2500 }
2501
2502 /**
2503  * Handler for any generic DHT stop messages, calls the appropriate handler
2504  * depending on message type (if processed locally)
2505  *
2506  * @param cls closure for the service
2507  * @param client the client we received this message from
2508  * @param message the actual message received
2509  *
2510  */
2511 static void
2512 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
2513                             const struct GNUNET_MessageHeader *message)
2514 {
2515
2516   const struct GNUNET_DHT_StopMessage *dht_stop_msg =
2517     (const struct GNUNET_DHT_StopMessage *) message;
2518   struct DHTQueryRecord *record;
2519   struct DHTRouteSource *pos;
2520   uint64_t uid;
2521 #if DEBUG_DHT
2522   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2523               "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
2524               "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
2525 #endif
2526
2527   uid = GNUNET_ntohll(dht_stop_msg->unique_id);
2528
2529   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
2530   if (record != NULL)
2531     {
2532       pos = record->head;
2533
2534       while (pos != NULL)
2535         {
2536           if ((pos->client != NULL) && (pos->client->client_handle == client))
2537             {
2538               GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
2539               GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
2540             }
2541           pos = pos->next;
2542         }
2543     }
2544
2545   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2546 }
2547
2548
2549 /**
2550  * Core handler for p2p route requests.
2551  */
2552 static int
2553 handle_dht_p2p_route_request (void *cls,
2554                               const struct GNUNET_PeerIdentity *peer,
2555                               const struct GNUNET_MessageHeader *message,
2556                               struct GNUNET_TIME_Relative latency, uint32_t distance)
2557 {
2558 #if DEBUG_DHT
2559   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2560               "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
2561 #endif
2562   struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
2563   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
2564   struct DHT_MessageContext *message_context;
2565
2566   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
2567     {
2568 #if DEBUG_PING
2569       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
2570 #endif
2571       return GNUNET_YES;
2572     }
2573
2574   if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2575     {
2576       GNUNET_break_op(0);
2577       return GNUNET_YES;
2578     }
2579   //memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2580   message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
2581   message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2582   GNUNET_assert(message_context->bloom != NULL);
2583   message_context->hop_count = ntohl(incoming->hop_count);
2584   message_context->key = &incoming->key;
2585   message_context->replication = ntohl(incoming->desired_replication_level);
2586   message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
2587   message_context->msg_options = ntohl(incoming->options);
2588   message_context->network_size = ntohl(incoming->network_size);
2589   message_context->peer = peer;
2590   route_message(cls, enc_msg, message_context);
2591   GNUNET_free(message_context);
2592   return GNUNET_YES;
2593 }
2594
2595
2596 /**
2597  * Core handler for p2p route results.
2598  */
2599 static int
2600 handle_dht_p2p_route_result (void *cls,
2601                              const struct GNUNET_PeerIdentity *peer,
2602                              const struct GNUNET_MessageHeader *message,
2603                              struct GNUNET_TIME_Relative latency, uint32_t distance)
2604 {
2605 #if DEBUG_DHT
2606   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2607               "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
2608 #endif
2609   struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
2610   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
2611   struct DHT_MessageContext message_context;
2612
2613   if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2614     {
2615       GNUNET_break_op(0);
2616       return GNUNET_YES;
2617     }
2618
2619   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2620   message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2621   GNUNET_assert(message_context.bloom != NULL);
2622   message_context.key = &incoming->key;
2623   message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
2624   message_context.msg_options = ntohl(incoming->options);
2625   message_context.hop_count = ntohl(incoming->hop_count);
2626   message_context.peer = peer;
2627   route_result_message(cls, enc_msg, &message_context);
2628   return GNUNET_YES;
2629 }
2630
2631
2632 /**
2633  * Receive the HELLO from transport service,
2634  * free current and replace if necessary.
2635  *
2636  * @param cls NULL
2637  * @param message HELLO message of peer
2638  */
2639 static void
2640 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
2641 {
2642 #if DEBUG_DHT
2643   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2644               "Received our `%s' from transport service\n",
2645               "HELLO");
2646 #endif
2647
2648   GNUNET_assert (message != NULL);
2649   GNUNET_free_non_null(my_hello);
2650   my_hello = GNUNET_malloc(ntohs(message->size));
2651   memcpy(my_hello, message, ntohs(message->size));
2652 }
2653
2654
2655 /**
2656  * Task run during shutdown.
2657  *
2658  * @param cls unused
2659  * @param tc unused
2660  */
2661 static void
2662 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2663 {
2664   int bucket_count;
2665   struct PeerInfo *pos;
2666   if (transport_handle != NULL)
2667   {
2668     GNUNET_free_non_null(my_hello);
2669     GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
2670     GNUNET_TRANSPORT_disconnect(transport_handle);
2671   }
2672
2673   for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
2674     {
2675       while (k_buckets[bucket_count].head != NULL)
2676         {
2677           pos = k_buckets[bucket_count].head;
2678 #if DEBUG_DHT
2679           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2680                       "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
2681 #endif
2682           delete_peer(pos, bucket_count);
2683         }
2684     }
2685   if (coreAPI != NULL)
2686     {
2687 #if DEBUG_DHT
2688       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2689                   "%s:%s Disconnecting core!\n", my_short_id, "DHT");
2690 #endif
2691       GNUNET_CORE_disconnect (coreAPI);
2692     }
2693   if (datacache != NULL)
2694     {
2695 #if DEBUG_DHT
2696       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2697                   "%s:%s Destroying datacache!\n", my_short_id, "DHT");
2698 #endif
2699       GNUNET_DATACACHE_destroy (datacache);
2700     }
2701
2702   if (stats != NULL)
2703     {
2704       GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
2705     }
2706
2707   if (dhtlog_handle != NULL)
2708     GNUNET_DHTLOG_disconnect(dhtlog_handle);
2709
2710   GNUNET_free_non_null(my_short_id);
2711 }
2712
2713
2714 /**
2715  * To be called on core init/fail.
2716  *
2717  * @param cls service closure
2718  * @param server handle to the server for this service
2719  * @param identity the public identity of this peer
2720  * @param publicKey the public key of this peer
2721  */
2722 void
2723 core_init (void *cls,
2724            struct GNUNET_CORE_Handle *server,
2725            const struct GNUNET_PeerIdentity *identity,
2726            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
2727 {
2728
2729   if (server == NULL)
2730     {
2731 #if DEBUG_DHT
2732   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2733               "%s: Connection to core FAILED!\n", "dht",
2734               GNUNET_i2s (identity));
2735 #endif
2736       GNUNET_SCHEDULER_cancel (sched, cleanup_task);
2737       GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
2738       return;
2739     }
2740 #if DEBUG_DHT
2741   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2742               "%s: Core connection initialized, I am peer: %s\n", "dht",
2743               GNUNET_i2s (identity));
2744 #endif
2745
2746   /* Copy our identity so we can use it */
2747   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
2748   if (my_short_id != NULL)
2749     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
2750   my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
2751   /* Set the server to local variable */
2752   coreAPI = server;
2753
2754   if (dhtlog_handle != NULL)
2755     dhtlog_handle->insert_node (NULL, &my_identity);
2756 }
2757
2758
2759 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
2760   {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
2761   {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
2762   {NULL, NULL, 0, 0}
2763 };
2764
2765
2766 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2767   {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
2768   {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
2769   {NULL, 0, 0}
2770 };
2771
2772 /**
2773  * Method called whenever a peer connects.
2774  *
2775  * @param cls closure
2776  * @param peer peer identity this notification is about
2777  * @param latency reported latency of the connection with peer
2778  * @param distance reported distance (DV) to peer
2779  */
2780 void handle_core_connect (void *cls,
2781                           const struct GNUNET_PeerIdentity * peer,
2782                           struct GNUNET_TIME_Relative latency,
2783                           uint32_t distance)
2784 {
2785   struct PeerInfo *ret;
2786
2787 #if DEBUG_DHT
2788   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2789               "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
2790 #endif
2791
2792   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
2793     {
2794       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s:%s Received %s message for peer %s, but already have peer in RT!", my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s(peer));
2795       return;
2796     }
2797
2798   if (datacache != NULL)
2799     GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
2800   ret = try_add_peer(peer,
2801                      find_current_bucket(&peer->hashPubKey),
2802                      latency,
2803                      distance);
2804   if (ret != NULL)
2805     {
2806       GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2807     }
2808 #if DEBUG_DHT
2809     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2810                 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
2811 #endif
2812 }
2813
2814 /**
2815  * Method called whenever a peer disconnects.
2816  *
2817  * @param cls closure
2818  * @param peer peer identity this notification is about
2819  */
2820 void handle_core_disconnect (void *cls,
2821                              const struct
2822                              GNUNET_PeerIdentity * peer)
2823 {
2824   struct PeerInfo *to_remove;
2825   int current_bucket;
2826
2827   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s: Received peer disconnect message for peer `%s' from %s\n", my_short_id, "DHT", GNUNET_i2s(peer), "CORE");
2828
2829   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
2830     {
2831       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: do not have peer `%s' in RT, can't disconnect!\n", my_short_id, "DHT", GNUNET_i2s(peer));
2832       return;
2833     }
2834   GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
2835   to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
2836   GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
2837   current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
2838   delete_peer(to_remove, current_bucket);
2839 }
2840
2841 /**
2842  * Process dht requests.
2843  *
2844  * @param cls closure
2845  * @param scheduler scheduler to use
2846  * @param server the initialized server
2847  * @param c configuration to use
2848  */
2849 static void
2850 run (void *cls,
2851      struct GNUNET_SCHEDULER_Handle *scheduler,
2852      struct GNUNET_SERVER_Handle *server,
2853      const struct GNUNET_CONFIGURATION_Handle *c)
2854 {
2855   int random_seconds;
2856   sched = scheduler;
2857   cfg = c;
2858   datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
2859   GNUNET_SERVER_add_handlers (server, plugin_handlers);
2860   coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
2861                                  cfg,   /* Main configuration */
2862                                  GNUNET_TIME_UNIT_FOREVER_REL,
2863                                  NULL,  /* Closure passed to DHT functionas around? */
2864                                  &core_init,    /* Call core_init once connected */
2865                                  &handle_core_connect,  /* Handle connects */
2866                                  &handle_core_disconnect,  /* remove peers on disconnects */
2867                                  NULL,  /* Do we care about "status" updates? */
2868                                  NULL,  /* Don't want notified about all incoming messages */
2869                                  GNUNET_NO,     /* For header only inbound notification */
2870                                  NULL,  /* Don't want notified about all outbound messages */
2871                                  GNUNET_NO,     /* For header only outbound notification */
2872                                  core_handlers);        /* Register these handlers */
2873
2874   if (coreAPI == NULL)
2875     return;
2876   transport_handle = GNUNET_TRANSPORT_connect(sched, cfg, 
2877                                               NULL, NULL, NULL, NULL, NULL);
2878   if (transport_handle != NULL)
2879     GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
2880   else
2881     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
2882
2883   lowest_bucket = MAX_BUCKETS - 1;
2884   forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
2885   forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
2886   all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
2887   GNUNET_assert(all_known_peers != NULL);
2888   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
2889     {
2890       debug_routes = GNUNET_YES;
2891     }
2892
2893   if (GNUNET_YES ==
2894       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
2895                                            "stop_on_closest"))
2896     {
2897       stop_on_closest = GNUNET_YES;
2898     }
2899
2900   if (GNUNET_YES ==
2901       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
2902                                            "stop_found"))
2903     {
2904       stop_on_found = GNUNET_YES;
2905     }
2906
2907   if (GNUNET_YES ==
2908       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
2909                                            "malicious_getter"))
2910     {
2911       malicious_getter = GNUNET_YES;
2912       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
2913                                             "MALICIOUS_GET_FREQUENCY",
2914                                             &malicious_get_frequency))
2915         malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
2916     }
2917
2918   if (GNUNET_YES ==
2919       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
2920                                            "malicious_putter"))
2921     {
2922       malicious_putter = GNUNET_YES;
2923       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
2924                                             "MALICIOUS_PUT_FREQUENCY",
2925                                             &malicious_put_frequency))
2926         malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
2927     }
2928
2929   if (GNUNET_YES ==
2930           GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
2931                                                "malicious_dropper"))
2932     {
2933       malicious_dropper = GNUNET_YES;
2934     }
2935
2936   if (GNUNET_YES ==
2937       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
2938                                            "mysql_logging_extended"))
2939     {
2940       debug_routes = GNUNET_YES;
2941       debug_routes_extended = GNUNET_YES;
2942     }
2943
2944   if (GNUNET_YES == debug_routes)
2945     {
2946       dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
2947       if (dhtlog_handle == NULL)
2948         {
2949           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2950                       "Could not connect to mysql logging server, logging will not happen!");
2951         }
2952     }
2953
2954   stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
2955
2956   if (stats != NULL)
2957     {
2958       GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
2959       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
2960       GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
2961       GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
2962       GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
2963       GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
2964       GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
2965       GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
2966       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
2967       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
2968       GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
2969       GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
2970       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
2971       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
2972       GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
2973       GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
2974     }
2975 #if DO_FIND_PEER
2976   random_seconds = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 180);
2977   GNUNET_SCHEDULER_add_delayed (sched,
2978                                 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, random_seconds),
2979                                 &send_find_peer_message, NULL);
2980 #endif
2981
2982   /* Scheduled the task to clean up when shutdown is called */
2983   cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
2984                                                GNUNET_TIME_UNIT_FOREVER_REL,
2985                                                &shutdown_task, NULL);
2986 }
2987
2988 /**
2989  * The main function for the dht service.
2990  *
2991  * @param argc number of arguments from the command line
2992  * @param argv command line arguments
2993  * @return 0 ok, 1 on error
2994  */
2995 int
2996 main (int argc, char *const *argv)
2997 {
2998   return (GNUNET_OK ==
2999           GNUNET_SERVICE_run (argc,
3000                               argv,
3001                               "dht",
3002                               GNUNET_SERVICE_OPTION_NONE,
3003                               &run, NULL)) ? 0 : 1;
3004 }