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