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