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