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