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