big scheduler refactoring, expect some issues
[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_block_lib.h"
30 #include "gnunet_client_lib.h"
31 #include "gnunet_getopt_lib.h"
32 #include "gnunet_os_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_service_lib.h"
35 #include "gnunet_core_service.h"
36 #include "gnunet_signal_lib.h"
37 #include "gnunet_util_lib.h"
38 #include "gnunet_datacache_lib.h"
39 #include "gnunet_transport_service.h"
40 #include "gnunet_hello_lib.h"
41 #include "gnunet_dht_service.h"
42 #include "gnunet_statistics_service.h"
43 #include "dhtlog.h"
44 #include "dht.h"
45 #include <fenv.h>
46
47 #define PRINT_TABLES GNUNET_NO
48
49 #define REAL_DISTANCE GNUNET_NO
50
51 #define EXTRA_CHECKS GNUNET_NO
52
53 /**
54  * How many buckets will we allow total.
55  */
56 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
57
58 /**
59  * Should the DHT issue FIND_PEER requests to get better routing tables?
60  */
61 #define DEFAULT_DO_FIND_PEER GNUNET_YES
62
63 /**
64  * Defines whether find peer requests send their HELLO's outgoing,
65  * or expect replies to contain hellos.
66  */
67 #define FIND_PEER_WITH_HELLO GNUNET_YES
68
69 /**
70  * What is the maximum number of peers in a given bucket.
71  */
72 #define DEFAULT_BUCKET_SIZE 4
73
74 /**
75  * Minimum number of peers we need for "good" routing,
76  * any less than this and we will allow messages to
77  * travel much further through the network!
78  */
79 #define MINIMUM_PEER_THRESHOLD 20
80
81 #define DHT_MAX_RECENT 1000
82
83 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
84
85 /**
86  * Default time to wait to send messages on behalf of other peers.
87  */
88 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
89
90 /**
91  * Default importance for handling messages on behalf of other peers.
92  */
93 #define DHT_DEFAULT_P2P_IMPORTANCE 0
94
95 /**
96  * How long to keep recent requests around by default.
97  */
98 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
99
100 /**
101  * Default time to wait to send find peer messages sent by the dht service.
102  */
103 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
104
105 /**
106  * Default importance for find peer messages sent by the dht service.
107  */
108 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
109
110 /**
111  * Default replication parameter for find peer messages sent by the dht service.
112  */
113 #define DHT_DEFAULT_PUT_REPLICATION 4
114
115 /**
116  * Default replication parameter for find peer messages sent by the dht service.
117  */
118 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
119
120 /**
121  * Default options for find peer requests sent by the dht service.
122  */
123 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
124 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
125
126 /**
127  * How long at least to wait before sending another find peer request.
128  */
129 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
130
131 /**
132  * How long at most to wait before sending another find peer request.
133  */
134 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
135
136 /**
137  * How often to update our preference levels for peers in our routing tables.
138  */
139 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
140
141 /**
142  * How long at most on average will we allow a reply forward to take
143  * (before we quit sending out new requests)
144  */
145 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
146
147 /**
148  * How many initial requests to send out (in true Kademlia fashion)
149  */
150 #define DHT_KADEMLIA_REPLICATION 3
151
152 /*
153  * Default frequency for sending malicious get messages
154  */
155 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
156
157 /*
158  * Default frequency for sending malicious put messages
159  */
160 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
161
162
163 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
164
165 /**
166  * Real maximum number of hops, at which point we refuse
167  * to forward the message.
168  */
169 #define DEFAULT_MAX_HOPS 10
170
171 /**
172  * How many time differences between requesting a core send and
173  * the actual callback to remember.
174  */
175 #define MAX_REPLY_TIMES 8
176
177 enum ConvergenceOptions
178 {
179    /**
180     * Use the linear method for convergence.
181     */
182    DHT_CONVERGE_LINEAR,
183
184    /**
185     * Converge using a fast converging square
186     * function.
187     */
188    DHT_CONVERGE_SQUARE,
189
190    /**
191     * Converge using a slower exponential
192     * function.
193     */
194    DHT_CONVERGE_EXPONENTIAL,
195
196    /**
197     * Don't do any special convergence, allow
198     * the algorithm to hopefully route to closer
199     * peers more often.
200     */
201    DHT_CONVERGE_RANDOM,
202
203    /**
204     * Binary convergence, start routing to closest
205     * only after set number of hops.
206     */
207    DHT_CONVERGE_BINARY
208 };
209
210 /**
211  * Linked list of messages to send to clients.
212  */
213 struct P2PPendingMessage
214 {
215   /**
216    * Pointer to next item in the list
217    */
218   struct P2PPendingMessage *next;
219
220   /**
221    * Pointer to previous item in the list
222    */
223   struct P2PPendingMessage *prev;
224
225   /**
226    * Message importance level.
227    */
228   unsigned int importance;
229
230   /**
231    * Time when this request was scheduled to be sent.
232    */
233   struct GNUNET_TIME_Absolute scheduled;
234
235   /**
236    * How long to wait before sending message.
237    */
238   struct GNUNET_TIME_Relative timeout;
239
240   /**
241    * Actual message to be sent; // avoid allocation
242    */
243   const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
244
245 };
246
247 /**
248  * Per-peer information.
249  */
250 struct PeerInfo
251 {
252   /**
253    * Next peer entry (DLL)
254    */
255   struct PeerInfo *next;
256
257   /**
258    *  Prev peer entry (DLL)
259    */
260   struct PeerInfo *prev;
261
262   /**
263    * Head of pending messages to be sent to this peer.
264    */
265   struct P2PPendingMessage *head;
266
267   /**
268    * Tail of pending messages to be sent to this peer.
269    */
270   struct P2PPendingMessage *tail;
271
272   /**
273    * Core handle for sending messages to this peer.
274    */
275   struct GNUNET_CORE_TransmitHandle *th;
276
277   /**
278    * Task for scheduling message sends.
279    */
280   GNUNET_SCHEDULER_TaskIdentifier send_task;
281
282   /**
283    * Task for scheduling preference updates
284    */
285   GNUNET_SCHEDULER_TaskIdentifier preference_task;
286
287   /**
288    * Preference update context
289    */
290   struct GNUNET_CORE_InformationRequestContext *info_ctx;
291
292   /**
293    * What is the average latency for replies received?
294    */
295   struct GNUNET_TIME_Relative latency;
296
297   /**
298    * What is the identity of the peer?
299    */
300   struct GNUNET_PeerIdentity id;
301
302   /**
303    * Transport level distance to peer.
304    */
305   unsigned int distance;
306
307   /**
308    * Holds matching bits from peer to current target,
309    * used for distance comparisons between peers. May
310    * be considered a really bad idea.
311    * FIXME: remove this value (create struct which holds
312    *        a single peerinfo and the matching bits, use
313    *        that to pass to comparitor)
314    */
315   unsigned int matching_bits;
316
317   /**
318    * Task for scheduling periodic ping messages for this peer.
319    */
320   GNUNET_SCHEDULER_TaskIdentifier ping_task;
321 };
322
323 /**
324  * Peers are grouped into buckets.
325  */
326 struct PeerBucket
327 {
328   /**
329    * Head of DLL
330    */
331   struct PeerInfo *head;
332
333   /**
334    * Tail of DLL
335    */
336   struct PeerInfo *tail;
337
338   /**
339    * Number of peers in the bucket.
340    */
341   unsigned int peers_size;
342 };
343
344 /**
345  * Linked list of messages to send to clients.
346  */
347 struct PendingMessage
348 {
349   /**
350    * Pointer to next item in the list
351    */
352   struct PendingMessage *next;
353
354   /**
355    * Pointer to previous item in the list
356    */
357   struct PendingMessage *prev;
358
359   /**
360    * Actual message to be sent; // avoid allocation
361    */
362   const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
363
364 };
365
366 /**
367  * Struct containing information about a client,
368  * handle to connect to it, and any pending messages
369  * that need to be sent to it.
370  */
371 struct ClientList
372 {
373   /**
374    * Linked list of active clients
375    */
376   struct ClientList *next;
377
378   /**
379    * The handle to this client
380    */
381   struct GNUNET_SERVER_Client *client_handle;
382
383   /**
384    * Handle to the current transmission request, NULL
385    * if none pending.
386    */
387   struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
388
389   /**
390    * Linked list of pending messages for this client
391    */
392   struct PendingMessage *pending_head;
393
394   /**
395    * Tail of linked list of pending messages for this client
396    */
397   struct PendingMessage *pending_tail;
398 };
399
400
401 /**
402  * Context containing information about a DHT message received.
403  */
404 struct DHT_MessageContext
405 {
406   /**
407    * The client this request was received from.
408    * (NULL if received from another peer)
409    */
410   struct ClientList *client;
411
412   /**
413    * The peer this request was received from.
414    * (NULL if received from local client)
415    */
416   const struct GNUNET_PeerIdentity *peer;
417
418   /**
419    * Bloomfilter for this routing request.
420    */
421   struct GNUNET_CONTAINER_BloomFilter *bloom;
422
423   /**
424    * extended query (see gnunet_block_lib.h).
425    */
426   const void *xquery;
427
428   /**
429    * Bloomfilter to filter out duplicate replies.
430    */
431   struct GNUNET_CONTAINER_BloomFilter *reply_bf;
432
433   /**
434    * The key this request was about
435    */
436   GNUNET_HashCode key;
437
438   /**
439    * How long should we wait to transmit this request?
440    */
441   struct GNUNET_TIME_Relative timeout;
442
443   /**
444    * The unique identifier of this request
445    */
446   uint64_t unique_id;
447
448   /**
449    * Number of bytes in xquery.
450    */
451   size_t xquery_size;
452
453   /**
454    * Mutator value for the reply_bf, see gnunet_block_lib.h
455    */
456   uint32_t reply_bf_mutator;
457
458   /**
459    * Desired replication level
460    */
461   uint32_t replication;
462
463   /**
464    * Network size estimate, either ours or the sum of
465    * those routed to thus far. =~ Log of number of peers
466    * chosen from for this request.
467    */
468   uint32_t network_size;
469
470   /**
471    * Any message options for this request
472    */
473   uint32_t msg_options;
474
475   /**
476    * How many hops has the message already traversed?
477    */
478   uint32_t hop_count;
479
480   /**
481    * How important is this message?
482    */
483   unsigned int importance;
484
485   /**
486    * Should we (still) forward the request on to other peers?
487    */
488   int do_forward;
489
490   /**
491    * Did we forward this message? (may need to remember it!)
492    */
493   int forwarded;
494
495   /**
496    * Are we the closest known peer to this key (out of our neighbors?)
497    */
498   int closest;
499 };
500
501 /**
502  * Record used for remembering what peers are waiting for what
503  * responses (based on search key).
504  */
505 struct DHTRouteSource
506 {
507   /**
508    * This is a DLL.
509    */
510   struct DHTRouteSource *next;
511
512   /**
513    * This is a DLL.
514    */
515   struct DHTRouteSource *prev;
516
517   /**
518    * Source of the request.  Replies should be forwarded to
519    * this peer.
520    */
521   struct GNUNET_PeerIdentity source;
522
523   /**
524    * If this was a local request, remember the client; otherwise NULL.
525    */
526   struct ClientList *client;
527
528   /**
529    * Pointer to this nodes heap location (for removal)
530    */
531   struct GNUNET_CONTAINER_HeapNode *hnode;
532
533   /**
534    * Back pointer to the record storing this information.
535    */
536   struct DHTQueryRecord *record;
537
538   /**
539    * Task to remove this entry on timeout.
540    */
541   GNUNET_SCHEDULER_TaskIdentifier delete_task;
542
543   /**
544    * Bloomfilter of peers we have already sent back as
545    * replies to the initial request.  Allows us to not
546    * forward the same peer multiple times for a find peer
547    * request.
548    */
549   struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
550
551 };
552
553 /**
554  * Entry in the DHT routing table.
555  */
556 struct DHTQueryRecord
557 {
558   /**
559    * Head of DLL for result forwarding.
560    */
561   struct DHTRouteSource *head;
562
563   /**
564    * Tail of DLL for result forwarding.
565    */
566   struct DHTRouteSource *tail;
567
568   /**
569    * Key that the record concerns.
570    */
571   GNUNET_HashCode key;
572
573   /**
574    * GET message of this record (what we already forwarded?).
575    */
576   //DV_DHT_MESSAGE get; Try to get away with not saving this.
577
578   /**
579    * Bloomfilter of the peers we've replied to so far
580    */
581   //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
582
583 };
584
585 /**
586  * Context used to calculate the number of find peer messages
587  * per X time units since our last scheduled find peer message
588  * was sent.  If we have seen too many messages, delay or don't
589  * send our own out.
590  */
591 struct FindPeerMessageContext
592 {
593   unsigned int count;
594
595   struct GNUNET_TIME_Absolute start;
596
597   struct GNUNET_TIME_Absolute end;
598 };
599
600 /**
601  * DHT Routing results structure
602  */
603 struct DHTResults
604 {
605   /*
606    * Min heap for removal upon reaching limit
607    */
608   struct GNUNET_CONTAINER_Heap *minHeap;
609
610   /*
611    * Hashmap for fast key based lookup
612    */
613   struct GNUNET_CONTAINER_MultiHashMap *hashmap;
614
615 };
616
617 /**
618  * DHT structure for recent requests.
619  */
620 struct RecentRequests
621 {
622   /*
623    * Min heap for removal upon reaching limit
624    */
625   struct GNUNET_CONTAINER_Heap *minHeap;
626
627   /*
628    * Hashmap for key based lookup
629    */
630   struct GNUNET_CONTAINER_MultiHashMap *hashmap;
631 };
632
633 struct RecentRequest
634 {
635   /**
636    * Position of this node in the min heap.
637    */
638   struct GNUNET_CONTAINER_HeapNode *heap_node;
639
640   /**
641    * Bloomfilter containing entries for peers
642    * we forwarded this request to.
643    */
644   struct GNUNET_CONTAINER_BloomFilter *bloom;
645
646   /**
647    * Timestamp of this request, for ordering
648    * the min heap.
649    */
650   struct GNUNET_TIME_Absolute timestamp;
651
652   /**
653    * Key of this request.
654    */
655   GNUNET_HashCode key;
656
657   /**
658    * Unique identifier for this request.
659    */
660   uint64_t uid;
661
662   /**
663    * Task to remove this entry on timeout.
664    */
665   GNUNET_SCHEDULER_TaskIdentifier remove_task;
666 };
667
668 struct RepublishContext
669 {
670   /**
671    * Key to republish.
672    */
673   GNUNET_HashCode key;
674
675   /**
676    * Type of the data.
677    */
678   unsigned int type;
679
680 };
681
682 /**
683  * Which kind of convergence will we be using?
684  */
685 static enum ConvergenceOptions converge_option;
686
687 /**
688  * Modifier for the convergence function
689  */
690 static float converge_modifier;
691
692 /**
693  * Recent requests by hash/uid and by time inserted.
694  */
695 static struct RecentRequests recent;
696
697 /**
698  * Context to use to calculate find peer rates.
699  */
700 static struct FindPeerMessageContext find_peer_context;
701
702 /**
703  * Don't use our routing algorithm, always route
704  * to closest peer; initially send requests to 3
705  * peers.
706  */
707 static unsigned int strict_kademlia;
708
709 /**
710  * Routing option to end routing when closest peer found.
711  */
712 static unsigned int stop_on_closest;
713
714 /**
715  * Routing option to end routing when data is found.
716  */
717 static unsigned int stop_on_found;
718
719 /**
720  * Whether DHT needs to manage find peer requests, or
721  * an external force will do it on behalf of the DHT.
722  */
723 static unsigned int do_find_peer;
724
725 /**
726  * Once we have stored an item in the DHT, refresh it
727  * according to our republish interval.
728  */
729 static unsigned int do_republish;
730
731 /**
732  * Use the "real" distance metric when selecting the
733  * next routing hop.  Can be less accurate.
734  */
735 static unsigned int use_real_distance;
736
737 /**
738  * How many peers have we added since we sent out our last
739  * find peer request?
740  */
741 static unsigned int newly_found_peers;
742
743 /**
744  * Container of active queries we should remember
745  */
746 static struct DHTResults forward_list;
747
748 /**
749  * Handle to the datacache service (for inserting/retrieving data)
750  */
751 static struct GNUNET_DATACACHE_Handle *datacache;
752
753 /**
754  * Handle for the statistics service.
755  */
756 struct GNUNET_STATISTICS_Handle *stats;
757
758
759 /**
760  * The configuration the DHT service is running with
761  */
762 static const struct GNUNET_CONFIGURATION_Handle *cfg;
763
764 /**
765  * Handle to the core service
766  */
767 static struct GNUNET_CORE_Handle *coreAPI;
768
769 /**
770  * Handle to the transport service, for getting our hello
771  */
772 static struct GNUNET_TRANSPORT_Handle *transport_handle;
773
774 /**
775  * The identity of our peer.
776  */
777 static struct GNUNET_PeerIdentity my_identity;
778
779 /**
780  * Short id of the peer, for printing
781  */
782 static char *my_short_id;
783
784 /**
785  * Our HELLO
786  */
787 static struct GNUNET_MessageHeader *my_hello;
788
789 /**
790  * Task to run when we shut down, cleaning up all our trash
791  */
792 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
793
794 /**
795  * The lowest currently used bucket.
796  */
797 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
798
799 /**
800  * The maximum number of hops before we stop routing messages.
801  */
802 static unsigned long long max_hops;
803
804 /**
805  * How often to republish content we have previously stored.
806  */
807 static struct GNUNET_TIME_Relative dht_republish_frequency;
808
809 /**
810  * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
811  */
812 static int use_max_hops;
813
814 /**
815  * The buckets (Kademlia routing table, complete with growth).
816  * Array of size MAX_BUCKET_SIZE.
817  */
818 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
819
820 /**
821  * Hash map of all known peers, for easy removal from k_buckets on disconnect.
822  */
823 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
824
825 /**
826  * Recently seen find peer requests.
827  */
828 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
829
830 /**
831  * Maximum size for each bucket.
832  */
833 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
834
835 /**
836  * List of active clients.
837  */
838 static struct ClientList *client_list;
839
840 /**
841  * Handle to the DHT logger.
842  */
843 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
844
845 /*
846  * Whether or not to send routing debugging information
847  * to the dht logging server
848  */
849 static unsigned int debug_routes;
850
851 /*
852  * Whether or not to send FULL route information to
853  * logging server
854  */
855 static unsigned int debug_routes_extended;
856
857 /*
858  * GNUNET_YES or GNUNET_NO, whether or not to act as
859  * a malicious node which drops all messages
860  */
861 static unsigned int malicious_dropper;
862
863 /*
864  * GNUNET_YES or GNUNET_NO, whether or not to act as
865  * a malicious node which sends out lots of GETS
866  */
867 static unsigned int malicious_getter;
868
869 /**
870  * GNUNET_YES or GNUNET_NO, whether or not to act as
871  * a malicious node which sends out lots of PUTS
872  */
873 static unsigned int malicious_putter;
874
875 /**
876  * Frequency for malicious get requests.
877  */
878 static unsigned long long malicious_get_frequency;
879
880 /**
881  * Frequency for malicious put requests.
882  */
883 static unsigned long long malicious_put_frequency;
884
885 /**
886  * Reply times for requests, if we are busy, don't send any
887  * more requests!
888  */
889 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
890
891 /**
892  * Current counter for replies.
893  */
894 static unsigned int reply_counter;
895
896 /**
897  * Our handle to the BLOCK library.
898  */
899 static struct GNUNET_BLOCK_Context *block_context;
900
901
902 /**
903  * Forward declaration.
904  */
905 static size_t 
906 send_generic_reply (void *cls, size_t size, void *buf);
907
908
909 /** Declare here so retry_core_send is aware of it */
910 static size_t 
911 core_transmit_notify (void *cls,
912                       size_t size, void *buf);
913
914 /**
915  * Convert unique ID to hash code.
916  *
917  * @param uid unique ID to convert
918  * @param hash set to uid (extended with zeros)
919  */
920 static void
921 hash_from_uid (uint64_t uid,
922                GNUNET_HashCode *hash)
923 {
924   memset (hash, 0, sizeof(GNUNET_HashCode));
925   *((uint64_t*)hash) = uid;
926 }
927
928 #if AVG
929 /**
930  * Calculate the average send time between messages so that we can
931  * ignore certain requests if we get too busy.
932  *
933  * @return the average time between asking core to send a message
934  *         and when the buffer for copying it is passed
935  */
936 static struct GNUNET_TIME_Relative get_average_send_delay()
937 {
938   unsigned int i;
939   unsigned int divisor;
940   struct GNUNET_TIME_Relative average_time;
941   average_time = GNUNET_TIME_relative_get_zero();
942   divisor = 0;
943   for (i = 0; i < MAX_REPLY_TIMES; i++)
944   {
945     average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
946     if (reply_times[i].abs_value == (uint64_t)0)
947       continue;
948     else
949       divisor++;
950   }
951   if (divisor == 0)
952   {
953     return average_time;
954   }
955
956   average_time = GNUNET_TIME_relative_divide(average_time, divisor);
957   fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.abs_value);
958   return average_time;
959 }
960 #endif
961
962 /**
963  * Given the largest send delay, artificially decrease it
964  * so the next time around we may have a chance at sending
965  * again.
966  */
967 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
968 {
969   unsigned int i;
970   for (i = 0; i < MAX_REPLY_TIMES; i++)
971     {
972       if (reply_times[i].rel_value == max_time.rel_value)
973         {
974           reply_times[i].rel_value = reply_times[i].rel_value / 2;
975           return;
976         }
977     }
978 }
979
980 /**
981  * Find the maximum send time of the recently sent values.
982  *
983  * @return the average time between asking core to send a message
984  *         and when the buffer for copying it is passed
985  */
986 static struct GNUNET_TIME_Relative get_max_send_delay()
987 {
988   unsigned int i;
989   struct GNUNET_TIME_Relative max_time;
990   max_time = GNUNET_TIME_relative_get_zero();
991
992   for (i = 0; i < MAX_REPLY_TIMES; i++)
993   {
994     if (reply_times[i].rel_value > max_time.rel_value)
995       max_time.rel_value = reply_times[i].rel_value;
996   }
997
998   if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
999     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.rel_value);
1000   return max_time;
1001 }
1002
1003 static void
1004 increment_stats(const char *value)
1005 {
1006   if (stats != NULL)
1007     {
1008       GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
1009     }
1010 }
1011
1012 /**
1013  *  Try to send another message from our core send list
1014  */
1015 static void
1016 try_core_send (void *cls,
1017                const struct GNUNET_SCHEDULER_TaskContext *tc)
1018 {
1019   struct PeerInfo *peer = cls;
1020   struct P2PPendingMessage *pending;
1021   size_t ssize;
1022
1023   peer->send_task = GNUNET_SCHEDULER_NO_TASK;
1024
1025   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1026     return;
1027
1028   if (peer->th != NULL)
1029     return; /* Message send already in progress */
1030
1031   pending = peer->head;
1032   if (pending != NULL)
1033     {
1034       ssize = ntohs(pending->msg->size);
1035 #if DEBUG_DHT > 1
1036      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1037                 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
1038                 "DHT", ssize, GNUNET_i2s(&peer->id));
1039 #endif
1040       pending->scheduled = GNUNET_TIME_absolute_get();
1041       reply_counter++;
1042       if (reply_counter >= MAX_REPLY_TIMES)
1043         reply_counter = 0;
1044       peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
1045                                                    pending->timeout, &peer->id,
1046                                                    ssize, &core_transmit_notify, peer);
1047     }
1048 }
1049
1050 /**
1051  * Function called to send a request out to another peer.
1052  * Called both for locally initiated requests and those
1053  * received from other peers.
1054  *
1055  * @param msg the encapsulated message
1056  * @param peer the peer to forward the message to
1057  * @param msg_ctx the context of the message (hop count, bloom, etc.)
1058  */
1059 static void 
1060 forward_result_message (const struct GNUNET_MessageHeader *msg,
1061                         struct PeerInfo *peer,
1062                         struct DHT_MessageContext *msg_ctx)
1063 {
1064   struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1065   struct P2PPendingMessage *pending;
1066   size_t msize;
1067   size_t psize;
1068
1069   increment_stats(STAT_RESULT_FORWARDS);
1070   msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1071   GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1072   psize = sizeof(struct P2PPendingMessage) + msize;
1073   pending = GNUNET_malloc(psize);
1074   pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1075   pending->importance = DHT_SEND_PRIORITY;
1076   pending->timeout = GNUNET_TIME_relative_get_forever();
1077   result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1078   result_message->header.size = htons(msize);
1079   result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1080   result_message->put_path_length = htons(0); /* FIXME: implement */
1081   result_message->get_path_length = htons(0); /* FIXME: implement */
1082   result_message->options = htonl(msg_ctx->msg_options);
1083   result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1084   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1085   result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1086   memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1087   memcpy(&result_message[1], msg, ntohs(msg->size));
1088 #if DEBUG_DHT > 1
1089   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));
1090 #endif
1091   GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1092   if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1093     peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1094 }
1095
1096
1097 /**
1098  * Called when core is ready to send a message we asked for
1099  * out to the destination.
1100  *
1101  * @param cls closure (NULL)
1102  * @param size number of bytes available in buf
1103  * @param buf where the callee should write the message
1104  * @return number of bytes written to buf
1105  */
1106 static size_t 
1107 core_transmit_notify (void *cls,
1108                       size_t size, void *buf)
1109 {
1110   struct PeerInfo *peer = cls;
1111   char *cbuf = buf;
1112   struct P2PPendingMessage *pending;
1113
1114   size_t off;
1115   size_t msize;
1116
1117   if (buf == NULL)
1118     {
1119       /* client disconnected */
1120 #if DEBUG_DHT
1121       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1122 #endif
1123       return 0;
1124     }
1125
1126   if (peer->head == NULL)
1127     return 0;
1128
1129   peer->th = NULL;
1130   off = 0;
1131   pending = peer->head;
1132   reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1133   msize = ntohs(pending->msg->size);
1134   if (msize <= size)
1135     {
1136       off = msize;
1137       memcpy (cbuf, pending->msg, msize);
1138       GNUNET_CONTAINER_DLL_remove (peer->head,
1139                                    peer->tail,
1140                                    pending);
1141 #if DEBUG_DHT > 1
1142       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));
1143 #endif
1144       GNUNET_free (pending);
1145     }
1146 #if SMART
1147   while (NULL != pending &&
1148           (size - off >= (msize = ntohs (pending->msg->size))))
1149     {
1150 #if DEBUG_DHT_ROUTING
1151       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);
1152 #endif
1153       memcpy (&cbuf[off], pending->msg, msize);
1154       off += msize;
1155       GNUNET_CONTAINER_DLL_remove (peer->head,
1156                                    peer->tail,
1157                                    pending);
1158       GNUNET_free (pending);
1159       pending = peer->head;
1160     }
1161 #endif
1162   if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1163     peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1164 #if DEBUG_DHT > 1
1165   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);
1166 #endif
1167   return off;
1168 }
1169
1170
1171 /**
1172  * Compute the distance between have and target as a 32-bit value.
1173  * Differences in the lower bits must count stronger than differences
1174  * in the higher bits.
1175  *
1176  * @return 0 if have==target, otherwise a number
1177  *           that is larger as the distance between
1178  *           the two hash codes increases
1179  */
1180 static unsigned int
1181 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1182 {
1183   unsigned int bucket;
1184   unsigned int msb;
1185   unsigned int lsb;
1186   unsigned int i;
1187
1188   /* We have to represent the distance between two 2^9 (=512)-bit
1189      numbers as a 2^5 (=32)-bit number with "0" being used for the
1190      two numbers being identical; furthermore, we need to
1191      guarantee that a difference in the number of matching
1192      bits is always represented in the result.
1193
1194      We use 2^32/2^9 numerical values to distinguish between
1195      hash codes that have the same LSB bit distance and
1196      use the highest 2^9 bits of the result to signify the
1197      number of (mis)matching LSB bits; if we have 0 matching
1198      and hence 512 mismatching LSB bits we return -1 (since
1199      512 itself cannot be represented with 9 bits) */
1200
1201   /* first, calculate the most significant 9 bits of our
1202      result, aka the number of LSBs */
1203   bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1204   /* bucket is now a value between 0 and 512 */
1205   if (bucket == 512)
1206     return 0;                   /* perfect match */
1207   if (bucket == 0)
1208     return (unsigned int) -1;   /* LSB differs; use max (if we did the bit-shifting
1209                                    below, we'd end up with max+1 (overflow)) */
1210
1211   /* calculate the most significant bits of the final result */
1212   msb = (512 - bucket) << (32 - 9);
1213   /* calculate the 32-9 least significant bits of the final result by
1214      looking at the differences in the 32-9 bits following the
1215      mismatching bit at 'bucket' */
1216   lsb = 0;
1217   for (i = bucket + 1;
1218        (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1219     {
1220       if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1221         lsb |= (1 << (bucket + 32 - 9 - i));    /* first bit set will be 10,
1222                                                    last bit set will be 31 -- if
1223                                                    i does not reach 512 first... */
1224     }
1225   return msb | lsb;
1226 }
1227
1228 /**
1229  * Return a number that is larger the closer the
1230  * "have" GNUNET_hash code is to the "target".
1231  *
1232  * @return inverse distance metric, non-zero.
1233  *         Must fudge the value if NO bits match.
1234  */
1235 static unsigned int
1236 inverse_distance (const GNUNET_HashCode * target,
1237                   const GNUNET_HashCode * have)
1238 {
1239   if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1240     return 1; /* Never return 0! */
1241   return ((unsigned int) -1) - distance (target, have);
1242 }
1243
1244 /**
1245  * Find the optimal bucket for this key, regardless
1246  * of the current number of buckets in use.
1247  *
1248  * @param hc the hashcode to compare our identity to
1249  *
1250  * @return the proper bucket index, or GNUNET_SYSERR
1251  *         on error (same hashcode)
1252  */
1253 static int find_bucket(const GNUNET_HashCode *hc)
1254 {
1255   unsigned int bits;
1256
1257   bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1258   if (bits == MAX_BUCKETS)
1259     return GNUNET_SYSERR;
1260   return MAX_BUCKETS - bits - 1;
1261 }
1262
1263 /**
1264  * Find which k-bucket this peer should go into,
1265  * taking into account the size of the k-bucket
1266  * array.  This means that if more bits match than
1267  * there are currently buckets, lowest_bucket will
1268  * be returned.
1269  *
1270  * @param hc GNUNET_HashCode we are finding the bucket for.
1271  *
1272  * @return the proper bucket index for this key,
1273  *         or GNUNET_SYSERR on error (same hashcode)
1274  */
1275 static int find_current_bucket(const GNUNET_HashCode *hc)
1276 {
1277   int actual_bucket;
1278   actual_bucket = find_bucket(hc);
1279
1280   if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1281     return lowest_bucket;
1282   else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1283     return lowest_bucket;
1284   else
1285     return actual_bucket;
1286 }
1287
1288 #if EXTRA_CHECKS
1289 /**
1290  * Find a routing table entry from a peer identity
1291  *
1292  * @param peer the peer to look up
1293  *
1294  * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1295  */
1296 static int
1297 find_bucket_by_peer(const struct PeerInfo *peer)
1298 {
1299   int bucket;
1300   struct PeerInfo *pos;
1301
1302   for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1303     {
1304       pos = k_buckets[bucket].head;
1305       while (pos != NULL)
1306         {
1307           if (peer == pos)
1308             return bucket;
1309           pos = pos->next;
1310         }
1311     }
1312
1313   return GNUNET_SYSERR; /* No such peer. */
1314 }
1315 #endif
1316
1317 #if PRINT_TABLES
1318 /**
1319  * Print the complete routing table for this peer.
1320  */
1321 static void
1322 print_routing_table ()
1323 {
1324   int bucket;
1325   struct PeerInfo *pos;
1326   char char_buf[30000];
1327   int char_pos;
1328   memset(char_buf, 0, sizeof(char_buf));
1329   char_pos = 0;
1330   char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1331   //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1332   for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1333     {
1334       pos = k_buckets[bucket].head;
1335       char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1336       //fprintf(stderr, "Bucket %d:\n", bucket);
1337       while (pos != NULL)
1338         {
1339           //fprintf(stderr, "\tPeer %s, best bucket %d, %d bits match\n", GNUNET_i2s(&pos->id), find_bucket(&pos->id.hashPubKey), GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey));
1340           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), GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey));
1341           pos = pos->next;
1342         }
1343     }
1344   fprintf(stderr, "%s", char_buf);
1345   fflush(stderr);
1346 }
1347 #endif
1348
1349 /**
1350  * Find a routing table entry from a peer identity
1351  *
1352  * @param peer the peer identity to look up
1353  *
1354  * @return the routing table entry, or NULL if not found
1355  */
1356 static struct PeerInfo *
1357 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1358 {
1359   int bucket;
1360   struct PeerInfo *pos;
1361   bucket = find_current_bucket(&peer->hashPubKey);
1362
1363   if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1364     return NULL;
1365
1366   pos = k_buckets[bucket].head;
1367   while (pos != NULL)
1368     {
1369       if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1370         return pos;
1371       pos = pos->next;
1372     }
1373   return NULL; /* No such peer. */
1374 }
1375
1376 /* Forward declaration */
1377 static void
1378 update_core_preference (void *cls,
1379                         const struct GNUNET_SCHEDULER_TaskContext *tc);
1380 /**
1381  * Function called with statistics about the given peer.
1382  *
1383  * @param cls closure
1384  * @param peer identifies the peer
1385  * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1386  * @param bpm_out set to the current bandwidth limit (sending) for this peer
1387  * @param amount set to the amount that was actually reserved or unreserved;
1388  *               either the full requested amount or zero (no partial reservations)
1389  * @param preference current traffic preference for the given peer
1390  */
1391 static void
1392 update_core_preference_finish (void *cls,
1393                                const struct GNUNET_PeerIdentity * peer,
1394                                struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1395                                struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1396                                int amount, uint64_t preference)
1397 {
1398   struct PeerInfo *peer_info = cls;
1399   peer_info->info_ctx = NULL;
1400   GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1401 }
1402
1403 static void
1404 update_core_preference (void *cls,
1405                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1406 {
1407   struct PeerInfo *peer = cls;
1408   uint64_t preference;
1409   unsigned int matching;
1410   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1411     {
1412       return;
1413     }
1414   matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1415   if (matching >= 64)
1416     {
1417       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1418       matching = 63;
1419     }
1420   preference = 1LL << matching;
1421   peer->info_ctx = GNUNET_CORE_peer_change_preference (cfg,
1422                                                        &peer->id,
1423                                                        GNUNET_TIME_relative_get_forever(),
1424                                                        GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1425                                                        0,
1426                                                        preference,
1427                                                        &update_core_preference_finish,
1428                                                        peer);
1429 }
1430
1431 /**
1432  * Really add a peer to a bucket (only do assertions
1433  * on size, etc.)
1434  *
1435  * @param peer GNUNET_PeerIdentity of the peer to add
1436  * @param bucket the already figured out bucket to add
1437  *        the peer to
1438  * @param latency the core reported latency of this peer
1439  * @param distance the transport level distance to this peer
1440  *
1441  * @return the newly added PeerInfo
1442  */
1443 static struct PeerInfo *
1444 add_peer(const struct GNUNET_PeerIdentity *peer,
1445          unsigned int bucket,
1446          struct GNUNET_TIME_Relative latency,
1447          unsigned int distance)
1448 {
1449   struct PeerInfo *new_peer;
1450   GNUNET_assert(bucket < MAX_BUCKETS);
1451   GNUNET_assert(peer != NULL);
1452   new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1453   new_peer->latency = latency;
1454   new_peer->distance = distance;
1455
1456   memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1457
1458   GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1459                                     k_buckets[bucket].tail,
1460                                     k_buckets[bucket].tail,
1461                                     new_peer);
1462   k_buckets[bucket].peers_size++;
1463
1464   if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1465     {
1466 #if DO_UPDATE_PREFERENCE
1467       new_peer->preference_task = GNUNET_SCHEDULER_add_now(&update_core_preference, new_peer);
1468 #endif
1469     }
1470
1471   return new_peer;
1472 }
1473
1474 /**
1475  * Given a peer and its corresponding bucket,
1476  * remove it from that bucket.  Does not free
1477  * the PeerInfo struct, nor cancel messages
1478  * or free messages waiting to be sent to this
1479  * peer!
1480  *
1481  * @param peer the peer to remove
1482  * @param bucket the bucket the peer belongs to
1483  */
1484 static void remove_peer (struct PeerInfo *peer,
1485                          unsigned int bucket)
1486 {
1487   GNUNET_assert(k_buckets[bucket].peers_size > 0);
1488   GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1489                               k_buckets[bucket].tail,
1490                               peer);
1491   k_buckets[bucket].peers_size--;
1492 #if CHANGE_LOWEST
1493   if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1494     lowest_bucket++;
1495 #endif
1496 }
1497
1498 /**
1499  * Removes peer from a bucket, then frees associated
1500  * resources and frees peer.
1501  *
1502  * @param peer peer to be removed and freed
1503  * @param bucket which bucket this peer belongs to
1504  */
1505 static void delete_peer (struct PeerInfo *peer,
1506                          unsigned int bucket)
1507 {
1508   struct P2PPendingMessage *pos;
1509   struct P2PPendingMessage *next;
1510 #if EXTRA_CHECKS
1511   struct PeerInfo *peer_pos;
1512
1513   peer_pos = k_buckets[bucket].head;
1514   while ((peer_pos != NULL) && (peer_pos != peer))
1515     peer_pos = peer_pos->next;
1516   if (peer_pos == NULL)
1517     {
1518       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1519       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));
1520     }
1521   GNUNET_assert(peer_pos != NULL);
1522 #endif
1523   remove_peer(peer, bucket); /* First remove the peer from its bucket */
1524
1525   if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1526     GNUNET_SCHEDULER_cancel(peer->send_task);
1527   if (peer->th != NULL)
1528     GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1529
1530   pos = peer->head;
1531   while (pos != NULL) /* Remove any pending messages for this peer */
1532     {
1533       next = pos->next;
1534       GNUNET_free(pos);
1535       pos = next;
1536     }
1537
1538   GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1539   GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1540   GNUNET_free(peer);
1541 }
1542
1543
1544 /**
1545  * Iterator over hash map entries.
1546  *
1547  * @param cls closure
1548  * @param key current key code
1549  * @param value PeerInfo of the peer to move to new lowest bucket
1550  * @return GNUNET_YES if we should continue to
1551  *         iterate,
1552  *         GNUNET_NO if not.
1553  */
1554 static int move_lowest_bucket (void *cls,
1555                                const GNUNET_HashCode * key,
1556                                void *value)
1557 {
1558   struct PeerInfo *peer = value;
1559   int new_bucket;
1560
1561   GNUNET_assert(lowest_bucket > 0);
1562   new_bucket = lowest_bucket - 1;
1563   remove_peer(peer, lowest_bucket);
1564   GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1565                                     k_buckets[new_bucket].tail,
1566                                     k_buckets[new_bucket].tail,
1567                                     peer);
1568   k_buckets[new_bucket].peers_size++;
1569   return GNUNET_YES;
1570 }
1571
1572
1573 /**
1574  * The current lowest bucket is full, so change the lowest
1575  * bucket to the next lower down, and move any appropriate
1576  * entries in the current lowest bucket to the new bucket.
1577  */
1578 static void enable_next_bucket()
1579 {
1580   struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1581   struct PeerInfo *pos;
1582   GNUNET_assert(lowest_bucket > 0);
1583   to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1584   pos = k_buckets[lowest_bucket].head;
1585
1586 #if PRINT_TABLES
1587   fprintf(stderr, "Printing RT before new bucket\n");
1588   print_routing_table();
1589 #endif
1590   /* Populate the array of peers which should be in the next lowest bucket */
1591   while (pos != NULL)
1592     {
1593       if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1594         GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1595       pos = pos->next;
1596     }
1597
1598   /* Remove peers from lowest bucket, insert into next lowest bucket */
1599   GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1600   GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1601   lowest_bucket = lowest_bucket - 1;
1602 #if PRINT_TABLES
1603   fprintf(stderr, "Printing RT after new bucket\n");
1604   print_routing_table();
1605 #endif
1606 }
1607
1608 /**
1609  * Find the closest peer in our routing table to the
1610  * given hashcode.
1611  *
1612  * @return The closest peer in our routing table to the
1613  *         key, or NULL on error.
1614  */
1615 static struct PeerInfo *
1616 find_closest_peer (const GNUNET_HashCode *hc)
1617 {
1618   struct PeerInfo *pos;
1619   struct PeerInfo *current_closest;
1620   unsigned int lowest_distance;
1621   unsigned int temp_distance;
1622   int bucket;
1623   int count;
1624
1625   lowest_distance = -1;
1626
1627   if (k_buckets[lowest_bucket].peers_size == 0)
1628     return NULL;
1629
1630   current_closest = NULL;
1631   for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1632     {
1633       pos = k_buckets[bucket].head;
1634       count = 0;
1635       while ((pos != NULL) && (count < bucket_size))
1636         {
1637           temp_distance = distance(&pos->id.hashPubKey, hc);
1638           if (temp_distance <= lowest_distance)
1639             {
1640               lowest_distance = temp_distance;
1641               current_closest = pos;
1642             }
1643           pos = pos->next;
1644           count++;
1645         }
1646     }
1647   GNUNET_assert(current_closest != NULL);
1648   return current_closest;
1649 }
1650
1651
1652 /**
1653  * Function called to send a request out to another peer.
1654  * Called both for locally initiated requests and those
1655  * received from other peers.
1656  *
1657  * @param msg the encapsulated message
1658  * @param peer the peer to forward the message to
1659  * @param msg_ctx the context of the message (hop count, bloom, etc.)
1660  */
1661 static void forward_message (const struct GNUNET_MessageHeader *msg,
1662                              struct PeerInfo *peer,
1663                              struct DHT_MessageContext *msg_ctx)
1664 {
1665   struct GNUNET_DHT_P2PRouteMessage *route_message;
1666   struct P2PPendingMessage *pending;
1667   size_t msize;
1668   size_t psize;
1669
1670   increment_stats(STAT_ROUTE_FORWARDS);
1671
1672   if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1673     increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1674
1675   msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1676   GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1677   psize = sizeof(struct P2PPendingMessage) + msize;
1678   pending = GNUNET_malloc(psize);
1679   pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1680   pending->importance = msg_ctx->importance;
1681   pending->timeout = msg_ctx->timeout;
1682   route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1683   route_message->header.size = htons(msize);
1684   route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1685   route_message->options = htonl(msg_ctx->msg_options);
1686   route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1687   route_message->network_size = htonl(msg_ctx->network_size);
1688   route_message->desired_replication_level = htonl(msg_ctx->replication);
1689   route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1690   if (msg_ctx->bloom != NULL)
1691     GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1692   memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1693   memcpy(&route_message[1], msg, ntohs(msg->size));
1694 #if DEBUG_DHT > 1
1695   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));
1696 #endif
1697   GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1698   if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1699     peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1700 }
1701
1702 #if DO_PING
1703 /**
1704  * Task used to send ping messages to peers so that
1705  * they don't get disconnected.
1706  *
1707  * @param cls the peer to send a ping message to
1708  * @param tc context, reason, etc.
1709  */
1710 static void
1711 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1712 {
1713   struct PeerInfo *peer = cls;
1714   struct GNUNET_MessageHeader ping_message;
1715   struct DHT_MessageContext message_context;
1716
1717   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1718     return;
1719
1720   ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1721   ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1722
1723   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1724 #if DEBUG_PING
1725   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1726 #endif
1727   forward_message(&ping_message, peer, &message_context);
1728   peer->ping_task = GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1729 }
1730
1731 /**
1732  * Schedule PING messages for the top X peers in each
1733  * bucket of the routing table (so core won't disconnect them!)
1734  */
1735 void schedule_ping_messages()
1736 {
1737   unsigned int bucket;
1738   unsigned int count;
1739   struct PeerInfo *pos;
1740   for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1741     {
1742       pos = k_buckets[bucket].head;
1743       count = 0;
1744       while (pos != NULL)
1745         {
1746           if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1747             GNUNET_SCHEDULER_add_now(&periodic_ping_task, pos);
1748           else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1749             {
1750               GNUNET_SCHEDULER_cancel(pos->ping_task);
1751               pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1752             }
1753           pos = pos->next;
1754           count++;
1755         }
1756     }
1757 }
1758 #endif
1759
1760 /**
1761  * Attempt to add a peer to our k-buckets.
1762  *
1763  * @param peer the peer identity of the peer being added
1764  * @param bucket the bucket that we want this peer to go in
1765  * @param latency transport latency of this peer
1766  * @param distance transport distance to this peer
1767  *
1768  * @return NULL if the peer was not added,
1769  *         pointer to PeerInfo for new peer otherwise
1770  */
1771 static struct PeerInfo *
1772 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1773              unsigned int bucket,
1774              struct GNUNET_TIME_Relative latency,
1775              unsigned int distance)
1776 {
1777   int peer_bucket;
1778   struct PeerInfo *new_peer;
1779
1780   if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1781     return NULL;
1782
1783   peer_bucket = find_current_bucket(&peer->hashPubKey);
1784
1785   GNUNET_assert(peer_bucket >= lowest_bucket);
1786   new_peer = add_peer(peer, peer_bucket, latency, distance);
1787
1788   if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1789     enable_next_bucket();
1790 #if DO_PING
1791   schedule_ping_messages();
1792 #endif
1793   return new_peer;
1794 }
1795
1796
1797 /**
1798  * Task run to check for messages that need to be sent to a client.
1799  *
1800  * @param client a ClientList, containing the client and any messages to be sent to it
1801  */
1802 static void
1803 process_pending_messages (struct ClientList *client)
1804
1805   if (client->pending_head == NULL) 
1806     return;    
1807   if (client->transmit_handle != NULL) 
1808     return;
1809
1810   client->transmit_handle =
1811     GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1812                                          ntohs (client->pending_head->msg->
1813                                                 size),
1814                                          GNUNET_TIME_UNIT_FOREVER_REL,
1815                                          &send_generic_reply, client);
1816 }
1817
1818 /**
1819  * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1820  * request.  A ClientList is passed as closure, take the head of the list
1821  * and copy it into buf, which has the result of sending the message to the
1822  * client.
1823  *
1824  * @param cls closure to this call
1825  * @param size maximum number of bytes available to send
1826  * @param buf where to copy the actual message to
1827  *
1828  * @return the number of bytes actually copied, 0 indicates failure
1829  */
1830 static size_t
1831 send_generic_reply (void *cls, size_t size, void *buf)
1832 {
1833   struct ClientList *client = cls;
1834   char *cbuf = buf;
1835   struct PendingMessage *reply;
1836   size_t off;
1837   size_t msize;
1838
1839   client->transmit_handle = NULL;
1840   if (buf == NULL)             
1841     {
1842       /* client disconnected */
1843       return 0;
1844     }
1845   off = 0;
1846   while ( (NULL != (reply = client->pending_head)) &&
1847           (size >= off + (msize = ntohs (reply->msg->size))))
1848     {
1849       GNUNET_CONTAINER_DLL_remove (client->pending_head,
1850                                    client->pending_tail,
1851                                    reply);
1852       memcpy (&cbuf[off], reply->msg, msize);
1853       GNUNET_free (reply);
1854       off += msize;
1855     }
1856   process_pending_messages (client);
1857 #if DEBUG_DHT
1858   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1859               "Transmitted %u bytes of replies to client\n",
1860               (unsigned int) off);
1861 #endif
1862   return off;
1863 }
1864
1865
1866 /**
1867  * Add a PendingMessage to the clients list of messages to be sent
1868  *
1869  * @param client the active client to send the message to
1870  * @param pending_message the actual message to send
1871  */
1872 static void
1873 add_pending_message (struct ClientList *client,
1874                      struct PendingMessage *pending_message)
1875 {
1876   GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1877                                      client->pending_tail,
1878                                      client->pending_tail,
1879                                      pending_message);
1880   process_pending_messages (client);
1881 }
1882
1883
1884 /**
1885  * Called when a reply needs to be sent to a client, as
1886  * a result it found to a GET or FIND PEER request.
1887  *
1888  * @param client the client to send the reply to
1889  * @param message the encapsulated message to send
1890  * @param uid the unique identifier of this request
1891  */
1892 static void
1893 send_reply_to_client (struct ClientList *client,
1894                       const struct GNUNET_MessageHeader *message,
1895                       unsigned long long uid,
1896                       const GNUNET_HashCode *key)
1897 {
1898   struct GNUNET_DHT_RouteResultMessage *reply;
1899   struct PendingMessage *pending_message;
1900   uint16_t msize;
1901   size_t tsize;
1902 #if DEBUG_DHT
1903   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1904               "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1905 #endif
1906   msize = ntohs (message->size);
1907   tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1908   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1909     {
1910       GNUNET_break_op (0);
1911       return;
1912     }
1913   pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1914   pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1915   reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1916   reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1917   reply->header.size = htons (tsize);
1918   reply->put_path_length = htons(0); /* FIXME: implement */
1919   reply->get_path_length = htons(0); /* FIXME: implement */
1920   reply->unique_id = GNUNET_htonll (uid);
1921   reply->key = *key;
1922   memcpy (&reply[1], message, msize);
1923   add_pending_message (client, pending_message);
1924 }
1925
1926 /**
1927  * Consider whether or not we would like to have this peer added to
1928  * our routing table.  Check whether bucket for this peer is full,
1929  * if so return negative; if not return positive.  Since peers are
1930  * only added on CORE level connect, this doesn't actually add the
1931  * peer to the routing table.
1932  *
1933  * @param peer the peer we are considering adding
1934  *
1935  * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1936  *         already full)
1937  */
1938 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1939 {
1940   int bucket;
1941
1942   if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1943     return GNUNET_NO; /* We already know this peer (are connected even!) */
1944   bucket = find_current_bucket(&peer->hashPubKey);
1945
1946   if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1947     return GNUNET_YES;
1948
1949   return GNUNET_NO;
1950 }
1951
1952 /**
1953  * Main function that handles whether or not to route a result
1954  * message to other peers, or to send to our local client.
1955  *
1956  * @param msg the result message to be routed
1957  * @param message_context context of the message we are routing
1958  *
1959  * @return the number of peers the message was routed to,
1960  *         GNUNET_SYSERR on failure
1961  */
1962 static int route_result_message(struct GNUNET_MessageHeader *msg,
1963                                 struct DHT_MessageContext *message_context)
1964 {
1965   struct GNUNET_PeerIdentity new_peer;
1966   struct DHTQueryRecord *record;
1967   struct DHTRouteSource *pos;
1968   struct PeerInfo *peer_info;
1969   const struct GNUNET_MessageHeader *hello_msg;
1970
1971   increment_stats(STAT_RESULTS);
1972   /**
1973    * If a find peer result message is received and contains a valid
1974    * HELLO for another peer, offer it to the transport service.
1975    */
1976   if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1977     {
1978       if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1979         GNUNET_break_op(0);
1980
1981       hello_msg = &msg[1];
1982       if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1983       {
1984         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1985         GNUNET_break_op(0);
1986         return GNUNET_NO;
1987       }
1988       else /* We have a valid hello, and peer id stored in new_peer */
1989       {
1990         find_peer_context.count++;
1991         increment_stats(STAT_FIND_PEER_REPLY);
1992         if (GNUNET_YES == consider_peer(&new_peer))
1993         {
1994           increment_stats(STAT_HELLOS_PROVIDED);
1995           GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1996           GNUNET_CORE_peer_request_connect(cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1997         }
1998       }
1999     }
2000
2001   if (malicious_dropper == GNUNET_YES)
2002     record = NULL;
2003   else
2004     record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
2005
2006   if (record == NULL) /* No record of this message! */
2007     {
2008 #if DEBUG_DHT
2009     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2010                 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
2011                 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2012 #endif
2013 #if DEBUG_DHT_ROUTING
2014       if ((debug_routes_extended) && (dhtlog_handle != NULL))
2015         {
2016           dhtlog_handle->insert_route (NULL,
2017                                        message_context->unique_id,
2018                                        DHTLOG_RESULT,
2019                                        message_context->hop_count,
2020                                        GNUNET_SYSERR,
2021                                        &my_identity,
2022                                        &message_context->key,
2023                                        message_context->peer, NULL);
2024         }
2025 #endif
2026       if (message_context->bloom != NULL)
2027         {
2028           GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2029           message_context->bloom = NULL;
2030         }
2031       return 0;
2032     }
2033
2034   pos = record->head;
2035   while (pos != NULL)
2036     {
2037 #if STRICT_FORWARDING
2038       if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2039         {
2040           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2041           {
2042             increment_stats("# find peer responses NOT forwarded (bloom match)");
2043             pos = pos->next;
2044             continue;
2045           }
2046           else
2047             GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2048         }
2049 #endif
2050
2051       if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2052         {
2053 #if DEBUG_DHT
2054           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2055                       "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2056                       "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2057 #endif
2058 #if DEBUG_DHT_ROUTING
2059           if ((debug_routes_extended) && (dhtlog_handle != NULL))
2060             {
2061               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2062                                            message_context->hop_count,
2063                                            GNUNET_YES, &my_identity, &message_context->key,
2064                                            message_context->peer, NULL);
2065             }
2066 #endif
2067           increment_stats(STAT_RESULTS_TO_CLIENT);
2068           if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2069             increment_stats(STAT_GET_REPLY);
2070
2071           send_reply_to_client(pos->client, msg, 
2072                                message_context->unique_id,
2073                                &message_context->key);
2074         }
2075       else /* Send to peer */
2076         {
2077           peer_info = find_peer_by_id(&pos->source);
2078           if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2079             {
2080               pos = pos->next;
2081               continue;
2082             }
2083
2084           if (message_context->bloom == NULL)
2085             message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2086           GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2087           if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2088             {
2089 #if DEBUG_DHT
2090               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2091                           "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2092                           "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2093 #endif
2094 #if DEBUG_DHT_ROUTING
2095               if ((debug_routes_extended) && (dhtlog_handle != NULL))
2096                 {
2097                   dhtlog_handle->insert_route (NULL, message_context->unique_id,
2098                                                DHTLOG_RESULT,
2099                                                message_context->hop_count,
2100                                                GNUNET_NO, &my_identity, &message_context->key,
2101                                                message_context->peer, &pos->source);
2102                 }
2103 #endif
2104               forward_result_message(msg, peer_info, message_context);
2105             }
2106           else
2107             {
2108 #if DEBUG_DHT
2109               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2110                           "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2111                           "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2112 #endif
2113             }
2114         }
2115       pos = pos->next;
2116     }
2117   if (message_context->bloom != NULL)
2118     GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2119   return 0;
2120 }
2121
2122 /**
2123  * Iterator for local get request results,
2124  *
2125  * @param cls closure for iterator, a DatacacheGetContext
2126  * @param exp when does this value expire?
2127  * @param key the key this data is stored under
2128  * @param size the size of the data identified by key
2129  * @param data the actual data
2130  * @param type the type of the data
2131  *
2132  * @return GNUNET_OK to continue iteration, anything else
2133  * to stop iteration.
2134  */
2135 static int
2136 datacache_get_iterator (void *cls,
2137                         struct GNUNET_TIME_Absolute exp,
2138                         const GNUNET_HashCode * key,
2139                         size_t size, const char *data, 
2140                         enum GNUNET_BLOCK_Type type)
2141 {
2142   struct DHT_MessageContext *msg_ctx = cls;
2143   struct DHT_MessageContext *new_msg_ctx;
2144   struct GNUNET_DHT_GetResultMessage *get_result;
2145   enum GNUNET_BLOCK_EvaluationResult eval;
2146
2147 #if DEBUG_DHT
2148   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2149               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2150 #endif  
2151   eval = GNUNET_BLOCK_evaluate (block_context,
2152                                 type,
2153                                 key,
2154                                 &msg_ctx->reply_bf,
2155                                 msg_ctx->reply_bf_mutator,
2156                                 msg_ctx->xquery,
2157                                 msg_ctx->xquery_size,
2158                                 data,
2159                                 size);
2160   switch (eval)
2161     {
2162     case GNUNET_BLOCK_EVALUATION_OK_LAST:
2163       msg_ctx->do_forward = GNUNET_NO;
2164     case GNUNET_BLOCK_EVALUATION_OK_MORE:
2165       new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2166       memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2167       get_result =
2168         GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2169       get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2170       get_result->header.size =
2171         htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2172       get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2173       get_result->type = htons (type);
2174       memcpy (&get_result[1], data, size);
2175       new_msg_ctx->peer = &my_identity;
2176       new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2177       new_msg_ctx->hop_count = 0;
2178       new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2179       new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2180       increment_stats(STAT_GET_RESPONSE_START);
2181       route_result_message(&get_result->header, new_msg_ctx);
2182       GNUNET_free(new_msg_ctx);
2183       GNUNET_free (get_result);
2184       break;
2185     case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2186 #if DEBUG_DHT
2187       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2188                   "`%s:%s': Duplicate block error\n", my_short_id, "DHT");
2189 #endif
2190       break;
2191     case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2192 #if DEBUG_DHT
2193       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194                   "`%s:%s': Invalid request error\n", my_short_id, "DHT");
2195 #endif
2196       break;
2197     case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2198 #if DEBUG_DHT
2199       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2200                   "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2201 #endif
2202       GNUNET_break (0);
2203       break;
2204     case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2205       GNUNET_break_op (0);
2206       msg_ctx->do_forward = GNUNET_NO;
2207       break;
2208     case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2209 #if DEBUG_DHT
2210       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2211                   "`%s:%s': Unsupported block type (%u) in response!\n", my_short_id, "DHT", type);
2212 #endif
2213       /* msg_ctx->do_forward = GNUNET_NO;  // not sure... */
2214       break;
2215     }  
2216   return GNUNET_OK;
2217 }
2218
2219
2220 /**
2221  * Main function that handles whether or not to route a message to other
2222  * peers.
2223  *
2224  * @param msg the message to be routed
2225  * @param message_context the context containing all pertinent information about the message
2226  */
2227 static void
2228 route_message(const struct GNUNET_MessageHeader *msg,
2229                struct DHT_MessageContext *message_context);
2230
2231
2232 /**
2233  * Server handler for all dht get requests, look for data,
2234  * if found, send response either to clients or other peers.
2235  *
2236  * @param msg the actual get message
2237  * @param message_context struct containing pertinent information about the get request
2238  *
2239  * @return number of items found for GET request
2240  */
2241 static unsigned int
2242 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2243                 struct DHT_MessageContext *message_context)
2244 {
2245   const struct GNUNET_DHT_GetMessage *get_msg;
2246   uint16_t msize;
2247   uint16_t bf_size;
2248   unsigned int results;
2249   const char *end;
2250   enum GNUNET_BLOCK_Type type;
2251
2252   msize = ntohs (msg->size);
2253   if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2254     {
2255       GNUNET_break (0);
2256       return 0;
2257     }
2258   get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2259   bf_size = ntohs (get_msg->bf_size);
2260   message_context->xquery_size = ntohs (get_msg->xquery_size);
2261   message_context->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2262   if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + message_context->xquery_size)
2263     {
2264       GNUNET_break (0);
2265       return 0;
2266     }
2267   end = (const char*) &get_msg[1];
2268   if (message_context->xquery_size == 0)
2269     {
2270       message_context->xquery = NULL;
2271     }
2272   else
2273     {
2274       message_context->xquery = (const void*) end;
2275       end += message_context->xquery_size;
2276     }
2277   if (bf_size == 0)
2278     {
2279       message_context->reply_bf = NULL;
2280     }
2281   else
2282     {
2283       message_context->reply_bf = GNUNET_CONTAINER_bloomfilter_init (end,
2284                                                                      bf_size,
2285                                                                      GNUNET_DHT_GET_BLOOMFILTER_K);
2286     }
2287   type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2288 #if DEBUG_DHT
2289   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2290               "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2291               my_short_id,
2292               "DHT", "GET", 
2293               type,
2294               GNUNET_h2s (&message_context->key),
2295               message_context->unique_id);
2296 #endif
2297   increment_stats(STAT_GETS);
2298   results = 0;
2299 #if HAVE_MALICIOUS
2300   if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2301     {
2302       GNUNET_CONTAINER_bloomfilter_free (message_context->reply_bf);
2303       return results;
2304     }
2305 #endif
2306   message_context->do_forward = GNUNET_YES;
2307   if (datacache != NULL)
2308     results
2309       = GNUNET_DATACACHE_get (datacache,
2310                               &message_context->key, type,
2311                               &datacache_get_iterator,
2312                               message_context);
2313 #if DEBUG_DHT
2314       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2315                   "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2316                   results, "GET", message_context->unique_id);
2317 #endif
2318   if (results >= 1)
2319     {
2320 #if DEBUG_DHT_ROUTING
2321       if ((debug_routes) && (dhtlog_handle != NULL))
2322         {
2323           dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2324                                 message_context->hop_count, GNUNET_YES, &my_identity,
2325                                 &message_context->key);
2326         }
2327
2328       if ((debug_routes_extended) && (dhtlog_handle != NULL))
2329         {
2330           dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2331                                        message_context->hop_count, GNUNET_YES,
2332                                        &my_identity, &message_context->key, message_context->peer,
2333                                        NULL);
2334         }
2335 #endif
2336     }
2337   else
2338     {
2339       /* check query valid */
2340       if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID
2341           == GNUNET_BLOCK_evaluate (block_context,
2342                                     type,
2343                                     &message_context->key,
2344                                     &message_context->reply_bf,
2345                                     message_context->reply_bf_mutator,
2346                                     message_context->xquery,
2347                                     message_context->xquery_size,
2348                                     NULL, 0))
2349         {
2350           GNUNET_break_op (0);
2351           message_context->do_forward = GNUNET_NO;
2352         }
2353     }
2354
2355   if (message_context->hop_count == 0) /* Locally initiated request */
2356     {
2357 #if DEBUG_DHT_ROUTING
2358     if ((debug_routes) && (dhtlog_handle != NULL))
2359       {
2360         dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2361                                       message_context->hop_count, GNUNET_NO, &my_identity,
2362                                       &message_context->key);
2363       }
2364 #endif
2365     }
2366   if (message_context->do_forward == GNUNET_YES)
2367     route_message (msg, message_context);
2368   GNUNET_CONTAINER_bloomfilter_free (message_context->reply_bf);
2369   return results;
2370 }
2371
2372 static void
2373 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2374 {
2375   GNUNET_HashCode *key = cls;
2376   
2377   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, NULL));
2378   GNUNET_free (key);
2379 }
2380
2381 /**
2382  * Server handler for initiating local dht find peer requests
2383  *
2384  * @param find_msg the actual find peer message
2385  * @param message_context struct containing pertinent information about the request
2386  *
2387  */
2388 static void
2389 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2390                       struct DHT_MessageContext *message_context)
2391 {
2392   struct GNUNET_MessageHeader *find_peer_result;
2393   struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2394   struct DHT_MessageContext *new_msg_ctx;
2395   struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2396   size_t hello_size;
2397   size_t tsize;
2398   GNUNET_HashCode *recent_hash;
2399   struct GNUNET_MessageHeader *other_hello;
2400   size_t other_hello_size;
2401   struct GNUNET_PeerIdentity peer_id;
2402
2403   find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2404   GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2405   if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2406     return;
2407   other_hello = NULL;
2408   other_hello_size = 0;
2409   if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2410     {
2411       other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2412       other_hello = GNUNET_malloc(other_hello_size);
2413       memcpy(other_hello, &find_peer_message[1], other_hello_size);
2414       if ((GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)other_hello) == 0) || (GNUNET_OK != GNUNET_HELLO_get_id((struct GNUNET_HELLO_Message *)other_hello, &peer_id)))
2415         {
2416           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2417           GNUNET_free(other_hello);
2418           return;
2419         }
2420 #if FIND_PEER_WITH_HELLO
2421       if (GNUNET_YES == consider_peer(&peer_id))
2422         {
2423           increment_stats(STAT_HELLOS_PROVIDED);
2424           GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2425           GNUNET_CORE_peer_request_connect(cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2426           route_message (find_msg, message_context);
2427           GNUNET_free (other_hello);
2428           return;
2429         }
2430       else /* We don't want this peer! */
2431         {
2432           route_message (find_msg, message_context);
2433           return;
2434         }
2435 #endif
2436     }
2437
2438 #if DEBUG_DHT
2439   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2440               "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2441               my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&message_context->key),
2442               ntohs (find_msg->size),
2443               sizeof (struct GNUNET_MessageHeader));
2444 #endif
2445   if (my_hello == NULL)
2446   {
2447 #if DEBUG_DHT
2448     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2449                 "`%s': Our HELLO is null, can't return.\n",
2450                 "DHT");
2451 #endif
2452     GNUNET_free_non_null (other_hello);
2453     route_message (find_msg, message_context);
2454     return;
2455   }
2456
2457   incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2458   if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2459     {
2460       increment_stats(STAT_BLOOM_FIND_PEER);
2461       GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2462       GNUNET_free_non_null(other_hello);
2463       route_message (find_msg, message_context);
2464       return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2465     }
2466   GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2467
2468 #if RESTRICT_FIND_PEER
2469
2470   /**
2471    * Ignore any find peer requests from a peer we have seen very recently.
2472    */
2473   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! */
2474   {
2475     increment_stats("# dht find peer requests ignored (recently seen!)");
2476     GNUNET_free_non_null(other_hello);
2477     return;
2478   }
2479
2480   /**
2481    * Use this check to only allow the peer to respond to find peer requests if
2482    * it would be beneficial to have the requesting peer in this peers routing
2483    * table.  Can be used to thwart peers flooding the network with find peer
2484    * requests that we don't care about.  However, if a new peer is joining
2485    * the network and has no other peers this is a problem (assume all buckets
2486    * full, no one will respond!).
2487    */
2488   memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2489   if (GNUNET_NO == consider_peer(&peer_id))
2490     {
2491       increment_stats("# dht find peer requests ignored (do not need!)");
2492       GNUNET_free_non_null(other_hello);
2493       route_message (find_msg, message_context);
2494       return;
2495     }
2496 #endif
2497
2498   recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2499   memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2500   if (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2501                                      &message_context->key, NULL, 
2502                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2503     {
2504       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding recent remove task for key `%s`!\n", GNUNET_h2s(&message_context->key));
2505       /* Only add a task if there wasn't one for this key already! */
2506       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30),
2507                                     &remove_recent_find_peer, recent_hash);
2508     }
2509   else
2510     {
2511       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received duplicate find peer request too soon!\n");
2512     }
2513
2514   /* Simplistic find_peer functionality, always return our hello */
2515   hello_size = ntohs(my_hello->size);
2516   tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2517
2518   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2519     {
2520       GNUNET_break_op (0);
2521       GNUNET_free_non_null(other_hello);
2522       return;
2523     }
2524
2525   find_peer_result = GNUNET_malloc (tsize);
2526   find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2527   find_peer_result->size = htons (tsize);
2528   memcpy (&find_peer_result[1], my_hello, hello_size);
2529
2530   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2531               "`%s': Sending hello size %d to requesting peer.\n",
2532               "DHT", hello_size);
2533
2534   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2535   memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2536   new_msg_ctx->peer = &my_identity;
2537   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2538   new_msg_ctx->hop_count = 0;
2539   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2540   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2541   increment_stats(STAT_FIND_PEER_ANSWER);
2542   route_result_message(find_peer_result, new_msg_ctx);
2543   GNUNET_free(new_msg_ctx);
2544 #if DEBUG_DHT_ROUTING
2545   if ((debug_routes) && (dhtlog_handle != NULL))
2546     {
2547       dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2548                                    message_context->hop_count, GNUNET_YES, &my_identity,
2549                                    &message_context->key);
2550     }
2551 #endif
2552   GNUNET_free_non_null(other_hello);
2553   GNUNET_free(find_peer_result);
2554   route_message (find_msg, message_context);
2555 }
2556
2557 /**
2558  * Task used to republish data.
2559  * Forward declaration; function call loop.
2560  *
2561  * @param cls closure (a struct RepublishContext)
2562  * @param tc runtime context for this task
2563  */
2564 static void
2565 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2566
2567 /**
2568  * Server handler for initiating local dht put requests
2569  *
2570  * @param msg the actual put message
2571  * @param message_context struct containing pertinent information about the request
2572  */
2573 static void
2574 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2575                 struct DHT_MessageContext *message_context)
2576 {
2577   const struct GNUNET_DHT_PutMessage *put_msg;
2578   enum GNUNET_BLOCK_Type put_type;
2579   size_t data_size;
2580   int ret;
2581   struct RepublishContext *put_context;
2582   GNUNET_HashCode key;
2583
2584   GNUNET_assert (ntohs (msg->size) >=
2585                  sizeof (struct GNUNET_DHT_PutMessage));
2586
2587
2588   put_msg = (const struct GNUNET_DHT_PutMessage *)msg;
2589   put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2590
2591   if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2592     return;
2593   data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2594   ret = GNUNET_BLOCK_get_key (block_context,
2595                               put_type,
2596                               &put_msg[1],
2597                               data_size,
2598                               &key);
2599   if (GNUNET_NO == ret)
2600     {
2601       /* invalid reply */
2602       GNUNET_break_op (0);
2603       return;
2604     }
2605   if ( (GNUNET_YES == ret) &&
2606        (0 != memcmp (&key,
2607                      &message_context->key,
2608                      sizeof (GNUNET_HashCode))) )
2609     {
2610       /* invalid wrapper: key mismatch! */
2611       GNUNET_break_op (0);
2612       return;
2613     }
2614   /* ret == GNUNET_SYSERR means that there is no known relationship between
2615      data and the key, so we cannot check it */
2616 #if DEBUG_DHT
2617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2618               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2619               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
2620 #endif
2621 #if DEBUG_DHT_ROUTING
2622   if (message_context->hop_count == 0) /* Locally initiated request */
2623     {
2624       if ((debug_routes) && (dhtlog_handle != NULL))
2625         {
2626           dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2627                                        message_context->hop_count, GNUNET_NO, &my_identity,
2628                                        &message_context->key);
2629         }
2630     }
2631 #endif
2632
2633   if (message_context->closest != GNUNET_YES)
2634     {
2635       route_message (msg, message_context);
2636       return;
2637     }
2638
2639 #if DEBUG_DHT
2640   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2641               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2642               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
2643 #endif
2644
2645 #if DEBUG_DHT_ROUTING
2646   if ((debug_routes_extended) && (dhtlog_handle != NULL))
2647     {
2648       dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2649                                    message_context->hop_count, GNUNET_YES,
2650                                    &my_identity, &message_context->key, message_context->peer,
2651                                    NULL);
2652     }
2653
2654   if ((debug_routes) && (dhtlog_handle != NULL))
2655     {
2656       dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2657                                    message_context->hop_count, GNUNET_YES, &my_identity,
2658                                    &message_context->key);
2659     }
2660 #endif
2661
2662   increment_stats(STAT_PUTS_INSERTED);
2663   if (datacache != NULL)
2664     {
2665       ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2666                                   (char *) &put_msg[1], put_type,
2667                                   GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2668
2669       if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2670         {
2671           put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2672           memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2673           put_context->type = put_type;
2674           GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content, put_context);
2675         }
2676     }
2677   else
2678     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2679                 "`%s:%s': %s request received, but have no datacache!\n",
2680                 my_short_id, "DHT", "PUT");
2681
2682   if (stop_on_closest == GNUNET_NO)
2683     route_message (msg, message_context);
2684 }
2685
2686 /**
2687  * Estimate the diameter of the network based
2688  * on how many buckets are currently in use.
2689  * Concept here is that the diameter of the network
2690  * is roughly the distance a message must travel in
2691  * order to reach its intended destination.  Since
2692  * at each hop we expect to get one bit closer, and
2693  * we have one bit per bucket, the number of buckets
2694  * in use should be the largest number of hops for
2695  * a successful message. (of course, this assumes we
2696  * know all peers in the network!)
2697  *
2698  * @return ballpark diameter figure
2699  */
2700 static unsigned int estimate_diameter()
2701 {
2702   return MAX_BUCKETS - lowest_bucket;
2703 }
2704
2705 /**
2706  * To how many peers should we (on average)
2707  * forward the request to obtain the desired
2708  * target_replication count (on average).
2709  *
2710  * Always 0, 1 or 2 (don't send, send once, split)
2711  */
2712 static unsigned int
2713 get_forward_count (unsigned int hop_count, size_t target_replication)
2714 {
2715 #if DOUBLE
2716   double target_count;
2717   double random_probability;
2718 #else
2719   uint32_t random_value;
2720 #endif
2721   unsigned int target_value;
2722   unsigned int diameter;
2723
2724   /**
2725    * If we are behaving in strict kademlia mode, send multiple initial requests,
2726    * but then only send to 1 or 0 peers based strictly on the number of hops.
2727    */
2728   if (strict_kademlia == GNUNET_YES)
2729     {
2730       if (hop_count == 0)
2731         return DHT_KADEMLIA_REPLICATION;
2732       else if (hop_count < max_hops)
2733         return 1;
2734       else
2735         return 0;
2736     }
2737
2738   /* FIXME: the smaller we think the network is the more lenient we should be for
2739    * routing right?  The estimation below only works if we think we have reasonably
2740    * full routing tables, which for our RR topologies may not be the case!
2741    */
2742   diameter = estimate_diameter ();
2743   if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size) && (use_max_hops == GNUNET_NO))
2744     {
2745 #if DEBUG_DHT
2746       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2747                   "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2748                   "DHT", estimate_diameter(), lowest_bucket);
2749 #endif
2750       return 0;
2751     }
2752   else if (hop_count > max_hops)
2753     {
2754 #if DEBUG_DHT
2755       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2756                   "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2757                   "DHT");
2758 #endif
2759       return 0;
2760     }
2761
2762 #if DOUBLE
2763   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2764   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2765   target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2766     (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2767   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2768   random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2769       RAND_MAX)) / RAND_MAX;
2770   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2771
2772   target_value = 0;
2773   //while (target_value < target_count)
2774   if (target_value < target_count)
2775     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? */
2776
2777
2778   //if ((target_count + 1 - (double)target_value) > random_probability)
2779   if ((target_count) > random_probability)
2780     target_value++;
2781 #endif
2782
2783   random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2784   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "replication %u, at hop %d, will split with probability %f\n", target_replication, hop_count, target_replication / (double)((target_replication * (hop_count + 1) + diameter) + 1));
2785   target_value = 1;
2786   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2787   if (random_value < target_replication)
2788     target_value++;
2789
2790   return target_value;
2791 }
2792
2793 /*
2794  * Check whether my identity is closer than any known peers.
2795  * If a non-null bloomfilter is given, check if this is the closest
2796  * peer that hasn't already been routed to.
2797  *
2798  * @param target hash code to check closeness to
2799  * @param bloom bloomfilter, exclude these entries from the decision
2800  *
2801  * Return GNUNET_YES if node location is closest, GNUNET_NO
2802  * otherwise.
2803  */
2804 int
2805 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2806 {
2807   int bits;
2808   int other_bits;
2809   int bucket_num;
2810   int count;
2811   struct PeerInfo *pos;
2812   unsigned int my_distance;
2813
2814   if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2815     return GNUNET_YES;
2816
2817   bucket_num = find_current_bucket(target);
2818
2819   bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2820   my_distance = distance(&my_identity.hashPubKey, target);
2821   pos = k_buckets[bucket_num].head;
2822   count = 0;
2823   while ((pos != NULL) && (count < bucket_size))
2824     {
2825       if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2826         {
2827           pos = pos->next;
2828           continue; /* Skip already checked entries */
2829         }
2830
2831       other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2832       if (other_bits > bits)
2833         return GNUNET_NO;
2834       else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2835         {
2836           if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2837             return GNUNET_YES;
2838           else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2839             return GNUNET_NO;
2840         }
2841       pos = pos->next;
2842     }
2843
2844   /* No peers closer, we are the closest! */
2845   return GNUNET_YES;
2846 }
2847
2848
2849 /**
2850  * Return this peers adjusted value based on the convergence
2851  * function chosen.  This is the key function for randomized
2852  * routing decisions.
2853  *
2854  * @param target the key of the request
2855  * @param peer the peer we would like the value of
2856  * @param hops number of hops this message has already traveled
2857  *
2858  * @return bit distance from target to peer raised to an exponent
2859  *         adjusted based on the current routing convergence algorithm
2860  *
2861  */
2862 static unsigned long long
2863 converge_distance (const GNUNET_HashCode *target,
2864                    struct PeerInfo *peer,
2865                    unsigned int hops)
2866 {
2867   unsigned long long ret;
2868   unsigned int other_matching_bits;
2869   double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
2870   double temp_modifier;
2871   double calc_value;
2872   double exponent;
2873   int curr_max_hops;
2874
2875   if (use_max_hops)
2876     curr_max_hops = max_hops;
2877   else
2878     curr_max_hops = (estimate_diameter() + 1) * 2;
2879
2880   if (converge_modifier > 0)
2881     temp_modifier = converge_modifier * base_converge_modifier;
2882   else
2883     {
2884       temp_modifier = base_converge_modifier;
2885       base_converge_modifier = 0.0;
2886     }
2887
2888   GNUNET_assert(temp_modifier > 0);
2889
2890   other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2891
2892   switch (converge_option)
2893     {
2894       case DHT_CONVERGE_RANDOM:
2895         return 1; /* Always return 1, choose equally among all peers */
2896       case DHT_CONVERGE_LINEAR:
2897         calc_value = hops * curr_max_hops * temp_modifier;
2898         break;
2899       case DHT_CONVERGE_SQUARE:
2900         /**
2901          * Simple square based curve.
2902          */
2903         calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * temp_modifier));
2904         break;
2905       case DHT_CONVERGE_EXPONENTIAL:
2906         /**
2907          * Simple exponential curve.
2908          */
2909         if (base_converge_modifier > 0)
2910           calc_value = (temp_modifier * hops * hops) / curr_max_hops;
2911         else
2912           calc_value = (hops * hops) / curr_max_hops;
2913         break;
2914       case DHT_CONVERGE_BINARY:
2915         /**
2916          * If below the cutoff, route randomly (return 1),
2917          * If above the cutoff, return the maximum possible
2918          * value first (always route to closest, because
2919          * they are sorted.)
2920          */
2921
2922         if (hops > converge_modifier) /* Past cutoff */
2923           {
2924             return ULLONG_MAX;
2925           }
2926         /* Fall through */
2927       default:
2928         return 1;
2929     }
2930
2931   /* Take the log (base e) of the number of bits matching the other peer */
2932   exponent = log(other_matching_bits);
2933
2934   /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
2935   if (exponent * calc_value >= 44.361419555836498)
2936     return ULLONG_MAX;
2937
2938   /* Clear errno and all math exceptions */
2939   errno = 0;
2940   feclearexcept(FE_ALL_EXCEPT);
2941   ret = (unsigned long long)pow(other_matching_bits, calc_value);
2942   if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2943       FE_UNDERFLOW))
2944     {
2945       if (0 != fetestexcept(FE_OVERFLOW))
2946         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2947       if (0 != fetestexcept(FE_INVALID))
2948         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2949       if (0 != fetestexcept(FE_UNDERFLOW))
2950         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2951       return 0;
2952     }
2953   else
2954     return ret;
2955 }
2956
2957 /**
2958  * Comparison function for two struct PeerInfo's
2959  * which have already had their matching bits to
2960  * some target calculated.
2961  *
2962  * @param p1 a pointer pointer to a struct PeerInfo
2963  * @param p2 a pointer pointer to a struct PeerInfo
2964  *
2965  * @return 0 if equidistant to target,
2966  *        -1 if p1 is closer,
2967  *         1 if p2 is closer
2968  */
2969 static int
2970 compare_peers (const void *p1, const void *p2)
2971 {
2972   struct PeerInfo **first = (struct PeerInfo **)p1;
2973   struct PeerInfo **second = (struct PeerInfo **)p2;
2974
2975   if ((*first)->matching_bits > (*second)->matching_bits)
2976     return -1;
2977   if ((*first)->matching_bits < (*second)->matching_bits)
2978     return 1;
2979   else
2980     return 0;
2981 }
2982
2983
2984 /**
2985  * Select a peer from the routing table that would be a good routing
2986  * destination for sending a message for "target".  The resulting peer
2987  * must not be in the set of blocked peers.<p>
2988  *
2989  * Note that we should not ALWAYS select the closest peer to the
2990  * target, peers further away from the target should be chosen with
2991  * exponentially declining probability.
2992  *
2993  * @param target the key we are selecting a peer to route to
2994  * @param bloom a bloomfilter containing entries this request has seen already
2995  *
2996  * @return Peer to route to, or NULL on error
2997  */
2998 static struct PeerInfo *
2999 select_peer (const GNUNET_HashCode * target,
3000              struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3001 {
3002   unsigned int bc;
3003   unsigned int i;
3004   unsigned int count;
3005   unsigned int offset;
3006   unsigned int my_matching_bits;
3007   int closest_bucket;
3008   struct PeerInfo *pos;
3009   struct PeerInfo *sorted_closest[bucket_size];
3010   unsigned long long temp_converge_distance;
3011   unsigned long long total_distance;
3012   unsigned long long selected;
3013 #if DEBUG_DHT > 1
3014   unsigned long long stats_total_distance;
3015   double sum;
3016 #endif
3017   /* For kademlia */
3018   unsigned int distance;
3019   unsigned int largest_distance;
3020   struct PeerInfo *chosen;
3021
3022   my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
3023
3024   total_distance = 0;
3025   if (strict_kademlia == GNUNET_YES)
3026     {
3027       largest_distance = 0;
3028       chosen = NULL;
3029       for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3030         {
3031           pos = k_buckets[bc].head;
3032           count = 0;
3033           while ((pos != NULL) && (count < bucket_size))
3034             {
3035               /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3036               if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3037                 {
3038                   distance = inverse_distance (target, &pos->id.hashPubKey);
3039                   if (distance > largest_distance)
3040                     {
3041                       chosen = pos;
3042                       largest_distance = distance;
3043                     }
3044                 }
3045               count++;
3046               pos = pos->next;
3047             }
3048         }
3049
3050       if ((largest_distance > 0) && (chosen != NULL))
3051         {
3052           GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
3053           return chosen;
3054         }
3055       else
3056         {
3057           return NULL;
3058         }
3059     }
3060
3061   /* GNUnet-style */
3062   total_distance = 0;
3063   /* Three steps: order peers in closest bucket (most matching bits).
3064    * Then go over all LOWER buckets (matching same bits we do)
3065    * Then go over all HIGHER buckets (matching less then we do)
3066    */
3067
3068   closest_bucket = find_current_bucket(target);
3069   GNUNET_assert(closest_bucket >= lowest_bucket);
3070   pos = k_buckets[closest_bucket].head;
3071   count = 0;
3072   offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3073   memset(sorted_closest, 0, sizeof(sorted_closest));
3074   /* Put any peers in the closest bucket in the sorting array */
3075   while ((pos != NULL) && (count < bucket_size))
3076     {
3077       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3078         {
3079           count++;
3080           pos = pos->next;
3081           continue; /* Ignore bloomfiltered peers */
3082         }
3083       pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
3084       sorted_closest[offset] = pos;
3085       pos = pos->next;
3086       offset++;
3087       count++;
3088     }
3089
3090   /* Sort the peers in descending order */
3091   qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
3092
3093   /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3094   for (i = 0; i < offset; i++)
3095     {
3096       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3097       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3098         break; /* Ignore bloomfiltered peers */
3099       if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3100         total_distance += temp_converge_distance;
3101       else
3102         break; /* overflow case */
3103     }
3104
3105   /* Now handle peers in lower buckets (matches same # of bits as target) */
3106   for (bc = lowest_bucket; bc < closest_bucket; bc++)
3107     {
3108       pos = k_buckets[bc].head;
3109       count = 0;
3110       while ((pos != NULL) && (count < bucket_size))
3111         {
3112           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3113             {
3114               count++;
3115               pos = pos->next;
3116               continue; /* Ignore bloomfiltered peers */
3117             }
3118           temp_converge_distance = converge_distance(target, pos, hops);
3119           if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3120             total_distance += temp_converge_distance;
3121           else
3122             break; /* overflow case */
3123           pos = pos->next;
3124           count++;
3125         }
3126     }
3127
3128   /* Now handle all the further away peers */
3129   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3130     {
3131       pos = k_buckets[bc].head;
3132       count = 0;
3133       while ((pos != NULL) && (count < bucket_size))
3134         {
3135           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3136             {
3137               count++;
3138               pos = pos->next;
3139               continue; /* Ignore bloomfiltered peers */
3140             }
3141           temp_converge_distance = converge_distance(target, pos, hops);
3142           if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3143             total_distance += temp_converge_distance;
3144           else
3145             break; /* overflow case */
3146           pos = pos->next;
3147           count++;
3148         }
3149     }
3150
3151   if (total_distance == 0) /* No peers to select from! */
3152     {
3153       increment_stats("# select_peer, total_distance == 0");
3154       return NULL;
3155     }
3156
3157 #if DEBUG_DHT_ROUTING > 1
3158   sum = 0.0;
3159   /* PRINT STATS */
3160   /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3161   stats_total_distance = 0;
3162   for (i = 0; i < offset; i++)
3163     {
3164       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3165         break; /* Ignore bloomfiltered peers */
3166       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3167       if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3168         stats_total_distance += temp_converge_distance;
3169       else
3170         break; /* overflow case */
3171       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n", GNUNET_CRYPTO_hash_matching_bits(&sorted_closest[i]->id.hashPubKey, target), GNUNET_CRYPTO_hash_matching_bits(&sorted_closest[i]->id.hashPubKey, &my_identity.hashPubKey), (temp_converge_distance / (double)total_distance) * 100, temp_converge_distance);
3172     }
3173
3174   /* Now handle peers in lower buckets (matches same # of bits as target) */
3175   for (bc = lowest_bucket; bc < closest_bucket; bc++)
3176     {
3177       pos = k_buckets[bc].head;
3178       count = 0;
3179       while ((pos != NULL) && (count < bucket_size))
3180         {
3181           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3182             {
3183               count++;
3184               pos = pos->next;
3185               continue; /* Ignore bloomfiltered peers */
3186             }
3187           temp_converge_distance = converge_distance(target, pos, hops);
3188           if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3189             stats_total_distance += temp_converge_distance;
3190           else
3191             break; /* overflow case */
3192           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n", GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target), GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey), (temp_converge_distance / (double)total_distance) * 100, temp_converge_distance);
3193           pos = pos->next;
3194           count++;
3195         }
3196     }
3197
3198   /* Now handle all the further away peers */
3199   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3200     {
3201       pos = k_buckets[bc].head;
3202       count = 0;
3203       while ((pos != NULL) && (count < bucket_size))
3204         {
3205           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3206             {
3207               count++;
3208               pos = pos->next;
3209               continue; /* Ignore bloomfiltered peers */
3210             }
3211           temp_converge_distance = converge_distance(target, pos, hops);
3212           if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3213             stats_total_distance += temp_converge_distance;
3214           else
3215             break; /* overflow case */
3216           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n", GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target), GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey),  (temp_converge_distance / (double)total_distance) * 100, temp_converge_distance);
3217           pos = pos->next;
3218           count++;
3219         }
3220     }
3221   /* END PRINT STATS */
3222 #endif
3223
3224   /* Now actually choose a peer */
3225   selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3226
3227   /* Go over closest sorted peers. */
3228   for (i = 0; i < offset; i++)
3229     {
3230       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3231         break; /* Ignore bloomfiltered peers */
3232       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3233       if (temp_converge_distance >= selected)
3234         return sorted_closest[i];
3235       else
3236         selected -= temp_converge_distance;
3237     }
3238
3239   /* Now handle peers in lower buckets (matches same # of bits as target) */
3240   for (bc = lowest_bucket; bc < closest_bucket; bc++)
3241     {
3242       pos = k_buckets[bc].head;
3243       count = 0;
3244       while ((pos != NULL) && (count < bucket_size))
3245         {
3246           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3247             {
3248               count++;
3249               pos = pos->next;
3250               continue; /* Ignore bloomfiltered peers */
3251             }
3252           temp_converge_distance = converge_distance(target, pos, hops);
3253           if (temp_converge_distance >= selected)
3254             return pos;
3255           else
3256             selected -= temp_converge_distance;
3257           pos = pos->next;
3258           count++;
3259         }
3260     }
3261
3262   /* Now handle all the further away peers */
3263   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3264     {
3265       pos = k_buckets[bc].head;
3266       count = 0;
3267       while ((pos != NULL) && (count < bucket_size))
3268         {
3269           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3270             {
3271               count++;
3272               pos = pos->next;
3273               continue; /* Ignore bloomfiltered peers */
3274             }
3275           temp_converge_distance = converge_distance(target, pos, hops);
3276           if (temp_converge_distance >= selected)
3277             return pos;
3278           else
3279             selected -= temp_converge_distance;
3280           pos = pos->next;
3281           count++;
3282         }
3283     }
3284
3285   increment_stats("# failed to select peer");
3286   return NULL;
3287 }
3288
3289
3290 /**
3291  * Task used to remove recent entries, either
3292  * after timeout, when full, or on shutdown.
3293  *
3294  * @param cls the entry to remove
3295  * @param tc context, reason, etc.
3296  */
3297 static void
3298 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3299 {
3300   struct RecentRequest *req = cls;
3301   static GNUNET_HashCode hash;
3302
3303   GNUNET_assert(req != NULL);
3304   hash_from_uid(req->uid, &hash);
3305   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3306   GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3307   GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3308   GNUNET_free(req);
3309
3310   /*
3311   if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3312   {
3313     GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3314     GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3315   }
3316   */
3317 }
3318
3319
3320 /**
3321  * Task used to remove forwarding entries, either
3322  * after timeout, when full, or on shutdown.
3323  *
3324  * @param cls the entry to remove
3325  * @param tc context, reason, etc.
3326  */
3327 static void
3328 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3329 {
3330   struct DHTRouteSource *source_info = cls;
3331   struct DHTQueryRecord *record;
3332   source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3333   record = source_info->record;
3334   GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3335
3336   if (record->head == NULL) /* No more entries in DLL */
3337     {
3338       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3339       GNUNET_free(record);
3340     }
3341   if (source_info->find_peers_responded != NULL)
3342     GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3343   GNUNET_free(source_info);
3344 }
3345
3346 /**
3347  * Remember this routing request so that if a reply is
3348  * received we can either forward it to the correct peer
3349  * or return the result locally.
3350  *
3351  * @param msg_ctx Context of the route request
3352  *
3353  * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3354  */
3355 static int cache_response(struct DHT_MessageContext *msg_ctx)
3356 {
3357   struct DHTQueryRecord *record;
3358   struct DHTRouteSource *source_info;
3359   struct DHTRouteSource *pos;
3360   struct GNUNET_TIME_Absolute now;
3361   unsigned int current_size;
3362
3363   current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3364   while (current_size >= MAX_OUTSTANDING_FORWARDS)
3365     {
3366       source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3367       GNUNET_assert(source_info != NULL);
3368       record = source_info->record;
3369       GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3370       if (record->head == NULL) /* No more entries in DLL */
3371         {
3372           GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3373           GNUNET_free(record);
3374         }
3375       if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3376         GNUNET_SCHEDULER_cancel(source_info->delete_task);
3377       if (source_info->find_peers_responded != NULL)
3378         GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3379       GNUNET_free(source_info);
3380       current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3381     }
3382   now = GNUNET_TIME_absolute_get();
3383   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3384   if (record != NULL) /* Already know this request! */
3385     {
3386       pos = record->head;
3387       while (pos != NULL)
3388         {
3389           if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3390             break; /* Already have this peer in reply list! */
3391           pos = pos->next;
3392         }
3393       if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3394         {
3395           GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.abs_value);
3396           return GNUNET_NO;
3397         }
3398     }
3399   else
3400     {
3401       record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3402       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3403       memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3404     }
3405
3406   source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3407   source_info->record = record;
3408   source_info->delete_task = GNUNET_SCHEDULER_add_delayed(DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3409   source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3410   memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3411   GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3412   if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3413     {
3414       source_info->client = msg_ctx->client;
3415       now = GNUNET_TIME_absolute_get_forever();
3416     }
3417   source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.abs_value);
3418 #if DEBUG_DHT > 1
3419       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3420                   "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3421                   "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3422 #endif
3423   return GNUNET_YES;
3424 }
3425
3426
3427 /**
3428  * Main function that handles whether or not to route a message to other
3429  * peers.
3430  *
3431  * @param msg the message to be routed
3432  * @param message_context the context containing all pertinent information about the message
3433  */
3434 static void
3435 route_message(const struct GNUNET_MessageHeader *msg,
3436                struct DHT_MessageContext *message_context)
3437 {
3438   int i;
3439   struct PeerInfo *selected;
3440 #if DEBUG_DHT_ROUTING > 1
3441   struct PeerInfo *nearest;
3442 #endif
3443   unsigned int forward_count;
3444   struct RecentRequest *recent_req;
3445   GNUNET_HashCode unique_hash;
3446   char *stat_forward_count;
3447   char *temp_stat_str;
3448 #if DEBUG_DHT_ROUTING
3449   int ret;
3450 #endif
3451
3452   if (malicious_dropper == GNUNET_YES)
3453     {
3454 #if DEBUG_DHT_ROUTING
3455       if ((debug_routes_extended) && (dhtlog_handle != NULL))
3456         {
3457           dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3458                                        message_context->hop_count, GNUNET_SYSERR,
3459                                        &my_identity, &message_context->key, message_context->peer,
3460                                        NULL);
3461         }
3462 #endif
3463       if (message_context->bloom != NULL)
3464         GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3465       return;
3466     }
3467
3468   increment_stats(STAT_ROUTES);
3469   /* Semantics of this call means we find whether we are the closest peer out of those already
3470    * routed to on this messages path.
3471    */
3472   forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3473   GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3474   increment_stats(stat_forward_count);
3475   GNUNET_free(stat_forward_count);
3476   if (message_context->bloom == NULL)
3477     message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3478
3479   if ((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3480     forward_count = 0;
3481
3482   /**
3483    * NOTICE:  In Kademlia, a find peer request goes no further if the peer doesn't return
3484    * any closer peers (which is being checked for below).  Since we are doing recursive
3485    * routing we have no choice but to stop forwarding in this case.  This means that at
3486    * any given step the request may NOT be forwarded to alpha peers (because routes will
3487    * stop and the parallel route will not be aware of it).  Of course, assuming that we
3488    * have fulfilled the Kademlia requirements for routing table fullness this will never
3489    * ever ever be a problem.
3490    *
3491    * However, is this fair?
3492    *
3493    * Since we use these requests to build our routing tables (and we build them in the
3494    * testing driver) we will ignore this restriction for FIND_PEER messages so that
3495    * routing tables still get constructed.
3496    */
3497   if ((GNUNET_YES == strict_kademlia) && (message_context->closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3498     forward_count = 0;
3499
3500 #if DEBUG_DHT_ROUTING
3501   if (forward_count == 0)
3502     ret = GNUNET_SYSERR;
3503   else
3504     ret = GNUNET_NO;
3505
3506   if ((debug_routes_extended) && (dhtlog_handle != NULL))
3507     {
3508       dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3509                                    message_context->hop_count, ret,
3510                                    &my_identity, &message_context->key, message_context->peer,
3511                                    NULL);
3512     }
3513 #endif
3514
3515
3516   GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3517   hash_from_uid (message_context->unique_id, &unique_hash);
3518   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3519   {
3520     recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3521     GNUNET_assert(recent_req != NULL);
3522     if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3523       increment_stats(STAT_DUPLICATE_UID);
3524     else
3525       {
3526         increment_stats(STAT_RECENT_SEEN);
3527         GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3528       }
3529     }
3530   else
3531     {
3532       recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3533       recent_req->uid = message_context->unique_id;
3534       memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3535       recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3536       recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().abs_value);
3537       recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3538       GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3539     }
3540
3541   if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3542     {
3543       recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3544       GNUNET_assert(recent_req != NULL);
3545       GNUNET_SCHEDULER_cancel(recent_req->remove_task);
3546       GNUNET_SCHEDULER_add_now(&remove_recent, recent_req);
3547     }
3548
3549   for (i = 0; i < forward_count; i++)
3550     {
3551       selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3552
3553       if (selected != NULL)
3554         {
3555           if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
3556             GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
3557           else
3558             GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
3559           if (temp_stat_str != NULL)
3560             {
3561               increment_stats(temp_stat_str);
3562               GNUNET_free(temp_stat_str);
3563             }
3564           GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3565 #if DEBUG_DHT_ROUTING > 1
3566           nearest = find_closest_peer(&message_context->key);
3567           nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3568           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3569                       "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3570                       "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&selected->id), nearest_buf, GNUNET_CRYPTO_hash_matching_bits(&nearest->id.hashPubKey, message_context->key), distance(&nearest->id.hashPubKey, message_context->key));
3571           GNUNET_free(nearest_buf);
3572 #endif
3573 #if DEBUG_DHT_ROUTING
3574           if ((debug_routes_extended) && (dhtlog_handle != NULL))
3575             {
3576               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3577                                            message_context->hop_count, GNUNET_NO,
3578                                            &my_identity, &message_context->key, message_context->peer,
3579                                            &selected->id);
3580             }
3581 #endif
3582           forward_message(msg, selected, message_context);
3583         }
3584     }
3585
3586   if (message_context->bloom != NULL)
3587     {
3588       GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3589       GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3590     }
3591 }
3592
3593
3594
3595 /**
3596  * Main function that handles whether or not to route a message to other
3597  * peers.
3598  *
3599  * @param msg the message to be routed
3600  * @param message_context the context containing all pertinent information about the message
3601  */
3602 static void
3603 demultiplex_message(const struct GNUNET_MessageHeader *msg,
3604                     struct DHT_MessageContext *message_context)
3605 {
3606   message_context->closest = am_closest_peer(&message_context->key, NULL); 
3607   switch (ntohs(msg->type))
3608     {
3609     case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3610       cache_response (message_context);
3611       handle_dht_get (msg, message_context);
3612       break;
3613     case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3614       increment_stats(STAT_PUTS);
3615       handle_dht_put (msg, message_context);
3616       break;
3617     case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3618       increment_stats(STAT_FIND_PEER);
3619       if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3620       {
3621         cache_response (message_context);
3622         if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3623           handle_dht_find_peer (msg, message_context);
3624       }
3625       else
3626         route_message (msg, message_context);
3627 #if DEBUG_DHT_ROUTING
3628       if (message_context->hop_count == 0) /* Locally initiated request */
3629         {
3630           if ((debug_routes) && (dhtlog_handle != NULL))
3631             {
3632               dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3633               dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3634                                            message_context->hop_count, GNUNET_NO, &my_identity,
3635                                            &message_context->key);
3636             }
3637         }
3638 #endif
3639       break;
3640     default:
3641       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3642                   "`%s': Message type (%d) not handled, forwarding anyway!\n", "DHT", ntohs(msg->type));
3643       route_message (msg, message_context);
3644     }
3645 }
3646
3647
3648
3649
3650 /**
3651  * Iterator for local get request results,
3652  *
3653  * @param cls closure for iterator, NULL
3654  * @param exp when does this value expire?
3655  * @param key the key this data is stored under
3656  * @param size the size of the data identified by key
3657  * @param data the actual data
3658  * @param type the type of the data
3659  *
3660  * @return GNUNET_OK to continue iteration, anything else
3661  * to stop iteration.
3662  */
3663 static int
3664 republish_content_iterator (void *cls,
3665                             struct GNUNET_TIME_Absolute exp,
3666                             const GNUNET_HashCode * key,
3667                             size_t size, const char *data, uint32_t type)
3668 {
3669
3670   struct DHT_MessageContext *new_msg_ctx;
3671   struct GNUNET_DHT_PutMessage *put_msg;
3672 #if DEBUG_DHT
3673   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3674               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3675 #endif
3676   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3677
3678   put_msg =
3679     GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3680   put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3681   put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3682   put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3683   put_msg->type = htons (type);
3684   memcpy (&put_msg[1], data, size);
3685   new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3686   new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3687   new_msg_ctx->msg_options = ntohl (0);
3688   new_msg_ctx->network_size = estimate_diameter();
3689   new_msg_ctx->peer = &my_identity;
3690   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3691   new_msg_ctx->hop_count = 0;
3692   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3693   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3694   increment_stats(STAT_PUT_START);
3695   demultiplex_message(&put_msg->header, new_msg_ctx);
3696
3697   GNUNET_free(new_msg_ctx);
3698   GNUNET_free (put_msg);
3699   return GNUNET_OK;
3700 }
3701
3702 /**
3703  * Task used to republish data.
3704  *
3705  * @param cls closure (a struct RepublishContext)
3706  * @param tc runtime context for this task
3707  */
3708 static void
3709 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3710 {
3711   struct RepublishContext *put_context = cls;
3712
3713   unsigned int results;
3714
3715   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3716     {
3717       GNUNET_free(put_context);
3718       return;
3719     }
3720
3721   GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3722   results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3723   if (results == 0) /* Data must have expired */
3724     GNUNET_free(put_context);
3725   else /* Reschedule task for next time period */
3726     GNUNET_SCHEDULER_add_delayed(dht_republish_frequency, &republish_content, put_context);
3727
3728 }
3729
3730
3731 /**
3732  * Iterator over hash map entries.
3733  *
3734  * @param cls client to search for in source routes
3735  * @param key current key code (ignored)
3736  * @param value value in the hash map, a DHTQueryRecord
3737  * @return GNUNET_YES if we should continue to
3738  *         iterate,
3739  *         GNUNET_NO if not.
3740  */
3741 static int find_client_records (void *cls,
3742                                 const GNUNET_HashCode * key, void *value)
3743 {
3744   struct ClientList *client = cls;
3745   struct DHTQueryRecord *record = value;
3746   struct DHTRouteSource *pos;
3747   pos = record->head;
3748   while (pos != NULL)
3749     {
3750       if (pos->client == client)
3751         break;
3752       pos = pos->next;
3753     }
3754   if (pos != NULL)
3755     {
3756       GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3757       GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3758       if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3759         GNUNET_SCHEDULER_cancel(pos->delete_task);
3760
3761       if (pos->find_peers_responded != NULL)
3762         GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3763       GNUNET_free(pos);
3764     }
3765   if (record->head == NULL) /* No more entries in DLL */
3766     {
3767       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3768       GNUNET_free(record);
3769     }
3770   return GNUNET_YES;
3771 }
3772
3773 /**
3774  * Functions with this signature are called whenever a client
3775  * is disconnected on the network level.
3776  *
3777  * @param cls closure (NULL for dht)
3778  * @param client identification of the client; NULL
3779  *        for the last call when the server is destroyed
3780  */
3781 static void handle_client_disconnect (void *cls,
3782                                       struct GNUNET_SERVER_Client* client)
3783 {
3784   struct ClientList *pos = client_list;
3785   struct ClientList *prev;
3786   struct ClientList *found;
3787   struct PendingMessage *reply;
3788
3789   prev = NULL;
3790   found = NULL;
3791   while (pos != NULL)
3792     {
3793       if (pos->client_handle == client)
3794         {
3795           if (prev != NULL)
3796             prev->next = pos->next;
3797           else
3798             client_list = pos->next;
3799           found = pos;
3800           break;
3801         }
3802       prev = pos;
3803       pos = pos->next;
3804     }
3805
3806   if (found != NULL)
3807     {
3808       while(NULL != (reply = found->pending_head))
3809         {
3810           GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3811           GNUNET_free(reply);
3812         }
3813       GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3814       GNUNET_free(found);
3815     }
3816 }
3817
3818 /**
3819  * Find a client if it exists, add it otherwise.
3820  *
3821  * @param client the server handle to the client
3822  *
3823  * @return the client if found, a new client otherwise
3824  */
3825 static struct ClientList *
3826 find_active_client (struct GNUNET_SERVER_Client *client)
3827 {
3828   struct ClientList *pos = client_list;
3829   struct ClientList *ret;
3830
3831   while (pos != NULL)
3832     {
3833       if (pos->client_handle == client)
3834         return pos;
3835       pos = pos->next;
3836     }
3837
3838   ret = GNUNET_malloc (sizeof (struct ClientList));
3839   ret->client_handle = client;
3840   ret->next = client_list;
3841   client_list = ret;
3842
3843   return ret;
3844 }
3845
3846 /**
3847  * Task to send a malicious put message across the network.
3848  *
3849  * @param cls closure for this task
3850  * @param tc the context under which the task is running
3851  */
3852 static void
3853 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3854 {
3855   static struct GNUNET_DHT_PutMessage put_message;
3856   static struct DHT_MessageContext message_context;
3857   static GNUNET_HashCode key;
3858   uint32_t random_key;
3859
3860   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3861     return;
3862
3863   put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3864   put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3865   put_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3866   put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3867   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3868   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3869   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3870   memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3871   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3872   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3873   message_context.msg_options = ntohl (0);
3874   message_context.network_size = estimate_diameter();
3875   message_context.peer = &my_identity;
3876   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3877   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3878 #if DEBUG_DHT_ROUTING
3879   if (dhtlog_handle != NULL)
3880     dhtlog_handle->insert_dhtkey(NULL, &key);
3881 #endif
3882   increment_stats(STAT_PUT_START);
3883   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3884   demultiplex_message(&put_message.header, &message_context);
3885   GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3886
3887 }
3888
3889 /**
3890  * Task to send a malicious put message across the network.
3891  *
3892  * @param cls closure for this task
3893  * @param tc the context under which the task is running
3894  */
3895 static void
3896 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3897 {
3898   static struct GNUNET_DHT_GetMessage get_message;
3899   struct DHT_MessageContext message_context;
3900   static GNUNET_HashCode key;
3901   uint32_t random_key;
3902
3903   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3904     return;
3905
3906   get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3907   get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3908   get_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3909   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3910   message_context.client = NULL;
3911   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3912   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3913   memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3914   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3915   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3916   message_context.msg_options = ntohl (0);
3917   message_context.network_size = estimate_diameter();
3918   message_context.peer = &my_identity;
3919   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3920   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3921 #if DEBUG_DHT_ROUTING
3922   if (dhtlog_handle != NULL)
3923     dhtlog_handle->insert_dhtkey(NULL, &key);
3924 #endif
3925   increment_stats(STAT_GET_START);
3926   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3927   demultiplex_message (&get_message.header, &message_context);
3928   GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3929 }
3930
3931 /**
3932  * Iterator over hash map entries.
3933  *
3934  * @param cls closure
3935  * @param key current key code
3936  * @param value value in the hash map
3937  * @return GNUNET_YES if we should continue to
3938  *         iterate,
3939  *         GNUNET_NO if not.
3940  */
3941 static int
3942 add_known_to_bloom (void *cls,
3943                     const GNUNET_HashCode * key,
3944                     void *value)
3945 {
3946   struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3947   GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3948   return GNUNET_YES;
3949 }
3950
3951 /**
3952  * Task to send a find peer message for our own peer identifier
3953  * so that we can find the closest peers in the network to ourselves
3954  * and attempt to connect to them.
3955  *
3956  * @param cls closure for this task
3957  * @param tc the context under which the task is running
3958  */
3959 static void
3960 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3961 {
3962   struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3963   struct DHT_MessageContext message_context;
3964   struct GNUNET_TIME_Relative next_send_time;
3965   struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3966 #if COUNT_INTERVAL
3967   struct GNUNET_TIME_Relative time_diff;
3968   struct GNUNET_TIME_Absolute end;
3969   double multiplier;
3970   double count_per_interval;
3971 #endif
3972   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3973     return;
3974
3975   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! */
3976     {
3977       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3978       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3979                                     &send_find_peer_message, NULL);
3980       newly_found_peers = 0;
3981       return;
3982     }
3983     
3984   increment_stats(STAT_FIND_PEER_START);
3985 #if COUNT_INTERVAL
3986   end = GNUNET_TIME_absolute_get();
3987   time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3988
3989   if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
3990     {
3991       multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
3992       count_per_interval = find_peer_context.count / multiplier;
3993     }
3994   else
3995     {
3996       multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
3997       count_per_interval = find_peer_context.count * multiplier;
3998     }
3999 #endif
4000
4001 #if FIND_PEER_WITH_HELLO
4002   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4003   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4004   memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4005 #else
4006   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
4007   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
4008 #endif
4009   find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4010   temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4011   GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
4012   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
4013   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4014   memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
4015   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
4016   message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4017   message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4018   message_context.network_size = estimate_diameter();
4019   message_context.peer = &my_identity;
4020   message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4021   message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4022
4023   demultiplex_message(&find_peer_msg->header, &message_context);
4024   GNUNET_free(find_peer_msg);
4025   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4026               "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
4027               "FIND PEER");
4028   if (newly_found_peers < bucket_size)
4029     {
4030       next_send_time.rel_value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4031                               GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4032                                                        DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4033     }
4034   else
4035     {
4036       next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4037                              GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4038                                                       DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4039     }
4040
4041   GNUNET_assert (next_send_time.rel_value != 0);
4042   find_peer_context.count = 0;
4043   newly_found_peers = 0;
4044   find_peer_context.start = GNUNET_TIME_absolute_get();
4045   if (GNUNET_YES == do_find_peer)
4046   {
4047     GNUNET_SCHEDULER_add_delayed (next_send_time,
4048                                   &send_find_peer_message, NULL);
4049   }
4050 }
4051
4052 /**
4053  * Handler for any generic DHT messages, calls the appropriate handler
4054  * depending on message type, sends confirmation if responses aren't otherwise
4055  * expected.
4056  *
4057  * @param cls closure for the service
4058  * @param client the client we received this message from
4059  * @param message the actual message received
4060  */
4061 static void
4062 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4063                                 const struct GNUNET_MessageHeader *message)
4064 {
4065   const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
4066   const struct GNUNET_MessageHeader *enc_msg;
4067   struct DHT_MessageContext message_context;
4068
4069   enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4070 #if DEBUG_DHT
4071   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4072               "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4073               my_short_id, 
4074               "DHT",
4075               "GENERIC",
4076               ntohs (message->type), 
4077               GNUNET_h2s (&dht_msg->key),
4078               GNUNET_ntohll (dht_msg->unique_id));
4079 #endif
4080 #if DEBUG_DHT_ROUTING
4081   if (dhtlog_handle != NULL)
4082     dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4083 #endif
4084   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4085   message_context.client = find_active_client (client);
4086   memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
4087   message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4088   message_context.replication = ntohl (dht_msg->desired_replication_level);
4089   message_context.msg_options = ntohl (dht_msg->options);
4090   message_context.network_size = estimate_diameter();
4091   message_context.peer = &my_identity;
4092   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
4093   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4094   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4095     increment_stats(STAT_GET_START);
4096   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4097     increment_stats(STAT_PUT_START);
4098   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4099     increment_stats(STAT_FIND_PEER_START);
4100
4101   demultiplex_message(enc_msg, &message_context);
4102
4103   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4104
4105 }
4106
4107 /**
4108  * Handler for any locally received DHT control messages,
4109  * sets malicious flags mostly for now.
4110  *
4111  * @param cls closure for the service
4112  * @param client the client we received this message from
4113  * @param message the actual message received
4114  *
4115  */
4116 static void
4117 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4118                             const struct GNUNET_MessageHeader *message)
4119 {
4120   const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4121       (const struct GNUNET_DHT_ControlMessage *) message;
4122 #if DEBUG_DHT
4123   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4124               "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4125               "CONTROL", ntohs(dht_control_msg->command));
4126 #endif
4127
4128   switch (ntohs(dht_control_msg->command))
4129   {
4130   case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4131     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4132     GNUNET_SCHEDULER_add_now(&send_find_peer_message, NULL);
4133     break;
4134   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4135     if (ntohs(dht_control_msg->variable) > 0)
4136       malicious_get_frequency = ntohs(dht_control_msg->variable);
4137     if (malicious_get_frequency == 0)
4138       malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4139     if (malicious_getter != GNUNET_YES)
4140       GNUNET_SCHEDULER_add_now(&malicious_get_task, NULL);
4141     malicious_getter = GNUNET_YES;
4142     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
4143                "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4144     break;
4145   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4146     if (ntohs(dht_control_msg->variable) > 0)
4147       malicious_put_frequency = ntohs(dht_control_msg->variable);
4148     if (malicious_put_frequency == 0)
4149       malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4150     if (malicious_putter != GNUNET_YES)
4151       GNUNET_SCHEDULER_add_now(&malicious_put_task, NULL);
4152     malicious_putter = GNUNET_YES;
4153     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4154                "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4155     break;
4156   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4157 #if DEBUG_DHT_ROUTING
4158     if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4159       dhtlog_handle->set_malicious(&my_identity);
4160 #endif
4161     malicious_dropper = GNUNET_YES;
4162     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4163                "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4164     break;
4165   default:
4166     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4167                "%s:%s Unknown control command type `%d'!\n", 
4168                my_short_id, "DHT",
4169                ntohs(dht_control_msg->command));
4170     break;
4171   }
4172
4173   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4174 }
4175
4176 /**
4177  * Handler for any generic DHT stop messages, calls the appropriate handler
4178  * depending on message type (if processed locally)
4179  *
4180  * @param cls closure for the service
4181  * @param client the client we received this message from
4182  * @param message the actual message received
4183  *
4184  */
4185 static void
4186 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4187                             const struct GNUNET_MessageHeader *message)
4188 {
4189
4190   const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4191     (const struct GNUNET_DHT_StopMessage *) message;
4192   struct DHTQueryRecord *record;
4193   struct DHTRouteSource *pos;
4194 #if DEBUG_DHT
4195   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4196               "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4197               "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4198 #endif
4199   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
4200   if (record != NULL)
4201     {
4202       pos = record->head;
4203
4204       while (pos != NULL)
4205         {
4206           if ((pos->client != NULL) && (pos->client->client_handle == client))
4207             {
4208               GNUNET_SCHEDULER_cancel(pos->delete_task);
4209               pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4210               GNUNET_SCHEDULER_add_now(&remove_forward_entry, pos);
4211             }
4212           pos = pos->next;
4213         }
4214     }
4215
4216   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4217 }
4218
4219
4220 /**
4221  * Core handler for p2p route requests.
4222  */
4223 static int
4224 handle_dht_p2p_route_request (void *cls,
4225                               const struct GNUNET_PeerIdentity *peer,
4226                               const struct GNUNET_MessageHeader *message,
4227                               struct GNUNET_TIME_Relative latency, uint32_t distance)
4228 {
4229 #if DEBUG_DHT
4230   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4231               "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4232 #endif
4233   struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4234   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4235   struct DHT_MessageContext *message_context;
4236
4237   if (get_max_send_delay().rel_value > MAX_REQUEST_TIME.rel_value)
4238   {
4239     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
4240     increment_stats("# route requests dropped due to high load");
4241     decrease_max_send_delay(get_max_send_delay());
4242     return GNUNET_YES;
4243   }
4244
4245   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4246     {
4247 #if DEBUG_PING
4248       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4249 #endif
4250       return GNUNET_YES;
4251     }
4252
4253   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4254     {
4255       GNUNET_break_op(0);
4256       return GNUNET_YES;
4257     }
4258   message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4259   message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4260   GNUNET_assert(message_context->bloom != NULL);
4261   message_context->hop_count = ntohl(incoming->hop_count);
4262   memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
4263   message_context->replication = ntohl(incoming->desired_replication_level);
4264   message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
4265   message_context->msg_options = ntohl(incoming->options);
4266   message_context->network_size = ntohl(incoming->network_size);
4267   message_context->peer = peer;
4268   message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4269   message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4270   demultiplex_message(enc_msg, message_context);
4271   GNUNET_free(message_context);
4272   return GNUNET_YES;
4273 }
4274
4275
4276 /**
4277  * Core handler for p2p route results.
4278  */
4279 static int
4280 handle_dht_p2p_route_result (void *cls,
4281                              const struct GNUNET_PeerIdentity *peer,
4282                              const struct GNUNET_MessageHeader *message,
4283                              struct GNUNET_TIME_Relative latency, uint32_t distance)
4284 {
4285 #if DEBUG_DHT
4286   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4287               "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4288 #endif
4289   struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4290   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4291   struct DHT_MessageContext message_context;
4292
4293   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4294     {
4295       GNUNET_break_op(0);
4296       return GNUNET_YES;
4297     }
4298
4299   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4300   // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4301   message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4302   GNUNET_assert(message_context.bloom != NULL);
4303   memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
4304   message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
4305   message_context.msg_options = ntohl(incoming->options);
4306   message_context.hop_count = ntohl(incoming->hop_count);
4307   message_context.peer = peer;
4308   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
4309   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4310   route_result_message(enc_msg, &message_context);
4311   return GNUNET_YES;
4312 }
4313
4314
4315 /**
4316  * Receive the HELLO from transport service,
4317  * free current and replace if necessary.
4318  *
4319  * @param cls NULL
4320  * @param message HELLO message of peer
4321  */
4322 static void
4323 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4324 {
4325 #if DEBUG_DHT
4326   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4327               "Received our `%s' from transport service\n",
4328               "HELLO");
4329 #endif
4330
4331   GNUNET_assert (message != NULL);
4332   GNUNET_free_non_null(my_hello);
4333   my_hello = GNUNET_malloc(ntohs(message->size));
4334   memcpy(my_hello, message, ntohs(message->size));
4335 }
4336
4337
4338 /**
4339  * Task run during shutdown.
4340  *
4341  * @param cls unused
4342  * @param tc unused
4343  */
4344 static void
4345 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4346 {
4347   int bucket_count;
4348   struct PeerInfo *pos;
4349
4350   if (transport_handle != NULL)
4351     {
4352       GNUNET_free_non_null(my_hello);
4353       GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4354       GNUNET_TRANSPORT_disconnect(transport_handle);
4355     }
4356   for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4357     {
4358       while (k_buckets[bucket_count].head != NULL)
4359         {
4360           pos = k_buckets[bucket_count].head;
4361 #if DEBUG_DHT
4362           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4363                       "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4364 #endif
4365           delete_peer(pos, bucket_count);
4366         }
4367     }
4368   if (coreAPI != NULL)
4369     {
4370 #if DEBUG_DHT
4371       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4372                   "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4373 #endif
4374       GNUNET_CORE_disconnect (coreAPI);
4375       coreAPI = NULL;
4376     }
4377   if (datacache != NULL)
4378     {
4379 #if DEBUG_DHT
4380       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4381                   "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4382 #endif
4383       GNUNET_DATACACHE_destroy (datacache);
4384       datacache = NULL;
4385     }
4386   if (stats != NULL)
4387     {
4388       GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4389       stats = NULL;
4390     }
4391   if (dhtlog_handle != NULL)
4392     {
4393       GNUNET_DHTLOG_disconnect(dhtlog_handle);
4394       dhtlog_handle = NULL;
4395     }
4396   if (block_context != NULL)
4397     {
4398       GNUNET_BLOCK_context_destroy (block_context);
4399       block_context = NULL;
4400     }
4401   GNUNET_free_non_null(my_short_id);
4402   my_short_id = NULL;
4403 }
4404
4405
4406 /**
4407  * To be called on core init/fail.
4408  *
4409  * @param cls service closure
4410  * @param server handle to the server for this service
4411  * @param identity the public identity of this peer
4412  * @param publicKey the public key of this peer
4413  */
4414 void
4415 core_init (void *cls,
4416            struct GNUNET_CORE_Handle *server,
4417            const struct GNUNET_PeerIdentity *identity,
4418            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4419 {
4420
4421   if (server == NULL)
4422     {
4423 #if DEBUG_DHT
4424   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4425               "%s: Connection to core FAILED!\n", "dht",
4426               GNUNET_i2s (identity));
4427 #endif
4428       GNUNET_SCHEDULER_cancel (cleanup_task);
4429       GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4430       return;
4431     }
4432 #if DEBUG_DHT
4433   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4434               "%s: Core connection initialized, I am peer: %s\n", "dht",
4435               GNUNET_i2s (identity));
4436 #endif
4437
4438   /* Copy our identity so we can use it */
4439   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4440   if (my_short_id != NULL)
4441     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4442   my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4443   /* Set the server to local variable */
4444   coreAPI = server;
4445
4446   if (dhtlog_handle != NULL)
4447     dhtlog_handle->insert_node (NULL, &my_identity);
4448 }
4449
4450
4451 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4452   {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4453   {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4454   {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4455   {NULL, NULL, 0, 0}
4456 };
4457
4458
4459 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4460   {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4461   {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4462   {NULL, 0, 0}
4463 };
4464
4465
4466 /**
4467  * Method called whenever a peer connects.
4468  *
4469  * @param cls closure
4470  * @param peer peer identity this notification is about
4471  * @param latency reported latency of the connection with peer
4472  * @param distance reported distance (DV) to peer
4473  */
4474 void handle_core_connect (void *cls,
4475                           const struct GNUNET_PeerIdentity * peer,
4476                           struct GNUNET_TIME_Relative latency,
4477                           uint32_t distance)
4478 {
4479   struct PeerInfo *ret;
4480
4481 #if DEBUG_DHT
4482   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4483               "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4484 #endif
4485
4486   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4487     {
4488       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));
4489       return;
4490     }
4491
4492   if (datacache != NULL)
4493     GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, GNUNET_BLOCK_TYPE_DHT_HELLO, GNUNET_TIME_absolute_get_forever());
4494   ret = try_add_peer(peer,
4495                      find_current_bucket(&peer->hashPubKey),
4496                      latency,
4497                      distance);
4498   if (ret != NULL)
4499     {
4500       newly_found_peers++;
4501       GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4502     }
4503 #if DEBUG_DHT
4504     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4505                 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4506 #endif
4507 }
4508
4509
4510 /**
4511  * Method called whenever a peer disconnects.
4512  *
4513  * @param cls closure
4514  * @param peer peer identity this notification is about
4515  */
4516 void handle_core_disconnect (void *cls,
4517                              const struct
4518                              GNUNET_PeerIdentity * peer)
4519 {
4520   struct PeerInfo *to_remove;
4521   int current_bucket;
4522
4523   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");
4524
4525   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4526     {
4527       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));
4528       return;
4529     }
4530   increment_stats(STAT_DISCONNECTS);
4531   GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4532   to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4533   GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4534   current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4535   delete_peer(to_remove, current_bucket);
4536 }
4537
4538
4539 /**
4540  * Process dht requests.
4541  *
4542  * @param cls closure
4543  * @param server the initialized server
4544  * @param c configuration to use
4545  */
4546 static void
4547 run (void *cls,
4548      struct GNUNET_SERVER_Handle *server,
4549      const struct GNUNET_CONFIGURATION_Handle *c)
4550 {
4551   struct GNUNET_TIME_Relative next_send_time;
4552   unsigned long long temp_config_num;
4553   char *converge_modifier_buf;
4554
4555   cfg = c;
4556   datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4557   GNUNET_SERVER_add_handlers (server, plugin_handlers);
4558   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4559   coreAPI = GNUNET_CORE_connect (cfg,   /* Main configuration */
4560                                  GNUNET_TIME_UNIT_FOREVER_REL,
4561                                  NULL,  /* Closure passed to DHT functions */
4562                                  &core_init,    /* Call core_init once connected */
4563                                  &handle_core_connect,  /* Handle connects */
4564                                  &handle_core_disconnect,  /* remove peers on disconnects */
4565                                  NULL,  /* Do we care about "status" updates? */
4566                                  NULL,  /* Don't want notified about all incoming messages */
4567                                  GNUNET_NO,     /* For header only inbound notification */
4568                                  NULL,  /* Don't want notified about all outbound messages */
4569                                  GNUNET_NO,     /* For header only outbound notification */
4570                                  core_handlers);        /* Register these handlers */
4571
4572   if (coreAPI == NULL)
4573     return;
4574   transport_handle = GNUNET_TRANSPORT_connect(cfg,
4575                                               NULL, NULL, NULL, NULL, NULL);
4576   if (transport_handle != NULL)
4577     GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4578   else
4579     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4580                "Failed to connect to transport service!\n");
4581   block_context = GNUNET_BLOCK_context_create (cfg);
4582   lowest_bucket = MAX_BUCKETS - 1;
4583   forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4584   forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4585   all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4586   recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4587   GNUNET_assert(all_known_peers != NULL);
4588   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4589     {
4590       debug_routes = GNUNET_YES;
4591     }
4592
4593   if (GNUNET_YES ==
4594       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4595                                            "strict_kademlia"))
4596     {
4597       strict_kademlia = GNUNET_YES;
4598     }
4599
4600   if (GNUNET_YES ==
4601       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4602                                            "stop_on_closest"))
4603     {
4604       stop_on_closest = GNUNET_YES;
4605     }
4606
4607   if (GNUNET_YES ==
4608       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4609                                            "stop_found"))
4610     {
4611       stop_on_found = GNUNET_YES;
4612     }
4613
4614   if (GNUNET_YES ==
4615       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4616                                            "malicious_getter"))
4617     {
4618       malicious_getter = GNUNET_YES;
4619       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4620                                             "MALICIOUS_GET_FREQUENCY",
4621                                             &malicious_get_frequency))
4622         malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4623     }
4624
4625   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4626                                         "MAX_HOPS",
4627                                         &max_hops))
4628     {
4629       max_hops = DEFAULT_MAX_HOPS;
4630     }
4631
4632   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4633                                                           "USE_MAX_HOPS"))
4634     {
4635       use_max_hops = GNUNET_YES;
4636     }
4637
4638   if (GNUNET_YES ==
4639       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4640                                            "malicious_putter"))
4641     {
4642       malicious_putter = GNUNET_YES;
4643       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4644                                             "MALICIOUS_PUT_FREQUENCY",
4645                                             &malicious_put_frequency))
4646         malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4647     }
4648
4649   dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
4650   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4651     {
4652       dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4653     }
4654
4655   if (GNUNET_YES ==
4656           GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4657                                                "malicious_dropper"))
4658     {
4659       malicious_dropper = GNUNET_YES;
4660     }
4661
4662   if (GNUNET_YES ==
4663         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4664                                              "republish"))
4665     do_republish = GNUNET_NO;
4666
4667   if (GNUNET_NO ==
4668         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4669                                              "do_find_peer"))
4670     {
4671       do_find_peer = GNUNET_NO;
4672     }
4673   else
4674     do_find_peer = GNUNET_YES;
4675
4676   if (GNUNET_YES ==
4677         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4678                                              "use_real_distance"))
4679     use_real_distance = GNUNET_YES;
4680
4681   if (GNUNET_YES ==
4682       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4683                                            "mysql_logging_extended"))
4684     {
4685       debug_routes = GNUNET_YES;
4686       debug_routes_extended = GNUNET_YES;
4687     }
4688
4689 #if DEBUG_DHT_ROUTING
4690   if (GNUNET_YES == debug_routes)
4691     {
4692       dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4693       if (dhtlog_handle == NULL)
4694         {
4695           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4696                       "Could not connect to mysql logging server, logging will not happen!");
4697         }
4698     }
4699 #endif
4700
4701   converge_option = DHT_CONVERGE_SQUARE;
4702   if (GNUNET_YES ==
4703       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4704                                            "converge_linear"))
4705     {
4706       converge_option = DHT_CONVERGE_LINEAR;
4707     }
4708   else if (GNUNET_YES ==
4709         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4710                                              "converge_exponential"))
4711     {
4712       converge_option = DHT_CONVERGE_EXPONENTIAL;
4713     }
4714   else if (GNUNET_YES ==
4715         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4716                                              "converge_random"))
4717     {
4718       converge_option = DHT_CONVERGE_RANDOM;
4719     }
4720   else if (GNUNET_YES ==
4721         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4722                                              "converge_binary"))
4723     {
4724       converge_option = DHT_CONVERGE_BINARY;
4725     }
4726
4727   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4728     {
4729       if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4730         {
4731           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4732           converge_modifier = 0.0;
4733         }
4734       GNUNET_free(converge_modifier_buf);
4735     }
4736
4737   stats = GNUNET_STATISTICS_create("dht", cfg);
4738
4739   if (stats != NULL)
4740     {
4741       GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4742       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4743       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4744       GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4745       GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4746       GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4747       GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4748       GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4749       GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4750       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4751       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4752       GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4753       GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4754       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4755       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4756       GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4757       GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4758       GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4759       GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4760       GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4761     }
4762   /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4763   recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4764   recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4765   if (GNUNET_YES == do_find_peer)
4766   {
4767     next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4768                            GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4769                                                     (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4770     find_peer_context.start = GNUNET_TIME_absolute_get();
4771     GNUNET_SCHEDULER_add_delayed (next_send_time,
4772                                   &send_find_peer_message, &find_peer_context);
4773   }
4774
4775   /* Scheduled the task to clean up when shutdown is called */
4776   cleanup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4777                                                &shutdown_task, NULL);
4778 }
4779
4780 /**
4781  * The main function for the dht service.
4782  *
4783  * @param argc number of arguments from the command line
4784  * @param argv command line arguments
4785  * @return 0 ok, 1 on error
4786  */
4787 int
4788 main (int argc, char *const *argv)
4789 {
4790   int ret;
4791
4792   ret = (GNUNET_OK ==
4793          GNUNET_SERVICE_run (argc,
4794                              argv,
4795                              "dht",
4796                              GNUNET_SERVICE_OPTION_NONE,
4797                              &run, NULL)) ? 0 : 1;
4798   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap));
4799   GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap));
4800   GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4801   GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4802   GNUNET_CONTAINER_heap_destroy (recent.minHeap);
4803   return ret;
4804 }