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