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