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