allow bucket size, kademlia replication to be set by configuration, increase base...
[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     return;
2604 #endif
2605   data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2606   ret = GNUNET_BLOCK_get_key (block_context,
2607                               put_type,
2608                               &put_msg[1],
2609                               data_size,
2610                               &key);
2611   if (GNUNET_NO == ret)
2612     {
2613       /* invalid reply */
2614       GNUNET_break_op (0);
2615       return;
2616     }
2617   if ( (GNUNET_YES == ret) &&
2618        (0 != memcmp (&key,
2619                      &msg_ctx->key,
2620                      sizeof (GNUNET_HashCode))) )
2621     {
2622       /* invalid wrapper: key mismatch! */
2623       GNUNET_break_op (0);
2624       return;
2625     }
2626   /* ret == GNUNET_SYSERR means that there is no known relationship between
2627      data and the key, so we cannot check it */
2628 #if DEBUG_DHT
2629   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2630               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2631               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2632 #endif
2633 #if DEBUG_DHT_ROUTING
2634   if (msg_ctx->hop_count == 0) /* Locally initiated request */
2635     {
2636       if ((debug_routes) && (dhtlog_handle != NULL))
2637         {
2638           dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2639                                        msg_ctx->hop_count, GNUNET_NO, &my_identity,
2640                                        &msg_ctx->key);
2641         }
2642     }
2643 #endif
2644
2645   if (msg_ctx->closest != GNUNET_YES)
2646     {
2647       route_message (msg, msg_ctx);
2648       return;
2649     }
2650
2651 #if DEBUG_DHT
2652   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2653               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2654               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2655 #endif
2656
2657 #if DEBUG_DHT_ROUTING
2658   if ((debug_routes_extended) && (dhtlog_handle != NULL))
2659     {
2660       dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2661                                    msg_ctx->hop_count, GNUNET_YES,
2662                                    &my_identity, &msg_ctx->key, msg_ctx->peer,
2663                                    NULL);
2664     }
2665
2666   if ((debug_routes) && (dhtlog_handle != NULL))
2667     {
2668       dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2669                                    msg_ctx->hop_count, GNUNET_YES, &my_identity,
2670                                    &msg_ctx->key);
2671     }
2672 #endif
2673
2674   increment_stats(STAT_PUTS_INSERTED);
2675   if (datacache != NULL)
2676     {
2677       ret = GNUNET_DATACACHE_put (datacache, &msg_ctx->key, data_size,
2678                                   (char *) &put_msg[1], put_type,
2679                                   GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2680
2681       if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2682         {
2683           put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2684           memcpy(&put_context->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
2685           put_context->type = put_type;
2686           GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content, put_context);
2687         }
2688     }
2689   else
2690     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2691                 "`%s:%s': %s request received, but have no datacache!\n",
2692                 my_short_id, "DHT", "PUT");
2693
2694   if (stop_on_closest == GNUNET_NO)
2695     route_message (msg, msg_ctx);
2696 }
2697
2698 /**
2699  * Estimate the diameter of the network based
2700  * on how many buckets are currently in use.
2701  * Concept here is that the diameter of the network
2702  * is roughly the distance a message must travel in
2703  * order to reach its intended destination.  Since
2704  * at each hop we expect to get one bit closer, and
2705  * we have one bit per bucket, the number of buckets
2706  * in use should be the largest number of hops for
2707  * a successful message. (of course, this assumes we
2708  * know all peers in the network!)
2709  *
2710  * @return ballpark diameter figure
2711  */
2712 static unsigned int estimate_diameter()
2713 {
2714   return MAX_BUCKETS - lowest_bucket;
2715 }
2716
2717 /**
2718  * To how many peers should we (on average)
2719  * forward the request to obtain the desired
2720  * target_replication count (on average).
2721  *
2722  * returns: target_replication / (est. hops) + (target_replication * hop_count)
2723  * where est. hops is typically 2 * the routing table depth
2724  *
2725  * @param hop_count number of hops the message has traversed
2726  * @param target_replication the number of total paths desired
2727  *
2728  * @return Some number of peers to forward the message to
2729  */
2730 static unsigned int
2731 get_forward_count (unsigned int hop_count, size_t target_replication)
2732 {
2733   uint32_t random_value;
2734   unsigned int forward_count;
2735   float target_value;
2736   unsigned int diameter;
2737
2738   diameter = estimate_diameter ();
2739
2740   if (GNUNET_NO == use_max_hops)
2741     max_hops = (diameter + 1) * 2;
2742
2743   /**
2744    * If we are behaving in strict kademlia mode, send multiple initial requests,
2745    * but then only send to 1 or 0 peers based strictly on the number of hops.
2746    */
2747   if (strict_kademlia == GNUNET_YES)
2748     {
2749       if (hop_count == 0)
2750         return kademlia_replication;
2751       else if (hop_count < max_hops)
2752         return 1;
2753       else
2754         return 0;
2755     }
2756
2757   /* FIXME: the smaller we think the network is the more lenient we should be for
2758    * routing right?  The estimation below only works if we think we have reasonably
2759    * full routing tables, which for our RR topologies may not be the case!
2760    */
2761   if (hop_count > max_hops)
2762     {
2763 #if DEBUG_DHT
2764       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2765                   "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2766                   "DHT", estimate_diameter(), lowest_bucket);
2767 #endif
2768       return 0;
2769     }
2770
2771   random_value = 0;
2772   /* FIXME: we use diameter as the expected number of hops, but with randomized routing we will likely route to more! */
2773   target_value = target_replication / (diameter + ((float)target_replication * hop_count));
2774   if (target_value > 1)
2775     return (unsigned int)target_value;
2776   else
2777     random_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int)-1);
2778
2779   if (random_value < (target_value * (unsigned int)-1))
2780     forward_count = 2;
2781   else
2782     forward_count = 1;
2783
2784   return forward_count;
2785 }
2786
2787 /*
2788  * Check whether my identity is closer than any known peers.
2789  * If a non-null bloomfilter is given, check if this is the closest
2790  * peer that hasn't already been routed to.
2791  *
2792  * @param target hash code to check closeness to
2793  * @param bloom bloomfilter, exclude these entries from the decision
2794  *
2795  * Return GNUNET_YES if node location is closest, GNUNET_NO
2796  * otherwise.
2797  */
2798 int
2799 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2800 {
2801   int bits;
2802   int other_bits;
2803   int bucket_num;
2804   int count;
2805   struct PeerInfo *pos;
2806   unsigned int my_distance;
2807
2808   if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2809     return GNUNET_YES;
2810
2811   bucket_num = find_current_bucket(target);
2812
2813   bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2814   my_distance = distance(&my_identity.hashPubKey, target);
2815   pos = k_buckets[bucket_num].head;
2816   count = 0;
2817   while ((pos != NULL) && (count < bucket_size))
2818     {
2819       if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2820         {
2821           pos = pos->next;
2822           continue; /* Skip already checked entries */
2823         }
2824
2825       other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2826       if (other_bits > bits)
2827         return GNUNET_NO;
2828       else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2829         {
2830           if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2831             return GNUNET_YES;
2832           else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2833             return GNUNET_NO;
2834         }
2835       pos = pos->next;
2836     }
2837
2838   /* No peers closer, we are the closest! */
2839   return GNUNET_YES;
2840 }
2841
2842
2843 /**
2844  * Return this peers adjusted value based on the convergence
2845  * function chosen.  This is the key function for randomized
2846  * routing decisions.
2847  *
2848  * @param target the key of the request
2849  * @param peer the peer we would like the value of
2850  * @param hops number of hops this message has already traveled
2851  *
2852  * @return bit distance from target to peer raised to an exponent
2853  *         adjusted based on the current routing convergence algorithm
2854  *
2855  */
2856 static unsigned long long
2857 converge_distance (const GNUNET_HashCode *target,
2858                    struct PeerInfo *peer,
2859                    unsigned int hops)
2860 {
2861   unsigned long long ret;
2862   unsigned int other_matching_bits;
2863   double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
2864   double temp_modifier;
2865   double calc_value;
2866   double exponent;
2867   int curr_max_hops;
2868
2869   if (use_max_hops)
2870     curr_max_hops = max_hops;
2871   else
2872     curr_max_hops = (estimate_diameter() + 1) * 2;
2873
2874   if (converge_modifier > 0)
2875     temp_modifier = converge_modifier * base_converge_modifier;
2876   else
2877     {
2878       temp_modifier = base_converge_modifier;
2879       base_converge_modifier = 0.0;
2880     }
2881
2882   GNUNET_assert(temp_modifier > 0);
2883
2884   other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2885
2886   switch (converge_option)
2887     {
2888       case DHT_CONVERGE_RANDOM:
2889         return 1; /* Always return 1, choose equally among all peers */
2890       case DHT_CONVERGE_LINEAR:
2891         calc_value = hops * curr_max_hops * temp_modifier;
2892         break;
2893       case DHT_CONVERGE_SQUARE:
2894         /**
2895          * Simple square based curve.
2896          */
2897         calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * temp_modifier));
2898         break;
2899       case DHT_CONVERGE_EXPONENTIAL:
2900         /**
2901          * Simple exponential curve.
2902          */
2903         if (base_converge_modifier > 0)
2904           calc_value = (temp_modifier * hops * hops) / curr_max_hops;
2905         else
2906           calc_value = (hops * hops) / curr_max_hops;
2907         break;
2908       case DHT_CONVERGE_BINARY:
2909         /**
2910          * If below the cutoff, route randomly (return 1),
2911          * If above the cutoff, return the maximum possible
2912          * value first (always route to closest, because
2913          * they are sorted.)
2914          */
2915
2916         if (hops > converge_modifier) /* Past cutoff */
2917           {
2918             return ULLONG_MAX;
2919           }
2920         /* Fall through */
2921       default:
2922         return 1;
2923     }
2924
2925   /* Take the log (base e) of the number of bits matching the other peer */
2926   exponent = log(other_matching_bits);
2927
2928   /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
2929   if (exponent * calc_value >= 44.361419555836498)
2930     return ULLONG_MAX;
2931
2932   /* Clear errno and all math exceptions */
2933   errno = 0;
2934   feclearexcept(FE_ALL_EXCEPT);
2935   ret = (unsigned long long)pow(other_matching_bits, calc_value);
2936   if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2937       FE_UNDERFLOW))
2938     {
2939       if (0 != fetestexcept(FE_OVERFLOW))
2940         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2941       if (0 != fetestexcept(FE_INVALID))
2942         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2943       if (0 != fetestexcept(FE_UNDERFLOW))
2944         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2945       return 0;
2946     }
2947   else
2948     return ret;
2949 }
2950
2951 /**
2952  * Comparison function for two struct PeerInfo's
2953  * which have already had their matching bits to
2954  * some target calculated.
2955  *
2956  * @param p1 a pointer pointer to a struct PeerInfo
2957  * @param p2 a pointer pointer to a struct PeerInfo
2958  *
2959  * @return 0 if equidistant to target,
2960  *        -1 if p1 is closer,
2961  *         1 if p2 is closer
2962  */
2963 static int
2964 compare_peers (const void *p1, const void *p2)
2965 {
2966   struct PeerInfo **first = (struct PeerInfo **)p1;
2967   struct PeerInfo **second = (struct PeerInfo **)p2;
2968
2969   if ((*first)->matching_bits > (*second)->matching_bits)
2970     return -1;
2971   if ((*first)->matching_bits < (*second)->matching_bits)
2972     return 1;
2973   else
2974     return 0;
2975 }
2976
2977
2978 /**
2979  * Select a peer from the routing table that would be a good routing
2980  * destination for sending a message for "target".  The resulting peer
2981  * must not be in the set of blocked peers.<p>
2982  *
2983  * Note that we should not ALWAYS select the closest peer to the
2984  * target, peers further away from the target should be chosen with
2985  * exponentially declining probability.
2986  *
2987  * @param target the key we are selecting a peer to route to
2988  * @param bloom a bloomfilter containing entries this request has seen already
2989  *
2990  * @return Peer to route to, or NULL on error
2991  */
2992 static struct PeerInfo *
2993 select_peer (const GNUNET_HashCode * target,
2994              struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2995 {
2996   unsigned int bc;
2997   unsigned int i;
2998   unsigned int count;
2999   unsigned int offset;
3000   unsigned int my_matching_bits;
3001   int closest_bucket;
3002   struct PeerInfo *pos;
3003   struct PeerInfo *sorted_closest[bucket_size];
3004   unsigned long long temp_converge_distance;
3005   unsigned long long total_distance;
3006   unsigned long long selected;
3007 #if DEBUG_DHT > 1
3008   unsigned long long stats_total_distance;
3009   double sum;
3010 #endif
3011   /* For kademlia */
3012   unsigned int distance;
3013   unsigned int largest_distance;
3014   struct PeerInfo *chosen;
3015
3016   my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
3017
3018   total_distance = 0;
3019   if (strict_kademlia == GNUNET_YES)
3020     {
3021       largest_distance = 0;
3022       chosen = NULL;
3023       for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3024         {
3025           pos = k_buckets[bc].head;
3026           count = 0;
3027           while ((pos != NULL) && (count < bucket_size))
3028             {
3029               /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3030               if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3031                 {
3032                   distance = inverse_distance (target, &pos->id.hashPubKey);
3033                   if (distance > largest_distance)
3034                     {
3035                       chosen = pos;
3036                       largest_distance = distance;
3037                     }
3038                 }
3039               count++;
3040               pos = pos->next;
3041             }
3042         }
3043
3044       if ((largest_distance > 0) && (chosen != NULL))
3045         {
3046           GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
3047           return chosen;
3048         }
3049       else
3050         {
3051           return NULL;
3052         }
3053     }
3054
3055   /* GNUnet-style */
3056   total_distance = 0;
3057   /* Three steps: order peers in closest bucket (most matching bits).
3058    * Then go over all LOWER buckets (matching same bits we do)
3059    * Then go over all HIGHER buckets (matching less then we do)
3060    */
3061
3062   closest_bucket = find_current_bucket(target);
3063   GNUNET_assert(closest_bucket >= lowest_bucket);
3064   pos = k_buckets[closest_bucket].head;
3065   count = 0;
3066   offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3067   memset(sorted_closest, 0, sizeof(sorted_closest));
3068   /* Put any peers in the closest bucket in the sorting array */
3069   while ((pos != NULL) && (count < bucket_size))
3070     {
3071       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3072         {
3073           count++;
3074           pos = pos->next;
3075           continue; /* Ignore bloomfiltered peers */
3076         }
3077       pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
3078       sorted_closest[offset] = pos;
3079       pos = pos->next;
3080       offset++;
3081       count++;
3082     }
3083
3084   /* Sort the peers in descending order */
3085   qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
3086
3087   /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3088   for (i = 0; i < offset; i++)
3089     {
3090       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3091       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3092         break; /* Ignore bloomfiltered peers */
3093       if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3094         total_distance += temp_converge_distance;
3095       else
3096         break; /* overflow case */
3097     }
3098
3099   /* Now handle peers in lower buckets (matches same # of bits as target) */
3100   for (bc = lowest_bucket; bc < closest_bucket; bc++)
3101     {
3102       pos = k_buckets[bc].head;
3103       count = 0;
3104       while ((pos != NULL) && (count < bucket_size))
3105         {
3106           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3107             {
3108               count++;
3109               pos = pos->next;
3110               continue; /* Ignore bloomfiltered peers */
3111             }
3112           temp_converge_distance = converge_distance(target, pos, hops);
3113           if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3114             total_distance += temp_converge_distance;
3115           else
3116             break; /* overflow case */
3117           pos = pos->next;
3118           count++;
3119         }
3120     }
3121
3122   /* Now handle all the further away peers */
3123   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3124     {
3125       pos = k_buckets[bc].head;
3126       count = 0;
3127       while ((pos != NULL) && (count < bucket_size))
3128         {
3129           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3130             {
3131               count++;
3132               pos = pos->next;
3133               continue; /* Ignore bloomfiltered peers */
3134             }
3135           temp_converge_distance = converge_distance(target, pos, hops);
3136           if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3137             total_distance += temp_converge_distance;
3138           else
3139             break; /* overflow case */
3140           pos = pos->next;
3141           count++;
3142         }
3143     }
3144
3145   if (total_distance == 0) /* No peers to select from! */
3146     {
3147       increment_stats("# select_peer, total_distance == 0");
3148       return NULL;
3149     }
3150
3151 #if DEBUG_DHT_ROUTING > 1
3152   sum = 0.0;
3153   /* PRINT STATS */
3154   /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3155   stats_total_distance = 0;
3156   for (i = 0; i < offset; i++)
3157     {
3158       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3159         break; /* Ignore bloomfiltered peers */
3160       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3161       if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3162         stats_total_distance += temp_converge_distance;
3163       else
3164         break; /* overflow case */
3165       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);
3166     }
3167
3168   /* Now handle peers in lower buckets (matches same # of bits as target) */
3169   for (bc = lowest_bucket; bc < closest_bucket; bc++)
3170     {
3171       pos = k_buckets[bc].head;
3172       count = 0;
3173       while ((pos != NULL) && (count < bucket_size))
3174         {
3175           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3176             {
3177               count++;
3178               pos = pos->next;
3179               continue; /* Ignore bloomfiltered peers */
3180             }
3181           temp_converge_distance = converge_distance(target, pos, hops);
3182           if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3183             stats_total_distance += temp_converge_distance;
3184           else
3185             break; /* overflow case */
3186           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);
3187           pos = pos->next;
3188           count++;
3189         }
3190     }
3191
3192   /* Now handle all the further away peers */
3193   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3194     {
3195       pos = k_buckets[bc].head;
3196       count = 0;
3197       while ((pos != NULL) && (count < bucket_size))
3198         {
3199           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3200             {
3201               count++;
3202               pos = pos->next;
3203               continue; /* Ignore bloomfiltered peers */
3204             }
3205           temp_converge_distance = converge_distance(target, pos, hops);
3206           if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3207             stats_total_distance += temp_converge_distance;
3208           else
3209             break; /* overflow case */
3210           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);
3211           pos = pos->next;
3212           count++;
3213         }
3214     }
3215   /* END PRINT STATS */
3216 #endif
3217
3218   /* Now actually choose a peer */
3219   selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3220
3221   /* Go over closest sorted peers. */
3222   for (i = 0; i < offset; i++)
3223     {
3224       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3225         break; /* Ignore bloomfiltered peers */
3226       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3227       if (temp_converge_distance >= selected)
3228         return sorted_closest[i];
3229       else
3230         selected -= temp_converge_distance;
3231     }
3232
3233   /* Now handle peers in lower buckets (matches same # of bits as target) */
3234   for (bc = lowest_bucket; bc < closest_bucket; bc++)
3235     {
3236       pos = k_buckets[bc].head;
3237       count = 0;
3238       while ((pos != NULL) && (count < bucket_size))
3239         {
3240           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3241             {
3242               count++;
3243               pos = pos->next;
3244               continue; /* Ignore bloomfiltered peers */
3245             }
3246           temp_converge_distance = converge_distance(target, pos, hops);
3247           if (temp_converge_distance >= selected)
3248             return pos;
3249           else
3250             selected -= temp_converge_distance;
3251           pos = pos->next;
3252           count++;
3253         }
3254     }
3255
3256   /* Now handle all the further away peers */
3257   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3258     {
3259       pos = k_buckets[bc].head;
3260       count = 0;
3261       while ((pos != NULL) && (count < bucket_size))
3262         {
3263           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3264             {
3265               count++;
3266               pos = pos->next;
3267               continue; /* Ignore bloomfiltered peers */
3268             }
3269           temp_converge_distance = converge_distance(target, pos, hops);
3270           if (temp_converge_distance >= selected)
3271             return pos;
3272           else
3273             selected -= temp_converge_distance;
3274           pos = pos->next;
3275           count++;
3276         }
3277     }
3278
3279   increment_stats("# failed to select peer");
3280   return NULL;
3281 }
3282
3283
3284 /**
3285  * Task used to remove recent entries, either
3286  * after timeout, when full, or on shutdown.
3287  *
3288  * @param cls the entry to remove
3289  * @param tc context, reason, etc.
3290  */
3291 static void
3292 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3293 {
3294   struct RecentRequest *req = cls;
3295   static GNUNET_HashCode hash;
3296
3297   GNUNET_assert(req != NULL);
3298   hash_from_uid(req->uid, &hash);
3299   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3300   GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3301   GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3302   GNUNET_free(req);
3303
3304   /*
3305   if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3306   {
3307     GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3308     GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3309   }
3310   */
3311 }
3312
3313
3314 /**
3315  * Task used to remove forwarding entries, either
3316  * after timeout, when full, or on shutdown.
3317  *
3318  * @param cls the entry to remove
3319  * @param tc context, reason, etc.
3320  */
3321 static void
3322 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3323 {
3324   struct DHTRouteSource *source_info = cls;
3325   struct DHTQueryRecord *record;
3326   source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3327   record = source_info->record;
3328   GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3329
3330   if (record->head == NULL) /* No more entries in DLL */
3331     {
3332       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap, &record->key, record));
3333       GNUNET_free(record);
3334     }
3335   if (source_info->find_peers_responded != NULL)
3336     GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3337   GNUNET_free(source_info);
3338 }
3339
3340 /**
3341  * Remember this routing request so that if a reply is
3342  * received we can either forward it to the correct peer
3343  * or return the result locally.
3344  *
3345  * @param msg_ctx Context of the route request
3346  *
3347  * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3348  */
3349 static int cache_response(struct DHT_MessageContext *msg_ctx)
3350 {
3351   struct DHTQueryRecord *record;
3352   struct DHTRouteSource *source_info;
3353   struct DHTRouteSource *pos;
3354   struct GNUNET_TIME_Absolute now;
3355   unsigned int current_size;
3356
3357   current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3358
3359 #if DELETE_WHEN_FULL
3360   while (current_size >= MAX_OUTSTANDING_FORWARDS)
3361     {
3362       source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3363       GNUNET_assert(source_info != NULL);
3364       record = source_info->record;
3365       GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3366       if (record->head == NULL) /* No more entries in DLL */
3367         {
3368           GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3369           GNUNET_free(record);
3370         }
3371       if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3372         GNUNET_SCHEDULER_cancel(source_info->delete_task);
3373       if (source_info->find_peers_responded != NULL)
3374         GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3375       GNUNET_free(source_info);
3376       current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3377     }
3378 #endif
3379   /** Non-local request and have too many outstanding forwards, discard! */
3380   if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3381     return GNUNET_NO;
3382
3383   now = GNUNET_TIME_absolute_get();
3384   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3385   if (record != NULL) /* Already know this request! */
3386     {
3387       pos = record->head;
3388       while (pos != NULL)
3389         {
3390           if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3391             break; /* Already have this peer in reply list! */
3392           pos = pos->next;
3393         }
3394       if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3395         {
3396           GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.abs_value);
3397           return GNUNET_NO;
3398         }
3399     }
3400   else
3401     {
3402       record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3403       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3404       memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3405     }
3406
3407   source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3408   source_info->record = record;
3409   source_info->delete_task = GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3410   source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3411   memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3412   GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail, source_info);
3413   if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3414     {
3415       source_info->client = msg_ctx->client;
3416       now = GNUNET_TIME_absolute_get_forever();
3417     }
3418   source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.abs_value);
3419 #if DEBUG_DHT > 1
3420       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3421                   "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3422                   "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3423 #endif
3424   return GNUNET_YES;
3425 }
3426
3427
3428 /**
3429  * Main function that handles whether or not to route a message to other
3430  * peers.
3431  *
3432  * @param msg the message to be routed
3433  * @param msg_ctx the context containing all pertinent information about the message
3434  */
3435 static void
3436 route_message(const struct GNUNET_MessageHeader *msg,
3437                struct DHT_MessageContext *msg_ctx)
3438 {
3439   int i;
3440   struct PeerInfo *selected;
3441 #if DEBUG_DHT_ROUTING > 1
3442   struct PeerInfo *nearest;
3443 #endif
3444   unsigned int forward_count;
3445   struct RecentRequest *recent_req;
3446   GNUNET_HashCode unique_hash;
3447   char *stat_forward_count;
3448   char *temp_stat_str;
3449 #if DEBUG_DHT_ROUTING
3450   int ret;
3451 #endif
3452
3453   if (malicious_dropper == GNUNET_YES)
3454     {
3455 #if DEBUG_DHT_ROUTING
3456       if ((debug_routes_extended) && (dhtlog_handle != NULL))
3457         {
3458           dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3459                                        msg_ctx->hop_count, GNUNET_SYSERR,
3460                                        &my_identity, &msg_ctx->key, msg_ctx->peer,
3461                                        NULL);
3462         }
3463 #endif
3464       if (msg_ctx->bloom != NULL)
3465       {
3466         GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3467         msg_ctx->bloom = NULL;
3468       }
3469       return;
3470     }
3471
3472   increment_stats(STAT_ROUTES);
3473   forward_count = get_forward_count(msg_ctx->hop_count, msg_ctx->replication);
3474   GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3475   increment_stats(stat_forward_count);
3476   GNUNET_free(stat_forward_count);
3477   if (msg_ctx->bloom == NULL)
3478     msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3479
3480   if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3481     forward_count = 0;
3482
3483   /**
3484    * NOTICE:  In Kademlia, a find peer request goes no further if the peer doesn't return
3485    * any closer peers (which is being checked for below).  Since we are doing recursive
3486    * routing we have no choice but to stop forwarding in this case.  This means that at
3487    * any given step the request may NOT be forwarded to alpha peers (because routes will
3488    * stop and the parallel route will not be aware of it).  Of course, assuming that we
3489    * have fulfilled the Kademlia requirements for routing table fullness this will never
3490    * ever ever be a problem.
3491    *
3492    * However, is this fair?
3493    *
3494    * Since we use these requests to build our routing tables (and we build them in the
3495    * testing driver) we will ignore this restriction for FIND_PEER messages so that
3496    * routing tables still get constructed.
3497    */
3498   if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) && (msg_ctx->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3499     forward_count = 0;
3500
3501 #if DEBUG_DHT_ROUTING
3502   if (forward_count == 0)
3503     ret = GNUNET_SYSERR;
3504   else
3505     ret = GNUNET_NO;
3506
3507   if ((debug_routes_extended) && (dhtlog_handle != NULL))
3508     {
3509       dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3510                                    msg_ctx->hop_count, ret,
3511                                    &my_identity, &msg_ctx->key, msg_ctx->peer,
3512                                    NULL);
3513     }
3514 #endif
3515
3516   GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3517   hash_from_uid (msg_ctx->unique_id, &unique_hash);
3518   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3519   {
3520     recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3521     GNUNET_assert(recent_req != NULL);
3522     if (0 != memcmp(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode)))
3523       increment_stats(STAT_DUPLICATE_UID);
3524     else
3525       {
3526         increment_stats(STAT_RECENT_SEEN);
3527         GNUNET_CONTAINER_bloomfilter_or2(msg_ctx->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3528       }
3529     }
3530   else
3531     {
3532       recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3533       recent_req->uid = msg_ctx->unique_id;
3534       memcpy(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3535       recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3536       recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().abs_value);
3537       recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3538       GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3539     }
3540
3541   if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3542     {
3543       recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3544       GNUNET_assert(recent_req != NULL);
3545       GNUNET_SCHEDULER_cancel(recent_req->remove_task);
3546       GNUNET_SCHEDULER_add_now(&remove_recent, recent_req);
3547     }
3548
3549   for (i = 0; i < forward_count; i++)
3550     {
3551       selected = select_peer(&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3552
3553       if (selected != NULL)
3554         {
3555           if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &msg_ctx->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &msg_ctx->key))
3556             GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", msg_ctx->hop_count);
3557           else
3558             GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", msg_ctx->hop_count);
3559           if (temp_stat_str != NULL)
3560             {
3561               increment_stats(temp_stat_str);
3562               GNUNET_free(temp_stat_str);
3563             }
3564           GNUNET_CONTAINER_bloomfilter_add(msg_ctx->bloom, &selected->id.hashPubKey);
3565 #if DEBUG_DHT_ROUTING > 1
3566           nearest = find_closest_peer(&msg_ctx->key);
3567           nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3568           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3569                       "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3570                       "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));
3571           GNUNET_free(nearest_buf);
3572 #endif
3573 #if DEBUG_DHT_ROUTING
3574           if ((debug_routes_extended) && (dhtlog_handle != NULL))
3575             {
3576               dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3577                                            msg_ctx->hop_count, GNUNET_NO,
3578                                            &my_identity, &msg_ctx->key, msg_ctx->peer,
3579                                            &selected->id);
3580             }
3581 #endif
3582           forward_message(msg, selected, msg_ctx);
3583         }
3584     }
3585
3586   if (msg_ctx->bloom != NULL)
3587     {
3588       GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, msg_ctx->bloom, DHT_BLOOM_SIZE);
3589       GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3590       msg_ctx->bloom = NULL;
3591     }
3592 }
3593
3594
3595
3596 /**
3597  * Main function that handles whether or not to route a message to other
3598  * peers.
3599  *
3600  * @param msg the message to be routed
3601  * @param msg_ctx the context containing all pertinent information about the message
3602  */
3603 static void
3604 demultiplex_message(const struct GNUNET_MessageHeader *msg,
3605                     struct DHT_MessageContext *msg_ctx)
3606 {
3607   msg_ctx->closest = am_closest_peer(&msg_ctx->key, NULL);
3608   switch (ntohs(msg->type))
3609     {
3610     case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3611       cache_response (msg_ctx);
3612       handle_dht_get (msg, msg_ctx);
3613       break;
3614     case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3615       increment_stats(STAT_PUTS);
3616       handle_dht_put (msg, msg_ctx);
3617       break;
3618     case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3619       increment_stats(STAT_FIND_PEER);
3620       if (((msg_ctx->hop_count > 0) && (0 != memcmp(msg_ctx->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (msg_ctx->client != NULL))
3621       {
3622         cache_response (msg_ctx);
3623         if ((msg_ctx->closest == GNUNET_YES) || (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3624           handle_dht_find_peer (msg, msg_ctx);
3625       }
3626       else
3627         route_message (msg, msg_ctx);
3628 #if DEBUG_DHT_ROUTING
3629       if (msg_ctx->hop_count == 0) /* Locally initiated request */
3630         {
3631           if ((debug_routes) && (dhtlog_handle != NULL))
3632             {
3633               dhtlog_handle->insert_dhtkey(NULL, &msg_ctx->key);
3634               dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
3635                                            msg_ctx->hop_count, GNUNET_NO, &my_identity,
3636                                            &msg_ctx->key);
3637             }
3638         }
3639 #endif
3640       break;
3641     default:
3642       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3643                   "`%s': Message type (%d) not handled, forwarding anyway!\n", "DHT", ntohs(msg->type));
3644       route_message (msg, msg_ctx);
3645     }
3646 }
3647
3648
3649
3650
3651 /**
3652  * Iterator for local get request results,
3653  *
3654  * @param cls closure for iterator, NULL
3655  * @param exp when does this value expire?
3656  * @param key the key this data is stored under
3657  * @param size the size of the data identified by key
3658  * @param data the actual data
3659  * @param type the type of the data
3660  *
3661  * @return GNUNET_OK to continue iteration, anything else
3662  * to stop iteration.
3663  */
3664 static int
3665 republish_content_iterator (void *cls,
3666                             struct GNUNET_TIME_Absolute exp,
3667                             const GNUNET_HashCode * key,
3668                             size_t size, const char *data, uint32_t type)
3669 {
3670
3671   struct DHT_MessageContext *new_msg_ctx;
3672   struct GNUNET_DHT_PutMessage *put_msg;
3673 #if DEBUG_DHT
3674   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3675               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3676 #endif
3677   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3678
3679   put_msg =
3680     GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3681   put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3682   put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3683   put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3684   put_msg->type = htons (type);
3685   memcpy (&put_msg[1], data, size);
3686   new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3687   new_msg_ctx->replication = ntohl (DEFAULT_PUT_REPLICATION);
3688   new_msg_ctx->msg_options = ntohl (0);
3689   new_msg_ctx->network_size = estimate_diameter();
3690   new_msg_ctx->peer = &my_identity;
3691   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3692   new_msg_ctx->hop_count = 0;
3693   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3694   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3695   increment_stats(STAT_PUT_START);
3696   demultiplex_message(&put_msg->header, new_msg_ctx);
3697
3698   GNUNET_free(new_msg_ctx);
3699   GNUNET_free (put_msg);
3700   return GNUNET_OK;
3701 }
3702
3703 /**
3704  * Task used to republish data.
3705  *
3706  * @param cls closure (a struct RepublishContext)
3707  * @param tc runtime context for this task
3708  */
3709 static void
3710 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3711 {
3712   struct RepublishContext *put_context = cls;
3713
3714   unsigned int results;
3715
3716   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3717     {
3718       GNUNET_free(put_context);
3719       return;
3720     }
3721
3722   GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3723   results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3724   if (results == 0) /* Data must have expired */
3725     GNUNET_free(put_context);
3726   else /* Reschedule task for next time period */
3727     GNUNET_SCHEDULER_add_delayed(dht_republish_frequency, &republish_content, put_context);
3728
3729 }
3730
3731
3732 /**
3733  * Iterator over hash map entries.
3734  *
3735  * @param cls client to search for in source routes
3736  * @param key current key code (ignored)
3737  * @param value value in the hash map, a DHTQueryRecord
3738  * @return GNUNET_YES if we should continue to
3739  *         iterate,
3740  *         GNUNET_NO if not.
3741  */
3742 static int find_client_records (void *cls,
3743                                 const GNUNET_HashCode * key, void *value)
3744 {
3745   struct ClientList *client = cls;
3746   struct DHTQueryRecord *record = value;
3747   struct DHTRouteSource *pos;
3748   pos = record->head;
3749   while (pos != NULL)
3750     {
3751       if (pos->client == client)
3752         break;
3753       pos = pos->next;
3754     }
3755   if (pos != NULL)
3756     {
3757       GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3758       GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3759       if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3760         GNUNET_SCHEDULER_cancel(pos->delete_task);
3761
3762       if (pos->find_peers_responded != NULL)
3763         GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3764       GNUNET_free(pos);
3765     }
3766   if (record->head == NULL) /* No more entries in DLL */
3767     {
3768       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3769       GNUNET_free(record);
3770     }
3771   return GNUNET_YES;
3772 }
3773
3774 /**
3775  * Functions with this signature are called whenever a client
3776  * is disconnected on the network level.
3777  *
3778  * @param cls closure (NULL for dht)
3779  * @param client identification of the client; NULL
3780  *        for the last call when the server is destroyed
3781  */
3782 static void handle_client_disconnect (void *cls,
3783                                       struct GNUNET_SERVER_Client* client)
3784 {
3785   struct ClientList *pos = client_list;
3786   struct ClientList *prev;
3787   struct ClientList *found;
3788   struct PendingMessage *reply;
3789
3790   prev = NULL;
3791   found = NULL;
3792   while (pos != NULL)
3793     {
3794       if (pos->client_handle == client)
3795         {
3796           if (prev != NULL)
3797             prev->next = pos->next;
3798           else
3799             client_list = pos->next;
3800           found = pos;
3801           break;
3802         }
3803       prev = pos;
3804       pos = pos->next;
3805     }
3806
3807   if (found != NULL)
3808     {
3809       if (found->transmit_handle != NULL)
3810         GNUNET_CONNECTION_notify_transmit_ready_cancel(found->transmit_handle);
3811
3812       while(NULL != (reply = found->pending_head))
3813         {
3814           GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3815           GNUNET_free(reply);
3816         }
3817       GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3818       GNUNET_free(found);
3819     }
3820 }
3821
3822 /**
3823  * Find a client if it exists, add it otherwise.
3824  *
3825  * @param client the server handle to the client
3826  *
3827  * @return the client if found, a new client otherwise
3828  */
3829 static struct ClientList *
3830 find_active_client (struct GNUNET_SERVER_Client *client)
3831 {
3832   struct ClientList *pos = client_list;
3833   struct ClientList *ret;
3834
3835   while (pos != NULL)
3836     {
3837       if (pos->client_handle == client)
3838         return pos;
3839       pos = pos->next;
3840     }
3841
3842   ret = GNUNET_malloc (sizeof (struct ClientList));
3843   ret->client_handle = client;
3844   ret->next = client_list;
3845   client_list = ret;
3846
3847   return ret;
3848 }
3849
3850 #if HAVE_MALICIOUS
3851 /**
3852  * Task to send a malicious put message across the network.
3853  *
3854  * @param cls closure for this task
3855  * @param tc the context under which the task is running
3856  */
3857 static void
3858 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3859 {
3860   static struct GNUNET_DHT_PutMessage put_message;
3861   static struct DHT_MessageContext msg_ctx;
3862   static GNUNET_HashCode key;
3863   uint32_t random_key;
3864
3865   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3866     return;
3867   put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3868   put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3869   put_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3870   put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3871   memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3872   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3873   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3874   memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3875   msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3876   msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3877   msg_ctx.msg_options = ntohl (0);
3878   msg_ctx.network_size = estimate_diameter();
3879   msg_ctx.peer = &my_identity;
3880   msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3881   msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3882 #if DEBUG_DHT_ROUTING
3883   if (dhtlog_handle != NULL)
3884     dhtlog_handle->insert_dhtkey(NULL, &key);
3885 #endif
3886   increment_stats(STAT_PUT_START);
3887   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3888   demultiplex_message(&put_message.header, &msg_ctx);
3889   GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3890 }
3891
3892
3893 /**
3894  * Task to send a malicious put message across the network.
3895  *
3896  * @param cls closure for this task
3897  * @param tc the context under which the task is running
3898  */
3899 static void
3900 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3901 {
3902   static struct GNUNET_DHT_GetMessage get_message;
3903   struct DHT_MessageContext msg_ctx;
3904   static GNUNET_HashCode key;
3905   uint32_t random_key;
3906
3907   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3908     return;
3909
3910   get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3911   get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3912   get_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3913   memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3914   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3915   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3916   memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3917   msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3918   msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3919   msg_ctx.msg_options = ntohl (0);
3920   msg_ctx.network_size = estimate_diameter();
3921   msg_ctx.peer = &my_identity;
3922   msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3923   msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3924 #if DEBUG_DHT_ROUTING
3925   if (dhtlog_handle != NULL)
3926     dhtlog_handle->insert_dhtkey(NULL, &key);
3927 #endif
3928   increment_stats(STAT_GET_START);
3929   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3930   demultiplex_message (&get_message.header, &msg_ctx);
3931   GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3932 }
3933 #endif
3934
3935
3936 /**
3937  * Iterator over hash map entries.
3938  *
3939  * @param cls closure
3940  * @param key current key code
3941  * @param value value in the hash map
3942  * @return GNUNET_YES if we should continue to
3943  *         iterate,
3944  *         GNUNET_NO if not.
3945  */
3946 static int
3947 add_known_to_bloom (void *cls,
3948                     const GNUNET_HashCode * key,
3949                     void *value)
3950 {
3951   struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3952   GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3953   return GNUNET_YES;
3954 }
3955
3956 /**
3957  * Task to send a find peer message for our own peer identifier
3958  * so that we can find the closest peers in the network to ourselves
3959  * and attempt to connect to them.
3960  *
3961  * @param cls closure for this task
3962  * @param tc the context under which the task is running
3963  */
3964 static void
3965 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3966 {
3967   struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3968   struct DHT_MessageContext msg_ctx;
3969   struct GNUNET_TIME_Relative next_send_time;
3970   struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3971 #if COUNT_INTERVAL
3972   struct GNUNET_TIME_Relative time_diff;
3973   struct GNUNET_TIME_Absolute end;
3974   double multiplier;
3975   double count_per_interval;
3976 #endif
3977   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3978     return;
3979
3980   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! */
3981     {
3982       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3983       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3984                                     &send_find_peer_message, NULL);
3985       newly_found_peers = 0;
3986       return;
3987     }
3988     
3989   increment_stats(STAT_FIND_PEER_START);
3990 #if COUNT_INTERVAL
3991   end = GNUNET_TIME_absolute_get();
3992   time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3993
3994   if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
3995     {
3996       multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
3997       count_per_interval = find_peer_context.count / multiplier;
3998     }
3999   else
4000     {
4001       multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
4002       count_per_interval = find_peer_context.count * multiplier;
4003     }
4004 #endif
4005
4006 #if FIND_PEER_WITH_HELLO
4007   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4008   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4009   memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4010 #else
4011   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
4012   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
4013 #endif
4014   find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4015   temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4016   GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
4017   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
4018   GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
4019   memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4020   memcpy(&msg_ctx.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
4021   msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
4022   msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4023   msg_ctx.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4024   msg_ctx.network_size = estimate_diameter();
4025   msg_ctx.peer = &my_identity;
4026   msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4027   msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4028
4029   demultiplex_message(&find_peer_msg->header, &msg_ctx);
4030   GNUNET_free(find_peer_msg);
4031   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4032               "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
4033               "FIND PEER");
4034   if (newly_found_peers < bucket_size)
4035     {
4036       next_send_time.rel_value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4037                               GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4038                                                        DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4039     }
4040   else
4041     {
4042       next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4043                              GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4044                                                       DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4045     }
4046
4047   GNUNET_assert (next_send_time.rel_value != 0);
4048   find_peer_context.count = 0;
4049   newly_found_peers = 0;
4050   find_peer_context.start = GNUNET_TIME_absolute_get();
4051   if (GNUNET_YES == do_find_peer)
4052   {
4053     GNUNET_SCHEDULER_add_delayed (next_send_time,
4054                                   &send_find_peer_message, NULL);
4055   }
4056 }
4057
4058 /**
4059  * Handler for any generic DHT messages, calls the appropriate handler
4060  * depending on message type, sends confirmation if responses aren't otherwise
4061  * expected.
4062  *
4063  * @param cls closure for the service
4064  * @param client the client we received this message from
4065  * @param message the actual message received
4066  */
4067 static void
4068 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4069                                 const struct GNUNET_MessageHeader *message)
4070 {
4071   const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
4072   const struct GNUNET_MessageHeader *enc_msg;
4073   struct DHT_MessageContext msg_ctx;
4074
4075   enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4076 #if DEBUG_DHT
4077   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4078               "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4079               my_short_id, 
4080               "DHT",
4081               "GENERIC",
4082               ntohs (message->type), 
4083               GNUNET_h2s (&dht_msg->key),
4084               GNUNET_ntohll (dht_msg->unique_id));
4085 #endif
4086 #if DEBUG_DHT_ROUTING
4087   if (dhtlog_handle != NULL)
4088     dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4089 #endif
4090   memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4091   msg_ctx.client = find_active_client (client);
4092   memcpy(&msg_ctx.key, &dht_msg->key, sizeof(GNUNET_HashCode));
4093   msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4094   msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
4095   msg_ctx.msg_options = ntohl (dht_msg->options);
4096   msg_ctx.network_size = estimate_diameter();
4097   msg_ctx.peer = &my_identity;
4098   msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
4099   msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4100   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4101     increment_stats(STAT_GET_START);
4102   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4103     increment_stats(STAT_PUT_START);
4104   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4105     increment_stats(STAT_FIND_PEER_START);
4106
4107   demultiplex_message(enc_msg, &msg_ctx);
4108
4109   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4110
4111 }
4112
4113 /**
4114  * Handler for any locally received DHT control messages,
4115  * sets malicious flags mostly for now.
4116  *
4117  * @param cls closure for the service
4118  * @param client the client we received this message from
4119  * @param message the actual message received
4120  *
4121  */
4122 static void
4123 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4124                             const struct GNUNET_MessageHeader *message)
4125 {
4126   const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4127       (const struct GNUNET_DHT_ControlMessage *) message;
4128 #if DEBUG_DHT
4129   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4130               "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4131               "CONTROL", ntohs(dht_control_msg->command));
4132 #endif
4133
4134   switch (ntohs(dht_control_msg->command))
4135   {
4136   case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4137     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4138     GNUNET_SCHEDULER_add_now(&send_find_peer_message, NULL);
4139     break;
4140 #if HAVE_MALICIOUS
4141   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4142     if (ntohs(dht_control_msg->variable) > 0)
4143       malicious_get_frequency = ntohs(dht_control_msg->variable);
4144     if (malicious_get_frequency == 0)
4145       malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4146     if (malicious_getter != GNUNET_YES)
4147       GNUNET_SCHEDULER_add_now(&malicious_get_task, NULL);
4148     malicious_getter = GNUNET_YES;
4149     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
4150                "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4151     break;
4152   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4153     if (ntohs(dht_control_msg->variable) > 0)
4154       malicious_put_frequency = ntohs(dht_control_msg->variable);
4155     if (malicious_put_frequency == 0)
4156       malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4157     if (malicious_putter != GNUNET_YES)
4158       GNUNET_SCHEDULER_add_now(&malicious_put_task, NULL);
4159     malicious_putter = GNUNET_YES;
4160     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4161                "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4162     break;
4163   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4164 #if DEBUG_DHT_ROUTING
4165     if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4166       dhtlog_handle->set_malicious(&my_identity);
4167 #endif
4168     malicious_dropper = GNUNET_YES;
4169     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4170                "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4171     break;
4172 #endif
4173   default:
4174     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4175                "%s:%s Unknown control command type `%d'!\n", 
4176                my_short_id, "DHT",
4177                ntohs(dht_control_msg->command));
4178     break;
4179   }
4180
4181   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4182 }
4183
4184 /**
4185  * Handler for any generic DHT stop messages, calls the appropriate handler
4186  * depending on message type (if processed locally)
4187  *
4188  * @param cls closure for the service
4189  * @param client the client we received this message from
4190  * @param message the actual message received
4191  *
4192  */
4193 static void
4194 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4195                             const struct GNUNET_MessageHeader *message)
4196 {
4197
4198   const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4199     (const struct GNUNET_DHT_StopMessage *) message;
4200   struct DHTQueryRecord *record;
4201   struct DHTRouteSource *pos;
4202 #if DEBUG_DHT
4203   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4204               "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4205               "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4206 #endif
4207   record = GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &dht_stop_msg->key);
4208   if (record != NULL)
4209     {
4210       pos = record->head;
4211
4212       while (pos != NULL)
4213         {
4214           /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
4215           if ((pos->client != NULL) && (pos->client->client_handle == client))
4216             {
4217               GNUNET_SCHEDULER_cancel(pos->delete_task);
4218               pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4219               GNUNET_SCHEDULER_add_continuation (&remove_forward_entry, pos, GNUNET_SCHEDULER_REASON_PREREQ_DONE);
4220             }
4221           pos = pos->next;
4222         }
4223     }
4224
4225   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4226 }
4227
4228
4229 /**
4230  * Core handler for p2p route requests.
4231  */
4232 static int
4233 handle_dht_p2p_route_request (void *cls,
4234                               const struct GNUNET_PeerIdentity *peer,
4235                               const struct GNUNET_MessageHeader *message,
4236                               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4237 {
4238 #if DEBUG_DHT
4239   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4240               "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4241 #endif
4242   struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4243   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4244   struct DHT_MessageContext *msg_ctx;
4245
4246   if (get_max_send_delay().rel_value > MAX_REQUEST_TIME.rel_value)
4247   {
4248     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending of previous replies took too long, backing off!\n");
4249     increment_stats("# route requests dropped due to high load");
4250     decrease_max_send_delay(get_max_send_delay());
4251     return GNUNET_YES;
4252   }
4253
4254   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4255     {
4256 #if DEBUG_PING
4257       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4258 #endif
4259       return GNUNET_YES;
4260     }
4261
4262   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4263     {
4264       GNUNET_break_op(0);
4265       return GNUNET_YES;
4266     }
4267   msg_ctx = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4268   msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4269   GNUNET_assert(msg_ctx->bloom != NULL);
4270   msg_ctx->hop_count = ntohl(incoming->hop_count);
4271   memcpy(&msg_ctx->key, &incoming->key, sizeof(GNUNET_HashCode));
4272   msg_ctx->replication = ntohl(incoming->desired_replication_level);
4273   msg_ctx->unique_id = GNUNET_ntohll(incoming->unique_id);
4274   msg_ctx->msg_options = ntohl(incoming->options);
4275   msg_ctx->network_size = ntohl(incoming->network_size);
4276   msg_ctx->peer = peer;
4277   msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4278   msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4279   demultiplex_message(enc_msg, msg_ctx);
4280   if (msg_ctx->bloom != NULL)
4281   {
4282     GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4283     msg_ctx->bloom = NULL;
4284   }
4285   GNUNET_free(msg_ctx);
4286   return GNUNET_YES;
4287 }
4288
4289
4290 /**
4291  * Core handler for p2p route results.
4292  */
4293 static int
4294 handle_dht_p2p_route_result (void *cls,
4295                              const struct GNUNET_PeerIdentity *peer,
4296                              const struct GNUNET_MessageHeader *message,
4297                              const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4298 {
4299 #if DEBUG_DHT
4300   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4301               "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4302 #endif
4303   struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4304   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4305   struct DHT_MessageContext msg_ctx;
4306
4307   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4308     {
4309       GNUNET_break_op(0);
4310       return GNUNET_YES;
4311     }
4312
4313   memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4314   // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4315   msg_ctx.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4316   GNUNET_assert(msg_ctx.bloom != NULL);
4317   memcpy(&msg_ctx.key, &incoming->key, sizeof(GNUNET_HashCode));
4318   msg_ctx.unique_id = GNUNET_ntohll(incoming->unique_id);
4319   msg_ctx.msg_options = ntohl(incoming->options);
4320   msg_ctx.hop_count = ntohl(incoming->hop_count);
4321   msg_ctx.peer = peer;
4322   msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4323   msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4324   route_result_message(enc_msg, &msg_ctx);
4325   return GNUNET_YES;
4326 }
4327
4328
4329 /**
4330  * Receive the HELLO from transport service,
4331  * free current and replace if necessary.
4332  *
4333  * @param cls NULL
4334  * @param message HELLO message of peer
4335  */
4336 static void
4337 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4338 {
4339 #if DEBUG_DHT
4340   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4341               "Received our `%s' from transport service\n",
4342               "HELLO");
4343 #endif
4344
4345   GNUNET_assert (message != NULL);
4346   GNUNET_free_non_null(my_hello);
4347   my_hello = GNUNET_malloc(ntohs(message->size));
4348   memcpy(my_hello, message, ntohs(message->size));
4349 }
4350
4351
4352 /**
4353  * Task run during shutdown.
4354  *
4355  * @param cls unused
4356  * @param tc unused
4357  */
4358 static void
4359 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4360 {
4361   int bucket_count;
4362   struct PeerInfo *pos;
4363
4364   if (transport_handle != NULL)
4365     {
4366       GNUNET_free_non_null(my_hello);
4367       GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4368       GNUNET_TRANSPORT_disconnect(transport_handle);
4369     }
4370   for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4371     {
4372       while (k_buckets[bucket_count].head != NULL)
4373         {
4374           pos = k_buckets[bucket_count].head;
4375 #if DEBUG_DHT
4376           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4377                       "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4378 #endif
4379           delete_peer(pos, bucket_count);
4380         }
4381     }
4382   if (coreAPI != NULL)
4383     {
4384 #if DEBUG_DHT
4385       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4386                   "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4387 #endif
4388       GNUNET_CORE_disconnect (coreAPI);
4389       coreAPI = NULL;
4390     }
4391   if (datacache != NULL)
4392     {
4393 #if DEBUG_DHT
4394       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4395                   "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4396 #endif
4397       GNUNET_DATACACHE_destroy (datacache);
4398       datacache = NULL;
4399     }
4400   if (stats != NULL)
4401     {
4402       GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4403       stats = NULL;
4404     }
4405   if (dhtlog_handle != NULL)
4406     {
4407       GNUNET_DHTLOG_disconnect(dhtlog_handle);
4408       dhtlog_handle = NULL;
4409     }
4410   if (block_context != NULL)
4411     {
4412       GNUNET_BLOCK_context_destroy (block_context);
4413       block_context = NULL;
4414     }
4415   GNUNET_free_non_null(my_short_id);
4416   my_short_id = NULL;
4417 }
4418
4419
4420 /**
4421  * To be called on core init/fail.
4422  *
4423  * @param cls service closure
4424  * @param server handle to the server for this service
4425  * @param identity the public identity of this peer
4426  * @param publicKey the public key of this peer
4427  */
4428 void
4429 core_init (void *cls,
4430            struct GNUNET_CORE_Handle *server,
4431            const struct GNUNET_PeerIdentity *identity,
4432            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4433 {
4434
4435   if (server == NULL)
4436     {
4437 #if DEBUG_DHT
4438       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4439                   "%s: Connection to core FAILED!\n", "dht",
4440                   GNUNET_i2s (identity));
4441 #endif
4442       GNUNET_SCHEDULER_cancel (cleanup_task);
4443       GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4444       return;
4445     }
4446 #if DEBUG_DHT
4447   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4448               "%s: Core connection initialized, I am peer: %s\n", "dht",
4449               GNUNET_i2s (identity));
4450 #endif
4451
4452   /* Copy our identity so we can use it */
4453   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4454   if (my_short_id != NULL)
4455     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4456   my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4457   /* Set the server to local variable */
4458   coreAPI = server;
4459
4460   if (dhtlog_handle != NULL)
4461     dhtlog_handle->insert_node (NULL, &my_identity);
4462 }
4463
4464
4465 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4466   {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4467   {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4468   {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4469   {NULL, NULL, 0, 0}
4470 };
4471
4472
4473 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4474   {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4475   {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4476   {NULL, 0, 0}
4477 };
4478
4479
4480 /**
4481  * Method called whenever a peer connects.
4482  *
4483  * @param cls closure
4484  * @param peer peer identity this notification is about
4485  * @param atsi performance data
4486  */
4487 static void 
4488 handle_core_connect (void *cls,
4489                      const struct GNUNET_PeerIdentity * peer,
4490                      const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4491 {
4492   struct PeerInfo *ret;
4493
4494 #if DEBUG_DHT
4495   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4496               "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4497 #endif
4498
4499   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4500     {
4501       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));
4502       return;
4503     }
4504
4505   if (datacache != NULL)
4506     GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, GNUNET_BLOCK_TYPE_DHT_HELLO, GNUNET_TIME_absolute_get_forever());
4507   ret = try_add_peer(peer,
4508                      find_current_bucket(&peer->hashPubKey),
4509                      atsi);
4510   if (ret != NULL)
4511     {
4512       newly_found_peers++;
4513       GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4514     }
4515 #if DEBUG_DHT
4516     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4517                 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4518 #endif
4519 }
4520
4521
4522 /**
4523  * Method called whenever a peer disconnects.
4524  *
4525  * @param cls closure
4526  * @param peer peer identity this notification is about
4527  */
4528 static void
4529 handle_core_disconnect (void *cls,
4530                         const struct
4531                         GNUNET_PeerIdentity * peer)
4532 {
4533   struct PeerInfo *to_remove;
4534   int current_bucket;
4535
4536   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");
4537
4538   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4539     {
4540       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));
4541       return;
4542     }
4543   increment_stats(STAT_DISCONNECTS);
4544   GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4545   to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4546   GNUNET_assert (to_remove != NULL);
4547   GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4548   current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4549   delete_peer(to_remove, current_bucket);
4550 }
4551
4552
4553 /**
4554  * Process dht requests.
4555  *
4556  * @param cls closure
4557  * @param server the initialized server
4558  * @param c configuration to use
4559  */
4560 static void
4561 run (void *cls,
4562      struct GNUNET_SERVER_Handle *server,
4563      const struct GNUNET_CONFIGURATION_Handle *c)
4564 {
4565   struct GNUNET_TIME_Relative next_send_time;
4566   unsigned long long temp_config_num;
4567   char *converge_modifier_buf;
4568
4569   cfg = c;
4570   datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4571   GNUNET_SERVER_add_handlers (server, plugin_handlers);
4572   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4573   coreAPI = GNUNET_CORE_connect (cfg,    /* Main configuration */
4574                                  DEFAULT_CORE_QUEUE_SIZE, /* queue size */
4575                                  NULL,  /* Closure passed to DHT functions */
4576                                  &core_init,    /* Call core_init once connected */
4577                                  &handle_core_connect,  /* Handle connects */
4578                                  &handle_core_disconnect,  /* remove peers on disconnects */
4579                                  NULL,  /* Do we care about "status" updates? */
4580                                  NULL,  /* Don't want notified about all incoming messages */
4581                                  GNUNET_NO,     /* For header only inbound notification */
4582                                  NULL,  /* Don't want notified about all outbound messages */
4583                                  GNUNET_NO,     /* For header only outbound notification */
4584                                  core_handlers);        /* Register these handlers */
4585
4586   if (coreAPI == NULL)
4587     return;
4588   transport_handle = GNUNET_TRANSPORT_connect(cfg,
4589                                               NULL, NULL, NULL, NULL, NULL);
4590   if (transport_handle != NULL)
4591     GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4592   else
4593     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4594                "Failed to connect to transport service!\n");
4595   block_context = GNUNET_BLOCK_context_create (cfg);
4596   lowest_bucket = MAX_BUCKETS - 1;
4597   forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4598   forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4599   all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4600   recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4601   GNUNET_assert(all_known_peers != NULL);
4602   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4603     {
4604       debug_routes = GNUNET_YES;
4605     }
4606
4607   if (GNUNET_YES ==
4608       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4609                                            "strict_kademlia"))
4610     {
4611       strict_kademlia = GNUNET_YES;
4612     }
4613
4614   if (GNUNET_YES ==
4615       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4616                                            "stop_on_closest"))
4617     {
4618       stop_on_closest = GNUNET_YES;
4619     }
4620
4621   if (GNUNET_YES ==
4622       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4623                                            "stop_found"))
4624     {
4625       stop_on_found = GNUNET_YES;
4626     }
4627
4628   if (GNUNET_YES ==
4629       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4630                                            "malicious_getter"))
4631     {
4632       malicious_getter = GNUNET_YES;
4633       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4634                                             "MALICIOUS_GET_FREQUENCY",
4635                                             &malicious_get_frequency))
4636         malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4637     }
4638
4639   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4640                                         "MAX_HOPS",
4641                                         &max_hops))
4642     {
4643       max_hops = DEFAULT_MAX_HOPS;
4644     }
4645
4646   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4647                                                           "USE_MAX_HOPS"))
4648     {
4649       use_max_hops = GNUNET_YES;
4650     }
4651
4652   if (GNUNET_YES ==
4653       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4654                                            "malicious_putter"))
4655     {
4656       malicious_putter = GNUNET_YES;
4657       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4658                                             "MALICIOUS_PUT_FREQUENCY",
4659                                             &malicious_put_frequency))
4660         malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4661     }
4662
4663   dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
4664   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4665     {
4666       dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4667     }
4668
4669   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "bucket_size", &temp_config_num))
4670     {
4671       bucket_size = (unsigned int)temp_config_num;
4672     }
4673
4674   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "kad_alpha", &kademlia_replication))
4675     {
4676       kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
4677     }
4678
4679   if (GNUNET_YES ==
4680           GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4681                                                "malicious_dropper"))
4682     {
4683       malicious_dropper = GNUNET_YES;
4684     }
4685
4686   if (GNUNET_YES ==
4687         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4688                                              "republish"))
4689     do_republish = GNUNET_NO;
4690
4691   if (GNUNET_NO ==
4692         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4693                                              "do_find_peer"))
4694     {
4695       do_find_peer = GNUNET_NO;
4696     }
4697   else
4698     do_find_peer = GNUNET_YES;
4699
4700   if (GNUNET_YES ==
4701         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4702                                              "use_real_distance"))
4703     use_real_distance = GNUNET_YES;
4704
4705   if (GNUNET_YES ==
4706       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4707                                            "mysql_logging_extended"))
4708     {
4709       debug_routes = GNUNET_YES;
4710       debug_routes_extended = GNUNET_YES;
4711     }
4712
4713 #if DEBUG_DHT_ROUTING
4714   if (GNUNET_YES == debug_routes)
4715     {
4716       dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4717       if (dhtlog_handle == NULL)
4718         {
4719           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4720                       "Could not connect to mysql logging server, logging will not happen!");
4721         }
4722     }
4723 #endif
4724
4725   converge_option = DHT_CONVERGE_SQUARE;
4726   if (GNUNET_YES ==
4727       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4728                                            "converge_linear"))
4729     {
4730       converge_option = DHT_CONVERGE_LINEAR;
4731     }
4732   else if (GNUNET_YES ==
4733         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4734                                              "converge_exponential"))
4735     {
4736       converge_option = DHT_CONVERGE_EXPONENTIAL;
4737     }
4738   else if (GNUNET_YES ==
4739         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4740                                              "converge_random"))
4741     {
4742       converge_option = DHT_CONVERGE_RANDOM;
4743     }
4744   else if (GNUNET_YES ==
4745         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4746                                              "converge_binary"))
4747     {
4748       converge_option = DHT_CONVERGE_BINARY;
4749     }
4750
4751   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht", "converge_modifier", &converge_modifier_buf))
4752     {
4753       if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4754         {
4755           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4756           converge_modifier = 0.0;
4757         }
4758       GNUNET_free(converge_modifier_buf);
4759     }
4760
4761   stats = GNUNET_STATISTICS_create("dht", cfg);
4762
4763   if (stats != NULL)
4764     {
4765       GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4766       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4767       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4768       GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4769       GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4770       GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4771       GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4772       GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4773       GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4774       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4775       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4776       GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4777       GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4778       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4779       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4780       GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4781       GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4782       GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4783       GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4784       GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4785     }
4786   /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4787   recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4788   recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4789   if (GNUNET_YES == do_find_peer)
4790   {
4791     next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4792                            GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4793                                                     (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4794     find_peer_context.start = GNUNET_TIME_absolute_get();
4795     GNUNET_SCHEDULER_add_delayed (next_send_time,
4796                                   &send_find_peer_message, &find_peer_context);
4797   }
4798
4799   /* Scheduled the task to clean up when shutdown is called */
4800   cleanup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4801                                                &shutdown_task, NULL);
4802 }
4803
4804 /**
4805  * The main function for the dht service.
4806  *
4807  * @param argc number of arguments from the command line
4808  * @param argv command line arguments
4809  * @return 0 ok, 1 on error
4810  */
4811 int
4812 main (int argc, char *const *argv)
4813 {
4814   int ret;
4815
4816   ret = (GNUNET_OK ==
4817          GNUNET_SERVICE_run (argc,
4818                              argv,
4819                              "dht",
4820                              GNUNET_SERVICE_OPTION_NONE,
4821                              &run, NULL)) ? 0 : 1;
4822   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap));
4823   GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap));
4824   GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4825   GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4826   GNUNET_CONTAINER_heap_destroy (recent.minHeap);
4827   return ret;
4828 }