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