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