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