minor dht alterations
[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 GNUNET_DHT_FindPeerMessage *find_peer_message;
1938   struct DHT_MessageContext *new_msg_ctx;
1939   struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
1940   size_t hello_size;
1941   size_t tsize;
1942   find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
1943 #if DEBUG_DHT
1944   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1945               "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
1946               my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
1947               ntohs (find_msg->size),
1948               sizeof (struct GNUNET_MessageHeader));
1949 #endif
1950   if (my_hello == NULL)
1951   {
1952 #if DEBUG_DHT
1953     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1954                 "`%s': Our HELLO is null, can't return.\n",
1955                 "DHT");
1956 #endif
1957     return;
1958   }
1959
1960   incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1961   if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
1962     {
1963       increment_stats(STAT_BLOOM_FIND_PEER);
1964       GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
1965       return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
1966     }
1967   GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
1968
1969   /* Simplistic find_peer functionality, always return our hello */
1970   hello_size = ntohs(my_hello->size);
1971   tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
1972
1973   if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1974     {
1975       GNUNET_break_op (0);
1976       return;
1977     }
1978
1979   find_peer_result = GNUNET_malloc (tsize);
1980   find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
1981   find_peer_result->size = htons (tsize);
1982   memcpy (&find_peer_result[1], my_hello, hello_size);
1983
1984   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1985               "`%s': Sending hello size %d to requesting peer.\n",
1986               "DHT", hello_size);
1987
1988   new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
1989   memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
1990   new_msg_ctx->peer = &my_identity;
1991   new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1992   new_msg_ctx->hop_count = 0;
1993   new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
1994   new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
1995   increment_stats(STAT_FIND_PEER_ANSWER);
1996   route_result_message(cls, find_peer_result, new_msg_ctx);
1997   GNUNET_free(new_msg_ctx);
1998 #if DEBUG_DHT_ROUTING
1999   if ((debug_routes) && (dhtlog_handle != NULL))
2000     {
2001       dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2002                                    message_context->hop_count, GNUNET_YES, &my_identity,
2003                                    message_context->key);
2004     }
2005 #endif
2006   GNUNET_free(find_peer_result);
2007 }
2008
2009
2010 /**
2011  * Server handler for initiating local dht put requests
2012  *
2013  * @param cls closure for service
2014  * @param msg the actual put message
2015  * @param message_context struct containing pertinent information about the request
2016  */
2017 static void
2018 handle_dht_put (void *cls,
2019                 const struct GNUNET_MessageHeader *msg,
2020                 struct DHT_MessageContext *message_context)
2021 {
2022   struct GNUNET_DHT_PutMessage *put_msg;
2023   size_t put_type;
2024   size_t data_size;
2025
2026   GNUNET_assert (ntohs (msg->size) >=
2027                  sizeof (struct GNUNET_DHT_PutMessage));
2028
2029
2030   put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2031   put_type = ntohs (put_msg->type);
2032
2033   if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2034     return;
2035
2036   data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2037 #if DEBUG_DHT
2038   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2039               "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2040               my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2041 #endif
2042 #if DEBUG_DHT_ROUTING
2043   if (message_context->hop_count == 0) /* Locally initiated request */
2044     {
2045       if ((debug_routes) && (dhtlog_handle != NULL))
2046         {
2047           dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2048                                        message_context->hop_count, GNUNET_NO, &my_identity,
2049                                        message_context->key);
2050         }
2051     }
2052 #endif
2053
2054   if (message_context->closest != GNUNET_YES)
2055     return;
2056
2057 #if DEBUG_DHT_ROUTING
2058   if ((debug_routes_extended) && (dhtlog_handle != NULL))
2059     {
2060       dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2061                                    message_context->hop_count, GNUNET_YES,
2062                                    &my_identity, message_context->key, message_context->peer,
2063                                    NULL);
2064     }
2065
2066   if ((debug_routes) && (dhtlog_handle != NULL))
2067     {
2068       dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2069                                    message_context->hop_count, GNUNET_YES, &my_identity,
2070                                    message_context->key);
2071     }
2072 #endif
2073
2074   increment_stats(STAT_PUTS_INSERTED);
2075   if (datacache != NULL)
2076     GNUNET_DATACACHE_put (datacache, message_context->key, data_size,
2077                           (char *) &put_msg[1], put_type,
2078                           GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2079   else
2080     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2081                 "`%s:%s': %s request received, but have no datacache!\n",
2082                 my_short_id, "DHT", "PUT");
2083 }
2084
2085 /**
2086  * Estimate the diameter of the network based
2087  * on how many buckets are currently in use.
2088  * Concept here is that the diameter of the network
2089  * is roughly the distance a message must travel in
2090  * order to reach its intended destination.  Since
2091  * at each hop we expect to get one bit closer, and
2092  * we have one bit per bucket, the number of buckets
2093  * in use should be the largest number of hops for
2094  * a sucessful message. (of course, this assumes we
2095  * know all peers in the network!)
2096  *
2097  * @return ballpark diameter figure
2098  */
2099 static unsigned int estimate_diameter()
2100 {
2101   return MAX_BUCKETS - lowest_bucket;
2102 }
2103
2104 /**
2105  * To how many peers should we (on average)
2106  * forward the request to obtain the desired
2107  * target_replication count (on average).
2108  *
2109  * Always 0, 1 or 2 (don't send, send once, split)
2110  */
2111 static unsigned int
2112 get_forward_count (unsigned int hop_count, size_t target_replication)
2113 {
2114   double target_count;
2115   unsigned int target_value;
2116   unsigned int diameter;
2117
2118   /**
2119    * If we are behaving in strict kademlia mode, send multiple initial requests,
2120    * but then only send to 1 or 0 peers.
2121    */
2122   if (strict_kademlia == GNUNET_YES)
2123     {
2124       if (hop_count == 0)
2125         return DHT_KADEMLIA_REPLICATION;
2126       else if (hop_count < MAX_HOPS)
2127         return 1;
2128       else
2129         return 0;
2130     }
2131
2132   /* FIXME: the smaller we think the network is the more lenient we should be for
2133    * routing right?  The estimation below only works if we think we have reasonably
2134    * full routing tables, which for our RR topologies may not be the case!
2135    */
2136   diameter = estimate_diameter ();
2137   if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2138     {
2139 #if DEBUG_DHT
2140       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2141                   "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2142                   "DHT", estimate_diameter(), lowest_bucket);
2143 #endif
2144       return 0;
2145     }
2146   else if (hop_count > MAX_HOPS)
2147     {
2148 #if DEBUG_DHT
2149       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2150                   "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2151                   "DHT");
2152 #endif
2153       return 0;
2154     }
2155   target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2156     target_replication / (target_replication * (hop_count + 1) + diameter);
2157   target_value = 0;
2158
2159 #if NONSENSE
2160   while (target_value < target_count)
2161     target_value++; /* target_value is ALWAYS 1 after this "loop" */
2162 #else
2163   target_value = 1;
2164 #endif
2165   if ((target_count + 1 - target_value) >
2166       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2167                                 RAND_MAX) / RAND_MAX)
2168     target_value++;
2169   return target_value;
2170 }
2171
2172 /*
2173  * Check whether my identity is closer than any known peers.
2174  *
2175  * @param target hash code to check closeness to
2176  *
2177  * Return GNUNET_YES if node location is closest, GNUNET_NO
2178  * otherwise.
2179  */
2180 int
2181 am_closest_peer (const GNUNET_HashCode * target)
2182 {
2183   int bits;
2184   int other_bits;
2185   int bucket_num;
2186   int count;
2187   struct PeerInfo *pos;
2188   unsigned int my_distance;
2189
2190   bucket_num = find_current_bucket(target);
2191   if (bucket_num == GNUNET_SYSERR) /* Same key! */
2192     return GNUNET_YES;
2193
2194   bits = matching_bits(&my_identity.hashPubKey, target);
2195   my_distance = distance(&my_identity.hashPubKey, target);
2196
2197   pos = k_buckets[bucket_num].head;
2198   count = 0;
2199   while ((pos != NULL) && (count < bucket_size))
2200     {
2201       other_bits = matching_bits(&pos->id.hashPubKey, target);
2202       if (other_bits > bits)
2203         return GNUNET_NO;
2204       else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2205         {
2206           return GNUNET_YES;
2207           /* FIXME: why not just return GNUNET_YES here?  We are certainly close. */
2208           /*if (distance(&pos->id.hashPubKey, target) < my_distance)
2209             return GNUNET_NO;*/
2210         }
2211       pos = pos->next;
2212     }
2213
2214 #if DEBUG_TABLE
2215   GNUNET_GE_LOG (coreAPI->ectx,
2216                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2217                  GNUNET_GE_BULK, "closest peer\n");
2218   printPeerBits (&closest);
2219   GNUNET_GE_LOG (coreAPI->ectx,
2220                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2221                  GNUNET_GE_BULK, "me\n");
2222   printPeerBits (coreAPI->my_identity);
2223   GNUNET_GE_LOG (coreAPI->ectx,
2224                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2225                  GNUNET_GE_BULK, "key\n");
2226   printKeyBits (target);
2227   GNUNET_GE_LOG (coreAPI->ectx,
2228                  GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2229                  GNUNET_GE_BULK,
2230                  "closest peer inverse distance is %u, mine is %u\n",
2231                  inverse_distance (target, &closest.hashPubKey),
2232                  inverse_distance (target,
2233                                    &coreAPI->my_identity->hashPubKey));
2234 #endif
2235
2236   /* No peers closer, we are the closest! */
2237   return GNUNET_YES;
2238
2239 }
2240
2241 /**
2242  * Select a peer from the routing table that would be a good routing
2243  * destination for sending a message for "target".  The resulting peer
2244  * must not be in the set of blocked peers.<p>
2245  *
2246  * Note that we should not ALWAYS select the closest peer to the
2247  * target, peers further away from the target should be chosen with
2248  * exponentially declining probability.
2249  *
2250  * @param target the key we are selecting a peer to route to
2251  * @param bloom a bloomfilter containing entries this request has seen already
2252  *
2253  * @return Peer to route to, or NULL on error
2254  */
2255 static struct PeerInfo *
2256 select_peer (const GNUNET_HashCode * target,
2257              struct GNUNET_CONTAINER_BloomFilter *bloom)
2258 {
2259   unsigned int distance;
2260   unsigned int bc;
2261   unsigned int count;
2262   struct PeerInfo *pos;
2263   struct PeerInfo *chosen;
2264   unsigned long long largest_distance;
2265   unsigned long long total_distance;
2266   unsigned long long selected;
2267
2268   if (strict_kademlia == GNUNET_YES)
2269     {
2270       largest_distance = 0;
2271       chosen = NULL;
2272       for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2273         {
2274           pos = k_buckets[bc].head;
2275           count = 0;
2276           while ((pos != NULL) && (count < bucket_size))
2277             {
2278               /* If we are doing strict Kademlia like routing, then checking the bloomfilter is basically cheating! */
2279               if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2280                 {
2281                   distance = inverse_distance (target, &pos->id.hashPubKey);
2282                   if (distance > largest_distance)
2283                     {
2284                       chosen = pos;
2285                       largest_distance = distance;
2286                     }
2287                 }
2288               count++;
2289               pos = pos->next;
2290             }
2291         }
2292
2293       if ((largest_distance > 0) && (chosen != NULL))
2294         {
2295           GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2296           return chosen;
2297         }
2298       else
2299         {
2300           return NULL;
2301         }
2302     }
2303   else
2304     {
2305       /* GNUnet-style */
2306       total_distance = 0;
2307       for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2308         {
2309           pos = k_buckets[bc].head;
2310           count = 0;
2311           while ((pos != NULL) && (count < bucket_size))
2312             {
2313               if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2314                 total_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2315   #if DEBUG_DHT > 1
2316               GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2317                           "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2318                           my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2319   #endif
2320               pos = pos->next;
2321               count++;
2322             }
2323         }
2324       if (total_distance == 0)
2325         {
2326           return NULL;
2327         }
2328
2329       selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2330       for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2331         {
2332           pos = k_buckets[bc].head;
2333           count = 0;
2334           while ((pos != NULL) && (count < bucket_size))
2335             {
2336               if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2337                 {
2338                   distance = inverse_distance (target, &pos->id.hashPubKey);
2339                   if (distance > selected)
2340                     return pos;
2341                   selected -= distance;
2342                 }
2343               else
2344                 {
2345   #if DEBUG_DHT
2346                   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2347                               "`%s:%s': peer %s matches bloomfilter.\n",
2348                               my_short_id, "DHT", GNUNET_i2s(&pos->id));
2349   #endif
2350                 }
2351               pos = pos->next;
2352               count++;
2353             }
2354         }
2355   #if DEBUG_DHT
2356         GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2357                     "`%s:%s': peer %s matches bloomfilter.\n",
2358                     my_short_id, "DHT", GNUNET_i2s(&pos->id));
2359   #endif
2360       return NULL;
2361     }
2362 }
2363
2364
2365 /**
2366  * Task used to remove forwarding entries, either
2367  * after timeout, when full, or on shutdown.
2368  *
2369  * @param cls the entry to remove
2370  * @param tc context, reason, etc.
2371  */
2372 static void
2373 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2374 {
2375   struct DHTRouteSource *source_info = cls;
2376   struct DHTQueryRecord *record;
2377   source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2378   record = source_info->record;
2379   GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2380
2381   if (record->head == NULL) /* No more entries in DLL */
2382     {
2383       GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2384       GNUNET_free(record);
2385     }
2386   GNUNET_free(source_info);
2387 }
2388
2389 /**
2390  * Remember this routing request so that if a reply is
2391  * received we can either forward it to the correct peer
2392  * or return the result locally.
2393  *
2394  * @param cls DHT service closure
2395  * @param msg_ctx Context of the route request
2396  *
2397  * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2398  */
2399 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2400 {
2401   struct DHTQueryRecord *record;
2402   struct DHTRouteSource *source_info;
2403   struct DHTRouteSource *pos;
2404   struct GNUNET_TIME_Absolute now;
2405   unsigned int current_size;
2406
2407   current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2408   while (current_size >= MAX_OUTSTANDING_FORWARDS)
2409     {
2410       source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2411       record = source_info->record;
2412       GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2413       if (record->head == NULL) /* No more entries in DLL */
2414         {
2415           GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2416           GNUNET_free(record);
2417         }
2418       GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2419       GNUNET_free(source_info);
2420       current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2421     }
2422   now = GNUNET_TIME_absolute_get();
2423   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, msg_ctx->key);
2424   if (record != NULL) /* Already know this request! */
2425     {
2426       pos = record->head;
2427       while (pos != NULL)
2428         {
2429           if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
2430             break; /* Already have this peer in reply list! */
2431           pos = pos->next;
2432         }
2433       if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
2434         {
2435           GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
2436           return GNUNET_NO;
2437         }
2438     }
2439   else
2440     {
2441       record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
2442       GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2443       memcpy(&record->key, msg_ctx->key, sizeof(GNUNET_HashCode));
2444     }
2445
2446   source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
2447   source_info->record = record;
2448   source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
2449   memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
2450   GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
2451   if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
2452     {
2453       source_info->client = msg_ctx->client;
2454       now = GNUNET_TIME_absolute_get_forever();
2455     }
2456   source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
2457 #if DEBUG_DHT > 1
2458       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2459                   "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
2460                   "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
2461 #endif
2462   return GNUNET_YES;
2463 }
2464
2465
2466 /**
2467  * Main function that handles whether or not to route a message to other
2468  * peers.
2469  *
2470  * @param cls closure for dht service (NULL)
2471  * @param msg the message to be routed
2472  * @param message_context the context containing all pertinent information about the message
2473  *
2474  * @return the number of peers the message was routed to,
2475  *         GNUNET_SYSERR on failure
2476  */
2477 static int route_message(void *cls,
2478                          const struct GNUNET_MessageHeader *msg,
2479                          struct DHT_MessageContext *message_context)
2480 {
2481   int i;
2482   struct PeerInfo *selected;
2483   struct PeerInfo *nearest;
2484   unsigned int forward_count;
2485 #if DEBUG_DHT
2486   char *nearest_buf;
2487 #endif
2488 #if DEBUG_DHT_ROUTING
2489   int ret;
2490 #endif
2491
2492   if (malicious_dropper == GNUNET_YES)
2493     {
2494 #if DEBUG_DHT_ROUTING
2495       if ((debug_routes_extended) && (dhtlog_handle != NULL))
2496         {
2497           dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2498                                        message_context->hop_count, GNUNET_SYSERR,
2499                                        &my_identity, message_context->key, message_context->peer,
2500                                        NULL);
2501         }
2502 #endif
2503       if (message_context->bloom != NULL)
2504         GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2505       return 0;
2506     }
2507
2508   increment_stats(STAT_ROUTES);
2509   message_context->closest = am_closest_peer(message_context->key);
2510   forward_count = get_forward_count(message_context->hop_count, message_context->replication);
2511   nearest = find_closest_peer(message_context->key);
2512
2513   if (message_context->bloom == NULL)
2514     message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2515
2516   if ((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
2517 /*      || ((strict_kademlia == GNUNET_YES) && (message_context->closest == GNUNET_YES))) */
2518     forward_count = 0;
2519
2520 #if DEBUG_DHT_ROUTING
2521   if (forward_count == 0)
2522     ret = GNUNET_SYSERR;
2523   else
2524     ret = GNUNET_NO;
2525
2526   if ((debug_routes_extended) && (dhtlog_handle != NULL))
2527     {
2528       dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2529                                    message_context->hop_count, ret,
2530                                    &my_identity, message_context->key, message_context->peer,
2531                                    NULL);
2532     }
2533 #endif
2534
2535   switch (ntohs(msg->type))
2536     {
2537     case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
2538       cache_response (cls, message_context);
2539       if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
2540         forward_count = 0;
2541       break;
2542     case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
2543       increment_stats(STAT_PUTS);
2544       handle_dht_put (cls, msg, message_context);
2545       break;
2546     case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
2547       increment_stats(STAT_FIND_PEER);
2548       if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
2549       {
2550         cache_response (cls, message_context);
2551         if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
2552           handle_dht_find_peer (cls, msg, message_context);
2553       }
2554 #if DEBUG_DHT_ROUTING
2555       if (message_context->hop_count == 0) /* Locally initiated request */
2556         {
2557           if ((debug_routes) && (dhtlog_handle != NULL))
2558             {
2559               dhtlog_handle->insert_dhtkey(NULL, message_context->key);
2560               dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2561                                            message_context->hop_count, GNUNET_NO, &my_identity,
2562                                            message_context->key);
2563             }
2564         }
2565 #endif
2566       break;
2567     default:
2568       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2569                   "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
2570     }
2571
2572   GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2573 #if 0
2574   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent->hashmap, message_context->key))
2575     {
2576       if (GNUNET_SYSERR = GNUNET_CONTAINER_multihashmap_get_multiple (recent->hashmap, message_context->key, &find_matching_recent, &message_context)) /* Have too recently seen this request! */
2577         {
2578           forward_count = 0;
2579         }
2580       else /* Exact match not found, but same key found */
2581         {
2582           recent_req = GNUNET_CONTAINER_multihashmap_get(recent->hashmap, message_context->key);
2583         }
2584     }
2585   else
2586     {
2587       recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
2588       recent_req->uid = message_context->unique_id;
2589       memcmp(&recent_req->key, message_context->key, sizeof(GNUNET_HashCode));
2590       recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
2591       GNUNET_CONTAINER_heap_insert(recent->minHeap, recent_req, GNUNET_TIME_absolute_get());
2592       GNUNET_CONTAINER_multihashmap_put(recent->hashmap, message_context->key, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2593     }
2594
2595   if (GNUNET_CONTAINER_multihashmap_size(recent->hashmap) > DHT_MAX_RECENT)
2596     {
2597       remove_oldest_recent();
2598     }
2599 #endif
2600
2601   for (i = 0; i < forward_count; i++)
2602     {
2603       selected = select_peer(message_context->key, message_context->bloom);
2604
2605       if (selected != NULL)
2606         {
2607           GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
2608 #if DEBUG_DHT_ROUTING > 1
2609           nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
2610           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2611                       "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
2612                       "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));
2613           GNUNET_free(nearest_buf);
2614 #endif
2615           if ((debug_routes_extended) && (dhtlog_handle != NULL))
2616             {
2617               dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2618                                            message_context->hop_count, GNUNET_NO,
2619                                            &my_identity, message_context->key, message_context->peer,
2620                                            &selected->id);
2621             }
2622           forward_message(cls, msg, selected, message_context);
2623         }
2624       else
2625         {
2626 #if DEBUG_DHT
2627           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2628                       "`%s:%s': No peers selected for forwarding.\n", my_short_id,
2629                       "DHT");
2630 #endif
2631         }
2632     }
2633 #if DEBUG_DHT_ROUTING > 1
2634   if (forward_count == 0)
2635     {
2636       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2637                   "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
2638                   "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2639     }
2640 #endif
2641
2642   if (message_context->bloom != NULL)
2643     GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2644
2645   return forward_count;
2646 }
2647
2648 /**
2649  * Find a client if it exists, add it otherwise.
2650  *
2651  * @param client the server handle to the client
2652  *
2653  * @return the client if found, a new client otherwise
2654  */
2655 static struct ClientList *
2656 find_active_client (struct GNUNET_SERVER_Client *client)
2657 {
2658   struct ClientList *pos = client_list;
2659   struct ClientList *ret;
2660
2661   while (pos != NULL)
2662     {
2663       if (pos->client_handle == client)
2664         return pos;
2665       pos = pos->next;
2666     }
2667
2668   ret = GNUNET_malloc (sizeof (struct ClientList));
2669   ret->client_handle = client;
2670   ret->next = client_list;
2671   client_list = ret;
2672   return ret;
2673 }
2674
2675 /**
2676  * Task to send a malicious put message across the network.
2677  *
2678  * @param cls closure for this task
2679  * @param tc the context under which the task is running
2680  */
2681 static void
2682 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2683 {
2684   static struct GNUNET_DHT_PutMessage put_message;
2685   static struct DHT_MessageContext message_context;
2686   static GNUNET_HashCode key;
2687   unsigned int mcsize;
2688   uint32_t random_key;
2689
2690   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2691     return;
2692
2693   put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
2694   put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
2695   put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2696   put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
2697   mcsize = sizeof(struct DHT_MessageContext) + sizeof(GNUNET_HashCode);
2698   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2699   message_context.client = NULL;
2700   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2701   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2702   message_context.key = &key;
2703   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2704   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2705   message_context.msg_options = ntohl (0);
2706   message_context.network_size = estimate_diameter();
2707   message_context.peer = &my_identity;
2708   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
2709   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
2710   if (dhtlog_handle != NULL)
2711     dhtlog_handle->insert_dhtkey(NULL, &key);
2712   increment_stats(STAT_PUT_START);
2713   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2714   route_message(NULL, &put_message.header, &message_context);
2715   GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
2716
2717 }
2718
2719 /**
2720  * Task to send a malicious put message across the network.
2721  *
2722  * @param cls closure for this task
2723  * @param tc the context under which the task is running
2724  */
2725 static void
2726 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2727 {
2728   static struct GNUNET_DHT_GetMessage get_message;
2729   static struct DHT_MessageContext message_context;
2730   static GNUNET_HashCode key;
2731   unsigned int mcsize;
2732   uint32_t random_key;
2733
2734   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2735     return;
2736
2737   get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
2738   get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
2739   get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2740   mcsize = sizeof(struct DHT_MessageContext) + sizeof(GNUNET_HashCode);
2741   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2742   message_context.client = NULL;
2743   random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2744   GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2745   message_context.key = &key;
2746   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2747   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2748   message_context.msg_options = ntohl (0);
2749   message_context.network_size = estimate_diameter();
2750   message_context.peer = &my_identity;
2751   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
2752   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
2753   if (dhtlog_handle != NULL)
2754     dhtlog_handle->insert_dhtkey(NULL, &key);
2755   increment_stats(STAT_GET_START);
2756   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2757   route_message(NULL, &get_message.header, &message_context);
2758   GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
2759 }
2760
2761 #if DO_FIND_PEER
2762
2763
2764 /**
2765  * Iterator over hash map entries.
2766  *
2767  * @param cls closure
2768  * @param key current key code
2769  * @param value value in the hash map
2770  * @return GNUNET_YES if we should continue to
2771  *         iterate,
2772  *         GNUNET_NO if not.
2773  */
2774 static int
2775 add_known_to_bloom (void *cls,
2776                     const GNUNET_HashCode * key,
2777                     void *value)
2778 {
2779   struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
2780   GNUNET_CONTAINER_bloomfilter_add (bloom, key);
2781   return GNUNET_YES;
2782 }
2783
2784 /**
2785  * Task to send a find peer message for our own peer identifier
2786  * so that we can find the closest peers in the network to ourselves
2787  * and attempt to connect to them.
2788  *
2789  * @param cls closure for this task
2790  * @param tc the context under which the task is running
2791  */
2792 static void
2793 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2794 {
2795   struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
2796   struct DHT_MessageContext message_context;
2797   int ret;
2798   struct GNUNET_TIME_Relative next_send_time;
2799   struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
2800
2801   if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2802     return;
2803
2804   increment_stats(STAT_FIND_PEER_START);
2805
2806   find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
2807   find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
2808   find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
2809   temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2810   GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
2811   GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
2812   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2813   message_context.key = &my_identity.hashPubKey;
2814   message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
2815   message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2816   message_context.msg_options = ntohl (DHT_DEFAULT_FIND_PEER_OPTIONS);
2817   message_context.network_size = estimate_diameter();
2818   message_context.peer = &my_identity;
2819   message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
2820   message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
2821
2822   ret = route_message(NULL, &find_peer_msg->header, &message_context);
2823   GNUNET_free(find_peer_msg);
2824   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2825               "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
2826               "FIND PEER", ret);
2827   if (newly_found_peers < bucket_size)
2828     {
2829       next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
2830                               GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
2831                                                        DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
2832     }
2833   else
2834     {
2835       next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
2836                              GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
2837                                                       DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
2838     }
2839   newly_found_peers = 0;
2840   GNUNET_SCHEDULER_add_delayed (sched,
2841                                 next_send_time,
2842                                 &send_find_peer_message, NULL);
2843 }
2844 #endif
2845
2846 /**
2847  * Handler for any generic DHT messages, calls the appropriate handler
2848  * depending on message type, sends confirmation if responses aren't otherwise
2849  * expected.
2850  *
2851  * @param cls closure for the service
2852  * @param client the client we received this message from
2853  * @param message the actual message received
2854  */
2855 static void
2856 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
2857                                 const struct GNUNET_MessageHeader *message)
2858 {
2859   const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
2860   const struct GNUNET_MessageHeader *enc_msg;
2861   struct DHT_MessageContext message_context;
2862   size_t enc_type;
2863
2864   enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
2865   enc_type = ntohs (enc_msg->type);
2866
2867 #if DEBUG_DHT
2868   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2869               "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
2870               my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
2871               GNUNET_ntohll (dht_msg->unique_id));
2872 #endif
2873 #if DEBUG_DHT_ROUTING
2874   if (dhtlog_handle != NULL)
2875     dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
2876 #endif
2877   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2878   message_context.client = find_active_client (client);
2879   message_context.key = &dht_msg->key;
2880   message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
2881   message_context.replication = ntohl (dht_msg->desired_replication_level);
2882   message_context.msg_options = ntohl (dht_msg->options);
2883   message_context.network_size = estimate_diameter();
2884   message_context.peer = &my_identity;
2885   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
2886   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
2887   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
2888     increment_stats(STAT_GET_START);
2889   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
2890     increment_stats(STAT_PUT_START);
2891   else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
2892     increment_stats(STAT_FIND_PEER_START);
2893
2894   route_message(cls, enc_msg, &message_context);
2895
2896   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2897
2898 }
2899
2900 /**
2901  * Handler for any locally received DHT control messages,
2902  * sets malicious flags mostly for now.
2903  *
2904  * @param cls closure for the service
2905  * @param client the client we received this message from
2906  * @param message the actual message received
2907  *
2908  */
2909 static void
2910 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
2911                             const struct GNUNET_MessageHeader *message)
2912 {
2913   const struct GNUNET_DHT_ControlMessage *dht_control_msg =
2914       (const struct GNUNET_DHT_ControlMessage *) message;
2915 #if DEBUG_DHT
2916   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2917               "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
2918               "CONTROL", ntohs(dht_control_msg->command));
2919 #endif
2920
2921   switch (ntohs(dht_control_msg->command))
2922   {
2923   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
2924     if (ntohs(dht_control_msg->variable) > 0)
2925       malicious_get_frequency = ntohs(dht_control_msg->variable);
2926     if (malicious_get_frequency == 0)
2927       malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
2928     if (malicious_getter != GNUNET_YES)
2929       GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
2930     malicious_getter = GNUNET_YES;
2931     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
2932     break;
2933   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
2934     if (ntohs(dht_control_msg->variable) > 0)
2935       malicious_put_frequency = ntohs(dht_control_msg->variable);
2936     if (malicious_put_frequency == 0)
2937       malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
2938     if (malicious_putter != GNUNET_YES)
2939       GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
2940     malicious_putter = GNUNET_YES;
2941     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
2942     break;
2943   case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
2944     if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
2945       dhtlog_handle->set_malicious(&my_identity);
2946     malicious_dropper = GNUNET_YES;
2947     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
2948     break;
2949   default:
2950     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
2951   }
2952
2953   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2954 }
2955
2956 /**
2957  * Handler for any generic DHT stop messages, calls the appropriate handler
2958  * depending on message type (if processed locally)
2959  *
2960  * @param cls closure for the service
2961  * @param client the client we received this message from
2962  * @param message the actual message received
2963  *
2964  */
2965 static void
2966 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
2967                             const struct GNUNET_MessageHeader *message)
2968 {
2969
2970   const struct GNUNET_DHT_StopMessage *dht_stop_msg =
2971     (const struct GNUNET_DHT_StopMessage *) message;
2972   struct DHTQueryRecord *record;
2973   struct DHTRouteSource *pos;
2974   uint64_t uid;
2975 #if DEBUG_DHT
2976   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2977               "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
2978               "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
2979 #endif
2980
2981   uid = GNUNET_ntohll(dht_stop_msg->unique_id);
2982
2983   record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
2984   if (record != NULL)
2985     {
2986       pos = record->head;
2987
2988       while (pos != NULL)
2989         {
2990           if ((pos->client != NULL) && (pos->client->client_handle == client))
2991             {
2992               GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
2993               GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
2994             }
2995           pos = pos->next;
2996         }
2997     }
2998
2999   GNUNET_SERVER_receive_done (client, GNUNET_OK);
3000 }
3001
3002
3003 /**
3004  * Core handler for p2p route requests.
3005  */
3006 static int
3007 handle_dht_p2p_route_request (void *cls,
3008                               const struct GNUNET_PeerIdentity *peer,
3009                               const struct GNUNET_MessageHeader *message,
3010                               struct GNUNET_TIME_Relative latency, uint32_t distance)
3011 {
3012 #if DEBUG_DHT
3013   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3014               "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3015 #endif
3016   struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3017   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3018   struct DHT_MessageContext *message_context;
3019
3020   if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3021     {
3022 #if DEBUG_PING
3023       GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3024 #endif
3025       return GNUNET_YES;
3026     }
3027
3028   if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3029     {
3030       GNUNET_break_op(0);
3031       return GNUNET_YES;
3032     }
3033   message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3034   message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3035   GNUNET_assert(message_context->bloom != NULL);
3036   message_context->hop_count = ntohl(incoming->hop_count);
3037   message_context->key = &incoming->key;
3038   message_context->replication = ntohl(incoming->desired_replication_level);
3039   message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3040   message_context->msg_options = ntohl(incoming->options);
3041   message_context->network_size = ntohl(incoming->network_size);
3042   message_context->peer = peer;
3043   message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3044   message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3045   route_message(cls, enc_msg, message_context);
3046   GNUNET_free(message_context);
3047   return GNUNET_YES;
3048 }
3049
3050
3051 /**
3052  * Core handler for p2p route results.
3053  */
3054 static int
3055 handle_dht_p2p_route_result (void *cls,
3056                              const struct GNUNET_PeerIdentity *peer,
3057                              const struct GNUNET_MessageHeader *message,
3058                              struct GNUNET_TIME_Relative latency, uint32_t distance)
3059 {
3060 #if DEBUG_DHT
3061   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3062               "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3063 #endif
3064   struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3065   struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3066   struct DHT_MessageContext message_context;
3067
3068   if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3069     {
3070       GNUNET_break_op(0);
3071       return GNUNET_YES;
3072     }
3073
3074   memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3075   message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3076   GNUNET_assert(message_context.bloom != NULL);
3077   message_context.key = &incoming->key;
3078   message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3079   message_context.msg_options = ntohl(incoming->options);
3080   message_context.hop_count = ntohl(incoming->hop_count);
3081   message_context.peer = peer;
3082   message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3083   message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3084   route_result_message(cls, enc_msg, &message_context);
3085   return GNUNET_YES;
3086 }
3087
3088
3089 /**
3090  * Receive the HELLO from transport service,
3091  * free current and replace if necessary.
3092  *
3093  * @param cls NULL
3094  * @param message HELLO message of peer
3095  */
3096 static void
3097 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3098 {
3099 #if DEBUG_DHT
3100   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3101               "Received our `%s' from transport service\n",
3102               "HELLO");
3103 #endif
3104
3105   GNUNET_assert (message != NULL);
3106   GNUNET_free_non_null(my_hello);
3107   my_hello = GNUNET_malloc(ntohs(message->size));
3108   memcpy(my_hello, message, ntohs(message->size));
3109 }
3110
3111
3112 /**
3113  * Task run during shutdown.
3114  *
3115  * @param cls unused
3116  * @param tc unused
3117  */
3118 static void
3119 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3120 {
3121   int bucket_count;
3122   struct PeerInfo *pos;
3123   if (transport_handle != NULL)
3124   {
3125     GNUNET_free_non_null(my_hello);
3126     GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3127     GNUNET_TRANSPORT_disconnect(transport_handle);
3128   }
3129
3130   for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3131     {
3132       while (k_buckets[bucket_count].head != NULL)
3133         {
3134           pos = k_buckets[bucket_count].head;
3135 #if DEBUG_DHT
3136           GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3137                       "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3138 #endif
3139           delete_peer(pos, bucket_count);
3140         }
3141     }
3142   if (coreAPI != NULL)
3143     {
3144 #if DEBUG_DHT
3145       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3146                   "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3147 #endif
3148       GNUNET_CORE_disconnect (coreAPI);
3149     }
3150   if (datacache != NULL)
3151     {
3152 #if DEBUG_DHT
3153       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3154                   "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3155 #endif
3156       GNUNET_DATACACHE_destroy (datacache);
3157     }
3158
3159   if (stats != NULL)
3160     {
3161       GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3162     }
3163
3164   if (dhtlog_handle != NULL)
3165     GNUNET_DHTLOG_disconnect(dhtlog_handle);
3166
3167   GNUNET_free_non_null(my_short_id);
3168 }
3169
3170
3171 /**
3172  * To be called on core init/fail.
3173  *
3174  * @param cls service closure
3175  * @param server handle to the server for this service
3176  * @param identity the public identity of this peer
3177  * @param publicKey the public key of this peer
3178  */
3179 void
3180 core_init (void *cls,
3181            struct GNUNET_CORE_Handle *server,
3182            const struct GNUNET_PeerIdentity *identity,
3183            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3184 {
3185
3186   if (server == NULL)
3187     {
3188 #if DEBUG_DHT
3189   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3190               "%s: Connection to core FAILED!\n", "dht",
3191               GNUNET_i2s (identity));
3192 #endif
3193       GNUNET_SCHEDULER_cancel (sched, cleanup_task);
3194       GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3195       return;
3196     }
3197 #if DEBUG_DHT
3198   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3199               "%s: Core connection initialized, I am peer: %s\n", "dht",
3200               GNUNET_i2s (identity));
3201 #endif
3202
3203   /* Copy our identity so we can use it */
3204   memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3205   if (my_short_id != NULL)
3206     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3207   my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3208   /* Set the server to local variable */
3209   coreAPI = server;
3210
3211   if (dhtlog_handle != NULL)
3212     dhtlog_handle->insert_node (NULL, &my_identity);
3213 }
3214
3215
3216 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3217   {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3218   {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3219   {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
3220   {NULL, NULL, 0, 0}
3221 };
3222
3223
3224 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3225   {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
3226   {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
3227   {NULL, 0, 0}
3228 };
3229
3230 /**
3231  * Method called whenever a peer connects.
3232  *
3233  * @param cls closure
3234  * @param peer peer identity this notification is about
3235  * @param latency reported latency of the connection with peer
3236  * @param distance reported distance (DV) to peer
3237  */
3238 void handle_core_connect (void *cls,
3239                           const struct GNUNET_PeerIdentity * peer,
3240                           struct GNUNET_TIME_Relative latency,
3241                           uint32_t distance)
3242 {
3243   struct PeerInfo *ret;
3244
3245 #if DEBUG_DHT
3246   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3247               "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
3248 #endif
3249
3250   if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3251     {
3252       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));
3253       return;
3254     }
3255
3256   if (datacache != NULL)
3257     GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
3258   ret = try_add_peer(peer,
3259                      find_current_bucket(&peer->hashPubKey),
3260                      latency,
3261                      distance);
3262   if (ret != NULL)
3263     {
3264       newly_found_peers++;
3265       GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3266     }
3267 #if DEBUG_DHT
3268     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3269                 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
3270 #endif
3271 }
3272
3273 /**
3274  * Method called whenever a peer disconnects.
3275  *
3276  * @param cls closure
3277  * @param peer peer identity this notification is about
3278  */
3279 void handle_core_disconnect (void *cls,
3280                              const struct
3281                              GNUNET_PeerIdentity * peer)
3282 {
3283   struct PeerInfo *to_remove;
3284   int current_bucket;
3285
3286   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");
3287
3288   if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3289     {
3290       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));
3291       return;
3292     }
3293   increment_stats(STAT_DISCONNECTS);
3294   GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
3295   to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
3296   GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
3297   current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
3298   delete_peer(to_remove, current_bucket);
3299 }
3300
3301 /**
3302  * Process dht requests.
3303  *
3304  * @param cls closure
3305  * @param scheduler scheduler to use
3306  * @param server the initialized server
3307  * @param c configuration to use
3308  */
3309 static void
3310 run (void *cls,
3311      struct GNUNET_SCHEDULER_Handle *scheduler,
3312      struct GNUNET_SERVER_Handle *server,
3313      const struct GNUNET_CONFIGURATION_Handle *c)
3314 {
3315 #if DO_FIND_PEER
3316   struct GNUNET_TIME_Relative next_send_time;
3317 #endif
3318   sched = scheduler;
3319   cfg = c;
3320   datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
3321   GNUNET_SERVER_add_handlers (server, plugin_handlers);
3322   coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
3323                                  cfg,   /* Main configuration */
3324                                  GNUNET_TIME_UNIT_FOREVER_REL,
3325                                  NULL,  /* Closure passed to DHT functionas around? */
3326                                  &core_init,    /* Call core_init once connected */
3327                                  &handle_core_connect,  /* Handle connects */
3328                                  &handle_core_disconnect,  /* remove peers on disconnects */
3329                                  NULL,  /* Do we care about "status" updates? */
3330                                  NULL,  /* Don't want notified about all incoming messages */
3331                                  GNUNET_NO,     /* For header only inbound notification */
3332                                  NULL,  /* Don't want notified about all outbound messages */
3333                                  GNUNET_NO,     /* For header only outbound notification */
3334                                  core_handlers);        /* Register these handlers */
3335
3336   if (coreAPI == NULL)
3337     return;
3338   transport_handle = GNUNET_TRANSPORT_connect(sched, cfg, 
3339                                               NULL, NULL, NULL, NULL, NULL);
3340   if (transport_handle != NULL)
3341     GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
3342   else
3343     GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
3344
3345   lowest_bucket = MAX_BUCKETS - 1;
3346   forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
3347   forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3348   all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
3349   GNUNET_assert(all_known_peers != NULL);
3350   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
3351     {
3352       debug_routes = GNUNET_YES;
3353     }
3354
3355   if (GNUNET_YES ==
3356       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3357                                            "strict_kademlia"))
3358     {
3359       strict_kademlia = GNUNET_YES;
3360     }
3361
3362   if (GNUNET_YES ==
3363       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3364                                            "stop_on_closest"))
3365     {
3366       stop_on_closest = GNUNET_YES;
3367     }
3368
3369   if (GNUNET_YES ==
3370       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3371                                            "stop_found"))
3372     {
3373       stop_on_found = GNUNET_YES;
3374     }
3375
3376   if (GNUNET_YES ==
3377       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3378                                            "malicious_getter"))
3379     {
3380       malicious_getter = GNUNET_YES;
3381       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3382                                             "MALICIOUS_GET_FREQUENCY",
3383                                             &malicious_get_frequency))
3384         malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3385     }
3386
3387   if (GNUNET_YES ==
3388       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3389                                            "malicious_putter"))
3390     {
3391       malicious_putter = GNUNET_YES;
3392       if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3393                                             "MALICIOUS_PUT_FREQUENCY",
3394                                             &malicious_put_frequency))
3395         malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3396     }
3397
3398   if (GNUNET_YES ==
3399           GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3400                                                "malicious_dropper"))
3401     {
3402       malicious_dropper = GNUNET_YES;
3403     }
3404
3405   if (GNUNET_YES ==
3406       GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
3407                                            "mysql_logging_extended"))
3408     {
3409       debug_routes = GNUNET_YES;
3410       debug_routes_extended = GNUNET_YES;
3411     }
3412
3413   if (GNUNET_YES == debug_routes)
3414     {
3415       dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
3416       if (dhtlog_handle == NULL)
3417         {
3418           GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3419                       "Could not connect to mysql logging server, logging will not happen!");
3420         }
3421     }
3422
3423   stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
3424
3425   if (stats != NULL)
3426     {
3427       GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
3428       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
3429       GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
3430       GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
3431       GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
3432       GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
3433       GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
3434       GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
3435       GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
3436       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
3437       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
3438       GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
3439       GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
3440       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
3441       GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
3442       GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
3443       GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
3444       GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
3445       GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
3446       GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
3447     }
3448 #if DO_FIND_PEER
3449   next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3450                          GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3451                                                   (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3452   GNUNET_SCHEDULER_add_delayed (sched,
3453                                 next_send_time,
3454                                 &send_find_peer_message, NULL);
3455 #endif
3456
3457   /* Scheduled the task to clean up when shutdown is called */
3458   cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
3459                                                GNUNET_TIME_UNIT_FOREVER_REL,
3460                                                &shutdown_task, NULL);
3461 }
3462
3463 /**
3464  * The main function for the dht service.
3465  *
3466  * @param argc number of arguments from the command line
3467  * @param argv command line arguments
3468  * @return 0 ok, 1 on error
3469  */
3470 int
3471 main (int argc, char *const *argv)
3472 {
3473   return (GNUNET_OK ==
3474           GNUNET_SERVICE_run (argc,
3475                               argv,
3476                               "dht",
3477                               GNUNET_SERVICE_OPTION_NONE,
3478                               &run, NULL)) ? 0 : 1;
3479 }