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