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