send multiple messages to peer if possible
[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  * Main function that handles whether or not to route a result
1969  * message to other peers, or to send to our local client.
1970  *
1971  * @param msg the result message to be routed
1972  * @param msg_ctx context of the message we are routing
1973  *
1974  * @return the number of peers the message was routed to,
1975  *         GNUNET_SYSERR on failure
1976  */
1977 static int route_result_message(struct GNUNET_MessageHeader *msg,
1978                                 struct DHT_MessageContext *msg_ctx)
1979 {
1980   struct GNUNET_PeerIdentity new_peer;
1981   struct DHTQueryRecord *record;
1982   struct DHTRouteSource *pos;
1983   struct PeerInfo *peer_info;
1984   const struct GNUNET_MessageHeader *hello_msg;
1985
1986   increment_stats(STAT_RESULTS);
1987   /**
1988    * If a find peer result message is received and contains a valid
1989    * HELLO for another peer, offer it to the transport service.
1990    */
1991   if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1992     {
1993       if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1994         GNUNET_break_op(0);
1995
1996       hello_msg = &msg[1];
1997       if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1998       {
1999         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
2000         GNUNET_break_op(0);
2001         return GNUNET_NO;
2002       }
2003       else /* We have a valid hello, and peer id stored in new_peer */
2004       {
2005         find_peer_context.count++;
2006         increment_stats(STAT_FIND_PEER_REPLY);
2007         if (GNUNET_YES == consider_peer(&new_peer))
2008         {
2009           increment_stats(STAT_HELLOS_PROVIDED);
2010           GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
2011           GNUNET_CORE_peer_request_connect(coreAPI, 
2012                                            GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
2013         }
2014       }
2015     }
2016
2017   if (malicious_dropper == GNUNET_YES)
2018     record = NULL;
2019   else
2020     record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2021
2022   if (record == NULL) /* No record of this message! */
2023     {
2024 #if DEBUG_DHT
2025     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2026                 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
2027                 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2028 #endif
2029 #if DEBUG_DHT_ROUTING
2030       if ((debug_routes_extended) && (dhtlog_handle != NULL))
2031         {
2032           dhtlog_handle->insert_route (NULL,
2033                                        msg_ctx->unique_id,
2034                                        DHTLOG_RESULT,
2035                                        msg_ctx->hop_count,
2036                                        GNUNET_SYSERR,
2037                                        &my_identity,
2038                                        &msg_ctx->key,
2039                                        msg_ctx->peer, NULL);
2040         }
2041 #endif
2042       if (msg_ctx->bloom != NULL)
2043         {
2044           GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
2045           msg_ctx->bloom = NULL;
2046         }
2047       return 0;
2048     }
2049
2050   pos = record->head;
2051   while (pos != NULL)
2052     {
2053 #if STRICT_FORWARDING
2054       if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2055         {
2056           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2057           {
2058             increment_stats("# find peer responses NOT forwarded (bloom match)");
2059             pos = pos->next;
2060             continue;
2061           }
2062           else
2063             GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2064         }
2065 #endif
2066
2067       if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2068         {
2069 #if DEBUG_DHT
2070           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2071                       "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2072                       "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2073 #endif
2074 #if DEBUG_DHT_ROUTING
2075           if ((debug_routes_extended) && (dhtlog_handle != NULL))
2076             {
2077               dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2078                                            msg_ctx->hop_count,
2079                                            GNUNET_YES, &my_identity, &msg_ctx->key,
2080                                            msg_ctx->peer, NULL);
2081             }
2082 #endif
2083           increment_stats(STAT_RESULTS_TO_CLIENT);
2084           if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2085             increment_stats(STAT_GET_REPLY);
2086
2087           send_reply_to_client(pos->client, msg, 
2088                                msg_ctx->unique_id,
2089                                &msg_ctx->key);
2090         }
2091       else /* Send to peer */
2092         {
2093           peer_info = find_peer_by_id(&pos->source);
2094           if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2095             {
2096               pos = pos->next;
2097               continue;
2098             }
2099
2100           if (msg_ctx->bloom == NULL)
2101             msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2102           GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
2103           if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom, &peer_info->id.hashPubKey)))
2104             {
2105 #if DEBUG_DHT
2106               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2107                           "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2108                           "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&peer_info->id));
2109 #endif
2110 #if DEBUG_DHT_ROUTING
2111               if ((debug_routes_extended) && (dhtlog_handle != NULL))
2112                 {
2113                   dhtlog_handle->insert_route (NULL, msg_ctx->unique_id,
2114                                                DHTLOG_RESULT,
2115                                                msg_ctx->hop_count,
2116                                                GNUNET_NO, &my_identity, &msg_ctx->key,
2117                                                msg_ctx->peer, &pos->source);
2118                 }
2119 #endif
2120               forward_result_message(msg, peer_info, msg_ctx);
2121             }
2122           else
2123             {
2124 #if DEBUG_DHT
2125               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2126                           "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2127                           "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&peer_info->id));
2128 #endif
2129             }
2130         }
2131       pos = pos->next;
2132     }
2133   if (msg_ctx->bloom != NULL)
2134   {
2135     GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
2136     msg_ctx->bloom = NULL;
2137   }
2138   return 0;
2139 }
2140
2141 /**
2142  * Iterator for local get request results,
2143  *
2144  * @param cls closure for iterator, a DatacacheGetContext
2145  * @param exp when does this value expire?
2146  * @param key the key this data is stored under
2147  * @param size the size of the data identified by key
2148  * @param data the actual data
2149  * @param type the type of the data
2150  *
2151  * @return GNUNET_OK to continue iteration, anything else
2152  * to stop iteration.
2153  */
2154 static int
2155 datacache_get_iterator (void *cls,
2156                         struct GNUNET_TIME_Absolute exp,
2157                         const GNUNET_HashCode * key,
2158                         size_t size, const char *data, 
2159                         enum GNUNET_BLOCK_Type type)
2160 {
2161   struct DHT_MessageContext *msg_ctx = cls;
2162   struct DHT_MessageContext *new_msg_ctx;
2163   struct GNUNET_DHT_GetResultMessage *get_result;
2164   enum GNUNET_BLOCK_EvaluationResult eval;
2165
2166 #if DEBUG_DHT
2167   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2168               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2169 #endif  
2170   eval = GNUNET_BLOCK_evaluate (block_context,
2171                                 type,
2172                                 key,
2173                                 &msg_ctx->reply_bf,
2174                                 msg_ctx->reply_bf_mutator,
2175                                 msg_ctx->xquery,
2176                                 msg_ctx->xquery_size,
2177                                 data,
2178                                 size);
2179   switch (eval)
2180     {
2181     case GNUNET_BLOCK_EVALUATION_OK_LAST:
2182       msg_ctx->do_forward = GNUNET_NO;
2183     case GNUNET_BLOCK_EVALUATION_OK_MORE:
2184       new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2185       memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2186       get_result =
2187         GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2188       get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2189       get_result->header.size =
2190         htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2191       get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2192       get_result->type = htons (type);
2193       memcpy (&get_result[1], data, size);
2194       new_msg_ctx->peer = &my_identity;
2195       new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2196       new_msg_ctx->hop_count = 0;
2197       new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
2198       new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2199       increment_stats(STAT_GET_RESPONSE_START);
2200       route_result_message(&get_result->header, new_msg_ctx);
2201       GNUNET_free(new_msg_ctx);
2202       GNUNET_free (get_result);
2203       break;
2204     case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2205 #if DEBUG_DHT
2206       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2207                   "`%s:%s': Duplicate block error\n", my_short_id, "DHT");
2208 #endif
2209       break;
2210     case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2211 #if DEBUG_DHT
2212       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2213                   "`%s:%s': Invalid request error\n", my_short_id, "DHT");
2214 #endif
2215       break;
2216     case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2217 #if DEBUG_DHT
2218       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2219                   "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2220 #endif
2221       GNUNET_break (0);
2222       break;
2223     case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2224       GNUNET_break_op (0);
2225       msg_ctx->do_forward = GNUNET_NO;
2226       break;
2227     case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2228 #if DEBUG_DHT
2229       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2230                   "`%s:%s': Unsupported block type (%u) in response!\n", my_short_id, "DHT", type);
2231 #endif
2232       /* msg_ctx->do_forward = GNUNET_NO;  // not sure... */
2233       break;
2234     }  
2235   return GNUNET_OK;
2236 }
2237
2238
2239 /**
2240  * Main function that handles whether or not to route a message to other
2241  * peers.
2242  *
2243  * @param msg the message to be routed
2244  * @param msg_ctx the context containing all pertinent information about the message
2245  */
2246 static void
2247 route_message(const struct GNUNET_MessageHeader *msg,
2248                struct DHT_MessageContext *msg_ctx);
2249
2250
2251 /**
2252  * Server handler for all dht get requests, look for data,
2253  * if found, send response either to clients or other peers.
2254  *
2255  * @param msg the actual get message
2256  * @param msg_ctx struct containing pertinent information about the get request
2257  *
2258  * @return number of items found for GET request
2259  */
2260 static unsigned int
2261 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2262                 struct DHT_MessageContext *msg_ctx)
2263 {
2264   const struct GNUNET_DHT_GetMessage *get_msg;
2265   uint16_t msize;
2266   uint16_t bf_size;
2267   unsigned int results;
2268   const char *end;
2269   enum GNUNET_BLOCK_Type type;
2270
2271   msize = ntohs (msg->size);
2272   if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2273     {
2274       GNUNET_break (0);
2275       return 0;
2276     }
2277   get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2278   bf_size = ntohs (get_msg->bf_size);
2279   msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2280   msg_ctx->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2281   if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2282     {
2283       GNUNET_break (0);
2284       return 0;
2285     }
2286   end = (const char*) &get_msg[1];
2287   if (msg_ctx->xquery_size == 0)
2288     {
2289       msg_ctx->xquery = NULL;
2290     }
2291   else
2292     {
2293       msg_ctx->xquery = (const void*) end;
2294       end += msg_ctx->xquery_size;
2295     }
2296   if (bf_size == 0)
2297     {
2298       msg_ctx->reply_bf = NULL;
2299     }
2300   else
2301     {
2302       msg_ctx->reply_bf = GNUNET_CONTAINER_bloomfilter_init (end,
2303                                                                      bf_size,
2304                                                                      GNUNET_DHT_GET_BLOOMFILTER_K);
2305     }
2306   type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2307 #if DEBUG_DHT
2308   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2309               "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2310               my_short_id,
2311               "DHT", "GET", 
2312               type,
2313               GNUNET_h2s (&msg_ctx->key),
2314               msg_ctx->unique_id);
2315 #endif
2316   increment_stats(STAT_GETS);
2317   results = 0;
2318 #if HAVE_MALICIOUS
2319   if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2320     {
2321       GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2322       return results;
2323     }
2324 #endif
2325   msg_ctx->do_forward = GNUNET_YES;
2326   if (datacache != NULL)
2327     results
2328       = GNUNET_DATACACHE_get (datacache,
2329                               &msg_ctx->key, type,
2330                               &datacache_get_iterator,
2331                               msg_ctx);
2332 #if DEBUG_DHT
2333       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2334                   "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2335                   results, "GET", msg_ctx->unique_id);
2336 #endif
2337   if (results >= 1)
2338     {
2339 #if DEBUG_DHT_ROUTING
2340       if ((debug_routes) && (dhtlog_handle != NULL))
2341         {
2342           dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2343                                 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2344                                 &msg_ctx->key);
2345         }
2346
2347       if ((debug_routes_extended) && (dhtlog_handle != NULL))
2348         {
2349           dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2350                                        msg_ctx->hop_count, GNUNET_YES,
2351                                        &my_identity, &msg_ctx->key, msg_ctx->peer,
2352                                        NULL);
2353         }
2354 #endif
2355     }
2356   else
2357     {
2358       /* check query valid */
2359       if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID
2360           == GNUNET_BLOCK_evaluate (block_context,
2361                                     type,
2362                                     &msg_ctx->key,
2363                                     &msg_ctx->reply_bf,
2364                                     msg_ctx->reply_bf_mutator,
2365                                     msg_ctx->xquery,
2366                                     msg_ctx->xquery_size,
2367                                     NULL, 0))
2368         {
2369           GNUNET_break_op (0);
2370           msg_ctx->do_forward = GNUNET_NO;
2371         }
2372     }
2373
2374   if (msg_ctx->hop_count == 0) /* Locally initiated request */
2375     {
2376 #if DEBUG_DHT_ROUTING
2377     if ((debug_routes) && (dhtlog_handle != NULL))
2378       {
2379         dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2380                                       msg_ctx->hop_count, GNUNET_NO, &my_identity,
2381                                       &msg_ctx->key);
2382       }
2383 #endif
2384     }
2385   if (msg_ctx->do_forward == GNUNET_YES)
2386     route_message (msg, msg_ctx);
2387   GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2388   return results;
2389 }
2390
2391 static void
2392 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2393 {
2394   GNUNET_HashCode *key = cls;
2395   
2396   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, NULL));
2397   GNUNET_free (key);
2398 }
2399
2400 /**
2401  * Server handler for initiating local dht find peer requests
2402  *
2403  * @param find_msg the actual find peer message
2404  * @param msg_ctx struct containing pertinent information about the request
2405  *
2406  */
2407 static void
2408 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2409                       struct DHT_MessageContext *msg_ctx)
2410 {
2411   struct GNUNET_MessageHeader *find_peer_result;
2412   struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2413   struct DHT_MessageContext *new_msg_ctx;
2414   struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2415   size_t hello_size;
2416   size_t tsize;
2417   GNUNET_HashCode *recent_hash;
2418   struct GNUNET_MessageHeader *other_hello;
2419   size_t other_hello_size;
2420   struct GNUNET_PeerIdentity peer_id;
2421
2422   find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2423   GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2424   if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2425     return;
2426   other_hello = NULL;
2427   other_hello_size = 0;
2428   if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2429     {
2430       other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2431       other_hello = GNUNET_malloc(other_hello_size);
2432       memcpy(other_hello, &find_peer_message[1], other_hello_size);
2433       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)))
2434         {
2435           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2436           GNUNET_free(other_hello);
2437           return;
2438         }
2439 #if FIND_PEER_WITH_HELLO
2440       if (GNUNET_YES == consider_peer(&peer_id))
2441         {
2442           increment_stats(STAT_HELLOS_PROVIDED);
2443           GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2444           GNUNET_CORE_peer_request_connect(coreAPI, 
2445                                            GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2446           route_message (find_msg, msg_ctx);
2447           GNUNET_free (other_hello);
2448           return;
2449         }
2450       else /* We don't want this peer! */
2451         {
2452           route_message (find_msg, msg_ctx);
2453           GNUNET_free (other_hello);
2454           return;
2455         }
2456 #endif
2457     }
2458
2459 #if DEBUG_DHT
2460   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2461               "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2462               my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2463               ntohs (find_msg->size),
2464               sizeof (struct GNUNET_MessageHeader));
2465 #endif
2466   if (my_hello == NULL)
2467   {
2468 #if DEBUG_DHT
2469     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2470                 "`%s': Our HELLO is null, can't return.\n",
2471                 "DHT");
2472 #endif
2473     GNUNET_free_non_null (other_hello);
2474     route_message (find_msg, msg_ctx);
2475     return;
2476   }
2477
2478   incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2479   if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2480     {
2481       increment_stats(STAT_BLOOM_FIND_PEER);
2482       GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2483       GNUNET_free_non_null(other_hello);
2484       route_message (find_msg, msg_ctx);
2485       return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2486     }
2487   GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2488
2489 #if RESTRICT_FIND_PEER
2490
2491   /**
2492    * Ignore any find peer requests from a peer we have seen very recently.
2493    */
2494   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! */
2495   {
2496     increment_stats("# dht find peer requests ignored (recently seen!)");
2497     GNUNET_free_non_null(other_hello);
2498     return;
2499   }
2500
2501   /**
2502    * Use this check to only allow the peer to respond to find peer requests if
2503    * it would be beneficial to have the requesting peer in this peers routing
2504    * table.  Can be used to thwart peers flooding the network with find peer
2505    * requests that we don't care about.  However, if a new peer is joining
2506    * the network and has no other peers this is a problem (assume all buckets
2507    * full, no one will respond!).
2508    */
2509   memcpy(&peer_id.hashPubKey, &msg_ctx->key, sizeof(GNUNET_HashCode));
2510   if (GNUNET_NO == consider_peer(&peer_id))
2511     {
2512       increment_stats("# dht find peer requests ignored (do not need!)");
2513       GNUNET_free_non_null(other_hello);
2514       route_message (find_msg, msg_ctx);
2515       return;
2516     }
2517 #endif
2518
2519   recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2520   memcpy(recent_hash, &msg_ctx->key, sizeof(GNUNET_HashCode));
2521   if (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2522                                      &msg_ctx->key, NULL,
2523                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2524     {
2525       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding recent remove task for key `%s`!\n", GNUNET_h2s(&msg_ctx->key));
2526       /* Only add a task if there wasn't one for this key already! */
2527       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30),
2528                                     &remove_recent_find_peer, recent_hash);
2529     }
2530   else
2531     {
2532       GNUNET_free(recent_hash);
2533       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received duplicate find peer request too soon!\n");
2534     }
2535
2536   /* Simplistic find_peer functionality, always return our hello */
2537   hello_size = ntohs(my_hello->size);
2538   tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2539
2540   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2541     {
2542       GNUNET_break_op (0);
2543       GNUNET_free_non_null(other_hello);
2544       return;
2545     }
2546
2547   find_peer_result = GNUNET_malloc (tsize);
2548   find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2549   find_peer_result->size = htons (tsize);
2550   memcpy (&find_peer_result[1], my_hello, hello_size);
2551
2552   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2553               "`%s': Sending hello size %d to requesting peer.\n",
2554               "DHT", hello_size);
2555
2556   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2557   memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2558   new_msg_ctx->peer = &my_identity;
2559   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2560   new_msg_ctx->hop_count = 0;
2561   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make find peer requests a higher priority */
2562   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2563   increment_stats(STAT_FIND_PEER_ANSWER);
2564   route_result_message(find_peer_result, new_msg_ctx);
2565   GNUNET_free(new_msg_ctx);
2566 #if DEBUG_DHT_ROUTING
2567   if ((debug_routes) && (dhtlog_handle != NULL))
2568     {
2569       dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2570                                    msg_ctx->hop_count, GNUNET_YES, &my_identity,
2571                                    &msg_ctx->key);
2572     }
2573 #endif
2574   GNUNET_free_non_null(other_hello);
2575   GNUNET_free(find_peer_result);
2576   route_message (find_msg, msg_ctx);
2577 }
2578
2579 /**
2580  * Task used to republish data.
2581  * Forward declaration; function call loop.
2582  *
2583  * @param cls closure (a struct RepublishContext)
2584  * @param tc runtime context for this task
2585  */
2586 static void
2587 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2588
2589 /**
2590  * Server handler for initiating local dht put requests
2591  *
2592  * @param msg the actual put message
2593  * @param msg_ctx struct containing pertinent information about the request
2594  */
2595 static void
2596 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2597                 struct DHT_MessageContext *msg_ctx)
2598 {
2599   const struct GNUNET_DHT_PutMessage *put_msg;
2600   enum GNUNET_BLOCK_Type put_type;
2601   size_t data_size;
2602   int ret;
2603   struct RepublishContext *put_context;
2604   GNUNET_HashCode key;
2605
2606   GNUNET_assert (ntohs (msg->size) >=
2607                  sizeof (struct GNUNET_DHT_PutMessage));
2608
2609
2610   put_msg = (const struct GNUNET_DHT_PutMessage *)msg;
2611   put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2612 #if HAVE_MALICIOUS
2613   if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2614     {
2615 #if DEBUG_DHT_ROUTING
2616       if ((debug_routes_extended) && (dhtlog_handle != NULL))
2617         {
2618           /** Log routes that die due to high load! */
2619           dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2620                                        msg_ctx->hop_count, GNUNET_SYSERR,
2621                                        &my_identity, &msg_ctx->key, msg_ctx->peer,
2622                                        NULL);
2623         }
2624 #endif
2625       return;
2626     }
2627 #endif
2628   data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2629   ret = GNUNET_BLOCK_get_key (block_context,
2630                               put_type,
2631                               &put_msg[1],
2632                               data_size,
2633                               &key);
2634   if (GNUNET_NO == ret)
2635     {
2636 #if DEBUG_DHT_ROUTING
2637       if ((debug_routes_extended) && (dhtlog_handle != NULL))
2638         {
2639           /** Log routes that die due to high load! */
2640           dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2641                                        msg_ctx->hop_count, GNUNET_SYSERR,
2642                                        &my_identity, &msg_ctx->key, msg_ctx->peer,
2643                                        NULL);
2644         }
2645 #endif
2646       /* invalid reply */
2647       GNUNET_break_op (0);
2648       return;
2649     }
2650   if ( (GNUNET_YES == ret) &&
2651        (0 != memcmp (&key,
2652                      &msg_ctx->key,
2653                      sizeof (GNUNET_HashCode))) )
2654     {
2655 #if DEBUG_DHT_ROUTING
2656       if ((debug_routes_extended) && (dhtlog_handle != NULL))
2657         {
2658           /** Log routes that die due to high load! */
2659           dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2660                                        msg_ctx->hop_count, GNUNET_SYSERR,
2661                                        &my_identity, &msg_ctx->key, msg_ctx->peer,
2662                                        NULL);
2663         }
2664 #endif
2665       /* invalid wrapper: key mismatch! */
2666       GNUNET_break_op (0);
2667       return;
2668     }
2669   /* ret == GNUNET_SYSERR means that there is no known relationship between
2670      data and the key, so we cannot check it */
2671 #if DEBUG_DHT
2672   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2673               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2674               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2675 #endif
2676 #if DEBUG_DHT_ROUTING
2677   if (msg_ctx->hop_count == 0) /* Locally initiated request */
2678     {
2679       if ((debug_routes) && (dhtlog_handle != NULL))
2680         {
2681           dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2682                                        msg_ctx->hop_count, GNUNET_NO, &my_identity,
2683                                        &msg_ctx->key);
2684         }
2685     }
2686 #endif
2687
2688   if (msg_ctx->closest != GNUNET_YES)
2689     {
2690       route_message (msg, msg_ctx);
2691       return;
2692     }
2693
2694 #if DEBUG_DHT
2695   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2696               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2697               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2698 #endif
2699
2700 #if DEBUG_DHT_ROUTING
2701   if ((debug_routes_extended) && (dhtlog_handle != NULL))
2702     {
2703       dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2704                                    msg_ctx->hop_count, GNUNET_YES,
2705                                    &my_identity, &msg_ctx->key, msg_ctx->peer,
2706                                    NULL);
2707     }
2708
2709   if ((debug_routes) && (dhtlog_handle != NULL))
2710     {
2711       dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2712                                    msg_ctx->hop_count, GNUNET_YES, &my_identity,
2713                                    &msg_ctx->key);
2714     }
2715 #endif
2716
2717   increment_stats(STAT_PUTS_INSERTED);
2718   if (datacache != NULL)
2719     {
2720       ret = GNUNET_DATACACHE_put (datacache, &msg_ctx->key, data_size,
2721                                   (char *) &put_msg[1], put_type,
2722                                   GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2723
2724       if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2725         {
2726           put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2727           memcpy(&put_context->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
2728           put_context->type = put_type;
2729           GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content, put_context);
2730         }
2731     }
2732   else
2733     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2734                 "`%s:%s': %s request received, but have no datacache!\n",
2735                 my_short_id, "DHT", "PUT");
2736
2737   if (stop_on_closest == GNUNET_NO)
2738     route_message (msg, msg_ctx);
2739 }
2740
2741 /**
2742  * Estimate the diameter of the network based
2743  * on how many buckets are currently in use.
2744  * Concept here is that the diameter of the network
2745  * is roughly the distance a message must travel in
2746  * order to reach its intended destination.  Since
2747  * at each hop we expect to get one bit closer, and
2748  * we have one bit per bucket, the number of buckets
2749  * in use should be the largest number of hops for
2750  * a successful message. (of course, this assumes we
2751  * know all peers in the network!)
2752  *
2753  * @return ballpark diameter figure
2754  */
2755 static unsigned int estimate_diameter()
2756 {
2757   return MAX_BUCKETS - lowest_bucket;
2758 }
2759
2760 /**
2761  * To how many peers should we (on average)
2762  * forward the request to obtain the desired
2763  * target_replication count (on average).
2764  *
2765  * returns: target_replication / (est. hops) + (target_replication * hop_count)
2766  * where est. hops is typically 2 * the routing table depth
2767  *
2768  * @param hop_count number of hops the message has traversed
2769  * @param target_replication the number of total paths desired
2770  *
2771  * @return Some number of peers to forward the message to
2772  */
2773 static unsigned int
2774 get_forward_count (unsigned int hop_count, size_t target_replication)
2775 {
2776   uint32_t random_value;
2777   unsigned int forward_count;
2778   float target_value;
2779   unsigned int diameter;
2780
2781   diameter = estimate_diameter ();
2782
2783   if (GNUNET_NO == use_max_hops)
2784     max_hops = (diameter + 1) * 2;
2785
2786   /**
2787    * If we are behaving in strict kademlia mode, send multiple initial requests,
2788    * but then only send to 1 or 0 peers based strictly on the number of hops.
2789    */
2790   if (strict_kademlia == GNUNET_YES)
2791     {
2792       if (hop_count == 0)
2793         return kademlia_replication;
2794       else if (hop_count < max_hops)
2795         return 1;
2796       else
2797         return 0;
2798     }
2799
2800   /* FIXME: the smaller we think the network is the more lenient we should be for
2801    * routing right?  The estimation below only works if we think we have reasonably
2802    * full routing tables, which for our RR topologies may not be the case!
2803    */
2804   if (hop_count > max_hops)
2805     {
2806 #if DEBUG_DHT
2807       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2808                   "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2809                   "DHT", estimate_diameter(), lowest_bucket);
2810 #endif
2811       return 0;
2812     }
2813
2814   random_value = 0;
2815   /* FIXME: we use diameter as the expected number of hops, but with randomized routing we will likely route to more! */
2816   target_value = target_replication / (diameter + ((float)target_replication * hop_count));
2817   if (target_value > 1)
2818     return (unsigned int)target_value;
2819   else
2820     random_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int)-1);
2821
2822   if (random_value < (target_value * (unsigned int)-1))
2823     forward_count = 2;
2824   else
2825     forward_count = 1;
2826
2827   return forward_count;
2828 }
2829
2830 /*
2831  * Check whether my identity is closer than any known peers.
2832  * If a non-null bloomfilter is given, check if this is the closest
2833  * peer that hasn't already been routed to.
2834  *
2835  * @param target hash code to check closeness to
2836  * @param bloom bloomfilter, exclude these entries from the decision
2837  *
2838  * Return GNUNET_YES if node location is closest, GNUNET_NO
2839  * otherwise.
2840  */
2841 int
2842 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2843 {
2844   int bits;
2845   int other_bits;
2846   int bucket_num;
2847   int count;
2848   struct PeerInfo *pos;
2849   unsigned int my_distance;
2850
2851   if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2852     return GNUNET_YES;
2853
2854   bucket_num = find_current_bucket(target);
2855
2856   bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2857   my_distance = distance(&my_identity.hashPubKey, target);
2858   pos = k_buckets[bucket_num].head;
2859   count = 0;
2860   while ((pos != NULL) && (count < bucket_size))
2861     {
2862       if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2863         {
2864           pos = pos->next;
2865           continue; /* Skip already checked entries */
2866         }
2867
2868       other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2869       if (other_bits > bits)
2870         return GNUNET_NO;
2871       else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2872         {
2873           if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2874             return GNUNET_YES;
2875           else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2876             return GNUNET_NO;
2877         }
2878       pos = pos->next;
2879     }
2880
2881   /* No peers closer, we are the closest! */
2882   return GNUNET_YES;
2883 }
2884
2885
2886 /**
2887  * Return this peers adjusted value based on the convergence
2888  * function chosen.  This is the key function for randomized
2889  * routing decisions.
2890  *
2891  * @param target the key of the request
2892  * @param peer the peer we would like the value of
2893  * @param hops number of hops this message has already traveled
2894  *
2895  * @return bit distance from target to peer raised to an exponent
2896  *         adjusted based on the current routing convergence algorithm
2897  *
2898  */
2899 static unsigned long long
2900 converge_distance (const GNUNET_HashCode *target,
2901                    struct PeerInfo *peer,
2902                    unsigned int hops)
2903 {
2904   unsigned long long ret;
2905   unsigned int other_matching_bits;
2906   double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
2907   double temp_modifier;
2908   double calc_value;
2909   double exponent;
2910   int curr_max_hops;
2911
2912   if (use_max_hops)
2913     curr_max_hops = max_hops;
2914   else
2915     curr_max_hops = (estimate_diameter() + 1) * 2;
2916
2917   if (converge_modifier > 0)
2918     temp_modifier = converge_modifier * base_converge_modifier;
2919   else
2920     {
2921       temp_modifier = base_converge_modifier;
2922       base_converge_modifier = 0.0;
2923     }
2924
2925   GNUNET_assert(temp_modifier > 0);
2926
2927   other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2928
2929   switch (converge_option)
2930     {
2931       case DHT_CONVERGE_RANDOM:
2932         return 1; /* Always return 1, choose equally among all peers */
2933       case DHT_CONVERGE_LINEAR:
2934         calc_value = hops * curr_max_hops * temp_modifier;
2935         break;
2936       case DHT_CONVERGE_SQUARE:
2937         /**
2938          * Simple square based curve.
2939          */
2940         calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * temp_modifier));
2941         break;
2942       case DHT_CONVERGE_EXPONENTIAL:
2943         /**
2944          * Simple exponential curve.
2945          */
2946         if (base_converge_modifier > 0)
2947           calc_value = (temp_modifier * hops * hops) / curr_max_hops;
2948         else
2949           calc_value = (hops * hops) / curr_max_hops;
2950         break;
2951       case DHT_CONVERGE_BINARY:
2952         /**
2953          * If below the cutoff, route randomly (return 1),
2954          * If above the cutoff, return the maximum possible
2955          * value first (always route to closest, because
2956          * they are sorted.)
2957          */
2958
2959         if (hops > converge_modifier) /* Past cutoff */
2960           {
2961             return ULLONG_MAX;
2962           }
2963         /* Fall through */
2964       default:
2965         return 1;
2966     }
2967
2968   /* Take the log (base e) of the number of bits matching the other peer */
2969   exponent = log(other_matching_bits);
2970
2971   /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
2972   if (exponent * calc_value >= 44.361419555836498)
2973     return ULLONG_MAX;
2974
2975   /* Clear errno and all math exceptions */
2976   errno = 0;
2977   feclearexcept(FE_ALL_EXCEPT);
2978   ret = (unsigned long long)pow(other_matching_bits, calc_value);
2979   if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2980       FE_UNDERFLOW))
2981     {
2982       if (0 != fetestexcept(FE_OVERFLOW))
2983         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2984       if (0 != fetestexcept(FE_INVALID))
2985         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2986       if (0 != fetestexcept(FE_UNDERFLOW))
2987         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2988       return 0;
2989     }
2990   else
2991     return ret;
2992 }
2993
2994 /**
2995  * Comparison function for two struct PeerInfo's
2996  * which have already had their matching bits to
2997  * some target calculated.
2998  *
2999  * @param p1 a pointer pointer to a struct PeerInfo
3000  * @param p2 a pointer pointer to a struct PeerInfo
3001  *
3002  * @return 0 if equidistant to target,
3003  *        -1 if p1 is closer,
3004  *         1 if p2 is closer
3005  */
3006 static int
3007 compare_peers (const void *p1, const void *p2)
3008 {
3009   struct PeerInfo **first = (struct PeerInfo **)p1;
3010   struct PeerInfo **second = (struct PeerInfo **)p2;
3011
3012   if ((*first)->matching_bits > (*second)->matching_bits)
3013     return -1;
3014   if ((*first)->matching_bits < (*second)->matching_bits)
3015     return 1;
3016   else
3017     return 0;
3018 }
3019
3020
3021 /**
3022  * Select a peer from the routing table that would be a good routing
3023  * destination for sending a message for "target".  The resulting peer
3024  * must not be in the set of blocked peers.<p>
3025  *
3026  * Note that we should not ALWAYS select the closest peer to the
3027  * target, peers further away from the target should be chosen with
3028  * exponentially declining probability.
3029  *
3030  * @param target the key we are selecting a peer to route to
3031  * @param bloom a bloomfilter containing entries this request has seen already
3032  *
3033  * @return Peer to route to, or NULL on error
3034  */
3035 static struct PeerInfo *
3036 select_peer (const GNUNET_HashCode * target,
3037              struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3038 {
3039   unsigned int bc;
3040   unsigned int i;
3041   unsigned int count;
3042   unsigned int offset;
3043   unsigned int my_matching_bits;
3044   int closest_bucket;
3045   struct PeerInfo *pos;
3046   struct PeerInfo *sorted_closest[bucket_size];
3047   unsigned long long temp_converge_distance;
3048   unsigned long long total_distance;
3049   unsigned long long selected;
3050 #if DEBUG_DHT > 1
3051   unsigned long long stats_total_distance;
3052   double sum;
3053 #endif
3054   /* For kademlia */
3055   unsigned int distance;
3056   unsigned int largest_distance;
3057   struct PeerInfo *chosen;
3058
3059   my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
3060
3061   total_distance = 0;
3062   if (strict_kademlia == GNUNET_YES)
3063     {
3064       largest_distance = 0;
3065       chosen = NULL;
3066       for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3067         {
3068           pos = k_buckets[bc].head;
3069           count = 0;
3070           while ((pos != NULL) && (count < bucket_size))
3071             {
3072               /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3073               if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3074                 {
3075                   distance = inverse_distance (target, &pos->id.hashPubKey);
3076                   if (distance > largest_distance)
3077                     {
3078                       chosen = pos;
3079                       largest_distance = distance;
3080                     }
3081                 }
3082               count++;
3083               pos = pos->next;
3084             }
3085         }
3086
3087       if ((largest_distance > 0) && (chosen != NULL))
3088         {
3089           GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
3090           return chosen;
3091         }
3092       else
3093         {
3094           return NULL;
3095         }
3096     }
3097
3098   /* GNUnet-style */
3099   total_distance = 0;
3100   /* Three steps: order peers in closest bucket (most matching bits).
3101    * Then go over all LOWER buckets (matching same bits we do)
3102    * Then go over all HIGHER buckets (matching less then we do)
3103    */
3104
3105   closest_bucket = find_current_bucket(target);
3106   GNUNET_assert(closest_bucket >= lowest_bucket);
3107   pos = k_buckets[closest_bucket].head;
3108   count = 0;
3109   offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3110   memset(sorted_closest, 0, sizeof(sorted_closest));
3111   /* Put any peers in the closest bucket in the sorting array */
3112   while ((pos != NULL) && (count < bucket_size))
3113     {
3114       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3115         {
3116           count++;
3117           pos = pos->next;
3118           continue; /* Ignore bloomfiltered peers */
3119         }
3120       pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
3121       sorted_closest[offset] = pos;
3122       pos = pos->next;
3123       offset++;
3124       count++;
3125     }
3126
3127   /* Sort the peers in descending order */
3128   qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
3129
3130   /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3131   for (i = 0; i < offset; i++)
3132     {
3133       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3134       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3135         break; /* Ignore bloomfiltered peers */
3136       if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3137         total_distance += temp_converge_distance;
3138       else
3139         break; /* overflow case */
3140     }
3141
3142   /* Now handle peers in lower buckets (matches same # of bits as target) */
3143   for (bc = lowest_bucket; bc < closest_bucket; bc++)
3144     {
3145       pos = k_buckets[bc].head;
3146       count = 0;
3147       while ((pos != NULL) && (count < bucket_size))
3148         {
3149           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3150             {
3151               count++;
3152               pos = pos->next;
3153               continue; /* Ignore bloomfiltered peers */
3154             }
3155           temp_converge_distance = converge_distance(target, pos, hops);
3156           if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3157             total_distance += temp_converge_distance;
3158           else
3159             break; /* overflow case */
3160           pos = pos->next;
3161           count++;
3162         }
3163     }
3164
3165   /* Now handle all the further away peers */
3166   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3167     {
3168       pos = k_buckets[bc].head;
3169       count = 0;
3170       while ((pos != NULL) && (count < bucket_size))
3171         {
3172           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3173             {
3174               count++;
3175               pos = pos->next;
3176               continue; /* Ignore bloomfiltered peers */
3177             }
3178           temp_converge_distance = converge_distance(target, pos, hops);
3179           if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3180             total_distance += temp_converge_distance;
3181           else
3182             break; /* overflow case */
3183           pos = pos->next;
3184           count++;
3185         }
3186     }
3187
3188   if (total_distance == 0) /* No peers to select from! */
3189     {
3190       increment_stats("# select_peer, total_distance == 0");
3191       return NULL;
3192     }
3193
3194 #if DEBUG_DHT_ROUTING > 1
3195   sum = 0.0;
3196   /* PRINT STATS */
3197   /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3198   stats_total_distance = 0;
3199   for (i = 0; i < offset; i++)
3200     {
3201       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3202         break; /* Ignore bloomfiltered peers */
3203       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3204       if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3205         stats_total_distance += temp_converge_distance;
3206       else
3207         break; /* overflow case */
3208       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);
3209     }
3210
3211   /* Now handle peers in lower buckets (matches same # of bits as target) */
3212   for (bc = lowest_bucket; bc < closest_bucket; bc++)
3213     {
3214       pos = k_buckets[bc].head;
3215       count = 0;
3216       while ((pos != NULL) && (count < bucket_size))
3217         {
3218           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3219             {
3220               count++;
3221               pos = pos->next;
3222               continue; /* Ignore bloomfiltered peers */
3223             }
3224           temp_converge_distance = converge_distance(target, pos, hops);
3225           if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3226             stats_total_distance += temp_converge_distance;
3227           else
3228             break; /* overflow case */
3229           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);
3230           pos = pos->next;
3231           count++;
3232         }
3233     }
3234
3235   /* Now handle all the further away peers */
3236   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3237     {
3238       pos = k_buckets[bc].head;
3239       count = 0;
3240       while ((pos != NULL) && (count < bucket_size))
3241         {
3242           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3243             {
3244               count++;
3245               pos = pos->next;
3246               continue; /* Ignore bloomfiltered peers */
3247             }
3248           temp_converge_distance = converge_distance(target, pos, hops);
3249           if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3250             stats_total_distance += temp_converge_distance;
3251           else
3252             break; /* overflow case */
3253           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);
3254           pos = pos->next;
3255           count++;
3256         }
3257     }
3258   /* END PRINT STATS */
3259 #endif
3260
3261   /* Now actually choose a peer */
3262   selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3263
3264   /* Go over closest sorted peers. */
3265   for (i = 0; i < offset; i++)
3266     {
3267       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3268         break; /* Ignore bloomfiltered peers */
3269       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3270       if (temp_converge_distance >= selected)
3271         return sorted_closest[i];
3272       else
3273         selected -= temp_converge_distance;
3274     }
3275
3276   /* Now handle peers in lower buckets (matches same # of bits as target) */
3277   for (bc = lowest_bucket; bc < closest_bucket; bc++)
3278     {
3279       pos = k_buckets[bc].head;
3280       count = 0;
3281       while ((pos != NULL) && (count < bucket_size))
3282         {
3283           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3284             {
3285               count++;
3286               pos = pos->next;
3287               continue; /* Ignore bloomfiltered peers */
3288             }
3289           temp_converge_distance = converge_distance(target, pos, hops);
3290           if (temp_converge_distance >= selected)
3291             return pos;
3292           else
3293             selected -= temp_converge_distance;
3294           pos = pos->next;
3295           count++;
3296         }
3297     }
3298
3299   /* Now handle all the further away peers */
3300   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3301     {
3302       pos = k_buckets[bc].head;
3303       count = 0;
3304       while ((pos != NULL) && (count < bucket_size))
3305         {
3306           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3307             {
3308               count++;
3309               pos = pos->next;
3310               continue; /* Ignore bloomfiltered peers */
3311             }
3312           temp_converge_distance = converge_distance(target, pos, hops);
3313           if (temp_converge_distance >= selected)
3314             return pos;
3315           else
3316             selected -= temp_converge_distance;
3317           pos = pos->next;
3318           count++;
3319         }
3320     }
3321
3322   increment_stats("# failed to select peer");
3323   return NULL;
3324 }
3325
3326
3327 /**
3328  * Task used to remove recent entries, either
3329  * after timeout, when full, or on shutdown.
3330  *
3331  * @param cls the entry to remove
3332  * @param tc context, reason, etc.
3333  */
3334 static void
3335 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3336 {
3337   struct RecentRequest *req = cls;
3338   static GNUNET_HashCode hash;
3339
3340   GNUNET_assert(req != NULL);
3341   hash_from_uid(req->uid, &hash);
3342   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3343   GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3344   GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3345   GNUNET_free(req);
3346
3347   /*
3348   if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3349   {
3350     GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3351     GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3352   }
3353   */
3354 }
3355
3356
3357 /**
3358  * Task used to remove forwarding entries, either
3359  * after timeout, when full, or on shutdown.
3360  *
3361  * @param cls the entry to remove
3362  * @param tc context, reason, etc.
3363  */
3364 static void
3365 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3366 {
3367   struct DHTRouteSource *source_info = cls;
3368   struct DHTQueryRecord *record;
3369   source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3370   record = source_info->record;
3371   GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3372
3373   if (record->head == NULL) /* No more entries in DLL */
3374     {
3375       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap, &record->key, record));
3376       GNUNET_free(record);
3377     }
3378   if (source_info->find_peers_responded != NULL)
3379     GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3380   GNUNET_free(source_info);
3381 }
3382
3383 /**
3384  * Remember this routing request so that if a reply is
3385  * received we can either forward it to the correct peer
3386  * or return the result locally.
3387  *
3388  * @param msg_ctx Context of the route request
3389  *
3390  * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3391  */
3392 static int cache_response(struct DHT_MessageContext *msg_ctx)
3393 {
3394   struct DHTQueryRecord *record;
3395   struct DHTRouteSource *source_info;
3396   struct DHTRouteSource *pos;
3397   struct GNUNET_TIME_Absolute now;
3398   unsigned int current_size;
3399
3400   current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3401
3402 #if DELETE_WHEN_FULL
3403   while (current_size >= MAX_OUTSTANDING_FORWARDS)
3404     {
3405       source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3406       GNUNET_assert(source_info != NULL);
3407       record = source_info->record;
3408       GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3409       if (record->head == NULL) /* No more entries in DLL */
3410         {
3411           GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3412           GNUNET_free(record);
3413         }
3414       if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3415         GNUNET_SCHEDULER_cancel(source_info->delete_task);
3416       if (source_info->find_peers_responded != NULL)
3417         GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3418       GNUNET_free(source_info);
3419       current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3420     }
3421 #endif
3422   /** Non-local request and have too many outstanding forwards, discard! */
3423   if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3424     return GNUNET_NO;
3425
3426   now = GNUNET_TIME_absolute_get();
3427   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3428   if (record != NULL) /* Already know this request! */
3429     {
3430       pos = record->head;
3431       while (pos != NULL)
3432         {
3433           if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3434             break; /* Already have this peer in reply list! */
3435           pos = pos->next;
3436         }
3437       if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3438         {
3439           GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.abs_value);
3440           return GNUNET_NO;
3441         }
3442     }
3443   else
3444     {
3445       record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3446       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3447       memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3448     }
3449
3450   source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3451   source_info->record = record;
3452   source_info->delete_task = GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3453   source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3454   memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3455   GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail, source_info);
3456   if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3457     {
3458       source_info->client = msg_ctx->client;
3459       now = GNUNET_TIME_absolute_get_forever();
3460     }
3461   source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.abs_value);
3462 #if DEBUG_DHT > 1
3463       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3464                   "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3465                   "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3466 #endif
3467   return GNUNET_YES;
3468 }
3469
3470
3471 /**
3472  * Main function that handles whether or not to route a message to other
3473  * peers.
3474  *
3475  * @param msg the message to be routed
3476  * @param msg_ctx the context containing all pertinent information about the message
3477  */
3478 static void
3479 route_message(const struct GNUNET_MessageHeader *msg,
3480                struct DHT_MessageContext *msg_ctx)
3481 {
3482   int i;
3483   struct PeerInfo *selected;
3484 #if DEBUG_DHT_ROUTING > 1
3485   struct PeerInfo *nearest;
3486 #endif
3487   unsigned int target_forward_count;
3488   unsigned int forward_count;
3489   struct RecentRequest *recent_req;
3490   GNUNET_HashCode unique_hash;
3491   char *stat_forward_count;
3492   char *temp_stat_str;
3493 #if DEBUG_DHT_ROUTING
3494   int ret;
3495 #endif
3496
3497   if (malicious_dropper == GNUNET_YES)
3498     {
3499 #if DEBUG_DHT_ROUTING
3500       if ((debug_routes_extended) && (dhtlog_handle != NULL))
3501         {
3502           dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3503                                        msg_ctx->hop_count, GNUNET_SYSERR,
3504                                        &my_identity, &msg_ctx->key, msg_ctx->peer,
3505                                        NULL);
3506         }
3507 #endif
3508       if (msg_ctx->bloom != NULL)
3509       {
3510         GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3511         msg_ctx->bloom = NULL;
3512       }
3513       return;
3514     }
3515
3516   increment_stats(STAT_ROUTES);
3517   target_forward_count = get_forward_count(msg_ctx->hop_count, msg_ctx->replication);
3518   GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", target_forward_count);
3519   increment_stats(stat_forward_count);
3520   GNUNET_free(stat_forward_count);
3521   if (msg_ctx->bloom == NULL)
3522     msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3523
3524   if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3525     target_forward_count = 0;
3526
3527   /**
3528    * NOTICE:  In Kademlia, a find peer request goes no further if the peer doesn't return
3529    * any closer peers (which is being checked for below).  Since we are doing recursive
3530    * routing we have no choice but to stop forwarding in this case.  This means that at
3531    * any given step the request may NOT be forwarded to alpha peers (because routes will
3532    * stop and the parallel route will not be aware of it).  Of course, assuming that we
3533    * have fulfilled the Kademlia requirements for routing table fullness this will never
3534    * ever ever be a problem.
3535    *
3536    * However, is this fair?
3537    *
3538    * Since we use these requests to build our routing tables (and we build them in the
3539    * testing driver) we will ignore this restriction for FIND_PEER messages so that
3540    * routing tables still get constructed.
3541    */
3542   if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) && (msg_ctx->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3543     target_forward_count = 0;
3544
3545
3546   GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3547   hash_from_uid (msg_ctx->unique_id, &unique_hash);
3548   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3549   {
3550     recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3551     GNUNET_assert(recent_req != NULL);
3552     if (0 != memcmp(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode)))
3553       increment_stats(STAT_DUPLICATE_UID);
3554     else
3555       {
3556         increment_stats(STAT_RECENT_SEEN);
3557         GNUNET_CONTAINER_bloomfilter_or2(msg_ctx->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3558       }
3559     }
3560   else
3561     {
3562       recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3563       recent_req->uid = msg_ctx->unique_id;
3564       memcpy(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3565       recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3566       recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().abs_value);
3567       recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3568       GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3569     }
3570
3571   if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3572     {
3573       recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3574       GNUNET_assert(recent_req != NULL);
3575       GNUNET_SCHEDULER_cancel(recent_req->remove_task);
3576       GNUNET_SCHEDULER_add_now(&remove_recent, recent_req);
3577     }
3578
3579   forward_count = 0;
3580   for (i = 0; i < target_forward_count; i++)
3581     {
3582       selected = select_peer(&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3583
3584       if (selected != NULL)
3585         {
3586           forward_count++;
3587           if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &msg_ctx->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &msg_ctx->key))
3588             GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", msg_ctx->hop_count);
3589           else
3590             GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", msg_ctx->hop_count);
3591           if (temp_stat_str != NULL)
3592             {
3593               increment_stats(temp_stat_str);
3594               GNUNET_free(temp_stat_str);
3595             }
3596           GNUNET_CONTAINER_bloomfilter_add(msg_ctx->bloom, &selected->id.hashPubKey);
3597 #if DEBUG_DHT_ROUTING > 1
3598           nearest = find_closest_peer(&msg_ctx->key);
3599           nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3600           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3601                       "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3602                       "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));
3603           GNUNET_free(nearest_buf);
3604 #endif
3605 #if DEBUG_DHT_ROUTING
3606           if ((debug_routes_extended) && (dhtlog_handle != NULL))
3607             {
3608               dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3609                                            msg_ctx->hop_count, GNUNET_NO,
3610                                            &my_identity, &msg_ctx->key, msg_ctx->peer,
3611                                            &selected->id);
3612             }
3613 #endif
3614           forward_message (msg, selected, msg_ctx);
3615         }
3616     }
3617
3618   if (msg_ctx->bloom != NULL)
3619     {
3620       GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, msg_ctx->bloom, DHT_BLOOM_SIZE);
3621       GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3622       msg_ctx->bloom = NULL;
3623     }
3624
3625 #if DEBUG_DHT_ROUTING
3626   if (forward_count == 0)
3627     ret = GNUNET_SYSERR;
3628   else
3629     ret = GNUNET_NO;
3630
3631   if ((debug_routes_extended) && (dhtlog_handle != NULL))
3632     {
3633       dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3634                                    msg_ctx->hop_count, ret,
3635                                    &my_identity, &msg_ctx->key, msg_ctx->peer,
3636                                    NULL);
3637     }
3638 #endif
3639 }
3640
3641
3642
3643 /**
3644  * Main function that handles whether or not to route a message to other
3645  * peers.
3646  *
3647  * @param msg the message to be routed
3648  * @param msg_ctx the context containing all pertinent information about the message
3649  */
3650 static void
3651 demultiplex_message(const struct GNUNET_MessageHeader *msg,
3652                     struct DHT_MessageContext *msg_ctx)
3653 {
3654   msg_ctx->closest = am_closest_peer(&msg_ctx->key, NULL);
3655   switch (ntohs(msg->type))
3656     {
3657     case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3658       cache_response (msg_ctx);
3659       handle_dht_get (msg, msg_ctx);
3660       break;
3661     case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3662       increment_stats(STAT_PUTS);
3663       handle_dht_put (msg, msg_ctx);
3664       break;
3665     case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3666       increment_stats(STAT_FIND_PEER);
3667       if (((msg_ctx->hop_count > 0) && (0 != memcmp(msg_ctx->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (msg_ctx->client != NULL))
3668       {
3669         cache_response (msg_ctx);
3670         if ((msg_ctx->closest == GNUNET_YES) || (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3671           handle_dht_find_peer (msg, msg_ctx);
3672       }
3673       else
3674         route_message (msg, msg_ctx);
3675 #if DEBUG_DHT_ROUTING
3676       if (msg_ctx->hop_count == 0) /* Locally initiated request */
3677         {
3678           if ((debug_routes) && (dhtlog_handle != NULL))
3679             {
3680               dhtlog_handle->insert_dhtkey(NULL, &msg_ctx->key);
3681               dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
3682                                            msg_ctx->hop_count, GNUNET_NO, &my_identity,
3683                                            &msg_ctx->key);
3684             }
3685         }
3686 #endif
3687       break;
3688     default:
3689       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3690                   "`%s': Message type (%d) not handled, forwarding anyway!\n", "DHT", ntohs(msg->type));
3691       route_message (msg, msg_ctx);
3692     }
3693 }
3694
3695
3696
3697
3698 /**
3699  * Iterator for local get request results,
3700  *
3701  * @param cls closure for iterator, NULL
3702  * @param exp when does this value expire?
3703  * @param key the key this data is stored under
3704  * @param size the size of the data identified by key
3705  * @param data the actual data
3706  * @param type the type of the data
3707  *
3708  * @return GNUNET_OK to continue iteration, anything else
3709  * to stop iteration.
3710  */
3711 static int
3712 republish_content_iterator (void *cls,
3713                             struct GNUNET_TIME_Absolute exp,
3714                             const GNUNET_HashCode * key,
3715                             size_t size, const char *data, uint32_t type)
3716 {
3717
3718   struct DHT_MessageContext *new_msg_ctx;
3719   struct GNUNET_DHT_PutMessage *put_msg;
3720 #if DEBUG_DHT
3721   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3722               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3723 #endif
3724   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3725
3726   put_msg =
3727     GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3728   put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3729   put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3730   put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3731   put_msg->type = htons (type);
3732   memcpy (&put_msg[1], data, size);
3733   new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3734   new_msg_ctx->replication = ntohl (DEFAULT_PUT_REPLICATION);
3735   new_msg_ctx->msg_options = ntohl (0);
3736   new_msg_ctx->network_size = estimate_diameter();
3737   new_msg_ctx->peer = &my_identity;
3738   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3739   new_msg_ctx->hop_count = 0;
3740   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3741   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3742   increment_stats(STAT_PUT_START);
3743   demultiplex_message(&put_msg->header, new_msg_ctx);
3744
3745   GNUNET_free(new_msg_ctx);
3746   GNUNET_free (put_msg);
3747   return GNUNET_OK;
3748 }
3749
3750 /**
3751  * Task used to republish data.
3752  *
3753  * @param cls closure (a struct RepublishContext)
3754  * @param tc runtime context for this task
3755  */
3756 static void
3757 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3758 {
3759   struct RepublishContext *put_context = cls;
3760
3761   unsigned int results;
3762
3763   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3764     {
3765       GNUNET_free(put_context);
3766       return;
3767     }
3768
3769   GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3770   results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3771   if (results == 0) /* Data must have expired */
3772     GNUNET_free(put_context);
3773   else /* Reschedule task for next time period */
3774     GNUNET_SCHEDULER_add_delayed(dht_republish_frequency, &republish_content, put_context);
3775
3776 }
3777
3778
3779 /**
3780  * Iterator over hash map entries.
3781  *
3782  * @param cls client to search for in source routes
3783  * @param key current key code (ignored)
3784  * @param value value in the hash map, a DHTQueryRecord
3785  * @return GNUNET_YES if we should continue to
3786  *         iterate,
3787  *         GNUNET_NO if not.
3788  */
3789 static int find_client_records (void *cls,
3790                                 const GNUNET_HashCode * key, void *value)
3791 {
3792   struct ClientList *client = cls;
3793   struct DHTQueryRecord *record = value;
3794   struct DHTRouteSource *pos;
3795   pos = record->head;
3796   while (pos != NULL)
3797     {
3798       if (pos->client == client)
3799         break;
3800       pos = pos->next;
3801     }
3802   if (pos != NULL)
3803     {
3804       GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3805       GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3806       if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3807         GNUNET_SCHEDULER_cancel(pos->delete_task);
3808
3809       if (pos->find_peers_responded != NULL)
3810         GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3811       GNUNET_free(pos);
3812     }
3813   if (record->head == NULL) /* No more entries in DLL */
3814     {
3815       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3816       GNUNET_free(record);
3817     }
3818   return GNUNET_YES;
3819 }
3820
3821 /**
3822  * Functions with this signature are called whenever a client
3823  * is disconnected on the network level.
3824  *
3825  * @param cls closure (NULL for dht)
3826  * @param client identification of the client; NULL
3827  *        for the last call when the server is destroyed
3828  */
3829 static void handle_client_disconnect (void *cls,
3830                                       struct GNUNET_SERVER_Client* client)
3831 {
3832   struct ClientList *pos = client_list;
3833   struct ClientList *prev;
3834   struct ClientList *found;
3835   struct PendingMessage *reply;
3836
3837   prev = NULL;
3838   found = NULL;
3839   while (pos != NULL)
3840     {
3841       if (pos->client_handle == client)
3842         {
3843           if (prev != NULL)
3844             prev->next = pos->next;
3845           else
3846             client_list = pos->next;
3847           found = pos;
3848           break;
3849         }
3850       prev = pos;
3851       pos = pos->next;
3852     }
3853
3854   if (found != NULL)
3855     {
3856       if (found->transmit_handle != NULL)
3857         GNUNET_CONNECTION_notify_transmit_ready_cancel(found->transmit_handle);
3858
3859       while(NULL != (reply = found->pending_head))
3860         {
3861           GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3862           GNUNET_free(reply);
3863         }
3864       GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3865       GNUNET_free(found);
3866     }
3867 }
3868
3869 /**
3870  * Find a client if it exists, add it otherwise.
3871  *
3872  * @param client the server handle to the client
3873  *
3874  * @return the client if found, a new client otherwise
3875  */
3876 static struct ClientList *
3877 find_active_client (struct GNUNET_SERVER_Client *client)
3878 {
3879   struct ClientList *pos = client_list;
3880   struct ClientList *ret;
3881
3882   while (pos != NULL)
3883     {
3884       if (pos->client_handle == client)
3885         return pos;
3886       pos = pos->next;
3887     }
3888
3889   ret = GNUNET_malloc (sizeof (struct ClientList));
3890   ret->client_handle = client;
3891   ret->next = client_list;
3892   client_list = ret;
3893
3894   return ret;
3895 }
3896
3897 #if HAVE_MALICIOUS
3898 /**
3899  * Task to send a malicious put message across the network.
3900  *
3901  * @param cls closure for this task
3902  * @param tc the context under which the task is running
3903  */
3904 static void
3905 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3906 {
3907   static struct GNUNET_DHT_PutMessage put_message;
3908   static struct DHT_MessageContext msg_ctx;
3909   static GNUNET_HashCode key;
3910   uint32_t random_key;
3911
3912   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3913     return;
3914   put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3915   put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3916   put_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3917   put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3918   memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3919   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3920   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3921   memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3922   msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3923   msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3924   msg_ctx.msg_options = ntohl (0);
3925   msg_ctx.network_size = estimate_diameter();
3926   msg_ctx.peer = &my_identity;
3927   msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3928   msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3929 #if DEBUG_DHT_ROUTING
3930   if (dhtlog_handle != NULL)
3931     dhtlog_handle->insert_dhtkey(NULL, &key);
3932 #endif
3933   increment_stats(STAT_PUT_START);
3934   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3935   demultiplex_message(&put_message.header, &msg_ctx);
3936   GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3937 }
3938
3939
3940 /**
3941  * Task to send a malicious put message across the network.
3942  *
3943  * @param cls closure for this task
3944  * @param tc the context under which the task is running
3945  */
3946 static void
3947 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3948 {
3949   static struct GNUNET_DHT_GetMessage get_message;
3950   struct DHT_MessageContext msg_ctx;
3951   static GNUNET_HashCode key;
3952   uint32_t random_key;
3953
3954   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3955     return;
3956
3957   get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3958   get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3959   get_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3960   memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3961   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3962   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3963   memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3964   msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3965   msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3966   msg_ctx.msg_options = ntohl (0);
3967   msg_ctx.network_size = estimate_diameter();
3968   msg_ctx.peer = &my_identity;
3969   msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3970   msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3971 #if DEBUG_DHT_ROUTING
3972   if (dhtlog_handle != NULL)
3973     dhtlog_handle->insert_dhtkey(NULL, &key);
3974 #endif
3975   increment_stats(STAT_GET_START);
3976   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3977   demultiplex_message (&get_message.header, &msg_ctx);
3978   GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3979 }
3980 #endif
3981
3982
3983 /**
3984  * Iterator over hash map entries.
3985  *
3986  * @param cls closure
3987  * @param key current key code
3988  * @param value value in the hash map
3989  * @return GNUNET_YES if we should continue to
3990  *         iterate,
3991  *         GNUNET_NO if not.
3992  */
3993 static int
3994 add_known_to_bloom (void *cls,
3995                     const GNUNET_HashCode * key,
3996                     void *value)
3997 {
3998   struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3999   GNUNET_CONTAINER_bloomfilter_add (bloom, key);
4000   return GNUNET_YES;
4001 }
4002
4003 /**
4004  * Task to send a find peer message for our own peer identifier
4005  * so that we can find the closest peers in the network to ourselves
4006  * and attempt to connect to them.
4007  *
4008  * @param cls closure for this task
4009  * @param tc the context under which the task is running
4010  */
4011 static void
4012 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4013 {
4014   struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
4015   struct DHT_MessageContext msg_ctx;
4016   struct GNUNET_TIME_Relative next_send_time;
4017   struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
4018 #if COUNT_INTERVAL
4019   struct GNUNET_TIME_Relative time_diff;
4020   struct GNUNET_TIME_Absolute end;
4021   double multiplier;
4022   double count_per_interval;
4023 #endif
4024   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
4025     return;
4026
4027   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! */
4028     {
4029       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
4030       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
4031                                     &send_find_peer_message, NULL);
4032       newly_found_peers = 0;
4033       return;
4034     }
4035     
4036   increment_stats(STAT_FIND_PEER_START);
4037 #if COUNT_INTERVAL
4038   end = GNUNET_TIME_absolute_get();
4039   time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
4040
4041   if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
4042     {
4043       multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
4044       count_per_interval = find_peer_context.count / multiplier;
4045     }
4046   else
4047     {
4048       multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
4049       count_per_interval = find_peer_context.count * multiplier;
4050     }
4051 #endif
4052
4053 #if FIND_PEER_WITH_HELLO
4054   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4055   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4056   memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4057 #else
4058   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
4059   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
4060 #endif
4061   find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4062   temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4063   GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
4064   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
4065   GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
4066   memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4067   memcpy(&msg_ctx.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
4068   msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
4069   msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4070   msg_ctx.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4071   msg_ctx.network_size = estimate_diameter();
4072   msg_ctx.peer = &my_identity;
4073   msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4074   msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4075
4076   demultiplex_message(&find_peer_msg->header, &msg_ctx);
4077   GNUNET_free(find_peer_msg);
4078   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4079               "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
4080               "FIND PEER");
4081   if (newly_found_peers < bucket_size)
4082     {
4083       next_send_time.rel_value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4084                               GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4085                                                        DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4086     }
4087   else
4088     {
4089       next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4090                              GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4091                                                       DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4092     }
4093
4094   GNUNET_assert (next_send_time.rel_value != 0);
4095   find_peer_context.count = 0;
4096   newly_found_peers = 0;
4097   find_peer_context.start = GNUNET_TIME_absolute_get();
4098   if (GNUNET_YES == do_find_peer)
4099   {
4100     GNUNET_SCHEDULER_add_delayed (next_send_time,
4101                                   &send_find_peer_message, NULL);
4102   }
4103 }
4104
4105 /**
4106  * Handler for any generic DHT messages, calls the appropriate handler
4107  * depending on message type, sends confirmation if responses aren't otherwise
4108  * expected.
4109  *
4110  * @param cls closure for the service
4111  * @param client the client we received this message from
4112  * @param message the actual message received
4113  */
4114 static void
4115 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4116                                 const struct GNUNET_MessageHeader *message)
4117 {
4118   const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
4119   const struct GNUNET_MessageHeader *enc_msg;
4120   struct DHT_MessageContext msg_ctx;
4121
4122   enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4123 #if DEBUG_DHT
4124   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4125               "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4126               my_short_id, 
4127               "DHT",
4128               "GENERIC",
4129               ntohs (message->type), 
4130               GNUNET_h2s (&dht_msg->key),
4131               GNUNET_ntohll (dht_msg->unique_id));
4132 #endif
4133 #if DEBUG_DHT_ROUTING
4134   if (dhtlog_handle != NULL)
4135     dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4136 #endif
4137   memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4138   msg_ctx.client = find_active_client (client);
4139   memcpy(&msg_ctx.key, &dht_msg->key, sizeof(GNUNET_HashCode));
4140   msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4141   msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
4142   msg_ctx.msg_options = ntohl (dht_msg->options);
4143   msg_ctx.network_size = estimate_diameter();
4144   msg_ctx.peer = &my_identity;
4145   msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
4146   msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4147   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4148     increment_stats(STAT_GET_START);
4149   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4150     increment_stats(STAT_PUT_START);
4151   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4152     increment_stats(STAT_FIND_PEER_START);
4153
4154   demultiplex_message(enc_msg, &msg_ctx);
4155
4156   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4157
4158 }
4159
4160 /**
4161  * Handler for any locally received DHT control messages,
4162  * sets malicious flags mostly for now.
4163  *
4164  * @param cls closure for the service
4165  * @param client the client we received this message from
4166  * @param message the actual message received
4167  *
4168  */
4169 static void
4170 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4171                             const struct GNUNET_MessageHeader *message)
4172 {
4173   const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4174       (const struct GNUNET_DHT_ControlMessage *) message;
4175 #if DEBUG_DHT
4176   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4177               "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4178               "CONTROL", ntohs(dht_control_msg->command));
4179 #endif
4180
4181   switch (ntohs(dht_control_msg->command))
4182   {
4183   case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4184     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4185     GNUNET_SCHEDULER_add_now(&send_find_peer_message, NULL);
4186     break;
4187 #if HAVE_MALICIOUS
4188   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4189     if (ntohs(dht_control_msg->variable) > 0)
4190       malicious_get_frequency = ntohs(dht_control_msg->variable);
4191     if (malicious_get_frequency == 0)
4192       malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4193     if (malicious_getter != GNUNET_YES)
4194       GNUNET_SCHEDULER_add_now(&malicious_get_task, NULL);
4195     malicious_getter = GNUNET_YES;
4196     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
4197                "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4198     break;
4199   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4200     if (ntohs(dht_control_msg->variable) > 0)
4201       malicious_put_frequency = ntohs(dht_control_msg->variable);
4202     if (malicious_put_frequency == 0)
4203       malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4204     if (malicious_putter != GNUNET_YES)
4205       GNUNET_SCHEDULER_add_now(&malicious_put_task, NULL);
4206     malicious_putter = GNUNET_YES;
4207     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4208                "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4209     break;
4210   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4211 #if DEBUG_DHT_ROUTING
4212     if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4213       dhtlog_handle->set_malicious(&my_identity);
4214 #endif
4215     malicious_dropper = GNUNET_YES;
4216     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4217                "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4218     break;
4219 #endif
4220   default:
4221     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4222                "%s:%s Unknown control command type `%d'!\n", 
4223                my_short_id, "DHT",
4224                ntohs(dht_control_msg->command));
4225     break;
4226   }
4227
4228   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4229 }
4230
4231 /**
4232  * Handler for any generic DHT stop messages, calls the appropriate handler
4233  * depending on message type (if processed locally)
4234  *
4235  * @param cls closure for the service
4236  * @param client the client we received this message from
4237  * @param message the actual message received
4238  *
4239  */
4240 static void
4241 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4242                             const struct GNUNET_MessageHeader *message)
4243 {
4244
4245   const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4246     (const struct GNUNET_DHT_StopMessage *) message;
4247   struct DHTQueryRecord *record;
4248   struct DHTRouteSource *pos;
4249 #if DEBUG_DHT
4250   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4251               "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4252               "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4253 #endif
4254   record = GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &dht_stop_msg->key);
4255   if (record != NULL)
4256     {
4257       pos = record->head;
4258
4259       while (pos != NULL)
4260         {
4261           /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
4262           if ((pos->client != NULL) && (pos->client->client_handle == client))
4263             {
4264               GNUNET_SCHEDULER_cancel(pos->delete_task);
4265               pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4266               GNUNET_SCHEDULER_add_continuation (&remove_forward_entry, pos, GNUNET_SCHEDULER_REASON_PREREQ_DONE);
4267             }
4268           pos = pos->next;
4269         }
4270     }
4271
4272   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4273 }
4274
4275
4276 /**
4277  * Core handler for p2p route requests.
4278  */
4279 static int
4280 handle_dht_p2p_route_request (void *cls,
4281                               const struct GNUNET_PeerIdentity *peer,
4282                               const struct GNUNET_MessageHeader *message,
4283                               const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4284 {
4285 #if DEBUG_DHT
4286   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4287               "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4288 #endif
4289   struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4290   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4291   struct DHT_MessageContext *msg_ctx;
4292
4293   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4294     {
4295 #if DEBUG_PING
4296       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4297 #endif
4298       return GNUNET_YES;
4299     }
4300
4301   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4302     {
4303       GNUNET_break_op(0);
4304       return GNUNET_YES;
4305     }
4306
4307   if (get_max_send_delay().rel_value > MAX_REQUEST_TIME.rel_value)
4308   {
4309     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending of previous replies took too long, backing off!\n");
4310     increment_stats("# route requests dropped due to high load");
4311     decrease_max_send_delay(get_max_send_delay());
4312 #if DEBUG_DHT_ROUTING
4313     if ((debug_routes_extended) && (dhtlog_handle != NULL))
4314       {
4315         /** Log routes that die due to high load! */
4316         dhtlog_handle->insert_route (NULL, GNUNET_ntohll(incoming->unique_id), DHTLOG_ROUTE,
4317                                      ntohl(incoming->hop_count), GNUNET_SYSERR,
4318                                      &my_identity, &incoming->key, peer,
4319                                      NULL);
4320       }
4321 #endif
4322     return GNUNET_YES;
4323   }
4324   msg_ctx = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4325   msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4326   GNUNET_assert(msg_ctx->bloom != NULL);
4327   msg_ctx->hop_count = ntohl(incoming->hop_count);
4328   memcpy(&msg_ctx->key, &incoming->key, sizeof(GNUNET_HashCode));
4329   msg_ctx->replication = ntohl(incoming->desired_replication_level);
4330   msg_ctx->unique_id = GNUNET_ntohll(incoming->unique_id);
4331   msg_ctx->msg_options = ntohl(incoming->options);
4332   msg_ctx->network_size = ntohl(incoming->network_size);
4333   msg_ctx->peer = peer;
4334   msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4335   msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4336   demultiplex_message (enc_msg, msg_ctx);
4337   if (msg_ctx->bloom != NULL)
4338   {
4339     GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4340     msg_ctx->bloom = NULL;
4341   }
4342   GNUNET_free(msg_ctx);
4343   return GNUNET_YES;
4344 }
4345
4346
4347 /**
4348  * Core handler for p2p route results.
4349  */
4350 static int
4351 handle_dht_p2p_route_result (void *cls,
4352                              const struct GNUNET_PeerIdentity *peer,
4353                              const struct GNUNET_MessageHeader *message,
4354                              const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4355 {
4356 #if DEBUG_DHT
4357   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4358               "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4359 #endif
4360   struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4361   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4362   struct DHT_MessageContext msg_ctx;
4363
4364   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4365     {
4366       GNUNET_break_op(0);
4367       return GNUNET_YES;
4368     }
4369
4370   memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4371   // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4372   msg_ctx.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4373   GNUNET_assert(msg_ctx.bloom != NULL);
4374   memcpy(&msg_ctx.key, &incoming->key, sizeof(GNUNET_HashCode));
4375   msg_ctx.unique_id = GNUNET_ntohll(incoming->unique_id);
4376   msg_ctx.msg_options = ntohl(incoming->options);
4377   msg_ctx.hop_count = ntohl(incoming->hop_count);
4378   msg_ctx.peer = peer;
4379   msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4380   msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4381   route_result_message(enc_msg, &msg_ctx);
4382   return GNUNET_YES;
4383 }
4384
4385
4386 /**
4387  * Receive the HELLO from transport service,
4388  * free current and replace if necessary.
4389  *
4390  * @param cls NULL
4391  * @param message HELLO message of peer
4392  */
4393 static void
4394 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4395 {
4396 #if DEBUG_DHT
4397   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4398               "Received our `%s' from transport service\n",
4399               "HELLO");
4400 #endif
4401
4402   GNUNET_assert (message != NULL);
4403   GNUNET_free_non_null(my_hello);
4404   my_hello = GNUNET_malloc(ntohs(message->size));
4405   memcpy(my_hello, message, ntohs(message->size));
4406 }
4407
4408
4409 /**
4410  * Task run during shutdown.
4411  *
4412  * @param cls unused
4413  * @param tc unused
4414  */
4415 static void
4416 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4417 {
4418   int bucket_count;
4419   struct PeerInfo *pos;
4420
4421   if (transport_handle != NULL)
4422     {
4423       GNUNET_free_non_null(my_hello);
4424       GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4425       GNUNET_TRANSPORT_disconnect(transport_handle);
4426     }
4427   for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4428     {
4429       while (k_buckets[bucket_count].head != NULL)
4430         {
4431           pos = k_buckets[bucket_count].head;
4432 #if DEBUG_DHT
4433           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4434                       "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4435 #endif
4436           delete_peer (pos, bucket_count);
4437         }
4438     }
4439   if (coreAPI != NULL)
4440     {
4441 #if DEBUG_DHT
4442       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4443                   "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4444 #endif
4445       GNUNET_CORE_disconnect (coreAPI);
4446       coreAPI = NULL;
4447     }
4448   if (datacache != NULL)
4449     {
4450 #if DEBUG_DHT
4451       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4452                   "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4453 #endif
4454       GNUNET_DATACACHE_destroy (datacache);
4455       datacache = NULL;
4456     }
4457   if (stats != NULL)
4458     {
4459       GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4460       stats = NULL;
4461     }
4462   if (dhtlog_handle != NULL)
4463     {
4464       GNUNET_DHTLOG_disconnect(dhtlog_handle);
4465       dhtlog_handle = NULL;
4466     }
4467   if (block_context != NULL)
4468     {
4469       GNUNET_BLOCK_context_destroy (block_context);
4470       block_context = NULL;
4471     }
4472   GNUNET_free_non_null(my_short_id);
4473   my_short_id = NULL;
4474 }
4475
4476
4477 /**
4478  * To be called on core init/fail.
4479  *
4480  * @param cls service closure
4481  * @param server handle to the server for this service
4482  * @param identity the public identity of this peer
4483  * @param publicKey the public key of this peer
4484  */
4485 void
4486 core_init (void *cls,
4487            struct GNUNET_CORE_Handle *server,
4488            const struct GNUNET_PeerIdentity *identity,
4489            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4490 {
4491
4492   if (server == NULL)
4493     {
4494 #if DEBUG_DHT
4495       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4496                   "%s: Connection to core FAILED!\n", "dht",
4497                   GNUNET_i2s (identity));
4498 #endif
4499       GNUNET_SCHEDULER_cancel (cleanup_task);
4500       GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4501       return;
4502     }
4503 #if DEBUG_DHT
4504   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4505               "%s: Core connection initialized, I am peer: %s\n", "dht",
4506               GNUNET_i2s (identity));
4507 #endif
4508
4509   /* Copy our identity so we can use it */
4510   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4511   if (my_short_id != NULL)
4512     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4513   my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4514   /* Set the server to local variable */
4515   coreAPI = server;
4516
4517   if (dhtlog_handle != NULL)
4518     dhtlog_handle->insert_node (NULL, &my_identity);
4519 }
4520
4521
4522 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4523   {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4524   {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4525   {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4526   {NULL, NULL, 0, 0}
4527 };
4528
4529
4530 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4531   {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4532   {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4533   {NULL, 0, 0}
4534 };
4535
4536
4537 /**
4538  * Method called whenever a peer connects.
4539  *
4540  * @param cls closure
4541  * @param peer peer identity this notification is about
4542  * @param atsi performance data
4543  */
4544 static void 
4545 handle_core_connect (void *cls,
4546                      const struct GNUNET_PeerIdentity * peer,
4547                      const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4548 {
4549   struct PeerInfo *ret;
4550
4551 #if DEBUG_DHT
4552   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4553               "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4554 #endif
4555
4556   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4557     {
4558       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));
4559       return;
4560     }
4561
4562   if (datacache != NULL)
4563     GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, GNUNET_BLOCK_TYPE_DHT_HELLO, GNUNET_TIME_absolute_get_forever());
4564   ret = try_add_peer(peer,
4565                      find_current_bucket(&peer->hashPubKey),
4566                      atsi);
4567   if (ret != NULL)
4568     {
4569       newly_found_peers++;
4570       GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4571     }
4572 #if DEBUG_DHT
4573     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4574                 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4575 #endif
4576 }
4577
4578
4579 /**
4580  * Method called whenever a peer disconnects.
4581  *
4582  * @param cls closure
4583  * @param peer peer identity this notification is about
4584  */
4585 static void
4586 handle_core_disconnect (void *cls,
4587                         const struct
4588                         GNUNET_PeerIdentity * peer)
4589 {
4590   struct PeerInfo *to_remove;
4591   int current_bucket;
4592
4593   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");
4594
4595   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4596     {
4597       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));
4598       return;
4599     }
4600   increment_stats(STAT_DISCONNECTS);
4601   GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4602   to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4603   GNUNET_assert (to_remove != NULL);
4604   GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4605   current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4606   delete_peer(to_remove, current_bucket);
4607 }
4608
4609
4610 /**
4611  * Process dht requests.
4612  *
4613  * @param cls closure
4614  * @param server the initialized server
4615  * @param c configuration to use
4616  */
4617 static void
4618 run (void *cls,
4619      struct GNUNET_SERVER_Handle *server,
4620      const struct GNUNET_CONFIGURATION_Handle *c)
4621 {
4622   struct GNUNET_TIME_Relative next_send_time;
4623   unsigned long long temp_config_num;
4624   char *converge_modifier_buf;
4625
4626   cfg = c;
4627   datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4628   GNUNET_SERVER_add_handlers (server, plugin_handlers);
4629   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4630   coreAPI = GNUNET_CORE_connect (cfg,    /* Main configuration */
4631                                  DEFAULT_CORE_QUEUE_SIZE, /* queue size */
4632                                  NULL,  /* Closure passed to DHT functions */
4633                                  &core_init,    /* Call core_init once connected */
4634                                  &handle_core_connect,  /* Handle connects */
4635                                  &handle_core_disconnect,  /* remove peers on disconnects */
4636                                  NULL,  /* Do we care about "status" updates? */
4637                                  NULL,  /* Don't want notified about all incoming messages */
4638                                  GNUNET_NO,     /* For header only inbound notification */
4639                                  NULL,  /* Don't want notified about all outbound messages */
4640                                  GNUNET_NO,     /* For header only outbound notification */
4641                                  core_handlers);        /* Register these handlers */
4642
4643   if (coreAPI == NULL)
4644     return;
4645   transport_handle = GNUNET_TRANSPORT_connect(cfg,
4646                                               NULL, NULL, NULL, NULL, NULL);
4647   if (transport_handle != NULL)
4648     GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4649   else
4650     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4651                "Failed to connect to transport service!\n");
4652   block_context = GNUNET_BLOCK_context_create (cfg);
4653   lowest_bucket = MAX_BUCKETS - 1;
4654   forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4655   forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4656   all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4657   recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4658   GNUNET_assert(all_known_peers != NULL);
4659   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4660     {
4661       debug_routes = GNUNET_YES;
4662     }
4663
4664   if (GNUNET_YES ==
4665       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4666                                            "strict_kademlia"))
4667     {
4668       strict_kademlia = GNUNET_YES;
4669     }
4670
4671   if (GNUNET_YES ==
4672       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4673                                            "stop_on_closest"))
4674     {
4675       stop_on_closest = GNUNET_YES;
4676     }
4677
4678   if (GNUNET_YES ==
4679       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4680                                            "stop_found"))
4681     {
4682       stop_on_found = GNUNET_YES;
4683     }
4684
4685   if (GNUNET_YES ==
4686       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4687                                            "malicious_getter"))
4688     {
4689       malicious_getter = GNUNET_YES;
4690       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4691                                             "MALICIOUS_GET_FREQUENCY",
4692                                             &malicious_get_frequency))
4693         malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4694     }
4695
4696   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4697                                         "MAX_HOPS",
4698                                         &max_hops))
4699     {
4700       max_hops = DEFAULT_MAX_HOPS;
4701     }
4702
4703   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4704                                                           "USE_MAX_HOPS"))
4705     {
4706       use_max_hops = GNUNET_YES;
4707     }
4708
4709   if (GNUNET_YES ==
4710       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4711                                            "malicious_putter"))
4712     {
4713       malicious_putter = GNUNET_YES;
4714       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4715                                             "MALICIOUS_PUT_FREQUENCY",
4716                                             &malicious_put_frequency))
4717         malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4718     }
4719
4720   dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
4721   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4722     {
4723       dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4724     }
4725
4726   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "bucket_size", &temp_config_num))
4727     {
4728       bucket_size = (unsigned int)temp_config_num;
4729     }
4730
4731   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "kad_alpha", &kademlia_replication))
4732     {
4733       kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
4734     }
4735
4736   if (GNUNET_YES ==
4737           GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4738                                                "malicious_dropper"))
4739     {
4740       malicious_dropper = GNUNET_YES;
4741     }
4742
4743   if (GNUNET_YES ==
4744         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4745                                              "republish"))
4746     do_republish = GNUNET_NO;
4747
4748   if (GNUNET_NO ==
4749         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4750                                              "do_find_peer"))
4751     {
4752       do_find_peer = GNUNET_NO;
4753     }
4754   else
4755     do_find_peer = GNUNET_YES;
4756
4757   if (GNUNET_YES ==
4758         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4759                                              "use_real_distance"))
4760     use_real_distance = GNUNET_YES;
4761
4762   if (GNUNET_YES ==
4763       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4764                                            "mysql_logging_extended"))
4765     {
4766       debug_routes = GNUNET_YES;
4767       debug_routes_extended = GNUNET_YES;
4768     }
4769
4770 #if DEBUG_DHT_ROUTING
4771   if (GNUNET_YES == debug_routes)
4772     {
4773       dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4774       if (dhtlog_handle == NULL)
4775         {
4776           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4777                       "Could not connect to mysql logging server, logging will not happen!");
4778         }
4779     }
4780 #endif
4781
4782   converge_option = DHT_CONVERGE_SQUARE;
4783   if (GNUNET_YES ==
4784       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4785                                            "converge_linear"))
4786     {
4787       converge_option = DHT_CONVERGE_LINEAR;
4788     }
4789   else if (GNUNET_YES ==
4790         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4791                                              "converge_exponential"))
4792     {
4793       converge_option = DHT_CONVERGE_EXPONENTIAL;
4794     }
4795   else if (GNUNET_YES ==
4796         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4797                                              "converge_random"))
4798     {
4799       converge_option = DHT_CONVERGE_RANDOM;
4800     }
4801   else if (GNUNET_YES ==
4802         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4803                                              "converge_binary"))
4804     {
4805       converge_option = DHT_CONVERGE_BINARY;
4806     }
4807
4808   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht", "converge_modifier", &converge_modifier_buf))
4809     {
4810       if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4811         {
4812           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4813           converge_modifier = 0.0;
4814         }
4815       GNUNET_free(converge_modifier_buf);
4816     }
4817
4818   stats = GNUNET_STATISTICS_create("dht", cfg);
4819
4820   if (stats != NULL)
4821     {
4822       GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4823       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4824       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4825       GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4826       GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4827       GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4828       GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4829       GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4830       GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4831       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4832       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4833       GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4834       GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4835       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4836       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4837       GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4838       GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4839       GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4840       GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4841       GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4842     }
4843   /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4844   recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4845   recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4846   if (GNUNET_YES == do_find_peer)
4847   {
4848     next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4849                            GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4850                                                     (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4851     find_peer_context.start = GNUNET_TIME_absolute_get();
4852     GNUNET_SCHEDULER_add_delayed (next_send_time,
4853                                   &send_find_peer_message, &find_peer_context);
4854   }
4855
4856   /* Scheduled the task to clean up when shutdown is called */
4857   cleanup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4858                                                &shutdown_task, NULL);
4859 }
4860
4861 /**
4862  * The main function for the dht service.
4863  *
4864  * @param argc number of arguments from the command line
4865  * @param argv command line arguments
4866  * @return 0 ok, 1 on error
4867  */
4868 int
4869 main (int argc, char *const *argv)
4870 {
4871   int ret;
4872
4873   ret = (GNUNET_OK ==
4874          GNUNET_SERVICE_run (argc,
4875                              argv,
4876                              "dht",
4877                              GNUNET_SERVICE_OPTION_NONE,
4878                              &run, NULL)) ? 0 : 1;
4879   GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap));
4880   GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap));
4881   GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4882   GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4883   GNUNET_CONTAINER_heap_destroy (recent.minHeap);
4884   return ret;
4885 }