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