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