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