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