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