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