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