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