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 1
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;
474 * Bloomfilter of peers we have already sent back as
475 * replies to the initial request. Allows us to not
476 * forward the same peer multiple times for a find peer
479 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
484 * Entry in the DHT routing table.
486 struct DHTQueryRecord
489 * Head of DLL for result forwarding.
491 struct DHTRouteSource *head;
494 * Tail of DLL for result forwarding.
496 struct DHTRouteSource *tail;
499 * Key that the record concerns.
504 * GET message of this record (what we already forwarded?).
506 //DV_DHT_MESSAGE get; Try to get away with not saving this.
509 * Bloomfilter of the peers we've replied to so far
511 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
516 * Context used to calculate the number of find peer messages
517 * per X time units since our last scheduled find peer message
518 * was sent. If we have seen too many messages, delay or don't
521 struct FindPeerMessageContext
525 struct GNUNET_TIME_Absolute start;
527 struct GNUNET_TIME_Absolute end;
531 * DHT Routing results structure
536 * Min heap for removal upon reaching limit
538 struct GNUNET_CONTAINER_Heap *minHeap;
541 * Hashmap for fast key based lookup
543 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
548 * DHT structure for recent requests.
550 struct RecentRequests
553 * Min heap for removal upon reaching limit
555 struct GNUNET_CONTAINER_Heap *minHeap;
558 * Hashmap for key based lookup
560 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
566 * Position of this node in the min heap.
568 struct GNUNET_CONTAINER_HeapNode *heap_node;
571 * Bloomfilter containing entries for peers
572 * we forwarded this request to.
574 struct GNUNET_CONTAINER_BloomFilter *bloom;
577 * Timestamp of this request, for ordering
580 struct GNUNET_TIME_Absolute timestamp;
583 * Key of this request.
588 * Unique identifier for this request.
593 * Task to remove this entry on timeout.
595 GNUNET_SCHEDULER_TaskIdentifier remove_task;
599 * Recent requests by hash/uid and by time inserted.
601 static struct RecentRequests recent;
604 * Context to use to calculate find peer rates.
606 static struct FindPeerMessageContext find_peer_context;
609 * Don't use our routing algorithm, always route
610 * to closest peer; initially send requests to 3
613 static int strict_kademlia;
616 * Routing option to end routing when closest peer found.
618 static int stop_on_closest;
621 * Routing option to end routing when data is found.
623 static int stop_on_found;
626 * Whether DHT needs to manage find peer requests, or
627 * an external force will do it on behalf of the DHT.
629 static int do_find_peer;
632 * How many peers have we added since we sent out our last
635 static unsigned int newly_found_peers;
638 * Container of active queries we should remember
640 static struct DHTResults forward_list;
643 * Handle to the datacache service (for inserting/retrieving data)
645 static struct GNUNET_DATACACHE_Handle *datacache;
648 * Handle for the statistics service.
650 struct GNUNET_STATISTICS_Handle *stats;
653 * The main scheduler to use for the DHT service
655 static struct GNUNET_SCHEDULER_Handle *sched;
658 * The configuration the DHT service is running with
660 static const struct GNUNET_CONFIGURATION_Handle *cfg;
663 * Handle to the core service
665 static struct GNUNET_CORE_Handle *coreAPI;
668 * Handle to the transport service, for getting our hello
670 static struct GNUNET_TRANSPORT_Handle *transport_handle;
673 * The identity of our peer.
675 static struct GNUNET_PeerIdentity my_identity;
678 * Short id of the peer, for printing
680 static char *my_short_id;
685 static struct GNUNET_MessageHeader *my_hello;
688 * Task to run when we shut down, cleaning up all our trash
690 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
693 * The lowest currently used bucket.
695 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
698 * The buckets (Kademlia routing table, complete with growth).
699 * Array of size MAX_BUCKET_SIZE.
701 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
704 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
706 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
709 * Recently seen find peer requests.
711 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
714 * Maximum size for each bucket.
716 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
719 * List of active clients.
721 static struct ClientList *client_list;
724 * Handle to the DHT logger.
726 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
729 * Whether or not to send routing debugging information
730 * to the dht logging server
732 static unsigned int debug_routes;
735 * Whether or not to send FULL route information to
738 static unsigned int debug_routes_extended;
741 * GNUNET_YES or GNUNET_NO, whether or not to act as
742 * a malicious node which drops all messages
744 static unsigned int malicious_dropper;
747 * GNUNET_YES or GNUNET_NO, whether or not to act as
748 * a malicious node which sends out lots of GETS
750 static unsigned int malicious_getter;
753 * GNUNET_YES or GNUNET_NO, whether or not to act as
754 * a malicious node which sends out lots of PUTS
756 static unsigned int malicious_putter;
759 * Frequency for malicious get requests.
761 static unsigned long long malicious_get_frequency;
764 * Frequency for malicious put requests.
766 static unsigned long long malicious_put_frequency;
769 * Reply times for requests, if we are busy, don't send any
772 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
775 * Current counter for replies.
777 static unsigned int reply_counter;
780 * Forward declaration.
782 static size_t send_generic_reply (void *cls, size_t size, void *buf);
784 /** Declare here so retry_core_send is aware of it */
785 size_t core_transmit_notify (void *cls,
786 size_t size, void *buf);
789 * Convert unique ID to hash code.
791 * @param uid unique ID to convert
792 * @param hash set to uid (extended with zeros)
795 hash_from_uid (uint64_t uid,
796 GNUNET_HashCode *hash)
798 memset (hash, 0, sizeof(GNUNET_HashCode));
799 *((uint64_t*)hash) = uid;
804 * Calculate the average send time between messages so that we can
805 * ignore certain requests if we get too busy.
807 * @return the average time between asking core to send a message
808 * and when the buffer for copying it is passed
810 static struct GNUNET_TIME_Relative get_average_send_delay()
813 unsigned int divisor;
814 struct GNUNET_TIME_Relative average_time;
815 average_time = GNUNET_TIME_relative_get_zero();
817 for (i = 0; i < MAX_REPLY_TIMES; i++)
819 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
820 if (reply_times[i].value == (uint64_t)0)
830 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
831 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
837 * Find the maximum send time of the recently sent values.
839 * @return the average time between asking core to send a message
840 * and when the buffer for copying it is passed
842 static struct GNUNET_TIME_Relative get_max_send_delay()
845 struct GNUNET_TIME_Relative max_time;
846 max_time = GNUNET_TIME_relative_get_zero();
848 for (i = 0; i < MAX_REPLY_TIMES; i++)
850 if (reply_times[i].value > max_time.value)
851 max_time.value = reply_times[i].value;
854 if (max_time.value > MAX_REQUEST_TIME.value)
855 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
860 increment_stats(const char *value)
864 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
869 * Try to send another message from our core send list
872 try_core_send (void *cls,
873 const struct GNUNET_SCHEDULER_TaskContext *tc)
875 struct PeerInfo *peer = cls;
876 struct P2PPendingMessage *pending;
879 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
881 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
884 if (peer->th != NULL)
885 return; /* Message send already in progress */
887 pending = peer->head;
890 ssize = ntohs(pending->msg->size);
892 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
893 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
894 "DHT", ssize, GNUNET_i2s(&peer->id));
896 pending->scheduled = GNUNET_TIME_absolute_get();
898 if (reply_counter >= MAX_REPLY_TIMES)
900 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
901 pending->timeout, &peer->id,
902 ssize, &core_transmit_notify, peer);
907 * Function called to send a request out to another peer.
908 * Called both for locally initiated requests and those
909 * received from other peers.
911 * @param cls DHT service closure argument
912 * @param msg the encapsulated message
913 * @param peer the peer to forward the message to
914 * @param msg_ctx the context of the message (hop count, bloom, etc.)
916 static void forward_result_message (void *cls,
917 const struct GNUNET_MessageHeader *msg,
918 struct PeerInfo *peer,
919 struct DHT_MessageContext *msg_ctx)
921 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
922 struct P2PPendingMessage *pending;
926 increment_stats(STAT_RESULT_FORWARDS);
927 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
928 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
929 psize = sizeof(struct P2PPendingMessage) + msize;
930 pending = GNUNET_malloc(psize);
931 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
932 pending->importance = DHT_SEND_PRIORITY;
933 pending->timeout = GNUNET_TIME_relative_get_forever();
934 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
935 result_message->header.size = htons(msize);
936 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
937 result_message->options = htonl(msg_ctx->msg_options);
938 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
939 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
940 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
941 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
942 memcpy(&result_message[1], msg, ntohs(msg->size));
944 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));
946 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
947 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
948 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
951 * Called when core is ready to send a message we asked for
952 * out to the destination.
954 * @param cls closure (NULL)
955 * @param size number of bytes available in buf
956 * @param buf where the callee should write the message
957 * @return number of bytes written to buf
959 size_t core_transmit_notify (void *cls,
960 size_t size, void *buf)
962 struct PeerInfo *peer = cls;
964 struct P2PPendingMessage *pending;
971 /* client disconnected */
973 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
978 if (peer->head == NULL)
983 pending = peer->head;
984 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
985 msize = ntohs(pending->msg->size);
989 memcpy (cbuf, pending->msg, msize);
990 GNUNET_CONTAINER_DLL_remove (peer->head,
994 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));
996 GNUNET_free (pending);
999 while (NULL != pending &&
1000 (size - off >= (msize = ntohs (pending->msg->size))))
1002 #if DEBUG_DHT_ROUTING
1003 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);
1005 memcpy (&cbuf[off], pending->msg, msize);
1007 GNUNET_CONTAINER_DLL_remove (peer->head,
1010 GNUNET_free (pending);
1011 pending = peer->head;
1014 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1015 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1017 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);
1023 * Determine how many low order bits match in two
1024 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
1025 * the first two lowest order bits, and therefore the
1026 * return value is two (NOT XOR distance, nor how many
1027 * bits match absolutely!).
1029 * @param first the first hashcode
1030 * @param second the hashcode to compare first to
1032 * @return the number of bits that match
1034 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
1038 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
1039 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
1041 return sizeof (GNUNET_HashCode) * 8;
1045 * Compute the distance between have and target as a 32-bit value.
1046 * Differences in the lower bits must count stronger than differences
1047 * in the higher bits.
1049 * @return 0 if have==target, otherwise a number
1050 * that is larger as the distance between
1051 * the two hash codes increases
1054 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1056 unsigned int bucket;
1061 /* We have to represent the distance between two 2^9 (=512)-bit
1062 numbers as a 2^5 (=32)-bit number with "0" being used for the
1063 two numbers being identical; furthermore, we need to
1064 guarantee that a difference in the number of matching
1065 bits is always represented in the result.
1067 We use 2^32/2^9 numerical values to distinguish between
1068 hash codes that have the same LSB bit distance and
1069 use the highest 2^9 bits of the result to signify the
1070 number of (mis)matching LSB bits; if we have 0 matching
1071 and hence 512 mismatching LSB bits we return -1 (since
1072 512 itself cannot be represented with 9 bits) */
1074 /* first, calculate the most significant 9 bits of our
1075 result, aka the number of LSBs */
1076 bucket = matching_bits (target, have);
1077 /* bucket is now a value between 0 and 512 */
1079 return 0; /* perfect match */
1081 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1082 below, we'd end up with max+1 (overflow)) */
1084 /* calculate the most significant bits of the final result */
1085 msb = (512 - bucket) << (32 - 9);
1086 /* calculate the 32-9 least significant bits of the final result by
1087 looking at the differences in the 32-9 bits following the
1088 mismatching bit at 'bucket' */
1090 for (i = bucket + 1;
1091 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1093 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1094 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1095 last bit set will be 31 -- if
1096 i does not reach 512 first... */
1102 * Return a number that is larger the closer the
1103 * "have" GNUNET_hash code is to the "target".
1105 * @return inverse distance metric, non-zero.
1106 * Must fudge the value if NO bits match.
1109 inverse_distance (const GNUNET_HashCode * target,
1110 const GNUNET_HashCode * have)
1112 if (matching_bits(target, have) == 0)
1113 return 1; /* Never return 0! */
1114 return ((unsigned int) -1) - distance (target, have);
1118 * Find the optimal bucket for this key, regardless
1119 * of the current number of buckets in use.
1121 * @param hc the hashcode to compare our identity to
1123 * @return the proper bucket index, or GNUNET_SYSERR
1124 * on error (same hashcode)
1126 static int find_bucket(const GNUNET_HashCode *hc)
1130 bits = matching_bits(&my_identity.hashPubKey, hc);
1131 if (bits == MAX_BUCKETS)
1132 return GNUNET_SYSERR;
1133 return MAX_BUCKETS - bits - 1;
1137 * Find which k-bucket this peer should go into,
1138 * taking into account the size of the k-bucket
1139 * array. This means that if more bits match than
1140 * there are currently buckets, lowest_bucket will
1143 * @param hc GNUNET_HashCode we are finding the bucket for.
1145 * @return the proper bucket index for this key,
1146 * or GNUNET_SYSERR on error (same hashcode)
1148 static int find_current_bucket(const GNUNET_HashCode *hc)
1151 actual_bucket = find_bucket(hc);
1153 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1154 return GNUNET_SYSERR;
1155 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1156 return lowest_bucket;
1158 return actual_bucket;
1163 * Find a routing table entry from a peer identity
1165 * @param peer the peer to look up
1167 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1170 find_bucket_by_peer(const struct PeerInfo *peer)
1173 struct PeerInfo *pos;
1175 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1177 pos = k_buckets[bucket].head;
1186 return GNUNET_SYSERR; /* No such peer. */
1192 * Print the complete routing table for this peer.
1195 print_routing_table ()
1198 struct PeerInfo *pos;
1199 char char_buf[30000];
1201 memset(char_buf, 0, sizeof(char_buf));
1203 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1204 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1205 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1207 pos = k_buckets[bucket].head;
1208 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1209 //fprintf(stderr, "Bucket %d:\n", bucket);
1212 //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));
1213 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));
1217 fprintf(stderr, "%s", char_buf);
1223 * Find a routing table entry from a peer identity
1225 * @param peer the peer identity to look up
1227 * @return the routing table entry, or NULL if not found
1229 static struct PeerInfo *
1230 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1233 struct PeerInfo *pos;
1234 bucket = find_current_bucket(&peer->hashPubKey);
1236 if (bucket == GNUNET_SYSERR)
1239 pos = k_buckets[bucket].head;
1242 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1246 return NULL; /* No such peer. */
1249 /* Forward declaration */
1251 update_core_preference (void *cls,
1252 const struct GNUNET_SCHEDULER_TaskContext *tc);
1254 * Function called with statistics about the given peer.
1256 * @param cls closure
1257 * @param peer identifies the peer
1258 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1259 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1260 * @param latency current latency estimate, "FOREVER" if we have been
1262 * @param amount set to the amount that was actually reserved or unreserved;
1263 * either the full requested amount or zero (no partial reservations)
1264 * @param preference current traffic preference for the given peer
1267 update_core_preference_finish (void *cls,
1269 GNUNET_PeerIdentity * peer,
1270 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1271 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1273 uint64_t preference)
1275 struct PeerInfo *peer_info = cls;
1276 peer_info->info_ctx = NULL;
1277 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1281 update_core_preference (void *cls,
1282 const struct GNUNET_SCHEDULER_TaskContext *tc)
1284 struct PeerInfo *peer = cls;
1285 uint64_t preference;
1287 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1292 preference = 2 << matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1293 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1295 GNUNET_TIME_relative_get_forever(),
1296 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1299 &update_core_preference_finish,
1304 * Really add a peer to a bucket (only do assertions
1307 * @param peer GNUNET_PeerIdentity of the peer to add
1308 * @param bucket the already figured out bucket to add
1310 * @param latency the core reported latency of this peer
1311 * @param distance the transport level distance to this peer
1313 * @return the newly added PeerInfo
1315 static struct PeerInfo *
1316 add_peer(const struct GNUNET_PeerIdentity *peer,
1317 unsigned int bucket,
1318 struct GNUNET_TIME_Relative latency,
1319 unsigned int distance)
1321 struct PeerInfo *new_peer;
1322 GNUNET_assert(bucket < MAX_BUCKETS);
1323 GNUNET_assert(peer != NULL);
1324 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1325 new_peer->latency = latency;
1326 new_peer->distance = distance;
1328 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1330 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1331 k_buckets[bucket].tail,
1332 k_buckets[bucket].tail,
1334 k_buckets[bucket].peers_size++;
1336 if ((matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1338 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1345 * Given a peer and its corresponding bucket,
1346 * remove it from that bucket. Does not free
1347 * the PeerInfo struct, nor cancel messages
1348 * or free messages waiting to be sent to this
1351 * @param peer the peer to remove
1352 * @param bucket the bucket the peer belongs to
1354 static void remove_peer (struct PeerInfo *peer,
1355 unsigned int bucket)
1357 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1358 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1359 k_buckets[bucket].tail,
1361 k_buckets[bucket].peers_size--;
1362 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1367 * Removes peer from a bucket, then frees associated
1368 * resources and frees peer.
1370 * @param peer peer to be removed and freed
1371 * @param bucket which bucket this peer belongs to
1373 static void delete_peer (struct PeerInfo *peer,
1374 unsigned int bucket)
1376 struct P2PPendingMessage *pos;
1377 struct P2PPendingMessage *next;
1379 struct PeerInfo *peer_pos;
1381 peer_pos = k_buckets[bucket].head;
1382 while ((peer_pos != NULL) && (peer_pos != peer))
1383 peer_pos = peer_pos->next;
1384 if (peer_pos == NULL)
1386 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1387 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));
1389 GNUNET_assert(peer_pos != NULL);
1391 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1393 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1394 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1395 if (peer->th != NULL)
1396 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1399 while (pos != NULL) /* Remove any pending messages for this peer */
1406 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1407 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1413 * Iterator over hash map entries.
1415 * @param cls closure
1416 * @param key current key code
1417 * @param value PeerInfo of the peer to move to new lowest bucket
1418 * @return GNUNET_YES if we should continue to
1422 static int move_lowest_bucket (void *cls,
1423 const GNUNET_HashCode * key,
1426 struct PeerInfo *peer = value;
1429 GNUNET_assert(lowest_bucket > 0);
1430 new_bucket = lowest_bucket - 1;
1431 remove_peer(peer, lowest_bucket);
1432 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1433 k_buckets[new_bucket].tail,
1434 k_buckets[new_bucket].tail,
1436 k_buckets[new_bucket].peers_size++;
1442 * The current lowest bucket is full, so change the lowest
1443 * bucket to the next lower down, and move any appropriate
1444 * entries in the current lowest bucket to the new bucket.
1446 static void enable_next_bucket()
1448 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1449 struct PeerInfo *pos;
1450 GNUNET_assert(lowest_bucket > 0);
1451 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1452 pos = k_buckets[lowest_bucket].head;
1455 fprintf(stderr, "Printing RT before new bucket\n");
1456 print_routing_table();
1458 /* Populate the array of peers which should be in the next lowest bucket */
1461 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1462 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1466 /* Remove peers from lowest bucket, insert into next lowest bucket */
1467 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1468 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1469 lowest_bucket = lowest_bucket - 1;
1471 fprintf(stderr, "Printing RT after new bucket\n");
1472 print_routing_table();
1477 * Find the closest peer in our routing table to the
1480 * @return The closest peer in our routing table to the
1481 * key, or NULL on error.
1483 static struct PeerInfo *
1484 find_closest_peer (const GNUNET_HashCode *hc)
1486 struct PeerInfo *pos;
1487 struct PeerInfo *current_closest;
1488 unsigned int lowest_distance;
1489 unsigned int temp_distance;
1493 lowest_distance = -1;
1495 if (k_buckets[lowest_bucket].peers_size == 0)
1498 current_closest = NULL;
1499 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1501 pos = k_buckets[bucket].head;
1503 while ((pos != NULL) && (count < bucket_size))
1505 temp_distance = distance(&pos->id.hashPubKey, hc);
1506 if (temp_distance <= lowest_distance)
1508 lowest_distance = temp_distance;
1509 current_closest = pos;
1515 GNUNET_assert(current_closest != NULL);
1516 return current_closest;
1521 * Function called to send a request out to another peer.
1522 * Called both for locally initiated requests and those
1523 * received from other peers.
1525 * @param cls DHT service closure argument (unused)
1526 * @param msg the encapsulated message
1527 * @param peer the peer to forward the message to
1528 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1530 static void forward_message (void *cls,
1531 const struct GNUNET_MessageHeader *msg,
1532 struct PeerInfo *peer,
1533 struct DHT_MessageContext *msg_ctx)
1535 struct GNUNET_DHT_P2PRouteMessage *route_message;
1536 struct P2PPendingMessage *pending;
1540 increment_stats(STAT_ROUTE_FORWARDS);
1542 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1543 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1545 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1546 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1547 psize = sizeof(struct P2PPendingMessage) + msize;
1548 pending = GNUNET_malloc(psize);
1549 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1550 pending->importance = msg_ctx->importance;
1551 pending->timeout = msg_ctx->timeout;
1552 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1553 route_message->header.size = htons(msize);
1554 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1555 route_message->options = htonl(msg_ctx->msg_options);
1556 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1557 route_message->network_size = htonl(msg_ctx->network_size);
1558 route_message->desired_replication_level = htonl(msg_ctx->replication);
1559 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1560 if (msg_ctx->bloom != NULL)
1561 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1562 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1563 memcpy(&route_message[1], msg, ntohs(msg->size));
1565 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));
1567 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1568 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1569 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1574 * Task used to send ping messages to peers so that
1575 * they don't get disconnected.
1577 * @param cls the peer to send a ping message to
1578 * @param tc context, reason, etc.
1581 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1583 struct PeerInfo *peer = cls;
1584 struct GNUNET_MessageHeader ping_message;
1585 struct DHT_MessageContext message_context;
1587 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1590 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1591 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1593 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1595 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1597 forward_message(NULL, &ping_message, peer, &message_context);
1598 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1602 * Schedule PING messages for the top X peers in each
1603 * bucket of the routing table (so core won't disconnect them!)
1605 void schedule_ping_messages()
1607 unsigned int bucket;
1609 struct PeerInfo *pos;
1610 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1612 pos = k_buckets[bucket].head;
1616 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1617 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1618 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1620 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1621 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1631 * Attempt to add a peer to our k-buckets.
1633 * @param peer, the peer identity of the peer being added
1635 * @return NULL if the peer was not added,
1636 * pointer to PeerInfo for new peer otherwise
1638 static struct PeerInfo *
1639 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1640 unsigned int bucket,
1641 struct GNUNET_TIME_Relative latency,
1642 unsigned int distance)
1645 struct PeerInfo *new_peer;
1646 peer_bucket = find_current_bucket(&peer->hashPubKey);
1647 if (peer_bucket == GNUNET_SYSERR)
1650 GNUNET_assert(peer_bucket >= lowest_bucket);
1651 new_peer = add_peer(peer, peer_bucket, latency, distance);
1653 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1654 enable_next_bucket();
1656 schedule_ping_messages();
1663 * Task run to check for messages that need to be sent to a client.
1665 * @param client a ClientList, containing the client and any messages to be sent to it
1668 process_pending_messages (struct ClientList *client)
1670 if (client->pending_head == NULL)
1672 if (client->transmit_handle != NULL)
1674 client->transmit_handle =
1675 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1676 ntohs (client->pending_head->msg->
1678 GNUNET_TIME_UNIT_FOREVER_REL,
1679 &send_generic_reply, client);
1683 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1684 * request. A ClientList is passed as closure, take the head of the list
1685 * and copy it into buf, which has the result of sending the message to the
1688 * @param cls closure to this call
1689 * @param size maximum number of bytes available to send
1690 * @param buf where to copy the actual message to
1692 * @return the number of bytes actually copied, 0 indicates failure
1695 send_generic_reply (void *cls, size_t size, void *buf)
1697 struct ClientList *client = cls;
1699 struct PendingMessage *reply;
1703 client->transmit_handle = NULL;
1706 /* client disconnected */
1710 while ( (NULL != (reply = client->pending_head)) &&
1711 (size >= off + (msize = ntohs (reply->msg->size))))
1713 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1714 client->pending_tail,
1716 memcpy (&cbuf[off], reply->msg, msize);
1717 GNUNET_free (reply);
1720 process_pending_messages (client);
1726 * Add a PendingMessage to the clients list of messages to be sent
1728 * @param client the active client to send the message to
1729 * @param pending_message the actual message to send
1732 add_pending_message (struct ClientList *client,
1733 struct PendingMessage *pending_message)
1735 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1736 client->pending_tail,
1737 client->pending_tail,
1739 process_pending_messages (client);
1746 * Called when a reply needs to be sent to a client, as
1747 * a result it found to a GET or FIND PEER request.
1749 * @param client the client to send the reply to
1750 * @param message the encapsulated message to send
1751 * @param uid the unique identifier of this request
1754 send_reply_to_client (struct ClientList *client,
1755 const struct GNUNET_MessageHeader *message,
1756 unsigned long long uid)
1758 struct GNUNET_DHT_RouteResultMessage *reply;
1759 struct PendingMessage *pending_message;
1763 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1764 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1766 msize = ntohs (message->size);
1767 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1768 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1770 GNUNET_break_op (0);
1774 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1775 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1776 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1777 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1778 reply->header.size = htons (tsize);
1779 reply->unique_id = GNUNET_htonll (uid);
1780 memcpy (&reply[1], message, msize);
1782 add_pending_message (client, pending_message);
1786 * Consider whether or not we would like to have this peer added to
1787 * our routing table. Check whether bucket for this peer is full,
1788 * if so return negative; if not return positive. Since peers are
1789 * only added on CORE level connect, this doesn't actually add the
1790 * peer to the routing table.
1792 * @param peer the peer we are considering adding
1794 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1797 * FIXME: Think about making a context for this call so that we can
1798 * ping the oldest peer in the current bucket and consider
1799 * removing it in lieu of the new peer.
1801 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1805 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1806 return GNUNET_NO; /* We already know this peer (are connected even!) */
1807 bucket = find_current_bucket(&peer->hashPubKey);
1808 if (bucket == GNUNET_SYSERR)
1810 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1817 * Main function that handles whether or not to route a result
1818 * message to other peers, or to send to our local client.
1820 * @param msg the result message to be routed
1821 * @return the number of peers the message was routed to,
1822 * GNUNET_SYSERR on failure
1824 static int route_result_message(void *cls,
1825 struct GNUNET_MessageHeader *msg,
1826 struct DHT_MessageContext *message_context)
1828 struct GNUNET_PeerIdentity new_peer;
1829 struct DHTQueryRecord *record;
1830 struct DHTRouteSource *pos;
1831 struct PeerInfo *peer_info;
1832 const struct GNUNET_MessageHeader *hello_msg;
1834 increment_stats(STAT_RESULTS);
1836 * If a find peer result message is received and contains a valid
1837 * HELLO for another peer, offer it to the transport service.
1839 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1841 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1844 hello_msg = &msg[1];
1845 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1847 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1851 else /* We have a valid hello, and peer id stored in new_peer */
1853 find_peer_context.count++;
1854 increment_stats(STAT_FIND_PEER_REPLY);
1855 if (GNUNET_YES == consider_peer(&new_peer))
1857 increment_stats(STAT_HELLOS_PROVIDED);
1858 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1859 /* GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_UNIT_FOREVER_REL, &new_peer, NULL, NULL); */
1860 /* peer_request_connect call causes service to segfault */
1861 /* FIXME: Do we need this (peer_request_connect call)??? */
1866 if (malicious_dropper == GNUNET_YES)
1869 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1871 if (record == NULL) /* No record of this message! */
1874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1875 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1876 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1878 #if DEBUG_DHT_ROUTING
1880 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1882 dhtlog_handle->insert_route (NULL,
1883 message_context->unique_id,
1885 message_context->hop_count,
1888 &message_context->key,
1889 message_context->peer, NULL);
1892 if (message_context->bloom != NULL)
1894 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1895 message_context->bloom = NULL;
1903 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
1905 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
1907 increment_stats("# find peer responses NOT forwarded (bloom match)");
1912 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
1915 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1918 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1919 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
1920 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1922 #if DEBUG_DHT_ROUTING
1923 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1925 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
1926 message_context->hop_count,
1927 GNUNET_YES, &my_identity, &message_context->key,
1928 message_context->peer, NULL);
1931 increment_stats(STAT_RESULTS_TO_CLIENT);
1932 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
1933 increment_stats(STAT_GET_REPLY);
1935 send_reply_to_client(pos->client, msg, message_context->unique_id);
1937 else /* Send to peer */
1939 peer_info = find_peer_by_id(&pos->source);
1940 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
1946 if (message_context->bloom == NULL)
1947 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1948 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
1949 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
1952 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1953 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
1954 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1956 #if DEBUG_DHT_ROUTING
1957 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1959 dhtlog_handle->insert_route (NULL, message_context->unique_id,
1961 message_context->hop_count,
1962 GNUNET_NO, &my_identity, &message_context->key,
1963 message_context->peer, &pos->source);
1966 forward_result_message(cls, msg, peer_info, message_context);
1971 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1972 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
1973 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1979 if (message_context->bloom != NULL)
1980 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1985 * Iterator for local get request results,
1987 * @param cls closure for iterator, a DatacacheGetContext
1988 * @param exp when does this value expire?
1989 * @param key the key this data is stored under
1990 * @param size the size of the data identified by key
1991 * @param data the actual data
1992 * @param type the type of the data
1994 * @return GNUNET_OK to continue iteration, anything else
1995 * to stop iteration.
1998 datacache_get_iterator (void *cls,
1999 struct GNUNET_TIME_Absolute exp,
2000 const GNUNET_HashCode * key,
2001 uint32_t size, const char *data, uint32_t type)
2003 struct DHT_MessageContext *msg_ctx = cls;
2004 struct DHT_MessageContext *new_msg_ctx;
2005 struct GNUNET_DHT_GetResultMessage *get_result;
2007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2008 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2010 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2011 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2013 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2014 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2015 get_result->header.size =
2016 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2017 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2018 get_result->type = htons (type);
2019 memcpy (&get_result[1], data, size);
2020 new_msg_ctx->peer = &my_identity;
2021 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2022 new_msg_ctx->hop_count = 0;
2023 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2024 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2025 increment_stats(STAT_GET_RESPONSE_START);
2026 route_result_message(cls, &get_result->header, new_msg_ctx);
2027 GNUNET_free(new_msg_ctx);
2028 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2029 // datacache_get_ctx->unique_id);
2030 GNUNET_free (get_result);
2036 * Server handler for all dht get requests, look for data,
2037 * if found, send response either to clients or other peers.
2039 * @param cls closure for service
2040 * @param msg the actual get message
2041 * @param message_context struct containing pertinent information about the get request
2043 * @return number of items found for GET request
2046 handle_dht_get (void *cls,
2047 const struct GNUNET_MessageHeader *msg,
2048 struct DHT_MessageContext *message_context)
2050 const struct GNUNET_DHT_GetMessage *get_msg;
2052 unsigned int results;
2054 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2055 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2061 get_type = ntohs (get_msg->type);
2063 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2064 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2065 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2066 message_context->unique_id);
2068 increment_stats(STAT_GETS);
2070 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2073 if (datacache != NULL)
2075 GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2076 &datacache_get_iterator, message_context);
2081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2082 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2083 results, "GET", message_context->unique_id);
2085 #if DEBUG_DHT_ROUTING
2086 if ((debug_routes) && (dhtlog_handle != NULL))
2088 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2089 message_context->hop_count, GNUNET_YES, &my_identity,
2090 &message_context->key);
2093 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2095 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2096 message_context->hop_count, GNUNET_YES,
2097 &my_identity, &message_context->key, message_context->peer,
2103 if (message_context->hop_count == 0) /* Locally initiated request */
2105 #if DEBUG_DHT_ROUTING
2106 if ((debug_routes) && (dhtlog_handle != NULL))
2108 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2109 message_context->hop_count, GNUNET_NO, &my_identity,
2110 &message_context->key);
2119 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2121 GNUNET_HashCode *key = cls;
2122 GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key);
2126 * Server handler for initiating local dht find peer requests
2128 * @param cls closure for service
2129 * @param find_msg the actual find peer message
2130 * @param message_context struct containing pertinent information about the request
2134 handle_dht_find_peer (void *cls,
2135 const struct GNUNET_MessageHeader *find_msg,
2136 struct DHT_MessageContext *message_context)
2138 struct GNUNET_MessageHeader *find_peer_result;
2139 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2140 struct DHT_MessageContext *new_msg_ctx;
2141 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2144 GNUNET_HashCode *recent_hash;
2146 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2148 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2149 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2150 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2151 ntohs (find_msg->size),
2152 sizeof (struct GNUNET_MessageHeader));
2154 if (my_hello == NULL)
2157 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2158 "`%s': Our HELLO is null, can't return.\n",
2164 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2165 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2167 increment_stats(STAT_BLOOM_FIND_PEER);
2168 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2169 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2171 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2173 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent_find_peer_requests, &message_context->key)) /* We have recently responded to a find peer request for this peer! */
2175 increment_stats("# dht find peer requests ignored (recently seen!)");
2178 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2179 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2180 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2181 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &message_context->key);
2183 /* Simplistic find_peer functionality, always return our hello */
2184 hello_size = ntohs(my_hello->size);
2185 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2187 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2189 GNUNET_break_op (0);
2193 find_peer_result = GNUNET_malloc (tsize);
2194 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2195 find_peer_result->size = htons (tsize);
2196 memcpy (&find_peer_result[1], my_hello, hello_size);
2198 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2199 "`%s': Sending hello size %d to requesting peer.\n",
2202 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2203 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2204 new_msg_ctx->peer = &my_identity;
2205 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2206 new_msg_ctx->hop_count = 0;
2207 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2208 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2209 increment_stats(STAT_FIND_PEER_ANSWER);
2210 route_result_message(cls, find_peer_result, new_msg_ctx);
2211 GNUNET_free(new_msg_ctx);
2212 #if DEBUG_DHT_ROUTING
2213 if ((debug_routes) && (dhtlog_handle != NULL))
2215 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2216 message_context->hop_count, GNUNET_YES, &my_identity,
2217 &message_context->key);
2220 GNUNET_free(find_peer_result);
2225 * Server handler for initiating local dht put requests
2227 * @param cls closure for service
2228 * @param msg the actual put message
2229 * @param message_context struct containing pertinent information about the request
2232 handle_dht_put (void *cls,
2233 const struct GNUNET_MessageHeader *msg,
2234 struct DHT_MessageContext *message_context)
2236 struct GNUNET_DHT_PutMessage *put_msg;
2240 GNUNET_assert (ntohs (msg->size) >=
2241 sizeof (struct GNUNET_DHT_PutMessage));
2244 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2245 put_type = ntohs (put_msg->type);
2247 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2250 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2252 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2253 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2254 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2256 #if DEBUG_DHT_ROUTING
2257 if (message_context->hop_count == 0) /* Locally initiated request */
2259 if ((debug_routes) && (dhtlog_handle != NULL))
2261 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2262 message_context->hop_count, GNUNET_NO, &my_identity,
2263 &message_context->key);
2268 if (message_context->closest != GNUNET_YES)
2271 #if DEBUG_DHT_ROUTING
2272 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2274 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2275 message_context->hop_count, GNUNET_YES,
2276 &my_identity, &message_context->key, message_context->peer,
2280 if ((debug_routes) && (dhtlog_handle != NULL))
2282 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2283 message_context->hop_count, GNUNET_YES, &my_identity,
2284 &message_context->key);
2288 increment_stats(STAT_PUTS_INSERTED);
2289 if (datacache != NULL)
2290 GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2291 (char *) &put_msg[1], put_type,
2292 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2294 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2295 "`%s:%s': %s request received, but have no datacache!\n",
2296 my_short_id, "DHT", "PUT");
2300 * Estimate the diameter of the network based
2301 * on how many buckets are currently in use.
2302 * Concept here is that the diameter of the network
2303 * is roughly the distance a message must travel in
2304 * order to reach its intended destination. Since
2305 * at each hop we expect to get one bit closer, and
2306 * we have one bit per bucket, the number of buckets
2307 * in use should be the largest number of hops for
2308 * a sucessful message. (of course, this assumes we
2309 * know all peers in the network!)
2311 * @return ballpark diameter figure
2313 static unsigned int estimate_diameter()
2315 return MAX_BUCKETS - lowest_bucket;
2319 * To how many peers should we (on average)
2320 * forward the request to obtain the desired
2321 * target_replication count (on average).
2323 * Always 0, 1 or 2 (don't send, send once, split)
2326 get_forward_count (unsigned int hop_count, size_t target_replication)
2328 double target_count;
2329 unsigned int target_value;
2330 unsigned int diameter;
2333 * If we are behaving in strict kademlia mode, send multiple initial requests,
2334 * but then only send to 1 or 0 peers based strictly on the number of hops.
2336 if (strict_kademlia == GNUNET_YES)
2339 return DHT_KADEMLIA_REPLICATION;
2340 else if (hop_count < MAX_HOPS)
2346 /* FIXME: the smaller we think the network is the more lenient we should be for
2347 * routing right? The estimation below only works if we think we have reasonably
2348 * full routing tables, which for our RR topologies may not be the case!
2350 diameter = estimate_diameter ();
2351 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2354 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2355 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2356 "DHT", estimate_diameter(), lowest_bucket);
2360 else if (hop_count > MAX_HOPS)
2363 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2364 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2369 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2370 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2373 while (target_value < target_count)
2374 target_value++; /* target_value is ALWAYS 1 after this "loop", right? Because target_count is always > 0, right? Or does it become 0.00000... at some point because the hop count is so high? */
2376 if ((target_count + 1 - target_value) >
2377 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2378 RAND_MAX) / RAND_MAX)
2380 return target_value;
2384 * Check whether my identity is closer than any known peers.
2385 * If a non-null bloomfilter is given, check if this is the closest
2386 * peer that hasn't already been routed to.
2388 * @param target hash code to check closeness to
2389 * @param bloom bloomfilter, exclude these entries from the decision
2391 * Return GNUNET_YES if node location is closest, GNUNET_NO
2395 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2401 struct PeerInfo *pos;
2402 #if INTEGER_DISTANCE
2403 unsigned int my_distance;
2405 bucket_num = find_current_bucket(target);
2406 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2409 bits = matching_bits(&my_identity.hashPubKey, target);
2410 #if INTEGER_DISTANCE
2411 my_distance = distance(&my_identity.hashPubKey, target);
2413 pos = k_buckets[bucket_num].head;
2415 while ((pos != NULL) && (count < bucket_size))
2417 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2420 continue; /* Skip already checked entries */
2423 other_bits = matching_bits(&pos->id.hashPubKey, target);
2424 if (other_bits > bits)
2426 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2429 /* FIXME: why not just return GNUNET_YES here? We are certainly close. */
2430 /*if (distance(&pos->id.hashPubKey, target) < my_distance)
2437 GNUNET_GE_LOG (coreAPI->ectx,
2438 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2439 GNUNET_GE_BULK, "closest peer\n");
2440 printPeerBits (&closest);
2441 GNUNET_GE_LOG (coreAPI->ectx,
2442 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2443 GNUNET_GE_BULK, "me\n");
2444 printPeerBits (coreAPI->my_identity);
2445 GNUNET_GE_LOG (coreAPI->ectx,
2446 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2447 GNUNET_GE_BULK, "key\n");
2448 printKeyBits (target);
2449 GNUNET_GE_LOG (coreAPI->ectx,
2450 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2452 "closest peer inverse distance is %u, mine is %u\n",
2453 inverse_distance (target, &closest.hashPubKey),
2454 inverse_distance (target,
2455 &coreAPI->my_identity->hashPubKey));
2458 /* No peers closer, we are the closest! */
2464 * Select a peer from the routing table that would be a good routing
2465 * destination for sending a message for "target". The resulting peer
2466 * must not be in the set of blocked peers.<p>
2468 * Note that we should not ALWAYS select the closest peer to the
2469 * target, peers further away from the target should be chosen with
2470 * exponentially declining probability.
2472 * @param target the key we are selecting a peer to route to
2473 * @param bloom a bloomfilter containing entries this request has seen already
2475 * @return Peer to route to, or NULL on error
2477 static struct PeerInfo *
2478 select_peer (const GNUNET_HashCode * target,
2479 struct GNUNET_CONTAINER_BloomFilter *bloom)
2481 unsigned int distance;
2484 struct PeerInfo *pos;
2485 struct PeerInfo *chosen;
2486 unsigned long long largest_distance;
2487 unsigned long long total_distance;
2488 unsigned long long selected;
2490 if (strict_kademlia == GNUNET_YES)
2492 largest_distance = 0;
2494 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2496 pos = k_buckets[bc].head;
2498 while ((pos != NULL) && (count < bucket_size))
2500 /* If we are doing strict Kademlia like routing, then checking the bloomfilter is basically cheating! */
2501 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2503 distance = inverse_distance (target, &pos->id.hashPubKey);
2504 if (distance > largest_distance)
2507 largest_distance = distance;
2515 if ((largest_distance > 0) && (chosen != NULL))
2517 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2529 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2531 pos = k_buckets[bc].head;
2533 while ((pos != NULL) && (count < bucket_size))
2535 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2536 total_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2538 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2539 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2540 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2546 if (total_distance == 0)
2551 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2552 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2554 pos = k_buckets[bc].head;
2556 while ((pos != NULL) && (count < bucket_size))
2558 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2560 distance = inverse_distance (target, &pos->id.hashPubKey);
2561 if (distance > selected)
2563 selected -= distance;
2568 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2569 "`%s:%s': peer %s matches bloomfilter.\n",
2570 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2579 "`%s:%s': peer %s matches bloomfilter.\n",
2580 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2587 * Task used to remove recent entries, either
2588 * after timeout, when full, or on shutdown.
2590 * @param cls the entry to remove
2591 * @param tc context, reason, etc.
2594 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2596 struct RecentRequest *req = cls;
2597 static GNUNET_HashCode hash;
2599 GNUNET_assert(req != NULL);
2600 hash_from_uid(req->uid, &hash);
2601 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
2602 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
2603 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
2606 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
2608 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
2609 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
2615 * Task used to remove forwarding entries, either
2616 * after timeout, when full, or on shutdown.
2618 * @param cls the entry to remove
2619 * @param tc context, reason, etc.
2622 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2624 struct DHTRouteSource *source_info = cls;
2625 struct DHTQueryRecord *record;
2626 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2627 record = source_info->record;
2628 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2630 if (record->head == NULL) /* No more entries in DLL */
2632 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2633 GNUNET_free(record);
2635 if (source_info->find_peers_responded != NULL)
2636 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
2637 GNUNET_free(source_info);
2641 * Remember this routing request so that if a reply is
2642 * received we can either forward it to the correct peer
2643 * or return the result locally.
2645 * @param cls DHT service closure
2646 * @param msg_ctx Context of the route request
2648 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2650 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2652 struct DHTQueryRecord *record;
2653 struct DHTRouteSource *source_info;
2654 struct DHTRouteSource *pos;
2655 struct GNUNET_TIME_Absolute now;
2656 unsigned int current_size;
2658 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2659 while (current_size >= MAX_OUTSTANDING_FORWARDS)
2661 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2662 GNUNET_assert(source_info != NULL);
2663 record = source_info->record;
2664 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2665 if (record->head == NULL) /* No more entries in DLL */
2667 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2668 GNUNET_free(record);
2670 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2671 if (source_info->find_peers_responded != NULL)
2672 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
2673 GNUNET_free(source_info);
2674 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2676 now = GNUNET_TIME_absolute_get();
2677 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2678 if (record != NULL) /* Already know this request! */
2683 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
2684 break; /* Already have this peer in reply list! */
2687 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
2689 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
2695 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
2696 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2697 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
2700 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
2701 source_info->record = record;
2702 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
2703 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2704 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
2705 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
2706 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
2708 source_info->client = msg_ctx->client;
2709 now = GNUNET_TIME_absolute_get_forever();
2711 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
2713 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2714 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
2715 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
2722 * Main function that handles whether or not to route a message to other
2725 * @param cls closure for dht service (NULL)
2726 * @param msg the message to be routed
2727 * @param message_context the context containing all pertinent information about the message
2729 * @return the number of peers the message was routed to,
2730 * GNUNET_SYSERR on failure
2732 static int route_message(void *cls,
2733 const struct GNUNET_MessageHeader *msg,
2734 struct DHT_MessageContext *message_context)
2738 struct PeerInfo *selected;
2739 #if DEBUG_DHT_ROUTING > 1
2740 struct PeerInfo *nearest;
2742 unsigned int forward_count;
2743 struct RecentRequest *recent_req;
2744 GNUNET_HashCode unique_hash;
2745 char *stat_forward_count;
2746 #if DEBUG_DHT_ROUTING
2750 if (malicious_dropper == GNUNET_YES)
2752 #if DEBUG_DHT_ROUTING
2753 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2755 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2756 message_context->hop_count, GNUNET_SYSERR,
2757 &my_identity, &message_context->key, message_context->peer,
2761 if (message_context->bloom != NULL)
2762 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2766 increment_stats(STAT_ROUTES);
2767 /* Semantics of this call means we find whether we are the closest peer out of those already
2768 * routed to on this messages path.
2770 global_closest = am_closest_peer(&message_context->key, NULL);
2771 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
2772 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
2773 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
2774 increment_stats(stat_forward_count);
2775 GNUNET_free(stat_forward_count);
2776 if (message_context->bloom == NULL)
2777 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2779 if ((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
2783 #if DEBUG_DHT_ROUTING
2784 if (forward_count == 0)
2785 ret = GNUNET_SYSERR;
2789 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2791 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2792 message_context->hop_count, ret,
2793 &my_identity, &message_context->key, message_context->peer,
2798 switch (ntohs(msg->type))
2800 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
2801 cache_response (cls, message_context);
2802 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
2805 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
2806 increment_stats(STAT_PUTS);
2807 handle_dht_put (cls, msg, message_context);
2809 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
2810 increment_stats(STAT_FIND_PEER);
2811 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
2813 cache_response (cls, message_context);
2814 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
2815 handle_dht_find_peer (cls, msg, message_context);
2817 #if DEBUG_DHT_ROUTING
2818 if (message_context->hop_count == 0) /* Locally initiated request */
2820 if ((debug_routes) && (dhtlog_handle != NULL))
2822 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
2823 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2824 message_context->hop_count, GNUNET_NO, &my_identity,
2825 &message_context->key);
2831 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2832 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
2835 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2836 hash_from_uid(message_context->unique_id, &unique_hash);
2837 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent.hashmap, &unique_hash))
2839 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
2840 GNUNET_assert(recent_req != NULL);
2841 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
2842 increment_stats(STAT_DUPLICATE_UID);
2845 increment_stats(STAT_RECENT_SEEN);
2846 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
2851 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
2852 recent_req->uid = message_context->unique_id;
2853 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
2854 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
2855 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
2856 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2857 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2860 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
2862 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
2863 GNUNET_assert(recent_req != NULL);
2864 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
2865 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
2868 for (i = 0; i < forward_count; i++)
2870 selected = select_peer(&message_context->key, message_context->bloom);
2872 if (selected != NULL)
2874 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
2875 #if DEBUG_DHT_ROUTING > 1
2876 nearest = find_closest_peer(&message_context->key);
2877 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
2878 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2879 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
2880 "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));
2881 GNUNET_free(nearest_buf);
2883 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2885 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2886 message_context->hop_count, GNUNET_NO,
2887 &my_identity, &message_context->key, message_context->peer,
2890 forward_message(cls, msg, selected, message_context);
2895 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2896 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
2901 #if DEBUG_DHT_ROUTING > 1
2902 if (forward_count == 0)
2904 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2905 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
2906 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2910 if (message_context->bloom != NULL)
2912 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
2913 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2916 return forward_count;
2920 * Find a client if it exists, add it otherwise.
2922 * @param client the server handle to the client
2924 * @return the client if found, a new client otherwise
2926 static struct ClientList *
2927 find_active_client (struct GNUNET_SERVER_Client *client)
2929 struct ClientList *pos = client_list;
2930 struct ClientList *ret;
2934 if (pos->client_handle == client)
2939 ret = GNUNET_malloc (sizeof (struct ClientList));
2940 ret->client_handle = client;
2941 ret->next = client_list;
2947 * Task to send a malicious put message across the network.
2949 * @param cls closure for this task
2950 * @param tc the context under which the task is running
2953 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2955 static struct GNUNET_DHT_PutMessage put_message;
2956 static struct DHT_MessageContext message_context;
2957 static GNUNET_HashCode key;
2958 uint32_t random_key;
2960 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2963 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
2964 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
2965 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2966 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
2967 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2968 message_context.client = NULL;
2969 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2970 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2971 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
2972 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2973 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2974 message_context.msg_options = ntohl (0);
2975 message_context.network_size = estimate_diameter();
2976 message_context.peer = &my_identity;
2977 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
2978 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
2979 if (dhtlog_handle != NULL)
2980 dhtlog_handle->insert_dhtkey(NULL, &key);
2981 increment_stats(STAT_PUT_START);
2982 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2983 route_message(NULL, &put_message.header, &message_context);
2984 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
2989 * Task to send a malicious put message across the network.
2991 * @param cls closure for this task
2992 * @param tc the context under which the task is running
2995 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2997 static struct GNUNET_DHT_GetMessage get_message;
2998 struct DHT_MessageContext message_context;
2999 static GNUNET_HashCode key;
3000 uint32_t random_key;
3002 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3005 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3006 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3007 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3008 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3009 message_context.client = NULL;
3010 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3011 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3012 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3013 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3014 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3015 message_context.msg_options = ntohl (0);
3016 message_context.network_size = estimate_diameter();
3017 message_context.peer = &my_identity;
3018 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3019 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3020 if (dhtlog_handle != NULL)
3021 dhtlog_handle->insert_dhtkey(NULL, &key);
3022 increment_stats(STAT_GET_START);
3023 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3024 route_message (NULL, &get_message.header, &message_context);
3025 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3029 * Iterator over hash map entries.
3031 * @param cls closure
3032 * @param key current key code
3033 * @param value value in the hash map
3034 * @return GNUNET_YES if we should continue to
3039 add_known_to_bloom (void *cls,
3040 const GNUNET_HashCode * key,
3043 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3044 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3049 * Task to send a find peer message for our own peer identifier
3050 * so that we can find the closest peers in the network to ourselves
3051 * and attempt to connect to them.
3053 * @param cls closure for this task
3054 * @param tc the context under which the task is running
3057 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3059 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3060 struct DHT_MessageContext message_context;
3062 struct GNUNET_TIME_Relative next_send_time;
3063 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3065 struct GNUNET_TIME_Relative time_diff;
3066 struct GNUNET_TIME_Absolute end;
3068 double count_per_interval;
3070 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3073 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! */
3075 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3076 GNUNET_SCHEDULER_add_delayed (sched,
3077 GNUNET_TIME_UNIT_MINUTES,
3078 &send_find_peer_message, NULL);
3079 newly_found_peers = 0;
3083 increment_stats(STAT_FIND_PEER_START);
3085 end = GNUNET_TIME_absolute_get();
3086 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3088 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3090 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3091 count_per_interval = find_peer_context.count / multiplier;
3095 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3096 count_per_interval = find_peer_context.count * multiplier;
3100 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3101 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3102 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3103 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3104 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3105 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3106 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3107 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3108 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3109 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3110 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3111 message_context.network_size = estimate_diameter();
3112 message_context.peer = &my_identity;
3113 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3114 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3116 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3117 GNUNET_free(find_peer_msg);
3118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3119 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3121 if (newly_found_peers < bucket_size)
3123 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3124 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3125 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3129 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3130 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3131 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3134 GNUNET_assert (next_send_time.value != 0);
3135 find_peer_context.count = 0;
3136 newly_found_peers = 0;
3137 find_peer_context.start = GNUNET_TIME_absolute_get();
3138 if (GNUNET_YES == do_find_peer)
3140 GNUNET_SCHEDULER_add_delayed (sched,
3142 &send_find_peer_message, NULL);
3147 * Handler for any generic DHT messages, calls the appropriate handler
3148 * depending on message type, sends confirmation if responses aren't otherwise
3151 * @param cls closure for the service
3152 * @param client the client we received this message from
3153 * @param message the actual message received
3156 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3157 const struct GNUNET_MessageHeader *message)
3159 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3160 const struct GNUNET_MessageHeader *enc_msg;
3161 struct DHT_MessageContext message_context;
3162 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3165 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3166 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3167 GNUNET_ntohll (dht_msg->unique_id));
3169 #if DEBUG_DHT_ROUTING
3170 if (dhtlog_handle != NULL)
3171 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3173 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3174 message_context.client = find_active_client (client);
3175 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3176 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3177 message_context.replication = ntohl (dht_msg->desired_replication_level);
3178 message_context.msg_options = ntohl (dht_msg->options);
3179 message_context.network_size = estimate_diameter();
3180 message_context.peer = &my_identity;
3181 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3182 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3183 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3184 increment_stats(STAT_GET_START);
3185 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3186 increment_stats(STAT_PUT_START);
3187 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3188 increment_stats(STAT_FIND_PEER_START);
3190 route_message(cls, enc_msg, &message_context);
3192 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3197 * Handler for any locally received DHT control messages,
3198 * sets malicious flags mostly for now.
3200 * @param cls closure for the service
3201 * @param client the client we received this message from
3202 * @param message the actual message received
3206 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3207 const struct GNUNET_MessageHeader *message)
3209 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3210 (const struct GNUNET_DHT_ControlMessage *) message;
3212 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3213 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3214 "CONTROL", ntohs(dht_control_msg->command));
3217 switch (ntohs(dht_control_msg->command))
3219 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3220 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending self seeking find peer request!\n");
3221 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3223 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3224 if (ntohs(dht_control_msg->variable) > 0)
3225 malicious_get_frequency = ntohs(dht_control_msg->variable);
3226 if (malicious_get_frequency == 0)
3227 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3228 if (malicious_getter != GNUNET_YES)
3229 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3230 malicious_getter = GNUNET_YES;
3231 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3233 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3234 if (ntohs(dht_control_msg->variable) > 0)
3235 malicious_put_frequency = ntohs(dht_control_msg->variable);
3236 if (malicious_put_frequency == 0)
3237 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3238 if (malicious_putter != GNUNET_YES)
3239 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3240 malicious_putter = GNUNET_YES;
3241 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3243 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3244 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3245 dhtlog_handle->set_malicious(&my_identity);
3246 malicious_dropper = GNUNET_YES;
3247 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3250 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3253 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3257 * Handler for any generic DHT stop messages, calls the appropriate handler
3258 * depending on message type (if processed locally)
3260 * @param cls closure for the service
3261 * @param client the client we received this message from
3262 * @param message the actual message received
3266 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3267 const struct GNUNET_MessageHeader *message)
3270 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3271 (const struct GNUNET_DHT_StopMessage *) message;
3272 struct DHTQueryRecord *record;
3273 struct DHTRouteSource *pos;
3275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3276 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3277 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3279 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3286 if ((pos->client != NULL) && (pos->client->client_handle == client))
3288 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3289 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3295 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3300 * Core handler for p2p route requests.
3303 handle_dht_p2p_route_request (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 P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3312 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3313 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3314 struct DHT_MessageContext *message_context;
3316 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
3318 fprintf(stderr, "Sending of previous requests has taken far too long, backing off!\n");
3322 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3325 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3330 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3335 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3336 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3337 GNUNET_assert(message_context->bloom != NULL);
3338 message_context->hop_count = ntohl(incoming->hop_count);
3339 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
3340 message_context->replication = ntohl(incoming->desired_replication_level);
3341 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3342 message_context->msg_options = ntohl(incoming->options);
3343 message_context->network_size = ntohl(incoming->network_size);
3344 message_context->peer = peer;
3345 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3346 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3347 route_message(cls, enc_msg, message_context);
3348 GNUNET_free(message_context);
3354 * Core handler for p2p route results.
3357 handle_dht_p2p_route_result (void *cls,
3358 const struct GNUNET_PeerIdentity *peer,
3359 const struct GNUNET_MessageHeader *message,
3360 struct GNUNET_TIME_Relative latency, uint32_t distance)
3363 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3364 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3366 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3367 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3368 struct DHT_MessageContext message_context;
3370 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3376 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3377 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3378 GNUNET_assert(message_context.bloom != NULL);
3379 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
3380 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3381 message_context.msg_options = ntohl(incoming->options);
3382 message_context.hop_count = ntohl(incoming->hop_count);
3383 message_context.peer = peer;
3384 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3385 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3386 route_result_message(cls, enc_msg, &message_context);
3392 * Receive the HELLO from transport service,
3393 * free current and replace if necessary.
3396 * @param message HELLO message of peer
3399 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3402 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3403 "Received our `%s' from transport service\n",
3407 GNUNET_assert (message != NULL);
3408 GNUNET_free_non_null(my_hello);
3409 my_hello = GNUNET_malloc(ntohs(message->size));
3410 memcpy(my_hello, message, ntohs(message->size));
3415 * Task run during shutdown.
3421 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3424 struct PeerInfo *pos;
3425 if (transport_handle != NULL)
3427 GNUNET_free_non_null(my_hello);
3428 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3429 GNUNET_TRANSPORT_disconnect(transport_handle);
3432 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3434 while (k_buckets[bucket_count].head != NULL)
3436 pos = k_buckets[bucket_count].head;
3438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3439 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3441 delete_peer(pos, bucket_count);
3444 if (coreAPI != NULL)
3447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3448 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3450 GNUNET_CORE_disconnect (coreAPI);
3452 if (datacache != NULL)
3455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3456 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3458 GNUNET_DATACACHE_destroy (datacache);
3463 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3466 if (dhtlog_handle != NULL)
3467 GNUNET_DHTLOG_disconnect(dhtlog_handle);
3469 GNUNET_free_non_null(my_short_id);
3474 * To be called on core init/fail.
3476 * @param cls service closure
3477 * @param server handle to the server for this service
3478 * @param identity the public identity of this peer
3479 * @param publicKey the public key of this peer
3482 core_init (void *cls,
3483 struct GNUNET_CORE_Handle *server,
3484 const struct GNUNET_PeerIdentity *identity,
3485 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3492 "%s: Connection to core FAILED!\n", "dht",
3493 GNUNET_i2s (identity));
3495 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
3496 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3500 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3501 "%s: Core connection initialized, I am peer: %s\n", "dht",
3502 GNUNET_i2s (identity));
3505 /* Copy our identity so we can use it */
3506 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3507 if (my_short_id != NULL)
3508 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3509 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3510 /* Set the server to local variable */
3513 if (dhtlog_handle != NULL)
3514 dhtlog_handle->insert_node (NULL, &my_identity);
3518 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3519 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3520 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3521 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
3526 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3527 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
3528 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
3533 * Method called whenever a peer connects.
3535 * @param cls closure
3536 * @param peer peer identity this notification is about
3537 * @param latency reported latency of the connection with peer
3538 * @param distance reported distance (DV) to peer
3540 void handle_core_connect (void *cls,
3541 const struct GNUNET_PeerIdentity * peer,
3542 struct GNUNET_TIME_Relative latency,
3545 struct PeerInfo *ret;
3548 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3549 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
3552 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3554 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));
3558 if (datacache != NULL)
3559 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
3560 ret = try_add_peer(peer,
3561 find_current_bucket(&peer->hashPubKey),
3566 newly_found_peers++;
3567 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3570 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3571 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
3576 * Method called whenever a peer disconnects.
3578 * @param cls closure
3579 * @param peer peer identity this notification is about
3581 void handle_core_disconnect (void *cls,
3583 GNUNET_PeerIdentity * peer)
3585 struct PeerInfo *to_remove;
3588 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");
3590 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3592 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));
3595 increment_stats(STAT_DISCONNECTS);
3596 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
3597 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
3598 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
3599 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
3600 delete_peer(to_remove, current_bucket);
3604 * Process dht requests.
3606 * @param cls closure
3607 * @param scheduler scheduler to use
3608 * @param server the initialized server
3609 * @param c configuration to use
3613 struct GNUNET_SCHEDULER_Handle *scheduler,
3614 struct GNUNET_SERVER_Handle *server,
3615 const struct GNUNET_CONFIGURATION_Handle *c)
3618 struct GNUNET_TIME_Relative next_send_time;
3622 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
3623 GNUNET_SERVER_add_handlers (server, plugin_handlers);
3624 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
3625 cfg, /* Main configuration */
3626 GNUNET_TIME_UNIT_FOREVER_REL,
3627 NULL, /* Closure passed to DHT functions */
3628 &core_init, /* Call core_init once connected */
3629 &handle_core_connect, /* Handle connects */
3630 &handle_core_disconnect, /* remove peers on disconnects */
3631 NULL, /* Do we care about "status" updates? */
3632 NULL, /* Don't want notified about all incoming messages */
3633 GNUNET_NO, /* For header only inbound notification */
3634 NULL, /* Don't want notified about all outbound messages */
3635 GNUNET_NO, /* For header only outbound notification */
3636 core_handlers); /* Register these handlers */
3638 if (coreAPI == NULL)
3640 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
3641 NULL, NULL, NULL, NULL, NULL);
3642 if (transport_handle != NULL)
3643 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
3645 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
3647 lowest_bucket = MAX_BUCKETS - 1;
3648 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
3649 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3650 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
3651 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
3652 GNUNET_assert(all_known_peers != NULL);
3653 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
3655 debug_routes = GNUNET_YES;
3659 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3662 strict_kademlia = GNUNET_YES;
3666 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3669 stop_on_closest = GNUNET_YES;
3673 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3676 stop_on_found = GNUNET_YES;
3680 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3681 "malicious_getter"))
3683 malicious_getter = GNUNET_YES;
3684 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3685 "MALICIOUS_GET_FREQUENCY",
3686 &malicious_get_frequency))
3687 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3691 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3692 "malicious_putter"))
3694 malicious_putter = GNUNET_YES;
3695 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3696 "MALICIOUS_PUT_FREQUENCY",
3697 &malicious_put_frequency))
3698 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3702 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3703 "malicious_dropper"))
3705 malicious_dropper = GNUNET_YES;
3709 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3712 do_find_peer = GNUNET_NO;
3715 do_find_peer = GNUNET_YES;
3718 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
3719 "mysql_logging_extended"))
3721 debug_routes = GNUNET_YES;
3722 debug_routes_extended = GNUNET_YES;
3725 if (GNUNET_YES == debug_routes)
3727 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
3728 if (dhtlog_handle == NULL)
3730 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3731 "Could not connect to mysql logging server, logging will not happen!");
3735 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
3739 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
3740 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
3741 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
3742 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
3743 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
3744 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
3745 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
3746 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
3747 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
3748 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
3749 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
3750 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
3751 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
3752 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
3753 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
3754 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
3755 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
3756 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
3757 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
3758 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
3760 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
3761 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
3762 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3763 if (GNUNET_YES == do_find_peer)
3765 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3766 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3767 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3768 find_peer_context.start = GNUNET_TIME_absolute_get();
3769 GNUNET_SCHEDULER_add_delayed (sched,
3771 &send_find_peer_message, &find_peer_context);
3774 /* Scheduled the task to clean up when shutdown is called */
3775 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
3776 GNUNET_TIME_UNIT_FOREVER_REL,
3777 &shutdown_task, NULL);
3781 * The main function for the dht service.
3783 * @param argc number of arguments from the command line
3784 * @param argv command line arguments
3785 * @return 0 ok, 1 on error
3788 main (int argc, char *const *argv)
3790 return (GNUNET_OK ==
3791 GNUNET_SERVICE_run (argc,
3794 GNUNET_SERVICE_OPTION_NONE,
3795 &run, NULL)) ? 0 : 1;