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