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