comparison bugfix
[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       real_selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_real_distance);
2850       selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2851
2852       for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2853         {
2854           pos = k_buckets[bc].head;
2855           count = 0;
2856           while ((pos != NULL) && (count < bucket_size))
2857             {
2858               if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2859                   ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2860                 {
2861                  if (GNUNET_YES == use_real_distance)
2862                    {
2863                     distance = inverse_distance (target, &pos->id.hashPubKey);
2864                     if (distance > real_selected)
2865                       {
2866                         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Selected peer with %u matching bits to route to\n", distance);
2867                         return pos;
2868                       }
2869                     real_selected -= distance;
2870                    }
2871                   else
2872                     {
2873                       distance = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target, &pos->id.hashPubKey));
2874                       if (distance > selected)
2875                         {
2876                           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Selected peer with %u matching bits to route to\n", distance);
2877                           return pos;
2878                         }
2879                       selected -= distance;
2880                     }
2881                 }
2882               else
2883                 {
2884   #if DEBUG_DHT
2885                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2886                               "`%s:%s': peer %s matches bloomfilter.\n",
2887                               my_short_id, "DHT", GNUNET_i2s(&pos->id));
2888   #endif
2889                 }
2890               pos = pos->next;
2891               count++;
2892             }
2893         }
2894   #if DEBUG_DHT
2895         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2896                     "`%s:%s': peer %s matches bloomfilter.\n",
2897                     my_short_id, "DHT", GNUNET_i2s(&pos->id));
2898   #endif
2899       increment_stats("# failed to select peer");
2900       GNUNET_assert(only_closer == GNUNET_NO);
2901       return NULL;
2902     }
2903 }
2904
2905 /**
2906  * Task used to remove recent entries, either
2907  * after timeout, when full, or on shutdown.
2908  *
2909  * @param cls the entry to remove
2910  * @param tc context, reason, etc.
2911  */
2912 static void
2913 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2914 {
2915   struct RecentRequest *req = cls;
2916   static GNUNET_HashCode hash;
2917
2918   GNUNET_assert(req != NULL);
2919   hash_from_uid(req->uid, &hash);
2920   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
2921   GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
2922   GNUNET_CONTAINER_bloomfilter_free(req->bloom);
2923   GNUNET_free(req);
2924
2925   if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
2926   {
2927     GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
2928     GNUNET_CONTAINER_heap_destroy(recent.minHeap);
2929   }
2930 }
2931
2932
2933 /**
2934  * Task used to remove forwarding entries, either
2935  * after timeout, when full, or on shutdown.
2936  *
2937  * @param cls the entry to remove
2938  * @param tc context, reason, etc.
2939  */
2940 static void
2941 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2942 {
2943   struct DHTRouteSource *source_info = cls;
2944   struct DHTQueryRecord *record;
2945   source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2946   record = source_info->record;
2947   GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2948
2949   if (record->head == NULL) /* No more entries in DLL */
2950     {
2951       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2952       GNUNET_free(record);
2953     }
2954   if (source_info->find_peers_responded != NULL)
2955     GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
2956   GNUNET_free(source_info);
2957 }
2958
2959 /**
2960  * Remember this routing request so that if a reply is
2961  * received we can either forward it to the correct peer
2962  * or return the result locally.
2963  *
2964  * @param cls DHT service closure
2965  * @param msg_ctx Context of the route request
2966  *
2967  * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2968  */
2969 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2970 {
2971   struct DHTQueryRecord *record;
2972   struct DHTRouteSource *source_info;
2973   struct DHTRouteSource *pos;
2974   struct GNUNET_TIME_Absolute now;
2975   unsigned int current_size;
2976
2977   current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2978   while (current_size >= MAX_OUTSTANDING_FORWARDS)
2979     {
2980       source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2981       GNUNET_assert(source_info != NULL);
2982       record = source_info->record;
2983       GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2984       if (record->head == NULL) /* No more entries in DLL */
2985         {
2986           GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2987           GNUNET_free(record);
2988         }
2989       GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2990       if (source_info->find_peers_responded != NULL)
2991         GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
2992       GNUNET_free(source_info);
2993       current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2994     }
2995   now = GNUNET_TIME_absolute_get();
2996   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2997   if (record != NULL) /* Already know this request! */
2998     {
2999       pos = record->head;
3000       while (pos != NULL)
3001         {
3002           if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3003             break; /* Already have this peer in reply list! */
3004           pos = pos->next;
3005         }
3006       if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3007         {
3008           GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3009           return GNUNET_NO;
3010         }
3011     }
3012   else
3013     {
3014       record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3015       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3016       memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3017     }
3018
3019   source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3020   source_info->record = record;
3021   source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3022   source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3023   memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3024   GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3025   if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3026     {
3027       source_info->client = msg_ctx->client;
3028       now = GNUNET_TIME_absolute_get_forever();
3029     }
3030   source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3031 #if DEBUG_DHT > 1
3032       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3033                   "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3034                   "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
3035 #endif
3036   return GNUNET_YES;
3037 }
3038
3039
3040 /**
3041  * Main function that handles whether or not to route a message to other
3042  * peers.
3043  *
3044  * @param cls closure for dht service (NULL)
3045  * @param msg the message to be routed
3046  * @param message_context the context containing all pertinent information about the message
3047  *
3048  * @return the number of peers the message was routed to,
3049  *         GNUNET_SYSERR on failure
3050  */
3051 static int route_message(void *cls,
3052                          const struct GNUNET_MessageHeader *msg,
3053                          struct DHT_MessageContext *message_context)
3054 {
3055   int i;
3056   int global_closest;
3057   struct PeerInfo *selected;
3058 #if DEBUG_DHT_ROUTING > 1
3059   struct PeerInfo *nearest;
3060 #endif
3061   unsigned int forward_count;
3062   struct RecentRequest *recent_req;
3063   GNUNET_HashCode unique_hash;
3064   char *stat_forward_count;
3065 #if DEBUG_DHT_ROUTING
3066   int ret;
3067 #endif
3068
3069   if (malicious_dropper == GNUNET_YES)
3070     {
3071 #if DEBUG_DHT_ROUTING
3072       if ((debug_routes_extended) && (dhtlog_handle != NULL))
3073         {
3074           dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3075                                        message_context->hop_count, GNUNET_SYSERR,
3076                                        &my_identity, &message_context->key, message_context->peer,
3077                                        NULL);
3078         }
3079 #endif
3080       if (message_context->bloom != NULL)
3081         GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3082       return 0;
3083     }
3084
3085   increment_stats(STAT_ROUTES);
3086   /* Semantics of this call means we find whether we are the closest peer out of those already
3087    * routed to on this messages path.
3088    */
3089   global_closest = am_closest_peer(&message_context->key, NULL);
3090   message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3091   forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3092   GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3093   increment_stats(stat_forward_count);
3094   GNUNET_free(stat_forward_count);
3095   if (message_context->bloom == NULL)
3096     message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3097
3098   if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3099     forward_count = 0;
3100
3101 #if DEBUG_DHT_ROUTING
3102   if (forward_count == 0)
3103     ret = GNUNET_SYSERR;
3104   else
3105     ret = GNUNET_NO;
3106
3107   if ((debug_routes_extended) && (dhtlog_handle != NULL))
3108     {
3109       dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3110                                    message_context->hop_count, ret,
3111                                    &my_identity, &message_context->key, message_context->peer,
3112                                    NULL);
3113     }
3114 #endif
3115
3116   switch (ntohs(msg->type))
3117     {
3118     case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3119       cache_response (cls, message_context);
3120       if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3121         forward_count = 0;
3122       break;
3123     case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3124       increment_stats(STAT_PUTS);
3125       message_context->closest = global_closest;
3126       handle_dht_put (cls, msg, message_context);
3127       break;
3128     case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3129       increment_stats(STAT_FIND_PEER);
3130       if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3131       {
3132         cache_response (cls, message_context);
3133         if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3134           handle_dht_find_peer (cls, msg, message_context);
3135       }
3136 #if DEBUG_DHT_ROUTING
3137       if (message_context->hop_count == 0) /* Locally initiated request */
3138         {
3139           if ((debug_routes) && (dhtlog_handle != NULL))
3140             {
3141               dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3142               dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3143                                            message_context->hop_count, GNUNET_NO, &my_identity,
3144                                            &message_context->key);
3145             }
3146         }
3147 #endif
3148       break;
3149     default:
3150       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3151                   "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3152     }
3153
3154   GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3155   hash_from_uid(message_context->unique_id, &unique_hash);
3156   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent.hashmap, &unique_hash))
3157   {
3158       recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3159       GNUNET_assert(recent_req != NULL);
3160       if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3161         increment_stats(STAT_DUPLICATE_UID);
3162       else
3163       {
3164         increment_stats(STAT_RECENT_SEEN);
3165         GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3166       }
3167     }
3168   else
3169     {
3170       recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3171       recent_req->uid = message_context->unique_id;
3172       memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3173       recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3174       recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3175       recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3176       GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3177     }
3178
3179   if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3180     {
3181       recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3182       GNUNET_assert(recent_req != NULL);
3183       GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3184       GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3185     }
3186
3187   for (i = 0; i < forward_count; i++)
3188     {
3189       selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3190
3191       if (selected != NULL)
3192         {
3193           GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3194 #if DEBUG_DHT_ROUTING > 1
3195           nearest = find_closest_peer(&message_context->key);
3196           nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3197           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3198                       "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3199                       "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));
3200           GNUNET_free(nearest_buf);
3201 #endif
3202           if ((debug_routes_extended) && (dhtlog_handle != NULL))
3203             {
3204               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3205                                            message_context->hop_count, GNUNET_NO,
3206                                            &my_identity, &message_context->key, message_context->peer,
3207                                            &selected->id);
3208             }
3209           forward_message(cls, msg, selected, message_context);
3210         }
3211       else
3212         {
3213           increment_stats("# NULL returned from select_peer");
3214           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3215                       "`%s:%s': No peers selected for forwarding.\n", my_short_id,
3216                       "DHT");
3217
3218         }
3219     }
3220 #if DEBUG_DHT_ROUTING > 1
3221   if (forward_count == 0)
3222     {
3223       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3224                   "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
3225                   "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
3226     }
3227 #endif
3228
3229   if (message_context->bloom != NULL)
3230     {
3231       GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3232       GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3233     }
3234
3235   return forward_count;
3236 }
3237
3238 /**
3239  * Iterator for local get request results,
3240  *
3241  * @param cls closure for iterator, NULL
3242  * @param exp when does this value expire?
3243  * @param key the key this data is stored under
3244  * @param size the size of the data identified by key
3245  * @param data the actual data
3246  * @param type the type of the data
3247  *
3248  * @return GNUNET_OK to continue iteration, anything else
3249  * to stop iteration.
3250  */
3251 static int
3252 republish_content_iterator (void *cls,
3253                             struct GNUNET_TIME_Absolute exp,
3254                             const GNUNET_HashCode * key,
3255                             uint32_t size, const char *data, uint32_t type)
3256 {
3257
3258   struct DHT_MessageContext *new_msg_ctx;
3259   struct GNUNET_DHT_PutMessage *put_msg;
3260 #if DEBUG_DHT
3261   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3262               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3263 #endif
3264   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3265
3266   put_msg =
3267     GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3268   put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3269   put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3270   put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3271   put_msg->type = htons (type);
3272   memcpy (&put_msg[1], data, size);
3273   new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3274   new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3275   new_msg_ctx->msg_options = ntohl (0);
3276   new_msg_ctx->network_size = estimate_diameter();
3277   new_msg_ctx->peer = &my_identity;
3278   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3279   new_msg_ctx->hop_count = 0;
3280   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3281   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3282   increment_stats(STAT_PUT_START);
3283   route_message(cls, &put_msg->header, new_msg_ctx);
3284
3285   GNUNET_free(new_msg_ctx);
3286   GNUNET_free (put_msg);
3287   return GNUNET_OK;
3288 }
3289
3290 /**
3291  * Task used to republish data.
3292  *
3293  * @param cls closure (a struct RepublishContext)
3294  * @param tc runtime context for this task
3295  */
3296 static void
3297 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3298 {
3299   struct RepublishContext *put_context = cls;
3300
3301   unsigned int results;
3302
3303   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3304     {
3305       GNUNET_free(put_context);
3306       return;
3307     }
3308
3309   GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3310   results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3311   if (results == 0) /* Data must have expired */
3312     GNUNET_free(put_context);
3313   else /* Reschedule task for next time period */
3314     GNUNET_SCHEDULER_add_delayed(sched, DHT_REPUBLISH_FREQUENCY, &republish_content, put_context);
3315
3316 }
3317
3318 /**
3319  * Find a client if it exists, add it otherwise.
3320  *
3321  * @param client the server handle to the client
3322  *
3323  * @return the client if found, a new client otherwise
3324  */
3325 static struct ClientList *
3326 find_active_client (struct GNUNET_SERVER_Client *client)
3327 {
3328   struct ClientList *pos = client_list;
3329   struct ClientList *ret;
3330
3331   while (pos != NULL)
3332     {
3333       if (pos->client_handle == client)
3334         return pos;
3335       pos = pos->next;
3336     }
3337
3338   ret = GNUNET_malloc (sizeof (struct ClientList));
3339   ret->client_handle = client;
3340   ret->next = client_list;
3341   client_list = ret;
3342   return ret;
3343 }
3344
3345 /**
3346  * Task to send a malicious put message across the network.
3347  *
3348  * @param cls closure for this task
3349  * @param tc the context under which the task is running
3350  */
3351 static void
3352 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3353 {
3354   static struct GNUNET_DHT_PutMessage put_message;
3355   static struct DHT_MessageContext message_context;
3356   static GNUNET_HashCode key;
3357   uint32_t random_key;
3358
3359   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3360     return;
3361
3362   put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3363   put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3364   put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3365   put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3366   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3367   message_context.client = NULL;
3368   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3369   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3370   memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3371   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3372   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3373   message_context.msg_options = ntohl (0);
3374   message_context.network_size = estimate_diameter();
3375   message_context.peer = &my_identity;
3376   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3377   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3378   if (dhtlog_handle != NULL)
3379     dhtlog_handle->insert_dhtkey(NULL, &key);
3380   increment_stats(STAT_PUT_START);
3381   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3382   route_message(NULL, &put_message.header, &message_context);
3383   GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3384
3385 }
3386
3387 /**
3388  * Task to send a malicious put message across the network.
3389  *
3390  * @param cls closure for this task
3391  * @param tc the context under which the task is running
3392  */
3393 static void
3394 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3395 {
3396   static struct GNUNET_DHT_GetMessage get_message;
3397   struct DHT_MessageContext message_context;
3398   static GNUNET_HashCode key;
3399   uint32_t random_key;
3400
3401   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3402     return;
3403
3404   get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3405   get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3406   get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3407   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3408   message_context.client = NULL;
3409   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3410   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3411   memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3412   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3413   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3414   message_context.msg_options = ntohl (0);
3415   message_context.network_size = estimate_diameter();
3416   message_context.peer = &my_identity;
3417   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3418   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3419   if (dhtlog_handle != NULL)
3420     dhtlog_handle->insert_dhtkey(NULL, &key);
3421   increment_stats(STAT_GET_START);
3422   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3423   route_message (NULL, &get_message.header, &message_context);
3424   GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3425 }
3426
3427 /**
3428  * Iterator over hash map entries.
3429  *
3430  * @param cls closure
3431  * @param key current key code
3432  * @param value value in the hash map
3433  * @return GNUNET_YES if we should continue to
3434  *         iterate,
3435  *         GNUNET_NO if not.
3436  */
3437 static int
3438 add_known_to_bloom (void *cls,
3439                     const GNUNET_HashCode * key,
3440                     void *value)
3441 {
3442   struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3443   GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3444   return GNUNET_YES;
3445 }
3446
3447 /**
3448  * Task to send a find peer message for our own peer identifier
3449  * so that we can find the closest peers in the network to ourselves
3450  * and attempt to connect to them.
3451  *
3452  * @param cls closure for this task
3453  * @param tc the context under which the task is running
3454  */
3455 static void
3456 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3457 {
3458   struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3459   struct DHT_MessageContext message_context;
3460   int ret;
3461   struct GNUNET_TIME_Relative next_send_time;
3462   struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3463 #if COUNT_INTERVAL
3464   struct GNUNET_TIME_Relative time_diff;
3465   struct GNUNET_TIME_Absolute end;
3466   double multiplier;
3467   double count_per_interval;
3468 #endif
3469   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3470     return;
3471
3472   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! */
3473     {
3474       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3475       GNUNET_SCHEDULER_add_delayed (sched,
3476                                     GNUNET_TIME_UNIT_MINUTES,
3477                                     &send_find_peer_message, NULL);
3478       newly_found_peers = 0;
3479       return;
3480     }
3481     
3482   increment_stats(STAT_FIND_PEER_START);
3483 #if COUNT_INTERVAL
3484   end = GNUNET_TIME_absolute_get();
3485   time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3486
3487   if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3488     {
3489       multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3490       count_per_interval = find_peer_context.count / multiplier;
3491     }
3492   else
3493     {
3494       multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3495       count_per_interval = find_peer_context.count * multiplier;
3496     }
3497 #endif
3498
3499   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3500   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3501   find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3502   temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3503   GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3504   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3505   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3506   memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3507   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3508   message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3509   message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3510   message_context.network_size = estimate_diameter();
3511   message_context.peer = &my_identity;
3512   message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3513   message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3514
3515   ret = route_message(NULL, &find_peer_msg->header, &message_context);
3516   GNUNET_free(find_peer_msg);
3517   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3518               "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3519               "FIND PEER", ret);
3520   if (newly_found_peers < bucket_size)
3521     {
3522       next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3523                               GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3524                                                        DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3525     }
3526   else
3527     {
3528       next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3529                              GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3530                                                       DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3531     }
3532
3533   GNUNET_assert (next_send_time.value != 0);
3534   find_peer_context.count = 0;
3535   newly_found_peers = 0;
3536   find_peer_context.start = GNUNET_TIME_absolute_get();
3537   if (GNUNET_YES == do_find_peer)
3538   {
3539     GNUNET_SCHEDULER_add_delayed (sched,
3540                                   next_send_time,
3541                                   &send_find_peer_message, NULL);
3542   }
3543 }
3544
3545 /**
3546  * Handler for any generic DHT messages, calls the appropriate handler
3547  * depending on message type, sends confirmation if responses aren't otherwise
3548  * expected.
3549  *
3550  * @param cls closure for the service
3551  * @param client the client we received this message from
3552  * @param message the actual message received
3553  */
3554 static void
3555 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3556                                 const struct GNUNET_MessageHeader *message)
3557 {
3558   const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3559   const struct GNUNET_MessageHeader *enc_msg;
3560   struct DHT_MessageContext message_context;
3561   enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3562 #if DEBUG_DHT
3563   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3564               "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3565               my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3566               GNUNET_ntohll (dht_msg->unique_id));
3567 #endif
3568 #if DEBUG_DHT_ROUTING
3569   if (dhtlog_handle != NULL)
3570     dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3571 #endif
3572   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3573   message_context.client = find_active_client (client);
3574   memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3575   message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3576   message_context.replication = ntohl (dht_msg->desired_replication_level);
3577   message_context.msg_options = ntohl (dht_msg->options);
3578   message_context.network_size = estimate_diameter();
3579   message_context.peer = &my_identity;
3580   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3581   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3582   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3583     increment_stats(STAT_GET_START);
3584   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3585     increment_stats(STAT_PUT_START);
3586   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3587     increment_stats(STAT_FIND_PEER_START);
3588
3589   route_message(cls, enc_msg, &message_context);
3590
3591   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3592
3593 }
3594
3595 /**
3596  * Handler for any locally received DHT control messages,
3597  * sets malicious flags mostly for now.
3598  *
3599  * @param cls closure for the service
3600  * @param client the client we received this message from
3601  * @param message the actual message received
3602  *
3603  */
3604 static void
3605 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3606                             const struct GNUNET_MessageHeader *message)
3607 {
3608   const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3609       (const struct GNUNET_DHT_ControlMessage *) message;
3610 #if DEBUG_DHT
3611   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3612               "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3613               "CONTROL", ntohs(dht_control_msg->command));
3614 #endif
3615
3616   switch (ntohs(dht_control_msg->command))
3617   {
3618   case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3619     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3620     GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3621     break;
3622   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3623     if (ntohs(dht_control_msg->variable) > 0)
3624       malicious_get_frequency = ntohs(dht_control_msg->variable);
3625     if (malicious_get_frequency == 0)
3626       malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3627     if (malicious_getter != GNUNET_YES)
3628       GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3629     malicious_getter = GNUNET_YES;
3630     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3631     break;
3632   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3633     if (ntohs(dht_control_msg->variable) > 0)
3634       malicious_put_frequency = ntohs(dht_control_msg->variable);
3635     if (malicious_put_frequency == 0)
3636       malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3637     if (malicious_putter != GNUNET_YES)
3638       GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3639     malicious_putter = GNUNET_YES;
3640     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3641     break;
3642   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3643     if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3644       dhtlog_handle->set_malicious(&my_identity);
3645     malicious_dropper = GNUNET_YES;
3646     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3647     break;
3648   default:
3649     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3650   }
3651
3652   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3653 }
3654
3655 /**
3656  * Handler for any generic DHT stop messages, calls the appropriate handler
3657  * depending on message type (if processed locally)
3658  *
3659  * @param cls closure for the service
3660  * @param client the client we received this message from
3661  * @param message the actual message received
3662  *
3663  */
3664 static void
3665 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3666                             const struct GNUNET_MessageHeader *message)
3667 {
3668
3669   const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3670     (const struct GNUNET_DHT_StopMessage *) message;
3671   struct DHTQueryRecord *record;
3672   struct DHTRouteSource *pos;
3673 #if DEBUG_DHT
3674   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3675               "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3676               "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3677 #endif
3678   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3679   if (record != NULL)
3680     {
3681       pos = record->head;
3682
3683       while (pos != NULL)
3684         {
3685           if ((pos->client != NULL) && (pos->client->client_handle == client))
3686             {
3687               GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3688               GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3689             }
3690           pos = pos->next;
3691         }
3692     }
3693
3694   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3695 }
3696
3697
3698 /**
3699  * Core handler for p2p route requests.
3700  */
3701 static int
3702 handle_dht_p2p_route_request (void *cls,
3703                               const struct GNUNET_PeerIdentity *peer,
3704                               const struct GNUNET_MessageHeader *message,
3705                               struct GNUNET_TIME_Relative latency, uint32_t distance)
3706 {
3707 #if DEBUG_DHT
3708   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3709               "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3710 #endif
3711   struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3712   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3713   struct DHT_MessageContext *message_context;
3714
3715   if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
3716   {
3717     fprintf(stderr, "Sending of previous replies took far too long, backing off!\n");
3718     decrease_max_send_delay(get_max_send_delay());
3719     return GNUNET_YES;
3720   }
3721
3722   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3723     {
3724 #if DEBUG_PING
3725       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3726 #endif
3727       return GNUNET_YES;
3728     }
3729
3730   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3731     {
3732       GNUNET_break_op(0);
3733       return GNUNET_YES;
3734     }
3735   message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3736   message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3737   GNUNET_assert(message_context->bloom != NULL);
3738   message_context->hop_count = ntohl(incoming->hop_count);
3739   memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
3740   message_context->replication = ntohl(incoming->desired_replication_level);
3741   message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3742   message_context->msg_options = ntohl(incoming->options);
3743   message_context->network_size = ntohl(incoming->network_size);
3744   message_context->peer = peer;
3745   message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3746   message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3747   route_message(cls, enc_msg, message_context);
3748   GNUNET_free(message_context);
3749   return GNUNET_YES;
3750 }
3751
3752
3753 /**
3754  * Core handler for p2p route results.
3755  */
3756 static int
3757 handle_dht_p2p_route_result (void *cls,
3758                              const struct GNUNET_PeerIdentity *peer,
3759                              const struct GNUNET_MessageHeader *message,
3760                              struct GNUNET_TIME_Relative latency, uint32_t distance)
3761 {
3762 #if DEBUG_DHT
3763   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3764               "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3765 #endif
3766   struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3767   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3768   struct DHT_MessageContext message_context;
3769
3770   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
3771     {
3772       GNUNET_break_op(0);
3773       return GNUNET_YES;
3774     }
3775
3776   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3777   message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3778   GNUNET_assert(message_context.bloom != NULL);
3779   memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
3780   message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3781   message_context.msg_options = ntohl(incoming->options);
3782   message_context.hop_count = ntohl(incoming->hop_count);
3783   message_context.peer = peer;
3784   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3785   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3786   route_result_message(cls, enc_msg, &message_context);
3787   return GNUNET_YES;
3788 }
3789
3790
3791 /**
3792  * Receive the HELLO from transport service,
3793  * free current and replace if necessary.
3794  *
3795  * @param cls NULL
3796  * @param message HELLO message of peer
3797  */
3798 static void
3799 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3800 {
3801 #if DEBUG_DHT
3802   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3803               "Received our `%s' from transport service\n",
3804               "HELLO");
3805 #endif
3806
3807   GNUNET_assert (message != NULL);
3808   GNUNET_free_non_null(my_hello);
3809   my_hello = GNUNET_malloc(ntohs(message->size));
3810   memcpy(my_hello, message, ntohs(message->size));
3811 }
3812
3813
3814 /**
3815  * Task run during shutdown.
3816  *
3817  * @param cls unused
3818  * @param tc unused
3819  */
3820 static void
3821 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3822 {
3823   int bucket_count;
3824   struct PeerInfo *pos;
3825   if (transport_handle != NULL)
3826   {
3827     GNUNET_free_non_null(my_hello);
3828     GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3829     GNUNET_TRANSPORT_disconnect(transport_handle);
3830   }
3831
3832   for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3833     {
3834       while (k_buckets[bucket_count].head != NULL)
3835         {
3836           pos = k_buckets[bucket_count].head;
3837 #if DEBUG_DHT
3838           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3839                       "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3840 #endif
3841           delete_peer(pos, bucket_count);
3842         }
3843     }
3844   if (coreAPI != NULL)
3845     {
3846 #if DEBUG_DHT
3847       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3848                   "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3849 #endif
3850       GNUNET_CORE_disconnect (coreAPI);
3851     }
3852   if (datacache != NULL)
3853     {
3854 #if DEBUG_DHT
3855       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3856                   "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3857 #endif
3858       GNUNET_DATACACHE_destroy (datacache);
3859     }
3860
3861   if (stats != NULL)
3862     {
3863       GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3864     }
3865
3866   if (dhtlog_handle != NULL)
3867     GNUNET_DHTLOG_disconnect(dhtlog_handle);
3868
3869   GNUNET_free_non_null(my_short_id);
3870 }
3871
3872
3873 /**
3874  * To be called on core init/fail.
3875  *
3876  * @param cls service closure
3877  * @param server handle to the server for this service
3878  * @param identity the public identity of this peer
3879  * @param publicKey the public key of this peer
3880  */
3881 void
3882 core_init (void *cls,
3883            struct GNUNET_CORE_Handle *server,
3884            const struct GNUNET_PeerIdentity *identity,
3885            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3886 {
3887
3888   if (server == NULL)
3889     {
3890 #if DEBUG_DHT
3891   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3892               "%s: Connection to core FAILED!\n", "dht",
3893               GNUNET_i2s (identity));
3894 #endif
3895       GNUNET_SCHEDULER_cancel (sched, cleanup_task);
3896       GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3897       return;
3898     }
3899 #if DEBUG_DHT
3900   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3901               "%s: Core connection initialized, I am peer: %s\n", "dht",
3902               GNUNET_i2s (identity));
3903 #endif
3904
3905   /* Copy our identity so we can use it */
3906   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3907   if (my_short_id != NULL)
3908     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3909   my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3910   /* Set the server to local variable */
3911   coreAPI = server;
3912
3913   if (dhtlog_handle != NULL)
3914     dhtlog_handle->insert_node (NULL, &my_identity);
3915 }
3916
3917
3918 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3919   {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3920   {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3921   {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
3922   {NULL, NULL, 0, 0}
3923 };
3924
3925
3926 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3927   {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
3928   {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
3929   {NULL, 0, 0}
3930 };
3931
3932 /**
3933  * Method called whenever a peer connects.
3934  *
3935  * @param cls closure
3936  * @param peer peer identity this notification is about
3937  * @param latency reported latency of the connection with peer
3938  * @param distance reported distance (DV) to peer
3939  */
3940 void handle_core_connect (void *cls,
3941                           const struct GNUNET_PeerIdentity * peer,
3942                           struct GNUNET_TIME_Relative latency,
3943                           uint32_t distance)
3944 {
3945   struct PeerInfo *ret;
3946
3947 #if DEBUG_DHT
3948   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3949               "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
3950 #endif
3951
3952   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3953     {
3954       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));
3955       return;
3956     }
3957
3958   if (datacache != NULL)
3959     GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
3960   ret = try_add_peer(peer,
3961                      find_current_bucket(&peer->hashPubKey),
3962                      latency,
3963                      distance);
3964   if (ret != NULL)
3965     {
3966       newly_found_peers++;
3967       GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3968     }
3969 #if DEBUG_DHT
3970     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3971                 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
3972 #endif
3973 }
3974
3975 /**
3976  * Method called whenever a peer disconnects.
3977  *
3978  * @param cls closure
3979  * @param peer peer identity this notification is about
3980  */
3981 void handle_core_disconnect (void *cls,
3982                              const struct
3983                              GNUNET_PeerIdentity * peer)
3984 {
3985   struct PeerInfo *to_remove;
3986   int current_bucket;
3987
3988   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");
3989
3990   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3991     {
3992       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));
3993       return;
3994     }
3995   increment_stats(STAT_DISCONNECTS);
3996   GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
3997   to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
3998   GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
3999   current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4000   delete_peer(to_remove, current_bucket);
4001 }
4002
4003 /**
4004  * Process dht requests.
4005  *
4006  * @param cls closure
4007  * @param scheduler scheduler to use
4008  * @param server the initialized server
4009  * @param c configuration to use
4010  */
4011 static void
4012 run (void *cls,
4013      struct GNUNET_SCHEDULER_Handle *scheduler,
4014      struct GNUNET_SERVER_Handle *server,
4015      const struct GNUNET_CONFIGURATION_Handle *c)
4016 {
4017 #if DO_FIND_PEER
4018   struct GNUNET_TIME_Relative next_send_time;
4019 #endif
4020   sched = scheduler;
4021   cfg = c;
4022   datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4023   GNUNET_SERVER_add_handlers (server, plugin_handlers);
4024   coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4025                                  cfg,   /* Main configuration */
4026                                  GNUNET_TIME_UNIT_FOREVER_REL,
4027                                  NULL,  /* Closure passed to DHT functions */
4028                                  &core_init,    /* Call core_init once connected */
4029                                  &handle_core_connect,  /* Handle connects */
4030                                  &handle_core_disconnect,  /* remove peers on disconnects */
4031                                  NULL,  /* Do we care about "status" updates? */
4032                                  NULL,  /* Don't want notified about all incoming messages */
4033                                  GNUNET_NO,     /* For header only inbound notification */
4034                                  NULL,  /* Don't want notified about all outbound messages */
4035                                  GNUNET_NO,     /* For header only outbound notification */
4036                                  core_handlers);        /* Register these handlers */
4037
4038   if (coreAPI == NULL)
4039     return;
4040   transport_handle = GNUNET_TRANSPORT_connect(sched, cfg, 
4041                                               NULL, NULL, NULL, NULL, NULL);
4042   if (transport_handle != NULL)
4043     GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4044   else
4045     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4046
4047   lowest_bucket = MAX_BUCKETS - 1;
4048   forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4049   forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4050   all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4051   recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4052   GNUNET_assert(all_known_peers != NULL);
4053   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4054     {
4055       debug_routes = GNUNET_YES;
4056     }
4057
4058   if (GNUNET_YES ==
4059       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4060                                            "strict_kademlia"))
4061     {
4062       strict_kademlia = GNUNET_YES;
4063     }
4064
4065   if (GNUNET_YES ==
4066       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4067                                            "stop_on_closest"))
4068     {
4069       stop_on_closest = GNUNET_YES;
4070     }
4071
4072   if (GNUNET_YES ==
4073       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4074                                            "stop_found"))
4075     {
4076       stop_on_found = GNUNET_YES;
4077     }
4078
4079   if (GNUNET_YES ==
4080       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4081                                            "malicious_getter"))
4082     {
4083       malicious_getter = GNUNET_YES;
4084       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4085                                             "MALICIOUS_GET_FREQUENCY",
4086                                             &malicious_get_frequency))
4087         malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4088     }
4089
4090   if (GNUNET_YES ==
4091       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4092                                            "malicious_putter"))
4093     {
4094       malicious_putter = GNUNET_YES;
4095       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4096                                             "MALICIOUS_PUT_FREQUENCY",
4097                                             &malicious_put_frequency))
4098         malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4099     }
4100
4101   if (GNUNET_YES ==
4102           GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4103                                                "malicious_dropper"))
4104     {
4105       malicious_dropper = GNUNET_YES;
4106     }
4107
4108   if (GNUNET_YES ==
4109         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4110                                              "republish"))
4111     do_republish = GNUNET_NO;
4112
4113   if (GNUNET_NO ==
4114         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4115                                              "do_find_peer"))
4116     {
4117       do_find_peer = GNUNET_NO;
4118     }
4119   else
4120     do_find_peer = GNUNET_YES;
4121
4122   if (GNUNET_YES ==
4123         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4124                                              "use_real_distance"))
4125     use_real_distance = GNUNET_YES;
4126
4127   if (GNUNET_YES ==
4128       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4129                                            "mysql_logging_extended"))
4130     {
4131       debug_routes = GNUNET_YES;
4132       debug_routes_extended = GNUNET_YES;
4133     }
4134
4135   if (GNUNET_YES == debug_routes)
4136     {
4137       dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4138       if (dhtlog_handle == NULL)
4139         {
4140           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4141                       "Could not connect to mysql logging server, logging will not happen!");
4142         }
4143     }
4144
4145   converge_option = DHT_CONVERGE_SQUARE;
4146   if (GNUNET_YES ==
4147       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4148                                            "converge_linear"))
4149     {
4150       converge_option = DHT_CONVERGE_LINEAR;
4151     }
4152
4153   stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4154
4155   if (stats != NULL)
4156     {
4157       GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4158       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4159       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4160       GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4161       GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4162       GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4163       GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4164       GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4165       GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4166       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4167       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4168       GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4169       GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4170       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4171       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4172       GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4173       GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4174       GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4175       GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4176       GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4177     }
4178   /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4179   recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4180   recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4181   if (GNUNET_YES == do_find_peer)
4182   {
4183     next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4184                            GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4185                                                     (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4186     find_peer_context.start = GNUNET_TIME_absolute_get();
4187     GNUNET_SCHEDULER_add_delayed (sched,
4188                                   next_send_time,
4189                                   &send_find_peer_message, &find_peer_context);
4190   }
4191
4192   /* Scheduled the task to clean up when shutdown is called */
4193   cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4194                                                GNUNET_TIME_UNIT_FOREVER_REL,
4195                                                &shutdown_task, NULL);
4196 }
4197
4198 /**
4199  * The main function for the dht service.
4200  *
4201  * @param argc number of arguments from the command line
4202  * @param argv command line arguments
4203  * @return 0 ok, 1 on error
4204  */
4205 int
4206 main (int argc, char *const *argv)
4207 {
4208   return (GNUNET_OK ==
4209           GNUNET_SERVICE_run (argc,
4210                               argv,
4211                               "dht",
4212                               GNUNET_SERVICE_OPTION_NONE,
4213                               &run, NULL)) ? 0 : 1;
4214 }