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