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