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