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