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