kademlia compromise, add some ifdefs, compile error fix on blackbox
[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       if ((debug_routes_extended) && (dhtlog_handle != NULL))
1958         {
1959           dhtlog_handle->insert_route (NULL,
1960                                        message_context->unique_id,
1961                                        DHTLOG_RESULT,
1962                                        message_context->hop_count,
1963                                        GNUNET_SYSERR,
1964                                        &my_identity,
1965                                        &message_context->key,
1966                                        message_context->peer, NULL);
1967         }
1968 #endif
1969       if (message_context->bloom != NULL)
1970         {
1971           GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1972           message_context->bloom = NULL;
1973         }
1974       return 0;
1975     }
1976
1977   pos = record->head;
1978   while (pos != NULL)
1979     {
1980 #if STRICT_FORWARDING
1981       if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
1982         {
1983           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
1984           {
1985             increment_stats("# find peer responses NOT forwarded (bloom match)");
1986             pos = pos->next;
1987             continue;
1988           }
1989           else
1990             GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
1991         }
1992 #endif
1993
1994       if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1995         {
1996 #if DEBUG_DHT
1997           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1998                       "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
1999                       "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2000 #endif
2001 #if DEBUG_DHT_ROUTING
2002           if ((debug_routes_extended) && (dhtlog_handle != NULL))
2003             {
2004               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2005                                            message_context->hop_count,
2006                                            GNUNET_YES, &my_identity, &message_context->key,
2007                                            message_context->peer, NULL);
2008             }
2009 #endif
2010           increment_stats(STAT_RESULTS_TO_CLIENT);
2011           if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2012             increment_stats(STAT_GET_REPLY);
2013
2014           send_reply_to_client(pos->client, msg, message_context->unique_id);
2015         }
2016       else /* Send to peer */
2017         {
2018           peer_info = find_peer_by_id(&pos->source);
2019           if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2020             {
2021               pos = pos->next;
2022               continue;
2023             }
2024
2025           if (message_context->bloom == NULL)
2026             message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2027           GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2028           if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2029             {
2030 #if DEBUG_DHT
2031               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2032                           "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2033                           "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2034 #endif
2035 #if DEBUG_DHT_ROUTING
2036               if ((debug_routes_extended) && (dhtlog_handle != NULL))
2037                 {
2038                   dhtlog_handle->insert_route (NULL, message_context->unique_id,
2039                                                DHTLOG_RESULT,
2040                                                message_context->hop_count,
2041                                                GNUNET_NO, &my_identity, &message_context->key,
2042                                                message_context->peer, &pos->source);
2043                 }
2044 #endif
2045               forward_result_message(cls, msg, peer_info, message_context);
2046             }
2047           else
2048             {
2049 #if DEBUG_DHT
2050               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2051                           "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2052                           "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2053 #endif
2054             }
2055         }
2056       pos = pos->next;
2057     }
2058   if (message_context->bloom != NULL)
2059     GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2060   return 0;
2061 }
2062
2063 /**
2064  * Iterator for local get request results,
2065  *
2066  * @param cls closure for iterator, a DatacacheGetContext
2067  * @param exp when does this value expire?
2068  * @param key the key this data is stored under
2069  * @param size the size of the data identified by key
2070  * @param data the actual data
2071  * @param type the type of the data
2072  *
2073  * @return GNUNET_OK to continue iteration, anything else
2074  * to stop iteration.
2075  */
2076 static int
2077 datacache_get_iterator (void *cls,
2078                         struct GNUNET_TIME_Absolute exp,
2079                         const GNUNET_HashCode * key,
2080                         uint32_t size, const char *data, uint32_t type)
2081 {
2082   struct DHT_MessageContext *msg_ctx = cls;
2083   struct DHT_MessageContext *new_msg_ctx;
2084   struct GNUNET_DHT_GetResultMessage *get_result;
2085 #if DEBUG_DHT
2086   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2087               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2088 #endif
2089   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2090   memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2091   get_result =
2092     GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2093   get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2094   get_result->header.size =
2095     htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2096   get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2097   get_result->type = htons (type);
2098   memcpy (&get_result[1], data, size);
2099   new_msg_ctx->peer = &my_identity;
2100   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2101   new_msg_ctx->hop_count = 0;
2102   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2103   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2104   increment_stats(STAT_GET_RESPONSE_START);
2105   route_result_message(cls, &get_result->header, new_msg_ctx);
2106   GNUNET_free(new_msg_ctx);
2107   //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2108   //                      datacache_get_ctx->unique_id);
2109   GNUNET_free (get_result);
2110   return GNUNET_OK;
2111 }
2112
2113
2114 /**
2115  * Server handler for all dht get requests, look for data,
2116  * if found, send response either to clients or other peers.
2117  *
2118  * @param cls closure for service
2119  * @param msg the actual get message
2120  * @param message_context struct containing pertinent information about the get request
2121  *
2122  * @return number of items found for GET request
2123  */
2124 static unsigned int
2125 handle_dht_get (void *cls, 
2126                 const struct GNUNET_MessageHeader *msg,
2127                 struct DHT_MessageContext *message_context)
2128 {
2129   const struct GNUNET_DHT_GetMessage *get_msg;
2130   uint16_t get_type;
2131   unsigned int results;
2132
2133   get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2134   if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2135     {
2136       GNUNET_break (0);
2137       return 0;
2138     }
2139
2140   get_type = ntohs (get_msg->type);
2141 #if DEBUG_DHT
2142   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2143               "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2144               "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2145               message_context->unique_id);
2146 #endif
2147   increment_stats(STAT_GETS);
2148   results = 0;
2149   if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2150     return results;
2151
2152   if (datacache != NULL)
2153     results =
2154       GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2155                             &datacache_get_iterator, message_context);
2156
2157   if (results >= 1)
2158     {
2159 #if DEBUG_DHT
2160       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2161                   "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2162                   results, "GET", message_context->unique_id);
2163 #endif
2164 #if DEBUG_DHT_ROUTING
2165       if ((debug_routes) && (dhtlog_handle != NULL))
2166         {
2167           dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2168                                 message_context->hop_count, GNUNET_YES, &my_identity,
2169                                 &message_context->key);
2170         }
2171
2172       if ((debug_routes_extended) && (dhtlog_handle != NULL))
2173         {
2174           dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2175                                        message_context->hop_count, GNUNET_YES,
2176                                        &my_identity, &message_context->key, message_context->peer,
2177                                        NULL);
2178         }
2179 #endif
2180     }
2181
2182   if (message_context->hop_count == 0) /* Locally initiated request */
2183     {
2184 #if DEBUG_DHT_ROUTING
2185     if ((debug_routes) && (dhtlog_handle != NULL))
2186       {
2187         dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2188                                       message_context->hop_count, GNUNET_NO, &my_identity,
2189                                       &message_context->key);
2190       }
2191 #endif
2192     }
2193
2194   return results;
2195 }
2196
2197 static void
2198 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2199 {
2200   GNUNET_HashCode *key = cls;
2201   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2202     {
2203       GNUNET_free(key);
2204     }
2205 }
2206
2207 /**
2208  * Server handler for initiating local dht find peer requests
2209  *
2210  * @param cls closure for service
2211  * @param find_msg the actual find peer message
2212  * @param message_context struct containing pertinent information about the request
2213  *
2214  */
2215 static void
2216 handle_dht_find_peer (void *cls,
2217                       const struct GNUNET_MessageHeader *find_msg,
2218                       struct DHT_MessageContext *message_context)
2219 {
2220   struct GNUNET_MessageHeader *find_peer_result;
2221   struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2222   struct DHT_MessageContext *new_msg_ctx;
2223   struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2224   size_t hello_size;
2225   size_t tsize;
2226   GNUNET_HashCode *recent_hash;
2227 #if RESTRICT_FIND_PEER
2228   struct GNUNET_PeerIdentity peer_id;
2229 #endif
2230
2231   find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2232 #if DEBUG_DHT
2233   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2234               "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2235               my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2236               ntohs (find_msg->size),
2237               sizeof (struct GNUNET_MessageHeader));
2238 #endif
2239   if (my_hello == NULL)
2240   {
2241 #if DEBUG_DHT
2242     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2243                 "`%s': Our HELLO is null, can't return.\n",
2244                 "DHT");
2245 #endif
2246     return;
2247   }
2248
2249   incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2250   if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2251     {
2252       increment_stats(STAT_BLOOM_FIND_PEER);
2253       GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2254       return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2255     }
2256   GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2257
2258 #if RESTRICT_FIND_PEER
2259
2260   /**
2261    * Ignore any find peer requests from a peer we have seen very recently.
2262    */
2263   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! */
2264   {
2265     increment_stats("# dht find peer requests ignored (recently seen!)");
2266     return;
2267   }
2268
2269   /**
2270    * Use this check to only allow the peer to respond to find peer requests if
2271    * it would be beneficial to have the requesting peer in this peers routing
2272    * table.  Can be used to thwart peers flooding the network with find peer
2273    * requests that we don't care about.  However, if a new peer is joining
2274    * the network and has no other peers this is a problem (assume all buckets
2275    * full, no one will respond!).
2276    */
2277   memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2278   if (GNUNET_NO == consider_peer(&peer_id))
2279     {
2280       increment_stats("# dht find peer requests ignored (do not need!)");
2281       return;
2282     }
2283 #endif
2284
2285   recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2286   memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2287   GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2288   GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2289
2290   /* Simplistic find_peer functionality, always return our hello */
2291   hello_size = ntohs(my_hello->size);
2292   tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2293
2294   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2295     {
2296       GNUNET_break_op (0);
2297       return;
2298     }
2299
2300   find_peer_result = GNUNET_malloc (tsize);
2301   find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2302   find_peer_result->size = htons (tsize);
2303   memcpy (&find_peer_result[1], my_hello, hello_size);
2304
2305   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2306               "`%s': Sending hello size %d to requesting peer.\n",
2307               "DHT", hello_size);
2308
2309   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2310   memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2311   new_msg_ctx->peer = &my_identity;
2312   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2313   new_msg_ctx->hop_count = 0;
2314   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2315   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2316   increment_stats(STAT_FIND_PEER_ANSWER);
2317   route_result_message(cls, find_peer_result, new_msg_ctx);
2318   GNUNET_free(new_msg_ctx);
2319 #if DEBUG_DHT_ROUTING
2320   if ((debug_routes) && (dhtlog_handle != NULL))
2321     {
2322       dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2323                                    message_context->hop_count, GNUNET_YES, &my_identity,
2324                                    &message_context->key);
2325     }
2326 #endif
2327   GNUNET_free(find_peer_result);
2328 }
2329
2330 /**
2331  * Task used to republish data.
2332  * Forward declaration; function call loop.
2333  *
2334  * @param cls closure (a struct RepublishContext)
2335  * @param tc runtime context for this task
2336  */
2337 static void
2338 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2339
2340 /**
2341  * Server handler for initiating local dht put requests
2342  *
2343  * @param cls closure for service
2344  * @param msg the actual put message
2345  * @param message_context struct containing pertinent information about the request
2346  */
2347 static void
2348 handle_dht_put (void *cls,
2349                 const struct GNUNET_MessageHeader *msg,
2350                 struct DHT_MessageContext *message_context)
2351 {
2352   struct GNUNET_DHT_PutMessage *put_msg;
2353   size_t put_type;
2354   size_t data_size;
2355   int ret;
2356   struct RepublishContext *put_context;
2357
2358   GNUNET_assert (ntohs (msg->size) >=
2359                  sizeof (struct GNUNET_DHT_PutMessage));
2360
2361
2362   put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2363   put_type = ntohs (put_msg->type);
2364
2365   if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2366     return;
2367
2368   data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2369 #if DEBUG_DHT
2370   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2371               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2372               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2373 #endif
2374 #if DEBUG_DHT_ROUTING
2375   if (message_context->hop_count == 0) /* Locally initiated request */
2376     {
2377       if ((debug_routes) && (dhtlog_handle != NULL))
2378         {
2379           dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2380                                        message_context->hop_count, GNUNET_NO, &my_identity,
2381                                        &message_context->key);
2382         }
2383     }
2384 #endif
2385
2386   if (message_context->closest != GNUNET_YES)
2387     return;
2388
2389 #if DEBUG_DHT_ROUTING
2390   if ((debug_routes_extended) && (dhtlog_handle != NULL))
2391     {
2392       dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2393                                    message_context->hop_count, GNUNET_YES,
2394                                    &my_identity, &message_context->key, message_context->peer,
2395                                    NULL);
2396     }
2397
2398   if ((debug_routes) && (dhtlog_handle != NULL))
2399     {
2400       dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2401                                    message_context->hop_count, GNUNET_YES, &my_identity,
2402                                    &message_context->key);
2403     }
2404 #endif
2405
2406   increment_stats(STAT_PUTS_INSERTED);
2407   if (datacache != NULL)
2408     {
2409       ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2410                                   (char *) &put_msg[1], put_type,
2411                                   GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2412
2413       if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2414         {
2415           put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2416           memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2417           put_context->type = put_type;
2418           GNUNET_SCHEDULER_add_delayed (sched, DHT_REPUBLISH_FREQUENCY, &republish_content, put_context);
2419         }
2420     }
2421   else
2422     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2423                 "`%s:%s': %s request received, but have no datacache!\n",
2424                 my_short_id, "DHT", "PUT");
2425 }
2426
2427 /**
2428  * Estimate the diameter of the network based
2429  * on how many buckets are currently in use.
2430  * Concept here is that the diameter of the network
2431  * is roughly the distance a message must travel in
2432  * order to reach its intended destination.  Since
2433  * at each hop we expect to get one bit closer, and
2434  * we have one bit per bucket, the number of buckets
2435  * in use should be the largest number of hops for
2436  * a sucessful message. (of course, this assumes we
2437  * know all peers in the network!)
2438  *
2439  * @return ballpark diameter figure
2440  */
2441 static unsigned int estimate_diameter()
2442 {
2443   return MAX_BUCKETS - lowest_bucket;
2444 }
2445
2446 /**
2447  * To how many peers should we (on average)
2448  * forward the request to obtain the desired
2449  * target_replication count (on average).
2450  *
2451  * Always 0, 1 or 2 (don't send, send once, split)
2452  */
2453 static unsigned int
2454 get_forward_count (unsigned int hop_count, size_t target_replication)
2455 {
2456 #if DOUBLE
2457   double target_count;
2458   double random_probability;
2459 #else
2460   uint32_t random_value;
2461 #endif
2462   unsigned int target_value;
2463   unsigned int diameter;
2464
2465   /**
2466    * If we are behaving in strict kademlia mode, send multiple initial requests,
2467    * but then only send to 1 or 0 peers based strictly on the number of hops.
2468    */
2469   if (strict_kademlia == GNUNET_YES)
2470     {
2471       if (hop_count == 0)
2472         return DHT_KADEMLIA_REPLICATION;
2473       else if (hop_count < MAX_HOPS)
2474         return 1;
2475       else
2476         return 0;
2477     }
2478
2479   /* FIXME: the smaller we think the network is the more lenient we should be for
2480    * routing right?  The estimation below only works if we think we have reasonably
2481    * full routing tables, which for our RR topologies may not be the case!
2482    */
2483   diameter = estimate_diameter ();
2484   if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2485     {
2486 #if DEBUG_DHT
2487       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2488                   "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2489                   "DHT", estimate_diameter(), lowest_bucket);
2490 #endif
2491       return 0;
2492     }
2493   else if (hop_count > MAX_HOPS)
2494     {
2495 #if DEBUG_DHT
2496       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2497                   "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2498                   "DHT");
2499 #endif
2500       return 0;
2501     }
2502
2503 #if DOUBLE
2504   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2505   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2506   target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2507     (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2508   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2509   random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2510       RAND_MAX)) / RAND_MAX;
2511   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2512
2513   target_value = 0;
2514   //while (target_value < target_count)
2515   if (target_value < target_count)
2516     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? */
2517
2518
2519   //if ((target_count + 1 - (double)target_value) > random_probability)
2520   if ((target_count) > random_probability)
2521     target_value++;
2522 #endif
2523
2524   random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2525   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));
2526   target_value = 1;
2527   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2528   if (random_value < target_replication)
2529     target_value++;
2530
2531   return target_value;
2532 }
2533
2534 /*
2535  * Check whether my identity is closer than any known peers.
2536  * If a non-null bloomfilter is given, check if this is the closest
2537  * peer that hasn't already been routed to.
2538  *
2539  * @param target hash code to check closeness to
2540  * @param bloom bloomfilter, exclude these entries from the decision
2541  *
2542  * Return GNUNET_YES if node location is closest, GNUNET_NO
2543  * otherwise.
2544  */
2545 int
2546 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2547 {
2548   int bits;
2549   int other_bits;
2550   int bucket_num;
2551   int count;
2552   struct PeerInfo *pos;
2553   unsigned int my_distance;
2554
2555   bucket_num = find_current_bucket(target);
2556   if (bucket_num == GNUNET_SYSERR) /* Same key! */
2557     return GNUNET_YES;
2558
2559   bits = matching_bits(&my_identity.hashPubKey, target);
2560   my_distance = distance(&my_identity.hashPubKey, target);
2561   pos = k_buckets[bucket_num].head;
2562   count = 0;
2563   while ((pos != NULL) && (count < bucket_size))
2564     {
2565       if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2566         {
2567           pos = pos->next;
2568           continue; /* Skip already checked entries */
2569         }
2570
2571       other_bits = matching_bits(&pos->id.hashPubKey, target);
2572       if (other_bits > bits)
2573         return GNUNET_NO;
2574       else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2575         {
2576           if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2577             return GNUNET_YES;
2578           else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2579             return GNUNET_NO;
2580         }
2581       pos = pos->next;
2582     }
2583
2584 #if DEBUG_TABLE
2585   GNUNET_GE_LOG (coreAPI->ectx,
2586                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2587                  GNUNET_GE_BULK, "closest peer\n");
2588   printPeerBits (&closest);
2589   GNUNET_GE_LOG (coreAPI->ectx,
2590                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2591                  GNUNET_GE_BULK, "me\n");
2592   printPeerBits (coreAPI->my_identity);
2593   GNUNET_GE_LOG (coreAPI->ectx,
2594                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2595                  GNUNET_GE_BULK, "key\n");
2596   printKeyBits (target);
2597   GNUNET_GE_LOG (coreAPI->ectx,
2598                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2599                  GNUNET_GE_BULK,
2600                  "closest peer inverse distance is %u, mine is %u\n",
2601                  inverse_distance (target, &closest.hashPubKey),
2602                  inverse_distance (target,
2603                                    &coreAPI->my_identity->hashPubKey));
2604 #endif
2605
2606   /* No peers closer, we are the closest! */
2607   return GNUNET_YES;
2608
2609 }
2610
2611 /**
2612  * Decide whether to route this request exclusively
2613  * to a closer peer (if closer peers exist) or to choose
2614  * from the whole set of peers.
2615  *
2616  * @param target the key of the request
2617  * @param bloom bloomfilter of peers this request has already traversed
2618  * @param hops number of hops this message has already traveled
2619  *
2620  * @return GNUNET_YES if we should try to route to a closer peer
2621  *         than ourselves (and one exists), GNUNET_NO if we should
2622  *         choose from the set of all known peers
2623  *
2624  */
2625 int
2626 route_closer (const GNUNET_HashCode *target,
2627               struct GNUNET_CONTAINER_BloomFilter *bloom,
2628               unsigned int hops)
2629 {
2630   unsigned int my_matching_bits;
2631   unsigned int bc;
2632   uint32_t random_value;
2633   struct PeerInfo *pos;
2634   int have_closer;
2635   int count;
2636   my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2637
2638   /**
2639    * First check if we know any close (as close as us or closer) peers.
2640    */
2641   have_closer = GNUNET_NO;
2642   count = 0;
2643   for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2644     {
2645       pos = k_buckets[bc].head;
2646       count = 0;
2647       while ((pos != NULL) && (count < bucket_size))
2648         {
2649           if ((matching_bits(target, &pos->id.hashPubKey) > my_matching_bits) &&
2650               (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
2651             {
2652               have_closer = GNUNET_YES;
2653               break;
2654             }
2655           pos = pos->next;
2656           count++;
2657         }
2658       if (have_closer == GNUNET_YES)
2659         break;
2660     }
2661
2662   if (have_closer == GNUNET_NO) /* We don't have a same distance or closer node, can't enforce closer only! */
2663     return GNUNET_NO;
2664
2665   switch (converge_option)
2666     {
2667       case DHT_CONVERGE_LINEAR:
2668         /**
2669          * Simple linear curve for choosing whether or not to converge.
2670          * Choose to route only closer with probability hops/MAX_HOPS.
2671          */
2672         random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, MAX_HOPS);
2673         if (random_value < hops)
2674           return GNUNET_YES;
2675         else
2676           return GNUNET_NO;
2677       case DHT_CONVERGE_SQUARE:
2678         /**
2679          * Simple square based curve.
2680          */
2681         if ((GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1) / (double)(uint32_t)-1) < (sqrt(hops) / sqrt(MAX_HOPS)))
2682           return GNUNET_YES;
2683         else
2684           return GNUNET_NO;
2685       default:
2686         return GNUNET_NO;
2687     }
2688 }
2689
2690 /**
2691  * Select a peer from the routing table that would be a good routing
2692  * destination for sending a message for "target".  The resulting peer
2693  * must not be in the set of blocked peers.<p>
2694  *
2695  * Note that we should not ALWAYS select the closest peer to the
2696  * target, peers further away from the target should be chosen with
2697  * exponentially declining probability.
2698  *
2699  * @param target the key we are selecting a peer to route to
2700  * @param bloom a bloomfilter containing entries this request has seen already
2701  * @param hops the number of hops this message has already traversed
2702  *
2703  * @return Peer to route to, or NULL on error
2704  */
2705 static struct PeerInfo *
2706 select_peer (const GNUNET_HashCode * target,
2707              struct GNUNET_CONTAINER_BloomFilter *bloom,
2708              unsigned int hops)
2709 {
2710   unsigned int distance;
2711   unsigned int bc;
2712   unsigned int count;
2713   unsigned int my_matching_bits;
2714   unsigned long long largest_distance;
2715   unsigned long long total_real_distance;
2716   unsigned long long real_selected;
2717   unsigned int total_distance;
2718   unsigned int selected;
2719   unsigned int match_num;
2720   int only_closer;
2721   struct PeerInfo *pos;
2722   struct PeerInfo *chosen;
2723   char *temp_stat;
2724 #if DEBUG_DHT_ROUTING > 1
2725   double sum;
2726 #endif
2727
2728   my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2729   only_closer = route_closer(target, bloom, hops);
2730
2731   if (GNUNET_YES == only_closer)
2732     {
2733       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "only routing to closer peers!\n");
2734       GNUNET_asprintf(&temp_stat, "# closer only routes at hop %u", hops);
2735       increment_stats(temp_stat);
2736     }
2737   else
2738     {
2739       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "routing to all possible peers!\n");
2740       GNUNET_asprintf(&temp_stat, "# NOT closer only routes at hop %u", hops);
2741       increment_stats(temp_stat);
2742     }
2743
2744   GNUNET_free(temp_stat);
2745   total_real_distance = 0;
2746   if (strict_kademlia == GNUNET_YES)
2747     {
2748       largest_distance = 0;
2749       chosen = NULL;
2750       for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2751         {
2752           pos = k_buckets[bc].head;
2753           count = 0;
2754           while ((pos != NULL) && (count < bucket_size))
2755             {
2756               /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2757               if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2758                 {
2759                   distance = inverse_distance (target, &pos->id.hashPubKey);
2760                   if (distance > largest_distance)
2761                     {
2762                       chosen = pos;
2763                       largest_distance = distance;
2764                     }
2765                 }
2766               count++;
2767               pos = pos->next;
2768             }
2769         }
2770
2771       if ((largest_distance > 0) && (chosen != NULL))
2772         {
2773           GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2774           return chosen;
2775         }
2776       else
2777         {
2778           return NULL;
2779         }
2780     }
2781   else
2782     {
2783       /* GNUnet-style */
2784       total_distance = 0;
2785       for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2786         {
2787           pos = k_buckets[bc].head;
2788           count = 0;
2789           while ((pos != NULL) && (count < bucket_size))
2790             {
2791               if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2792                   ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2793                 {
2794                   if (GNUNET_YES == use_real_distance)
2795                     total_real_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2796                   else
2797                     {
2798                       /* Always add 1, in case 0 bits match! */
2799                       match_num = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target ,&pos->id.hashPubKey));
2800                       total_distance += match_num;
2801                     }
2802                 }
2803   #if DEBUG_DHT > 1
2804               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2805                           "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2806                           my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2807   #endif
2808               pos = pos->next;
2809               count++;
2810             }
2811         }
2812
2813       if (((GNUNET_YES == use_real_distance) && (total_real_distance == 0)) || (total_distance == 0))
2814         {
2815           increment_stats("# select_peer, total_distance == 0");
2816           return NULL;
2817         }
2818
2819 #if DEBUG_DHT_ROUTING > 1
2820       sum = 0.0;
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 #endif
2847       real_selected = 0;
2848       selected = 0;
2849       if (use_real_distance)
2850         {
2851           GNUNET_assert(total_real_distance != 0);
2852           real_selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_real_distance);
2853         }
2854       else
2855         {
2856           GNUNET_assert(total_distance != 0);
2857           selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2858         }
2859
2860       for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2861         {
2862           pos = k_buckets[bc].head;
2863           count = 0;
2864           while ((pos != NULL) && (count < bucket_size))
2865             {
2866               if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2867                   ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2868                 {
2869                  if (GNUNET_YES == use_real_distance)
2870                    {
2871                     distance = inverse_distance (target, &pos->id.hashPubKey);
2872                     if (distance > real_selected)
2873                       {
2874                         GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "(REAL) Selected peer with %u matching bits to route to\n", matching_bits(target, &pos->id.hashPubKey));
2875                         return pos;
2876                       }
2877                     real_selected -= distance;
2878                    }
2879                   else
2880                     {
2881                       distance = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target, &pos->id.hashPubKey));
2882                       if (distance > selected)
2883                         {
2884                           GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Selected peer with %u matching bits to route to\n", matching_bits(target, &pos->id.hashPubKey));
2885                           return pos;
2886                         }
2887                       selected -= distance;
2888                     }
2889                 }
2890               else
2891                 {
2892   #if DEBUG_DHT
2893                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2894                               "`%s:%s': peer %s matches bloomfilter.\n",
2895                               my_short_id, "DHT", GNUNET_i2s(&pos->id));
2896   #endif
2897                 }
2898               pos = pos->next;
2899               count++;
2900             }
2901         }
2902   #if DEBUG_DHT
2903         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2904                     "`%s:%s': peer %s matches bloomfilter.\n",
2905                     my_short_id, "DHT", GNUNET_i2s(&pos->id));
2906   #endif
2907       increment_stats("# failed to select peer");
2908       GNUNET_assert(only_closer == GNUNET_NO);
2909       return NULL;
2910     }
2911 }
2912
2913 /**
2914  * Task used to remove recent entries, either
2915  * after timeout, when full, or on shutdown.
2916  *
2917  * @param cls the entry to remove
2918  * @param tc context, reason, etc.
2919  */
2920 static void
2921 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2922 {
2923   struct RecentRequest *req = cls;
2924   static GNUNET_HashCode hash;
2925
2926   GNUNET_assert(req != NULL);
2927   hash_from_uid(req->uid, &hash);
2928   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
2929   GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
2930   GNUNET_CONTAINER_bloomfilter_free(req->bloom);
2931   GNUNET_free(req);
2932
2933   if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
2934   {
2935     GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
2936     GNUNET_CONTAINER_heap_destroy(recent.minHeap);
2937   }
2938 }
2939
2940
2941 /**
2942  * Task used to remove forwarding entries, either
2943  * after timeout, when full, or on shutdown.
2944  *
2945  * @param cls the entry to remove
2946  * @param tc context, reason, etc.
2947  */
2948 static void
2949 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2950 {
2951   struct DHTRouteSource *source_info = cls;
2952   struct DHTQueryRecord *record;
2953   source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2954   record = source_info->record;
2955   GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2956
2957   if (record->head == NULL) /* No more entries in DLL */
2958     {
2959       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2960       GNUNET_free(record);
2961     }
2962   if (source_info->find_peers_responded != NULL)
2963     GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
2964   GNUNET_free(source_info);
2965 }
2966
2967 /**
2968  * Remember this routing request so that if a reply is
2969  * received we can either forward it to the correct peer
2970  * or return the result locally.
2971  *
2972  * @param cls DHT service closure
2973  * @param msg_ctx Context of the route request
2974  *
2975  * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2976  */
2977 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2978 {
2979   struct DHTQueryRecord *record;
2980   struct DHTRouteSource *source_info;
2981   struct DHTRouteSource *pos;
2982   struct GNUNET_TIME_Absolute now;
2983   unsigned int current_size;
2984
2985   current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2986   while (current_size >= MAX_OUTSTANDING_FORWARDS)
2987     {
2988       source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2989       GNUNET_assert(source_info != NULL);
2990       record = source_info->record;
2991       GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2992       if (record->head == NULL) /* No more entries in DLL */
2993         {
2994           GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2995           GNUNET_free(record);
2996         }
2997       GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2998       if (source_info->find_peers_responded != NULL)
2999         GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3000       GNUNET_free(source_info);
3001       current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3002     }
3003   now = GNUNET_TIME_absolute_get();
3004   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3005   if (record != NULL) /* Already know this request! */
3006     {
3007       pos = record->head;
3008       while (pos != NULL)
3009         {
3010           if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3011             break; /* Already have this peer in reply list! */
3012           pos = pos->next;
3013         }
3014       if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3015         {
3016           GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3017           return GNUNET_NO;
3018         }
3019     }
3020   else
3021     {
3022       record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3023       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3024       memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3025     }
3026
3027   source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3028   source_info->record = record;
3029   source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3030   source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3031   memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3032   GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3033   if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3034     {
3035       source_info->client = msg_ctx->client;
3036       now = GNUNET_TIME_absolute_get_forever();
3037     }
3038   source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3039 #if DEBUG_DHT > 1
3040       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3041                   "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3042                   "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
3043 #endif
3044   return GNUNET_YES;
3045 }
3046
3047
3048 /**
3049  * Main function that handles whether or not to route a message to other
3050  * peers.
3051  *
3052  * @param cls closure for dht service (NULL)
3053  * @param msg the message to be routed
3054  * @param message_context the context containing all pertinent information about the message
3055  *
3056  * @return the number of peers the message was routed to,
3057  *         GNUNET_SYSERR on failure
3058  */
3059 static int route_message(void *cls,
3060                          const struct GNUNET_MessageHeader *msg,
3061                          struct DHT_MessageContext *message_context)
3062 {
3063   int i;
3064   int global_closest;
3065   struct PeerInfo *selected;
3066 #if DEBUG_DHT_ROUTING > 1
3067   struct PeerInfo *nearest;
3068 #endif
3069   unsigned int forward_count;
3070   struct RecentRequest *recent_req;
3071   GNUNET_HashCode unique_hash;
3072   char *stat_forward_count;
3073 #if DEBUG_DHT_ROUTING
3074   int ret;
3075 #endif
3076
3077   if (malicious_dropper == GNUNET_YES)
3078     {
3079 #if DEBUG_DHT_ROUTING
3080       if ((debug_routes_extended) && (dhtlog_handle != NULL))
3081         {
3082           dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3083                                        message_context->hop_count, GNUNET_SYSERR,
3084                                        &my_identity, &message_context->key, message_context->peer,
3085                                        NULL);
3086         }
3087 #endif
3088       if (message_context->bloom != NULL)
3089         GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3090       return 0;
3091     }
3092
3093   increment_stats(STAT_ROUTES);
3094   /* Semantics of this call means we find whether we are the closest peer out of those already
3095    * routed to on this messages path.
3096    */
3097   global_closest = am_closest_peer(&message_context->key, NULL);
3098   message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3099   forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3100   GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3101   increment_stats(stat_forward_count);
3102   GNUNET_free(stat_forward_count);
3103   if (message_context->bloom == NULL)
3104     message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3105
3106   if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3107     forward_count = 0;
3108
3109   /**
3110    * NOTICE:  In Kademlia, a find peer request goes no further if the peer doesn't return
3111    * any closer peers (which is being checked for below).  Since we are doing recursive
3112    * routing we have no choice but to stop forwarding in this case.  This means that at
3113    * any given step the request may NOT be forwarded to alpha peers (because routes will
3114    * stop and the parallel route will not be aware of it).  Of course, assuming that we
3115    * have fulfilled the Kademlia requirements for routing table fullness this will never
3116    * ever ever be a problem.
3117    *
3118    * However, is this fair?
3119    *
3120    * Since we use these requests to build our routing tables (and we build them in the
3121    * testing driver) we will ignore this restriction for FIND_PEER messages so that
3122    * routing tables still get constructed.
3123    */
3124   if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3125     forward_count = 0;
3126
3127 #if DEBUG_DHT_ROUTING
3128   if (forward_count == 0)
3129     ret = GNUNET_SYSERR;
3130   else
3131     ret = GNUNET_NO;
3132
3133   if ((debug_routes_extended) && (dhtlog_handle != NULL))
3134     {
3135       dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3136                                    message_context->hop_count, ret,
3137                                    &my_identity, &message_context->key, message_context->peer,
3138                                    NULL);
3139     }
3140 #endif
3141
3142   switch (ntohs(msg->type))
3143     {
3144     case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3145       cache_response (cls, message_context);
3146       if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3147         forward_count = 0;
3148       break;
3149     case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3150       increment_stats(STAT_PUTS);
3151       message_context->closest = global_closest;
3152       handle_dht_put (cls, msg, message_context);
3153       break;
3154     case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3155       increment_stats(STAT_FIND_PEER);
3156       if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3157       {
3158         cache_response (cls, message_context);
3159         if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3160           handle_dht_find_peer (cls, msg, message_context);
3161       }
3162 #if DEBUG_DHT_ROUTING
3163       if (message_context->hop_count == 0) /* Locally initiated request */
3164         {
3165           if ((debug_routes) && (dhtlog_handle != NULL))
3166             {
3167               dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3168               dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3169                                            message_context->hop_count, GNUNET_NO, &my_identity,
3170                                            &message_context->key);
3171             }
3172         }
3173 #endif
3174       break;
3175     default:
3176       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3177                   "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3178     }
3179
3180   GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3181   hash_from_uid(message_context->unique_id, &unique_hash);
3182   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent.hashmap, &unique_hash))
3183   {
3184       recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3185       GNUNET_assert(recent_req != NULL);
3186       if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3187         increment_stats(STAT_DUPLICATE_UID);
3188       else
3189       {
3190         increment_stats(STAT_RECENT_SEEN);
3191         GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3192       }
3193     }
3194   else
3195     {
3196       recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3197       recent_req->uid = message_context->unique_id;
3198       memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3199       recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3200       recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3201       recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3202       GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3203     }
3204
3205   if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3206     {
3207       recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3208       GNUNET_assert(recent_req != NULL);
3209       GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3210       GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3211     }
3212
3213   for (i = 0; i < forward_count; i++)
3214     {
3215       selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3216
3217       if (selected != NULL)
3218         {
3219           GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3220 #if DEBUG_DHT_ROUTING > 1
3221           nearest = find_closest_peer(&message_context->key);
3222           nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3223           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3224                       "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3225                       "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));
3226           GNUNET_free(nearest_buf);
3227 #endif
3228 #if DEBUG_DHT_ROUTING
3229           if ((debug_routes_extended) && (dhtlog_handle != NULL))
3230             {
3231               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3232                                            message_context->hop_count, GNUNET_NO,
3233                                            &my_identity, &message_context->key, message_context->peer,
3234                                            &selected->id);
3235             }
3236 #endif
3237           forward_message(cls, msg, selected, message_context);
3238         }
3239       else
3240         {
3241           increment_stats("# NULL returned from select_peer");
3242           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3243                       "`%s:%s': No peers selected for forwarding.\n", my_short_id,
3244                       "DHT");
3245
3246         }
3247     }
3248 #if DEBUG_DHT_ROUTING > 1
3249   if (forward_count == 0)
3250     {
3251       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3252                   "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
3253                   "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
3254     }
3255 #endif
3256
3257   if (message_context->bloom != NULL)
3258     {
3259       GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3260       GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3261     }
3262
3263   return forward_count;
3264 }
3265
3266 /**
3267  * Iterator for local get request results,
3268  *
3269  * @param cls closure for iterator, NULL
3270  * @param exp when does this value expire?
3271  * @param key the key this data is stored under
3272  * @param size the size of the data identified by key
3273  * @param data the actual data
3274  * @param type the type of the data
3275  *
3276  * @return GNUNET_OK to continue iteration, anything else
3277  * to stop iteration.
3278  */
3279 static int
3280 republish_content_iterator (void *cls,
3281                             struct GNUNET_TIME_Absolute exp,
3282                             const GNUNET_HashCode * key,
3283                             uint32_t size, const char *data, uint32_t type)
3284 {
3285
3286   struct DHT_MessageContext *new_msg_ctx;
3287   struct GNUNET_DHT_PutMessage *put_msg;
3288 #if DEBUG_DHT
3289   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3290               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3291 #endif
3292   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3293
3294   put_msg =
3295     GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3296   put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3297   put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3298   put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3299   put_msg->type = htons (type);
3300   memcpy (&put_msg[1], data, size);
3301   new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3302   new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3303   new_msg_ctx->msg_options = ntohl (0);
3304   new_msg_ctx->network_size = estimate_diameter();
3305   new_msg_ctx->peer = &my_identity;
3306   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3307   new_msg_ctx->hop_count = 0;
3308   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3309   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3310   increment_stats(STAT_PUT_START);
3311   route_message(cls, &put_msg->header, new_msg_ctx);
3312
3313   GNUNET_free(new_msg_ctx);
3314   GNUNET_free (put_msg);
3315   return GNUNET_OK;
3316 }
3317
3318 /**
3319  * Task used to republish data.
3320  *
3321  * @param cls closure (a struct RepublishContext)
3322  * @param tc runtime context for this task
3323  */
3324 static void
3325 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3326 {
3327   struct RepublishContext *put_context = cls;
3328
3329   unsigned int results;
3330
3331   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3332     {
3333       GNUNET_free(put_context);
3334       return;
3335     }
3336
3337   GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3338   results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3339   if (results == 0) /* Data must have expired */
3340     GNUNET_free(put_context);
3341   else /* Reschedule task for next time period */
3342     GNUNET_SCHEDULER_add_delayed(sched, DHT_REPUBLISH_FREQUENCY, &republish_content, put_context);
3343
3344 }
3345
3346 /**
3347  * Find a client if it exists, add it otherwise.
3348  *
3349  * @param client the server handle to the client
3350  *
3351  * @return the client if found, a new client otherwise
3352  */
3353 static struct ClientList *
3354 find_active_client (struct GNUNET_SERVER_Client *client)
3355 {
3356   struct ClientList *pos = client_list;
3357   struct ClientList *ret;
3358
3359   while (pos != NULL)
3360     {
3361       if (pos->client_handle == client)
3362         return pos;
3363       pos = pos->next;
3364     }
3365
3366   ret = GNUNET_malloc (sizeof (struct ClientList));
3367   ret->client_handle = client;
3368   ret->next = client_list;
3369   client_list = ret;
3370   return ret;
3371 }
3372
3373 /**
3374  * Task to send a malicious put message across the network.
3375  *
3376  * @param cls closure for this task
3377  * @param tc the context under which the task is running
3378  */
3379 static void
3380 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3381 {
3382   static struct GNUNET_DHT_PutMessage put_message;
3383   static struct DHT_MessageContext message_context;
3384   static GNUNET_HashCode key;
3385   uint32_t random_key;
3386
3387   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3388     return;
3389
3390   put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3391   put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3392   put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3393   put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3394   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3395   message_context.client = NULL;
3396   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3397   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3398   memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3399   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3400   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3401   message_context.msg_options = ntohl (0);
3402   message_context.network_size = estimate_diameter();
3403   message_context.peer = &my_identity;
3404   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3405   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3406 #if DEBUG_DHT_ROUTING
3407   if (dhtlog_handle != NULL)
3408     dhtlog_handle->insert_dhtkey(NULL, &key);
3409 #endif
3410   increment_stats(STAT_PUT_START);
3411   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3412   route_message(NULL, &put_message.header, &message_context);
3413   GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3414
3415 }
3416
3417 /**
3418  * Task to send a malicious put message across the network.
3419  *
3420  * @param cls closure for this task
3421  * @param tc the context under which the task is running
3422  */
3423 static void
3424 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3425 {
3426   static struct GNUNET_DHT_GetMessage get_message;
3427   struct DHT_MessageContext message_context;
3428   static GNUNET_HashCode key;
3429   uint32_t random_key;
3430
3431   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3432     return;
3433
3434   get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3435   get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3436   get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3437   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3438   message_context.client = NULL;
3439   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3440   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3441   memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3442   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3443   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3444   message_context.msg_options = ntohl (0);
3445   message_context.network_size = estimate_diameter();
3446   message_context.peer = &my_identity;
3447   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3448   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3449 #if DEBUG_DHT_ROUTING
3450   if (dhtlog_handle != NULL)
3451     dhtlog_handle->insert_dhtkey(NULL, &key);
3452 #endif
3453   increment_stats(STAT_GET_START);
3454   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3455   route_message (NULL, &get_message.header, &message_context);
3456   GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3457 }
3458
3459 /**
3460  * Iterator over hash map entries.
3461  *
3462  * @param cls closure
3463  * @param key current key code
3464  * @param value value in the hash map
3465  * @return GNUNET_YES if we should continue to
3466  *         iterate,
3467  *         GNUNET_NO if not.
3468  */
3469 static int
3470 add_known_to_bloom (void *cls,
3471                     const GNUNET_HashCode * key,
3472                     void *value)
3473 {
3474   struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3475   GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3476   return GNUNET_YES;
3477 }
3478
3479 /**
3480  * Task to send a find peer message for our own peer identifier
3481  * so that we can find the closest peers in the network to ourselves
3482  * and attempt to connect to them.
3483  *
3484  * @param cls closure for this task
3485  * @param tc the context under which the task is running
3486  */
3487 static void
3488 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3489 {
3490   struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3491   struct DHT_MessageContext message_context;
3492   int ret;
3493   struct GNUNET_TIME_Relative next_send_time;
3494   struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3495 #if COUNT_INTERVAL
3496   struct GNUNET_TIME_Relative time_diff;
3497   struct GNUNET_TIME_Absolute end;
3498   double multiplier;
3499   double count_per_interval;
3500 #endif
3501   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3502     return;
3503
3504   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! */
3505     {
3506       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3507       GNUNET_SCHEDULER_add_delayed (sched,
3508                                     GNUNET_TIME_UNIT_MINUTES,
3509                                     &send_find_peer_message, NULL);
3510       newly_found_peers = 0;
3511       return;
3512     }
3513     
3514   increment_stats(STAT_FIND_PEER_START);
3515 #if COUNT_INTERVAL
3516   end = GNUNET_TIME_absolute_get();
3517   time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3518
3519   if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3520     {
3521       multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3522       count_per_interval = find_peer_context.count / multiplier;
3523     }
3524   else
3525     {
3526       multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3527       count_per_interval = find_peer_context.count * multiplier;
3528     }
3529 #endif
3530
3531   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3532   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3533   find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3534   temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3535   GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3536   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3537   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3538   memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3539   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3540   message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3541   message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3542   message_context.network_size = estimate_diameter();
3543   message_context.peer = &my_identity;
3544   message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3545   message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3546
3547   ret = route_message(NULL, &find_peer_msg->header, &message_context);
3548   GNUNET_free(find_peer_msg);
3549   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3550               "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3551               "FIND PEER", ret);
3552   if (newly_found_peers < bucket_size)
3553     {
3554       next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3555                               GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3556                                                        DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3557     }
3558   else
3559     {
3560       next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3561                              GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3562                                                       DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3563     }
3564
3565   GNUNET_assert (next_send_time.value != 0);
3566   find_peer_context.count = 0;
3567   newly_found_peers = 0;
3568   find_peer_context.start = GNUNET_TIME_absolute_get();
3569   if (GNUNET_YES == do_find_peer)
3570   {
3571     GNUNET_SCHEDULER_add_delayed (sched,
3572                                   next_send_time,
3573                                   &send_find_peer_message, NULL);
3574   }
3575 }
3576
3577 /**
3578  * Handler for any generic DHT messages, calls the appropriate handler
3579  * depending on message type, sends confirmation if responses aren't otherwise
3580  * expected.
3581  *
3582  * @param cls closure for the service
3583  * @param client the client we received this message from
3584  * @param message the actual message received
3585  */
3586 static void
3587 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3588                                 const struct GNUNET_MessageHeader *message)
3589 {
3590   const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3591   const struct GNUNET_MessageHeader *enc_msg;
3592   struct DHT_MessageContext message_context;
3593   enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3594 #if DEBUG_DHT
3595   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3596               "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3597               my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3598               GNUNET_ntohll (dht_msg->unique_id));
3599 #endif
3600 #if DEBUG_DHT_ROUTING
3601   if (dhtlog_handle != NULL)
3602     dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3603 #endif
3604   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3605   message_context.client = find_active_client (client);
3606   memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3607   message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3608   message_context.replication = ntohl (dht_msg->desired_replication_level);
3609   message_context.msg_options = ntohl (dht_msg->options);
3610   message_context.network_size = estimate_diameter();
3611   message_context.peer = &my_identity;
3612   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3613   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3614   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3615     increment_stats(STAT_GET_START);
3616   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3617     increment_stats(STAT_PUT_START);
3618   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3619     increment_stats(STAT_FIND_PEER_START);
3620
3621   route_message(cls, enc_msg, &message_context);
3622
3623   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3624
3625 }
3626
3627 /**
3628  * Handler for any locally received DHT control messages,
3629  * sets malicious flags mostly for now.
3630  *
3631  * @param cls closure for the service
3632  * @param client the client we received this message from
3633  * @param message the actual message received
3634  *
3635  */
3636 static void
3637 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3638                             const struct GNUNET_MessageHeader *message)
3639 {
3640   const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3641       (const struct GNUNET_DHT_ControlMessage *) message;
3642 #if DEBUG_DHT
3643   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3644               "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3645               "CONTROL", ntohs(dht_control_msg->command));
3646 #endif
3647
3648   switch (ntohs(dht_control_msg->command))
3649   {
3650   case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3651     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3652     GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3653     break;
3654   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3655     if (ntohs(dht_control_msg->variable) > 0)
3656       malicious_get_frequency = ntohs(dht_control_msg->variable);
3657     if (malicious_get_frequency == 0)
3658       malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3659     if (malicious_getter != GNUNET_YES)
3660       GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3661     malicious_getter = GNUNET_YES;
3662     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3663     break;
3664   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3665     if (ntohs(dht_control_msg->variable) > 0)
3666       malicious_put_frequency = ntohs(dht_control_msg->variable);
3667     if (malicious_put_frequency == 0)
3668       malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3669     if (malicious_putter != GNUNET_YES)
3670       GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3671     malicious_putter = GNUNET_YES;
3672     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3673     break;
3674   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3675 #if DEBUG_DHT_ROUTING
3676     if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3677       dhtlog_handle->set_malicious(&my_identity);
3678 #endif
3679     malicious_dropper = GNUNET_YES;
3680     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3681     break;
3682   default:
3683     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3684   }
3685
3686   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3687 }
3688
3689 /**
3690  * Handler for any generic DHT stop messages, calls the appropriate handler
3691  * depending on message type (if processed locally)
3692  *
3693  * @param cls closure for the service
3694  * @param client the client we received this message from
3695  * @param message the actual message received
3696  *
3697  */
3698 static void
3699 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3700                             const struct GNUNET_MessageHeader *message)
3701 {
3702
3703   const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3704     (const struct GNUNET_DHT_StopMessage *) message;
3705   struct DHTQueryRecord *record;
3706   struct DHTRouteSource *pos;
3707 #if DEBUG_DHT
3708   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3709               "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3710               "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3711 #endif
3712   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3713   if (record != NULL)
3714     {
3715       pos = record->head;
3716
3717       while (pos != NULL)
3718         {
3719           if ((pos->client != NULL) && (pos->client->client_handle == client))
3720             {
3721               GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3722               GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3723             }
3724           pos = pos->next;
3725         }
3726     }
3727
3728   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3729 }
3730
3731
3732 /**
3733  * Core handler for p2p route requests.
3734  */
3735 static int
3736 handle_dht_p2p_route_request (void *cls,
3737                               const struct GNUNET_PeerIdentity *peer,
3738                               const struct GNUNET_MessageHeader *message,
3739                               struct GNUNET_TIME_Relative latency, uint32_t distance)
3740 {
3741 #if DEBUG_DHT
3742   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3743               "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3744 #endif
3745   struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3746   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3747   struct DHT_MessageContext *message_context;
3748
3749   if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
3750   {
3751     fprintf(stderr, "Sending of previous replies took far too long, backing off!\n");
3752     decrease_max_send_delay(get_max_send_delay());
3753     return GNUNET_YES;
3754   }
3755
3756   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3757     {
3758 #if DEBUG_PING
3759       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3760 #endif
3761       return GNUNET_YES;
3762     }
3763
3764   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
3765     {
3766       GNUNET_break_op(0);
3767       return GNUNET_YES;
3768     }
3769   message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3770   message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3771   GNUNET_assert(message_context->bloom != NULL);
3772   message_context->hop_count = ntohl(incoming->hop_count);
3773   memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
3774   message_context->replication = ntohl(incoming->desired_replication_level);
3775   message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3776   message_context->msg_options = ntohl(incoming->options);
3777   message_context->network_size = ntohl(incoming->network_size);
3778   message_context->peer = peer;
3779   message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3780   message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3781   route_message(cls, enc_msg, message_context);
3782   GNUNET_free(message_context);
3783   return GNUNET_YES;
3784 }
3785
3786
3787 /**
3788  * Core handler for p2p route results.
3789  */
3790 static int
3791 handle_dht_p2p_route_result (void *cls,
3792                              const struct GNUNET_PeerIdentity *peer,
3793                              const struct GNUNET_MessageHeader *message,
3794                              struct GNUNET_TIME_Relative latency, uint32_t distance)
3795 {
3796 #if DEBUG_DHT
3797   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3798               "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3799 #endif
3800   struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3801   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3802   struct DHT_MessageContext message_context;
3803
3804   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
3805     {
3806       GNUNET_break_op(0);
3807       return GNUNET_YES;
3808     }
3809
3810   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3811   message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3812   GNUNET_assert(message_context.bloom != NULL);
3813   memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
3814   message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3815   message_context.msg_options = ntohl(incoming->options);
3816   message_context.hop_count = ntohl(incoming->hop_count);
3817   message_context.peer = peer;
3818   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3819   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3820   route_result_message(cls, enc_msg, &message_context);
3821   return GNUNET_YES;
3822 }
3823
3824
3825 /**
3826  * Receive the HELLO from transport service,
3827  * free current and replace if necessary.
3828  *
3829  * @param cls NULL
3830  * @param message HELLO message of peer
3831  */
3832 static void
3833 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3834 {
3835 #if DEBUG_DHT
3836   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3837               "Received our `%s' from transport service\n",
3838               "HELLO");
3839 #endif
3840
3841   GNUNET_assert (message != NULL);
3842   GNUNET_free_non_null(my_hello);
3843   my_hello = GNUNET_malloc(ntohs(message->size));
3844   memcpy(my_hello, message, ntohs(message->size));
3845 }
3846
3847
3848 /**
3849  * Task run during shutdown.
3850  *
3851  * @param cls unused
3852  * @param tc unused
3853  */
3854 static void
3855 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3856 {
3857   int bucket_count;
3858   struct PeerInfo *pos;
3859   if (transport_handle != NULL)
3860   {
3861     GNUNET_free_non_null(my_hello);
3862     GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3863     GNUNET_TRANSPORT_disconnect(transport_handle);
3864   }
3865
3866   for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3867     {
3868       while (k_buckets[bucket_count].head != NULL)
3869         {
3870           pos = k_buckets[bucket_count].head;
3871 #if DEBUG_DHT
3872           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3873                       "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3874 #endif
3875           delete_peer(pos, bucket_count);
3876         }
3877     }
3878   if (coreAPI != NULL)
3879     {
3880 #if DEBUG_DHT
3881       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3882                   "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3883 #endif
3884       GNUNET_CORE_disconnect (coreAPI);
3885     }
3886   if (datacache != NULL)
3887     {
3888 #if DEBUG_DHT
3889       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3890                   "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3891 #endif
3892       GNUNET_DATACACHE_destroy (datacache);
3893     }
3894
3895   if (stats != NULL)
3896     {
3897       GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3898     }
3899
3900   if (dhtlog_handle != NULL)
3901     GNUNET_DHTLOG_disconnect(dhtlog_handle);
3902
3903   GNUNET_free_non_null(my_short_id);
3904 }
3905
3906
3907 /**
3908  * To be called on core init/fail.
3909  *
3910  * @param cls service closure
3911  * @param server handle to the server for this service
3912  * @param identity the public identity of this peer
3913  * @param publicKey the public key of this peer
3914  */
3915 void
3916 core_init (void *cls,
3917            struct GNUNET_CORE_Handle *server,
3918            const struct GNUNET_PeerIdentity *identity,
3919            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3920 {
3921
3922   if (server == NULL)
3923     {
3924 #if DEBUG_DHT
3925   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3926               "%s: Connection to core FAILED!\n", "dht",
3927               GNUNET_i2s (identity));
3928 #endif
3929       GNUNET_SCHEDULER_cancel (sched, cleanup_task);
3930       GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3931       return;
3932     }
3933 #if DEBUG_DHT
3934   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3935               "%s: Core connection initialized, I am peer: %s\n", "dht",
3936               GNUNET_i2s (identity));
3937 #endif
3938
3939   /* Copy our identity so we can use it */
3940   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3941   if (my_short_id != NULL)
3942     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3943   my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3944   /* Set the server to local variable */
3945   coreAPI = server;
3946
3947   if (dhtlog_handle != NULL)
3948     dhtlog_handle->insert_node (NULL, &my_identity);
3949 }
3950
3951
3952 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3953   {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3954   {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3955   {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
3956   {NULL, NULL, 0, 0}
3957 };
3958
3959
3960 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3961   {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
3962   {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
3963   {NULL, 0, 0}
3964 };
3965
3966 /**
3967  * Method called whenever a peer connects.
3968  *
3969  * @param cls closure
3970  * @param peer peer identity this notification is about
3971  * @param latency reported latency of the connection with peer
3972  * @param distance reported distance (DV) to peer
3973  */
3974 void handle_core_connect (void *cls,
3975                           const struct GNUNET_PeerIdentity * peer,
3976                           struct GNUNET_TIME_Relative latency,
3977                           uint32_t distance)
3978 {
3979   struct PeerInfo *ret;
3980
3981 #if DEBUG_DHT
3982   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3983               "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
3984 #endif
3985
3986   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3987     {
3988       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));
3989       return;
3990     }
3991
3992   if (datacache != NULL)
3993     GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
3994   ret = try_add_peer(peer,
3995                      find_current_bucket(&peer->hashPubKey),
3996                      latency,
3997                      distance);
3998   if (ret != NULL)
3999     {
4000       newly_found_peers++;
4001       GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4002     }
4003 #if DEBUG_DHT
4004     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4005                 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4006 #endif
4007 }
4008
4009 /**
4010  * Method called whenever a peer disconnects.
4011  *
4012  * @param cls closure
4013  * @param peer peer identity this notification is about
4014  */
4015 void handle_core_disconnect (void *cls,
4016                              const struct
4017                              GNUNET_PeerIdentity * peer)
4018 {
4019   struct PeerInfo *to_remove;
4020   int current_bucket;
4021
4022   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");
4023
4024   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4025     {
4026       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));
4027       return;
4028     }
4029   increment_stats(STAT_DISCONNECTS);
4030   GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4031   to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4032   GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4033   current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4034   delete_peer(to_remove, current_bucket);
4035 }
4036
4037 /**
4038  * Process dht requests.
4039  *
4040  * @param cls closure
4041  * @param scheduler scheduler to use
4042  * @param server the initialized server
4043  * @param c configuration to use
4044  */
4045 static void
4046 run (void *cls,
4047      struct GNUNET_SCHEDULER_Handle *scheduler,
4048      struct GNUNET_SERVER_Handle *server,
4049      const struct GNUNET_CONFIGURATION_Handle *c)
4050 {
4051 #if DO_FIND_PEER
4052   struct GNUNET_TIME_Relative next_send_time;
4053 #endif
4054   sched = scheduler;
4055   cfg = c;
4056   datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4057   GNUNET_SERVER_add_handlers (server, plugin_handlers);
4058   coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4059                                  cfg,   /* Main configuration */
4060                                  GNUNET_TIME_UNIT_FOREVER_REL,
4061                                  NULL,  /* Closure passed to DHT functions */
4062                                  &core_init,    /* Call core_init once connected */
4063                                  &handle_core_connect,  /* Handle connects */
4064                                  &handle_core_disconnect,  /* remove peers on disconnects */
4065                                  NULL,  /* Do we care about "status" updates? */
4066                                  NULL,  /* Don't want notified about all incoming messages */
4067                                  GNUNET_NO,     /* For header only inbound notification */
4068                                  NULL,  /* Don't want notified about all outbound messages */
4069                                  GNUNET_NO,     /* For header only outbound notification */
4070                                  core_handlers);        /* Register these handlers */
4071
4072   if (coreAPI == NULL)
4073     return;
4074   transport_handle = GNUNET_TRANSPORT_connect(sched, cfg, 
4075                                               NULL, NULL, NULL, NULL, NULL);
4076   if (transport_handle != NULL)
4077     GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4078   else
4079     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4080
4081   lowest_bucket = MAX_BUCKETS - 1;
4082   forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4083   forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4084   all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4085   recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4086   GNUNET_assert(all_known_peers != NULL);
4087   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4088     {
4089       debug_routes = GNUNET_YES;
4090     }
4091
4092   if (GNUNET_YES ==
4093       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4094                                            "strict_kademlia"))
4095     {
4096       strict_kademlia = GNUNET_YES;
4097     }
4098
4099   if (GNUNET_YES ==
4100       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4101                                            "stop_on_closest"))
4102     {
4103       stop_on_closest = GNUNET_YES;
4104     }
4105
4106   if (GNUNET_YES ==
4107       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4108                                            "stop_found"))
4109     {
4110       stop_on_found = GNUNET_YES;
4111     }
4112
4113   if (GNUNET_YES ==
4114       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4115                                            "malicious_getter"))
4116     {
4117       malicious_getter = GNUNET_YES;
4118       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4119                                             "MALICIOUS_GET_FREQUENCY",
4120                                             &malicious_get_frequency))
4121         malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4122     }
4123
4124   if (GNUNET_YES ==
4125       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4126                                            "malicious_putter"))
4127     {
4128       malicious_putter = GNUNET_YES;
4129       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4130                                             "MALICIOUS_PUT_FREQUENCY",
4131                                             &malicious_put_frequency))
4132         malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4133     }
4134
4135   if (GNUNET_YES ==
4136           GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4137                                                "malicious_dropper"))
4138     {
4139       malicious_dropper = GNUNET_YES;
4140     }
4141
4142   if (GNUNET_YES ==
4143         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4144                                              "republish"))
4145     do_republish = GNUNET_NO;
4146
4147   if (GNUNET_NO ==
4148         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4149                                              "do_find_peer"))
4150     {
4151       do_find_peer = GNUNET_NO;
4152     }
4153   else
4154     do_find_peer = GNUNET_YES;
4155
4156   if (GNUNET_YES ==
4157         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4158                                              "use_real_distance"))
4159     use_real_distance = GNUNET_YES;
4160
4161   if (GNUNET_YES ==
4162       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4163                                            "mysql_logging_extended"))
4164     {
4165       debug_routes = GNUNET_YES;
4166       debug_routes_extended = GNUNET_YES;
4167     }
4168
4169 #if DEBUG_DHT_ROUTING
4170   if (GNUNET_YES == debug_routes)
4171     {
4172       dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4173       if (dhtlog_handle == NULL)
4174         {
4175           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4176                       "Could not connect to mysql logging server, logging will not happen!");
4177         }
4178     }
4179 #endif
4180
4181   converge_option = DHT_CONVERGE_SQUARE;
4182   if (GNUNET_YES ==
4183       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4184                                            "converge_linear"))
4185     {
4186       converge_option = DHT_CONVERGE_LINEAR;
4187     }
4188
4189   stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4190
4191   if (stats != NULL)
4192     {
4193       GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4194       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4195       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4196       GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4197       GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4198       GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4199       GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4200       GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4201       GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4202       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4203       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4204       GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4205       GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4206       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4207       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4208       GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4209       GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4210       GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4211       GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4212       GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4213     }
4214   /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4215   recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4216   recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4217   if (GNUNET_YES == do_find_peer)
4218   {
4219     next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4220                            GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4221                                                     (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4222     find_peer_context.start = GNUNET_TIME_absolute_get();
4223     GNUNET_SCHEDULER_add_delayed (sched,
4224                                   next_send_time,
4225                                   &send_find_peer_message, &find_peer_context);
4226   }
4227
4228   /* Scheduled the task to clean up when shutdown is called */
4229   cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4230                                                GNUNET_TIME_UNIT_FOREVER_REL,
4231                                                &shutdown_task, NULL);
4232 }
4233
4234 /**
4235  * The main function for the dht service.
4236  *
4237  * @param argc number of arguments from the command line
4238  * @param argv command line arguments
4239  * @return 0 ok, 1 on error
4240  */
4241 int
4242 main (int argc, char *const *argv)
4243 {
4244   return (GNUNET_OK ==
4245           GNUNET_SERVICE_run (argc,
4246                               argv,
4247                               "dht",
4248                               GNUNET_SERVICE_OPTION_NONE,
4249                               &run, NULL)) ? 0 : 1;
4250 }