client-side path tracking support
[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 
1028 forward_result_message (void *cls,
1029                         const struct GNUNET_MessageHeader *msg,
1030                         struct PeerInfo *peer,
1031                         struct DHT_MessageContext *msg_ctx)
1032 {
1033   struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1034   struct P2PPendingMessage *pending;
1035   size_t msize;
1036   size_t psize;
1037
1038   increment_stats(STAT_RESULT_FORWARDS);
1039   msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1040   GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1041   psize = sizeof(struct P2PPendingMessage) + msize;
1042   pending = GNUNET_malloc(psize);
1043   pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1044   pending->importance = DHT_SEND_PRIORITY;
1045   pending->timeout = GNUNET_TIME_relative_get_forever();
1046   result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1047   result_message->header.size = htons(msize);
1048   result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1049   result_message->put_path_length = htons(0); /* FIXME: implement */
1050   result_message->get_path_length = htons(0); /* FIXME: implement */
1051   result_message->options = htonl(msg_ctx->msg_options);
1052   result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1053   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1054   result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1055   memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1056   memcpy(&result_message[1], msg, ntohs(msg->size));
1057 #if DEBUG_DHT > 1
1058   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));
1059 #endif
1060   GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1061   if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1062     peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1063 }
1064 /**
1065  * Called when core is ready to send a message we asked for
1066  * out to the destination.
1067  *
1068  * @param cls closure (NULL)
1069  * @param size number of bytes available in buf
1070  * @param buf where the callee should write the message
1071  * @return number of bytes written to buf
1072  */
1073 size_t core_transmit_notify (void *cls,
1074                              size_t size, void *buf)
1075 {
1076   struct PeerInfo *peer = cls;
1077   char *cbuf = buf;
1078   struct P2PPendingMessage *pending;
1079
1080   size_t off;
1081   size_t msize;
1082
1083   if (buf == NULL)
1084     {
1085       /* client disconnected */
1086 #if DEBUG_DHT
1087       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1088 #endif
1089       return 0;
1090     }
1091
1092   if (peer->head == NULL)
1093     return 0;
1094
1095   peer->th = NULL;
1096   off = 0;
1097   pending = peer->head;
1098   reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1099   msize = ntohs(pending->msg->size);
1100   if (msize <= size)
1101     {
1102       off = msize;
1103       memcpy (cbuf, pending->msg, msize);
1104       GNUNET_CONTAINER_DLL_remove (peer->head,
1105                                    peer->tail,
1106                                    pending);
1107 #if DEBUG_DHT > 1
1108       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));
1109 #endif
1110       GNUNET_free (pending);
1111     }
1112 #if SMART
1113   while (NULL != pending &&
1114           (size - off >= (msize = ntohs (pending->msg->size))))
1115     {
1116 #if DEBUG_DHT_ROUTING
1117       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);
1118 #endif
1119       memcpy (&cbuf[off], pending->msg, msize);
1120       off += msize;
1121       GNUNET_CONTAINER_DLL_remove (peer->head,
1122                                    peer->tail,
1123                                    pending);
1124       GNUNET_free (pending);
1125       pending = peer->head;
1126     }
1127 #endif
1128   if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1129     peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1130 #if DEBUG_DHT > 1
1131   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);
1132 #endif
1133   return off;
1134 }
1135
1136
1137 /**
1138  * Compute the distance between have and target as a 32-bit value.
1139  * Differences in the lower bits must count stronger than differences
1140  * in the higher bits.
1141  *
1142  * @return 0 if have==target, otherwise a number
1143  *           that is larger as the distance between
1144  *           the two hash codes increases
1145  */
1146 static unsigned int
1147 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1148 {
1149   unsigned int bucket;
1150   unsigned int msb;
1151   unsigned int lsb;
1152   unsigned int i;
1153
1154   /* We have to represent the distance between two 2^9 (=512)-bit
1155      numbers as a 2^5 (=32)-bit number with "0" being used for the
1156      two numbers being identical; furthermore, we need to
1157      guarantee that a difference in the number of matching
1158      bits is always represented in the result.
1159
1160      We use 2^32/2^9 numerical values to distinguish between
1161      hash codes that have the same LSB bit distance and
1162      use the highest 2^9 bits of the result to signify the
1163      number of (mis)matching LSB bits; if we have 0 matching
1164      and hence 512 mismatching LSB bits we return -1 (since
1165      512 itself cannot be represented with 9 bits) */
1166
1167   /* first, calculate the most significant 9 bits of our
1168      result, aka the number of LSBs */
1169   bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1170   /* bucket is now a value between 0 and 512 */
1171   if (bucket == 512)
1172     return 0;                   /* perfect match */
1173   if (bucket == 0)
1174     return (unsigned int) -1;   /* LSB differs; use max (if we did the bit-shifting
1175                                    below, we'd end up with max+1 (overflow)) */
1176
1177   /* calculate the most significant bits of the final result */
1178   msb = (512 - bucket) << (32 - 9);
1179   /* calculate the 32-9 least significant bits of the final result by
1180      looking at the differences in the 32-9 bits following the
1181      mismatching bit at 'bucket' */
1182   lsb = 0;
1183   for (i = bucket + 1;
1184        (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1185     {
1186       if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1187         lsb |= (1 << (bucket + 32 - 9 - i));    /* first bit set will be 10,
1188                                                    last bit set will be 31 -- if
1189                                                    i does not reach 512 first... */
1190     }
1191   return msb | lsb;
1192 }
1193
1194 /**
1195  * Return a number that is larger the closer the
1196  * "have" GNUNET_hash code is to the "target".
1197  *
1198  * @return inverse distance metric, non-zero.
1199  *         Must fudge the value if NO bits match.
1200  */
1201 static unsigned int
1202 inverse_distance (const GNUNET_HashCode * target,
1203                   const GNUNET_HashCode * have)
1204 {
1205   if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1206     return 1; /* Never return 0! */
1207   return ((unsigned int) -1) - distance (target, have);
1208 }
1209
1210 /**
1211  * Find the optimal bucket for this key, regardless
1212  * of the current number of buckets in use.
1213  *
1214  * @param hc the hashcode to compare our identity to
1215  *
1216  * @return the proper bucket index, or GNUNET_SYSERR
1217  *         on error (same hashcode)
1218  */
1219 static int find_bucket(const GNUNET_HashCode *hc)
1220 {
1221   unsigned int bits;
1222
1223   bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1224   if (bits == MAX_BUCKETS)
1225     return GNUNET_SYSERR;
1226   return MAX_BUCKETS - bits - 1;
1227 }
1228
1229 /**
1230  * Find which k-bucket this peer should go into,
1231  * taking into account the size of the k-bucket
1232  * array.  This means that if more bits match than
1233  * there are currently buckets, lowest_bucket will
1234  * be returned.
1235  *
1236  * @param hc GNUNET_HashCode we are finding the bucket for.
1237  *
1238  * @return the proper bucket index for this key,
1239  *         or GNUNET_SYSERR on error (same hashcode)
1240  */
1241 static int find_current_bucket(const GNUNET_HashCode *hc)
1242 {
1243   int actual_bucket;
1244   actual_bucket = find_bucket(hc);
1245
1246   if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1247     return lowest_bucket;
1248   else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1249     return lowest_bucket;
1250   else
1251     return actual_bucket;
1252 }
1253
1254 #if EXTRA_CHECKS
1255 /**
1256  * Find a routing table entry from a peer identity
1257  *
1258  * @param peer the peer to look up
1259  *
1260  * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1261  */
1262 static int
1263 find_bucket_by_peer(const struct PeerInfo *peer)
1264 {
1265   int bucket;
1266   struct PeerInfo *pos;
1267
1268   for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1269     {
1270       pos = k_buckets[bucket].head;
1271       while (pos != NULL)
1272         {
1273           if (peer == pos)
1274             return bucket;
1275           pos = pos->next;
1276         }
1277     }
1278
1279   return GNUNET_SYSERR; /* No such peer. */
1280 }
1281 #endif
1282
1283 #if PRINT_TABLES
1284 /**
1285  * Print the complete routing table for this peer.
1286  */
1287 static void
1288 print_routing_table ()
1289 {
1290   int bucket;
1291   struct PeerInfo *pos;
1292   char char_buf[30000];
1293   int char_pos;
1294   memset(char_buf, 0, sizeof(char_buf));
1295   char_pos = 0;
1296   char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1297   //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1298   for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1299     {
1300       pos = k_buckets[bucket].head;
1301       char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1302       //fprintf(stderr, "Bucket %d:\n", bucket);
1303       while (pos != NULL)
1304         {
1305           //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));
1306           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));
1307           pos = pos->next;
1308         }
1309     }
1310   fprintf(stderr, "%s", char_buf);
1311   fflush(stderr);
1312 }
1313 #endif
1314
1315 /**
1316  * Find a routing table entry from a peer identity
1317  *
1318  * @param peer the peer identity to look up
1319  *
1320  * @return the routing table entry, or NULL if not found
1321  */
1322 static struct PeerInfo *
1323 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1324 {
1325   int bucket;
1326   struct PeerInfo *pos;
1327   bucket = find_current_bucket(&peer->hashPubKey);
1328
1329   if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1330     return NULL;
1331
1332   pos = k_buckets[bucket].head;
1333   while (pos != NULL)
1334     {
1335       if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1336         return pos;
1337       pos = pos->next;
1338     }
1339   return NULL; /* No such peer. */
1340 }
1341
1342 /* Forward declaration */
1343 static void
1344 update_core_preference (void *cls,
1345                         const struct GNUNET_SCHEDULER_TaskContext *tc);
1346 /**
1347  * Function called with statistics about the given peer.
1348  *
1349  * @param cls closure
1350  * @param peer identifies the peer
1351  * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1352  * @param bpm_out set to the current bandwidth limit (sending) for this peer
1353  * @param amount set to the amount that was actually reserved or unreserved;
1354  *               either the full requested amount or zero (no partial reservations)
1355  * @param preference current traffic preference for the given peer
1356  */
1357 static void
1358 update_core_preference_finish (void *cls,
1359                                const struct GNUNET_PeerIdentity * peer,
1360                                struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1361                                struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1362                                int amount, uint64_t preference)
1363 {
1364   struct PeerInfo *peer_info = cls;
1365   peer_info->info_ctx = NULL;
1366   GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1367 }
1368
1369 static void
1370 update_core_preference (void *cls,
1371                         const struct GNUNET_SCHEDULER_TaskContext *tc)
1372 {
1373   struct PeerInfo *peer = cls;
1374   uint64_t preference;
1375   unsigned int matching;
1376   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1377     {
1378       return;
1379     }
1380   matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1381   if (matching >= 64)
1382     {
1383       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1384       matching = 63;
1385     }
1386   preference = 1LL << matching;
1387   peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1388                                                        &peer->id,
1389                                                        GNUNET_TIME_relative_get_forever(),
1390                                                        GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1391                                                        0,
1392                                                        preference,
1393                                                        &update_core_preference_finish,
1394                                                        peer);
1395 }
1396
1397 /**
1398  * Really add a peer to a bucket (only do assertions
1399  * on size, etc.)
1400  *
1401  * @param peer GNUNET_PeerIdentity of the peer to add
1402  * @param bucket the already figured out bucket to add
1403  *        the peer to
1404  * @param latency the core reported latency of this peer
1405  * @param distance the transport level distance to this peer
1406  *
1407  * @return the newly added PeerInfo
1408  */
1409 static struct PeerInfo *
1410 add_peer(const struct GNUNET_PeerIdentity *peer,
1411          unsigned int bucket,
1412          struct GNUNET_TIME_Relative latency,
1413          unsigned int distance)
1414 {
1415   struct PeerInfo *new_peer;
1416   GNUNET_assert(bucket < MAX_BUCKETS);
1417   GNUNET_assert(peer != NULL);
1418   new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1419   new_peer->latency = latency;
1420   new_peer->distance = distance;
1421
1422   memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1423
1424   GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1425                                     k_buckets[bucket].tail,
1426                                     k_buckets[bucket].tail,
1427                                     new_peer);
1428   k_buckets[bucket].peers_size++;
1429
1430   if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1431     {
1432 #if DO_UPDATE_PREFERENCE
1433       new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1434 #endif
1435     }
1436
1437   return new_peer;
1438 }
1439
1440 /**
1441  * Given a peer and its corresponding bucket,
1442  * remove it from that bucket.  Does not free
1443  * the PeerInfo struct, nor cancel messages
1444  * or free messages waiting to be sent to this
1445  * peer!
1446  *
1447  * @param peer the peer to remove
1448  * @param bucket the bucket the peer belongs to
1449  */
1450 static void remove_peer (struct PeerInfo *peer,
1451                          unsigned int bucket)
1452 {
1453   GNUNET_assert(k_buckets[bucket].peers_size > 0);
1454   GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1455                               k_buckets[bucket].tail,
1456                               peer);
1457   k_buckets[bucket].peers_size--;
1458 #if CHANGE_LOWEST
1459   if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1460     lowest_bucket++;
1461 #endif
1462 }
1463
1464 /**
1465  * Removes peer from a bucket, then frees associated
1466  * resources and frees peer.
1467  *
1468  * @param peer peer to be removed and freed
1469  * @param bucket which bucket this peer belongs to
1470  */
1471 static void delete_peer (struct PeerInfo *peer,
1472                          unsigned int bucket)
1473 {
1474   struct P2PPendingMessage *pos;
1475   struct P2PPendingMessage *next;
1476 #if EXTRA_CHECKS
1477   struct PeerInfo *peer_pos;
1478
1479   peer_pos = k_buckets[bucket].head;
1480   while ((peer_pos != NULL) && (peer_pos != peer))
1481     peer_pos = peer_pos->next;
1482   if (peer_pos == NULL)
1483     {
1484       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1485       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));
1486     }
1487   GNUNET_assert(peer_pos != NULL);
1488 #endif
1489   remove_peer(peer, bucket); /* First remove the peer from its bucket */
1490
1491   if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1492     GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1493   if (peer->th != NULL)
1494     GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1495
1496   pos = peer->head;
1497   while (pos != NULL) /* Remove any pending messages for this peer */
1498     {
1499       next = pos->next;
1500       GNUNET_free(pos);
1501       pos = next;
1502     }
1503
1504   GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1505   GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1506   GNUNET_free(peer);
1507 }
1508
1509
1510 /**
1511  * Iterator over hash map entries.
1512  *
1513  * @param cls closure
1514  * @param key current key code
1515  * @param value PeerInfo of the peer to move to new lowest bucket
1516  * @return GNUNET_YES if we should continue to
1517  *         iterate,
1518  *         GNUNET_NO if not.
1519  */
1520 static int move_lowest_bucket (void *cls,
1521                                const GNUNET_HashCode * key,
1522                                void *value)
1523 {
1524   struct PeerInfo *peer = value;
1525   int new_bucket;
1526
1527   GNUNET_assert(lowest_bucket > 0);
1528   new_bucket = lowest_bucket - 1;
1529   remove_peer(peer, lowest_bucket);
1530   GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1531                                     k_buckets[new_bucket].tail,
1532                                     k_buckets[new_bucket].tail,
1533                                     peer);
1534   k_buckets[new_bucket].peers_size++;
1535   return GNUNET_YES;
1536 }
1537
1538
1539 /**
1540  * The current lowest bucket is full, so change the lowest
1541  * bucket to the next lower down, and move any appropriate
1542  * entries in the current lowest bucket to the new bucket.
1543  */
1544 static void enable_next_bucket()
1545 {
1546   struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1547   struct PeerInfo *pos;
1548   GNUNET_assert(lowest_bucket > 0);
1549   to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1550   pos = k_buckets[lowest_bucket].head;
1551
1552 #if PRINT_TABLES
1553   fprintf(stderr, "Printing RT before new bucket\n");
1554   print_routing_table();
1555 #endif
1556   /* Populate the array of peers which should be in the next lowest bucket */
1557   while (pos != NULL)
1558     {
1559       if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1560         GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1561       pos = pos->next;
1562     }
1563
1564   /* Remove peers from lowest bucket, insert into next lowest bucket */
1565   GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1566   GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1567   lowest_bucket = lowest_bucket - 1;
1568 #if PRINT_TABLES
1569   fprintf(stderr, "Printing RT after new bucket\n");
1570   print_routing_table();
1571 #endif
1572 }
1573
1574 /**
1575  * Find the closest peer in our routing table to the
1576  * given hashcode.
1577  *
1578  * @return The closest peer in our routing table to the
1579  *         key, or NULL on error.
1580  */
1581 static struct PeerInfo *
1582 find_closest_peer (const GNUNET_HashCode *hc)
1583 {
1584   struct PeerInfo *pos;
1585   struct PeerInfo *current_closest;
1586   unsigned int lowest_distance;
1587   unsigned int temp_distance;
1588   int bucket;
1589   int count;
1590
1591   lowest_distance = -1;
1592
1593   if (k_buckets[lowest_bucket].peers_size == 0)
1594     return NULL;
1595
1596   current_closest = NULL;
1597   for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1598     {
1599       pos = k_buckets[bucket].head;
1600       count = 0;
1601       while ((pos != NULL) && (count < bucket_size))
1602         {
1603           temp_distance = distance(&pos->id.hashPubKey, hc);
1604           if (temp_distance <= lowest_distance)
1605             {
1606               lowest_distance = temp_distance;
1607               current_closest = pos;
1608             }
1609           pos = pos->next;
1610           count++;
1611         }
1612     }
1613   GNUNET_assert(current_closest != NULL);
1614   return current_closest;
1615 }
1616
1617
1618 /**
1619  * Function called to send a request out to another peer.
1620  * Called both for locally initiated requests and those
1621  * received from other peers.
1622  *
1623  * @param cls DHT service closure argument (unused)
1624  * @param msg the encapsulated message
1625  * @param peer the peer to forward the message to
1626  * @param msg_ctx the context of the message (hop count, bloom, etc.)
1627  */
1628 static void forward_message (void *cls,
1629                              const struct GNUNET_MessageHeader *msg,
1630                              struct PeerInfo *peer,
1631                              struct DHT_MessageContext *msg_ctx)
1632 {
1633   struct GNUNET_DHT_P2PRouteMessage *route_message;
1634   struct P2PPendingMessage *pending;
1635   size_t msize;
1636   size_t psize;
1637
1638   increment_stats(STAT_ROUTE_FORWARDS);
1639
1640   if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1641     increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1642
1643   msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1644   GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1645   psize = sizeof(struct P2PPendingMessage) + msize;
1646   pending = GNUNET_malloc(psize);
1647   pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1648   pending->importance = msg_ctx->importance;
1649   pending->timeout = msg_ctx->timeout;
1650   route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1651   route_message->header.size = htons(msize);
1652   route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1653   route_message->options = htonl(msg_ctx->msg_options);
1654   route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1655   route_message->network_size = htonl(msg_ctx->network_size);
1656   route_message->desired_replication_level = htonl(msg_ctx->replication);
1657   route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1658   if (msg_ctx->bloom != NULL)
1659     GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1660   memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1661   memcpy(&route_message[1], msg, ntohs(msg->size));
1662 #if DEBUG_DHT > 1
1663   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));
1664 #endif
1665   GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1666   if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1667     peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1668 }
1669
1670 #if DO_PING
1671 /**
1672  * Task used to send ping messages to peers so that
1673  * they don't get disconnected.
1674  *
1675  * @param cls the peer to send a ping message to
1676  * @param tc context, reason, etc.
1677  */
1678 static void
1679 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1680 {
1681   struct PeerInfo *peer = cls;
1682   struct GNUNET_MessageHeader ping_message;
1683   struct DHT_MessageContext message_context;
1684
1685   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1686     return;
1687
1688   ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1689   ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1690
1691   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1692 #if DEBUG_PING
1693   GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1694 #endif
1695   forward_message(NULL, &ping_message, peer, &message_context);
1696   peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1697 }
1698
1699 /**
1700  * Schedule PING messages for the top X peers in each
1701  * bucket of the routing table (so core won't disconnect them!)
1702  */
1703 void schedule_ping_messages()
1704 {
1705   unsigned int bucket;
1706   unsigned int count;
1707   struct PeerInfo *pos;
1708   for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1709     {
1710       pos = k_buckets[bucket].head;
1711       count = 0;
1712       while (pos != NULL)
1713         {
1714           if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1715             GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1716           else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1717             {
1718               GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1719               pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1720             }
1721           pos = pos->next;
1722           count++;
1723         }
1724     }
1725 }
1726 #endif
1727
1728 /**
1729  * Attempt to add a peer to our k-buckets.
1730  *
1731  * @param peer the peer identity of the peer being added
1732  * @param bucket the bucket that we want this peer to go in
1733  * @param latency transport latency of this peer
1734  * @param distance transport distance to this peer
1735  *
1736  * @return NULL if the peer was not added,
1737  *         pointer to PeerInfo for new peer otherwise
1738  */
1739 static struct PeerInfo *
1740 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1741              unsigned int bucket,
1742              struct GNUNET_TIME_Relative latency,
1743              unsigned int distance)
1744 {
1745   int peer_bucket;
1746   struct PeerInfo *new_peer;
1747
1748   if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1749     return NULL;
1750
1751   peer_bucket = find_current_bucket(&peer->hashPubKey);
1752
1753   GNUNET_assert(peer_bucket >= lowest_bucket);
1754   new_peer = add_peer(peer, peer_bucket, latency, distance);
1755
1756   if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1757     enable_next_bucket();
1758 #if DO_PING
1759   schedule_ping_messages();
1760 #endif
1761   return new_peer;
1762 }
1763
1764
1765 /**
1766  * Task run to check for messages that need to be sent to a client.
1767  *
1768  * @param client a ClientList, containing the client and any messages to be sent to it
1769  */
1770 static void
1771 process_pending_messages (struct ClientList *client)
1772
1773   if (client->pending_head == NULL) 
1774     return;    
1775   if (client->transmit_handle != NULL) 
1776     return;
1777
1778   client->transmit_handle =
1779     GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1780                                          ntohs (client->pending_head->msg->
1781                                                 size),
1782                                          GNUNET_TIME_UNIT_FOREVER_REL,
1783                                          &send_generic_reply, client);
1784 }
1785
1786 /**
1787  * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1788  * request.  A ClientList is passed as closure, take the head of the list
1789  * and copy it into buf, which has the result of sending the message to the
1790  * client.
1791  *
1792  * @param cls closure to this call
1793  * @param size maximum number of bytes available to send
1794  * @param buf where to copy the actual message to
1795  *
1796  * @return the number of bytes actually copied, 0 indicates failure
1797  */
1798 static size_t
1799 send_generic_reply (void *cls, size_t size, void *buf)
1800 {
1801   struct ClientList *client = cls;
1802   char *cbuf = buf;
1803   struct PendingMessage *reply;
1804   size_t off;
1805   size_t msize;
1806
1807   client->transmit_handle = NULL;
1808   if (buf == NULL)             
1809     {
1810       /* client disconnected */
1811       return 0;
1812     }
1813   off = 0;
1814   while ( (NULL != (reply = client->pending_head)) &&
1815           (size >= off + (msize = ntohs (reply->msg->size))))
1816     {
1817       GNUNET_CONTAINER_DLL_remove (client->pending_head,
1818                                    client->pending_tail,
1819                                    reply);
1820       memcpy (&cbuf[off], reply->msg, msize);
1821       GNUNET_free (reply);
1822       off += msize;
1823     }
1824   process_pending_messages (client);
1825 #if DEBUG_DHT
1826   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1827               "Transmitted %u bytes of replies to client\n",
1828               (unsigned int) off);
1829 #endif
1830   return off;
1831 }
1832
1833
1834 /**
1835  * Add a PendingMessage to the clients list of messages to be sent
1836  *
1837  * @param client the active client to send the message to
1838  * @param pending_message the actual message to send
1839  */
1840 static void
1841 add_pending_message (struct ClientList *client,
1842                      struct PendingMessage *pending_message)
1843 {
1844   GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1845                                      client->pending_tail,
1846                                      client->pending_tail,
1847                                      pending_message);
1848   process_pending_messages (client);
1849 }
1850
1851
1852
1853
1854 /**
1855  * Called when a reply needs to be sent to a client, as
1856  * a result it found to a GET or FIND PEER request.
1857  *
1858  * @param client the client to send the reply to
1859  * @param message the encapsulated message to send
1860  * @param uid the unique identifier of this request
1861  */
1862 static void
1863 send_reply_to_client (struct ClientList *client,
1864                       const struct GNUNET_MessageHeader *message,
1865                       unsigned long long uid,
1866                       const GNUNET_HashCode *key)
1867 {
1868   struct GNUNET_DHT_RouteResultMessage *reply;
1869   struct PendingMessage *pending_message;
1870   uint16_t msize;
1871   size_t tsize;
1872 #if DEBUG_DHT
1873   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1874               "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1875 #endif
1876   msize = ntohs (message->size);
1877   tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1878   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1879     {
1880       GNUNET_break_op (0);
1881       return;
1882     }
1883   pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1884   pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1885   reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1886   reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1887   reply->header.size = htons (tsize);
1888   reply->put_path_length = htons(0); /* FIXME: implement */
1889   reply->get_path_length = htons(0); /* FIXME: implement */
1890   reply->unique_id = GNUNET_htonll (uid);
1891   reply->key = *key;
1892   memcpy (&reply[1], message, msize);
1893   add_pending_message (client, pending_message);
1894 }
1895
1896 /**
1897  * Consider whether or not we would like to have this peer added to
1898  * our routing table.  Check whether bucket for this peer is full,
1899  * if so return negative; if not return positive.  Since peers are
1900  * only added on CORE level connect, this doesn't actually add the
1901  * peer to the routing table.
1902  *
1903  * @param peer the peer we are considering adding
1904  *
1905  * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1906  *         already full)
1907  */
1908 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1909 {
1910   int bucket;
1911
1912   if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1913     return GNUNET_NO; /* We already know this peer (are connected even!) */
1914   bucket = find_current_bucket(&peer->hashPubKey);
1915
1916   if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1917     return GNUNET_YES;
1918
1919   return GNUNET_NO;
1920 }
1921
1922 /**
1923  * Main function that handles whether or not to route a result
1924  * message to other peers, or to send to our local client.
1925  *
1926  * @param cls closure (unused, always should be NULL)
1927  * @param msg the result message to be routed
1928  * @param message_context context of the message we are routing
1929  *
1930  * @return the number of peers the message was routed to,
1931  *         GNUNET_SYSERR on failure
1932  */
1933 static int route_result_message(void *cls,
1934                                 struct GNUNET_MessageHeader *msg,
1935                                 struct DHT_MessageContext *message_context)
1936 {
1937   struct GNUNET_PeerIdentity new_peer;
1938   struct DHTQueryRecord *record;
1939   struct DHTRouteSource *pos;
1940   struct PeerInfo *peer_info;
1941   const struct GNUNET_MessageHeader *hello_msg;
1942
1943   increment_stats(STAT_RESULTS);
1944   /**
1945    * If a find peer result message is received and contains a valid
1946    * HELLO for another peer, offer it to the transport service.
1947    */
1948   if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1949     {
1950       if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1951         GNUNET_break_op(0);
1952
1953       hello_msg = &msg[1];
1954       if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1955       {
1956         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1957         GNUNET_break_op(0);
1958         return GNUNET_NO;
1959       }
1960       else /* We have a valid hello, and peer id stored in new_peer */
1961       {
1962         find_peer_context.count++;
1963         increment_stats(STAT_FIND_PEER_REPLY);
1964         if (GNUNET_YES == consider_peer(&new_peer))
1965         {
1966           increment_stats(STAT_HELLOS_PROVIDED);
1967           GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1968           GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1969         }
1970       }
1971     }
1972
1973   if (malicious_dropper == GNUNET_YES)
1974     record = NULL;
1975   else
1976     record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1977
1978   if (record == NULL) /* No record of this message! */
1979     {
1980 #if DEBUG_DHT
1981     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1982                 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1983                 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
1984 #endif
1985 #if DEBUG_DHT_ROUTING
1986       if ((debug_routes_extended) && (dhtlog_handle != NULL))
1987         {
1988           dhtlog_handle->insert_route (NULL,
1989                                        message_context->unique_id,
1990                                        DHTLOG_RESULT,
1991                                        message_context->hop_count,
1992                                        GNUNET_SYSERR,
1993                                        &my_identity,
1994                                        &message_context->key,
1995                                        message_context->peer, NULL);
1996         }
1997 #endif
1998       if (message_context->bloom != NULL)
1999         {
2000           GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2001           message_context->bloom = NULL;
2002         }
2003       return 0;
2004     }
2005
2006   pos = record->head;
2007   while (pos != NULL)
2008     {
2009 #if STRICT_FORWARDING
2010       if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2011         {
2012           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2013           {
2014             increment_stats("# find peer responses NOT forwarded (bloom match)");
2015             pos = pos->next;
2016             continue;
2017           }
2018           else
2019             GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2020         }
2021 #endif
2022
2023       if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2024         {
2025 #if DEBUG_DHT
2026           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2027                       "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2028                       "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2029 #endif
2030 #if DEBUG_DHT_ROUTING
2031           if ((debug_routes_extended) && (dhtlog_handle != NULL))
2032             {
2033               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2034                                            message_context->hop_count,
2035                                            GNUNET_YES, &my_identity, &message_context->key,
2036                                            message_context->peer, NULL);
2037             }
2038 #endif
2039           increment_stats(STAT_RESULTS_TO_CLIENT);
2040           if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2041             increment_stats(STAT_GET_REPLY);
2042
2043           send_reply_to_client(pos->client, msg, 
2044                                message_context->unique_id,
2045                                &message_context->key);
2046         }
2047       else /* Send to peer */
2048         {
2049           peer_info = find_peer_by_id(&pos->source);
2050           if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2051             {
2052               pos = pos->next;
2053               continue;
2054             }
2055
2056           if (message_context->bloom == NULL)
2057             message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2058           GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2059           if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2060             {
2061 #if DEBUG_DHT
2062               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2063                           "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2064                           "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2065 #endif
2066 #if DEBUG_DHT_ROUTING
2067               if ((debug_routes_extended) && (dhtlog_handle != NULL))
2068                 {
2069                   dhtlog_handle->insert_route (NULL, message_context->unique_id,
2070                                                DHTLOG_RESULT,
2071                                                message_context->hop_count,
2072                                                GNUNET_NO, &my_identity, &message_context->key,
2073                                                message_context->peer, &pos->source);
2074                 }
2075 #endif
2076               forward_result_message(cls, msg, peer_info, message_context);
2077             }
2078           else
2079             {
2080 #if DEBUG_DHT
2081               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2082                           "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2083                           "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2084 #endif
2085             }
2086         }
2087       pos = pos->next;
2088     }
2089   if (message_context->bloom != NULL)
2090     GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2091   return 0;
2092 }
2093
2094 /**
2095  * Iterator for local get request results,
2096  *
2097  * @param cls closure for iterator, a DatacacheGetContext
2098  * @param exp when does this value expire?
2099  * @param key the key this data is stored under
2100  * @param size the size of the data identified by key
2101  * @param data the actual data
2102  * @param type the type of the data
2103  *
2104  * @return GNUNET_OK to continue iteration, anything else
2105  * to stop iteration.
2106  */
2107 static int
2108 datacache_get_iterator (void *cls,
2109                         struct GNUNET_TIME_Absolute exp,
2110                         const GNUNET_HashCode * key,
2111                         uint32_t size, const char *data, uint32_t type)
2112 {
2113   struct DHT_MessageContext *msg_ctx = cls;
2114   struct DHT_MessageContext *new_msg_ctx;
2115   struct GNUNET_DHT_GetResultMessage *get_result;
2116 #if DEBUG_DHT
2117   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2118               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2119 #endif
2120   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2121   memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2122   get_result =
2123     GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2124   get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2125   get_result->header.size =
2126     htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2127   get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2128   get_result->type = htons (type);
2129   memcpy (&get_result[1], data, size);
2130   new_msg_ctx->peer = &my_identity;
2131   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2132   new_msg_ctx->hop_count = 0;
2133   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2134   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2135   increment_stats(STAT_GET_RESPONSE_START);
2136   route_result_message(cls, &get_result->header, new_msg_ctx);
2137   GNUNET_free(new_msg_ctx);
2138   //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2139   //                      datacache_get_ctx->unique_id);
2140   GNUNET_free (get_result);
2141   return GNUNET_OK;
2142 }
2143
2144
2145 /**
2146  * Server handler for all dht get requests, look for data,
2147  * if found, send response either to clients or other peers.
2148  *
2149  * @param cls closure for service
2150  * @param msg the actual get message
2151  * @param message_context struct containing pertinent information about the get request
2152  *
2153  * @return number of items found for GET request
2154  */
2155 static unsigned int
2156 handle_dht_get (void *cls, 
2157                 const struct GNUNET_MessageHeader *msg,
2158                 struct DHT_MessageContext *message_context)
2159 {
2160   const struct GNUNET_DHT_GetMessage *get_msg;
2161   uint16_t get_type;
2162   uint16_t bf_size;
2163   uint16_t msize;
2164   uint16_t xquery_size;
2165   unsigned int results;
2166   struct GNUNET_CONTAINER_BloomFilter *bf;
2167   const void *xquery;
2168   const char *end;
2169
2170   msize = ntohs (msg->size);
2171   if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2172     {
2173       GNUNET_break (0);
2174       return 0;
2175     }
2176   get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2177   bf_size = ntohs (get_msg->bf_size);
2178   xquery_size = ntohs (get_msg->xquery_size);
2179   if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + xquery_size)
2180     {
2181       GNUNET_break (0);
2182       return 0;
2183     }
2184   end = (const char*) &get_msg[1];
2185   if (xquery_size == 0)
2186     {
2187       xquery = NULL;
2188     }
2189   else
2190     {
2191       xquery = (const void*) end;
2192       end += xquery_size;
2193     }
2194   if (bf_size == 0)
2195     {
2196       bf = NULL;
2197     }
2198   else
2199     {
2200       bf = GNUNET_CONTAINER_bloomfilter_init (end,
2201                                               bf_size,
2202                                               GNUNET_DHT_GET_BLOOMFILTER_K);
2203     }
2204
2205   get_type = ntohs (get_msg->type);
2206 #if DEBUG_DHT
2207   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2208               "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2209               my_short_id,
2210               "DHT", "GET", 
2211               get_type,
2212               GNUNET_h2s (&message_context->key),
2213               message_context->unique_id);
2214 #endif
2215   increment_stats(STAT_GETS);
2216   results = 0;
2217 #if HAVE_MALICIOUS
2218   if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2219     {
2220       GNUNET_CONTAINER_bloomfilter_free (bf);
2221       return results;
2222     }
2223 #endif
2224   /* FIXME: put xquery / bf into message_context and use
2225      them for processing! */
2226   if (datacache != NULL)
2227     results
2228       = GNUNET_DATACACHE_get (datacache,
2229                               &message_context->key, get_type,
2230                               &datacache_get_iterator,
2231                               message_context);
2232
2233   if (results >= 1)
2234     {
2235 #if DEBUG_DHT
2236       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2237                   "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2238                   results, "GET", message_context->unique_id);
2239 #endif
2240 #if DEBUG_DHT_ROUTING
2241       if ((debug_routes) && (dhtlog_handle != NULL))
2242         {
2243           dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2244                                 message_context->hop_count, GNUNET_YES, &my_identity,
2245                                 &message_context->key);
2246         }
2247
2248       if ((debug_routes_extended) && (dhtlog_handle != NULL))
2249         {
2250           dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2251                                        message_context->hop_count, GNUNET_YES,
2252                                        &my_identity, &message_context->key, message_context->peer,
2253                                        NULL);
2254         }
2255 #endif
2256     }
2257
2258   if (message_context->hop_count == 0) /* Locally initiated request */
2259     {
2260 #if DEBUG_DHT_ROUTING
2261     if ((debug_routes) && (dhtlog_handle != NULL))
2262       {
2263         dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2264                                       message_context->hop_count, GNUNET_NO, &my_identity,
2265                                       &message_context->key);
2266       }
2267 #endif
2268     }
2269   GNUNET_CONTAINER_bloomfilter_free (bf);
2270   return results;
2271 }
2272
2273 static void
2274 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2275 {
2276   GNUNET_HashCode *key = cls;
2277   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2278     {
2279       GNUNET_free(key);
2280     }
2281 }
2282
2283 /**
2284  * Server handler for initiating local dht find peer requests
2285  *
2286  * @param cls closure for service
2287  * @param find_msg the actual find peer message
2288  * @param message_context struct containing pertinent information about the request
2289  *
2290  */
2291 static void
2292 handle_dht_find_peer (void *cls,
2293                       const struct GNUNET_MessageHeader *find_msg,
2294                       struct DHT_MessageContext *message_context)
2295 {
2296   struct GNUNET_MessageHeader *find_peer_result;
2297   struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2298   struct DHT_MessageContext *new_msg_ctx;
2299   struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2300   size_t hello_size;
2301   size_t tsize;
2302   GNUNET_HashCode *recent_hash;
2303   struct GNUNET_MessageHeader *other_hello;
2304   size_t other_hello_size;
2305   struct GNUNET_PeerIdentity peer_id;
2306
2307   find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2308   GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2309   if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2310     return;
2311   other_hello = NULL;
2312   other_hello_size = 0;
2313   if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2314     {
2315       other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2316       other_hello = GNUNET_malloc(other_hello_size);
2317       memcpy(other_hello, &find_peer_message[1], other_hello_size);
2318       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)))
2319         {
2320           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2321           GNUNET_free(other_hello);
2322           return;
2323         }
2324 #if FIND_PEER_WITH_HELLO
2325       if (GNUNET_YES == consider_peer(&peer_id))
2326         {
2327           increment_stats(STAT_HELLOS_PROVIDED);
2328           GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2329           GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2330           return;
2331         }
2332       else /* We don't want this peer! */
2333         return;
2334 #endif
2335     }
2336
2337 #if DEBUG_DHT
2338   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2339               "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2340               my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&message_context->key),
2341               ntohs (find_msg->size),
2342               sizeof (struct GNUNET_MessageHeader));
2343 #endif
2344   if (my_hello == NULL)
2345   {
2346 #if DEBUG_DHT
2347     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2348                 "`%s': Our HELLO is null, can't return.\n",
2349                 "DHT");
2350 #endif
2351     GNUNET_free_non_null(other_hello);
2352     return;
2353   }
2354
2355   incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2356   if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2357     {
2358       increment_stats(STAT_BLOOM_FIND_PEER);
2359       GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2360       GNUNET_free_non_null(other_hello);
2361       return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2362     }
2363   GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2364
2365 #if RESTRICT_FIND_PEER
2366
2367   /**
2368    * Ignore any find peer requests from a peer we have seen very recently.
2369    */
2370   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! */
2371   {
2372     increment_stats("# dht find peer requests ignored (recently seen!)");
2373     GNUNET_free_non_null(other_hello);
2374     return;
2375   }
2376
2377   /**
2378    * Use this check to only allow the peer to respond to find peer requests if
2379    * it would be beneficial to have the requesting peer in this peers routing
2380    * table.  Can be used to thwart peers flooding the network with find peer
2381    * requests that we don't care about.  However, if a new peer is joining
2382    * the network and has no other peers this is a problem (assume all buckets
2383    * full, no one will respond!).
2384    */
2385   memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2386   if (GNUNET_NO == consider_peer(&peer_id))
2387     {
2388       increment_stats("# dht find peer requests ignored (do not need!)");
2389       GNUNET_free_non_null(other_hello);
2390       return;
2391     }
2392 #endif
2393
2394   recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2395   memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2396   GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2397   GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2398
2399   /* Simplistic find_peer functionality, always return our hello */
2400   hello_size = ntohs(my_hello->size);
2401   tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2402
2403   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2404     {
2405       GNUNET_break_op (0);
2406       GNUNET_free_non_null(other_hello);
2407       return;
2408     }
2409
2410   find_peer_result = GNUNET_malloc (tsize);
2411   find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2412   find_peer_result->size = htons (tsize);
2413   memcpy (&find_peer_result[1], my_hello, hello_size);
2414
2415   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2416               "`%s': Sending hello size %d to requesting peer.\n",
2417               "DHT", hello_size);
2418
2419   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2420   memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2421   new_msg_ctx->peer = &my_identity;
2422   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2423   new_msg_ctx->hop_count = 0;
2424   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2425   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2426   increment_stats(STAT_FIND_PEER_ANSWER);
2427   route_result_message(cls, find_peer_result, new_msg_ctx);
2428   GNUNET_free(new_msg_ctx);
2429 #if DEBUG_DHT_ROUTING
2430   if ((debug_routes) && (dhtlog_handle != NULL))
2431     {
2432       dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2433                                    message_context->hop_count, GNUNET_YES, &my_identity,
2434                                    &message_context->key);
2435     }
2436 #endif
2437   GNUNET_free_non_null(other_hello);
2438   GNUNET_free(find_peer_result);
2439 }
2440
2441 /**
2442  * Task used to republish data.
2443  * Forward declaration; function call loop.
2444  *
2445  * @param cls closure (a struct RepublishContext)
2446  * @param tc runtime context for this task
2447  */
2448 static void
2449 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2450
2451 /**
2452  * Server handler for initiating local dht put requests
2453  *
2454  * @param cls closure for service
2455  * @param msg the actual put message
2456  * @param message_context struct containing pertinent information about the request
2457  */
2458 static void
2459 handle_dht_put (void *cls,
2460                 const struct GNUNET_MessageHeader *msg,
2461                 struct DHT_MessageContext *message_context)
2462 {
2463   struct GNUNET_DHT_PutMessage *put_msg;
2464   size_t put_type;
2465   size_t data_size;
2466   int ret;
2467   struct RepublishContext *put_context;
2468
2469   GNUNET_assert (ntohs (msg->size) >=
2470                  sizeof (struct GNUNET_DHT_PutMessage));
2471
2472
2473   put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2474   put_type = ntohs (put_msg->type);
2475
2476   if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2477     return;
2478
2479   data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2480 #if DEBUG_DHT
2481   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2482               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2483               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
2484 #endif
2485 #if DEBUG_DHT_ROUTING
2486   if (message_context->hop_count == 0) /* Locally initiated request */
2487     {
2488       if ((debug_routes) && (dhtlog_handle != NULL))
2489         {
2490           dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2491                                        message_context->hop_count, GNUNET_NO, &my_identity,
2492                                        &message_context->key);
2493         }
2494     }
2495 #endif
2496
2497   if (message_context->closest != GNUNET_YES)
2498     return;
2499
2500 #if DEBUG_DHT_ROUTING
2501   if ((debug_routes_extended) && (dhtlog_handle != NULL))
2502     {
2503       dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2504                                    message_context->hop_count, GNUNET_YES,
2505                                    &my_identity, &message_context->key, message_context->peer,
2506                                    NULL);
2507     }
2508
2509   if ((debug_routes) && (dhtlog_handle != NULL))
2510     {
2511       dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2512                                    message_context->hop_count, GNUNET_YES, &my_identity,
2513                                    &message_context->key);
2514     }
2515 #endif
2516
2517   increment_stats(STAT_PUTS_INSERTED);
2518   if (datacache != NULL)
2519     {
2520       ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2521                                   (char *) &put_msg[1], put_type,
2522                                   GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2523
2524       if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2525         {
2526           put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2527           memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2528           put_context->type = put_type;
2529           GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
2530         }
2531     }
2532   else
2533     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2534                 "`%s:%s': %s request received, but have no datacache!\n",
2535                 my_short_id, "DHT", "PUT");
2536 }
2537
2538 /**
2539  * Estimate the diameter of the network based
2540  * on how many buckets are currently in use.
2541  * Concept here is that the diameter of the network
2542  * is roughly the distance a message must travel in
2543  * order to reach its intended destination.  Since
2544  * at each hop we expect to get one bit closer, and
2545  * we have one bit per bucket, the number of buckets
2546  * in use should be the largest number of hops for
2547  * a sucessful message. (of course, this assumes we
2548  * know all peers in the network!)
2549  *
2550  * @return ballpark diameter figure
2551  */
2552 static unsigned int estimate_diameter()
2553 {
2554   return MAX_BUCKETS - lowest_bucket;
2555 }
2556
2557 /**
2558  * To how many peers should we (on average)
2559  * forward the request to obtain the desired
2560  * target_replication count (on average).
2561  *
2562  * Always 0, 1 or 2 (don't send, send once, split)
2563  */
2564 static unsigned int
2565 get_forward_count (unsigned int hop_count, size_t target_replication)
2566 {
2567 #if DOUBLE
2568   double target_count;
2569   double random_probability;
2570 #else
2571   uint32_t random_value;
2572 #endif
2573   unsigned int target_value;
2574   unsigned int diameter;
2575
2576   /**
2577    * If we are behaving in strict kademlia mode, send multiple initial requests,
2578    * but then only send to 1 or 0 peers based strictly on the number of hops.
2579    */
2580   if (strict_kademlia == GNUNET_YES)
2581     {
2582       if (hop_count == 0)
2583         return DHT_KADEMLIA_REPLICATION;
2584       else if (hop_count < max_hops)
2585         return 1;
2586       else
2587         return 0;
2588     }
2589
2590   /* FIXME: the smaller we think the network is the more lenient we should be for
2591    * routing right?  The estimation below only works if we think we have reasonably
2592    * full routing tables, which for our RR topologies may not be the case!
2593    */
2594   diameter = estimate_diameter ();
2595   if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2596     {
2597 #if DEBUG_DHT
2598       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2599                   "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2600                   "DHT", estimate_diameter(), lowest_bucket);
2601 #endif
2602       return 0;
2603     }
2604   else if (hop_count > max_hops)
2605     {
2606 #if DEBUG_DHT
2607       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2608                   "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2609                   "DHT");
2610 #endif
2611       return 0;
2612     }
2613
2614 #if DOUBLE
2615   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2616   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2617   target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2618     (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2619   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2620   random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2621       RAND_MAX)) / RAND_MAX;
2622   GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2623
2624   target_value = 0;
2625   //while (target_value < target_count)
2626   if (target_value < target_count)
2627     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? */
2628
2629
2630   //if ((target_count + 1 - (double)target_value) > random_probability)
2631   if ((target_count) > random_probability)
2632     target_value++;
2633 #endif
2634
2635   random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2636   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));
2637   target_value = 1;
2638   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2639   if (random_value < target_replication)
2640     target_value++;
2641
2642   return target_value;
2643 }
2644
2645 /*
2646  * Check whether my identity is closer than any known peers.
2647  * If a non-null bloomfilter is given, check if this is the closest
2648  * peer that hasn't already been routed to.
2649  *
2650  * @param target hash code to check closeness to
2651  * @param bloom bloomfilter, exclude these entries from the decision
2652  *
2653  * Return GNUNET_YES if node location is closest, GNUNET_NO
2654  * otherwise.
2655  */
2656 int
2657 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2658 {
2659   int bits;
2660   int other_bits;
2661   int bucket_num;
2662   int count;
2663   struct PeerInfo *pos;
2664   unsigned int my_distance;
2665
2666   if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2667     return GNUNET_YES;
2668
2669   bucket_num = find_current_bucket(target);
2670
2671   bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2672   my_distance = distance(&my_identity.hashPubKey, target);
2673   pos = k_buckets[bucket_num].head;
2674   count = 0;
2675   while ((pos != NULL) && (count < bucket_size))
2676     {
2677       if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2678         {
2679           pos = pos->next;
2680           continue; /* Skip already checked entries */
2681         }
2682
2683       other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2684       if (other_bits > bits)
2685         return GNUNET_NO;
2686       else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2687         {
2688           if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2689             return GNUNET_YES;
2690           else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2691             return GNUNET_NO;
2692         }
2693       pos = pos->next;
2694     }
2695
2696 #if DEBUG_TABLE
2697   GNUNET_GE_LOG (coreAPI->ectx,
2698                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2699                  GNUNET_GE_BULK, "closest peer\n");
2700   printPeerBits (&closest);
2701   GNUNET_GE_LOG (coreAPI->ectx,
2702                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2703                  GNUNET_GE_BULK, "me\n");
2704   printPeerBits (coreAPI->my_identity);
2705   GNUNET_GE_LOG (coreAPI->ectx,
2706                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2707                  GNUNET_GE_BULK, "key\n");
2708   printKeyBits (target);
2709   GNUNET_GE_LOG (coreAPI->ectx,
2710                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2711                  GNUNET_GE_BULK,
2712                  "closest peer inverse distance is %u, mine is %u\n",
2713                  inverse_distance (target, &closest.hashPubKey),
2714                  inverse_distance (target,
2715                                    &coreAPI->my_identity->hashPubKey));
2716 #endif
2717
2718   /* No peers closer, we are the closest! */
2719   return GNUNET_YES;
2720 }
2721
2722
2723 /**
2724  * Return this peers adjusted value based on the convergence
2725  * function chosen.  This is the key function for randomized
2726  * routing decisions.
2727  *
2728  * @param target the key of the request
2729  * @param peer the peer we would like the value of
2730  * @param hops number of hops this message has already traveled
2731  *
2732  * @return bit distance from target to peer raised to an exponent
2733  *         adjusted based on the current routing convergence algorithm
2734  *
2735  */
2736 unsigned long long
2737 converge_distance (const GNUNET_HashCode *target,
2738                    struct PeerInfo *peer,
2739                    unsigned int hops)
2740 {
2741   unsigned long long ret;
2742   unsigned int other_matching_bits;
2743   double converge_modifier = 0.0;
2744   double base_converge_modifier = .1;
2745   double calc_value;
2746   double exponent;
2747   int curr_max_hops;
2748
2749   if (use_max_hops)
2750     curr_max_hops = max_hops;
2751   else
2752     curr_max_hops = (estimate_diameter() + 1) * 2;
2753
2754   if (converge_modifier > 0)
2755     converge_modifier = converge_modifier * base_converge_modifier;
2756   else
2757     {
2758       converge_modifier = base_converge_modifier;
2759       base_converge_modifier = 0.0;
2760     }
2761
2762   GNUNET_assert(converge_modifier > 0);
2763
2764   other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2765
2766   switch (converge_option)
2767     {
2768       case DHT_CONVERGE_RANDOM:
2769         return 1; /* Always return 1, choose equally among all peers */
2770       case DHT_CONVERGE_LINEAR:
2771         calc_value = hops * curr_max_hops * converge_modifier;
2772         break;
2773       case DHT_CONVERGE_SQUARE:
2774         /**
2775          * Simple square based curve.
2776          */
2777         calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * converge_modifier));
2778         break;
2779       case DHT_CONVERGE_EXPONENTIAL:
2780         /**
2781          * Simple exponential curve.
2782          */
2783         if (base_converge_modifier > 0)
2784           calc_value = (converge_modifier * hops * hops) / curr_max_hops;
2785         else
2786           calc_value = (hops * hops) / curr_max_hops;
2787         break;
2788       default:
2789         return 1;
2790     }
2791
2792   /* Take the log (base e) of the number of bits matching the other peer */
2793   exponent = log(other_matching_bits);
2794
2795   /* Check if we would overflow; our largest possible value is 2^64 = e^44.361419555836498 */
2796   if (exponent * calc_value >= 44.361419555836498)
2797     return ULLONG_MAX;
2798
2799   /* Clear errno and all math exceptions */
2800   errno = 0;
2801   feclearexcept(FE_ALL_EXCEPT);
2802   ret = (unsigned long long)pow(other_matching_bits, calc_value);
2803   if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2804       FE_UNDERFLOW))
2805     {
2806       if (0 != fetestexcept(FE_OVERFLOW))
2807         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2808       if (0 != fetestexcept(FE_INVALID))
2809         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2810       if (0 != fetestexcept(FE_UNDERFLOW))
2811         GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2812       return 0;
2813     }
2814   else
2815     return ret;
2816 }
2817
2818 /**
2819  * Comparison function for two struct PeerInfo's
2820  * which have already had their matching bits to
2821  * some target calculated.
2822  *
2823  * @param p1 a pointer pointer to a struct PeerInfo
2824  * @param p2 a pointer pointer to a struct PeerInfo
2825  *
2826  * @return 0 if equidistant to target,
2827  *        -1 if p1 is closer,
2828  *         1 if p2 is closer
2829  */
2830 static int
2831 compare_peers (const void *p1, const void *p2)
2832 {
2833   struct PeerInfo **first = (struct PeerInfo **)p1;
2834   struct PeerInfo **second = (struct PeerInfo **)p2;
2835
2836   if ((*first)->matching_bits > (*second)->matching_bits)
2837     return -1;
2838   if ((*first)->matching_bits < (*second)->matching_bits)
2839     return 1;
2840   else
2841     return 0;
2842 }
2843
2844
2845 /**
2846  * Select a peer from the routing table that would be a good routing
2847  * destination for sending a message for "target".  The resulting peer
2848  * must not be in the set of blocked peers.<p>
2849  *
2850  * Note that we should not ALWAYS select the closest peer to the
2851  * target, peers further away from the target should be chosen with
2852  * exponentially declining probability.
2853  *
2854  * @param target the key we are selecting a peer to route to
2855  * @param bloom a bloomfilter containing entries this request has seen already
2856  *
2857  * @return Peer to route to, or NULL on error
2858  */
2859 static struct PeerInfo *
2860 select_peer (const GNUNET_HashCode * target,
2861              struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2862 {
2863   unsigned int bc;
2864   unsigned int i;
2865   unsigned int count;
2866   unsigned int offset;
2867   unsigned int my_matching_bits;
2868   int closest_bucket;
2869   struct PeerInfo *pos;
2870   struct PeerInfo *sorted_closest[bucket_size];
2871   unsigned long long temp_converge_distance;
2872   unsigned long long total_distance;
2873   unsigned long long selected;
2874 #if DEBUG_DHT > 1
2875   unsigned long long stats_total_distance;
2876   double sum;
2877 #endif
2878   /* For kademlia */
2879   unsigned int distance;
2880   unsigned int largest_distance;
2881   struct PeerInfo *chosen;
2882
2883   my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
2884
2885   total_distance = 0;
2886   if (strict_kademlia == GNUNET_YES)
2887     {
2888       largest_distance = 0;
2889       chosen = NULL;
2890       for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2891         {
2892           pos = k_buckets[bc].head;
2893           count = 0;
2894           while ((pos != NULL) && (count < bucket_size))
2895             {
2896               /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2897               if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2898                 {
2899                   distance = inverse_distance (target, &pos->id.hashPubKey);
2900                   if (distance > largest_distance)
2901                     {
2902                       chosen = pos;
2903                       largest_distance = distance;
2904                     }
2905                 }
2906               count++;
2907               pos = pos->next;
2908             }
2909         }
2910
2911       if ((largest_distance > 0) && (chosen != NULL))
2912         {
2913           GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2914           return chosen;
2915         }
2916       else
2917         {
2918           return NULL;
2919         }
2920     }
2921
2922   /* GNUnet-style */
2923   total_distance = 0;
2924   /* Three steps: order peers in closest bucket (most matching bits).
2925    * Then go over all LOWER buckets (matching same bits we do)
2926    * Then go over all HIGHER buckets (matching less then we do)
2927    */
2928
2929   closest_bucket = find_current_bucket(target);
2930   GNUNET_assert(closest_bucket >= lowest_bucket);
2931   pos = k_buckets[closest_bucket].head;
2932   count = 0;
2933   offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
2934   memset(sorted_closest, 0, sizeof(sorted_closest));
2935   /* Put any peers in the closest bucket in the sorting array */
2936   while ((pos != NULL) && (count < bucket_size))
2937     {
2938       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2939         {
2940           count++;
2941           pos = pos->next;
2942           continue; /* Ignore bloomfiltered peers */
2943         }
2944       pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2945       sorted_closest[offset] = pos;
2946       pos = pos->next;
2947       offset++;
2948       count++;
2949     }
2950
2951   /* Sort the peers in descending order */
2952   qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
2953
2954   /* Put the sorted closest peers into the possible bins first, in case of overflow. */
2955   for (i = 0; i < offset; i++)
2956     {
2957       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
2958       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
2959         break; /* Ignore bloomfiltered peers */
2960       if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2961         total_distance += temp_converge_distance;
2962       else
2963         break; /* overflow case */
2964     }
2965
2966   /* Now handle peers in lower buckets (matches same # of bits as target) */
2967   for (bc = lowest_bucket; bc < closest_bucket; bc++)
2968     {
2969       pos = k_buckets[bc].head;
2970       count = 0;
2971       while ((pos != NULL) && (count < bucket_size))
2972         {
2973           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2974             {
2975               count++;
2976               pos = pos->next;
2977               continue; /* Ignore bloomfiltered peers */
2978             }
2979           temp_converge_distance = converge_distance(target, pos, hops);
2980           if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2981             total_distance += temp_converge_distance;
2982           else
2983             break; /* overflow case */
2984           pos = pos->next;
2985           count++;
2986         }
2987     }
2988
2989   /* Now handle all the further away peers */
2990   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
2991     {
2992       pos = k_buckets[bc].head;
2993       count = 0;
2994       while ((pos != NULL) && (count < bucket_size))
2995         {
2996           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2997             {
2998               count++;
2999               pos = pos->next;
3000               continue; /* Ignore bloomfiltered peers */
3001             }
3002           temp_converge_distance = converge_distance(target, pos, hops);
3003           if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3004             total_distance += temp_converge_distance;
3005           else
3006             break; /* overflow case */
3007           pos = pos->next;
3008           count++;
3009         }
3010     }
3011
3012   if (total_distance == 0) /* No peers to select from! */
3013     {
3014       increment_stats("# select_peer, total_distance == 0");
3015       return NULL;
3016     }
3017
3018 #if DEBUG_DHT_ROUTING > 1
3019   sum = 0.0;
3020   /* PRINT STATS */
3021   /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3022   stats_total_distance = 0;
3023   for (i = 0; i < offset; i++)
3024     {
3025       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3026         break; /* Ignore bloomfiltered peers */
3027       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3028       if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3029         stats_total_distance += temp_converge_distance;
3030       else
3031         break; /* overflow case */
3032       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);
3033     }
3034
3035   /* Now handle peers in lower buckets (matches same # of bits as target) */
3036   for (bc = lowest_bucket; bc < closest_bucket; bc++)
3037     {
3038       pos = k_buckets[bc].head;
3039       count = 0;
3040       while ((pos != NULL) && (count < bucket_size))
3041         {
3042           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3043             {
3044               count++;
3045               pos = pos->next;
3046               continue; /* Ignore bloomfiltered peers */
3047             }
3048           temp_converge_distance = converge_distance(target, pos, hops);
3049           if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3050             stats_total_distance += temp_converge_distance;
3051           else
3052             break; /* overflow case */
3053           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);
3054           pos = pos->next;
3055           count++;
3056         }
3057     }
3058
3059   /* Now handle all the further away peers */
3060   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3061     {
3062       pos = k_buckets[bc].head;
3063       count = 0;
3064       while ((pos != NULL) && (count < bucket_size))
3065         {
3066           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3067             {
3068               count++;
3069               pos = pos->next;
3070               continue; /* Ignore bloomfiltered peers */
3071             }
3072           temp_converge_distance = converge_distance(target, pos, hops);
3073           if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3074             stats_total_distance += temp_converge_distance;
3075           else
3076             break; /* overflow case */
3077           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);
3078           pos = pos->next;
3079           count++;
3080         }
3081     }
3082   /* END PRINT STATS */
3083 #endif
3084
3085   /* Now actually choose a peer */
3086   selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3087
3088   /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3089   for (i = 0; i < offset; i++)
3090     {
3091       if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3092         break; /* Ignore bloomfiltered peers */
3093       temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3094       if (temp_converge_distance >= selected)
3095         return sorted_closest[i];
3096       else
3097         selected -= temp_converge_distance;
3098     }
3099
3100   /* Now handle peers in lower buckets (matches same # of bits as target) */
3101   for (bc = lowest_bucket; bc < closest_bucket; bc++)
3102     {
3103       pos = k_buckets[bc].head;
3104       count = 0;
3105       while ((pos != NULL) && (count < bucket_size))
3106         {
3107           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3108             {
3109               count++;
3110               pos = pos->next;
3111               continue; /* Ignore bloomfiltered peers */
3112             }
3113           temp_converge_distance = converge_distance(target, pos, hops);
3114           if (temp_converge_distance >= selected)
3115             return pos;
3116           else
3117             selected -= temp_converge_distance;
3118           pos = pos->next;
3119           count++;
3120         }
3121     }
3122
3123   /* Now handle all the further away peers */
3124   for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3125     {
3126       pos = k_buckets[bc].head;
3127       count = 0;
3128       while ((pos != NULL) && (count < bucket_size))
3129         {
3130           if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3131             {
3132               count++;
3133               pos = pos->next;
3134               continue; /* Ignore bloomfiltered peers */
3135             }
3136           temp_converge_distance = converge_distance(target, pos, hops);
3137           if (temp_converge_distance >= selected)
3138             return pos;
3139           else
3140             selected -= temp_converge_distance;
3141           pos = pos->next;
3142           count++;
3143         }
3144     }
3145
3146   increment_stats("# failed to select peer");
3147   return NULL;
3148 }
3149
3150
3151 /**
3152  * Task used to remove recent entries, either
3153  * after timeout, when full, or on shutdown.
3154  *
3155  * @param cls the entry to remove
3156  * @param tc context, reason, etc.
3157  */
3158 static void
3159 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3160 {
3161   struct RecentRequest *req = cls;
3162   static GNUNET_HashCode hash;
3163
3164   GNUNET_assert(req != NULL);
3165   hash_from_uid(req->uid, &hash);
3166   GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3167   GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3168   GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3169   GNUNET_free(req);
3170
3171   if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3172   {
3173     GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3174     GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3175   }
3176 }
3177
3178
3179 /**
3180  * Task used to remove forwarding entries, either
3181  * after timeout, when full, or on shutdown.
3182  *
3183  * @param cls the entry to remove
3184  * @param tc context, reason, etc.
3185  */
3186 static void
3187 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3188 {
3189   struct DHTRouteSource *source_info = cls;
3190   struct DHTQueryRecord *record;
3191   source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3192   record = source_info->record;
3193   GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3194
3195   if (record->head == NULL) /* No more entries in DLL */
3196     {
3197       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3198       GNUNET_free(record);
3199     }
3200   if (source_info->find_peers_responded != NULL)
3201     GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3202   GNUNET_free(source_info);
3203 }
3204
3205 /**
3206  * Remember this routing request so that if a reply is
3207  * received we can either forward it to the correct peer
3208  * or return the result locally.
3209  *
3210  * @param cls DHT service closure
3211  * @param msg_ctx Context of the route request
3212  *
3213  * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3214  */
3215 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
3216 {
3217   struct DHTQueryRecord *record;
3218   struct DHTRouteSource *source_info;
3219   struct DHTRouteSource *pos;
3220   struct GNUNET_TIME_Absolute now;
3221   unsigned int current_size;
3222
3223   current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3224   while (current_size >= MAX_OUTSTANDING_FORWARDS)
3225     {
3226       source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3227       GNUNET_assert(source_info != NULL);
3228       record = source_info->record;
3229       GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3230       if (record->head == NULL) /* No more entries in DLL */
3231         {
3232           GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3233           GNUNET_free(record);
3234         }
3235       GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
3236       if (source_info->find_peers_responded != NULL)
3237         GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3238       GNUNET_free(source_info);
3239       current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3240     }
3241   now = GNUNET_TIME_absolute_get();
3242   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3243   if (record != NULL) /* Already know this request! */
3244     {
3245       pos = record->head;
3246       while (pos != NULL)
3247         {
3248           if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3249             break; /* Already have this peer in reply list! */
3250           pos = pos->next;
3251         }
3252       if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3253         {
3254           GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3255           return GNUNET_NO;
3256         }
3257     }
3258   else
3259     {
3260       record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3261       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3262       memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3263     }
3264
3265   source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3266   source_info->record = record;
3267   source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3268   source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3269   memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3270   GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3271   if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3272     {
3273       source_info->client = msg_ctx->client;
3274       now = GNUNET_TIME_absolute_get_forever();
3275     }
3276   source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3277 #if DEBUG_DHT > 1
3278       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3279                   "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3280                   "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3281 #endif
3282   return GNUNET_YES;
3283 }
3284
3285
3286 /**
3287  * Main function that handles whether or not to route a message to other
3288  * peers.
3289  *
3290  * @param cls closure for dht service (NULL)
3291  * @param msg the message to be routed
3292  * @param message_context the context containing all pertinent information about the message
3293  *
3294  * @return the number of peers the message was routed to,
3295  *         GNUNET_SYSERR on failure
3296  */
3297 static int route_message(void *cls,
3298                          const struct GNUNET_MessageHeader *msg,
3299                          struct DHT_MessageContext *message_context)
3300 {
3301   int i;
3302   int global_closest;
3303   struct PeerInfo *selected;
3304 #if DEBUG_DHT_ROUTING > 1
3305   struct PeerInfo *nearest;
3306 #endif
3307   unsigned int forward_count;
3308   struct RecentRequest *recent_req;
3309   GNUNET_HashCode unique_hash;
3310   char *stat_forward_count;
3311   char *temp_stat_str;
3312 #if DEBUG_DHT_ROUTING
3313   int ret;
3314 #endif
3315
3316   if (malicious_dropper == GNUNET_YES)
3317     {
3318 #if DEBUG_DHT_ROUTING
3319       if ((debug_routes_extended) && (dhtlog_handle != NULL))
3320         {
3321           dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3322                                        message_context->hop_count, GNUNET_SYSERR,
3323                                        &my_identity, &message_context->key, message_context->peer,
3324                                        NULL);
3325         }
3326 #endif
3327       if (message_context->bloom != NULL)
3328         GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3329       return 0;
3330     }
3331
3332   increment_stats(STAT_ROUTES);
3333   /* Semantics of this call means we find whether we are the closest peer out of those already
3334    * routed to on this messages path.
3335    */
3336   global_closest = am_closest_peer(&message_context->key, NULL);
3337   message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3338   forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3339   GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3340   increment_stats(stat_forward_count);
3341   GNUNET_free(stat_forward_count);
3342   if (message_context->bloom == NULL)
3343     message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3344
3345   if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3346     forward_count = 0;
3347
3348   /**
3349    * NOTICE:  In Kademlia, a find peer request goes no further if the peer doesn't return
3350    * any closer peers (which is being checked for below).  Since we are doing recursive
3351    * routing we have no choice but to stop forwarding in this case.  This means that at
3352    * any given step the request may NOT be forwarded to alpha peers (because routes will
3353    * stop and the parallel route will not be aware of it).  Of course, assuming that we
3354    * have fulfilled the Kademlia requirements for routing table fullness this will never
3355    * ever ever be a problem.
3356    *
3357    * However, is this fair?
3358    *
3359    * Since we use these requests to build our routing tables (and we build them in the
3360    * testing driver) we will ignore this restriction for FIND_PEER messages so that
3361    * routing tables still get constructed.
3362    */
3363   if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3364     forward_count = 0;
3365
3366 #if DEBUG_DHT_ROUTING
3367   if (forward_count == 0)
3368     ret = GNUNET_SYSERR;
3369   else
3370     ret = GNUNET_NO;
3371
3372   if ((debug_routes_extended) && (dhtlog_handle != NULL))
3373     {
3374       dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3375                                    message_context->hop_count, ret,
3376                                    &my_identity, &message_context->key, message_context->peer,
3377                                    NULL);
3378     }
3379 #endif
3380
3381   switch (ntohs(msg->type))
3382     {
3383     case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3384       cache_response (cls, message_context);
3385       if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3386         forward_count = 0;
3387       break;
3388     case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3389       increment_stats(STAT_PUTS);
3390       message_context->closest = global_closest;
3391       handle_dht_put (cls, msg, message_context);
3392       break;
3393     case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3394       increment_stats(STAT_FIND_PEER);
3395       if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3396       {
3397         cache_response (cls, message_context);
3398         if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3399           handle_dht_find_peer (cls, msg, message_context);
3400       }
3401 #if DEBUG_DHT_ROUTING
3402       if (message_context->hop_count == 0) /* Locally initiated request */
3403         {
3404           if ((debug_routes) && (dhtlog_handle != NULL))
3405             {
3406               dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3407               dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3408                                            message_context->hop_count, GNUNET_NO, &my_identity,
3409                                            &message_context->key);
3410             }
3411         }
3412 #endif
3413       break;
3414     default:
3415       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3416                   "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3417     }
3418
3419   GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3420   hash_from_uid (message_context->unique_id, &unique_hash);
3421   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3422   {
3423     recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3424     GNUNET_assert(recent_req != NULL);
3425     if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3426       increment_stats(STAT_DUPLICATE_UID);
3427     else
3428       {
3429         increment_stats(STAT_RECENT_SEEN);
3430         GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3431       }
3432     }
3433   else
3434     {
3435       recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3436       recent_req->uid = message_context->unique_id;
3437       memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3438       recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3439       recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3440       recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3441       GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3442     }
3443
3444   if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3445     {
3446       recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3447       GNUNET_assert(recent_req != NULL);
3448       GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3449       GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3450     }
3451
3452   for (i = 0; i < forward_count; i++)
3453     {
3454       selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3455
3456       if (selected != NULL)
3457         {
3458           if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
3459             GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
3460           else
3461             GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
3462           if (temp_stat_str != NULL)
3463             {
3464               increment_stats(temp_stat_str);
3465               GNUNET_free(temp_stat_str);
3466             }
3467           GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3468 #if DEBUG_DHT_ROUTING > 1
3469           nearest = find_closest_peer(&message_context->key);
3470           nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3471           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3472                       "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3473                       "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));
3474           GNUNET_free(nearest_buf);
3475 #endif
3476 #if DEBUG_DHT_ROUTING
3477           if ((debug_routes_extended) && (dhtlog_handle != NULL))
3478             {
3479               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3480                                            message_context->hop_count, GNUNET_NO,
3481                                            &my_identity, &message_context->key, message_context->peer,
3482                                            &selected->id);
3483             }
3484 #endif
3485           forward_message(cls, msg, selected, message_context);
3486         }
3487     }
3488
3489   if (message_context->bloom != NULL)
3490     {
3491       GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3492       GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3493     }
3494
3495   return forward_count;
3496 }
3497
3498 /**
3499  * Iterator for local get request results,
3500  *
3501  * @param cls closure for iterator, NULL
3502  * @param exp when does this value expire?
3503  * @param key the key this data is stored under
3504  * @param size the size of the data identified by key
3505  * @param data the actual data
3506  * @param type the type of the data
3507  *
3508  * @return GNUNET_OK to continue iteration, anything else
3509  * to stop iteration.
3510  */
3511 static int
3512 republish_content_iterator (void *cls,
3513                             struct GNUNET_TIME_Absolute exp,
3514                             const GNUNET_HashCode * key,
3515                             uint32_t size, const char *data, uint32_t type)
3516 {
3517
3518   struct DHT_MessageContext *new_msg_ctx;
3519   struct GNUNET_DHT_PutMessage *put_msg;
3520 #if DEBUG_DHT
3521   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3522               "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3523 #endif
3524   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3525
3526   put_msg =
3527     GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3528   put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3529   put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3530   put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3531   put_msg->type = htons (type);
3532   memcpy (&put_msg[1], data, size);
3533   new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3534   new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3535   new_msg_ctx->msg_options = ntohl (0);
3536   new_msg_ctx->network_size = estimate_diameter();
3537   new_msg_ctx->peer = &my_identity;
3538   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3539   new_msg_ctx->hop_count = 0;
3540   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3541   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3542   increment_stats(STAT_PUT_START);
3543   route_message(cls, &put_msg->header, new_msg_ctx);
3544
3545   GNUNET_free(new_msg_ctx);
3546   GNUNET_free (put_msg);
3547   return GNUNET_OK;
3548 }
3549
3550 /**
3551  * Task used to republish data.
3552  *
3553  * @param cls closure (a struct RepublishContext)
3554  * @param tc runtime context for this task
3555  */
3556 static void
3557 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3558 {
3559   struct RepublishContext *put_context = cls;
3560
3561   unsigned int results;
3562
3563   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3564     {
3565       GNUNET_free(put_context);
3566       return;
3567     }
3568
3569   GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3570   results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3571   if (results == 0) /* Data must have expired */
3572     GNUNET_free(put_context);
3573   else /* Reschedule task for next time period */
3574     GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);
3575
3576 }
3577
3578
3579 /**
3580  * Iterator over hash map entries.
3581  *
3582  * @param cls client to search for in source routes
3583  * @param key current key code (ignored)
3584  * @param value value in the hash map, a DHTQueryRecord
3585  * @return GNUNET_YES if we should continue to
3586  *         iterate,
3587  *         GNUNET_NO if not.
3588  */
3589 static int find_client_records (void *cls,
3590                                 const GNUNET_HashCode * key, void *value)
3591 {
3592   struct ClientList *client = cls;
3593   struct DHTQueryRecord *record = value;
3594   struct DHTRouteSource *pos;
3595   pos = record->head;
3596   while (pos != NULL)
3597     {
3598       if (pos->client == client)
3599         break;
3600       pos = pos->next;
3601     }
3602   if (pos != NULL)
3603     {
3604       GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3605       GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3606       if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3607         GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3608
3609       if (pos->find_peers_responded != NULL)
3610         GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3611       GNUNET_free(pos);
3612     }
3613   if (record->head == NULL) /* No more entries in DLL */
3614     {
3615       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3616       GNUNET_free(record);
3617     }
3618   return GNUNET_YES;
3619 }
3620
3621 /**
3622  * Functions with this signature are called whenever a client
3623  * is disconnected on the network level.
3624  *
3625  * @param cls closure (NULL for dht)
3626  * @param client identification of the client; NULL
3627  *        for the last call when the server is destroyed
3628  */
3629 static void handle_client_disconnect (void *cls,
3630                                       struct GNUNET_SERVER_Client* client)
3631 {
3632   struct ClientList *pos = client_list;
3633   struct ClientList *prev;
3634   struct ClientList *found;
3635   struct PendingMessage *reply;
3636
3637   prev = NULL;
3638   found = NULL;
3639   while (pos != NULL)
3640     {
3641       if (pos->client_handle == client)
3642         {
3643           if (prev != NULL)
3644             prev->next = pos->next;
3645           else
3646             client_list = pos->next;
3647           found = pos;
3648           break;
3649         }
3650       prev = pos;
3651       pos = pos->next;
3652     }
3653
3654   if (found != NULL)
3655     {
3656       while(NULL != (reply = found->pending_head))
3657         {
3658           GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3659           GNUNET_free(reply);
3660         }
3661       GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3662       GNUNET_free(found);
3663     }
3664 }
3665
3666 /**
3667  * Find a client if it exists, add it otherwise.
3668  *
3669  * @param client the server handle to the client
3670  *
3671  * @return the client if found, a new client otherwise
3672  */
3673 static struct ClientList *
3674 find_active_client (struct GNUNET_SERVER_Client *client)
3675 {
3676   struct ClientList *pos = client_list;
3677   struct ClientList *ret;
3678
3679   while (pos != NULL)
3680     {
3681       if (pos->client_handle == client)
3682         return pos;
3683       pos = pos->next;
3684     }
3685
3686   ret = GNUNET_malloc (sizeof (struct ClientList));
3687   ret->client_handle = client;
3688   ret->next = client_list;
3689   client_list = ret;
3690
3691   return ret;
3692 }
3693
3694 /**
3695  * Task to send a malicious put message across the network.
3696  *
3697  * @param cls closure for this task
3698  * @param tc the context under which the task is running
3699  */
3700 static void
3701 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3702 {
3703   static struct GNUNET_DHT_PutMessage put_message;
3704   static struct DHT_MessageContext message_context;
3705   static GNUNET_HashCode key;
3706   uint32_t random_key;
3707
3708   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3709     return;
3710
3711   put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3712   put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3713   put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3714   put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3715   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3716   message_context.client = NULL;
3717   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3718   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3719   memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3720   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3721   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3722   message_context.msg_options = ntohl (0);
3723   message_context.network_size = estimate_diameter();
3724   message_context.peer = &my_identity;
3725   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3726   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3727 #if DEBUG_DHT_ROUTING
3728   if (dhtlog_handle != NULL)
3729     dhtlog_handle->insert_dhtkey(NULL, &key);
3730 #endif
3731   increment_stats(STAT_PUT_START);
3732   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3733   route_message(NULL, &put_message.header, &message_context);
3734   GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3735
3736 }
3737
3738 /**
3739  * Task to send a malicious put message across the network.
3740  *
3741  * @param cls closure for this task
3742  * @param tc the context under which the task is running
3743  */
3744 static void
3745 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3746 {
3747   static struct GNUNET_DHT_GetMessage get_message;
3748   struct DHT_MessageContext message_context;
3749   static GNUNET_HashCode key;
3750   uint32_t random_key;
3751
3752   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3753     return;
3754
3755   get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3756   get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3757   get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3758   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3759   message_context.client = NULL;
3760   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3761   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3762   memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3763   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3764   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3765   message_context.msg_options = ntohl (0);
3766   message_context.network_size = estimate_diameter();
3767   message_context.peer = &my_identity;
3768   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3769   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3770 #if DEBUG_DHT_ROUTING
3771   if (dhtlog_handle != NULL)
3772     dhtlog_handle->insert_dhtkey(NULL, &key);
3773 #endif
3774   increment_stats(STAT_GET_START);
3775   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3776   route_message (NULL, &get_message.header, &message_context);
3777   GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3778 }
3779
3780 /**
3781  * Iterator over hash map entries.
3782  *
3783  * @param cls closure
3784  * @param key current key code
3785  * @param value value in the hash map
3786  * @return GNUNET_YES if we should continue to
3787  *         iterate,
3788  *         GNUNET_NO if not.
3789  */
3790 static int
3791 add_known_to_bloom (void *cls,
3792                     const GNUNET_HashCode * key,
3793                     void *value)
3794 {
3795   struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3796   GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3797   return GNUNET_YES;
3798 }
3799
3800 /**
3801  * Task to send a find peer message for our own peer identifier
3802  * so that we can find the closest peers in the network to ourselves
3803  * and attempt to connect to them.
3804  *
3805  * @param cls closure for this task
3806  * @param tc the context under which the task is running
3807  */
3808 static void
3809 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3810 {
3811   struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3812   struct DHT_MessageContext message_context;
3813   int ret;
3814   struct GNUNET_TIME_Relative next_send_time;
3815   struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3816 #if COUNT_INTERVAL
3817   struct GNUNET_TIME_Relative time_diff;
3818   struct GNUNET_TIME_Absolute end;
3819   double multiplier;
3820   double count_per_interval;
3821 #endif
3822   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3823     return;
3824
3825   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! */
3826     {
3827       GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3828       GNUNET_SCHEDULER_add_delayed (sched,
3829                                     GNUNET_TIME_UNIT_MINUTES,
3830                                     &send_find_peer_message, NULL);
3831       newly_found_peers = 0;
3832       return;
3833     }
3834     
3835   increment_stats(STAT_FIND_PEER_START);
3836 #if COUNT_INTERVAL
3837   end = GNUNET_TIME_absolute_get();
3838   time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3839
3840   if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3841     {
3842       multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3843       count_per_interval = find_peer_context.count / multiplier;
3844     }
3845   else
3846     {
3847       multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3848       count_per_interval = find_peer_context.count * multiplier;
3849     }
3850 #endif
3851
3852 #if FIND_PEER_WITH_HELLO
3853   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3854   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3855   memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3856 #else
3857   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3858   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3859 #endif
3860   find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3861   temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3862   GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3863   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3864   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3865   memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3866   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3867   message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3868   message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3869   message_context.network_size = estimate_diameter();
3870   message_context.peer = &my_identity;
3871   message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3872   message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3873
3874   ret = route_message(NULL, &find_peer_msg->header, &message_context);
3875   GNUNET_free(find_peer_msg);
3876   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3877               "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3878               "FIND PEER", ret);
3879   if (newly_found_peers < bucket_size)
3880     {
3881       next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3882                               GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3883                                                        DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3884     }
3885   else
3886     {
3887       next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3888                              GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3889                                                       DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3890     }
3891
3892   GNUNET_assert (next_send_time.value != 0);
3893   find_peer_context.count = 0;
3894   newly_found_peers = 0;
3895   find_peer_context.start = GNUNET_TIME_absolute_get();
3896   if (GNUNET_YES == do_find_peer)
3897   {
3898     GNUNET_SCHEDULER_add_delayed (sched,
3899                                   next_send_time,
3900                                   &send_find_peer_message, NULL);
3901   }
3902 }
3903
3904 /**
3905  * Handler for any generic DHT messages, calls the appropriate handler
3906  * depending on message type, sends confirmation if responses aren't otherwise
3907  * expected.
3908  *
3909  * @param cls closure for the service
3910  * @param client the client we received this message from
3911  * @param message the actual message received
3912  */
3913 static void
3914 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3915                                 const struct GNUNET_MessageHeader *message)
3916 {
3917   const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3918   const struct GNUNET_MessageHeader *enc_msg;
3919   struct DHT_MessageContext message_context;
3920
3921   enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3922 #if DEBUG_DHT
3923   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3924               "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3925               my_short_id, 
3926               "DHT",
3927               "GENERIC",
3928               ntohs (message->type), 
3929               GNUNET_h2s (&dht_msg->key),
3930               GNUNET_ntohll (dht_msg->unique_id));
3931 #endif
3932 #if DEBUG_DHT_ROUTING
3933   if (dhtlog_handle != NULL)
3934     dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3935 #endif
3936   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3937   message_context.client = find_active_client (client);
3938   memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3939   message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3940   message_context.replication = ntohl (dht_msg->desired_replication_level);
3941   message_context.msg_options = ntohl (dht_msg->options);
3942   message_context.network_size = estimate_diameter();
3943   message_context.peer = &my_identity;
3944   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3945   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3946   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3947     increment_stats(STAT_GET_START);
3948   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3949     increment_stats(STAT_PUT_START);
3950   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3951     increment_stats(STAT_FIND_PEER_START);
3952
3953   route_message(cls, enc_msg, &message_context);
3954
3955   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3956
3957 }
3958
3959 /**
3960  * Handler for any locally received DHT control messages,
3961  * sets malicious flags mostly for now.
3962  *
3963  * @param cls closure for the service
3964  * @param client the client we received this message from
3965  * @param message the actual message received
3966  *
3967  */
3968 static void
3969 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3970                             const struct GNUNET_MessageHeader *message)
3971 {
3972   const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3973       (const struct GNUNET_DHT_ControlMessage *) message;
3974 #if DEBUG_DHT
3975   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3976               "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3977               "CONTROL", ntohs(dht_control_msg->command));
3978 #endif
3979
3980   switch (ntohs(dht_control_msg->command))
3981   {
3982   case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3983     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3984     GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3985     break;
3986   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3987     if (ntohs(dht_control_msg->variable) > 0)
3988       malicious_get_frequency = ntohs(dht_control_msg->variable);
3989     if (malicious_get_frequency == 0)
3990       malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3991     if (malicious_getter != GNUNET_YES)
3992       GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3993     malicious_getter = GNUNET_YES;
3994     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
3995                "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3996     break;
3997   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3998     if (ntohs(dht_control_msg->variable) > 0)
3999       malicious_put_frequency = ntohs(dht_control_msg->variable);
4000     if (malicious_put_frequency == 0)
4001       malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4002     if (malicious_putter != GNUNET_YES)
4003       GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
4004     malicious_putter = GNUNET_YES;
4005     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4006                "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4007     break;
4008   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4009 #if DEBUG_DHT_ROUTING
4010     if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4011       dhtlog_handle->set_malicious(&my_identity);
4012 #endif
4013     malicious_dropper = GNUNET_YES;
4014     GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4015                "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4016     break;
4017   default:
4018     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, 
4019                "%s:%s Unknown control command type `%d'!\n", 
4020                my_short_id, "DHT",
4021                ntohs(dht_control_msg->command));
4022     break;
4023   }
4024
4025   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4026 }
4027
4028 /**
4029  * Handler for any generic DHT stop messages, calls the appropriate handler
4030  * depending on message type (if processed locally)
4031  *
4032  * @param cls closure for the service
4033  * @param client the client we received this message from
4034  * @param message the actual message received
4035  *
4036  */
4037 static void
4038 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4039                             const struct GNUNET_MessageHeader *message)
4040 {
4041
4042   const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4043     (const struct GNUNET_DHT_StopMessage *) message;
4044   struct DHTQueryRecord *record;
4045   struct DHTRouteSource *pos;
4046 #if DEBUG_DHT
4047   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4048               "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4049               "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4050 #endif
4051   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
4052   if (record != NULL)
4053     {
4054       pos = record->head;
4055
4056       while (pos != NULL)
4057         {
4058           if ((pos->client != NULL) && (pos->client->client_handle == client))
4059             {
4060               GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
4061               GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
4062             }
4063           pos = pos->next;
4064         }
4065     }
4066
4067   GNUNET_SERVER_receive_done (client, GNUNET_OK);
4068 }
4069
4070
4071 /**
4072  * Core handler for p2p route requests.
4073  */
4074 static int
4075 handle_dht_p2p_route_request (void *cls,
4076                               const struct GNUNET_PeerIdentity *peer,
4077                               const struct GNUNET_MessageHeader *message,
4078                               struct GNUNET_TIME_Relative latency, uint32_t distance)
4079 {
4080 #if DEBUG_DHT
4081   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4082               "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4083 #endif
4084   struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4085   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4086   struct DHT_MessageContext *message_context;
4087
4088   if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
4089   {
4090     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
4091     increment_stats("# route requests dropped due to high load");
4092     decrease_max_send_delay(get_max_send_delay());
4093     return GNUNET_YES;
4094   }
4095
4096   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4097     {
4098 #if DEBUG_PING
4099       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4100 #endif
4101       return GNUNET_YES;
4102     }
4103
4104   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4105     {
4106       GNUNET_break_op(0);
4107       return GNUNET_YES;
4108     }
4109   message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4110   message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4111   GNUNET_assert(message_context->bloom != NULL);
4112   message_context->hop_count = ntohl(incoming->hop_count);
4113   memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
4114   message_context->replication = ntohl(incoming->desired_replication_level);
4115   message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
4116   message_context->msg_options = ntohl(incoming->options);
4117   message_context->network_size = ntohl(incoming->network_size);
4118   message_context->peer = peer;
4119   message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4120   message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4121   route_message(cls, enc_msg, message_context);
4122   GNUNET_free(message_context);
4123   return GNUNET_YES;
4124 }
4125
4126
4127 /**
4128  * Core handler for p2p route results.
4129  */
4130 static int
4131 handle_dht_p2p_route_result (void *cls,
4132                              const struct GNUNET_PeerIdentity *peer,
4133                              const struct GNUNET_MessageHeader *message,
4134                              struct GNUNET_TIME_Relative latency, uint32_t distance)
4135 {
4136 #if DEBUG_DHT
4137   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4138               "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4139 #endif
4140   struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4141   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4142   struct DHT_MessageContext message_context;
4143
4144   if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4145     {
4146       GNUNET_break_op(0);
4147       return GNUNET_YES;
4148     }
4149
4150   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4151   // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4152   message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4153   GNUNET_assert(message_context.bloom != NULL);
4154   memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
4155   message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
4156   message_context.msg_options = ntohl(incoming->options);
4157   message_context.hop_count = ntohl(incoming->hop_count);
4158   message_context.peer = peer;
4159   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
4160   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4161   route_result_message(cls, enc_msg, &message_context);
4162   return GNUNET_YES;
4163 }
4164
4165
4166 /**
4167  * Receive the HELLO from transport service,
4168  * free current and replace if necessary.
4169  *
4170  * @param cls NULL
4171  * @param message HELLO message of peer
4172  */
4173 static void
4174 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4175 {
4176 #if DEBUG_DHT
4177   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4178               "Received our `%s' from transport service\n",
4179               "HELLO");
4180 #endif
4181
4182   GNUNET_assert (message != NULL);
4183   GNUNET_free_non_null(my_hello);
4184   my_hello = GNUNET_malloc(ntohs(message->size));
4185   memcpy(my_hello, message, ntohs(message->size));
4186 }
4187
4188
4189 /**
4190  * Task run during shutdown.
4191  *
4192  * @param cls unused
4193  * @param tc unused
4194  */
4195 static void
4196 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4197 {
4198   int bucket_count;
4199   struct PeerInfo *pos;
4200   if (transport_handle != NULL)
4201   {
4202     GNUNET_free_non_null(my_hello);
4203     GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4204     GNUNET_TRANSPORT_disconnect(transport_handle);
4205   }
4206
4207   for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4208     {
4209       while (k_buckets[bucket_count].head != NULL)
4210         {
4211           pos = k_buckets[bucket_count].head;
4212 #if DEBUG_DHT
4213           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4214                       "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4215 #endif
4216           delete_peer(pos, bucket_count);
4217         }
4218     }
4219   if (coreAPI != NULL)
4220     {
4221 #if DEBUG_DHT
4222       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4223                   "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4224 #endif
4225       GNUNET_CORE_disconnect (coreAPI);
4226     }
4227   if (datacache != NULL)
4228     {
4229 #if DEBUG_DHT
4230       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4231                   "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4232 #endif
4233       GNUNET_DATACACHE_destroy (datacache);
4234     }
4235
4236   if (stats != NULL)
4237     {
4238       GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4239     }
4240
4241   if (dhtlog_handle != NULL)
4242     GNUNET_DHTLOG_disconnect(dhtlog_handle);
4243
4244   GNUNET_free_non_null(my_short_id);
4245 }
4246
4247
4248 /**
4249  * To be called on core init/fail.
4250  *
4251  * @param cls service closure
4252  * @param server handle to the server for this service
4253  * @param identity the public identity of this peer
4254  * @param publicKey the public key of this peer
4255  */
4256 void
4257 core_init (void *cls,
4258            struct GNUNET_CORE_Handle *server,
4259            const struct GNUNET_PeerIdentity *identity,
4260            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4261 {
4262
4263   if (server == NULL)
4264     {
4265 #if DEBUG_DHT
4266   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4267               "%s: Connection to core FAILED!\n", "dht",
4268               GNUNET_i2s (identity));
4269 #endif
4270       GNUNET_SCHEDULER_cancel (sched, cleanup_task);
4271       GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
4272       return;
4273     }
4274 #if DEBUG_DHT
4275   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4276               "%s: Core connection initialized, I am peer: %s\n", "dht",
4277               GNUNET_i2s (identity));
4278 #endif
4279
4280   /* Copy our identity so we can use it */
4281   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4282   if (my_short_id != NULL)
4283     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4284   my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4285   /* Set the server to local variable */
4286   coreAPI = server;
4287
4288   if (dhtlog_handle != NULL)
4289     dhtlog_handle->insert_node (NULL, &my_identity);
4290 }
4291
4292
4293 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4294   {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4295   {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4296   {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4297   {NULL, NULL, 0, 0}
4298 };
4299
4300
4301 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4302   {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4303   {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4304   {NULL, 0, 0}
4305 };
4306
4307 /**
4308  * Method called whenever a peer connects.
4309  *
4310  * @param cls closure
4311  * @param peer peer identity this notification is about
4312  * @param latency reported latency of the connection with peer
4313  * @param distance reported distance (DV) to peer
4314  */
4315 void handle_core_connect (void *cls,
4316                           const struct GNUNET_PeerIdentity * peer,
4317                           struct GNUNET_TIME_Relative latency,
4318                           uint32_t distance)
4319 {
4320   struct PeerInfo *ret;
4321
4322 #if DEBUG_DHT
4323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4324               "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4325 #endif
4326
4327   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4328     {
4329       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));
4330       return;
4331     }
4332
4333   if (datacache != NULL)
4334     GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
4335   ret = try_add_peer(peer,
4336                      find_current_bucket(&peer->hashPubKey),
4337                      latency,
4338                      distance);
4339   if (ret != NULL)
4340     {
4341       newly_found_peers++;
4342       GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4343     }
4344 #if DEBUG_DHT
4345     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4346                 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4347 #endif
4348 }
4349
4350 /**
4351  * Method called whenever a peer disconnects.
4352  *
4353  * @param cls closure
4354  * @param peer peer identity this notification is about
4355  */
4356 void handle_core_disconnect (void *cls,
4357                              const struct
4358                              GNUNET_PeerIdentity * peer)
4359 {
4360   struct PeerInfo *to_remove;
4361   int current_bucket;
4362
4363   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");
4364
4365   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4366     {
4367       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));
4368       return;
4369     }
4370   increment_stats(STAT_DISCONNECTS);
4371   GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4372   to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4373   GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4374   current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4375   delete_peer(to_remove, current_bucket);
4376 }
4377
4378 /**
4379  * Process dht requests.
4380  *
4381  * @param cls closure
4382  * @param scheduler scheduler to use
4383  * @param server the initialized server
4384  * @param c configuration to use
4385  */
4386 static void
4387 run (void *cls,
4388      struct GNUNET_SCHEDULER_Handle *scheduler,
4389      struct GNUNET_SERVER_Handle *server,
4390      const struct GNUNET_CONFIGURATION_Handle *c)
4391 {
4392   struct GNUNET_TIME_Relative next_send_time;
4393   unsigned long long temp_config_num;
4394   char *converge_modifier_buf;
4395   sched = scheduler;
4396   cfg = c;
4397   datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4398   GNUNET_SERVER_add_handlers (server, plugin_handlers);
4399   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4400   coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4401                                  cfg,   /* Main configuration */
4402                                  GNUNET_TIME_UNIT_FOREVER_REL,
4403                                  NULL,  /* Closure passed to DHT functions */
4404                                  &core_init,    /* Call core_init once connected */
4405                                  &handle_core_connect,  /* Handle connects */
4406                                  &handle_core_disconnect,  /* remove peers on disconnects */
4407                                  NULL,  /* Do we care about "status" updates? */
4408                                  NULL,  /* Don't want notified about all incoming messages */
4409                                  GNUNET_NO,     /* For header only inbound notification */
4410                                  NULL,  /* Don't want notified about all outbound messages */
4411                                  GNUNET_NO,     /* For header only outbound notification */
4412                                  core_handlers);        /* Register these handlers */
4413
4414   if (coreAPI == NULL)
4415     return;
4416   transport_handle = GNUNET_TRANSPORT_connect(sched, cfg, 
4417                                               NULL, NULL, NULL, NULL, NULL);
4418   if (transport_handle != NULL)
4419     GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4420   else
4421     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4422
4423   lowest_bucket = MAX_BUCKETS - 1;
4424   forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4425   forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4426   all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4427   recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4428   GNUNET_assert(all_known_peers != NULL);
4429   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4430     {
4431       debug_routes = GNUNET_YES;
4432     }
4433
4434   if (GNUNET_YES ==
4435       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4436                                            "strict_kademlia"))
4437     {
4438       strict_kademlia = GNUNET_YES;
4439     }
4440
4441   if (GNUNET_YES ==
4442       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4443                                            "stop_on_closest"))
4444     {
4445       stop_on_closest = GNUNET_YES;
4446     }
4447
4448   if (GNUNET_YES ==
4449       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4450                                            "stop_found"))
4451     {
4452       stop_on_found = GNUNET_YES;
4453     }
4454
4455   if (GNUNET_YES ==
4456       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4457                                            "malicious_getter"))
4458     {
4459       malicious_getter = GNUNET_YES;
4460       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4461                                             "MALICIOUS_GET_FREQUENCY",
4462                                             &malicious_get_frequency))
4463         malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4464     }
4465
4466   if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4467                                         "MAX_HOPS",
4468                                         &max_hops))
4469     {
4470       max_hops = DEFAULT_MAX_HOPS;
4471     }
4472
4473   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4474                                                           "USE_MAX_HOPS"))
4475     {
4476       use_max_hops = GNUNET_YES;
4477     }
4478
4479   if (GNUNET_YES ==
4480       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4481                                            "malicious_putter"))
4482     {
4483       malicious_putter = GNUNET_YES;
4484       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4485                                             "MALICIOUS_PUT_FREQUENCY",
4486                                             &malicious_put_frequency))
4487         malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4488     }
4489
4490   dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
4491   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4492     {
4493       dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4494     }
4495
4496   if (GNUNET_YES ==
4497           GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4498                                                "malicious_dropper"))
4499     {
4500       malicious_dropper = GNUNET_YES;
4501     }
4502
4503   if (GNUNET_YES ==
4504         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4505                                              "republish"))
4506     do_republish = GNUNET_NO;
4507
4508   if (GNUNET_NO ==
4509         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4510                                              "do_find_peer"))
4511     {
4512       do_find_peer = GNUNET_NO;
4513     }
4514   else
4515     do_find_peer = GNUNET_YES;
4516
4517   if (GNUNET_YES ==
4518         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4519                                              "use_real_distance"))
4520     use_real_distance = GNUNET_YES;
4521
4522   if (GNUNET_YES ==
4523       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4524                                            "mysql_logging_extended"))
4525     {
4526       debug_routes = GNUNET_YES;
4527       debug_routes_extended = GNUNET_YES;
4528     }
4529
4530 #if DEBUG_DHT_ROUTING
4531   if (GNUNET_YES == debug_routes)
4532     {
4533       dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4534       if (dhtlog_handle == NULL)
4535         {
4536           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4537                       "Could not connect to mysql logging server, logging will not happen!");
4538         }
4539     }
4540 #endif
4541
4542   converge_option = DHT_CONVERGE_SQUARE;
4543   if (GNUNET_YES ==
4544       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4545                                            "converge_linear"))
4546     {
4547       converge_option = DHT_CONVERGE_LINEAR;
4548     }
4549   else if (GNUNET_YES ==
4550         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4551                                              "converge_exponential"))
4552     {
4553       converge_option = DHT_CONVERGE_EXPONENTIAL;
4554     }
4555   else if (GNUNET_YES ==
4556         GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4557                                              "converge_random"))
4558     {
4559       converge_option = DHT_CONVERGE_RANDOM;
4560     }
4561
4562   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4563     {
4564       if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4565         {
4566           GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4567           converge_modifier = 0.0;
4568         }
4569       GNUNET_free(converge_modifier_buf);
4570     }
4571
4572   stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4573
4574   if (stats != NULL)
4575     {
4576       GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4577       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4578       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4579       GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4580       GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4581       GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4582       GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4583       GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4584       GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4585       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4586       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4587       GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4588       GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4589       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4590       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4591       GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4592       GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4593       GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4594       GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4595       GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4596     }
4597   /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4598   recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4599   recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4600   if (GNUNET_YES == do_find_peer)
4601   {
4602     next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4603                            GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4604                                                     (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4605     find_peer_context.start = GNUNET_TIME_absolute_get();
4606     GNUNET_SCHEDULER_add_delayed (sched,
4607                                   next_send_time,
4608                                   &send_find_peer_message, &find_peer_context);
4609   }
4610
4611   /* Scheduled the task to clean up when shutdown is called */
4612   cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4613                                                GNUNET_TIME_UNIT_FOREVER_REL,
4614                                                &shutdown_task, NULL);
4615 }
4616
4617 /**
4618  * The main function for the dht service.
4619  *
4620  * @param argc number of arguments from the command line
4621  * @param argv command line arguments
4622  * @return 0 ok, 1 on error
4623  */
4624 int
4625 main (int argc, char *const *argv)
4626 {
4627   return (GNUNET_OK ==
4628           GNUNET_SERVICE_run (argc,
4629                               argv,
4630                               "dht",
4631                               GNUNET_SERVICE_OPTION_NONE,
4632                               &run, NULL)) ? 0 : 1;
4633 }