FreeBSD 7 does not have log2.
[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
1774   client->transmit_handle =
1775     GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1776                                          ntohs (client->pending_head->msg->
1777                                                 size),
1778                                          GNUNET_TIME_UNIT_FOREVER_REL,
1779                                          &send_generic_reply, client);
1780 }
1781
1782 /**
1783  * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1784  * request.  A ClientList is passed as closure, take the head of the list
1785  * and copy it into buf, which has the result of sending the message to the
1786  * client.
1787  *
1788  * @param cls closure to this call
1789  * @param size maximum number of bytes available to send
1790  * @param buf where to copy the actual message to
1791  *
1792  * @return the number of bytes actually copied, 0 indicates failure
1793  */
1794 static size_t
1795 send_generic_reply (void *cls, size_t size, void *buf)
1796 {
1797   struct ClientList *client = cls;
1798   char *cbuf = buf;
1799   struct PendingMessage *reply;
1800   size_t off;
1801   size_t msize;
1802
1803   client->transmit_handle = NULL;
1804   if (buf == NULL)             
1805     {
1806       /* client disconnected */
1807       return 0;
1808     }
1809   off = 0;
1810   while ( (NULL != (reply = client->pending_head)) &&
1811           (size >= off + (msize = ntohs (reply->msg->size))))
1812     {
1813       GNUNET_CONTAINER_DLL_remove (client->pending_head,
1814                                    client->pending_tail,
1815                                    reply);
1816       memcpy (&cbuf[off], reply->msg, msize);
1817       GNUNET_free (reply);
1818       off += msize;
1819     }
1820   process_pending_messages (client);
1821   return off;
1822 }
1823
1824
1825 /**
1826  * Add a PendingMessage to the clients list of messages to be sent
1827  *
1828  * @param client the active client to send the message to
1829  * @param pending_message the actual message to send
1830  */
1831 static void
1832 add_pending_message (struct ClientList *client,
1833                      struct PendingMessage *pending_message)
1834 {
1835   GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1836                                      client->pending_tail,
1837                                      client->pending_tail,
1838                                      pending_message);
1839   process_pending_messages (client);
1840 }
1841
1842
1843
1844
1845 /**
1846  * Called when a reply needs to be sent to a client, as
1847  * a result it found to a GET or FIND PEER request.
1848  *
1849  * @param client the client to send the reply to
1850  * @param message the encapsulated message to send
1851  * @param uid the unique identifier of this request
1852  */
1853 static void
1854 send_reply_to_client (struct ClientList *client,
1855                       const struct GNUNET_MessageHeader *message,
1856                       unsigned long long uid)
1857 {
1858   struct GNUNET_DHT_RouteResultMessage *reply;
1859   struct PendingMessage *pending_message;
1860   uint16_t msize;
1861   size_t tsize;
1862 #if DEBUG_DHT
1863   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1864               "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1865 #endif
1866   msize = ntohs (message->size);
1867   tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1868   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1869     {
1870       GNUNET_break_op (0);
1871       return;
1872     }
1873
1874   pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1875   pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1876   reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1877   reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1878   reply->header.size = htons (tsize);
1879   reply->unique_id = GNUNET_htonll (uid);
1880   memcpy (&reply[1], message, msize);
1881
1882   add_pending_message (client, pending_message);
1883 }
1884
1885 /**
1886  * Consider whether or not we would like to have this peer added to
1887  * our routing table.  Check whether bucket for this peer is full,
1888  * if so return negative; if not return positive.  Since peers are
1889  * only added on CORE level connect, this doesn't actually add the
1890  * peer to the routing table.
1891  *
1892  * @param peer the peer we are considering adding
1893  *
1894  * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1895  *         already full)
1896  */
1897 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1898 {
1899   int bucket;
1900
1901   if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1902     return GNUNET_NO; /* We already know this peer (are connected even!) */
1903   bucket = find_current_bucket(&peer->hashPubKey);
1904
1905   if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1906     return GNUNET_YES;
1907
1908   return GNUNET_NO;
1909 }
1910
1911 /**
1912  * Main function that handles whether or not to route a result
1913  * message to other peers, or to send to our local client.
1914  *
1915  * @param cls closure (unused, always should be NULL)
1916  * @param msg the result message to be routed
1917  * @param message_context context of the message we are routing
1918  *
1919  * @return the number of peers the message was routed to,
1920  *         GNUNET_SYSERR on failure
1921  */
1922 static int route_result_message(void *cls,
1923                                 struct GNUNET_MessageHeader *msg,
1924                                 struct DHT_MessageContext *message_context)
1925 {
1926   struct GNUNET_PeerIdentity new_peer;
1927   struct DHTQueryRecord *record;
1928   struct DHTRouteSource *pos;
1929   struct PeerInfo *peer_info;
1930   const struct GNUNET_MessageHeader *hello_msg;
1931
1932   increment_stats(STAT_RESULTS);
1933   /**
1934    * If a find peer result message is received and contains a valid
1935    * HELLO for another peer, offer it to the transport service.
1936    */
1937   if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1938     {
1939       if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1940         GNUNET_break_op(0);
1941
1942       hello_msg = &msg[1];
1943       if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1944       {
1945         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1946         GNUNET_break_op(0);
1947         return GNUNET_NO;
1948       }
1949       else /* We have a valid hello, and peer id stored in new_peer */
1950       {
1951         find_peer_context.count++;
1952         increment_stats(STAT_FIND_PEER_REPLY);
1953         if (GNUNET_YES == consider_peer(&new_peer))
1954         {
1955           increment_stats(STAT_HELLOS_PROVIDED);
1956           GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1957           GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1958         }
1959       }
1960     }
1961
1962   if (malicious_dropper == GNUNET_YES)
1963     record = NULL;
1964   else
1965     record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1966
1967   if (record == NULL) /* No record of this message! */
1968     {
1969 #if DEBUG_DHT
1970     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1971                 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1972                 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1973 #endif
1974 #if DEBUG_DHT_ROUTING
1975       if ((debug_routes_extended) && (dhtlog_handle != NULL))
1976         {
1977           dhtlog_handle->insert_route (NULL,
1978                                        message_context->unique_id,
1979                                        DHTLOG_RESULT,
1980                                        message_context->hop_count,
1981                                        GNUNET_SYSERR,
1982                                        &my_identity,
1983                                        &message_context->key,
1984                                        message_context->peer, NULL);
1985         }
1986 #endif
1987       if (message_context->bloom != NULL)
1988         {
1989           GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1990           message_context->bloom = NULL;
1991         }
1992       return 0;
1993     }
1994
1995   pos = record->head;
1996   while (pos != NULL)
1997     {
1998 #if STRICT_FORWARDING
1999       if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2000         {
2001           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2002           {
2003             increment_stats("# find peer responses NOT forwarded (bloom match)");
2004             pos = pos->next;
2005             continue;
2006           }
2007           else
2008             GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2009         }
2010 #endif
2011
2012       if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2013         {
2014 #if DEBUG_DHT
2015           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2016                       "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2017                       "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2018 #endif
2019 #if DEBUG_DHT_ROUTING
2020           if ((debug_routes_extended) && (dhtlog_handle != NULL))
2021             {
2022               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2023                                            message_context->hop_count,
2024                                            GNUNET_YES, &my_identity, &message_context->key,
2025                                            message_context->peer, NULL);
2026             }
2027 #endif
2028           increment_stats(STAT_RESULTS_TO_CLIENT);
2029           if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2030             increment_stats(STAT_GET_REPLY);
2031
2032           send_reply_to_client(pos->client, msg, message_context->unique_id);
2033         }
2034       else /* Send to peer */
2035         {
2036           peer_info = find_peer_by_id(&pos->source);
2037           if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2038             {
2039               pos = pos->next;
2040               continue;
2041             }
2042
2043           if (message_context->bloom == NULL)
2044             message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2045           GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2046           if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2047             {
2048 #if DEBUG_DHT
2049               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2050                           "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2051                           "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2052 #endif
2053 #if DEBUG_DHT_ROUTING
2054               if ((debug_routes_extended) && (dhtlog_handle != NULL))
2055                 {
2056                   dhtlog_handle->insert_route (NULL, message_context->unique_id,
2057                                                DHTLOG_RESULT,
2058                                                message_context->hop_count,
2059                                                GNUNET_NO, &my_identity, &message_context->key,
2060                                                message_context->peer, &pos->source);
2061                 }
2062 #endif
2063               forward_result_message(cls, msg, peer_info, message_context);
2064             }
2065           else
2066             {
2067 #if DEBUG_DHT
2068               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2069                           "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2070                           "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2071 #endif
2072             }
2073         }
2074       pos = pos->next;
2075     }
2076   if (message_context->bloom != NULL)
2077     GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2078   return 0;
2079 }
2080
2081 /**
2082  * Iterator for local get request results,
2083  *
2084  * @param cls closure for iterator, a DatacacheGetContext
2085  * @param exp when does this value expire?
2086  * @param key the key this data is stored under
2087  * @param size the size of the data identified by key
2088  * @param data the actual data
2089  * @param type the type of the data
2090  *
2091  * @return GNUNET_OK to continue iteration, anything else
2092  * to stop iteration.
2093  */
2094 static int
2095 datacache_get_iterator (void *cls,
2096                         struct GNUNET_TIME_Absolute exp,
2097                         const GNUNET_HashCode * key,
2098                         uint32_t size, const char *data, uint32_t type)
2099 {
2100   struct DHT_MessageContext *msg_ctx = cls;
2101   struct DHT_MessageContext *new_msg_ctx;
2102   struct GNUNET_DHT_GetResultMessage *get_result;
2103 #if DEBUG_DHT
2104   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2105               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2106 #endif
2107   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2108   memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2109   get_result =
2110     GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2111   get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2112   get_result->header.size =
2113     htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2114   get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2115   get_result->type = htons (type);
2116   memcpy (&get_result[1], data, size);
2117   new_msg_ctx->peer = &my_identity;
2118   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2119   new_msg_ctx->hop_count = 0;
2120   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2121   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2122   increment_stats(STAT_GET_RESPONSE_START);
2123   route_result_message(cls, &get_result->header, new_msg_ctx);
2124   GNUNET_free(new_msg_ctx);
2125   //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2126   //                      datacache_get_ctx->unique_id);
2127   GNUNET_free (get_result);
2128   return GNUNET_OK;
2129 }
2130
2131
2132 /**
2133  * Server handler for all dht get requests, look for data,
2134  * if found, send response either to clients or other peers.
2135  *
2136  * @param cls closure for service
2137  * @param msg the actual get message
2138  * @param message_context struct containing pertinent information about the get request
2139  *
2140  * @return number of items found for GET request
2141  */
2142 static unsigned int
2143 handle_dht_get (void *cls, 
2144                 const struct GNUNET_MessageHeader *msg,
2145                 struct DHT_MessageContext *message_context)
2146 {
2147   const struct GNUNET_DHT_GetMessage *get_msg;
2148   uint16_t get_type;
2149   unsigned int results;
2150
2151   get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2152   if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2153     {
2154       GNUNET_break (0);
2155       return 0;
2156     }
2157
2158   get_type = ntohs (get_msg->type);
2159 #if DEBUG_DHT
2160   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2161               "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2162               "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2163               message_context->unique_id);
2164 #endif
2165   increment_stats(STAT_GETS);
2166   results = 0;
2167   if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2168     return results;
2169
2170   if (datacache != NULL)
2171     results =
2172       GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2173                             &datacache_get_iterator, message_context);
2174
2175   if (results >= 1)
2176     {
2177 #if DEBUG_DHT
2178       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2179                   "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2180                   results, "GET", message_context->unique_id);
2181 #endif
2182 #if DEBUG_DHT_ROUTING
2183       if ((debug_routes) && (dhtlog_handle != NULL))
2184         {
2185           dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2186                                 message_context->hop_count, GNUNET_YES, &my_identity,
2187                                 &message_context->key);
2188         }
2189
2190       if ((debug_routes_extended) && (dhtlog_handle != NULL))
2191         {
2192           dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2193                                        message_context->hop_count, GNUNET_YES,
2194                                        &my_identity, &message_context->key, message_context->peer,
2195                                        NULL);
2196         }
2197 #endif
2198     }
2199
2200   if (message_context->hop_count == 0) /* Locally initiated request */
2201     {
2202 #if DEBUG_DHT_ROUTING
2203     if ((debug_routes) && (dhtlog_handle != NULL))
2204       {
2205         dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2206                                       message_context->hop_count, GNUNET_NO, &my_identity,
2207                                       &message_context->key);
2208       }
2209 #endif
2210     }
2211
2212   return results;
2213 }
2214
2215 static void
2216 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2217 {
2218   GNUNET_HashCode *key = cls;
2219   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2220     {
2221       GNUNET_free(key);
2222     }
2223 }
2224
2225 /**
2226  * Server handler for initiating local dht find peer requests
2227  *
2228  * @param cls closure for service
2229  * @param find_msg the actual find peer message
2230  * @param message_context struct containing pertinent information about the request
2231  *
2232  */
2233 static void
2234 handle_dht_find_peer (void *cls,
2235                       const struct GNUNET_MessageHeader *find_msg,
2236                       struct DHT_MessageContext *message_context)
2237 {
2238   struct GNUNET_MessageHeader *find_peer_result;
2239   struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2240   struct DHT_MessageContext *new_msg_ctx;
2241   struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2242   size_t hello_size;
2243   size_t tsize;
2244   GNUNET_HashCode *recent_hash;
2245   struct GNUNET_MessageHeader *other_hello;
2246   size_t other_hello_size;
2247   struct GNUNET_PeerIdentity peer_id;
2248
2249   find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2250   GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2251   if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2252     return;
2253   other_hello = NULL;
2254   other_hello_size = 0;
2255   if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2256     {
2257       other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2258       other_hello = GNUNET_malloc(other_hello_size);
2259       memcpy(other_hello, &find_peer_message[1], other_hello_size);
2260       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)))
2261         {
2262           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2263           GNUNET_free(other_hello);
2264           return;
2265         }
2266 #if FIND_PEER_WITH_HELLO
2267       if (GNUNET_YES == consider_peer(&peer_id))
2268         {
2269           increment_stats(STAT_HELLOS_PROVIDED);
2270           GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2271           GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2272           return;
2273         }
2274       else /* We don't want this peer! */
2275         return;
2276 #endif
2277     }
2278
2279 #if DEBUG_DHT
2280   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2281               "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2282               my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2283               ntohs (find_msg->size),
2284               sizeof (struct GNUNET_MessageHeader));
2285 #endif
2286   if (my_hello == NULL)
2287   {
2288 #if DEBUG_DHT
2289     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2290                 "`%s': Our HELLO is null, can't return.\n",
2291                 "DHT");
2292 #endif
2293     GNUNET_free_non_null(other_hello);
2294     return;
2295   }
2296
2297   incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2298   if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2299     {
2300       increment_stats(STAT_BLOOM_FIND_PEER);
2301       GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2302       GNUNET_free_non_null(other_hello);
2303       return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2304     }
2305   GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2306
2307 #if RESTRICT_FIND_PEER
2308
2309   /**
2310    * Ignore any find peer requests from a peer we have seen very recently.
2311    */
2312   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! */
2313   {
2314     increment_stats("# dht find peer requests ignored (recently seen!)");
2315     GNUNET_free_non_null(other_hello);
2316     return;
2317   }
2318
2319   /**
2320    * Use this check to only allow the peer to respond to find peer requests if
2321    * it would be beneficial to have the requesting peer in this peers routing
2322    * table.  Can be used to thwart peers flooding the network with find peer
2323    * requests that we don't care about.  However, if a new peer is joining
2324    * the network and has no other peers this is a problem (assume all buckets
2325    * full, no one will respond!).
2326    */
2327   memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2328   if (GNUNET_NO == consider_peer(&peer_id))
2329     {
2330       increment_stats("# dht find peer requests ignored (do not need!)");
2331       GNUNET_free_non_null(other_hello);
2332       return;
2333     }
2334 #endif
2335
2336   recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2337   memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2338   GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2339   GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2340
2341   /* Simplistic find_peer functionality, always return our hello */
2342   hello_size = ntohs(my_hello->size);
2343   tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2344
2345   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2346     {
2347       GNUNET_break_op (0);
2348       GNUNET_free_non_null(other_hello);
2349       return;
2350     }
2351
2352   find_peer_result = GNUNET_malloc (tsize);
2353   find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2354   find_peer_result->size = htons (tsize);
2355   memcpy (&find_peer_result[1], my_hello, hello_size);
2356
2357   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2358               "`%s': Sending hello size %d to requesting peer.\n",
2359               "DHT", hello_size);
2360
2361   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2362   memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2363   new_msg_ctx->peer = &my_identity;
2364   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2365   new_msg_ctx->hop_count = 0;
2366   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2367   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2368   increment_stats(STAT_FIND_PEER_ANSWER);
2369   route_result_message(cls, find_peer_result, new_msg_ctx);
2370   GNUNET_free(new_msg_ctx);
2371 #if DEBUG_DHT_ROUTING
2372   if ((debug_routes) && (dhtlog_handle != NULL))
2373     {
2374       dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2375                                    message_context->hop_count, GNUNET_YES, &my_identity,
2376                                    &message_context->key);
2377     }
2378 #endif
2379   GNUNET_free_non_null(other_hello);
2380   GNUNET_free(find_peer_result);
2381 }
2382
2383 /**
2384  * Task used to republish data.
2385  * Forward declaration; function call loop.
2386  *
2387  * @param cls closure (a struct RepublishContext)
2388  * @param tc runtime context for this task
2389  */
2390 static void
2391 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2392
2393 /**
2394  * Server handler for initiating local dht put requests
2395  *
2396  * @param cls closure for service
2397  * @param msg the actual put message
2398  * @param message_context struct containing pertinent information about the request
2399  */
2400 static void
2401 handle_dht_put (void *cls,
2402                 const struct GNUNET_MessageHeader *msg,
2403                 struct DHT_MessageContext *message_context)
2404 {
2405   struct GNUNET_DHT_PutMessage *put_msg;
2406   size_t put_type;
2407   size_t data_size;
2408   int ret;
2409   struct RepublishContext *put_context;
2410
2411   GNUNET_assert (ntohs (msg->size) >=
2412                  sizeof (struct GNUNET_DHT_PutMessage));
2413
2414
2415   put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2416   put_type = ntohs (put_msg->type);
2417
2418   if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2419     return;
2420
2421   data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2422 #if DEBUG_DHT
2423   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2424               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2425               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2426 #endif
2427 #if DEBUG_DHT_ROUTING
2428   if (message_context->hop_count == 0) /* Locally initiated request */
2429     {
2430       if ((debug_routes) && (dhtlog_handle != NULL))
2431         {
2432           dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2433                                        message_context->hop_count, GNUNET_NO, &my_identity,
2434                                        &message_context->key);
2435         }
2436     }
2437 #endif
2438
2439   if (message_context->closest != GNUNET_YES)
2440     return;
2441
2442 #if DEBUG_DHT_ROUTING
2443   if ((debug_routes_extended) && (dhtlog_handle != NULL))
2444     {
2445       dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2446                                    message_context->hop_count, GNUNET_YES,
2447                                    &my_identity, &message_context->key, message_context->peer,
2448                                    NULL);
2449     }
2450
2451   if ((debug_routes) && (dhtlog_handle != NULL))
2452     {
2453       dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2454                                    message_context->hop_count, GNUNET_YES, &my_identity,
2455                                    &message_context->key);
2456     }
2457 #endif
2458
2459   increment_stats(STAT_PUTS_INSERTED);
2460   if (datacache != NULL)
2461     {
2462       ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2463                                   (char *) &put_msg[1], put_type,
2464                                   GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2465
2466       if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2467         {
2468           put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2469           memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2470           put_context->type = put_type;
2471           GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
2472         }
2473     }
2474   else
2475     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2476                 "`%s:%s': %s request received, but have no datacache!\n",
2477                 my_short_id, "DHT", "PUT");
2478 }
2479
2480 /**
2481  * Estimate the diameter of the network based
2482  * on how many buckets are currently in use.
2483  * Concept here is that the diameter of the network
2484  * is roughly the distance a message must travel in
2485  * order to reach its intended destination.  Since
2486  * at each hop we expect to get one bit closer, and
2487  * we have one bit per bucket, the number of buckets
2488  * in use should be the largest number of hops for
2489  * a sucessful message. (of course, this assumes we
2490  * know all peers in the network!)
2491  *
2492  * @return ballpark diameter figure
2493  */
2494 static unsigned int estimate_diameter()
2495 {
2496   return MAX_BUCKETS - lowest_bucket;
2497 }
2498
2499 /**
2500  * To how many peers should we (on average)
2501  * forward the request to obtain the desired
2502  * target_replication count (on average).
2503  *
2504  * Always 0, 1 or 2 (don't send, send once, split)
2505  */
2506 static unsigned int
2507 get_forward_count (unsigned int hop_count, size_t target_replication)
2508 {
2509 #if DOUBLE
2510   double target_count;
2511   double random_probability;
2512 #else
2513   uint32_t random_value;
2514 #endif
2515   unsigned int target_value;
2516   unsigned int diameter;
2517
2518   /**
2519    * If we are behaving in strict kademlia mode, send multiple initial requests,
2520    * but then only send to 1 or 0 peers based strictly on the number of hops.
2521    */
2522   if (strict_kademlia == GNUNET_YES)
2523     {
2524       if (hop_count == 0)
2525         return DHT_KADEMLIA_REPLICATION;
2526       else if (hop_count < max_hops)
2527         return 1;
2528       else
2529         return 0;
2530     }
2531
2532   /* FIXME: the smaller we think the network is the more lenient we should be for
2533    * routing right?  The estimation below only works if we think we have reasonably
2534    * full routing tables, which for our RR topologies may not be the case!
2535    */
2536   diameter = estimate_diameter ();
2537   if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2538     {
2539 #if DEBUG_DHT
2540       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541                   "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2542                   "DHT", estimate_diameter(), lowest_bucket);
2543 #endif
2544       return 0;
2545     }
2546   else if (hop_count > max_hops)
2547     {
2548 #if DEBUG_DHT
2549       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2550                   "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2551                   "DHT");
2552 #endif
2553       return 0;
2554     }
2555
2556 #if DOUBLE
2557   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2558   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2559   target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2560     (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2561   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2562   random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2563       RAND_MAX)) / RAND_MAX;
2564   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2565
2566   target_value = 0;
2567   //while (target_value < target_count)
2568   if (target_value < target_count)
2569     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? */
2570
2571
2572   //if ((target_count + 1 - (double)target_value) > random_probability)
2573   if ((target_count) > random_probability)
2574     target_value++;
2575 #endif
2576
2577   random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2578   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));
2579   target_value = 1;
2580   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2581   if (random_value < target_replication)
2582     target_value++;
2583
2584   return target_value;
2585 }
2586
2587 /*
2588  * Check whether my identity is closer than any known peers.
2589  * If a non-null bloomfilter is given, check if this is the closest
2590  * peer that hasn't already been routed to.
2591  *
2592  * @param target hash code to check closeness to
2593  * @param bloom bloomfilter, exclude these entries from the decision
2594  *
2595  * Return GNUNET_YES if node location is closest, GNUNET_NO
2596  * otherwise.
2597  */
2598 int
2599 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2600 {
2601   int bits;
2602   int other_bits;
2603   int bucket_num;
2604   int count;
2605   struct PeerInfo *pos;
2606   unsigned int my_distance;
2607
2608   if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2609     return GNUNET_YES;
2610
2611   bucket_num = find_current_bucket(target);
2612
2613   bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2614   my_distance = distance(&my_identity.hashPubKey, target);
2615   pos = k_buckets[bucket_num].head;
2616   count = 0;
2617   while ((pos != NULL) && (count < bucket_size))
2618     {
2619       if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2620         {
2621           pos = pos->next;
2622           continue; /* Skip already checked entries */
2623         }
2624
2625       other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2626       if (other_bits > bits)
2627         return GNUNET_NO;
2628       else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2629         {
2630           if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2631             return GNUNET_YES;
2632           else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2633             return GNUNET_NO;
2634         }
2635       pos = pos->next;
2636     }
2637
2638 #if DEBUG_TABLE
2639   GNUNET_GE_LOG (coreAPI->ectx,
2640                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2641                  GNUNET_GE_BULK, "closest peer\n");
2642   printPeerBits (&closest);
2643   GNUNET_GE_LOG (coreAPI->ectx,
2644                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2645                  GNUNET_GE_BULK, "me\n");
2646   printPeerBits (coreAPI->my_identity);
2647   GNUNET_GE_LOG (coreAPI->ectx,
2648                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2649                  GNUNET_GE_BULK, "key\n");
2650   printKeyBits (target);
2651   GNUNET_GE_LOG (coreAPI->ectx,
2652                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2653                  GNUNET_GE_BULK,
2654                  "closest peer inverse distance is %u, mine is %u\n",
2655                  inverse_distance (target, &closest.hashPubKey),
2656                  inverse_distance (target,
2657                                    &coreAPI->my_identity->hashPubKey));
2658 #endif
2659
2660   /* No peers closer, we are the closest! */
2661   return GNUNET_YES;
2662 }
2663
2664
2665 /**
2666  * Return this peers adjusted value based on the convergence
2667  * function chosen.  This is the key function for randomized
2668  * routing decisions.
2669  *
2670  * @param target the key of the request
2671  * @param peer the peer we would like the value of
2672  * @param hops number of hops this message has already traveled
2673  *
2674  * @return bit distance from target to peer raised to an exponent
2675  *         adjusted based on the current routing convergence algorithm
2676  *
2677  */
2678 unsigned long long
2679 converge_distance (const GNUNET_HashCode *target,
2680                    struct PeerInfo *peer,
2681                    unsigned int hops)
2682 {
2683   unsigned long long ret;
2684   unsigned int other_matching_bits;
2685   double converge_modifier = 0.0;
2686   double base_converge_modifier = .1;
2687   double calc_value;
2688   double exponent;
2689   int curr_max_hops;
2690
2691   if (use_max_hops)
2692     curr_max_hops = max_hops;
2693   else
2694     curr_max_hops = (estimate_diameter() + 1) * 2;
2695
2696   if (converge_modifier > 0)
2697     converge_modifier = converge_modifier * base_converge_modifier;
2698   else
2699     {
2700       converge_modifier = base_converge_modifier;
2701       base_converge_modifier = 0.0;
2702     }
2703
2704   GNUNET_assert(converge_modifier > 0);
2705
2706   other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2707
2708   switch (converge_option)
2709     {
2710       case DHT_CONVERGE_RANDOM:
2711         return 1; /* Always return 1, choose equally among all peers */
2712       case DHT_CONVERGE_LINEAR:
2713         calc_value = hops * curr_max_hops * converge_modifier;
2714         break;
2715       case DHT_CONVERGE_SQUARE:
2716         /**
2717          * Simple square based curve.
2718          */
2719         calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * converge_modifier));
2720         break;
2721       case DHT_CONVERGE_EXPONENTIAL:
2722         /**
2723          * Simple exponential curve.
2724          */
2725         if (base_converge_modifier > 0)
2726           calc_value = (converge_modifier * hops * hops) / curr_max_hops;
2727         else
2728           calc_value = (hops * hops) / curr_max_hops;
2729         break;
2730       default:
2731         return 1;
2732     }
2733
2734   /* Take the log (base e) of the number of bits matching the other peer */
2735   exponent = log(other_matching_bits);
2736
2737   /* Check if we would overflow; our largest possible value is 2^64 = e^44.361419555836498 */
2738   if (exponent * calc_value >= 44.361419555836498)
2739     return ULLONG_MAX;
2740
2741   /* Clear errno and all math exceptions */
2742   errno = 0;
2743   feclearexcept(FE_ALL_EXCEPT);
2744   ret = (unsigned long long)pow(other_matching_bits, calc_value);
2745   if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2746       FE_UNDERFLOW))
2747     {
2748       if (0 != fetestexcept(FE_OVERFLOW))
2749         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2750       if (0 != fetestexcept(FE_INVALID))
2751         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2752       if (0 != fetestexcept(FE_UNDERFLOW))
2753         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2754       return 0;
2755     }
2756   else
2757     return ret;
2758 }
2759
2760 /**
2761  * Comparison function for two struct PeerInfo's
2762  * which have already had their matching bits to
2763  * some target calculated.
2764  *
2765  * @param p1 a pointer pointer to a struct PeerInfo
2766  * @param p2 a pointer pointer to a struct PeerInfo
2767  *
2768  * @return 0 if equidistant to target,
2769  *        -1 if p1 is closer,
2770  *         1 if p2 is closer
2771  */
2772 static int
2773 compare_peers (const void *p1, const void *p2)
2774 {
2775   struct PeerInfo **first = (struct PeerInfo **)p1;
2776   struct PeerInfo **second = (struct PeerInfo **)p2;
2777
2778   if ((*first)->matching_bits > (*second)->matching_bits)
2779     return -1;
2780   if ((*first)->matching_bits < (*second)->matching_bits)
2781     return 1;
2782   else
2783     return 0;
2784 }
2785
2786
2787 /**
2788  * Select a peer from the routing table that would be a good routing
2789  * destination for sending a message for "target".  The resulting peer
2790  * must not be in the set of blocked peers.<p>
2791  *
2792  * Note that we should not ALWAYS select the closest peer to the
2793  * target, peers further away from the target should be chosen with
2794  * exponentially declining probability.
2795  *
2796  * @param target the key we are selecting a peer to route to
2797  * @param bloom a bloomfilter containing entries this request has seen already
2798  *
2799  * @return Peer to route to, or NULL on error
2800  */
2801 static struct PeerInfo *
2802 select_peer (const GNUNET_HashCode * target,
2803              struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2804 {
2805   unsigned int bc;
2806   unsigned int i;
2807   unsigned int count;
2808   unsigned int offset;
2809   unsigned int my_matching_bits;
2810   int closest_bucket;
2811   struct PeerInfo *pos;
2812   struct PeerInfo *sorted_closest[bucket_size];
2813   unsigned long long temp_converge_distance;
2814   unsigned long long total_distance;
2815   unsigned long long selected;
2816 #if DEBUG_DHT > 1
2817   unsigned long long stats_total_distance;
2818   double sum;
2819 #endif
2820   /* For kademlia */
2821   unsigned int distance;
2822   unsigned int largest_distance;
2823   struct PeerInfo *chosen;
2824
2825   my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
2826
2827   total_distance = 0;
2828   if (strict_kademlia == GNUNET_YES)
2829     {
2830       largest_distance = 0;
2831       chosen = NULL;
2832       for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2833         {
2834           pos = k_buckets[bc].head;
2835           count = 0;
2836           while ((pos != NULL) && (count < bucket_size))
2837             {
2838               /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2839               if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2840                 {
2841                   distance = inverse_distance (target, &pos->id.hashPubKey);
2842                   if (distance > largest_distance)
2843                     {
2844                       chosen = pos;
2845                       largest_distance = distance;
2846                     }
2847                 }
2848               count++;
2849               pos = pos->next;
2850             }
2851         }
2852
2853       if ((largest_distance > 0) && (chosen != NULL))
2854         {
2855           GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2856           return chosen;
2857         }
2858       else
2859         {
2860           return NULL;
2861         }
2862     }
2863
2864   /* GNUnet-style */
2865   total_distance = 0;
2866   /* Three steps: order peers in closest bucket (most matching bits).
2867    * Then go over all LOWER buckets (matching same bits we do)
2868    * Then go over all HIGHER buckets (matching less then we do)
2869    */
2870
2871   closest_bucket = find_current_bucket(target);
2872   GNUNET_assert(closest_bucket >= lowest_bucket);
2873   pos = k_buckets[closest_bucket].head;
2874   count = 0;
2875   offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
2876   memset(sorted_closest, 0, sizeof(sorted_closest));
2877   /* Put any peers in the closest bucket in the sorting array */
2878   while ((pos != NULL) && (count < bucket_size))
2879     {
2880       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2881         {
2882           count++;
2883           pos = pos->next;
2884           continue; /* Ignore bloomfiltered peers */
2885         }
2886       pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2887       sorted_closest[offset] = pos;
2888       pos = pos->next;
2889       offset++;
2890       count++;
2891     }
2892
2893   /* Sort the peers in descending order */
2894   qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
2895
2896   /* Put the sorted closest peers into the possible bins first, in case of overflow. */
2897   for (i = 0; i < offset; i++)
2898     {
2899       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
2900       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
2901         break; /* Ignore bloomfiltered peers */
2902       if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2903         total_distance += temp_converge_distance;
2904       else
2905         break; /* overflow case */
2906     }
2907
2908   /* Now handle peers in lower buckets (matches same # of bits as target) */
2909   for (bc = lowest_bucket; bc < closest_bucket; bc++)
2910     {
2911       pos = k_buckets[bc].head;
2912       count = 0;
2913       while ((pos != NULL) && (count < bucket_size))
2914         {
2915           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2916             {
2917               count++;
2918               pos = pos->next;
2919               continue; /* Ignore bloomfiltered peers */
2920             }
2921           temp_converge_distance = converge_distance(target, pos, hops);
2922           if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2923             total_distance += temp_converge_distance;
2924           else
2925             break; /* overflow case */
2926           pos = pos->next;
2927           count++;
2928         }
2929     }
2930
2931   /* Now handle all the further away peers */
2932   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
2933     {
2934       pos = k_buckets[bc].head;
2935       count = 0;
2936       while ((pos != NULL) && (count < bucket_size))
2937         {
2938           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2939             {
2940               count++;
2941               pos = pos->next;
2942               continue; /* Ignore bloomfiltered peers */
2943             }
2944           temp_converge_distance = converge_distance(target, pos, hops);
2945           if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2946             total_distance += temp_converge_distance;
2947           else
2948             break; /* overflow case */
2949           pos = pos->next;
2950           count++;
2951         }
2952     }
2953
2954   if (total_distance == 0) /* No peers to select from! */
2955     {
2956       increment_stats("# select_peer, total_distance == 0");
2957       return NULL;
2958     }
2959
2960 #if DEBUG_DHT_ROUTING > 1
2961   sum = 0.0;
2962   /* PRINT STATS */
2963   /* Put the sorted closest peers into the possible bins first, in case of overflow. */
2964   stats_total_distance = 0;
2965   for (i = 0; i < offset; i++)
2966     {
2967       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
2968         break; /* Ignore bloomfiltered peers */
2969       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
2970       if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
2971         stats_total_distance += temp_converge_distance;
2972       else
2973         break; /* overflow case */
2974       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);
2975     }
2976
2977   /* Now handle peers in lower buckets (matches same # of bits as target) */
2978   for (bc = lowest_bucket; bc < closest_bucket; bc++)
2979     {
2980       pos = k_buckets[bc].head;
2981       count = 0;
2982       while ((pos != NULL) && (count < bucket_size))
2983         {
2984           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2985             {
2986               count++;
2987               pos = pos->next;
2988               continue; /* Ignore bloomfiltered peers */
2989             }
2990           temp_converge_distance = converge_distance(target, pos, hops);
2991           if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
2992             stats_total_distance += temp_converge_distance;
2993           else
2994             break; /* overflow case */
2995           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);
2996           pos = pos->next;
2997           count++;
2998         }
2999     }
3000
3001   /* Now handle all the further away peers */
3002   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3003     {
3004       pos = k_buckets[bc].head;
3005       count = 0;
3006       while ((pos != NULL) && (count < bucket_size))
3007         {
3008           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3009             {
3010               count++;
3011               pos = pos->next;
3012               continue; /* Ignore bloomfiltered peers */
3013             }
3014           temp_converge_distance = converge_distance(target, pos, hops);
3015           if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3016             stats_total_distance += temp_converge_distance;
3017           else
3018             break; /* overflow case */
3019           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);
3020           pos = pos->next;
3021           count++;
3022         }
3023     }
3024   /* END PRINT STATS */
3025 #endif
3026
3027   /* Now actually choose a peer */
3028   selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3029
3030   /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3031   for (i = 0; i < offset; i++)
3032     {
3033       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3034         break; /* Ignore bloomfiltered peers */
3035       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3036       if (temp_converge_distance >= selected)
3037         return sorted_closest[i];
3038       else
3039         selected -= temp_converge_distance;
3040     }
3041
3042   /* Now handle peers in lower buckets (matches same # of bits as target) */
3043   for (bc = lowest_bucket; bc < closest_bucket; bc++)
3044     {
3045       pos = k_buckets[bc].head;
3046       count = 0;
3047       while ((pos != NULL) && (count < bucket_size))
3048         {
3049           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3050             {
3051               count++;
3052               pos = pos->next;
3053               continue; /* Ignore bloomfiltered peers */
3054             }
3055           temp_converge_distance = converge_distance(target, pos, hops);
3056           if (temp_converge_distance >= selected)
3057             return pos;
3058           else
3059             selected -= temp_converge_distance;
3060           pos = pos->next;
3061           count++;
3062         }
3063     }
3064
3065   /* Now handle all the further away peers */
3066   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3067     {
3068       pos = k_buckets[bc].head;
3069       count = 0;
3070       while ((pos != NULL) && (count < bucket_size))
3071         {
3072           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3073             {
3074               count++;
3075               pos = pos->next;
3076               continue; /* Ignore bloomfiltered peers */
3077             }
3078           temp_converge_distance = converge_distance(target, pos, hops);
3079           if (temp_converge_distance >= selected)
3080             return pos;
3081           else
3082             selected -= temp_converge_distance;
3083           pos = pos->next;
3084           count++;
3085         }
3086     }
3087
3088   increment_stats("# failed to select peer");
3089   return NULL;
3090 }
3091
3092
3093 /**
3094  * Task used to remove recent entries, either
3095  * after timeout, when full, or on shutdown.
3096  *
3097  * @param cls the entry to remove
3098  * @param tc context, reason, etc.
3099  */
3100 static void
3101 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3102 {
3103   struct RecentRequest *req = cls;
3104   static GNUNET_HashCode hash;
3105
3106   GNUNET_assert(req != NULL);
3107   hash_from_uid(req->uid, &hash);
3108   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3109   GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3110   GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3111   GNUNET_free(req);
3112
3113   if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3114   {
3115     GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3116     GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3117   }
3118 }
3119
3120
3121 /**
3122  * Task used to remove forwarding entries, either
3123  * after timeout, when full, or on shutdown.
3124  *
3125  * @param cls the entry to remove
3126  * @param tc context, reason, etc.
3127  */
3128 static void
3129 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3130 {
3131   struct DHTRouteSource *source_info = cls;
3132   struct DHTQueryRecord *record;
3133   source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3134   record = source_info->record;
3135   GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3136
3137   if (record->head == NULL) /* No more entries in DLL */
3138     {
3139       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3140       GNUNET_free(record);
3141     }
3142   if (source_info->find_peers_responded != NULL)
3143     GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3144   GNUNET_free(source_info);
3145 }
3146
3147 /**
3148  * Remember this routing request so that if a reply is
3149  * received we can either forward it to the correct peer
3150  * or return the result locally.
3151  *
3152  * @param cls DHT service closure
3153  * @param msg_ctx Context of the route request
3154  *
3155  * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3156  */
3157 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
3158 {
3159   struct DHTQueryRecord *record;
3160   struct DHTRouteSource *source_info;
3161   struct DHTRouteSource *pos;
3162   struct GNUNET_TIME_Absolute now;
3163   unsigned int current_size;
3164
3165   current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3166   while (current_size >= MAX_OUTSTANDING_FORWARDS)
3167     {
3168       source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3169       GNUNET_assert(source_info != NULL);
3170       record = source_info->record;
3171       GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3172       if (record->head == NULL) /* No more entries in DLL */
3173         {
3174           GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3175           GNUNET_free(record);
3176         }
3177       GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
3178       if (source_info->find_peers_responded != NULL)
3179         GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3180       GNUNET_free(source_info);
3181       current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3182     }
3183   now = GNUNET_TIME_absolute_get();
3184   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3185   if (record != NULL) /* Already know this request! */
3186     {
3187       pos = record->head;
3188       while (pos != NULL)
3189         {
3190           if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3191             break; /* Already have this peer in reply list! */
3192           pos = pos->next;
3193         }
3194       if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3195         {
3196           GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3197           return GNUNET_NO;
3198         }
3199     }
3200   else
3201     {
3202       record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3203       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3204       memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3205     }
3206
3207   source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3208   source_info->record = record;
3209   source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3210   source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3211   memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3212   GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3213   if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3214     {
3215       source_info->client = msg_ctx->client;
3216       now = GNUNET_TIME_absolute_get_forever();
3217     }
3218   source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3219 #if DEBUG_DHT > 1
3220       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3221                   "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3222                   "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
3223 #endif
3224   return GNUNET_YES;
3225 }
3226
3227
3228 /**
3229  * Main function that handles whether or not to route a message to other
3230  * peers.
3231  *
3232  * @param cls closure for dht service (NULL)
3233  * @param msg the message to be routed
3234  * @param message_context the context containing all pertinent information about the message
3235  *
3236  * @return the number of peers the message was routed to,
3237  *         GNUNET_SYSERR on failure
3238  */
3239 static int route_message(void *cls,
3240                          const struct GNUNET_MessageHeader *msg,
3241                          struct DHT_MessageContext *message_context)
3242 {
3243   int i;
3244   int global_closest;
3245   struct PeerInfo *selected;
3246 #if DEBUG_DHT_ROUTING > 1
3247   struct PeerInfo *nearest;
3248 #endif
3249   unsigned int forward_count;
3250   struct RecentRequest *recent_req;
3251   GNUNET_HashCode unique_hash;
3252   char *stat_forward_count;
3253   char *temp_stat_str;
3254 #if DEBUG_DHT_ROUTING
3255   int ret;
3256 #endif
3257
3258   if (malicious_dropper == GNUNET_YES)
3259     {
3260 #if DEBUG_DHT_ROUTING
3261       if ((debug_routes_extended) && (dhtlog_handle != NULL))
3262         {
3263           dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3264                                        message_context->hop_count, GNUNET_SYSERR,
3265                                        &my_identity, &message_context->key, message_context->peer,
3266                                        NULL);
3267         }
3268 #endif
3269       if (message_context->bloom != NULL)
3270         GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3271       return 0;
3272     }
3273
3274   increment_stats(STAT_ROUTES);
3275   /* Semantics of this call means we find whether we are the closest peer out of those already
3276    * routed to on this messages path.
3277    */
3278   global_closest = am_closest_peer(&message_context->key, NULL);
3279   message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3280   forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3281   GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3282   increment_stats(stat_forward_count);
3283   GNUNET_free(stat_forward_count);
3284   if (message_context->bloom == NULL)
3285     message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3286
3287   if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3288     forward_count = 0;
3289
3290   /**
3291    * NOTICE:  In Kademlia, a find peer request goes no further if the peer doesn't return
3292    * any closer peers (which is being checked for below).  Since we are doing recursive
3293    * routing we have no choice but to stop forwarding in this case.  This means that at
3294    * any given step the request may NOT be forwarded to alpha peers (because routes will
3295    * stop and the parallel route will not be aware of it).  Of course, assuming that we
3296    * have fulfilled the Kademlia requirements for routing table fullness this will never
3297    * ever ever be a problem.
3298    *
3299    * However, is this fair?
3300    *
3301    * Since we use these requests to build our routing tables (and we build them in the
3302    * testing driver) we will ignore this restriction for FIND_PEER messages so that
3303    * routing tables still get constructed.
3304    */
3305   if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3306     forward_count = 0;
3307
3308 #if DEBUG_DHT_ROUTING
3309   if (forward_count == 0)
3310     ret = GNUNET_SYSERR;
3311   else
3312     ret = GNUNET_NO;
3313
3314   if ((debug_routes_extended) && (dhtlog_handle != NULL))
3315     {
3316       dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3317                                    message_context->hop_count, ret,
3318                                    &my_identity, &message_context->key, message_context->peer,
3319                                    NULL);
3320     }
3321 #endif
3322
3323   switch (ntohs(msg->type))
3324     {
3325     case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3326       cache_response (cls, message_context);
3327       if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3328         forward_count = 0;
3329       break;
3330     case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3331       increment_stats(STAT_PUTS);
3332       message_context->closest = global_closest;
3333       handle_dht_put (cls, msg, message_context);
3334       break;
3335     case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3336       increment_stats(STAT_FIND_PEER);
3337       if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3338       {
3339         cache_response (cls, message_context);
3340         if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3341           handle_dht_find_peer (cls, msg, message_context);
3342       }
3343 #if DEBUG_DHT_ROUTING
3344       if (message_context->hop_count == 0) /* Locally initiated request */
3345         {
3346           if ((debug_routes) && (dhtlog_handle != NULL))
3347             {
3348               dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3349               dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3350                                            message_context->hop_count, GNUNET_NO, &my_identity,
3351                                            &message_context->key);
3352             }
3353         }
3354 #endif
3355       break;
3356     default:
3357       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3358                   "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3359     }
3360
3361   GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3362   hash_from_uid (message_context->unique_id, &unique_hash);
3363   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3364   {
3365     recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3366     GNUNET_assert(recent_req != NULL);
3367     if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3368       increment_stats(STAT_DUPLICATE_UID);
3369     else
3370       {
3371         increment_stats(STAT_RECENT_SEEN);
3372         GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3373       }
3374     }
3375   else
3376     {
3377       recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3378       recent_req->uid = message_context->unique_id;
3379       memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3380       recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3381       recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3382       recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3383       GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3384     }
3385
3386   if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3387     {
3388       recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3389       GNUNET_assert(recent_req != NULL);
3390       GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3391       GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3392     }
3393
3394   for (i = 0; i < forward_count; i++)
3395     {
3396       selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3397
3398       if (selected != NULL)
3399         {
3400           if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
3401             GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
3402           else
3403             GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
3404           if (temp_stat_str != NULL)
3405             {
3406               increment_stats(temp_stat_str);
3407               GNUNET_free(temp_stat_str);
3408             }
3409           GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3410 #if DEBUG_DHT_ROUTING > 1
3411           nearest = find_closest_peer(&message_context->key);
3412           nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3413           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3414                       "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3415                       "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));
3416           GNUNET_free(nearest_buf);
3417 #endif
3418 #if DEBUG_DHT_ROUTING
3419           if ((debug_routes_extended) && (dhtlog_handle != NULL))
3420             {
3421               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3422                                            message_context->hop_count, GNUNET_NO,
3423                                            &my_identity, &message_context->key, message_context->peer,
3424                                            &selected->id);
3425             }
3426 #endif
3427           forward_message(cls, msg, selected, message_context);
3428         }
3429     }
3430
3431   if (message_context->bloom != NULL)
3432     {
3433       GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3434       GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3435     }
3436
3437   return forward_count;
3438 }
3439
3440 /**
3441  * Iterator for local get request results,
3442  *
3443  * @param cls closure for iterator, NULL
3444  * @param exp when does this value expire?
3445  * @param key the key this data is stored under
3446  * @param size the size of the data identified by key
3447  * @param data the actual data
3448  * @param type the type of the data
3449  *
3450  * @return GNUNET_OK to continue iteration, anything else
3451  * to stop iteration.
3452  */
3453 static int
3454 republish_content_iterator (void *cls,
3455                             struct GNUNET_TIME_Absolute exp,
3456                             const GNUNET_HashCode * key,
3457                             uint32_t size, const char *data, uint32_t type)
3458 {
3459
3460   struct DHT_MessageContext *new_msg_ctx;
3461   struct GNUNET_DHT_PutMessage *put_msg;
3462 #if DEBUG_DHT
3463   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3464               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3465 #endif
3466   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3467
3468   put_msg =
3469     GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3470   put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3471   put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3472   put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3473   put_msg->type = htons (type);
3474   memcpy (&put_msg[1], data, size);
3475   new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3476   new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3477   new_msg_ctx->msg_options = ntohl (0);
3478   new_msg_ctx->network_size = estimate_diameter();
3479   new_msg_ctx->peer = &my_identity;
3480   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3481   new_msg_ctx->hop_count = 0;
3482   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3483   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3484   increment_stats(STAT_PUT_START);
3485   route_message(cls, &put_msg->header, new_msg_ctx);
3486
3487   GNUNET_free(new_msg_ctx);
3488   GNUNET_free (put_msg);
3489   return GNUNET_OK;
3490 }
3491
3492 /**
3493  * Task used to republish data.
3494  *
3495  * @param cls closure (a struct RepublishContext)
3496  * @param tc runtime context for this task
3497  */
3498 static void
3499 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3500 {
3501   struct RepublishContext *put_context = cls;
3502
3503   unsigned int results;
3504
3505   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3506     {
3507       GNUNET_free(put_context);
3508       return;
3509     }
3510
3511   GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3512   results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3513   if (results == 0) /* Data must have expired */
3514     GNUNET_free(put_context);
3515   else /* Reschedule task for next time period */
3516     GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);
3517
3518 }
3519
3520
3521 /**
3522  * Iterator over hash map entries.
3523  *
3524  * @param cls client to search for in source routes
3525  * @param key current key code (ignored)
3526  * @param value value in the hash map, a DHTQueryRecord
3527  * @return GNUNET_YES if we should continue to
3528  *         iterate,
3529  *         GNUNET_NO if not.
3530  */
3531 static int find_client_records (void *cls,
3532                                 const GNUNET_HashCode * key, void *value)
3533 {
3534   struct ClientList *client = cls;
3535   struct DHTQueryRecord *record = value;
3536   struct DHTRouteSource *pos;
3537   pos = record->head;
3538   while (pos != NULL)
3539     {
3540       if (pos->client == client)
3541         break;
3542       pos = pos->next;
3543     }
3544   if (pos != NULL)
3545     {
3546       GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3547       GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3548       if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3549         GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3550
3551       if (pos->find_peers_responded != NULL)
3552         GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3553       GNUNET_free(pos);
3554     }
3555   if (record->head == NULL) /* No more entries in DLL */
3556     {
3557       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3558       GNUNET_free(record);
3559     }
3560   return GNUNET_YES;
3561 }
3562
3563 /**
3564  * Functions with this signature are called whenever a client
3565  * is disconnected on the network level.
3566  *
3567  * @param cls closure (NULL for dht)
3568  * @param client identification of the client; NULL
3569  *        for the last call when the server is destroyed
3570  */
3571 static void handle_client_disconnect (void *cls,
3572                                       struct GNUNET_SERVER_Client* client)
3573 {
3574   struct ClientList *pos = client_list;
3575   struct ClientList *prev;
3576   struct ClientList *found;
3577   struct PendingMessage *reply;
3578
3579   prev = NULL;
3580   found = NULL;
3581   while (pos != NULL)
3582     {
3583       if (pos->client_handle == client)
3584         {
3585           if (prev != NULL)
3586             prev->next = pos->next;
3587           else
3588             client_list = pos->next;
3589           found = pos;
3590           break;
3591         }
3592       prev = pos;
3593       pos = pos->next;
3594     }
3595
3596   if (found != NULL)
3597     {
3598       while(NULL != (reply = found->pending_head))
3599         {
3600           GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3601           GNUNET_free(reply);
3602         }
3603       GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3604       GNUNET_free(found);
3605     }
3606 }
3607
3608 /**
3609  * Find a client if it exists, add it otherwise.
3610  *
3611  * @param client the server handle to the client
3612  *
3613  * @return the client if found, a new client otherwise
3614  */
3615 static struct ClientList *
3616 find_active_client (struct GNUNET_SERVER_Client *client)
3617 {
3618   struct ClientList *pos = client_list;
3619   struct ClientList *ret;
3620
3621   while (pos != NULL)
3622     {
3623       if (pos->client_handle == client)
3624         return pos;
3625       pos = pos->next;
3626     }
3627
3628   ret = GNUNET_malloc (sizeof (struct ClientList));
3629   ret->client_handle = client;
3630   ret->next = client_list;
3631   client_list = ret;
3632
3633   return ret;
3634 }
3635
3636 /**
3637  * Task to send a malicious put message across the network.
3638  *
3639  * @param cls closure for this task
3640  * @param tc the context under which the task is running
3641  */
3642 static void
3643 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3644 {
3645   static struct GNUNET_DHT_PutMessage put_message;
3646   static struct DHT_MessageContext message_context;
3647   static GNUNET_HashCode key;
3648   uint32_t random_key;
3649
3650   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3651     return;
3652
3653   put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3654   put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3655   put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3656   put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3657   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3658   message_context.client = NULL;
3659   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3660   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3661   memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3662   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3663   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3664   message_context.msg_options = ntohl (0);
3665   message_context.network_size = estimate_diameter();
3666   message_context.peer = &my_identity;
3667   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3668   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3669 #if DEBUG_DHT_ROUTING
3670   if (dhtlog_handle != NULL)
3671     dhtlog_handle->insert_dhtkey(NULL, &key);
3672 #endif
3673   increment_stats(STAT_PUT_START);
3674   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3675   route_message(NULL, &put_message.header, &message_context);
3676   GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3677
3678 }
3679
3680 /**
3681  * Task to send a malicious put message across the network.
3682  *
3683  * @param cls closure for this task
3684  * @param tc the context under which the task is running
3685  */
3686 static void
3687 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3688 {
3689   static struct GNUNET_DHT_GetMessage get_message;
3690   struct DHT_MessageContext message_context;
3691   static GNUNET_HashCode key;
3692   uint32_t random_key;
3693
3694   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3695     return;
3696
3697   get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3698   get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3699   get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3700   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3701   message_context.client = NULL;
3702   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3703   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3704   memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3705   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3706   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3707   message_context.msg_options = ntohl (0);
3708   message_context.network_size = estimate_diameter();
3709   message_context.peer = &my_identity;
3710   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3711   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3712 #if DEBUG_DHT_ROUTING
3713   if (dhtlog_handle != NULL)
3714     dhtlog_handle->insert_dhtkey(NULL, &key);
3715 #endif
3716   increment_stats(STAT_GET_START);
3717   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3718   route_message (NULL, &get_message.header, &message_context);
3719   GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3720 }
3721
3722 /**
3723  * Iterator over hash map entries.
3724  *
3725  * @param cls closure
3726  * @param key current key code
3727  * @param value value in the hash map
3728  * @return GNUNET_YES if we should continue to
3729  *         iterate,
3730  *         GNUNET_NO if not.
3731  */
3732 static int
3733 add_known_to_bloom (void *cls,
3734                     const GNUNET_HashCode * key,
3735                     void *value)
3736 {
3737   struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3738   GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3739   return GNUNET_YES;
3740 }
3741
3742 /**
3743  * Task to send a find peer message for our own peer identifier
3744  * so that we can find the closest peers in the network to ourselves
3745  * and attempt to connect to them.
3746  *
3747  * @param cls closure for this task
3748  * @param tc the context under which the task is running
3749  */
3750 static void
3751 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3752 {
3753   struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3754   struct DHT_MessageContext message_context;
3755   int ret;
3756   struct GNUNET_TIME_Relative next_send_time;
3757   struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3758 #if COUNT_INTERVAL
3759   struct GNUNET_TIME_Relative time_diff;
3760   struct GNUNET_TIME_Absolute end;
3761   double multiplier;
3762   double count_per_interval;
3763 #endif
3764   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3765     return;
3766
3767   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! */
3768     {
3769       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3770       GNUNET_SCHEDULER_add_delayed (sched,
3771                                     GNUNET_TIME_UNIT_MINUTES,
3772                                     &send_find_peer_message, NULL);
3773       newly_found_peers = 0;
3774       return;
3775     }
3776     
3777   increment_stats(STAT_FIND_PEER_START);
3778 #if COUNT_INTERVAL
3779   end = GNUNET_TIME_absolute_get();
3780   time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3781
3782   if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3783     {
3784       multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3785       count_per_interval = find_peer_context.count / multiplier;
3786     }
3787   else
3788     {
3789       multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3790       count_per_interval = find_peer_context.count * multiplier;
3791     }
3792 #endif
3793
3794 #if FIND_PEER_WITH_HELLO
3795   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3796   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3797   memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3798 #else
3799   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3800   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3801 #endif
3802   find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3803   temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3804   GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3805   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3806   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3807   memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3808   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3809   message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3810   message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3811   message_context.network_size = estimate_diameter();
3812   message_context.peer = &my_identity;
3813   message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3814   message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3815
3816   ret = route_message(NULL, &find_peer_msg->header, &message_context);
3817   GNUNET_free(find_peer_msg);
3818   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3819               "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3820               "FIND PEER", ret);
3821   if (newly_found_peers < bucket_size)
3822     {
3823       next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3824                               GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3825                                                        DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3826     }
3827   else
3828     {
3829       next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3830                              GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3831                                                       DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3832     }
3833
3834   GNUNET_assert (next_send_time.value != 0);
3835   find_peer_context.count = 0;
3836   newly_found_peers = 0;
3837   find_peer_context.start = GNUNET_TIME_absolute_get();
3838   if (GNUNET_YES == do_find_peer)
3839   {
3840     GNUNET_SCHEDULER_add_delayed (sched,
3841                                   next_send_time,
3842                                   &send_find_peer_message, NULL);
3843   }
3844 }
3845
3846 /**
3847  * Handler for any generic DHT messages, calls the appropriate handler
3848  * depending on message type, sends confirmation if responses aren't otherwise
3849  * expected.
3850  *
3851  * @param cls closure for the service
3852  * @param client the client we received this message from
3853  * @param message the actual message received
3854  */
3855 static void
3856 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3857                                 const struct GNUNET_MessageHeader *message)
3858 {
3859   const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3860   const struct GNUNET_MessageHeader *enc_msg;
3861   struct DHT_MessageContext message_context;
3862   enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3863 #if DEBUG_DHT
3864   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3865               "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3866               my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3867               GNUNET_ntohll (dht_msg->unique_id));
3868 #endif
3869 #if DEBUG_DHT_ROUTING
3870   if (dhtlog_handle != NULL)
3871     dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3872 #endif
3873   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3874   message_context.client = find_active_client (client);
3875   memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3876   message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3877   message_context.replication = ntohl (dht_msg->desired_replication_level);
3878   message_context.msg_options = ntohl (dht_msg->options);
3879   message_context.network_size = estimate_diameter();
3880   message_context.peer = &my_identity;
3881   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3882   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3883   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3884     increment_stats(STAT_GET_START);
3885   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3886     increment_stats(STAT_PUT_START);
3887   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3888     increment_stats(STAT_FIND_PEER_START);
3889
3890   route_message(cls, enc_msg, &message_context);
3891
3892   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3893
3894 }
3895
3896 /**
3897  * Handler for any locally received DHT control messages,
3898  * sets malicious flags mostly for now.
3899  *
3900  * @param cls closure for the service
3901  * @param client the client we received this message from
3902  * @param message the actual message received
3903  *
3904  */
3905 static void
3906 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3907                             const struct GNUNET_MessageHeader *message)
3908 {
3909   const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3910       (const struct GNUNET_DHT_ControlMessage *) message;
3911 #if DEBUG_DHT
3912   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3913               "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3914               "CONTROL", ntohs(dht_control_msg->command));
3915 #endif
3916
3917   switch (ntohs(dht_control_msg->command))
3918   {
3919   case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3920     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3921     GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3922     break;
3923   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3924     if (ntohs(dht_control_msg->variable) > 0)
3925       malicious_get_frequency = ntohs(dht_control_msg->variable);
3926     if (malicious_get_frequency == 0)
3927       malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3928     if (malicious_getter != GNUNET_YES)
3929       GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3930     malicious_getter = GNUNET_YES;
3931     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3932     break;
3933   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3934     if (ntohs(dht_control_msg->variable) > 0)
3935       malicious_put_frequency = ntohs(dht_control_msg->variable);
3936     if (malicious_put_frequency == 0)
3937       malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3938     if (malicious_putter != GNUNET_YES)
3939       GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3940     malicious_putter = GNUNET_YES;
3941     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3942     break;
3943   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3944 #if DEBUG_DHT_ROUTING
3945     if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3946       dhtlog_handle->set_malicious(&my_identity);
3947 #endif
3948     malicious_dropper = GNUNET_YES;
3949     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3950     break;
3951   default:
3952     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3953   }
3954
3955   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3956 }
3957
3958 /**
3959  * Handler for any generic DHT stop messages, calls the appropriate handler
3960  * depending on message type (if processed locally)
3961  *
3962  * @param cls closure for the service
3963  * @param client the client we received this message from
3964  * @param message the actual message received
3965  *
3966  */
3967 static void
3968 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3969                             const struct GNUNET_MessageHeader *message)
3970 {
3971
3972   const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3973     (const struct GNUNET_DHT_StopMessage *) message;
3974   struct DHTQueryRecord *record;
3975   struct DHTRouteSource *pos;
3976 #if DEBUG_DHT
3977   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3978               "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3979               "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3980 #endif
3981   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3982   if (record != NULL)
3983     {
3984       pos = record->head;
3985
3986       while (pos != NULL)
3987         {
3988           if ((pos->client != NULL) && (pos->client->client_handle == client))
3989             {
3990               GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3991               GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3992             }
3993           pos = pos->next;
3994         }
3995     }
3996
3997   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3998 }
3999
4000
4001 /**
4002  * Core handler for p2p route requests.
4003  */
4004 static int
4005 handle_dht_p2p_route_request (void *cls,
4006                               const struct GNUNET_PeerIdentity *peer,
4007                               const struct GNUNET_MessageHeader *message,
4008                               struct GNUNET_TIME_Relative latency, uint32_t distance)
4009 {
4010 #if DEBUG_DHT
4011   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4012               "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4013 #endif
4014   struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4015   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4016   struct DHT_MessageContext *message_context;
4017
4018   if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
4019   {
4020     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
4021     increment_stats("# route requests dropped due to high load");
4022     decrease_max_send_delay(get_max_send_delay());
4023     return GNUNET_YES;
4024   }
4025
4026   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4027     {
4028 #if DEBUG_PING
4029       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4030 #endif
4031       return GNUNET_YES;
4032     }
4033
4034   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4035     {
4036       GNUNET_break_op(0);
4037       return GNUNET_YES;
4038     }
4039   message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4040   message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4041   GNUNET_assert(message_context->bloom != NULL);
4042   message_context->hop_count = ntohl(incoming->hop_count);
4043   memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
4044   message_context->replication = ntohl(incoming->desired_replication_level);
4045   message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
4046   message_context->msg_options = ntohl(incoming->options);
4047   message_context->network_size = ntohl(incoming->network_size);
4048   message_context->peer = peer;
4049   message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4050   message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4051   route_message(cls, enc_msg, message_context);
4052   GNUNET_free(message_context);
4053   return GNUNET_YES;
4054 }
4055
4056
4057 /**
4058  * Core handler for p2p route results.
4059  */
4060 static int
4061 handle_dht_p2p_route_result (void *cls,
4062                              const struct GNUNET_PeerIdentity *peer,
4063                              const struct GNUNET_MessageHeader *message,
4064                              struct GNUNET_TIME_Relative latency, uint32_t distance)
4065 {
4066 #if DEBUG_DHT
4067   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4068               "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4069 #endif
4070   struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4071   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4072   struct DHT_MessageContext message_context;
4073
4074   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4075     {
4076       GNUNET_break_op(0);
4077       return GNUNET_YES;
4078     }
4079
4080   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4081   // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4082   message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4083   GNUNET_assert(message_context.bloom != NULL);
4084   memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
4085   message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
4086   message_context.msg_options = ntohl(incoming->options);
4087   message_context.hop_count = ntohl(incoming->hop_count);
4088   message_context.peer = peer;
4089   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
4090   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4091   route_result_message(cls, enc_msg, &message_context);
4092   return GNUNET_YES;
4093 }
4094
4095
4096 /**
4097  * Receive the HELLO from transport service,
4098  * free current and replace if necessary.
4099  *
4100  * @param cls NULL
4101  * @param message HELLO message of peer
4102  */
4103 static void
4104 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4105 {
4106 #if DEBUG_DHT
4107   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4108               "Received our `%s' from transport service\n",
4109               "HELLO");
4110 #endif
4111
4112   GNUNET_assert (message != NULL);
4113   GNUNET_free_non_null(my_hello);
4114   my_hello = GNUNET_malloc(ntohs(message->size));
4115   memcpy(my_hello, message, ntohs(message->size));
4116 }
4117
4118
4119 /**
4120  * Task run during shutdown.
4121  *
4122  * @param cls unused
4123  * @param tc unused
4124  */
4125 static void
4126 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4127 {
4128   int bucket_count;
4129   struct PeerInfo *pos;
4130   if (transport_handle != NULL)
4131   {
4132     GNUNET_free_non_null(my_hello);
4133     GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4134     GNUNET_TRANSPORT_disconnect(transport_handle);
4135   }
4136
4137   for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4138     {
4139       while (k_buckets[bucket_count].head != NULL)
4140         {
4141           pos = k_buckets[bucket_count].head;
4142 #if DEBUG_DHT
4143           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4144                       "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4145 #endif
4146           delete_peer(pos, bucket_count);
4147         }
4148     }
4149   if (coreAPI != NULL)
4150     {
4151 #if DEBUG_DHT
4152       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4153                   "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4154 #endif
4155       GNUNET_CORE_disconnect (coreAPI);
4156     }
4157   if (datacache != NULL)
4158     {
4159 #if DEBUG_DHT
4160       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4161                   "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4162 #endif
4163       GNUNET_DATACACHE_destroy (datacache);
4164     }
4165
4166   if (stats != NULL)
4167     {
4168       GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4169     }
4170
4171   if (dhtlog_handle != NULL)
4172     GNUNET_DHTLOG_disconnect(dhtlog_handle);
4173
4174   GNUNET_free_non_null(my_short_id);
4175 }
4176
4177
4178 /**
4179  * To be called on core init/fail.
4180  *
4181  * @param cls service closure
4182  * @param server handle to the server for this service
4183  * @param identity the public identity of this peer
4184  * @param publicKey the public key of this peer
4185  */
4186 void
4187 core_init (void *cls,
4188            struct GNUNET_CORE_Handle *server,
4189            const struct GNUNET_PeerIdentity *identity,
4190            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4191 {
4192
4193   if (server == NULL)
4194     {
4195 #if DEBUG_DHT
4196   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4197               "%s: Connection to core FAILED!\n", "dht",
4198               GNUNET_i2s (identity));
4199 #endif
4200       GNUNET_SCHEDULER_cancel (sched, cleanup_task);
4201       GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
4202       return;
4203     }
4204 #if DEBUG_DHT
4205   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4206               "%s: Core connection initialized, I am peer: %s\n", "dht",
4207               GNUNET_i2s (identity));
4208 #endif
4209
4210   /* Copy our identity so we can use it */
4211   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4212   if (my_short_id != NULL)
4213     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4214   my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4215   /* Set the server to local variable */
4216   coreAPI = server;
4217
4218   if (dhtlog_handle != NULL)
4219     dhtlog_handle->insert_node (NULL, &my_identity);
4220 }
4221
4222
4223 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4224   {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4225   {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4226   {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4227   {NULL, NULL, 0, 0}
4228 };
4229
4230
4231 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4232   {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4233   {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4234   {NULL, 0, 0}
4235 };
4236
4237 /**
4238  * Method called whenever a peer connects.
4239  *
4240  * @param cls closure
4241  * @param peer peer identity this notification is about
4242  * @param latency reported latency of the connection with peer
4243  * @param distance reported distance (DV) to peer
4244  */
4245 void handle_core_connect (void *cls,
4246                           const struct GNUNET_PeerIdentity * peer,
4247                           struct GNUNET_TIME_Relative latency,
4248                           uint32_t distance)
4249 {
4250   struct PeerInfo *ret;
4251
4252 #if DEBUG_DHT
4253   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4254               "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4255 #endif
4256
4257   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4258     {
4259       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));
4260       return;
4261     }
4262
4263   if (datacache != NULL)
4264     GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
4265   ret = try_add_peer(peer,
4266                      find_current_bucket(&peer->hashPubKey),
4267                      latency,
4268                      distance);
4269   if (ret != NULL)
4270     {
4271       newly_found_peers++;
4272       GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4273     }
4274 #if DEBUG_DHT
4275     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4276                 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4277 #endif
4278 }
4279
4280 /**
4281  * Method called whenever a peer disconnects.
4282  *
4283  * @param cls closure
4284  * @param peer peer identity this notification is about
4285  */
4286 void handle_core_disconnect (void *cls,
4287                              const struct
4288                              GNUNET_PeerIdentity * peer)
4289 {
4290   struct PeerInfo *to_remove;
4291   int current_bucket;
4292
4293   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");
4294
4295   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4296     {
4297       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));
4298       return;
4299     }
4300   increment_stats(STAT_DISCONNECTS);
4301   GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4302   to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4303   GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4304   current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4305   delete_peer(to_remove, current_bucket);
4306 }
4307
4308 /**
4309  * Process dht requests.
4310  *
4311  * @param cls closure
4312  * @param scheduler scheduler to use
4313  * @param server the initialized server
4314  * @param c configuration to use
4315  */
4316 static void
4317 run (void *cls,
4318      struct GNUNET_SCHEDULER_Handle *scheduler,
4319      struct GNUNET_SERVER_Handle *server,
4320      const struct GNUNET_CONFIGURATION_Handle *c)
4321 {
4322   struct GNUNET_TIME_Relative next_send_time;
4323   unsigned long long temp_config_num;
4324   char *converge_modifier_buf;
4325   sched = scheduler;
4326   cfg = c;
4327   datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4328   GNUNET_SERVER_add_handlers (server, plugin_handlers);
4329   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4330   coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4331                                  cfg,   /* Main configuration */
4332                                  GNUNET_TIME_UNIT_FOREVER_REL,
4333                                  NULL,  /* Closure passed to DHT functions */
4334                                  &core_init,    /* Call core_init once connected */
4335                                  &handle_core_connect,  /* Handle connects */
4336                                  &handle_core_disconnect,  /* remove peers on disconnects */
4337                                  NULL,  /* Do we care about "status" updates? */
4338                                  NULL,  /* Don't want notified about all incoming messages */
4339                                  GNUNET_NO,     /* For header only inbound notification */
4340                                  NULL,  /* Don't want notified about all outbound messages */
4341                                  GNUNET_NO,     /* For header only outbound notification */
4342                                  core_handlers);        /* Register these handlers */
4343
4344   if (coreAPI == NULL)
4345     return;
4346   transport_handle = GNUNET_TRANSPORT_connect(sched, cfg, 
4347                                               NULL, NULL, NULL, NULL, NULL);
4348   if (transport_handle != NULL)
4349     GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4350   else
4351     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4352
4353   lowest_bucket = MAX_BUCKETS - 1;
4354   forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4355   forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4356   all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4357   recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4358   GNUNET_assert(all_known_peers != NULL);
4359   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4360     {
4361       debug_routes = GNUNET_YES;
4362     }
4363
4364   if (GNUNET_YES ==
4365       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4366                                            "strict_kademlia"))
4367     {
4368       strict_kademlia = GNUNET_YES;
4369     }
4370
4371   if (GNUNET_YES ==
4372       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4373                                            "stop_on_closest"))
4374     {
4375       stop_on_closest = GNUNET_YES;
4376     }
4377
4378   if (GNUNET_YES ==
4379       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4380                                            "stop_found"))
4381     {
4382       stop_on_found = GNUNET_YES;
4383     }
4384
4385   if (GNUNET_YES ==
4386       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4387                                            "malicious_getter"))
4388     {
4389       malicious_getter = GNUNET_YES;
4390       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4391                                             "MALICIOUS_GET_FREQUENCY",
4392                                             &malicious_get_frequency))
4393         malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4394     }
4395
4396   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4397                                         "MAX_HOPS",
4398                                         &max_hops))
4399     {
4400       max_hops = DEFAULT_MAX_HOPS;
4401     }
4402
4403   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4404                                                           "USE_MAX_HOPS"))
4405     {
4406       use_max_hops = GNUNET_YES;
4407     }
4408
4409   if (GNUNET_YES ==
4410       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4411                                            "malicious_putter"))
4412     {
4413       malicious_putter = GNUNET_YES;
4414       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4415                                             "MALICIOUS_PUT_FREQUENCY",
4416                                             &malicious_put_frequency))
4417         malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4418     }
4419
4420   dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
4421   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4422     {
4423       dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4424     }
4425
4426   if (GNUNET_YES ==
4427           GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4428                                                "malicious_dropper"))
4429     {
4430       malicious_dropper = GNUNET_YES;
4431     }
4432
4433   if (GNUNET_YES ==
4434         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4435                                              "republish"))
4436     do_republish = GNUNET_NO;
4437
4438   if (GNUNET_NO ==
4439         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4440                                              "do_find_peer"))
4441     {
4442       do_find_peer = GNUNET_NO;
4443     }
4444   else
4445     do_find_peer = GNUNET_YES;
4446
4447   if (GNUNET_YES ==
4448         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4449                                              "use_real_distance"))
4450     use_real_distance = GNUNET_YES;
4451
4452   if (GNUNET_YES ==
4453       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4454                                            "mysql_logging_extended"))
4455     {
4456       debug_routes = GNUNET_YES;
4457       debug_routes_extended = GNUNET_YES;
4458     }
4459
4460 #if DEBUG_DHT_ROUTING
4461   if (GNUNET_YES == debug_routes)
4462     {
4463       dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4464       if (dhtlog_handle == NULL)
4465         {
4466           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4467                       "Could not connect to mysql logging server, logging will not happen!");
4468         }
4469     }
4470 #endif
4471
4472   converge_option = DHT_CONVERGE_SQUARE;
4473   if (GNUNET_YES ==
4474       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4475                                            "converge_linear"))
4476     {
4477       converge_option = DHT_CONVERGE_LINEAR;
4478     }
4479   else if (GNUNET_YES ==
4480         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4481                                              "converge_exponential"))
4482     {
4483       converge_option = DHT_CONVERGE_EXPONENTIAL;
4484     }
4485   else if (GNUNET_YES ==
4486         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4487                                              "converge_random"))
4488     {
4489       converge_option = DHT_CONVERGE_RANDOM;
4490     }
4491
4492   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4493     {
4494       if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4495         {
4496           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4497           converge_modifier = 0.0;
4498         }
4499       GNUNET_free(converge_modifier_buf);
4500     }
4501
4502   stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4503
4504   if (stats != NULL)
4505     {
4506       GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4507       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4508       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4509       GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4510       GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4511       GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4512       GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4513       GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4514       GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4515       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4516       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4517       GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4518       GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4519       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4520       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4521       GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4522       GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4523       GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4524       GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4525       GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4526     }
4527   /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4528   recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4529   recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4530   if (GNUNET_YES == do_find_peer)
4531   {
4532     next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4533                            GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4534                                                     (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4535     find_peer_context.start = GNUNET_TIME_absolute_get();
4536     GNUNET_SCHEDULER_add_delayed (sched,
4537                                   next_send_time,
4538                                   &send_find_peer_message, &find_peer_context);
4539   }
4540
4541   /* Scheduled the task to clean up when shutdown is called */
4542   cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4543                                                GNUNET_TIME_UNIT_FOREVER_REL,
4544                                                &shutdown_task, NULL);
4545 }
4546
4547 /**
4548  * The main function for the dht service.
4549  *
4550  * @param argc number of arguments from the command line
4551  * @param argv command line arguments
4552  * @return 0 ok, 1 on error
4553  */
4554 int
4555 main (int argc, char *const *argv)
4556 {
4557   return (GNUNET_OK ==
4558           GNUNET_SERVICE_run (argc,
4559                               argv,
4560                               "dht",
4561                               GNUNET_SERVICE_OPTION_NONE,
4562                               &run, NULL)) ? 0 : 1;
4563 }