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