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