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