2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
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.
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.
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.
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
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"
45 #define PRINT_TABLES GNUNET_NO
47 #define EXTRA_CHECKS GNUNET_NO
49 * How many buckets will we allow total.
51 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
54 * Should the DHT issue FIND_PEER requests to get better routing tables?
56 #define DO_FIND_PEER GNUNET_YES
59 * What is the maximum number of peers in a given bucket.
61 #define DEFAULT_BUCKET_SIZE 4
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!
68 #define MINIMUM_PEER_THRESHOLD 20
70 #define DHT_MAX_RECENT 100
72 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
75 * Default time to wait to send messages on behalf of other peers.
77 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
80 * Default importance for handling messages on behalf of other peers.
82 #define DHT_DEFAULT_P2P_IMPORTANCE 0
85 * How long to keep recent requests arounds by default.
87 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60)
90 * Default time to wait to send find peer messages sent by the dht service.
92 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
95 * Default importance for find peer messages sent by the dht service.
97 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
100 * Default replication parameter for find peer messages sent by the dht service.
102 #define DHT_DEFAULT_FIND_PEER_REPLICATION 10
105 * Default options for find peer requests sent by the dht service.
107 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE
110 * How long at least to wait before sending another find peer request.
112 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
115 * How long at most to wait before sending another find peer request.
117 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
120 * How often to update our preference levels for peers in our routing tables.
122 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
125 * How long at most on average will we allow a reply forward to take
126 * (before we quit sending out new requests)
128 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
131 * How many initial requests to send out (in true Kademlia fashion)
133 #define DHT_KADEMLIA_REPLICATION 3
136 * Default frequency for sending malicious get messages
138 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
141 * Default frequency for sending malicious put messages
143 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
146 * Type for a malicious request, so we can ignore it during testing
148 #define DHT_MALICIOUS_MESSAGE_TYPE 42
150 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
153 * Real maximum number of hops, at which point we refuse
154 * to forward the message.
159 * How many time differences between requesting a core send and
160 * the actual callback to remember.
162 #define MAX_REPLY_TIMES 8
165 * Linked list of messages to send to clients.
167 struct P2PPendingMessage
170 * Pointer to next item in the list
172 struct P2PPendingMessage *next;
175 * Pointer to previous item in the list
177 struct P2PPendingMessage *prev;
180 * Message importance level.
182 unsigned int importance;
185 * Time when this request was scheduled to be sent.
187 struct GNUNET_TIME_Absolute scheduled;
190 * How long to wait before sending message.
192 struct GNUNET_TIME_Relative timeout;
195 * Actual message to be sent; // avoid allocation
197 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
203 * Per-peer information.
208 * Next peer entry (DLL)
210 struct PeerInfo *next;
213 * Prev peer entry (DLL)
215 struct PeerInfo *prev;
218 * Head of pending messages to be sent to this peer.
220 struct P2PPendingMessage *head;
223 * Tail of pending messages to be sent to this peer.
225 struct P2PPendingMessage *tail;
228 * Core handle for sending messages to this peer.
230 struct GNUNET_CORE_TransmitHandle *th;
233 * Task for scheduling message sends.
235 GNUNET_SCHEDULER_TaskIdentifier send_task;
238 * Task for scheduling preference updates
240 GNUNET_SCHEDULER_TaskIdentifier preference_task;
243 * Preference update context
245 struct GNUNET_CORE_InformationRequestContext *info_ctx;
248 * What is the average latency for replies received?
250 struct GNUNET_TIME_Relative latency;
253 * Number of responses received
255 unsigned long long response_count;
258 * Number of requests sent
260 unsigned long long request_count;
263 * What is the identity of the peer?
265 struct GNUNET_PeerIdentity id;
268 * Transport level distance to peer.
270 unsigned int distance;
273 * Task for scheduling periodic ping messages for this peer.
275 GNUNET_SCHEDULER_TaskIdentifier ping_task;
279 * Peers are grouped into buckets.
286 struct PeerInfo *head;
291 struct PeerInfo *tail;
294 * Number of peers in the bucket.
296 unsigned int peers_size;
300 * Linked list of messages to send to clients.
302 struct PendingMessage
305 * Pointer to next item in the list
307 struct PendingMessage *next;
310 * Pointer to previous item in the list
312 struct PendingMessage *prev;
315 * Actual message to be sent; // avoid allocation
317 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
322 * Struct containing information about a client,
323 * handle to connect to it, and any pending messages
324 * that need to be sent to it.
329 * Linked list of active clients
331 struct ClientList *next;
334 * The handle to this client
336 struct GNUNET_SERVER_Client *client_handle;
339 * Handle to the current transmission request, NULL
342 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
345 * Linked list of pending messages for this client
347 struct PendingMessage *pending_head;
350 * Tail of linked list of pending messages for this client
352 struct PendingMessage *pending_tail;
357 * Context containing information about a DHT message received.
359 struct DHT_MessageContext
362 * The client this request was received from.
363 * (NULL if received from another peer)
365 struct ClientList *client;
368 * The peer this request was received from.
369 * (NULL if received from local client)
371 const struct GNUNET_PeerIdentity *peer;
374 * The key this request was about
379 * The unique identifier of this request
384 * Desired replication level
386 uint32_t replication;
389 * Network size estimate, either ours or the sum of
390 * those routed to thus far. =~ Log of number of peers
391 * chosen from for this request.
393 uint32_t network_size;
396 * Any message options for this request
398 uint32_t msg_options;
401 * How many hops has the message already traversed?
406 * How important is this message?
408 unsigned int importance;
411 * How long should we wait to transmit this request?
413 struct GNUNET_TIME_Relative timeout;
416 * Bloomfilter for this routing request.
418 struct GNUNET_CONTAINER_BloomFilter *bloom;
421 * Did we forward this message? (may need to remember it!)
426 * Are we the closest known peer to this key (out of our neighbors?)
432 * Record used for remembering what peers are waiting for what
433 * responses (based on search key).
435 struct DHTRouteSource
440 struct DHTRouteSource *next;
445 struct DHTRouteSource *prev;
448 * Source of the request. Replies should be forwarded to
451 struct GNUNET_PeerIdentity source;
454 * If this was a local request, remember the client; otherwise NULL.
456 struct ClientList *client;
459 * Pointer to this nodes heap location (for removal)
461 struct GNUNET_CONTAINER_HeapNode *hnode;
464 * Back pointer to the record storing this information.
466 struct DHTQueryRecord *record;
469 * Task to remove this entry on timeout.
471 GNUNET_SCHEDULER_TaskIdentifier delete_task;
475 * Entry in the DHT routing table.
477 struct DHTQueryRecord
480 * Head of DLL for result forwarding.
482 struct DHTRouteSource *head;
485 * Tail of DLL for result forwarding.
487 struct DHTRouteSource *tail;
490 * Key that the record concerns.
495 * GET message of this record (what we already forwarded?).
497 //DV_DHT_MESSAGE get; Try to get away with not saving this.
500 * Bloomfilter of the peers we've replied to so far
502 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
507 * Context used to calculate the number of find peer messages
508 * per X time units since our last scheduled find peer message
509 * was sent. If we have seen too many messages, delay or don't
512 struct FindPeerMessageContext
516 struct GNUNET_TIME_Absolute start;
518 struct GNUNET_TIME_Absolute end;
522 * DHT Routing results structure
527 * Min heap for removal upon reaching limit
529 struct GNUNET_CONTAINER_Heap *minHeap;
532 * Hashmap for fast key based lookup
534 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
539 * DHT structure for recent requests.
541 struct RecentRequests
544 * Min heap for removal upon reaching limit
546 struct GNUNET_CONTAINER_Heap *minHeap;
549 * Hashmap for key based lookup
551 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
557 * Position of this node in the min heap.
559 struct GNUNET_CONTAINER_HeapNode *heap_node;
562 * Bloomfilter containing entries for peers
563 * we forwarded this request to.
565 struct GNUNET_CONTAINER_BloomFilter *bloom;
568 * Timestamp of this request, for ordering
571 struct GNUNET_TIME_Absolute timestamp;
574 * Key of this request.
579 * Unique identifier for this request.
584 * Task to remove this entry on timeout.
586 GNUNET_SCHEDULER_TaskIdentifier remove_task;
590 * Recent requests by hash/uid and by time inserted.
592 static struct RecentRequests recent;
595 * Context to use to calculate find peer rates.
597 static struct FindPeerMessageContext find_peer_context;
600 * Don't use our routing algorithm, always route
601 * to closest peer; initially send requests to 3
604 static int strict_kademlia;
607 * Routing option to end routing when closest peer found.
609 static int stop_on_closest;
612 * Routing option to end routing when data is found.
614 static int stop_on_found;
617 * Whether DHT needs to manage find peer requests, or
618 * an external force will do it on behalf of the DHT.
620 static int do_find_peer;
623 * How many peers have we added since we sent out our last
626 static unsigned int newly_found_peers;
629 * Container of active queries we should remember
631 static struct DHTResults forward_list;
634 * Handle to the datacache service (for inserting/retrieving data)
636 static struct GNUNET_DATACACHE_Handle *datacache;
639 * Handle for the statistics service.
641 struct GNUNET_STATISTICS_Handle *stats;
644 * The main scheduler to use for the DHT service
646 static struct GNUNET_SCHEDULER_Handle *sched;
649 * The configuration the DHT service is running with
651 static const struct GNUNET_CONFIGURATION_Handle *cfg;
654 * Handle to the core service
656 static struct GNUNET_CORE_Handle *coreAPI;
659 * Handle to the transport service, for getting our hello
661 static struct GNUNET_TRANSPORT_Handle *transport_handle;
664 * The identity of our peer.
666 static struct GNUNET_PeerIdentity my_identity;
669 * Short id of the peer, for printing
671 static char *my_short_id;
676 static struct GNUNET_MessageHeader *my_hello;
679 * Task to run when we shut down, cleaning up all our trash
681 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
684 * The lowest currently used bucket.
686 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
689 * The buckets (Kademlia routing table, complete with growth).
690 * Array of size MAX_BUCKET_SIZE.
692 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
695 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
697 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
700 * Maximum size for each bucket.
702 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
705 * List of active clients.
707 static struct ClientList *client_list;
710 * Handle to the DHT logger.
712 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
715 * Whether or not to send routing debugging information
716 * to the dht logging server
718 static unsigned int debug_routes;
721 * Whether or not to send FULL route information to
724 static unsigned int debug_routes_extended;
727 * GNUNET_YES or GNUNET_NO, whether or not to act as
728 * a malicious node which drops all messages
730 static unsigned int malicious_dropper;
733 * GNUNET_YES or GNUNET_NO, whether or not to act as
734 * a malicious node which sends out lots of GETS
736 static unsigned int malicious_getter;
739 * GNUNET_YES or GNUNET_NO, whether or not to act as
740 * a malicious node which sends out lots of PUTS
742 static unsigned int malicious_putter;
745 * Frequency for malicious get requests.
747 static unsigned long long malicious_get_frequency;
750 * Frequency for malicious put requests.
752 static unsigned long long malicious_put_frequency;
755 * Reply times for requests, if we are busy, don't send any
758 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
761 * Current counter for replies.
763 static unsigned int reply_counter;
766 * Forward declaration.
768 static size_t send_generic_reply (void *cls, size_t size, void *buf);
770 /** Declare here so retry_core_send is aware of it */
771 size_t core_transmit_notify (void *cls,
772 size_t size, void *buf);
775 * Convert unique ID to hash code.
777 * @param uid unique ID to convert
778 * @param hash set to uid (extended with zeros)
781 hash_from_uid (uint64_t uid,
782 GNUNET_HashCode *hash)
784 memset (hash, 0, sizeof(GNUNET_HashCode));
785 *((uint64_t*)hash) = uid;
790 * Calculate the average send time between messages so that we can
791 * ignore certain requests if we get too busy.
793 * @return the average time between asking core to send a message
794 * and when the buffer for copying it is passed
796 static struct GNUNET_TIME_Relative get_average_send_delay()
799 unsigned int divisor;
800 struct GNUNET_TIME_Relative average_time;
801 average_time = GNUNET_TIME_relative_get_zero();
803 for (i = 0; i < MAX_REPLY_TIMES; i++)
805 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
806 if (reply_times[i].value == (uint64_t)0)
816 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
817 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
823 * Find the maximum send time of the recently sent values.
825 * @return the average time between asking core to send a message
826 * and when the buffer for copying it is passed
828 static struct GNUNET_TIME_Relative get_max_send_delay()
831 struct GNUNET_TIME_Relative max_time;
832 max_time = GNUNET_TIME_relative_get_zero();
834 for (i = 0; i < MAX_REPLY_TIMES; i++)
836 if (reply_times[i].value > max_time.value)
837 max_time.value = reply_times[i].value;
840 if (max_time.value > MAX_REQUEST_TIME.value)
841 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
846 increment_stats(const char *value)
850 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
855 * Try to send another message from our core send list
858 try_core_send (void *cls,
859 const struct GNUNET_SCHEDULER_TaskContext *tc)
861 struct PeerInfo *peer = cls;
862 struct P2PPendingMessage *pending;
865 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
867 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
870 if (peer->th != NULL)
871 return; /* Message send already in progress */
873 pending = peer->head;
876 ssize = ntohs(pending->msg->size);
878 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
879 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
880 "DHT", ssize, GNUNET_i2s(&peer->id));
882 pending->scheduled = GNUNET_TIME_absolute_get();
884 if (reply_counter >= MAX_REPLY_TIMES)
886 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
887 pending->timeout, &peer->id,
888 ssize, &core_transmit_notify, peer);
893 * Function called to send a request out to another peer.
894 * Called both for locally initiated requests and those
895 * received from other peers.
897 * @param cls DHT service closure argument
898 * @param msg the encapsulated message
899 * @param peer the peer to forward the message to
900 * @param msg_ctx the context of the message (hop count, bloom, etc.)
902 static void forward_result_message (void *cls,
903 const struct GNUNET_MessageHeader *msg,
904 struct PeerInfo *peer,
905 struct DHT_MessageContext *msg_ctx)
907 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
908 struct P2PPendingMessage *pending;
912 increment_stats(STAT_RESULT_FORWARDS);
913 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
914 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
915 psize = sizeof(struct P2PPendingMessage) + msize;
916 pending = GNUNET_malloc(psize);
917 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
918 pending->importance = DHT_SEND_PRIORITY;
919 pending->timeout = GNUNET_TIME_relative_get_forever();
920 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
921 result_message->header.size = htons(msize);
922 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
923 result_message->options = htonl(msg_ctx->msg_options);
924 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
925 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
926 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
927 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
928 memcpy(&result_message[1], msg, ntohs(msg->size));
930 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Adding pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
932 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
933 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
934 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
937 * Called when core is ready to send a message we asked for
938 * out to the destination.
940 * @param cls closure (NULL)
941 * @param size number of bytes available in buf
942 * @param buf where the callee should write the message
943 * @return number of bytes written to buf
945 size_t core_transmit_notify (void *cls,
946 size_t size, void *buf)
948 struct PeerInfo *peer = cls;
950 struct P2PPendingMessage *pending;
957 /* client disconnected */
959 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
964 if (peer->head == NULL)
969 pending = peer->head;
970 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
971 msize = ntohs(pending->msg->size);
975 memcpy (cbuf, pending->msg, msize);
976 GNUNET_CONTAINER_DLL_remove (peer->head,
980 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Removing pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
982 GNUNET_free (pending);
985 while (NULL != pending &&
986 (size - off >= (msize = ntohs (pending->msg->size))))
988 #if DEBUG_DHT_ROUTING
989 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s:%s' : transmit_notify (core) called with size %d, available %d\n", my_short_id, "dht service", msize, size);
991 memcpy (&cbuf[off], pending->msg, msize);
993 GNUNET_CONTAINER_DLL_remove (peer->head,
996 GNUNET_free (pending);
997 pending = peer->head;
1000 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1001 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1003 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s:%s' : transmit_notify (core) called with size %d, available %d, returning %d\n", my_short_id, "dht service", msize, size, off);
1009 * Determine how many low order bits match in two
1010 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
1011 * the first two lowest order bits, and therefore the
1012 * return value is two (NOT XOR distance, nor how many
1013 * bits match absolutely!).
1015 * @param first the first hashcode
1016 * @param second the hashcode to compare first to
1018 * @return the number of bits that match
1020 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
1024 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
1025 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
1027 return sizeof (GNUNET_HashCode) * 8;
1031 * Compute the distance between have and target as a 32-bit value.
1032 * Differences in the lower bits must count stronger than differences
1033 * in the higher bits.
1035 * @return 0 if have==target, otherwise a number
1036 * that is larger as the distance between
1037 * the two hash codes increases
1040 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1042 unsigned int bucket;
1047 /* We have to represent the distance between two 2^9 (=512)-bit
1048 numbers as a 2^5 (=32)-bit number with "0" being used for the
1049 two numbers being identical; furthermore, we need to
1050 guarantee that a difference in the number of matching
1051 bits is always represented in the result.
1053 We use 2^32/2^9 numerical values to distinguish between
1054 hash codes that have the same LSB bit distance and
1055 use the highest 2^9 bits of the result to signify the
1056 number of (mis)matching LSB bits; if we have 0 matching
1057 and hence 512 mismatching LSB bits we return -1 (since
1058 512 itself cannot be represented with 9 bits) */
1060 /* first, calculate the most significant 9 bits of our
1061 result, aka the number of LSBs */
1062 bucket = matching_bits (target, have);
1063 /* bucket is now a value between 0 and 512 */
1065 return 0; /* perfect match */
1067 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1068 below, we'd end up with max+1 (overflow)) */
1070 /* calculate the most significant bits of the final result */
1071 msb = (512 - bucket) << (32 - 9);
1072 /* calculate the 32-9 least significant bits of the final result by
1073 looking at the differences in the 32-9 bits following the
1074 mismatching bit at 'bucket' */
1076 for (i = bucket + 1;
1077 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1079 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1080 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1081 last bit set will be 31 -- if
1082 i does not reach 512 first... */
1088 * Return a number that is larger the closer the
1089 * "have" GNUNET_hash code is to the "target".
1091 * @return inverse distance metric, non-zero.
1092 * Must fudge the value if NO bits match.
1095 inverse_distance (const GNUNET_HashCode * target,
1096 const GNUNET_HashCode * have)
1098 if (matching_bits(target, have) == 0)
1099 return 1; /* Never return 0! */
1100 return ((unsigned int) -1) - distance (target, have);
1104 * Find the optimal bucket for this key, regardless
1105 * of the current number of buckets in use.
1107 * @param hc the hashcode to compare our identity to
1109 * @return the proper bucket index, or GNUNET_SYSERR
1110 * on error (same hashcode)
1112 static int find_bucket(const GNUNET_HashCode *hc)
1116 bits = matching_bits(&my_identity.hashPubKey, hc);
1117 if (bits == MAX_BUCKETS)
1118 return GNUNET_SYSERR;
1119 return MAX_BUCKETS - bits - 1;
1123 * Find which k-bucket this peer should go into,
1124 * taking into account the size of the k-bucket
1125 * array. This means that if more bits match than
1126 * there are currently buckets, lowest_bucket will
1129 * @param hc GNUNET_HashCode we are finding the bucket for.
1131 * @return the proper bucket index for this key,
1132 * or GNUNET_SYSERR on error (same hashcode)
1134 static int find_current_bucket(const GNUNET_HashCode *hc)
1137 actual_bucket = find_bucket(hc);
1139 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1140 return GNUNET_SYSERR;
1141 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1142 return lowest_bucket;
1144 return actual_bucket;
1149 * Find a routing table entry from a peer identity
1151 * @param peer the peer to look up
1153 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1156 find_bucket_by_peer(const struct PeerInfo *peer)
1159 struct PeerInfo *pos;
1161 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1163 pos = k_buckets[bucket].head;
1172 return GNUNET_SYSERR; /* No such peer. */
1178 * Print the complete routing table for this peer.
1181 print_routing_table ()
1184 struct PeerInfo *pos;
1185 char char_buf[30000];
1187 memset(char_buf, 0, sizeof(char_buf));
1189 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1190 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1191 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1193 pos = k_buckets[bucket].head;
1194 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1195 //fprintf(stderr, "Bucket %d:\n", bucket);
1198 //fprintf(stderr, "\tPeer %s, best bucket %d, %d bits match\n", GNUNET_i2s(&pos->id), find_bucket(&pos->id.hashPubKey), matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey));
1199 char_pos += sprintf(&char_buf[char_pos], "\tPeer %s, best bucket %d, %d bits match\n", GNUNET_i2s(&pos->id), find_bucket(&pos->id.hashPubKey), matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey));
1203 fprintf(stderr, "%s", char_buf);
1209 * Find a routing table entry from a peer identity
1211 * @param peer the peer identity to look up
1213 * @return the routing table entry, or NULL if not found
1215 static struct PeerInfo *
1216 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1219 struct PeerInfo *pos;
1220 bucket = find_current_bucket(&peer->hashPubKey);
1222 if (bucket == GNUNET_SYSERR)
1225 pos = k_buckets[bucket].head;
1228 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1232 return NULL; /* No such peer. */
1235 /* Forward declaration */
1237 update_core_preference (void *cls,
1238 const struct GNUNET_SCHEDULER_TaskContext *tc);
1240 * Function called with statistics about the given peer.
1242 * @param cls closure
1243 * @param peer identifies the peer
1244 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1245 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1246 * @param latency current latency estimate, "FOREVER" if we have been
1248 * @param amount set to the amount that was actually reserved or unreserved;
1249 * either the full requested amount or zero (no partial reservations)
1250 * @param preference current traffic preference for the given peer
1253 update_core_preference_finish (void *cls,
1255 GNUNET_PeerIdentity * peer,
1256 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1257 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1259 uint64_t preference)
1261 struct PeerInfo *peer_info = cls;
1262 peer_info->info_ctx = NULL;
1263 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1267 update_core_preference (void *cls,
1268 const struct GNUNET_SCHEDULER_TaskContext *tc)
1270 struct PeerInfo *peer = cls;
1271 uint64_t preference;
1273 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1278 preference = 2 << matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1279 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1281 GNUNET_TIME_relative_get_forever(),
1282 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1285 &update_core_preference_finish,
1290 * Really add a peer to a bucket (only do assertions
1293 * @param peer GNUNET_PeerIdentity of the peer to add
1294 * @param bucket the already figured out bucket to add
1296 * @param latency the core reported latency of this peer
1297 * @param distance the transport level distance to this peer
1299 * @return the newly added PeerInfo
1301 static struct PeerInfo *
1302 add_peer(const struct GNUNET_PeerIdentity *peer,
1303 unsigned int bucket,
1304 struct GNUNET_TIME_Relative latency,
1305 unsigned int distance)
1307 struct PeerInfo *new_peer;
1308 GNUNET_assert(bucket < MAX_BUCKETS);
1309 GNUNET_assert(peer != NULL);
1310 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1311 new_peer->latency = latency;
1312 new_peer->distance = distance;
1314 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1316 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1317 k_buckets[bucket].tail,
1318 k_buckets[bucket].tail,
1320 k_buckets[bucket].peers_size++;
1322 if ((matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1324 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1331 * Given a peer and its corresponding bucket,
1332 * remove it from that bucket. Does not free
1333 * the PeerInfo struct, nor cancel messages
1334 * or free messages waiting to be sent to this
1337 * @param peer the peer to remove
1338 * @param bucket the bucket the peer belongs to
1340 static void remove_peer (struct PeerInfo *peer,
1341 unsigned int bucket)
1343 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1344 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1345 k_buckets[bucket].tail,
1347 k_buckets[bucket].peers_size--;
1348 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1353 * Removes peer from a bucket, then frees associated
1354 * resources and frees peer.
1356 * @param peer peer to be removed and freed
1357 * @param bucket which bucket this peer belongs to
1359 static void delete_peer (struct PeerInfo *peer,
1360 unsigned int bucket)
1362 struct P2PPendingMessage *pos;
1363 struct P2PPendingMessage *next;
1365 struct PeerInfo *peer_pos;
1367 peer_pos = k_buckets[bucket].head;
1368 while ((peer_pos != NULL) && (peer_pos != peer))
1369 peer_pos = peer_pos->next;
1370 if (peer_pos == NULL)
1372 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1373 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Lowest bucket: %d, find_current_bucket: %d, peer resides in bucket: %d\n", my_short_id, "DHT", lowest_bucket, find_current_bucket(&peer->id.hashPubKey), find_bucket_by_peer(peer));
1375 GNUNET_assert(peer_pos != NULL);
1377 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1379 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1380 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1381 if (peer->th != NULL)
1382 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1385 while (pos != NULL) /* Remove any pending messages for this peer */
1392 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1393 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1399 * Iterator over hash map entries.
1401 * @param cls closure
1402 * @param key current key code
1403 * @param value PeerInfo of the peer to move to new lowest bucket
1404 * @return GNUNET_YES if we should continue to
1408 static int move_lowest_bucket (void *cls,
1409 const GNUNET_HashCode * key,
1412 struct PeerInfo *peer = value;
1415 GNUNET_assert(lowest_bucket > 0);
1416 new_bucket = lowest_bucket - 1;
1417 remove_peer(peer, lowest_bucket);
1418 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1419 k_buckets[new_bucket].tail,
1420 k_buckets[new_bucket].tail,
1422 k_buckets[new_bucket].peers_size++;
1428 * The current lowest bucket is full, so change the lowest
1429 * bucket to the next lower down, and move any appropriate
1430 * entries in the current lowest bucket to the new bucket.
1432 static void enable_next_bucket()
1434 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1435 struct PeerInfo *pos;
1436 GNUNET_assert(lowest_bucket > 0);
1437 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1438 pos = k_buckets[lowest_bucket].head;
1441 fprintf(stderr, "Printing RT before new bucket\n");
1442 print_routing_table();
1444 /* Populate the array of peers which should be in the next lowest bucket */
1447 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1448 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1452 /* Remove peers from lowest bucket, insert into next lowest bucket */
1453 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1454 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1455 lowest_bucket = lowest_bucket - 1;
1457 fprintf(stderr, "Printing RT after new bucket\n");
1458 print_routing_table();
1463 * Find the closest peer in our routing table to the
1466 * @return The closest peer in our routing table to the
1467 * key, or NULL on error.
1469 static struct PeerInfo *
1470 find_closest_peer (const GNUNET_HashCode *hc)
1472 struct PeerInfo *pos;
1473 struct PeerInfo *current_closest;
1474 unsigned int lowest_distance;
1475 unsigned int temp_distance;
1479 lowest_distance = -1;
1481 if (k_buckets[lowest_bucket].peers_size == 0)
1484 current_closest = NULL;
1485 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1487 pos = k_buckets[bucket].head;
1489 while ((pos != NULL) && (count < bucket_size))
1491 temp_distance = distance(&pos->id.hashPubKey, hc);
1492 if (temp_distance <= lowest_distance)
1494 lowest_distance = temp_distance;
1495 current_closest = pos;
1501 GNUNET_assert(current_closest != NULL);
1502 return current_closest;
1507 * Function called to send a request out to another peer.
1508 * Called both for locally initiated requests and those
1509 * received from other peers.
1511 * @param cls DHT service closure argument (unused)
1512 * @param msg the encapsulated message
1513 * @param peer the peer to forward the message to
1514 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1516 static void forward_message (void *cls,
1517 const struct GNUNET_MessageHeader *msg,
1518 struct PeerInfo *peer,
1519 struct DHT_MessageContext *msg_ctx)
1521 struct GNUNET_DHT_P2PRouteMessage *route_message;
1522 struct P2PPendingMessage *pending;
1526 increment_stats(STAT_ROUTE_FORWARDS);
1528 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1529 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1531 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1532 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1533 psize = sizeof(struct P2PPendingMessage) + msize;
1534 pending = GNUNET_malloc(psize);
1535 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1536 pending->importance = msg_ctx->importance;
1537 pending->timeout = msg_ctx->timeout;
1538 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1539 route_message->header.size = htons(msize);
1540 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1541 route_message->options = htonl(msg_ctx->msg_options);
1542 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1543 route_message->network_size = htonl(msg_ctx->network_size);
1544 route_message->desired_replication_level = htonl(msg_ctx->replication);
1545 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1546 if (msg_ctx->bloom != NULL)
1547 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1548 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1549 memcpy(&route_message[1], msg, ntohs(msg->size));
1551 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Adding pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
1553 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1554 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1555 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1560 * Task used to send ping messages to peers so that
1561 * they don't get disconnected.
1563 * @param cls the peer to send a ping message to
1564 * @param tc context, reason, etc.
1567 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1569 struct PeerInfo *peer = cls;
1570 struct GNUNET_MessageHeader ping_message;
1571 struct DHT_MessageContext message_context;
1573 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1576 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1577 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1579 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1581 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1583 forward_message(NULL, &ping_message, peer, &message_context);
1584 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1588 * Schedule PING messages for the top X peers in each
1589 * bucket of the routing table (so core won't disconnect them!)
1591 void schedule_ping_messages()
1593 unsigned int bucket;
1595 struct PeerInfo *pos;
1596 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1598 pos = k_buckets[bucket].head;
1602 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1603 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1604 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1606 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1607 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1617 * Attempt to add a peer to our k-buckets.
1619 * @param peer, the peer identity of the peer being added
1621 * @return NULL if the peer was not added,
1622 * pointer to PeerInfo for new peer otherwise
1624 static struct PeerInfo *
1625 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1626 unsigned int bucket,
1627 struct GNUNET_TIME_Relative latency,
1628 unsigned int distance)
1631 struct PeerInfo *new_peer;
1632 peer_bucket = find_current_bucket(&peer->hashPubKey);
1633 if (peer_bucket == GNUNET_SYSERR)
1636 GNUNET_assert(peer_bucket >= lowest_bucket);
1637 new_peer = add_peer(peer, peer_bucket, latency, distance);
1639 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1640 enable_next_bucket();
1642 schedule_ping_messages();
1649 * Task run to check for messages that need to be sent to a client.
1651 * @param client a ClientList, containing the client and any messages to be sent to it
1654 process_pending_messages (struct ClientList *client)
1656 if (client->pending_head == NULL)
1658 if (client->transmit_handle != NULL)
1660 client->transmit_handle =
1661 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1662 ntohs (client->pending_head->msg->
1664 GNUNET_TIME_UNIT_FOREVER_REL,
1665 &send_generic_reply, client);
1669 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1670 * request. A ClientList is passed as closure, take the head of the list
1671 * and copy it into buf, which has the result of sending the message to the
1674 * @param cls closure to this call
1675 * @param size maximum number of bytes available to send
1676 * @param buf where to copy the actual message to
1678 * @return the number of bytes actually copied, 0 indicates failure
1681 send_generic_reply (void *cls, size_t size, void *buf)
1683 struct ClientList *client = cls;
1685 struct PendingMessage *reply;
1689 client->transmit_handle = NULL;
1692 /* client disconnected */
1696 while ( (NULL != (reply = client->pending_head)) &&
1697 (size >= off + (msize = ntohs (reply->msg->size))))
1699 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1700 client->pending_tail,
1702 memcpy (&cbuf[off], reply->msg, msize);
1703 GNUNET_free (reply);
1706 process_pending_messages (client);
1712 * Add a PendingMessage to the clients list of messages to be sent
1714 * @param client the active client to send the message to
1715 * @param pending_message the actual message to send
1718 add_pending_message (struct ClientList *client,
1719 struct PendingMessage *pending_message)
1721 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1722 client->pending_tail,
1723 client->pending_tail,
1725 process_pending_messages (client);
1732 * Called when a reply needs to be sent to a client, as
1733 * a result it found to a GET or FIND PEER request.
1735 * @param client the client to send the reply to
1736 * @param message the encapsulated message to send
1737 * @param uid the unique identifier of this request
1740 send_reply_to_client (struct ClientList *client,
1741 const struct GNUNET_MessageHeader *message,
1742 unsigned long long uid)
1744 struct GNUNET_DHT_RouteResultMessage *reply;
1745 struct PendingMessage *pending_message;
1749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1750 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1752 msize = ntohs (message->size);
1753 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1754 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1756 GNUNET_break_op (0);
1760 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1761 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1762 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1763 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1764 reply->header.size = htons (tsize);
1765 reply->unique_id = GNUNET_htonll (uid);
1766 memcpy (&reply[1], message, msize);
1768 add_pending_message (client, pending_message);
1772 * Consider whether or not we would like to have this peer added to
1773 * our routing table. Check whether bucket for this peer is full,
1774 * if so return negative; if not return positive. Since peers are
1775 * only added on CORE level connect, this doesn't actually add the
1776 * peer to the routing table.
1778 * @param peer the peer we are considering adding
1780 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1783 * FIXME: Think about making a context for this call so that we can
1784 * ping the oldest peer in the current bucket and consider
1785 * removing it in lieu of the new peer.
1787 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1791 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1792 return GNUNET_NO; /* We already know this peer (are connected even!) */
1793 bucket = find_current_bucket(&peer->hashPubKey);
1794 if (bucket == GNUNET_SYSERR)
1796 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1803 * Main function that handles whether or not to route a result
1804 * message to other peers, or to send to our local client.
1806 * @param msg the result message to be routed
1807 * @return the number of peers the message was routed to,
1808 * GNUNET_SYSERR on failure
1810 static int route_result_message(void *cls,
1811 struct GNUNET_MessageHeader *msg,
1812 struct DHT_MessageContext *message_context)
1814 struct GNUNET_PeerIdentity new_peer;
1815 struct DHTQueryRecord *record;
1816 struct DHTRouteSource *pos;
1817 struct PeerInfo *peer_info;
1818 const struct GNUNET_MessageHeader *hello_msg;
1820 increment_stats(STAT_RESULTS);
1822 * If a find peer result message is received and contains a valid
1823 * HELLO for another peer, offer it to the transport service.
1825 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1827 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1830 hello_msg = &msg[1];
1831 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1833 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1836 else /* We have a valid hello, and peer id stored in new_peer */
1838 find_peer_context.count++;
1839 increment_stats(STAT_FIND_PEER_REPLY);
1840 if (GNUNET_YES == consider_peer(&new_peer))
1842 increment_stats(STAT_HELLOS_PROVIDED);
1843 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1844 /* GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_UNIT_FOREVER_REL, &new_peer, NULL, NULL); */
1845 /* peer_request_connect call causes service to segfault */
1846 /* FIXME: Do we need this (peer_request_connect call)??? */
1851 if (malicious_dropper == GNUNET_YES)
1854 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1856 if (record == NULL) /* No record of this message! */
1859 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1860 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1861 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1863 #if DEBUG_DHT_ROUTING
1865 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1867 dhtlog_handle->insert_route (NULL,
1868 message_context->unique_id,
1870 message_context->hop_count,
1873 &message_context->key,
1874 message_context->peer, NULL);
1877 if (message_context->bloom != NULL)
1879 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1880 message_context->bloom = NULL;
1888 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1891 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1892 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
1893 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1895 #if DEBUG_DHT_ROUTING
1896 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1898 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
1899 message_context->hop_count,
1900 GNUNET_YES, &my_identity, &message_context->key,
1901 message_context->peer, NULL);
1904 increment_stats(STAT_RESULTS_TO_CLIENT);
1905 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
1906 increment_stats(STAT_GET_REPLY);
1908 send_reply_to_client(pos->client, msg, message_context->unique_id);
1910 else /* Send to peer */
1912 peer_info = find_peer_by_id(&pos->source);
1913 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
1919 if (message_context->bloom == NULL)
1920 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1921 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
1922 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey))
1925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1926 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
1927 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1929 #if DEBUG_DHT_ROUTING
1930 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1932 dhtlog_handle->insert_route (NULL, message_context->unique_id,
1934 message_context->hop_count,
1935 GNUNET_NO, &my_identity, &message_context->key,
1936 message_context->peer, &pos->source);
1939 forward_result_message(cls, msg, peer_info, message_context);
1944 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1945 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
1946 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1952 if (message_context->bloom != NULL)
1953 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1958 * Iterator for local get request results,
1960 * @param cls closure for iterator, a DatacacheGetContext
1961 * @param exp when does this value expire?
1962 * @param key the key this data is stored under
1963 * @param size the size of the data identified by key
1964 * @param data the actual data
1965 * @param type the type of the data
1967 * @return GNUNET_OK to continue iteration, anything else
1968 * to stop iteration.
1971 datacache_get_iterator (void *cls,
1972 struct GNUNET_TIME_Absolute exp,
1973 const GNUNET_HashCode * key,
1974 uint32_t size, const char *data, uint32_t type)
1976 struct DHT_MessageContext *msg_ctx = cls;
1977 struct DHT_MessageContext *new_msg_ctx;
1978 struct GNUNET_DHT_GetResultMessage *get_result;
1980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1981 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
1983 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
1984 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
1986 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
1987 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
1988 get_result->header.size =
1989 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
1990 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
1991 get_result->type = htons (type);
1992 memcpy (&get_result[1], data, size);
1993 new_msg_ctx->peer = &my_identity;
1994 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1995 new_msg_ctx->hop_count = 0;
1996 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
1997 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
1998 increment_stats(STAT_GET_RESPONSE_START);
1999 route_result_message(cls, &get_result->header, new_msg_ctx);
2000 GNUNET_free(new_msg_ctx);
2001 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2002 // datacache_get_ctx->unique_id);
2003 GNUNET_free (get_result);
2009 * Server handler for all dht get requests, look for data,
2010 * if found, send response either to clients or other peers.
2012 * @param cls closure for service
2013 * @param msg the actual get message
2014 * @param message_context struct containing pertinent information about the get request
2016 * @return number of items found for GET request
2019 handle_dht_get (void *cls,
2020 const struct GNUNET_MessageHeader *msg,
2021 struct DHT_MessageContext *message_context)
2023 const struct GNUNET_DHT_GetMessage *get_msg;
2025 unsigned int results;
2027 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2028 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2034 get_type = ntohs (get_msg->type);
2036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2037 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2038 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2039 message_context->unique_id);
2041 increment_stats(STAT_GETS);
2043 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2046 if (datacache != NULL)
2048 GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2049 &datacache_get_iterator, message_context);
2054 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2055 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2056 results, "GET", message_context->unique_id);
2058 #if DEBUG_DHT_ROUTING
2059 if ((debug_routes) && (dhtlog_handle != NULL))
2061 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2062 message_context->hop_count, GNUNET_YES, &my_identity,
2063 &message_context->key);
2066 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2068 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2069 message_context->hop_count, GNUNET_YES,
2070 &my_identity, &message_context->key, message_context->peer,
2076 if (message_context->hop_count == 0) /* Locally initiated request */
2078 #if DEBUG_DHT_ROUTING
2079 if ((debug_routes) && (dhtlog_handle != NULL))
2081 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2082 message_context->hop_count, GNUNET_NO, &my_identity,
2083 &message_context->key);
2093 * Server handler for initiating local dht find peer requests
2095 * @param cls closure for service
2096 * @param find_msg the actual find peer message
2097 * @param message_context struct containing pertinent information about the request
2101 handle_dht_find_peer (void *cls,
2102 const struct GNUNET_MessageHeader *find_msg,
2103 struct DHT_MessageContext *message_context)
2105 struct GNUNET_MessageHeader *find_peer_result;
2106 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2107 struct DHT_MessageContext *new_msg_ctx;
2108 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2111 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2113 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2114 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2115 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2116 ntohs (find_msg->size),
2117 sizeof (struct GNUNET_MessageHeader));
2119 if (my_hello == NULL)
2122 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2123 "`%s': Our HELLO is null, can't return.\n",
2129 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2130 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2132 increment_stats(STAT_BLOOM_FIND_PEER);
2133 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2134 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2136 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2138 /* Simplistic find_peer functionality, always return our hello */
2139 hello_size = ntohs(my_hello->size);
2140 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2142 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2144 GNUNET_break_op (0);
2148 find_peer_result = GNUNET_malloc (tsize);
2149 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2150 find_peer_result->size = htons (tsize);
2151 memcpy (&find_peer_result[1], my_hello, hello_size);
2153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2154 "`%s': Sending hello size %d to requesting peer.\n",
2157 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2158 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2159 new_msg_ctx->peer = &my_identity;
2160 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2161 new_msg_ctx->hop_count = 0;
2162 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2163 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2164 increment_stats(STAT_FIND_PEER_ANSWER);
2165 route_result_message(cls, find_peer_result, new_msg_ctx);
2166 GNUNET_free(new_msg_ctx);
2167 #if DEBUG_DHT_ROUTING
2168 if ((debug_routes) && (dhtlog_handle != NULL))
2170 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2171 message_context->hop_count, GNUNET_YES, &my_identity,
2172 &message_context->key);
2175 GNUNET_free(find_peer_result);
2180 * Server handler for initiating local dht put requests
2182 * @param cls closure for service
2183 * @param msg the actual put message
2184 * @param message_context struct containing pertinent information about the request
2187 handle_dht_put (void *cls,
2188 const struct GNUNET_MessageHeader *msg,
2189 struct DHT_MessageContext *message_context)
2191 struct GNUNET_DHT_PutMessage *put_msg;
2195 GNUNET_assert (ntohs (msg->size) >=
2196 sizeof (struct GNUNET_DHT_PutMessage));
2199 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2200 put_type = ntohs (put_msg->type);
2202 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2205 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2208 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2209 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2211 #if DEBUG_DHT_ROUTING
2212 if (message_context->hop_count == 0) /* Locally initiated request */
2214 if ((debug_routes) && (dhtlog_handle != NULL))
2216 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2217 message_context->hop_count, GNUNET_NO, &my_identity,
2218 &message_context->key);
2223 if (message_context->closest != GNUNET_YES)
2226 #if DEBUG_DHT_ROUTING
2227 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2229 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2230 message_context->hop_count, GNUNET_YES,
2231 &my_identity, &message_context->key, message_context->peer,
2235 if ((debug_routes) && (dhtlog_handle != NULL))
2237 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2238 message_context->hop_count, GNUNET_YES, &my_identity,
2239 &message_context->key);
2243 increment_stats(STAT_PUTS_INSERTED);
2244 if (datacache != NULL)
2245 GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2246 (char *) &put_msg[1], put_type,
2247 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2249 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2250 "`%s:%s': %s request received, but have no datacache!\n",
2251 my_short_id, "DHT", "PUT");
2255 * Estimate the diameter of the network based
2256 * on how many buckets are currently in use.
2257 * Concept here is that the diameter of the network
2258 * is roughly the distance a message must travel in
2259 * order to reach its intended destination. Since
2260 * at each hop we expect to get one bit closer, and
2261 * we have one bit per bucket, the number of buckets
2262 * in use should be the largest number of hops for
2263 * a sucessful message. (of course, this assumes we
2264 * know all peers in the network!)
2266 * @return ballpark diameter figure
2268 static unsigned int estimate_diameter()
2270 return MAX_BUCKETS - lowest_bucket;
2274 * To how many peers should we (on average)
2275 * forward the request to obtain the desired
2276 * target_replication count (on average).
2278 * Always 0, 1 or 2 (don't send, send once, split)
2281 get_forward_count (unsigned int hop_count, size_t target_replication)
2283 double target_count;
2284 unsigned int target_value;
2285 unsigned int diameter;
2288 * If we are behaving in strict kademlia mode, send multiple initial requests,
2289 * but then only send to 1 or 0 peers.
2291 if (strict_kademlia == GNUNET_YES)
2294 return DHT_KADEMLIA_REPLICATION;
2295 else if (hop_count < MAX_HOPS)
2301 /* FIXME: the smaller we think the network is the more lenient we should be for
2302 * routing right? The estimation below only works if we think we have reasonably
2303 * full routing tables, which for our RR topologies may not be the case!
2305 diameter = estimate_diameter ();
2306 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2310 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2311 "DHT", estimate_diameter(), lowest_bucket);
2315 else if (hop_count > MAX_HOPS)
2318 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2319 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2324 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2325 target_replication / (target_replication * (hop_count + 1) + diameter);
2328 while (target_value < target_count)
2329 target_value++; /* target_value is ALWAYS 1 after this "loop" */
2333 if ((target_count + 1 - target_value) >
2334 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2335 RAND_MAX) / RAND_MAX)
2337 return target_value;
2341 * Check whether my identity is closer than any known peers.
2342 * If a non-null bloomfilter is given, check if this is the closest
2343 * peer that hasn't already been routed to.
2345 * @param target hash code to check closeness to
2346 * @param bloom bloomfilter, exclude these entries from the decision
2348 * Return GNUNET_YES if node location is closest, GNUNET_NO
2352 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2358 struct PeerInfo *pos;
2359 #if INTEGER_DISTANCE
2360 unsigned int my_distance;
2362 bucket_num = find_current_bucket(target);
2363 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2366 bits = matching_bits(&my_identity.hashPubKey, target);
2367 #if INTEGER_DISTANCE
2368 my_distance = distance(&my_identity.hashPubKey, target);
2370 pos = k_buckets[bucket_num].head;
2372 while ((pos != NULL) && (count < bucket_size))
2374 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2377 continue; /* Skip already checked entries */
2380 other_bits = matching_bits(&pos->id.hashPubKey, target);
2381 if (other_bits > bits)
2383 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2386 /* FIXME: why not just return GNUNET_YES here? We are certainly close. */
2387 /*if (distance(&pos->id.hashPubKey, target) < my_distance)
2394 GNUNET_GE_LOG (coreAPI->ectx,
2395 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2396 GNUNET_GE_BULK, "closest peer\n");
2397 printPeerBits (&closest);
2398 GNUNET_GE_LOG (coreAPI->ectx,
2399 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2400 GNUNET_GE_BULK, "me\n");
2401 printPeerBits (coreAPI->my_identity);
2402 GNUNET_GE_LOG (coreAPI->ectx,
2403 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2404 GNUNET_GE_BULK, "key\n");
2405 printKeyBits (target);
2406 GNUNET_GE_LOG (coreAPI->ectx,
2407 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2409 "closest peer inverse distance is %u, mine is %u\n",
2410 inverse_distance (target, &closest.hashPubKey),
2411 inverse_distance (target,
2412 &coreAPI->my_identity->hashPubKey));
2415 /* No peers closer, we are the closest! */
2421 * Select a peer from the routing table that would be a good routing
2422 * destination for sending a message for "target". The resulting peer
2423 * must not be in the set of blocked peers.<p>
2425 * Note that we should not ALWAYS select the closest peer to the
2426 * target, peers further away from the target should be chosen with
2427 * exponentially declining probability.
2429 * @param target the key we are selecting a peer to route to
2430 * @param bloom a bloomfilter containing entries this request has seen already
2432 * @return Peer to route to, or NULL on error
2434 static struct PeerInfo *
2435 select_peer (const GNUNET_HashCode * target,
2436 struct GNUNET_CONTAINER_BloomFilter *bloom)
2438 unsigned int distance;
2441 struct PeerInfo *pos;
2442 struct PeerInfo *chosen;
2443 unsigned long long largest_distance;
2444 unsigned long long total_distance;
2445 unsigned long long selected;
2447 if (strict_kademlia == GNUNET_YES)
2449 largest_distance = 0;
2451 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2453 pos = k_buckets[bc].head;
2455 while ((pos != NULL) && (count < bucket_size))
2457 /* If we are doing strict Kademlia like routing, then checking the bloomfilter is basically cheating! */
2458 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2460 distance = inverse_distance (target, &pos->id.hashPubKey);
2461 if (distance > largest_distance)
2464 largest_distance = distance;
2472 if ((largest_distance > 0) && (chosen != NULL))
2474 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2486 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2488 pos = k_buckets[bc].head;
2490 while ((pos != NULL) && (count < bucket_size))
2492 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2493 total_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2495 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2496 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2497 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2503 if (total_distance == 0)
2508 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2509 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2511 pos = k_buckets[bc].head;
2513 while ((pos != NULL) && (count < bucket_size))
2515 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2517 distance = inverse_distance (target, &pos->id.hashPubKey);
2518 if (distance > selected)
2520 selected -= distance;
2525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2526 "`%s:%s': peer %s matches bloomfilter.\n",
2527 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2535 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2536 "`%s:%s': peer %s matches bloomfilter.\n",
2537 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2544 * Task used to remove recent entries, either
2545 * after timeout, when full, or on shutdown.
2547 * @param cls the entry to remove
2548 * @param tc context, reason, etc.
2551 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2553 struct RecentRequest *req = cls;
2554 static GNUNET_HashCode hash;
2556 GNUNET_assert(req != NULL);
2557 hash_from_uid(req->uid, &hash);
2558 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
2559 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
2560 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
2563 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
2565 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
2566 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
2572 * Task used to remove forwarding entries, either
2573 * after timeout, when full, or on shutdown.
2575 * @param cls the entry to remove
2576 * @param tc context, reason, etc.
2579 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2581 struct DHTRouteSource *source_info = cls;
2582 struct DHTQueryRecord *record;
2583 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2584 record = source_info->record;
2585 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2587 if (record->head == NULL) /* No more entries in DLL */
2589 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2590 GNUNET_free(record);
2592 GNUNET_free(source_info);
2596 * Remember this routing request so that if a reply is
2597 * received we can either forward it to the correct peer
2598 * or return the result locally.
2600 * @param cls DHT service closure
2601 * @param msg_ctx Context of the route request
2603 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2605 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2607 struct DHTQueryRecord *record;
2608 struct DHTRouteSource *source_info;
2609 struct DHTRouteSource *pos;
2610 struct GNUNET_TIME_Absolute now;
2611 unsigned int current_size;
2613 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2614 while (current_size >= MAX_OUTSTANDING_FORWARDS)
2616 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2617 GNUNET_assert(source_info != NULL);
2618 record = source_info->record;
2619 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2620 if (record->head == NULL) /* No more entries in DLL */
2622 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2623 GNUNET_free(record);
2625 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2626 GNUNET_free(source_info);
2627 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2629 now = GNUNET_TIME_absolute_get();
2630 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2631 if (record != NULL) /* Already know this request! */
2636 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
2637 break; /* Already have this peer in reply list! */
2640 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
2642 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
2648 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
2649 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2650 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
2653 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
2654 source_info->record = record;
2655 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
2656 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
2657 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
2658 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
2660 source_info->client = msg_ctx->client;
2661 now = GNUNET_TIME_absolute_get_forever();
2663 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
2665 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2666 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
2667 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
2674 * Main function that handles whether or not to route a message to other
2677 * @param cls closure for dht service (NULL)
2678 * @param msg the message to be routed
2679 * @param message_context the context containing all pertinent information about the message
2681 * @return the number of peers the message was routed to,
2682 * GNUNET_SYSERR on failure
2684 static int route_message(void *cls,
2685 const struct GNUNET_MessageHeader *msg,
2686 struct DHT_MessageContext *message_context)
2689 struct PeerInfo *selected;
2690 #if DEBUG_DHT_ROUTING > 1
2691 struct PeerInfo *nearest;
2693 unsigned int forward_count;
2694 struct RecentRequest *recent_req;
2695 GNUNET_HashCode unique_hash;
2696 #if DEBUG_DHT_ROUTING
2700 if (malicious_dropper == GNUNET_YES)
2702 #if DEBUG_DHT_ROUTING
2703 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2705 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2706 message_context->hop_count, GNUNET_SYSERR,
2707 &my_identity, &message_context->key, message_context->peer,
2711 if (message_context->bloom != NULL)
2712 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2716 increment_stats(STAT_ROUTES);
2717 /* Semantics of this call means we find whether we are the closest peer out of those already
2718 * routed to on this messages path.
2720 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
2721 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
2723 if (message_context->bloom == NULL)
2724 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2726 if ((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
2729 #if DEBUG_DHT_ROUTING
2730 if (forward_count == 0)
2731 ret = GNUNET_SYSERR;
2735 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2737 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2738 message_context->hop_count, ret,
2739 &my_identity, &message_context->key, message_context->peer,
2744 switch (ntohs(msg->type))
2746 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
2747 cache_response (cls, message_context);
2748 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
2751 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
2752 increment_stats(STAT_PUTS);
2753 handle_dht_put (cls, msg, message_context);
2755 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
2756 increment_stats(STAT_FIND_PEER);
2757 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
2759 cache_response (cls, message_context);
2760 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
2761 handle_dht_find_peer (cls, msg, message_context);
2763 #if DEBUG_DHT_ROUTING
2764 if (message_context->hop_count == 0) /* Locally initiated request */
2766 if ((debug_routes) && (dhtlog_handle != NULL))
2768 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
2769 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2770 message_context->hop_count, GNUNET_NO, &my_identity,
2771 &message_context->key);
2777 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2778 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
2781 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2782 hash_from_uid(message_context->unique_id, &unique_hash);
2783 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent.hashmap, &unique_hash))
2785 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
2786 GNUNET_assert(recent_req != NULL);
2787 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
2788 increment_stats(STAT_DUPLICATE_UID);
2791 increment_stats(STAT_RECENT_SEEN);
2792 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
2797 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
2798 recent_req->uid = message_context->unique_id;
2799 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
2800 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
2801 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
2802 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2803 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2806 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
2808 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
2809 GNUNET_assert(recent_req != NULL);
2810 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
2811 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
2814 for (i = 0; i < forward_count; i++)
2816 selected = select_peer(&message_context->key, message_context->bloom);
2818 if (selected != NULL)
2820 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
2821 #if DEBUG_DHT_ROUTING > 1
2822 nearest = find_closest_peer(&message_context->key);
2823 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
2824 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2825 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
2826 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&selected->id), nearest_buf, matching_bits(&nearest->id.hashPubKey, message_context->key), distance(&nearest->id.hashPubKey, message_context->key));
2827 GNUNET_free(nearest_buf);
2829 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2831 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2832 message_context->hop_count, GNUNET_NO,
2833 &my_identity, &message_context->key, message_context->peer,
2836 forward_message(cls, msg, selected, message_context);
2841 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2842 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
2847 #if DEBUG_DHT_ROUTING > 1
2848 if (forward_count == 0)
2850 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2851 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
2852 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2856 if (message_context->bloom != NULL)
2858 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
2859 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2862 return forward_count;
2866 * Find a client if it exists, add it otherwise.
2868 * @param client the server handle to the client
2870 * @return the client if found, a new client otherwise
2872 static struct ClientList *
2873 find_active_client (struct GNUNET_SERVER_Client *client)
2875 struct ClientList *pos = client_list;
2876 struct ClientList *ret;
2880 if (pos->client_handle == client)
2885 ret = GNUNET_malloc (sizeof (struct ClientList));
2886 ret->client_handle = client;
2887 ret->next = client_list;
2893 * Task to send a malicious put message across the network.
2895 * @param cls closure for this task
2896 * @param tc the context under which the task is running
2899 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2901 static struct GNUNET_DHT_PutMessage put_message;
2902 static struct DHT_MessageContext message_context;
2903 static GNUNET_HashCode key;
2904 uint32_t random_key;
2906 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2909 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
2910 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
2911 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2912 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
2913 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2914 message_context.client = NULL;
2915 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2916 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2917 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
2918 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2919 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2920 message_context.msg_options = ntohl (0);
2921 message_context.network_size = estimate_diameter();
2922 message_context.peer = &my_identity;
2923 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
2924 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
2925 if (dhtlog_handle != NULL)
2926 dhtlog_handle->insert_dhtkey(NULL, &key);
2927 increment_stats(STAT_PUT_START);
2928 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2929 route_message(NULL, &put_message.header, &message_context);
2930 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
2935 * Task to send a malicious put message across the network.
2937 * @param cls closure for this task
2938 * @param tc the context under which the task is running
2941 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2943 static struct GNUNET_DHT_GetMessage get_message;
2944 struct DHT_MessageContext message_context;
2945 static GNUNET_HashCode key;
2946 uint32_t random_key;
2948 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2951 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
2952 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
2953 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2954 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2955 message_context.client = NULL;
2956 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2957 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2958 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
2959 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2960 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2961 message_context.msg_options = ntohl (0);
2962 message_context.network_size = estimate_diameter();
2963 message_context.peer = &my_identity;
2964 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
2965 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
2966 if (dhtlog_handle != NULL)
2967 dhtlog_handle->insert_dhtkey(NULL, &key);
2968 increment_stats(STAT_GET_START);
2969 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2970 route_message (NULL, &get_message.header, &message_context);
2971 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
2975 * Iterator over hash map entries.
2977 * @param cls closure
2978 * @param key current key code
2979 * @param value value in the hash map
2980 * @return GNUNET_YES if we should continue to
2985 add_known_to_bloom (void *cls,
2986 const GNUNET_HashCode * key,
2989 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
2990 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
2995 * Task to send a find peer message for our own peer identifier
2996 * so that we can find the closest peers in the network to ourselves
2997 * and attempt to connect to them.
2999 * @param cls closure for this task
3000 * @param tc the context under which the task is running
3003 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3005 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3006 struct DHT_MessageContext message_context;
3008 struct GNUNET_TIME_Relative next_send_time;
3009 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3011 struct GNUNET_TIME_Relative time_diff;
3012 struct GNUNET_TIME_Absolute end;
3014 double count_per_interval;
3016 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3019 if ((newly_found_peers > bucket_size) && (GNUNET_YES == do_find_peer)) /* If we are finding peers already, no need to send out our request right now! */
3021 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3022 GNUNET_SCHEDULER_add_delayed (sched,
3023 GNUNET_TIME_UNIT_MINUTES,
3024 &send_find_peer_message, NULL);
3025 newly_found_peers = 0;
3029 increment_stats(STAT_FIND_PEER_START);
3031 end = GNUNET_TIME_absolute_get();
3032 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3034 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3036 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3037 count_per_interval = find_peer_context.count / multiplier;
3041 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3042 count_per_interval = find_peer_context.count * multiplier;
3046 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3047 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3048 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3049 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3050 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3051 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3052 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3053 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3054 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3055 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3056 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3057 message_context.network_size = estimate_diameter();
3058 message_context.peer = &my_identity;
3059 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3060 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3062 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3063 GNUNET_free(find_peer_msg);
3064 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3065 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3067 if (newly_found_peers < bucket_size)
3069 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3070 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3071 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3075 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3076 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3077 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3080 GNUNET_assert (next_send_time.value != 0);
3081 find_peer_context.count = 0;
3082 newly_found_peers = 0;
3083 find_peer_context.start = GNUNET_TIME_absolute_get();
3084 if (GNUNET_YES == do_find_peer)
3086 GNUNET_SCHEDULER_add_delayed (sched,
3088 &send_find_peer_message, NULL);
3093 * Handler for any generic DHT messages, calls the appropriate handler
3094 * depending on message type, sends confirmation if responses aren't otherwise
3097 * @param cls closure for the service
3098 * @param client the client we received this message from
3099 * @param message the actual message received
3102 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3103 const struct GNUNET_MessageHeader *message)
3105 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3106 const struct GNUNET_MessageHeader *enc_msg;
3107 struct DHT_MessageContext message_context;
3108 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3111 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3112 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3113 GNUNET_ntohll (dht_msg->unique_id));
3115 #if DEBUG_DHT_ROUTING
3116 if (dhtlog_handle != NULL)
3117 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3119 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3120 message_context.client = find_active_client (client);
3121 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3122 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3123 message_context.replication = ntohl (dht_msg->desired_replication_level);
3124 message_context.msg_options = ntohl (dht_msg->options);
3125 message_context.network_size = estimate_diameter();
3126 message_context.peer = &my_identity;
3127 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3128 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3129 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3130 increment_stats(STAT_GET_START);
3131 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3132 increment_stats(STAT_PUT_START);
3133 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3134 increment_stats(STAT_FIND_PEER_START);
3136 route_message(cls, enc_msg, &message_context);
3138 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3143 * Handler for any locally received DHT control messages,
3144 * sets malicious flags mostly for now.
3146 * @param cls closure for the service
3147 * @param client the client we received this message from
3148 * @param message the actual message received
3152 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3153 const struct GNUNET_MessageHeader *message)
3155 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3156 (const struct GNUNET_DHT_ControlMessage *) message;
3158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3159 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3160 "CONTROL", ntohs(dht_control_msg->command));
3163 switch (ntohs(dht_control_msg->command))
3165 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3166 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending self seeking find peer request!\n");
3167 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3169 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3170 if (ntohs(dht_control_msg->variable) > 0)
3171 malicious_get_frequency = ntohs(dht_control_msg->variable);
3172 if (malicious_get_frequency == 0)
3173 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3174 if (malicious_getter != GNUNET_YES)
3175 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3176 malicious_getter = GNUNET_YES;
3177 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3179 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3180 if (ntohs(dht_control_msg->variable) > 0)
3181 malicious_put_frequency = ntohs(dht_control_msg->variable);
3182 if (malicious_put_frequency == 0)
3183 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3184 if (malicious_putter != GNUNET_YES)
3185 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3186 malicious_putter = GNUNET_YES;
3187 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3189 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3190 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3191 dhtlog_handle->set_malicious(&my_identity);
3192 malicious_dropper = GNUNET_YES;
3193 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3196 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3199 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3203 * Handler for any generic DHT stop messages, calls the appropriate handler
3204 * depending on message type (if processed locally)
3206 * @param cls closure for the service
3207 * @param client the client we received this message from
3208 * @param message the actual message received
3212 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3213 const struct GNUNET_MessageHeader *message)
3216 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3217 (const struct GNUNET_DHT_StopMessage *) message;
3218 struct DHTQueryRecord *record;
3219 struct DHTRouteSource *pos;
3221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3222 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3223 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3225 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3232 if ((pos->client != NULL) && (pos->client->client_handle == client))
3234 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3235 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3241 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3246 * Core handler for p2p route requests.
3249 handle_dht_p2p_route_request (void *cls,
3250 const struct GNUNET_PeerIdentity *peer,
3251 const struct GNUNET_MessageHeader *message,
3252 struct GNUNET_TIME_Relative latency, uint32_t distance)
3255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3256 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3258 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3259 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3260 struct DHT_MessageContext *message_context;
3262 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
3264 fprintf(stderr, "Sending of previous requests has taken far too long, backing off!\n");
3268 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3271 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3276 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3281 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3282 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3283 GNUNET_assert(message_context->bloom != NULL);
3284 message_context->hop_count = ntohl(incoming->hop_count);
3285 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
3286 message_context->replication = ntohl(incoming->desired_replication_level);
3287 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3288 message_context->msg_options = ntohl(incoming->options);
3289 message_context->network_size = ntohl(incoming->network_size);
3290 message_context->peer = peer;
3291 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3292 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3293 route_message(cls, enc_msg, message_context);
3294 GNUNET_free(message_context);
3300 * Core handler for p2p route results.
3303 handle_dht_p2p_route_result (void *cls,
3304 const struct GNUNET_PeerIdentity *peer,
3305 const struct GNUNET_MessageHeader *message,
3306 struct GNUNET_TIME_Relative latency, uint32_t distance)
3309 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3310 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3312 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3313 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3314 struct DHT_MessageContext message_context;
3316 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3322 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3323 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3324 GNUNET_assert(message_context.bloom != NULL);
3325 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
3326 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3327 message_context.msg_options = ntohl(incoming->options);
3328 message_context.hop_count = ntohl(incoming->hop_count);
3329 message_context.peer = peer;
3330 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3331 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3332 route_result_message(cls, enc_msg, &message_context);
3338 * Receive the HELLO from transport service,
3339 * free current and replace if necessary.
3342 * @param message HELLO message of peer
3345 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3349 "Received our `%s' from transport service\n",
3353 GNUNET_assert (message != NULL);
3354 GNUNET_free_non_null(my_hello);
3355 my_hello = GNUNET_malloc(ntohs(message->size));
3356 memcpy(my_hello, message, ntohs(message->size));
3361 * Task run during shutdown.
3367 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3370 struct PeerInfo *pos;
3371 if (transport_handle != NULL)
3373 GNUNET_free_non_null(my_hello);
3374 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3375 GNUNET_TRANSPORT_disconnect(transport_handle);
3378 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3380 while (k_buckets[bucket_count].head != NULL)
3382 pos = k_buckets[bucket_count].head;
3384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3385 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3387 delete_peer(pos, bucket_count);
3390 if (coreAPI != NULL)
3393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3394 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3396 GNUNET_CORE_disconnect (coreAPI);
3398 if (datacache != NULL)
3401 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3402 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3404 GNUNET_DATACACHE_destroy (datacache);
3409 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3412 if (dhtlog_handle != NULL)
3413 GNUNET_DHTLOG_disconnect(dhtlog_handle);
3415 GNUNET_free_non_null(my_short_id);
3420 * To be called on core init/fail.
3422 * @param cls service closure
3423 * @param server handle to the server for this service
3424 * @param identity the public identity of this peer
3425 * @param publicKey the public key of this peer
3428 core_init (void *cls,
3429 struct GNUNET_CORE_Handle *server,
3430 const struct GNUNET_PeerIdentity *identity,
3431 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3438 "%s: Connection to core FAILED!\n", "dht",
3439 GNUNET_i2s (identity));
3441 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
3442 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3446 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3447 "%s: Core connection initialized, I am peer: %s\n", "dht",
3448 GNUNET_i2s (identity));
3451 /* Copy our identity so we can use it */
3452 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3453 if (my_short_id != NULL)
3454 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3455 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3456 /* Set the server to local variable */
3459 if (dhtlog_handle != NULL)
3460 dhtlog_handle->insert_node (NULL, &my_identity);
3464 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3465 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3466 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3467 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
3472 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3473 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
3474 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
3479 * Method called whenever a peer connects.
3481 * @param cls closure
3482 * @param peer peer identity this notification is about
3483 * @param latency reported latency of the connection with peer
3484 * @param distance reported distance (DV) to peer
3486 void handle_core_connect (void *cls,
3487 const struct GNUNET_PeerIdentity * peer,
3488 struct GNUNET_TIME_Relative latency,
3491 struct PeerInfo *ret;
3494 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3495 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
3498 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3500 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received %s message for peer %s, but already have peer in RT!", my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s(peer));
3504 if (datacache != NULL)
3505 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
3506 ret = try_add_peer(peer,
3507 find_current_bucket(&peer->hashPubKey),
3512 newly_found_peers++;
3513 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3516 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3517 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
3522 * Method called whenever a peer disconnects.
3524 * @param cls closure
3525 * @param peer peer identity this notification is about
3527 void handle_core_disconnect (void *cls,
3529 GNUNET_PeerIdentity * peer)
3531 struct PeerInfo *to_remove;
3534 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s: Received peer disconnect message for peer `%s' from %s\n", my_short_id, "DHT", GNUNET_i2s(peer), "CORE");
3536 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3538 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s: do not have peer `%s' in RT, can't disconnect!\n", my_short_id, "DHT", GNUNET_i2s(peer));
3541 increment_stats(STAT_DISCONNECTS);
3542 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
3543 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
3544 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
3545 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
3546 delete_peer(to_remove, current_bucket);
3550 * Process dht requests.
3552 * @param cls closure
3553 * @param scheduler scheduler to use
3554 * @param server the initialized server
3555 * @param c configuration to use
3559 struct GNUNET_SCHEDULER_Handle *scheduler,
3560 struct GNUNET_SERVER_Handle *server,
3561 const struct GNUNET_CONFIGURATION_Handle *c)
3564 struct GNUNET_TIME_Relative next_send_time;
3568 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
3569 GNUNET_SERVER_add_handlers (server, plugin_handlers);
3570 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
3571 cfg, /* Main configuration */
3572 GNUNET_TIME_UNIT_FOREVER_REL,
3573 NULL, /* Closure passed to DHT functions */
3574 &core_init, /* Call core_init once connected */
3575 &handle_core_connect, /* Handle connects */
3576 &handle_core_disconnect, /* remove peers on disconnects */
3577 NULL, /* Do we care about "status" updates? */
3578 NULL, /* Don't want notified about all incoming messages */
3579 GNUNET_NO, /* For header only inbound notification */
3580 NULL, /* Don't want notified about all outbound messages */
3581 GNUNET_NO, /* For header only outbound notification */
3582 core_handlers); /* Register these handlers */
3584 if (coreAPI == NULL)
3586 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
3587 NULL, NULL, NULL, NULL, NULL);
3588 if (transport_handle != NULL)
3589 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
3591 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
3593 lowest_bucket = MAX_BUCKETS - 1;
3594 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
3595 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3596 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
3597 GNUNET_assert(all_known_peers != NULL);
3598 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
3600 debug_routes = GNUNET_YES;
3604 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3607 strict_kademlia = GNUNET_YES;
3611 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3614 stop_on_closest = GNUNET_YES;
3618 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3621 stop_on_found = GNUNET_YES;
3625 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3626 "malicious_getter"))
3628 malicious_getter = GNUNET_YES;
3629 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3630 "MALICIOUS_GET_FREQUENCY",
3631 &malicious_get_frequency))
3632 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3636 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3637 "malicious_putter"))
3639 malicious_putter = GNUNET_YES;
3640 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3641 "MALICIOUS_PUT_FREQUENCY",
3642 &malicious_put_frequency))
3643 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3647 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3648 "malicious_dropper"))
3650 malicious_dropper = GNUNET_YES;
3654 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3657 do_find_peer = GNUNET_NO;
3660 do_find_peer = GNUNET_YES;
3663 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
3664 "mysql_logging_extended"))
3666 debug_routes = GNUNET_YES;
3667 debug_routes_extended = GNUNET_YES;
3670 if (GNUNET_YES == debug_routes)
3672 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
3673 if (dhtlog_handle == NULL)
3675 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3676 "Could not connect to mysql logging server, logging will not happen!");
3680 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
3684 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
3685 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
3686 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
3687 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
3688 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
3689 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
3690 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
3691 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
3692 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
3693 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
3694 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
3695 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
3696 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
3697 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
3698 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
3699 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
3700 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
3701 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
3702 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
3703 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
3705 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
3706 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
3707 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3708 if (GNUNET_YES == do_find_peer)
3710 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3711 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3712 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3713 find_peer_context.start = GNUNET_TIME_absolute_get();
3714 GNUNET_SCHEDULER_add_delayed (sched,
3716 &send_find_peer_message, &find_peer_context);
3719 /* Scheduled the task to clean up when shutdown is called */
3720 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
3721 GNUNET_TIME_UNIT_FOREVER_REL,
3722 &shutdown_task, NULL);
3726 * The main function for the dht service.
3728 * @param argc number of arguments from the command line
3729 * @param argv command line arguments
3730 * @return 0 ok, 1 on error
3733 main (int argc, char *const *argv)
3735 return (GNUNET_OK ==
3736 GNUNET_SERVICE_run (argc,
3739 GNUNET_SERVICE_OPTION_NONE,
3740 &run, NULL)) ? 0 : 1;