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