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 REAL_DISTANCE GNUNET_NO
49 #define EXTRA_CHECKS GNUNET_NO
51 * How many buckets will we allow total.
53 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
56 * Should the DHT issue FIND_PEER requests to get better routing tables?
58 #define DO_FIND_PEER GNUNET_YES
61 * What is the maximum number of peers in a given bucket.
63 #define DEFAULT_BUCKET_SIZE 4
66 * Minimum number of peers we need for "good" routing,
67 * any less than this and we will allow messages to
68 * travel much further through the network!
70 #define MINIMUM_PEER_THRESHOLD 20
72 #define DHT_MAX_RECENT 1000
74 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
77 * Default time to wait to send messages on behalf of other peers.
79 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
82 * Default importance for handling messages on behalf of other peers.
84 #define DHT_DEFAULT_P2P_IMPORTANCE 0
87 * How long to keep recent requests around by default.
89 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
92 * Default time to wait to send find peer messages sent by the dht service.
94 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
97 * Default importance for find peer messages sent by the dht service.
99 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
102 * Default replication parameter for find peer messages sent by the dht service.
104 #define DHT_DEFAULT_PUT_REPLICATION 4
107 * Default replication parameter for find peer messages sent by the dht service.
109 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
112 * Default options for find peer requests sent by the dht service.
114 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
115 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
118 * How long at least to wait before sending another find peer request.
120 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
123 * How long at most to wait before sending another find peer request.
125 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
128 * How often to update our preference levels for peers in our routing tables.
130 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
133 * How long at most on average will we allow a reply forward to take
134 * (before we quit sending out new requests)
136 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
139 * How many initial requests to send out (in true Kademlia fashion)
141 #define DHT_KADEMLIA_REPLICATION 3
144 * Default frequency for sending malicious get messages
146 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
149 * Default frequency for sending malicious put messages
151 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
154 * Type for a malicious request, so we can ignore it during testing
156 #define DHT_MALICIOUS_MESSAGE_TYPE 42
158 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
161 * Real maximum number of hops, at which point we refuse
162 * to forward the message.
167 * How many time differences between requesting a core send and
168 * the actual callback to remember.
170 #define MAX_REPLY_TIMES 8
172 enum ConvergenceOptions
175 * Use the linear method for convergence.
180 * Converge using a fast converging square
186 * Converge using a slower exponential
189 DHT_CONVERGE_EXPONENTIAL,
192 * Don't do any special convergence, allow
193 * the algorithm to hopefully route to closer
200 * Linked list of messages to send to clients.
202 struct P2PPendingMessage
205 * Pointer to next item in the list
207 struct P2PPendingMessage *next;
210 * Pointer to previous item in the list
212 struct P2PPendingMessage *prev;
215 * Message importance level.
217 unsigned int importance;
220 * Time when this request was scheduled to be sent.
222 struct GNUNET_TIME_Absolute scheduled;
225 * How long to wait before sending message.
227 struct GNUNET_TIME_Relative timeout;
230 * Actual message to be sent; // avoid allocation
232 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
237 * Per-peer information.
242 * Next peer entry (DLL)
244 struct PeerInfo *next;
247 * Prev peer entry (DLL)
249 struct PeerInfo *prev;
252 * Head of pending messages to be sent to this peer.
254 struct P2PPendingMessage *head;
257 * Tail of pending messages to be sent to this peer.
259 struct P2PPendingMessage *tail;
262 * Core handle for sending messages to this peer.
264 struct GNUNET_CORE_TransmitHandle *th;
267 * Task for scheduling message sends.
269 GNUNET_SCHEDULER_TaskIdentifier send_task;
272 * Task for scheduling preference updates
274 GNUNET_SCHEDULER_TaskIdentifier preference_task;
277 * Preference update context
279 struct GNUNET_CORE_InformationRequestContext *info_ctx;
282 * What is the average latency for replies received?
284 struct GNUNET_TIME_Relative latency;
287 * What is the identity of the peer?
289 struct GNUNET_PeerIdentity id;
292 * Transport level distance to peer.
294 unsigned int distance;
297 * Task for scheduling periodic ping messages for this peer.
299 GNUNET_SCHEDULER_TaskIdentifier ping_task;
303 * Peers are grouped into buckets.
310 struct PeerInfo *head;
315 struct PeerInfo *tail;
318 * Number of peers in the bucket.
320 unsigned int peers_size;
324 * Linked list of messages to send to clients.
326 struct PendingMessage
329 * Pointer to next item in the list
331 struct PendingMessage *next;
334 * Pointer to previous item in the list
336 struct PendingMessage *prev;
339 * Actual message to be sent; // avoid allocation
341 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
346 * Struct containing information about a client,
347 * handle to connect to it, and any pending messages
348 * that need to be sent to it.
353 * Linked list of active clients
355 struct ClientList *next;
358 * The handle to this client
360 struct GNUNET_SERVER_Client *client_handle;
363 * Handle to the current transmission request, NULL
366 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
369 * Linked list of pending messages for this client
371 struct PendingMessage *pending_head;
374 * Tail of linked list of pending messages for this client
376 struct PendingMessage *pending_tail;
381 * Context containing information about a DHT message received.
383 struct DHT_MessageContext
386 * The client this request was received from.
387 * (NULL if received from another peer)
389 struct ClientList *client;
392 * The peer this request was received from.
393 * (NULL if received from local client)
395 const struct GNUNET_PeerIdentity *peer;
398 * The key this request was about
403 * The unique identifier of this request
408 * Desired replication level
410 uint32_t replication;
413 * Network size estimate, either ours or the sum of
414 * those routed to thus far. =~ Log of number of peers
415 * chosen from for this request.
417 uint32_t network_size;
420 * Any message options for this request
422 uint32_t msg_options;
425 * How many hops has the message already traversed?
430 * How important is this message?
432 unsigned int importance;
435 * How long should we wait to transmit this request?
437 struct GNUNET_TIME_Relative timeout;
440 * Bloomfilter for this routing request.
442 struct GNUNET_CONTAINER_BloomFilter *bloom;
445 * Did we forward this message? (may need to remember it!)
450 * Are we the closest known peer to this key (out of our neighbors?)
456 * Record used for remembering what peers are waiting for what
457 * responses (based on search key).
459 struct DHTRouteSource
464 struct DHTRouteSource *next;
469 struct DHTRouteSource *prev;
472 * Source of the request. Replies should be forwarded to
475 struct GNUNET_PeerIdentity source;
478 * If this was a local request, remember the client; otherwise NULL.
480 struct ClientList *client;
483 * Pointer to this nodes heap location (for removal)
485 struct GNUNET_CONTAINER_HeapNode *hnode;
488 * Back pointer to the record storing this information.
490 struct DHTQueryRecord *record;
493 * Task to remove this entry on timeout.
495 GNUNET_SCHEDULER_TaskIdentifier delete_task;
498 * Bloomfilter of peers we have already sent back as
499 * replies to the initial request. Allows us to not
500 * forward the same peer multiple times for a find peer
503 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
508 * Entry in the DHT routing table.
510 struct DHTQueryRecord
513 * Head of DLL for result forwarding.
515 struct DHTRouteSource *head;
518 * Tail of DLL for result forwarding.
520 struct DHTRouteSource *tail;
523 * Key that the record concerns.
528 * GET message of this record (what we already forwarded?).
530 //DV_DHT_MESSAGE get; Try to get away with not saving this.
533 * Bloomfilter of the peers we've replied to so far
535 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
540 * Context used to calculate the number of find peer messages
541 * per X time units since our last scheduled find peer message
542 * was sent. If we have seen too many messages, delay or don't
545 struct FindPeerMessageContext
549 struct GNUNET_TIME_Absolute start;
551 struct GNUNET_TIME_Absolute end;
555 * DHT Routing results structure
560 * Min heap for removal upon reaching limit
562 struct GNUNET_CONTAINER_Heap *minHeap;
565 * Hashmap for fast key based lookup
567 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
572 * DHT structure for recent requests.
574 struct RecentRequests
577 * Min heap for removal upon reaching limit
579 struct GNUNET_CONTAINER_Heap *minHeap;
582 * Hashmap for key based lookup
584 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
590 * Position of this node in the min heap.
592 struct GNUNET_CONTAINER_HeapNode *heap_node;
595 * Bloomfilter containing entries for peers
596 * we forwarded this request to.
598 struct GNUNET_CONTAINER_BloomFilter *bloom;
601 * Timestamp of this request, for ordering
604 struct GNUNET_TIME_Absolute timestamp;
607 * Key of this request.
612 * Unique identifier for this request.
617 * Task to remove this entry on timeout.
619 GNUNET_SCHEDULER_TaskIdentifier remove_task;
622 struct RepublishContext
637 * Which kind of convergence will we be using?
639 enum ConvergenceOptions converge_option;
642 * Recent requests by hash/uid and by time inserted.
644 static struct RecentRequests recent;
647 * Context to use to calculate find peer rates.
649 static struct FindPeerMessageContext find_peer_context;
652 * Don't use our routing algorithm, always route
653 * to closest peer; initially send requests to 3
656 static unsigned int strict_kademlia;
659 * Routing option to end routing when closest peer found.
661 static unsigned int stop_on_closest;
664 * Routing option to end routing when data is found.
666 static unsigned int stop_on_found;
669 * Whether DHT needs to manage find peer requests, or
670 * an external force will do it on behalf of the DHT.
672 static unsigned int do_find_peer;
675 * Once we have stored an item in the DHT, refresh it
676 * according to our republish interval.
678 static unsigned int do_republish;
681 * Use the "real" distance metric when selecting the
682 * next routing hop. Can be less accurate.
684 static unsigned int use_real_distance;
687 * How many peers have we added since we sent out our last
690 static unsigned int newly_found_peers;
693 * Container of active queries we should remember
695 static struct DHTResults forward_list;
698 * Handle to the datacache service (for inserting/retrieving data)
700 static struct GNUNET_DATACACHE_Handle *datacache;
703 * Handle for the statistics service.
705 struct GNUNET_STATISTICS_Handle *stats;
708 * The main scheduler to use for the DHT service
710 static struct GNUNET_SCHEDULER_Handle *sched;
713 * The configuration the DHT service is running with
715 static const struct GNUNET_CONFIGURATION_Handle *cfg;
718 * Handle to the core service
720 static struct GNUNET_CORE_Handle *coreAPI;
723 * Handle to the transport service, for getting our hello
725 static struct GNUNET_TRANSPORT_Handle *transport_handle;
728 * The identity of our peer.
730 static struct GNUNET_PeerIdentity my_identity;
733 * Short id of the peer, for printing
735 static char *my_short_id;
740 static struct GNUNET_MessageHeader *my_hello;
743 * Task to run when we shut down, cleaning up all our trash
745 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
748 * The lowest currently used bucket.
750 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
753 * The buckets (Kademlia routing table, complete with growth).
754 * Array of size MAX_BUCKET_SIZE.
756 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
759 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
761 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
764 * Recently seen find peer requests.
766 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
769 * Maximum size for each bucket.
771 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
774 * List of active clients.
776 static struct ClientList *client_list;
779 * Handle to the DHT logger.
781 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
784 * Whether or not to send routing debugging information
785 * to the dht logging server
787 static unsigned int debug_routes;
790 * Whether or not to send FULL route information to
793 static unsigned int debug_routes_extended;
796 * GNUNET_YES or GNUNET_NO, whether or not to act as
797 * a malicious node which drops all messages
799 static unsigned int malicious_dropper;
802 * GNUNET_YES or GNUNET_NO, whether or not to act as
803 * a malicious node which sends out lots of GETS
805 static unsigned int malicious_getter;
808 * GNUNET_YES or GNUNET_NO, whether or not to act as
809 * a malicious node which sends out lots of PUTS
811 static unsigned int malicious_putter;
814 * Frequency for malicious get requests.
816 static unsigned long long malicious_get_frequency;
819 * Frequency for malicious put requests.
821 static unsigned long long malicious_put_frequency;
824 * Reply times for requests, if we are busy, don't send any
827 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
830 * Current counter for replies.
832 static unsigned int reply_counter;
835 * Forward declaration.
837 static size_t send_generic_reply (void *cls, size_t size, void *buf);
839 /** Declare here so retry_core_send is aware of it */
840 size_t core_transmit_notify (void *cls,
841 size_t size, void *buf);
844 * Convert unique ID to hash code.
846 * @param uid unique ID to convert
847 * @param hash set to uid (extended with zeros)
850 hash_from_uid (uint64_t uid,
851 GNUNET_HashCode *hash)
853 memset (hash, 0, sizeof(GNUNET_HashCode));
854 *((uint64_t*)hash) = uid;
859 * Calculate the average send time between messages so that we can
860 * ignore certain requests if we get too busy.
862 * @return the average time between asking core to send a message
863 * and when the buffer for copying it is passed
865 static struct GNUNET_TIME_Relative get_average_send_delay()
868 unsigned int divisor;
869 struct GNUNET_TIME_Relative average_time;
870 average_time = GNUNET_TIME_relative_get_zero();
872 for (i = 0; i < MAX_REPLY_TIMES; i++)
874 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
875 if (reply_times[i].value == (uint64_t)0)
885 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
886 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
892 * Given the largest send delay, artificially decrease it
893 * so the next time around we may have a chance at sending
896 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
899 for (i = 0; i < MAX_REPLY_TIMES; i++)
901 if (reply_times[i].value == max_time.value)
903 reply_times[i].value = reply_times[i].value / 2;
910 * Find the maximum send time of the recently sent values.
912 * @return the average time between asking core to send a message
913 * and when the buffer for copying it is passed
915 static struct GNUNET_TIME_Relative get_max_send_delay()
918 struct GNUNET_TIME_Relative max_time;
919 max_time = GNUNET_TIME_relative_get_zero();
921 for (i = 0; i < MAX_REPLY_TIMES; i++)
923 if (reply_times[i].value > max_time.value)
924 max_time.value = reply_times[i].value;
927 if (max_time.value > MAX_REQUEST_TIME.value)
928 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
933 increment_stats(const char *value)
937 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
942 * Try to send another message from our core send list
945 try_core_send (void *cls,
946 const struct GNUNET_SCHEDULER_TaskContext *tc)
948 struct PeerInfo *peer = cls;
949 struct P2PPendingMessage *pending;
952 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
954 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
957 if (peer->th != NULL)
958 return; /* Message send already in progress */
960 pending = peer->head;
963 ssize = ntohs(pending->msg->size);
965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
966 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
967 "DHT", ssize, GNUNET_i2s(&peer->id));
969 pending->scheduled = GNUNET_TIME_absolute_get();
971 if (reply_counter >= MAX_REPLY_TIMES)
973 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
974 pending->timeout, &peer->id,
975 ssize, &core_transmit_notify, peer);
980 * Function called to send a request out to another peer.
981 * Called both for locally initiated requests and those
982 * received from other peers.
984 * @param cls DHT service closure argument
985 * @param msg the encapsulated message
986 * @param peer the peer to forward the message to
987 * @param msg_ctx the context of the message (hop count, bloom, etc.)
989 static void forward_result_message (void *cls,
990 const struct GNUNET_MessageHeader *msg,
991 struct PeerInfo *peer,
992 struct DHT_MessageContext *msg_ctx)
994 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
995 struct P2PPendingMessage *pending;
999 increment_stats(STAT_RESULT_FORWARDS);
1000 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1001 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1002 psize = sizeof(struct P2PPendingMessage) + msize;
1003 pending = GNUNET_malloc(psize);
1004 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1005 pending->importance = DHT_SEND_PRIORITY;
1006 pending->timeout = GNUNET_TIME_relative_get_forever();
1007 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1008 result_message->header.size = htons(msize);
1009 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1010 result_message->options = htonl(msg_ctx->msg_options);
1011 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1012 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1013 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1014 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1015 memcpy(&result_message[1], msg, ntohs(msg->size));
1017 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));
1019 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1020 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1021 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1024 * Called when core is ready to send a message we asked for
1025 * out to the destination.
1027 * @param cls closure (NULL)
1028 * @param size number of bytes available in buf
1029 * @param buf where the callee should write the message
1030 * @return number of bytes written to buf
1032 size_t core_transmit_notify (void *cls,
1033 size_t size, void *buf)
1035 struct PeerInfo *peer = cls;
1037 struct P2PPendingMessage *pending;
1044 /* client disconnected */
1046 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1051 if (peer->head == NULL)
1056 pending = peer->head;
1057 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1058 msize = ntohs(pending->msg->size);
1062 memcpy (cbuf, pending->msg, msize);
1063 GNUNET_CONTAINER_DLL_remove (peer->head,
1067 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));
1069 GNUNET_free (pending);
1072 while (NULL != pending &&
1073 (size - off >= (msize = ntohs (pending->msg->size))))
1075 #if DEBUG_DHT_ROUTING
1076 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);
1078 memcpy (&cbuf[off], pending->msg, msize);
1080 GNUNET_CONTAINER_DLL_remove (peer->head,
1083 GNUNET_free (pending);
1084 pending = peer->head;
1087 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1088 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1090 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);
1096 * Determine how many low order bits match in two
1097 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
1098 * the first two lowest order bits, and therefore the
1099 * return value is two (NOT XOR distance, nor how many
1100 * bits match absolutely!).
1102 * @param first the first hashcode
1103 * @param second the hashcode to compare first to
1105 * @return the number of bits that match
1107 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
1111 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
1112 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
1114 return sizeof (GNUNET_HashCode) * 8;
1118 * Compute the distance between have and target as a 32-bit value.
1119 * Differences in the lower bits must count stronger than differences
1120 * in the higher bits.
1122 * @return 0 if have==target, otherwise a number
1123 * that is larger as the distance between
1124 * the two hash codes increases
1127 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1129 unsigned int bucket;
1134 /* We have to represent the distance between two 2^9 (=512)-bit
1135 numbers as a 2^5 (=32)-bit number with "0" being used for the
1136 two numbers being identical; furthermore, we need to
1137 guarantee that a difference in the number of matching
1138 bits is always represented in the result.
1140 We use 2^32/2^9 numerical values to distinguish between
1141 hash codes that have the same LSB bit distance and
1142 use the highest 2^9 bits of the result to signify the
1143 number of (mis)matching LSB bits; if we have 0 matching
1144 and hence 512 mismatching LSB bits we return -1 (since
1145 512 itself cannot be represented with 9 bits) */
1147 /* first, calculate the most significant 9 bits of our
1148 result, aka the number of LSBs */
1149 bucket = matching_bits (target, have);
1150 /* bucket is now a value between 0 and 512 */
1152 return 0; /* perfect match */
1154 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1155 below, we'd end up with max+1 (overflow)) */
1157 /* calculate the most significant bits of the final result */
1158 msb = (512 - bucket) << (32 - 9);
1159 /* calculate the 32-9 least significant bits of the final result by
1160 looking at the differences in the 32-9 bits following the
1161 mismatching bit at 'bucket' */
1163 for (i = bucket + 1;
1164 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1166 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1167 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1168 last bit set will be 31 -- if
1169 i does not reach 512 first... */
1175 * Return a number that is larger the closer the
1176 * "have" GNUNET_hash code is to the "target".
1178 * @return inverse distance metric, non-zero.
1179 * Must fudge the value if NO bits match.
1182 inverse_distance (const GNUNET_HashCode * target,
1183 const GNUNET_HashCode * have)
1185 if (matching_bits(target, have) == 0)
1186 return 1; /* Never return 0! */
1187 return ((unsigned int) -1) - distance (target, have);
1191 * Find the optimal bucket for this key, regardless
1192 * of the current number of buckets in use.
1194 * @param hc the hashcode to compare our identity to
1196 * @return the proper bucket index, or GNUNET_SYSERR
1197 * on error (same hashcode)
1199 static int find_bucket(const GNUNET_HashCode *hc)
1203 bits = matching_bits(&my_identity.hashPubKey, hc);
1204 if (bits == MAX_BUCKETS)
1205 return GNUNET_SYSERR;
1206 return MAX_BUCKETS - bits - 1;
1210 * Find which k-bucket this peer should go into,
1211 * taking into account the size of the k-bucket
1212 * array. This means that if more bits match than
1213 * there are currently buckets, lowest_bucket will
1216 * @param hc GNUNET_HashCode we are finding the bucket for.
1218 * @return the proper bucket index for this key,
1219 * or GNUNET_SYSERR on error (same hashcode)
1221 static int find_current_bucket(const GNUNET_HashCode *hc)
1224 actual_bucket = find_bucket(hc);
1226 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1227 return GNUNET_SYSERR;
1228 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1229 return lowest_bucket;
1231 return actual_bucket;
1236 * Find a routing table entry from a peer identity
1238 * @param peer the peer to look up
1240 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1243 find_bucket_by_peer(const struct PeerInfo *peer)
1246 struct PeerInfo *pos;
1248 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1250 pos = k_buckets[bucket].head;
1259 return GNUNET_SYSERR; /* No such peer. */
1265 * Print the complete routing table for this peer.
1268 print_routing_table ()
1271 struct PeerInfo *pos;
1272 char char_buf[30000];
1274 memset(char_buf, 0, sizeof(char_buf));
1276 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1277 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1278 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1280 pos = k_buckets[bucket].head;
1281 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1282 //fprintf(stderr, "Bucket %d:\n", bucket);
1285 //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));
1286 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));
1290 fprintf(stderr, "%s", char_buf);
1296 * Find a routing table entry from a peer identity
1298 * @param peer the peer identity to look up
1300 * @return the routing table entry, or NULL if not found
1302 static struct PeerInfo *
1303 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1306 struct PeerInfo *pos;
1307 bucket = find_current_bucket(&peer->hashPubKey);
1309 if (bucket == GNUNET_SYSERR)
1312 pos = k_buckets[bucket].head;
1315 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1319 return NULL; /* No such peer. */
1322 /* Forward declaration */
1324 update_core_preference (void *cls,
1325 const struct GNUNET_SCHEDULER_TaskContext *tc);
1327 * Function called with statistics about the given peer.
1329 * @param cls closure
1330 * @param peer identifies the peer
1331 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1332 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1333 * @param amount set to the amount that was actually reserved or unreserved;
1334 * either the full requested amount or zero (no partial reservations)
1335 * @param preference current traffic preference for the given peer
1338 update_core_preference_finish (void *cls,
1339 const struct GNUNET_PeerIdentity * peer,
1340 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1341 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1342 int amount, uint64_t preference)
1344 struct PeerInfo *peer_info = cls;
1345 peer_info->info_ctx = NULL;
1346 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1350 update_core_preference (void *cls,
1351 const struct GNUNET_SCHEDULER_TaskContext *tc)
1353 struct PeerInfo *peer = cls;
1354 uint64_t preference;
1355 unsigned int matching;
1356 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1360 matching = matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1363 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching_bits);
1366 preference = 1LL << matching;
1367 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1369 GNUNET_TIME_relative_get_forever(),
1370 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1373 &update_core_preference_finish,
1378 * Really add a peer to a bucket (only do assertions
1381 * @param peer GNUNET_PeerIdentity of the peer to add
1382 * @param bucket the already figured out bucket to add
1384 * @param latency the core reported latency of this peer
1385 * @param distance the transport level distance to this peer
1387 * @return the newly added PeerInfo
1389 static struct PeerInfo *
1390 add_peer(const struct GNUNET_PeerIdentity *peer,
1391 unsigned int bucket,
1392 struct GNUNET_TIME_Relative latency,
1393 unsigned int distance)
1395 struct PeerInfo *new_peer;
1396 GNUNET_assert(bucket < MAX_BUCKETS);
1397 GNUNET_assert(peer != NULL);
1398 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1399 new_peer->latency = latency;
1400 new_peer->distance = distance;
1402 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1404 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1405 k_buckets[bucket].tail,
1406 k_buckets[bucket].tail,
1408 k_buckets[bucket].peers_size++;
1410 if ((matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1412 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1419 * Given a peer and its corresponding bucket,
1420 * remove it from that bucket. Does not free
1421 * the PeerInfo struct, nor cancel messages
1422 * or free messages waiting to be sent to this
1425 * @param peer the peer to remove
1426 * @param bucket the bucket the peer belongs to
1428 static void remove_peer (struct PeerInfo *peer,
1429 unsigned int bucket)
1431 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1432 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1433 k_buckets[bucket].tail,
1435 k_buckets[bucket].peers_size--;
1436 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1441 * Removes peer from a bucket, then frees associated
1442 * resources and frees peer.
1444 * @param peer peer to be removed and freed
1445 * @param bucket which bucket this peer belongs to
1447 static void delete_peer (struct PeerInfo *peer,
1448 unsigned int bucket)
1450 struct P2PPendingMessage *pos;
1451 struct P2PPendingMessage *next;
1453 struct PeerInfo *peer_pos;
1455 peer_pos = k_buckets[bucket].head;
1456 while ((peer_pos != NULL) && (peer_pos != peer))
1457 peer_pos = peer_pos->next;
1458 if (peer_pos == NULL)
1460 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1461 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));
1463 GNUNET_assert(peer_pos != NULL);
1465 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1467 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1468 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1469 if (peer->th != NULL)
1470 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1473 while (pos != NULL) /* Remove any pending messages for this peer */
1480 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1481 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1487 * Iterator over hash map entries.
1489 * @param cls closure
1490 * @param key current key code
1491 * @param value PeerInfo of the peer to move to new lowest bucket
1492 * @return GNUNET_YES if we should continue to
1496 static int move_lowest_bucket (void *cls,
1497 const GNUNET_HashCode * key,
1500 struct PeerInfo *peer = value;
1503 GNUNET_assert(lowest_bucket > 0);
1504 new_bucket = lowest_bucket - 1;
1505 remove_peer(peer, lowest_bucket);
1506 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1507 k_buckets[new_bucket].tail,
1508 k_buckets[new_bucket].tail,
1510 k_buckets[new_bucket].peers_size++;
1516 * The current lowest bucket is full, so change the lowest
1517 * bucket to the next lower down, and move any appropriate
1518 * entries in the current lowest bucket to the new bucket.
1520 static void enable_next_bucket()
1522 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1523 struct PeerInfo *pos;
1524 GNUNET_assert(lowest_bucket > 0);
1525 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1526 pos = k_buckets[lowest_bucket].head;
1529 fprintf(stderr, "Printing RT before new bucket\n");
1530 print_routing_table();
1532 /* Populate the array of peers which should be in the next lowest bucket */
1535 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1536 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1540 /* Remove peers from lowest bucket, insert into next lowest bucket */
1541 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1542 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1543 lowest_bucket = lowest_bucket - 1;
1545 fprintf(stderr, "Printing RT after new bucket\n");
1546 print_routing_table();
1551 * Find the closest peer in our routing table to the
1554 * @return The closest peer in our routing table to the
1555 * key, or NULL on error.
1557 static struct PeerInfo *
1558 find_closest_peer (const GNUNET_HashCode *hc)
1560 struct PeerInfo *pos;
1561 struct PeerInfo *current_closest;
1562 unsigned int lowest_distance;
1563 unsigned int temp_distance;
1567 lowest_distance = -1;
1569 if (k_buckets[lowest_bucket].peers_size == 0)
1572 current_closest = NULL;
1573 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1575 pos = k_buckets[bucket].head;
1577 while ((pos != NULL) && (count < bucket_size))
1579 temp_distance = distance(&pos->id.hashPubKey, hc);
1580 if (temp_distance <= lowest_distance)
1582 lowest_distance = temp_distance;
1583 current_closest = pos;
1589 GNUNET_assert(current_closest != NULL);
1590 return current_closest;
1595 * Function called to send a request out to another peer.
1596 * Called both for locally initiated requests and those
1597 * received from other peers.
1599 * @param cls DHT service closure argument (unused)
1600 * @param msg the encapsulated message
1601 * @param peer the peer to forward the message to
1602 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1604 static void forward_message (void *cls,
1605 const struct GNUNET_MessageHeader *msg,
1606 struct PeerInfo *peer,
1607 struct DHT_MessageContext *msg_ctx)
1609 struct GNUNET_DHT_P2PRouteMessage *route_message;
1610 struct P2PPendingMessage *pending;
1614 increment_stats(STAT_ROUTE_FORWARDS);
1616 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1617 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1619 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1620 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1621 psize = sizeof(struct P2PPendingMessage) + msize;
1622 pending = GNUNET_malloc(psize);
1623 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1624 pending->importance = msg_ctx->importance;
1625 pending->timeout = msg_ctx->timeout;
1626 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1627 route_message->header.size = htons(msize);
1628 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1629 route_message->options = htonl(msg_ctx->msg_options);
1630 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1631 route_message->network_size = htonl(msg_ctx->network_size);
1632 route_message->desired_replication_level = htonl(msg_ctx->replication);
1633 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1634 if (msg_ctx->bloom != NULL)
1635 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1636 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1637 memcpy(&route_message[1], msg, ntohs(msg->size));
1639 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));
1641 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1642 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1643 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1648 * Task used to send ping messages to peers so that
1649 * they don't get disconnected.
1651 * @param cls the peer to send a ping message to
1652 * @param tc context, reason, etc.
1655 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1657 struct PeerInfo *peer = cls;
1658 struct GNUNET_MessageHeader ping_message;
1659 struct DHT_MessageContext message_context;
1661 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1664 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1665 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1667 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1669 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1671 forward_message(NULL, &ping_message, peer, &message_context);
1672 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1676 * Schedule PING messages for the top X peers in each
1677 * bucket of the routing table (so core won't disconnect them!)
1679 void schedule_ping_messages()
1681 unsigned int bucket;
1683 struct PeerInfo *pos;
1684 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1686 pos = k_buckets[bucket].head;
1690 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1691 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1692 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1694 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1695 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1705 * Attempt to add a peer to our k-buckets.
1707 * @param peer the peer identity of the peer being added
1708 * @param bucket the bucket that we want this peer to go in
1709 * @param latency transport latency of this peer
1710 * @param distance transport distance to this peer
1712 * @return NULL if the peer was not added,
1713 * pointer to PeerInfo for new peer otherwise
1715 static struct PeerInfo *
1716 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1717 unsigned int bucket,
1718 struct GNUNET_TIME_Relative latency,
1719 unsigned int distance)
1722 struct PeerInfo *new_peer;
1723 peer_bucket = find_current_bucket(&peer->hashPubKey);
1724 if (peer_bucket == GNUNET_SYSERR)
1727 GNUNET_assert(peer_bucket >= lowest_bucket);
1728 new_peer = add_peer(peer, peer_bucket, latency, distance);
1730 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1731 enable_next_bucket();
1733 schedule_ping_messages();
1740 * Task run to check for messages that need to be sent to a client.
1742 * @param client a ClientList, containing the client and any messages to be sent to it
1745 process_pending_messages (struct ClientList *client)
1747 if (client->pending_head == NULL)
1749 if (client->transmit_handle != NULL)
1751 client->transmit_handle =
1752 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1753 ntohs (client->pending_head->msg->
1755 GNUNET_TIME_UNIT_FOREVER_REL,
1756 &send_generic_reply, client);
1760 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1761 * request. A ClientList is passed as closure, take the head of the list
1762 * and copy it into buf, which has the result of sending the message to the
1765 * @param cls closure to this call
1766 * @param size maximum number of bytes available to send
1767 * @param buf where to copy the actual message to
1769 * @return the number of bytes actually copied, 0 indicates failure
1772 send_generic_reply (void *cls, size_t size, void *buf)
1774 struct ClientList *client = cls;
1776 struct PendingMessage *reply;
1780 client->transmit_handle = NULL;
1783 /* client disconnected */
1787 while ( (NULL != (reply = client->pending_head)) &&
1788 (size >= off + (msize = ntohs (reply->msg->size))))
1790 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1791 client->pending_tail,
1793 memcpy (&cbuf[off], reply->msg, msize);
1794 GNUNET_free (reply);
1797 process_pending_messages (client);
1803 * Add a PendingMessage to the clients list of messages to be sent
1805 * @param client the active client to send the message to
1806 * @param pending_message the actual message to send
1809 add_pending_message (struct ClientList *client,
1810 struct PendingMessage *pending_message)
1812 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1813 client->pending_tail,
1814 client->pending_tail,
1816 process_pending_messages (client);
1823 * Called when a reply needs to be sent to a client, as
1824 * a result it found to a GET or FIND PEER request.
1826 * @param client the client to send the reply to
1827 * @param message the encapsulated message to send
1828 * @param uid the unique identifier of this request
1831 send_reply_to_client (struct ClientList *client,
1832 const struct GNUNET_MessageHeader *message,
1833 unsigned long long uid)
1835 struct GNUNET_DHT_RouteResultMessage *reply;
1836 struct PendingMessage *pending_message;
1840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1841 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1843 msize = ntohs (message->size);
1844 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1845 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1847 GNUNET_break_op (0);
1851 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1852 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1853 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1854 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1855 reply->header.size = htons (tsize);
1856 reply->unique_id = GNUNET_htonll (uid);
1857 memcpy (&reply[1], message, msize);
1859 add_pending_message (client, pending_message);
1863 * Consider whether or not we would like to have this peer added to
1864 * our routing table. Check whether bucket for this peer is full,
1865 * if so return negative; if not return positive. Since peers are
1866 * only added on CORE level connect, this doesn't actually add the
1867 * peer to the routing table.
1869 * @param peer the peer we are considering adding
1871 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1874 * FIXME: Think about making a context for this call so that we can
1875 * ping the oldest peer in the current bucket and consider
1876 * removing it in lieu of the new peer.
1878 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1882 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1883 return GNUNET_NO; /* We already know this peer (are connected even!) */
1884 bucket = find_current_bucket(&peer->hashPubKey);
1885 if (bucket == GNUNET_SYSERR)
1887 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1894 * Main function that handles whether or not to route a result
1895 * message to other peers, or to send to our local client.
1897 * @param cls closure (unused, always should be NULL)
1898 * @param msg the result message to be routed
1899 * @param message_context context of the message we are routing
1901 * @return the number of peers the message was routed to,
1902 * GNUNET_SYSERR on failure
1904 static int route_result_message(void *cls,
1905 struct GNUNET_MessageHeader *msg,
1906 struct DHT_MessageContext *message_context)
1908 struct GNUNET_PeerIdentity new_peer;
1909 struct DHTQueryRecord *record;
1910 struct DHTRouteSource *pos;
1911 struct PeerInfo *peer_info;
1912 const struct GNUNET_MessageHeader *hello_msg;
1914 increment_stats(STAT_RESULTS);
1916 * If a find peer result message is received and contains a valid
1917 * HELLO for another peer, offer it to the transport service.
1919 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1921 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1924 hello_msg = &msg[1];
1925 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1927 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1931 else /* We have a valid hello, and peer id stored in new_peer */
1933 find_peer_context.count++;
1934 increment_stats(STAT_FIND_PEER_REPLY);
1935 if (GNUNET_YES == consider_peer(&new_peer))
1937 increment_stats(STAT_HELLOS_PROVIDED);
1938 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1939 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_UNIT_FOREVER_REL, &new_peer, NULL, NULL);
1944 if (malicious_dropper == GNUNET_YES)
1947 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1949 if (record == NULL) /* No record of this message! */
1952 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1953 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1954 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1956 #if DEBUG_DHT_ROUTING
1957 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1959 dhtlog_handle->insert_route (NULL,
1960 message_context->unique_id,
1962 message_context->hop_count,
1965 &message_context->key,
1966 message_context->peer, NULL);
1969 if (message_context->bloom != NULL)
1971 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1972 message_context->bloom = NULL;
1980 #if STRICT_FORWARDING
1981 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
1983 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
1985 increment_stats("# find peer responses NOT forwarded (bloom match)");
1990 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
1994 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1997 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1998 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
1999 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2001 #if DEBUG_DHT_ROUTING
2002 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2004 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2005 message_context->hop_count,
2006 GNUNET_YES, &my_identity, &message_context->key,
2007 message_context->peer, NULL);
2010 increment_stats(STAT_RESULTS_TO_CLIENT);
2011 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2012 increment_stats(STAT_GET_REPLY);
2014 send_reply_to_client(pos->client, msg, message_context->unique_id);
2016 else /* Send to peer */
2018 peer_info = find_peer_by_id(&pos->source);
2019 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2025 if (message_context->bloom == NULL)
2026 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2027 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2028 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2032 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2033 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2035 #if DEBUG_DHT_ROUTING
2036 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2038 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2040 message_context->hop_count,
2041 GNUNET_NO, &my_identity, &message_context->key,
2042 message_context->peer, &pos->source);
2045 forward_result_message(cls, msg, peer_info, message_context);
2050 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2051 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2052 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2058 if (message_context->bloom != NULL)
2059 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2064 * Iterator for local get request results,
2066 * @param cls closure for iterator, a DatacacheGetContext
2067 * @param exp when does this value expire?
2068 * @param key the key this data is stored under
2069 * @param size the size of the data identified by key
2070 * @param data the actual data
2071 * @param type the type of the data
2073 * @return GNUNET_OK to continue iteration, anything else
2074 * to stop iteration.
2077 datacache_get_iterator (void *cls,
2078 struct GNUNET_TIME_Absolute exp,
2079 const GNUNET_HashCode * key,
2080 uint32_t size, const char *data, uint32_t type)
2082 struct DHT_MessageContext *msg_ctx = cls;
2083 struct DHT_MessageContext *new_msg_ctx;
2084 struct GNUNET_DHT_GetResultMessage *get_result;
2086 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2087 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2089 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2090 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2092 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2093 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2094 get_result->header.size =
2095 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2096 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2097 get_result->type = htons (type);
2098 memcpy (&get_result[1], data, size);
2099 new_msg_ctx->peer = &my_identity;
2100 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2101 new_msg_ctx->hop_count = 0;
2102 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2103 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2104 increment_stats(STAT_GET_RESPONSE_START);
2105 route_result_message(cls, &get_result->header, new_msg_ctx);
2106 GNUNET_free(new_msg_ctx);
2107 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2108 // datacache_get_ctx->unique_id);
2109 GNUNET_free (get_result);
2115 * Server handler for all dht get requests, look for data,
2116 * if found, send response either to clients or other peers.
2118 * @param cls closure for service
2119 * @param msg the actual get message
2120 * @param message_context struct containing pertinent information about the get request
2122 * @return number of items found for GET request
2125 handle_dht_get (void *cls,
2126 const struct GNUNET_MessageHeader *msg,
2127 struct DHT_MessageContext *message_context)
2129 const struct GNUNET_DHT_GetMessage *get_msg;
2131 unsigned int results;
2133 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2134 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2140 get_type = ntohs (get_msg->type);
2142 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2143 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2144 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2145 message_context->unique_id);
2147 increment_stats(STAT_GETS);
2149 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2152 if (datacache != NULL)
2154 GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2155 &datacache_get_iterator, message_context);
2160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2161 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2162 results, "GET", message_context->unique_id);
2164 #if DEBUG_DHT_ROUTING
2165 if ((debug_routes) && (dhtlog_handle != NULL))
2167 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2168 message_context->hop_count, GNUNET_YES, &my_identity,
2169 &message_context->key);
2172 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2174 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2175 message_context->hop_count, GNUNET_YES,
2176 &my_identity, &message_context->key, message_context->peer,
2182 if (message_context->hop_count == 0) /* Locally initiated request */
2184 #if DEBUG_DHT_ROUTING
2185 if ((debug_routes) && (dhtlog_handle != NULL))
2187 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2188 message_context->hop_count, GNUNET_NO, &my_identity,
2189 &message_context->key);
2198 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2200 GNUNET_HashCode *key = cls;
2201 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2208 * Server handler for initiating local dht find peer requests
2210 * @param cls closure for service
2211 * @param find_msg the actual find peer message
2212 * @param message_context struct containing pertinent information about the request
2216 handle_dht_find_peer (void *cls,
2217 const struct GNUNET_MessageHeader *find_msg,
2218 struct DHT_MessageContext *message_context)
2220 struct GNUNET_MessageHeader *find_peer_result;
2221 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2222 struct DHT_MessageContext *new_msg_ctx;
2223 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2226 GNUNET_HashCode *recent_hash;
2227 #if RESTRICT_FIND_PEER
2228 struct GNUNET_PeerIdentity peer_id;
2231 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2233 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2234 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2235 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2236 ntohs (find_msg->size),
2237 sizeof (struct GNUNET_MessageHeader));
2239 if (my_hello == NULL)
2242 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2243 "`%s': Our HELLO is null, can't return.\n",
2249 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2250 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2252 increment_stats(STAT_BLOOM_FIND_PEER);
2253 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2254 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2256 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2258 #if RESTRICT_FIND_PEER
2261 * Ignore any find peer requests from a peer we have seen very recently.
2263 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! */
2265 increment_stats("# dht find peer requests ignored (recently seen!)");
2270 * Use this check to only allow the peer to respond to find peer requests if
2271 * it would be beneficial to have the requesting peer in this peers routing
2272 * table. Can be used to thwart peers flooding the network with find peer
2273 * requests that we don't care about. However, if a new peer is joining
2274 * the network and has no other peers this is a problem (assume all buckets
2275 * full, no one will respond!).
2277 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2278 if (GNUNET_NO == consider_peer(&peer_id))
2280 increment_stats("# dht find peer requests ignored (do not need!)");
2285 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2286 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2287 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2288 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2290 /* Simplistic find_peer functionality, always return our hello */
2291 hello_size = ntohs(my_hello->size);
2292 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2294 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2296 GNUNET_break_op (0);
2300 find_peer_result = GNUNET_malloc (tsize);
2301 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2302 find_peer_result->size = htons (tsize);
2303 memcpy (&find_peer_result[1], my_hello, hello_size);
2305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2306 "`%s': Sending hello size %d to requesting peer.\n",
2309 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2310 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2311 new_msg_ctx->peer = &my_identity;
2312 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2313 new_msg_ctx->hop_count = 0;
2314 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2315 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2316 increment_stats(STAT_FIND_PEER_ANSWER);
2317 route_result_message(cls, find_peer_result, new_msg_ctx);
2318 GNUNET_free(new_msg_ctx);
2319 #if DEBUG_DHT_ROUTING
2320 if ((debug_routes) && (dhtlog_handle != NULL))
2322 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2323 message_context->hop_count, GNUNET_YES, &my_identity,
2324 &message_context->key);
2327 GNUNET_free(find_peer_result);
2331 * Task used to republish data.
2332 * Forward declaration; function call loop.
2334 * @param cls closure (a struct RepublishContext)
2335 * @param tc runtime context for this task
2338 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2341 * Server handler for initiating local dht put requests
2343 * @param cls closure for service
2344 * @param msg the actual put message
2345 * @param message_context struct containing pertinent information about the request
2348 handle_dht_put (void *cls,
2349 const struct GNUNET_MessageHeader *msg,
2350 struct DHT_MessageContext *message_context)
2352 struct GNUNET_DHT_PutMessage *put_msg;
2356 struct RepublishContext *put_context;
2358 GNUNET_assert (ntohs (msg->size) >=
2359 sizeof (struct GNUNET_DHT_PutMessage));
2362 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2363 put_type = ntohs (put_msg->type);
2365 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2368 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2371 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2372 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2374 #if DEBUG_DHT_ROUTING
2375 if (message_context->hop_count == 0) /* Locally initiated request */
2377 if ((debug_routes) && (dhtlog_handle != NULL))
2379 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2380 message_context->hop_count, GNUNET_NO, &my_identity,
2381 &message_context->key);
2386 if (message_context->closest != GNUNET_YES)
2389 #if DEBUG_DHT_ROUTING
2390 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2392 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2393 message_context->hop_count, GNUNET_YES,
2394 &my_identity, &message_context->key, message_context->peer,
2398 if ((debug_routes) && (dhtlog_handle != NULL))
2400 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2401 message_context->hop_count, GNUNET_YES, &my_identity,
2402 &message_context->key);
2406 increment_stats(STAT_PUTS_INSERTED);
2407 if (datacache != NULL)
2409 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2410 (char *) &put_msg[1], put_type,
2411 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2413 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2415 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2416 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2417 put_context->type = put_type;
2418 GNUNET_SCHEDULER_add_delayed (sched, DHT_REPUBLISH_FREQUENCY, &republish_content, put_context);
2422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2423 "`%s:%s': %s request received, but have no datacache!\n",
2424 my_short_id, "DHT", "PUT");
2428 * Estimate the diameter of the network based
2429 * on how many buckets are currently in use.
2430 * Concept here is that the diameter of the network
2431 * is roughly the distance a message must travel in
2432 * order to reach its intended destination. Since
2433 * at each hop we expect to get one bit closer, and
2434 * we have one bit per bucket, the number of buckets
2435 * in use should be the largest number of hops for
2436 * a sucessful message. (of course, this assumes we
2437 * know all peers in the network!)
2439 * @return ballpark diameter figure
2441 static unsigned int estimate_diameter()
2443 return MAX_BUCKETS - lowest_bucket;
2447 * To how many peers should we (on average)
2448 * forward the request to obtain the desired
2449 * target_replication count (on average).
2451 * Always 0, 1 or 2 (don't send, send once, split)
2454 get_forward_count (unsigned int hop_count, size_t target_replication)
2457 double target_count;
2458 double random_probability;
2460 uint32_t random_value;
2462 unsigned int target_value;
2463 unsigned int diameter;
2466 * If we are behaving in strict kademlia mode, send multiple initial requests,
2467 * but then only send to 1 or 0 peers based strictly on the number of hops.
2469 if (strict_kademlia == GNUNET_YES)
2472 return DHT_KADEMLIA_REPLICATION;
2473 else if (hop_count < MAX_HOPS)
2479 /* FIXME: the smaller we think the network is the more lenient we should be for
2480 * routing right? The estimation below only works if we think we have reasonably
2481 * full routing tables, which for our RR topologies may not be the case!
2483 diameter = estimate_diameter ();
2484 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2487 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2488 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2489 "DHT", estimate_diameter(), lowest_bucket);
2493 else if (hop_count > MAX_HOPS)
2496 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2497 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2504 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2505 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2506 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2507 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2508 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2509 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2510 RAND_MAX)) / RAND_MAX;
2511 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2514 //while (target_value < target_count)
2515 if (target_value < target_count)
2516 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? */
2519 //if ((target_count + 1 - (double)target_value) > random_probability)
2520 if ((target_count) > random_probability)
2524 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2525 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "replication %u, at hop %d, will split with probability %f\n", target_replication, hop_count, target_replication / (double)((target_replication * (hop_count + 1) + diameter) + 1));
2527 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2528 if (random_value < target_replication)
2531 return target_value;
2535 * Check whether my identity is closer than any known peers.
2536 * If a non-null bloomfilter is given, check if this is the closest
2537 * peer that hasn't already been routed to.
2539 * @param target hash code to check closeness to
2540 * @param bloom bloomfilter, exclude these entries from the decision
2542 * Return GNUNET_YES if node location is closest, GNUNET_NO
2546 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2552 struct PeerInfo *pos;
2553 unsigned int my_distance;
2555 bucket_num = find_current_bucket(target);
2556 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2559 bits = matching_bits(&my_identity.hashPubKey, target);
2560 my_distance = distance(&my_identity.hashPubKey, target);
2561 pos = k_buckets[bucket_num].head;
2563 while ((pos != NULL) && (count < bucket_size))
2565 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2568 continue; /* Skip already checked entries */
2571 other_bits = matching_bits(&pos->id.hashPubKey, target);
2572 if (other_bits > bits)
2574 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2576 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2578 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2585 GNUNET_GE_LOG (coreAPI->ectx,
2586 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2587 GNUNET_GE_BULK, "closest peer\n");
2588 printPeerBits (&closest);
2589 GNUNET_GE_LOG (coreAPI->ectx,
2590 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2591 GNUNET_GE_BULK, "me\n");
2592 printPeerBits (coreAPI->my_identity);
2593 GNUNET_GE_LOG (coreAPI->ectx,
2594 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2595 GNUNET_GE_BULK, "key\n");
2596 printKeyBits (target);
2597 GNUNET_GE_LOG (coreAPI->ectx,
2598 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2600 "closest peer inverse distance is %u, mine is %u\n",
2601 inverse_distance (target, &closest.hashPubKey),
2602 inverse_distance (target,
2603 &coreAPI->my_identity->hashPubKey));
2606 /* No peers closer, we are the closest! */
2612 * Decide whether to route this request exclusively
2613 * to a closer peer (if closer peers exist) or to choose
2614 * from the whole set of peers.
2616 * @param target the key of the request
2617 * @param bloom bloomfilter of peers this request has already traversed
2618 * @param hops number of hops this message has already traveled
2620 * @return GNUNET_YES if we should try to route to a closer peer
2621 * than ourselves (and one exists), GNUNET_NO if we should
2622 * choose from the set of all known peers
2626 route_closer (const GNUNET_HashCode *target,
2627 struct GNUNET_CONTAINER_BloomFilter *bloom,
2630 unsigned int my_matching_bits;
2632 uint32_t random_value;
2633 struct PeerInfo *pos;
2636 my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2639 * First check if we know any close (as close as us or closer) peers.
2641 have_closer = GNUNET_NO;
2643 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2645 pos = k_buckets[bc].head;
2647 while ((pos != NULL) && (count < bucket_size))
2649 if ((matching_bits(target, &pos->id.hashPubKey) > my_matching_bits) &&
2650 (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
2652 have_closer = GNUNET_YES;
2658 if (have_closer == GNUNET_YES)
2662 if (have_closer == GNUNET_NO) /* We don't have a same distance or closer node, can't enforce closer only! */
2665 switch (converge_option)
2667 case DHT_CONVERGE_LINEAR:
2669 * Simple linear curve for choosing whether or not to converge.
2670 * Choose to route only closer with probability hops/MAX_HOPS.
2672 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, MAX_HOPS);
2673 if (random_value < hops)
2677 case DHT_CONVERGE_SQUARE:
2679 * Simple square based curve.
2681 if ((GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1) / (double)(uint32_t)-1) < (sqrt(hops) / sqrt(MAX_HOPS)))
2691 * Select a peer from the routing table that would be a good routing
2692 * destination for sending a message for "target". The resulting peer
2693 * must not be in the set of blocked peers.<p>
2695 * Note that we should not ALWAYS select the closest peer to the
2696 * target, peers further away from the target should be chosen with
2697 * exponentially declining probability.
2699 * @param target the key we are selecting a peer to route to
2700 * @param bloom a bloomfilter containing entries this request has seen already
2701 * @param hops the number of hops this message has already traversed
2703 * @return Peer to route to, or NULL on error
2705 static struct PeerInfo *
2706 select_peer (const GNUNET_HashCode * target,
2707 struct GNUNET_CONTAINER_BloomFilter *bloom,
2710 unsigned int distance;
2713 unsigned int my_matching_bits;
2714 unsigned long long largest_distance;
2715 unsigned long long total_real_distance;
2716 unsigned long long real_selected;
2717 unsigned int total_distance;
2718 unsigned int selected;
2719 unsigned int match_num;
2721 struct PeerInfo *pos;
2722 struct PeerInfo *chosen;
2724 #if DEBUG_DHT_ROUTING > 1
2728 my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2729 only_closer = route_closer(target, bloom, hops);
2731 if (GNUNET_YES == only_closer)
2733 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "only routing to closer peers!\n");
2734 GNUNET_asprintf(&temp_stat, "# closer only routes at hop %u", hops);
2735 increment_stats(temp_stat);
2739 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "routing to all possible peers!\n");
2740 GNUNET_asprintf(&temp_stat, "# NOT closer only routes at hop %u", hops);
2741 increment_stats(temp_stat);
2744 GNUNET_free(temp_stat);
2745 total_real_distance = 0;
2746 if (strict_kademlia == GNUNET_YES)
2748 largest_distance = 0;
2750 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2752 pos = k_buckets[bc].head;
2754 while ((pos != NULL) && (count < bucket_size))
2756 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2757 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2759 distance = inverse_distance (target, &pos->id.hashPubKey);
2760 if (distance > largest_distance)
2763 largest_distance = distance;
2771 if ((largest_distance > 0) && (chosen != NULL))
2773 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2785 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2787 pos = k_buckets[bc].head;
2789 while ((pos != NULL) && (count < bucket_size))
2791 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2792 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2794 if (GNUNET_YES == use_real_distance)
2795 total_real_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2798 /* Always add 1, in case 0 bits match! */
2799 match_num = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target ,&pos->id.hashPubKey));
2800 total_distance += match_num;
2804 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2805 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2806 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2813 if (((GNUNET_YES == use_real_distance) && (total_real_distance == 0)) || (total_distance == 0))
2815 increment_stats("# select_peer, total_distance == 0");
2819 #if DEBUG_DHT_ROUTING > 1
2821 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2823 pos = k_buckets[bc].head;
2825 while ((pos != NULL) && (count < bucket_size))
2827 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2828 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2830 if (GNUNET_YES == use_real_distance)
2832 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "REAL: Choose peer with %d matching bits (%.2f percent)\n", matching_bits(&pos->id.hashPubKey, target), (inverse_distance (target, &pos->id.hashPubKey) / (double)total_real_distance) * 100);
2833 sum += inverse_distance (target, &pos->id.hashPubKey) / (double)total_real_distance;
2837 match_num = 1 + (matching_bits(&pos->id.hashPubKey, target) * matching_bits(&pos->id.hashPubKey, target));
2838 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose peer with %d matching bits (%.2f percent)\n", matching_bits(&pos->id.hashPubKey, target), (match_num / (double)total_distance) * 100);
2839 sum += match_num / (double)total_distance;
2849 if (use_real_distance)
2851 GNUNET_assert(total_real_distance != 0);
2852 real_selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_real_distance);
2856 GNUNET_assert(total_distance != 0);
2857 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2860 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2862 pos = k_buckets[bc].head;
2864 while ((pos != NULL) && (count < bucket_size))
2866 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2867 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2869 if (GNUNET_YES == use_real_distance)
2871 distance = inverse_distance (target, &pos->id.hashPubKey);
2872 if (distance > real_selected)
2874 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "(REAL) Selected peer with %u matching bits to route to\n", matching_bits(target, &pos->id.hashPubKey));
2877 real_selected -= distance;
2881 distance = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target, &pos->id.hashPubKey));
2882 if (distance > selected)
2884 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Selected peer with %u matching bits to route to\n", matching_bits(target, &pos->id.hashPubKey));
2887 selected -= distance;
2893 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2894 "`%s:%s': peer %s matches bloomfilter.\n",
2895 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2904 "`%s:%s': peer %s matches bloomfilter.\n",
2905 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2907 increment_stats("# failed to select peer");
2908 GNUNET_assert(only_closer == GNUNET_NO);
2914 * Task used to remove recent entries, either
2915 * after timeout, when full, or on shutdown.
2917 * @param cls the entry to remove
2918 * @param tc context, reason, etc.
2921 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2923 struct RecentRequest *req = cls;
2924 static GNUNET_HashCode hash;
2926 GNUNET_assert(req != NULL);
2927 hash_from_uid(req->uid, &hash);
2928 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
2929 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
2930 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
2933 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
2935 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
2936 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
2942 * Task used to remove forwarding entries, either
2943 * after timeout, when full, or on shutdown.
2945 * @param cls the entry to remove
2946 * @param tc context, reason, etc.
2949 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2951 struct DHTRouteSource *source_info = cls;
2952 struct DHTQueryRecord *record;
2953 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2954 record = source_info->record;
2955 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2957 if (record->head == NULL) /* No more entries in DLL */
2959 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2960 GNUNET_free(record);
2962 if (source_info->find_peers_responded != NULL)
2963 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
2964 GNUNET_free(source_info);
2968 * Remember this routing request so that if a reply is
2969 * received we can either forward it to the correct peer
2970 * or return the result locally.
2972 * @param cls DHT service closure
2973 * @param msg_ctx Context of the route request
2975 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2977 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2979 struct DHTQueryRecord *record;
2980 struct DHTRouteSource *source_info;
2981 struct DHTRouteSource *pos;
2982 struct GNUNET_TIME_Absolute now;
2983 unsigned int current_size;
2985 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2986 while (current_size >= MAX_OUTSTANDING_FORWARDS)
2988 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2989 GNUNET_assert(source_info != NULL);
2990 record = source_info->record;
2991 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2992 if (record->head == NULL) /* No more entries in DLL */
2994 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2995 GNUNET_free(record);
2997 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2998 if (source_info->find_peers_responded != NULL)
2999 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3000 GNUNET_free(source_info);
3001 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3003 now = GNUNET_TIME_absolute_get();
3004 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3005 if (record != NULL) /* Already know this request! */
3010 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3011 break; /* Already have this peer in reply list! */
3014 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3016 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3022 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3023 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3024 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3027 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3028 source_info->record = record;
3029 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3030 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3031 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3032 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3033 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3035 source_info->client = msg_ctx->client;
3036 now = GNUNET_TIME_absolute_get_forever();
3038 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3041 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3042 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
3049 * Main function that handles whether or not to route a message to other
3052 * @param cls closure for dht service (NULL)
3053 * @param msg the message to be routed
3054 * @param message_context the context containing all pertinent information about the message
3056 * @return the number of peers the message was routed to,
3057 * GNUNET_SYSERR on failure
3059 static int route_message(void *cls,
3060 const struct GNUNET_MessageHeader *msg,
3061 struct DHT_MessageContext *message_context)
3065 struct PeerInfo *selected;
3066 #if DEBUG_DHT_ROUTING > 1
3067 struct PeerInfo *nearest;
3069 unsigned int forward_count;
3070 struct RecentRequest *recent_req;
3071 GNUNET_HashCode unique_hash;
3072 char *stat_forward_count;
3073 #if DEBUG_DHT_ROUTING
3077 if (malicious_dropper == GNUNET_YES)
3079 #if DEBUG_DHT_ROUTING
3080 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3082 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3083 message_context->hop_count, GNUNET_SYSERR,
3084 &my_identity, &message_context->key, message_context->peer,
3088 if (message_context->bloom != NULL)
3089 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3093 increment_stats(STAT_ROUTES);
3094 /* Semantics of this call means we find whether we are the closest peer out of those already
3095 * routed to on this messages path.
3097 global_closest = am_closest_peer(&message_context->key, NULL);
3098 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3099 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3100 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3101 increment_stats(stat_forward_count);
3102 GNUNET_free(stat_forward_count);
3103 if (message_context->bloom == NULL)
3104 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3106 if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3110 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3111 * any closer peers (which is being checked for below). Since we are doing recursive
3112 * routing we have no choice but to stop forwarding in this case. This means that at
3113 * any given step the request may NOT be forwarded to alpha peers (because routes will
3114 * stop and the parallel route will not be aware of it). Of course, assuming that we
3115 * have fulfilled the Kademlia requirements for routing table fullness this will never
3116 * ever ever be a problem.
3118 * However, is this fair?
3120 * Since we use these requests to build our routing tables (and we build them in the
3121 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3122 * routing tables still get constructed.
3124 if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3127 #if DEBUG_DHT_ROUTING
3128 if (forward_count == 0)
3129 ret = GNUNET_SYSERR;
3133 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3135 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3136 message_context->hop_count, ret,
3137 &my_identity, &message_context->key, message_context->peer,
3142 switch (ntohs(msg->type))
3144 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3145 cache_response (cls, message_context);
3146 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3149 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3150 increment_stats(STAT_PUTS);
3151 message_context->closest = global_closest;
3152 handle_dht_put (cls, msg, message_context);
3154 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3155 increment_stats(STAT_FIND_PEER);
3156 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3158 cache_response (cls, message_context);
3159 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3160 handle_dht_find_peer (cls, msg, message_context);
3162 #if DEBUG_DHT_ROUTING
3163 if (message_context->hop_count == 0) /* Locally initiated request */
3165 if ((debug_routes) && (dhtlog_handle != NULL))
3167 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3168 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3169 message_context->hop_count, GNUNET_NO, &my_identity,
3170 &message_context->key);
3176 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3177 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3180 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3181 hash_from_uid(message_context->unique_id, &unique_hash);
3182 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent.hashmap, &unique_hash))
3184 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3185 GNUNET_assert(recent_req != NULL);
3186 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3187 increment_stats(STAT_DUPLICATE_UID);
3190 increment_stats(STAT_RECENT_SEEN);
3191 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3196 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3197 recent_req->uid = message_context->unique_id;
3198 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3199 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3200 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3201 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3202 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3205 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3207 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3208 GNUNET_assert(recent_req != NULL);
3209 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3210 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3213 for (i = 0; i < forward_count; i++)
3215 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3217 if (selected != NULL)
3219 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3220 #if DEBUG_DHT_ROUTING > 1
3221 nearest = find_closest_peer(&message_context->key);
3222 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3223 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3224 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3225 "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));
3226 GNUNET_free(nearest_buf);
3228 #if DEBUG_DHT_ROUTING
3229 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3231 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3232 message_context->hop_count, GNUNET_NO,
3233 &my_identity, &message_context->key, message_context->peer,
3237 forward_message(cls, msg, selected, message_context);
3241 increment_stats("# NULL returned from select_peer");
3242 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3243 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
3248 #if DEBUG_DHT_ROUTING > 1
3249 if (forward_count == 0)
3251 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3252 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
3253 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
3257 if (message_context->bloom != NULL)
3259 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3260 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3263 return forward_count;
3267 * Iterator for local get request results,
3269 * @param cls closure for iterator, NULL
3270 * @param exp when does this value expire?
3271 * @param key the key this data is stored under
3272 * @param size the size of the data identified by key
3273 * @param data the actual data
3274 * @param type the type of the data
3276 * @return GNUNET_OK to continue iteration, anything else
3277 * to stop iteration.
3280 republish_content_iterator (void *cls,
3281 struct GNUNET_TIME_Absolute exp,
3282 const GNUNET_HashCode * key,
3283 uint32_t size, const char *data, uint32_t type)
3286 struct DHT_MessageContext *new_msg_ctx;
3287 struct GNUNET_DHT_PutMessage *put_msg;
3289 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3290 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3292 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3295 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3296 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3297 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3298 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3299 put_msg->type = htons (type);
3300 memcpy (&put_msg[1], data, size);
3301 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3302 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3303 new_msg_ctx->msg_options = ntohl (0);
3304 new_msg_ctx->network_size = estimate_diameter();
3305 new_msg_ctx->peer = &my_identity;
3306 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3307 new_msg_ctx->hop_count = 0;
3308 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3309 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3310 increment_stats(STAT_PUT_START);
3311 route_message(cls, &put_msg->header, new_msg_ctx);
3313 GNUNET_free(new_msg_ctx);
3314 GNUNET_free (put_msg);
3319 * Task used to republish data.
3321 * @param cls closure (a struct RepublishContext)
3322 * @param tc runtime context for this task
3325 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3327 struct RepublishContext *put_context = cls;
3329 unsigned int results;
3331 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3333 GNUNET_free(put_context);
3337 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3338 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3339 if (results == 0) /* Data must have expired */
3340 GNUNET_free(put_context);
3341 else /* Reschedule task for next time period */
3342 GNUNET_SCHEDULER_add_delayed(sched, DHT_REPUBLISH_FREQUENCY, &republish_content, put_context);
3347 * Find a client if it exists, add it otherwise.
3349 * @param client the server handle to the client
3351 * @return the client if found, a new client otherwise
3353 static struct ClientList *
3354 find_active_client (struct GNUNET_SERVER_Client *client)
3356 struct ClientList *pos = client_list;
3357 struct ClientList *ret;
3361 if (pos->client_handle == client)
3366 ret = GNUNET_malloc (sizeof (struct ClientList));
3367 ret->client_handle = client;
3368 ret->next = client_list;
3374 * Task to send a malicious put message across the network.
3376 * @param cls closure for this task
3377 * @param tc the context under which the task is running
3380 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3382 static struct GNUNET_DHT_PutMessage put_message;
3383 static struct DHT_MessageContext message_context;
3384 static GNUNET_HashCode key;
3385 uint32_t random_key;
3387 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3390 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3391 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3392 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3393 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3394 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3395 message_context.client = NULL;
3396 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3397 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3398 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3399 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3400 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3401 message_context.msg_options = ntohl (0);
3402 message_context.network_size = estimate_diameter();
3403 message_context.peer = &my_identity;
3404 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3405 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3406 #if DEBUG_DHT_ROUTING
3407 if (dhtlog_handle != NULL)
3408 dhtlog_handle->insert_dhtkey(NULL, &key);
3410 increment_stats(STAT_PUT_START);
3411 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3412 route_message(NULL, &put_message.header, &message_context);
3413 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3418 * Task to send a malicious put message across the network.
3420 * @param cls closure for this task
3421 * @param tc the context under which the task is running
3424 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3426 static struct GNUNET_DHT_GetMessage get_message;
3427 struct DHT_MessageContext message_context;
3428 static GNUNET_HashCode key;
3429 uint32_t random_key;
3431 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3434 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3435 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3436 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3437 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3438 message_context.client = NULL;
3439 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3440 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3441 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3442 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3443 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3444 message_context.msg_options = ntohl (0);
3445 message_context.network_size = estimate_diameter();
3446 message_context.peer = &my_identity;
3447 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3448 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3449 #if DEBUG_DHT_ROUTING
3450 if (dhtlog_handle != NULL)
3451 dhtlog_handle->insert_dhtkey(NULL, &key);
3453 increment_stats(STAT_GET_START);
3454 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3455 route_message (NULL, &get_message.header, &message_context);
3456 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3460 * Iterator over hash map entries.
3462 * @param cls closure
3463 * @param key current key code
3464 * @param value value in the hash map
3465 * @return GNUNET_YES if we should continue to
3470 add_known_to_bloom (void *cls,
3471 const GNUNET_HashCode * key,
3474 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3475 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3480 * Task to send a find peer message for our own peer identifier
3481 * so that we can find the closest peers in the network to ourselves
3482 * and attempt to connect to them.
3484 * @param cls closure for this task
3485 * @param tc the context under which the task is running
3488 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3490 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3491 struct DHT_MessageContext message_context;
3493 struct GNUNET_TIME_Relative next_send_time;
3494 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3496 struct GNUNET_TIME_Relative time_diff;
3497 struct GNUNET_TIME_Absolute end;
3499 double count_per_interval;
3501 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3504 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! */
3506 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3507 GNUNET_SCHEDULER_add_delayed (sched,
3508 GNUNET_TIME_UNIT_MINUTES,
3509 &send_find_peer_message, NULL);
3510 newly_found_peers = 0;
3514 increment_stats(STAT_FIND_PEER_START);
3516 end = GNUNET_TIME_absolute_get();
3517 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3519 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3521 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3522 count_per_interval = find_peer_context.count / multiplier;
3526 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3527 count_per_interval = find_peer_context.count * multiplier;
3531 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3532 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3533 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3534 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3535 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3536 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3537 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3538 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3539 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3540 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3541 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3542 message_context.network_size = estimate_diameter();
3543 message_context.peer = &my_identity;
3544 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3545 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3547 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3548 GNUNET_free(find_peer_msg);
3549 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3550 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3552 if (newly_found_peers < bucket_size)
3554 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3555 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3556 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3560 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3561 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3562 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3565 GNUNET_assert (next_send_time.value != 0);
3566 find_peer_context.count = 0;
3567 newly_found_peers = 0;
3568 find_peer_context.start = GNUNET_TIME_absolute_get();
3569 if (GNUNET_YES == do_find_peer)
3571 GNUNET_SCHEDULER_add_delayed (sched,
3573 &send_find_peer_message, NULL);
3578 * Handler for any generic DHT messages, calls the appropriate handler
3579 * depending on message type, sends confirmation if responses aren't otherwise
3582 * @param cls closure for the service
3583 * @param client the client we received this message from
3584 * @param message the actual message received
3587 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3588 const struct GNUNET_MessageHeader *message)
3590 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3591 const struct GNUNET_MessageHeader *enc_msg;
3592 struct DHT_MessageContext message_context;
3593 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3595 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3596 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3597 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3598 GNUNET_ntohll (dht_msg->unique_id));
3600 #if DEBUG_DHT_ROUTING
3601 if (dhtlog_handle != NULL)
3602 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3604 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3605 message_context.client = find_active_client (client);
3606 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3607 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3608 message_context.replication = ntohl (dht_msg->desired_replication_level);
3609 message_context.msg_options = ntohl (dht_msg->options);
3610 message_context.network_size = estimate_diameter();
3611 message_context.peer = &my_identity;
3612 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3613 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3614 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3615 increment_stats(STAT_GET_START);
3616 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3617 increment_stats(STAT_PUT_START);
3618 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3619 increment_stats(STAT_FIND_PEER_START);
3621 route_message(cls, enc_msg, &message_context);
3623 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3628 * Handler for any locally received DHT control messages,
3629 * sets malicious flags mostly for now.
3631 * @param cls closure for the service
3632 * @param client the client we received this message from
3633 * @param message the actual message received
3637 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3638 const struct GNUNET_MessageHeader *message)
3640 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3641 (const struct GNUNET_DHT_ControlMessage *) message;
3643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3644 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3645 "CONTROL", ntohs(dht_control_msg->command));
3648 switch (ntohs(dht_control_msg->command))
3650 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3651 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3652 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3654 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3655 if (ntohs(dht_control_msg->variable) > 0)
3656 malicious_get_frequency = ntohs(dht_control_msg->variable);
3657 if (malicious_get_frequency == 0)
3658 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3659 if (malicious_getter != GNUNET_YES)
3660 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3661 malicious_getter = GNUNET_YES;
3662 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3664 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3665 if (ntohs(dht_control_msg->variable) > 0)
3666 malicious_put_frequency = ntohs(dht_control_msg->variable);
3667 if (malicious_put_frequency == 0)
3668 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3669 if (malicious_putter != GNUNET_YES)
3670 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3671 malicious_putter = GNUNET_YES;
3672 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3674 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3675 #if DEBUG_DHT_ROUTING
3676 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3677 dhtlog_handle->set_malicious(&my_identity);
3679 malicious_dropper = GNUNET_YES;
3680 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3683 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3686 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3690 * Handler for any generic DHT stop messages, calls the appropriate handler
3691 * depending on message type (if processed locally)
3693 * @param cls closure for the service
3694 * @param client the client we received this message from
3695 * @param message the actual message received
3699 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3700 const struct GNUNET_MessageHeader *message)
3703 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3704 (const struct GNUNET_DHT_StopMessage *) message;
3705 struct DHTQueryRecord *record;
3706 struct DHTRouteSource *pos;
3708 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3709 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3710 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3712 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3719 if ((pos->client != NULL) && (pos->client->client_handle == client))
3721 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3722 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3728 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3733 * Core handler for p2p route requests.
3736 handle_dht_p2p_route_request (void *cls,
3737 const struct GNUNET_PeerIdentity *peer,
3738 const struct GNUNET_MessageHeader *message,
3739 struct GNUNET_TIME_Relative latency, uint32_t distance)
3742 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3743 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3745 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3746 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3747 struct DHT_MessageContext *message_context;
3749 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
3751 fprintf(stderr, "Sending of previous replies took far too long, backing off!\n");
3752 decrease_max_send_delay(get_max_send_delay());
3756 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3759 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3764 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
3769 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3770 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3771 GNUNET_assert(message_context->bloom != NULL);
3772 message_context->hop_count = ntohl(incoming->hop_count);
3773 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
3774 message_context->replication = ntohl(incoming->desired_replication_level);
3775 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3776 message_context->msg_options = ntohl(incoming->options);
3777 message_context->network_size = ntohl(incoming->network_size);
3778 message_context->peer = peer;
3779 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3780 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3781 route_message(cls, enc_msg, message_context);
3782 GNUNET_free(message_context);
3788 * Core handler for p2p route results.
3791 handle_dht_p2p_route_result (void *cls,
3792 const struct GNUNET_PeerIdentity *peer,
3793 const struct GNUNET_MessageHeader *message,
3794 struct GNUNET_TIME_Relative latency, uint32_t distance)
3797 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3798 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3800 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3801 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3802 struct DHT_MessageContext message_context;
3804 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
3810 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3811 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3812 GNUNET_assert(message_context.bloom != NULL);
3813 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
3814 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3815 message_context.msg_options = ntohl(incoming->options);
3816 message_context.hop_count = ntohl(incoming->hop_count);
3817 message_context.peer = peer;
3818 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3819 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3820 route_result_message(cls, enc_msg, &message_context);
3826 * Receive the HELLO from transport service,
3827 * free current and replace if necessary.
3830 * @param message HELLO message of peer
3833 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3836 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3837 "Received our `%s' from transport service\n",
3841 GNUNET_assert (message != NULL);
3842 GNUNET_free_non_null(my_hello);
3843 my_hello = GNUNET_malloc(ntohs(message->size));
3844 memcpy(my_hello, message, ntohs(message->size));
3849 * Task run during shutdown.
3855 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3858 struct PeerInfo *pos;
3859 if (transport_handle != NULL)
3861 GNUNET_free_non_null(my_hello);
3862 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3863 GNUNET_TRANSPORT_disconnect(transport_handle);
3866 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3868 while (k_buckets[bucket_count].head != NULL)
3870 pos = k_buckets[bucket_count].head;
3872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3873 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3875 delete_peer(pos, bucket_count);
3878 if (coreAPI != NULL)
3881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3882 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3884 GNUNET_CORE_disconnect (coreAPI);
3886 if (datacache != NULL)
3889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3890 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3892 GNUNET_DATACACHE_destroy (datacache);
3897 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3900 if (dhtlog_handle != NULL)
3901 GNUNET_DHTLOG_disconnect(dhtlog_handle);
3903 GNUNET_free_non_null(my_short_id);
3908 * To be called on core init/fail.
3910 * @param cls service closure
3911 * @param server handle to the server for this service
3912 * @param identity the public identity of this peer
3913 * @param publicKey the public key of this peer
3916 core_init (void *cls,
3917 struct GNUNET_CORE_Handle *server,
3918 const struct GNUNET_PeerIdentity *identity,
3919 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3926 "%s: Connection to core FAILED!\n", "dht",
3927 GNUNET_i2s (identity));
3929 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
3930 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3934 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3935 "%s: Core connection initialized, I am peer: %s\n", "dht",
3936 GNUNET_i2s (identity));
3939 /* Copy our identity so we can use it */
3940 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3941 if (my_short_id != NULL)
3942 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3943 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3944 /* Set the server to local variable */
3947 if (dhtlog_handle != NULL)
3948 dhtlog_handle->insert_node (NULL, &my_identity);
3952 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3953 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3954 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3955 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
3960 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3961 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
3962 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
3967 * Method called whenever a peer connects.
3969 * @param cls closure
3970 * @param peer peer identity this notification is about
3971 * @param latency reported latency of the connection with peer
3972 * @param distance reported distance (DV) to peer
3974 void handle_core_connect (void *cls,
3975 const struct GNUNET_PeerIdentity * peer,
3976 struct GNUNET_TIME_Relative latency,
3979 struct PeerInfo *ret;
3982 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3983 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
3986 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3988 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));
3992 if (datacache != NULL)
3993 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
3994 ret = try_add_peer(peer,
3995 find_current_bucket(&peer->hashPubKey),
4000 newly_found_peers++;
4001 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4004 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4005 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4010 * Method called whenever a peer disconnects.
4012 * @param cls closure
4013 * @param peer peer identity this notification is about
4015 void handle_core_disconnect (void *cls,
4017 GNUNET_PeerIdentity * peer)
4019 struct PeerInfo *to_remove;
4022 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");
4024 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4026 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));
4029 increment_stats(STAT_DISCONNECTS);
4030 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4031 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4032 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4033 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4034 delete_peer(to_remove, current_bucket);
4038 * Process dht requests.
4040 * @param cls closure
4041 * @param scheduler scheduler to use
4042 * @param server the initialized server
4043 * @param c configuration to use
4047 struct GNUNET_SCHEDULER_Handle *scheduler,
4048 struct GNUNET_SERVER_Handle *server,
4049 const struct GNUNET_CONFIGURATION_Handle *c)
4052 struct GNUNET_TIME_Relative next_send_time;
4056 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4057 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4058 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4059 cfg, /* Main configuration */
4060 GNUNET_TIME_UNIT_FOREVER_REL,
4061 NULL, /* Closure passed to DHT functions */
4062 &core_init, /* Call core_init once connected */
4063 &handle_core_connect, /* Handle connects */
4064 &handle_core_disconnect, /* remove peers on disconnects */
4065 NULL, /* Do we care about "status" updates? */
4066 NULL, /* Don't want notified about all incoming messages */
4067 GNUNET_NO, /* For header only inbound notification */
4068 NULL, /* Don't want notified about all outbound messages */
4069 GNUNET_NO, /* For header only outbound notification */
4070 core_handlers); /* Register these handlers */
4072 if (coreAPI == NULL)
4074 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
4075 NULL, NULL, NULL, NULL, NULL);
4076 if (transport_handle != NULL)
4077 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4079 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4081 lowest_bucket = MAX_BUCKETS - 1;
4082 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4083 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4084 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4085 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4086 GNUNET_assert(all_known_peers != NULL);
4087 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4089 debug_routes = GNUNET_YES;
4093 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4096 strict_kademlia = GNUNET_YES;
4100 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4103 stop_on_closest = GNUNET_YES;
4107 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4110 stop_on_found = GNUNET_YES;
4114 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4115 "malicious_getter"))
4117 malicious_getter = GNUNET_YES;
4118 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4119 "MALICIOUS_GET_FREQUENCY",
4120 &malicious_get_frequency))
4121 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4125 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4126 "malicious_putter"))
4128 malicious_putter = GNUNET_YES;
4129 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4130 "MALICIOUS_PUT_FREQUENCY",
4131 &malicious_put_frequency))
4132 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4136 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4137 "malicious_dropper"))
4139 malicious_dropper = GNUNET_YES;
4143 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4145 do_republish = GNUNET_NO;
4148 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4151 do_find_peer = GNUNET_NO;
4154 do_find_peer = GNUNET_YES;
4157 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4158 "use_real_distance"))
4159 use_real_distance = GNUNET_YES;
4162 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4163 "mysql_logging_extended"))
4165 debug_routes = GNUNET_YES;
4166 debug_routes_extended = GNUNET_YES;
4169 #if DEBUG_DHT_ROUTING
4170 if (GNUNET_YES == debug_routes)
4172 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4173 if (dhtlog_handle == NULL)
4175 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4176 "Could not connect to mysql logging server, logging will not happen!");
4181 converge_option = DHT_CONVERGE_SQUARE;
4183 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4186 converge_option = DHT_CONVERGE_LINEAR;
4189 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4193 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4194 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4195 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4196 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4197 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4198 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4199 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4200 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4201 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4202 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4203 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4204 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4205 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4206 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4207 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4208 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4209 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4210 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4211 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4212 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4214 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4215 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4216 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4217 if (GNUNET_YES == do_find_peer)
4219 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4220 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4221 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4222 find_peer_context.start = GNUNET_TIME_absolute_get();
4223 GNUNET_SCHEDULER_add_delayed (sched,
4225 &send_find_peer_message, &find_peer_context);
4228 /* Scheduled the task to clean up when shutdown is called */
4229 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4230 GNUNET_TIME_UNIT_FOREVER_REL,
4231 &shutdown_task, NULL);
4235 * The main function for the dht service.
4237 * @param argc number of arguments from the command line
4238 * @param argv command line arguments
4239 * @return 0 ok, 1 on error
4242 main (int argc, char *const *argv)
4244 return (GNUNET_OK ==
4245 GNUNET_SERVICE_run (argc,
4248 GNUNET_SERVICE_OPTION_NONE,
4249 &run, NULL)) ? 0 : 1;