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