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;
674 static unsigned int use_real_distance;
677 * How many peers have we added since we sent out our last
680 static unsigned int newly_found_peers;
683 * Container of active queries we should remember
685 static struct DHTResults forward_list;
688 * Handle to the datacache service (for inserting/retrieving data)
690 static struct GNUNET_DATACACHE_Handle *datacache;
693 * Handle for the statistics service.
695 struct GNUNET_STATISTICS_Handle *stats;
698 * The main scheduler to use for the DHT service
700 static struct GNUNET_SCHEDULER_Handle *sched;
703 * The configuration the DHT service is running with
705 static const struct GNUNET_CONFIGURATION_Handle *cfg;
708 * Handle to the core service
710 static struct GNUNET_CORE_Handle *coreAPI;
713 * Handle to the transport service, for getting our hello
715 static struct GNUNET_TRANSPORT_Handle *transport_handle;
718 * The identity of our peer.
720 static struct GNUNET_PeerIdentity my_identity;
723 * Short id of the peer, for printing
725 static char *my_short_id;
730 static struct GNUNET_MessageHeader *my_hello;
733 * Task to run when we shut down, cleaning up all our trash
735 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
738 * The lowest currently used bucket.
740 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
743 * The buckets (Kademlia routing table, complete with growth).
744 * Array of size MAX_BUCKET_SIZE.
746 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
749 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
751 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
754 * Recently seen find peer requests.
756 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
759 * Maximum size for each bucket.
761 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
764 * List of active clients.
766 static struct ClientList *client_list;
769 * Handle to the DHT logger.
771 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
774 * Whether or not to send routing debugging information
775 * to the dht logging server
777 static unsigned int debug_routes;
780 * Whether or not to send FULL route information to
783 static unsigned int debug_routes_extended;
786 * GNUNET_YES or GNUNET_NO, whether or not to act as
787 * a malicious node which drops all messages
789 static unsigned int malicious_dropper;
792 * GNUNET_YES or GNUNET_NO, whether or not to act as
793 * a malicious node which sends out lots of GETS
795 static unsigned int malicious_getter;
798 * GNUNET_YES or GNUNET_NO, whether or not to act as
799 * a malicious node which sends out lots of PUTS
801 static unsigned int malicious_putter;
804 * Frequency for malicious get requests.
806 static unsigned long long malicious_get_frequency;
809 * Frequency for malicious put requests.
811 static unsigned long long malicious_put_frequency;
814 * Reply times for requests, if we are busy, don't send any
817 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
820 * Current counter for replies.
822 static unsigned int reply_counter;
825 * Forward declaration.
827 static size_t send_generic_reply (void *cls, size_t size, void *buf);
829 /** Declare here so retry_core_send is aware of it */
830 size_t core_transmit_notify (void *cls,
831 size_t size, void *buf);
834 * Convert unique ID to hash code.
836 * @param uid unique ID to convert
837 * @param hash set to uid (extended with zeros)
840 hash_from_uid (uint64_t uid,
841 GNUNET_HashCode *hash)
843 memset (hash, 0, sizeof(GNUNET_HashCode));
844 *((uint64_t*)hash) = uid;
849 * Calculate the average send time between messages so that we can
850 * ignore certain requests if we get too busy.
852 * @return the average time between asking core to send a message
853 * and when the buffer for copying it is passed
855 static struct GNUNET_TIME_Relative get_average_send_delay()
858 unsigned int divisor;
859 struct GNUNET_TIME_Relative average_time;
860 average_time = GNUNET_TIME_relative_get_zero();
862 for (i = 0; i < MAX_REPLY_TIMES; i++)
864 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
865 if (reply_times[i].value == (uint64_t)0)
875 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
876 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
882 * Given the largest send delay, artificially decrease it
883 * so the next time around we may have a chance at sending
886 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
889 for (i = 0; i < MAX_REPLY_TIMES; i++)
891 if (reply_times[i].value == max_time.value)
893 reply_times[i].value = reply_times[i].value / 2;
900 * Find the maximum send time of the recently sent values.
902 * @return the average time between asking core to send a message
903 * and when the buffer for copying it is passed
905 static struct GNUNET_TIME_Relative get_max_send_delay()
908 struct GNUNET_TIME_Relative max_time;
909 max_time = GNUNET_TIME_relative_get_zero();
911 for (i = 0; i < MAX_REPLY_TIMES; i++)
913 if (reply_times[i].value > max_time.value)
914 max_time.value = reply_times[i].value;
917 if (max_time.value > MAX_REQUEST_TIME.value)
918 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
923 increment_stats(const char *value)
927 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
932 * Try to send another message from our core send list
935 try_core_send (void *cls,
936 const struct GNUNET_SCHEDULER_TaskContext *tc)
938 struct PeerInfo *peer = cls;
939 struct P2PPendingMessage *pending;
942 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
944 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
947 if (peer->th != NULL)
948 return; /* Message send already in progress */
950 pending = peer->head;
953 ssize = ntohs(pending->msg->size);
955 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
956 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
957 "DHT", ssize, GNUNET_i2s(&peer->id));
959 pending->scheduled = GNUNET_TIME_absolute_get();
961 if (reply_counter >= MAX_REPLY_TIMES)
963 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
964 pending->timeout, &peer->id,
965 ssize, &core_transmit_notify, peer);
970 * Function called to send a request out to another peer.
971 * Called both for locally initiated requests and those
972 * received from other peers.
974 * @param cls DHT service closure argument
975 * @param msg the encapsulated message
976 * @param peer the peer to forward the message to
977 * @param msg_ctx the context of the message (hop count, bloom, etc.)
979 static void forward_result_message (void *cls,
980 const struct GNUNET_MessageHeader *msg,
981 struct PeerInfo *peer,
982 struct DHT_MessageContext *msg_ctx)
984 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
985 struct P2PPendingMessage *pending;
989 increment_stats(STAT_RESULT_FORWARDS);
990 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
991 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
992 psize = sizeof(struct P2PPendingMessage) + msize;
993 pending = GNUNET_malloc(psize);
994 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
995 pending->importance = DHT_SEND_PRIORITY;
996 pending->timeout = GNUNET_TIME_relative_get_forever();
997 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
998 result_message->header.size = htons(msize);
999 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1000 result_message->options = htonl(msg_ctx->msg_options);
1001 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1002 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1003 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1004 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1005 memcpy(&result_message[1], msg, ntohs(msg->size));
1007 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));
1009 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1010 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1011 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1014 * Called when core is ready to send a message we asked for
1015 * out to the destination.
1017 * @param cls closure (NULL)
1018 * @param size number of bytes available in buf
1019 * @param buf where the callee should write the message
1020 * @return number of bytes written to buf
1022 size_t core_transmit_notify (void *cls,
1023 size_t size, void *buf)
1025 struct PeerInfo *peer = cls;
1027 struct P2PPendingMessage *pending;
1034 /* client disconnected */
1036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1041 if (peer->head == NULL)
1046 pending = peer->head;
1047 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1048 msize = ntohs(pending->msg->size);
1052 memcpy (cbuf, pending->msg, msize);
1053 GNUNET_CONTAINER_DLL_remove (peer->head,
1057 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));
1059 GNUNET_free (pending);
1062 while (NULL != pending &&
1063 (size - off >= (msize = ntohs (pending->msg->size))))
1065 #if DEBUG_DHT_ROUTING
1066 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);
1068 memcpy (&cbuf[off], pending->msg, msize);
1070 GNUNET_CONTAINER_DLL_remove (peer->head,
1073 GNUNET_free (pending);
1074 pending = peer->head;
1077 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1078 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1080 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);
1086 * Determine how many low order bits match in two
1087 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
1088 * the first two lowest order bits, and therefore the
1089 * return value is two (NOT XOR distance, nor how many
1090 * bits match absolutely!).
1092 * @param first the first hashcode
1093 * @param second the hashcode to compare first to
1095 * @return the number of bits that match
1097 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
1101 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
1102 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
1104 return sizeof (GNUNET_HashCode) * 8;
1108 * Compute the distance between have and target as a 32-bit value.
1109 * Differences in the lower bits must count stronger than differences
1110 * in the higher bits.
1112 * @return 0 if have==target, otherwise a number
1113 * that is larger as the distance between
1114 * the two hash codes increases
1117 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1119 unsigned int bucket;
1124 /* We have to represent the distance between two 2^9 (=512)-bit
1125 numbers as a 2^5 (=32)-bit number with "0" being used for the
1126 two numbers being identical; furthermore, we need to
1127 guarantee that a difference in the number of matching
1128 bits is always represented in the result.
1130 We use 2^32/2^9 numerical values to distinguish between
1131 hash codes that have the same LSB bit distance and
1132 use the highest 2^9 bits of the result to signify the
1133 number of (mis)matching LSB bits; if we have 0 matching
1134 and hence 512 mismatching LSB bits we return -1 (since
1135 512 itself cannot be represented with 9 bits) */
1137 /* first, calculate the most significant 9 bits of our
1138 result, aka the number of LSBs */
1139 bucket = matching_bits (target, have);
1140 /* bucket is now a value between 0 and 512 */
1142 return 0; /* perfect match */
1144 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1145 below, we'd end up with max+1 (overflow)) */
1147 /* calculate the most significant bits of the final result */
1148 msb = (512 - bucket) << (32 - 9);
1149 /* calculate the 32-9 least significant bits of the final result by
1150 looking at the differences in the 32-9 bits following the
1151 mismatching bit at 'bucket' */
1153 for (i = bucket + 1;
1154 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1156 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1157 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1158 last bit set will be 31 -- if
1159 i does not reach 512 first... */
1165 * Return a number that is larger the closer the
1166 * "have" GNUNET_hash code is to the "target".
1168 * @return inverse distance metric, non-zero.
1169 * Must fudge the value if NO bits match.
1172 inverse_distance (const GNUNET_HashCode * target,
1173 const GNUNET_HashCode * have)
1175 if (matching_bits(target, have) == 0)
1176 return 1; /* Never return 0! */
1177 return ((unsigned int) -1) - distance (target, have);
1181 * Find the optimal bucket for this key, regardless
1182 * of the current number of buckets in use.
1184 * @param hc the hashcode to compare our identity to
1186 * @return the proper bucket index, or GNUNET_SYSERR
1187 * on error (same hashcode)
1189 static int find_bucket(const GNUNET_HashCode *hc)
1193 bits = matching_bits(&my_identity.hashPubKey, hc);
1194 if (bits == MAX_BUCKETS)
1195 return GNUNET_SYSERR;
1196 return MAX_BUCKETS - bits - 1;
1200 * Find which k-bucket this peer should go into,
1201 * taking into account the size of the k-bucket
1202 * array. This means that if more bits match than
1203 * there are currently buckets, lowest_bucket will
1206 * @param hc GNUNET_HashCode we are finding the bucket for.
1208 * @return the proper bucket index for this key,
1209 * or GNUNET_SYSERR on error (same hashcode)
1211 static int find_current_bucket(const GNUNET_HashCode *hc)
1214 actual_bucket = find_bucket(hc);
1216 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1217 return GNUNET_SYSERR;
1218 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1219 return lowest_bucket;
1221 return actual_bucket;
1226 * Find a routing table entry from a peer identity
1228 * @param peer the peer to look up
1230 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1233 find_bucket_by_peer(const struct PeerInfo *peer)
1236 struct PeerInfo *pos;
1238 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1240 pos = k_buckets[bucket].head;
1249 return GNUNET_SYSERR; /* No such peer. */
1255 * Print the complete routing table for this peer.
1258 print_routing_table ()
1261 struct PeerInfo *pos;
1262 char char_buf[30000];
1264 memset(char_buf, 0, sizeof(char_buf));
1266 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1267 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1268 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1270 pos = k_buckets[bucket].head;
1271 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1272 //fprintf(stderr, "Bucket %d:\n", bucket);
1275 //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));
1276 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));
1280 fprintf(stderr, "%s", char_buf);
1286 * Find a routing table entry from a peer identity
1288 * @param peer the peer identity to look up
1290 * @return the routing table entry, or NULL if not found
1292 static struct PeerInfo *
1293 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1296 struct PeerInfo *pos;
1297 bucket = find_current_bucket(&peer->hashPubKey);
1299 if (bucket == GNUNET_SYSERR)
1302 pos = k_buckets[bucket].head;
1305 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1309 return NULL; /* No such peer. */
1312 /* Forward declaration */
1314 update_core_preference (void *cls,
1315 const struct GNUNET_SCHEDULER_TaskContext *tc);
1317 * Function called with statistics about the given peer.
1319 * @param cls closure
1320 * @param peer identifies the peer
1321 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1322 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1323 * @param amount set to the amount that was actually reserved or unreserved;
1324 * either the full requested amount or zero (no partial reservations)
1325 * @param preference current traffic preference for the given peer
1328 update_core_preference_finish (void *cls,
1329 const struct GNUNET_PeerIdentity * peer,
1330 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1331 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1332 int amount, uint64_t preference)
1334 struct PeerInfo *peer_info = cls;
1335 peer_info->info_ctx = NULL;
1336 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1340 update_core_preference (void *cls,
1341 const struct GNUNET_SCHEDULER_TaskContext *tc)
1343 struct PeerInfo *peer = cls;
1344 uint64_t preference;
1345 unsigned int matching;
1346 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1350 matching = matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1353 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching_bits);
1356 preference = 1LL << matching;
1357 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1359 GNUNET_TIME_relative_get_forever(),
1360 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1363 &update_core_preference_finish,
1368 * Really add a peer to a bucket (only do assertions
1371 * @param peer GNUNET_PeerIdentity of the peer to add
1372 * @param bucket the already figured out bucket to add
1374 * @param latency the core reported latency of this peer
1375 * @param distance the transport level distance to this peer
1377 * @return the newly added PeerInfo
1379 static struct PeerInfo *
1380 add_peer(const struct GNUNET_PeerIdentity *peer,
1381 unsigned int bucket,
1382 struct GNUNET_TIME_Relative latency,
1383 unsigned int distance)
1385 struct PeerInfo *new_peer;
1386 GNUNET_assert(bucket < MAX_BUCKETS);
1387 GNUNET_assert(peer != NULL);
1388 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1389 new_peer->latency = latency;
1390 new_peer->distance = distance;
1392 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1394 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1395 k_buckets[bucket].tail,
1396 k_buckets[bucket].tail,
1398 k_buckets[bucket].peers_size++;
1400 if ((matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1402 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1409 * Given a peer and its corresponding bucket,
1410 * remove it from that bucket. Does not free
1411 * the PeerInfo struct, nor cancel messages
1412 * or free messages waiting to be sent to this
1415 * @param peer the peer to remove
1416 * @param bucket the bucket the peer belongs to
1418 static void remove_peer (struct PeerInfo *peer,
1419 unsigned int bucket)
1421 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1422 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1423 k_buckets[bucket].tail,
1425 k_buckets[bucket].peers_size--;
1426 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1431 * Removes peer from a bucket, then frees associated
1432 * resources and frees peer.
1434 * @param peer peer to be removed and freed
1435 * @param bucket which bucket this peer belongs to
1437 static void delete_peer (struct PeerInfo *peer,
1438 unsigned int bucket)
1440 struct P2PPendingMessage *pos;
1441 struct P2PPendingMessage *next;
1443 struct PeerInfo *peer_pos;
1445 peer_pos = k_buckets[bucket].head;
1446 while ((peer_pos != NULL) && (peer_pos != peer))
1447 peer_pos = peer_pos->next;
1448 if (peer_pos == NULL)
1450 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1451 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));
1453 GNUNET_assert(peer_pos != NULL);
1455 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1457 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1458 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1459 if (peer->th != NULL)
1460 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1463 while (pos != NULL) /* Remove any pending messages for this peer */
1470 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1471 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1477 * Iterator over hash map entries.
1479 * @param cls closure
1480 * @param key current key code
1481 * @param value PeerInfo of the peer to move to new lowest bucket
1482 * @return GNUNET_YES if we should continue to
1486 static int move_lowest_bucket (void *cls,
1487 const GNUNET_HashCode * key,
1490 struct PeerInfo *peer = value;
1493 GNUNET_assert(lowest_bucket > 0);
1494 new_bucket = lowest_bucket - 1;
1495 remove_peer(peer, lowest_bucket);
1496 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1497 k_buckets[new_bucket].tail,
1498 k_buckets[new_bucket].tail,
1500 k_buckets[new_bucket].peers_size++;
1506 * The current lowest bucket is full, so change the lowest
1507 * bucket to the next lower down, and move any appropriate
1508 * entries in the current lowest bucket to the new bucket.
1510 static void enable_next_bucket()
1512 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1513 struct PeerInfo *pos;
1514 GNUNET_assert(lowest_bucket > 0);
1515 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1516 pos = k_buckets[lowest_bucket].head;
1519 fprintf(stderr, "Printing RT before new bucket\n");
1520 print_routing_table();
1522 /* Populate the array of peers which should be in the next lowest bucket */
1525 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1526 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1530 /* Remove peers from lowest bucket, insert into next lowest bucket */
1531 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1532 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1533 lowest_bucket = lowest_bucket - 1;
1535 fprintf(stderr, "Printing RT after new bucket\n");
1536 print_routing_table();
1541 * Find the closest peer in our routing table to the
1544 * @return The closest peer in our routing table to the
1545 * key, or NULL on error.
1547 static struct PeerInfo *
1548 find_closest_peer (const GNUNET_HashCode *hc)
1550 struct PeerInfo *pos;
1551 struct PeerInfo *current_closest;
1552 unsigned int lowest_distance;
1553 unsigned int temp_distance;
1557 lowest_distance = -1;
1559 if (k_buckets[lowest_bucket].peers_size == 0)
1562 current_closest = NULL;
1563 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1565 pos = k_buckets[bucket].head;
1567 while ((pos != NULL) && (count < bucket_size))
1569 temp_distance = distance(&pos->id.hashPubKey, hc);
1570 if (temp_distance <= lowest_distance)
1572 lowest_distance = temp_distance;
1573 current_closest = pos;
1579 GNUNET_assert(current_closest != NULL);
1580 return current_closest;
1585 * Function called to send a request out to another peer.
1586 * Called both for locally initiated requests and those
1587 * received from other peers.
1589 * @param cls DHT service closure argument (unused)
1590 * @param msg the encapsulated message
1591 * @param peer the peer to forward the message to
1592 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1594 static void forward_message (void *cls,
1595 const struct GNUNET_MessageHeader *msg,
1596 struct PeerInfo *peer,
1597 struct DHT_MessageContext *msg_ctx)
1599 struct GNUNET_DHT_P2PRouteMessage *route_message;
1600 struct P2PPendingMessage *pending;
1604 increment_stats(STAT_ROUTE_FORWARDS);
1606 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1607 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1609 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1610 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1611 psize = sizeof(struct P2PPendingMessage) + msize;
1612 pending = GNUNET_malloc(psize);
1613 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1614 pending->importance = msg_ctx->importance;
1615 pending->timeout = msg_ctx->timeout;
1616 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1617 route_message->header.size = htons(msize);
1618 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1619 route_message->options = htonl(msg_ctx->msg_options);
1620 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1621 route_message->network_size = htonl(msg_ctx->network_size);
1622 route_message->desired_replication_level = htonl(msg_ctx->replication);
1623 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1624 if (msg_ctx->bloom != NULL)
1625 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1626 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1627 memcpy(&route_message[1], msg, ntohs(msg->size));
1629 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));
1631 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1632 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1633 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1638 * Task used to send ping messages to peers so that
1639 * they don't get disconnected.
1641 * @param cls the peer to send a ping message to
1642 * @param tc context, reason, etc.
1645 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1647 struct PeerInfo *peer = cls;
1648 struct GNUNET_MessageHeader ping_message;
1649 struct DHT_MessageContext message_context;
1651 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1654 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1655 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1657 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1659 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1661 forward_message(NULL, &ping_message, peer, &message_context);
1662 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1666 * Schedule PING messages for the top X peers in each
1667 * bucket of the routing table (so core won't disconnect them!)
1669 void schedule_ping_messages()
1671 unsigned int bucket;
1673 struct PeerInfo *pos;
1674 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1676 pos = k_buckets[bucket].head;
1680 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1681 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1682 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1684 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1685 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1695 * Attempt to add a peer to our k-buckets.
1697 * @param peer the peer identity of the peer being added
1698 * @param bucket the bucket that we want this peer to go in
1699 * @param latency transport latency of this peer
1700 * @param distance transport distance to this peer
1702 * @return NULL if the peer was not added,
1703 * pointer to PeerInfo for new peer otherwise
1705 static struct PeerInfo *
1706 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1707 unsigned int bucket,
1708 struct GNUNET_TIME_Relative latency,
1709 unsigned int distance)
1712 struct PeerInfo *new_peer;
1713 peer_bucket = find_current_bucket(&peer->hashPubKey);
1714 if (peer_bucket == GNUNET_SYSERR)
1717 GNUNET_assert(peer_bucket >= lowest_bucket);
1718 new_peer = add_peer(peer, peer_bucket, latency, distance);
1720 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1721 enable_next_bucket();
1723 schedule_ping_messages();
1730 * Task run to check for messages that need to be sent to a client.
1732 * @param client a ClientList, containing the client and any messages to be sent to it
1735 process_pending_messages (struct ClientList *client)
1737 if (client->pending_head == NULL)
1739 if (client->transmit_handle != NULL)
1741 client->transmit_handle =
1742 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1743 ntohs (client->pending_head->msg->
1745 GNUNET_TIME_UNIT_FOREVER_REL,
1746 &send_generic_reply, client);
1750 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1751 * request. A ClientList is passed as closure, take the head of the list
1752 * and copy it into buf, which has the result of sending the message to the
1755 * @param cls closure to this call
1756 * @param size maximum number of bytes available to send
1757 * @param buf where to copy the actual message to
1759 * @return the number of bytes actually copied, 0 indicates failure
1762 send_generic_reply (void *cls, size_t size, void *buf)
1764 struct ClientList *client = cls;
1766 struct PendingMessage *reply;
1770 client->transmit_handle = NULL;
1773 /* client disconnected */
1777 while ( (NULL != (reply = client->pending_head)) &&
1778 (size >= off + (msize = ntohs (reply->msg->size))))
1780 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1781 client->pending_tail,
1783 memcpy (&cbuf[off], reply->msg, msize);
1784 GNUNET_free (reply);
1787 process_pending_messages (client);
1793 * Add a PendingMessage to the clients list of messages to be sent
1795 * @param client the active client to send the message to
1796 * @param pending_message the actual message to send
1799 add_pending_message (struct ClientList *client,
1800 struct PendingMessage *pending_message)
1802 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1803 client->pending_tail,
1804 client->pending_tail,
1806 process_pending_messages (client);
1813 * Called when a reply needs to be sent to a client, as
1814 * a result it found to a GET or FIND PEER request.
1816 * @param client the client to send the reply to
1817 * @param message the encapsulated message to send
1818 * @param uid the unique identifier of this request
1821 send_reply_to_client (struct ClientList *client,
1822 const struct GNUNET_MessageHeader *message,
1823 unsigned long long uid)
1825 struct GNUNET_DHT_RouteResultMessage *reply;
1826 struct PendingMessage *pending_message;
1830 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1831 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1833 msize = ntohs (message->size);
1834 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1835 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1837 GNUNET_break_op (0);
1841 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1842 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1843 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1844 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1845 reply->header.size = htons (tsize);
1846 reply->unique_id = GNUNET_htonll (uid);
1847 memcpy (&reply[1], message, msize);
1849 add_pending_message (client, pending_message);
1853 * Consider whether or not we would like to have this peer added to
1854 * our routing table. Check whether bucket for this peer is full,
1855 * if so return negative; if not return positive. Since peers are
1856 * only added on CORE level connect, this doesn't actually add the
1857 * peer to the routing table.
1859 * @param peer the peer we are considering adding
1861 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1864 * FIXME: Think about making a context for this call so that we can
1865 * ping the oldest peer in the current bucket and consider
1866 * removing it in lieu of the new peer.
1868 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1872 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1873 return GNUNET_NO; /* We already know this peer (are connected even!) */
1874 bucket = find_current_bucket(&peer->hashPubKey);
1875 if (bucket == GNUNET_SYSERR)
1877 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1884 * Main function that handles whether or not to route a result
1885 * message to other peers, or to send to our local client.
1887 * @param cls closure (unused, always should be NULL)
1888 * @param msg the result message to be routed
1889 * @param message_context context of the message we are routing
1891 * @return the number of peers the message was routed to,
1892 * GNUNET_SYSERR on failure
1894 static int route_result_message(void *cls,
1895 struct GNUNET_MessageHeader *msg,
1896 struct DHT_MessageContext *message_context)
1898 struct GNUNET_PeerIdentity new_peer;
1899 struct DHTQueryRecord *record;
1900 struct DHTRouteSource *pos;
1901 struct PeerInfo *peer_info;
1902 const struct GNUNET_MessageHeader *hello_msg;
1904 increment_stats(STAT_RESULTS);
1906 * If a find peer result message is received and contains a valid
1907 * HELLO for another peer, offer it to the transport service.
1909 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1911 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1914 hello_msg = &msg[1];
1915 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1917 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1921 else /* We have a valid hello, and peer id stored in new_peer */
1923 find_peer_context.count++;
1924 increment_stats(STAT_FIND_PEER_REPLY);
1925 if (GNUNET_YES == consider_peer(&new_peer))
1927 increment_stats(STAT_HELLOS_PROVIDED);
1928 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1929 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_UNIT_FOREVER_REL, &new_peer, NULL, NULL);
1934 if (malicious_dropper == GNUNET_YES)
1937 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1939 if (record == NULL) /* No record of this message! */
1942 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1943 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1944 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1946 #if DEBUG_DHT_ROUTING
1948 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1950 dhtlog_handle->insert_route (NULL,
1951 message_context->unique_id,
1953 message_context->hop_count,
1956 &message_context->key,
1957 message_context->peer, NULL);
1960 if (message_context->bloom != NULL)
1962 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1963 message_context->bloom = NULL;
1971 #if STRICT_FORWARDING
1972 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
1974 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
1976 increment_stats("# find peer responses NOT forwarded (bloom match)");
1981 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
1985 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1988 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1989 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
1990 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1992 #if DEBUG_DHT_ROUTING
1993 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1995 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
1996 message_context->hop_count,
1997 GNUNET_YES, &my_identity, &message_context->key,
1998 message_context->peer, NULL);
2001 increment_stats(STAT_RESULTS_TO_CLIENT);
2002 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2003 increment_stats(STAT_GET_REPLY);
2005 send_reply_to_client(pos->client, msg, message_context->unique_id);
2007 else /* Send to peer */
2009 peer_info = find_peer_by_id(&pos->source);
2010 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2016 if (message_context->bloom == NULL)
2017 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2018 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2019 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2023 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2024 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2026 #if DEBUG_DHT_ROUTING
2027 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2029 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2031 message_context->hop_count,
2032 GNUNET_NO, &my_identity, &message_context->key,
2033 message_context->peer, &pos->source);
2036 forward_result_message(cls, msg, peer_info, message_context);
2041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2042 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2043 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2049 if (message_context->bloom != NULL)
2050 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2055 * Iterator for local get request results,
2057 * @param cls closure for iterator, a DatacacheGetContext
2058 * @param exp when does this value expire?
2059 * @param key the key this data is stored under
2060 * @param size the size of the data identified by key
2061 * @param data the actual data
2062 * @param type the type of the data
2064 * @return GNUNET_OK to continue iteration, anything else
2065 * to stop iteration.
2068 datacache_get_iterator (void *cls,
2069 struct GNUNET_TIME_Absolute exp,
2070 const GNUNET_HashCode * key,
2071 uint32_t size, const char *data, uint32_t type)
2073 struct DHT_MessageContext *msg_ctx = cls;
2074 struct DHT_MessageContext *new_msg_ctx;
2075 struct GNUNET_DHT_GetResultMessage *get_result;
2077 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2078 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2080 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2081 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2083 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2084 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2085 get_result->header.size =
2086 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2087 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2088 get_result->type = htons (type);
2089 memcpy (&get_result[1], data, size);
2090 new_msg_ctx->peer = &my_identity;
2091 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2092 new_msg_ctx->hop_count = 0;
2093 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2094 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2095 increment_stats(STAT_GET_RESPONSE_START);
2096 route_result_message(cls, &get_result->header, new_msg_ctx);
2097 GNUNET_free(new_msg_ctx);
2098 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2099 // datacache_get_ctx->unique_id);
2100 GNUNET_free (get_result);
2106 * Server handler for all dht get requests, look for data,
2107 * if found, send response either to clients or other peers.
2109 * @param cls closure for service
2110 * @param msg the actual get message
2111 * @param message_context struct containing pertinent information about the get request
2113 * @return number of items found for GET request
2116 handle_dht_get (void *cls,
2117 const struct GNUNET_MessageHeader *msg,
2118 struct DHT_MessageContext *message_context)
2120 const struct GNUNET_DHT_GetMessage *get_msg;
2122 unsigned int results;
2124 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2125 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2131 get_type = ntohs (get_msg->type);
2133 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2134 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2135 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2136 message_context->unique_id);
2138 increment_stats(STAT_GETS);
2140 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2143 if (datacache != NULL)
2145 GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2146 &datacache_get_iterator, message_context);
2151 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2152 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2153 results, "GET", message_context->unique_id);
2155 #if DEBUG_DHT_ROUTING
2156 if ((debug_routes) && (dhtlog_handle != NULL))
2158 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2159 message_context->hop_count, GNUNET_YES, &my_identity,
2160 &message_context->key);
2163 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2165 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2166 message_context->hop_count, GNUNET_YES,
2167 &my_identity, &message_context->key, message_context->peer,
2173 if (message_context->hop_count == 0) /* Locally initiated request */
2175 #if DEBUG_DHT_ROUTING
2176 if ((debug_routes) && (dhtlog_handle != NULL))
2178 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2179 message_context->hop_count, GNUNET_NO, &my_identity,
2180 &message_context->key);
2189 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2191 GNUNET_HashCode *key = cls;
2192 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2199 * Server handler for initiating local dht find peer requests
2201 * @param cls closure for service
2202 * @param find_msg the actual find peer message
2203 * @param message_context struct containing pertinent information about the request
2207 handle_dht_find_peer (void *cls,
2208 const struct GNUNET_MessageHeader *find_msg,
2209 struct DHT_MessageContext *message_context)
2211 struct GNUNET_MessageHeader *find_peer_result;
2212 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2213 struct DHT_MessageContext *new_msg_ctx;
2214 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2217 GNUNET_HashCode *recent_hash;
2218 #if RESTRICT_FIND_PEER
2219 struct GNUNET_PeerIdentity peer_id;
2222 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2224 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2225 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2226 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2227 ntohs (find_msg->size),
2228 sizeof (struct GNUNET_MessageHeader));
2230 if (my_hello == NULL)
2233 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2234 "`%s': Our HELLO is null, can't return.\n",
2240 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2241 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2243 increment_stats(STAT_BLOOM_FIND_PEER);
2244 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2245 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2247 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2249 #if RESTRICT_FIND_PEER
2252 * Ignore any find peer requests from a peer we have seen very recently.
2254 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! */
2256 increment_stats("# dht find peer requests ignored (recently seen!)");
2261 * Use this check to only allow the peer to respond to find peer requests if
2262 * it would be beneficial to have the requesting peer in this peers routing
2263 * table. Can be used to thwart peers flooding the network with find peer
2264 * requests that we don't care about. However, if a new peer is joining
2265 * the network and has no other peers this is a problem (assume all buckets
2266 * full, no one will respond!).
2268 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2269 if (GNUNET_NO == consider_peer(&peer_id))
2271 increment_stats("# dht find peer requests ignored (do not need!)");
2276 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2277 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2278 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2279 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2281 /* Simplistic find_peer functionality, always return our hello */
2282 hello_size = ntohs(my_hello->size);
2283 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2285 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2287 GNUNET_break_op (0);
2291 find_peer_result = GNUNET_malloc (tsize);
2292 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2293 find_peer_result->size = htons (tsize);
2294 memcpy (&find_peer_result[1], my_hello, hello_size);
2296 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2297 "`%s': Sending hello size %d to requesting peer.\n",
2300 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2301 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2302 new_msg_ctx->peer = &my_identity;
2303 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2304 new_msg_ctx->hop_count = 0;
2305 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2306 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2307 increment_stats(STAT_FIND_PEER_ANSWER);
2308 route_result_message(cls, find_peer_result, new_msg_ctx);
2309 GNUNET_free(new_msg_ctx);
2310 #if DEBUG_DHT_ROUTING
2311 if ((debug_routes) && (dhtlog_handle != NULL))
2313 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2314 message_context->hop_count, GNUNET_YES, &my_identity,
2315 &message_context->key);
2318 GNUNET_free(find_peer_result);
2322 * Task used to republish data.
2323 * Forward declaration; function call loop.
2325 * @param cls closure (a struct RepublishContext)
2326 * @param tc runtime context for this task
2329 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2332 * Server handler for initiating local dht put requests
2334 * @param cls closure for service
2335 * @param msg the actual put message
2336 * @param message_context struct containing pertinent information about the request
2339 handle_dht_put (void *cls,
2340 const struct GNUNET_MessageHeader *msg,
2341 struct DHT_MessageContext *message_context)
2343 struct GNUNET_DHT_PutMessage *put_msg;
2347 struct RepublishContext *put_context;
2349 GNUNET_assert (ntohs (msg->size) >=
2350 sizeof (struct GNUNET_DHT_PutMessage));
2353 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2354 put_type = ntohs (put_msg->type);
2356 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2359 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2361 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2362 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2363 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2365 #if DEBUG_DHT_ROUTING
2366 if (message_context->hop_count == 0) /* Locally initiated request */
2368 if ((debug_routes) && (dhtlog_handle != NULL))
2370 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2371 message_context->hop_count, GNUNET_NO, &my_identity,
2372 &message_context->key);
2377 if (message_context->closest != GNUNET_YES)
2380 #if DEBUG_DHT_ROUTING
2381 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2383 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2384 message_context->hop_count, GNUNET_YES,
2385 &my_identity, &message_context->key, message_context->peer,
2389 if ((debug_routes) && (dhtlog_handle != NULL))
2391 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2392 message_context->hop_count, GNUNET_YES, &my_identity,
2393 &message_context->key);
2397 increment_stats(STAT_PUTS_INSERTED);
2398 if (datacache != NULL)
2400 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2401 (char *) &put_msg[1], put_type,
2402 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2404 if (ret == GNUNET_YES)
2406 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2407 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2408 put_context->type = put_type;
2409 GNUNET_SCHEDULER_add_delayed (sched, DHT_REPUBLISH_FREQUENCY, &republish_content, put_context);
2413 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2414 "`%s:%s': %s request received, but have no datacache!\n",
2415 my_short_id, "DHT", "PUT");
2419 * Estimate the diameter of the network based
2420 * on how many buckets are currently in use.
2421 * Concept here is that the diameter of the network
2422 * is roughly the distance a message must travel in
2423 * order to reach its intended destination. Since
2424 * at each hop we expect to get one bit closer, and
2425 * we have one bit per bucket, the number of buckets
2426 * in use should be the largest number of hops for
2427 * a sucessful message. (of course, this assumes we
2428 * know all peers in the network!)
2430 * @return ballpark diameter figure
2432 static unsigned int estimate_diameter()
2434 return MAX_BUCKETS - lowest_bucket;
2438 * To how many peers should we (on average)
2439 * forward the request to obtain the desired
2440 * target_replication count (on average).
2442 * Always 0, 1 or 2 (don't send, send once, split)
2445 get_forward_count (unsigned int hop_count, size_t target_replication)
2448 double target_count;
2449 double random_probability;
2451 uint32_t random_value;
2453 unsigned int target_value;
2454 unsigned int diameter;
2457 * If we are behaving in strict kademlia mode, send multiple initial requests,
2458 * but then only send to 1 or 0 peers based strictly on the number of hops.
2460 if (strict_kademlia == GNUNET_YES)
2463 return DHT_KADEMLIA_REPLICATION;
2464 else if (hop_count < MAX_HOPS)
2470 /* FIXME: the smaller we think the network is the more lenient we should be for
2471 * routing right? The estimation below only works if we think we have reasonably
2472 * full routing tables, which for our RR topologies may not be the case!
2474 diameter = estimate_diameter ();
2475 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2478 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2479 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2480 "DHT", estimate_diameter(), lowest_bucket);
2484 else if (hop_count > MAX_HOPS)
2487 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2488 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2495 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2496 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2497 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2498 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2499 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2500 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2501 RAND_MAX)) / RAND_MAX;
2502 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2505 //while (target_value < target_count)
2506 if (target_value < target_count)
2507 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? */
2510 //if ((target_count + 1 - (double)target_value) > random_probability)
2511 if ((target_count) > random_probability)
2515 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2516 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));
2518 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2519 if (random_value < target_replication)
2522 return target_value;
2526 * Check whether my identity is closer than any known peers.
2527 * If a non-null bloomfilter is given, check if this is the closest
2528 * peer that hasn't already been routed to.
2530 * @param target hash code to check closeness to
2531 * @param bloom bloomfilter, exclude these entries from the decision
2533 * Return GNUNET_YES if node location is closest, GNUNET_NO
2537 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2543 struct PeerInfo *pos;
2544 unsigned int my_distance;
2546 bucket_num = find_current_bucket(target);
2547 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2550 bits = matching_bits(&my_identity.hashPubKey, target);
2551 my_distance = distance(&my_identity.hashPubKey, target);
2552 pos = k_buckets[bucket_num].head;
2554 while ((pos != NULL) && (count < bucket_size))
2556 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2559 continue; /* Skip already checked entries */
2562 other_bits = matching_bits(&pos->id.hashPubKey, target);
2563 if (other_bits > bits)
2565 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2567 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2569 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2576 GNUNET_GE_LOG (coreAPI->ectx,
2577 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2578 GNUNET_GE_BULK, "closest peer\n");
2579 printPeerBits (&closest);
2580 GNUNET_GE_LOG (coreAPI->ectx,
2581 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2582 GNUNET_GE_BULK, "me\n");
2583 printPeerBits (coreAPI->my_identity);
2584 GNUNET_GE_LOG (coreAPI->ectx,
2585 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2586 GNUNET_GE_BULK, "key\n");
2587 printKeyBits (target);
2588 GNUNET_GE_LOG (coreAPI->ectx,
2589 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2591 "closest peer inverse distance is %u, mine is %u\n",
2592 inverse_distance (target, &closest.hashPubKey),
2593 inverse_distance (target,
2594 &coreAPI->my_identity->hashPubKey));
2597 /* No peers closer, we are the closest! */
2603 * Decide whether to route this request exclusively
2604 * to a closer peer (if closer peers exist) or to choose
2605 * from the whole set of peers.
2607 * @param target the key of the request
2608 * @param bloom bloomfilter of peers this request has already traversed
2609 * @param hops number of hops this message has already traveled
2611 * @return GNUNET_YES if we should try to route to a closer peer
2612 * than ourselves (and one exists), GNUNET_NO if we should
2613 * choose from the set of all known peers
2617 route_closer (const GNUNET_HashCode *target,
2618 struct GNUNET_CONTAINER_BloomFilter *bloom,
2621 unsigned int my_matching_bits;
2623 uint32_t random_value;
2624 struct PeerInfo *pos;
2627 my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2630 * First check if we know any close (as close as us or closer) peers.
2632 have_closer = GNUNET_NO;
2634 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2636 pos = k_buckets[bc].head;
2638 while ((pos != NULL) && (count < bucket_size))
2640 if ((matching_bits(target, &pos->id.hashPubKey) > my_matching_bits) &&
2641 (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
2643 have_closer = GNUNET_YES;
2649 if (have_closer == GNUNET_YES)
2653 if (have_closer == GNUNET_NO) /* We don't have a same distance or closer node, can't enforce closer only! */
2656 switch (converge_option)
2658 case DHT_CONVERGE_LINEAR:
2660 * Simple linear curve for choosing whether or not to converge.
2661 * Choose to route only closer with probability hops/MAX_HOPS.
2663 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, MAX_HOPS);
2664 if (random_value < hops)
2668 case DHT_CONVERGE_SQUARE:
2670 * Simple square based curve.
2672 if ((GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1) / (double)(uint32_t)-1) < (sqrt(hops) / sqrt(MAX_HOPS)))
2682 * Select a peer from the routing table that would be a good routing
2683 * destination for sending a message for "target". The resulting peer
2684 * must not be in the set of blocked peers.<p>
2686 * Note that we should not ALWAYS select the closest peer to the
2687 * target, peers further away from the target should be chosen with
2688 * exponentially declining probability.
2690 * @param target the key we are selecting a peer to route to
2691 * @param bloom a bloomfilter containing entries this request has seen already
2692 * @param hops the number of hops this message has already traversed
2694 * @return Peer to route to, or NULL on error
2696 static struct PeerInfo *
2697 select_peer (const GNUNET_HashCode * target,
2698 struct GNUNET_CONTAINER_BloomFilter *bloom,
2701 unsigned int distance;
2704 unsigned int my_matching_bits;
2705 unsigned long long largest_distance;
2706 unsigned long long total_real_distance;
2707 unsigned long long real_selected;
2708 unsigned int total_distance;
2709 unsigned int selected;
2710 unsigned int match_num;
2712 struct PeerInfo *pos;
2713 struct PeerInfo *chosen;
2715 #if DEBUG_DHT_ROUTING
2719 my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2720 only_closer = route_closer(target, bloom, hops);
2722 if (GNUNET_YES == only_closer)
2724 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "only routing to closer peers!\n");
2725 GNUNET_asprintf(&temp_stat, "# closer only routes at hop %u", hops);
2726 increment_stats(temp_stat);
2730 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "routing to all possible peers!\n");
2731 GNUNET_asprintf(&temp_stat, "# NOT closer only routes at hop %u", hops);
2732 increment_stats(temp_stat);
2735 GNUNET_free(temp_stat);
2737 if (strict_kademlia == GNUNET_YES)
2739 largest_distance = 0;
2741 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2743 pos = k_buckets[bc].head;
2745 while ((pos != NULL) && (count < bucket_size))
2747 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2748 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2750 distance = inverse_distance (target, &pos->id.hashPubKey);
2751 if (distance > largest_distance)
2754 largest_distance = distance;
2762 if ((largest_distance > 0) && (chosen != NULL))
2764 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2776 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2778 pos = k_buckets[bc].head;
2780 while ((pos != NULL) && (count < bucket_size))
2782 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2783 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2785 if (GNUNET_YES == use_real_distance)
2786 total_real_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2789 /* Always add 1, in case 0 bits match! */
2790 match_num = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target ,&pos->id.hashPubKey));
2791 total_distance += match_num;
2795 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2796 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2797 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2804 if (((GNUNET_YES == use_real_distance) && (total_real_distance == 0)) || (total_distance == 0))
2806 increment_stats("# select_peer, total_distance == 0");
2810 #if DEBUG_DHT_ROUTING
2811 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2813 pos = k_buckets[bc].head;
2815 while ((pos != NULL) && (count < bucket_size))
2817 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2818 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2820 if (GNUNET_YES == use_real_distance)
2822 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);
2823 sum += inverse_distance (target, &pos->id.hashPubKey) / (double)total_real_distance;
2827 match_num = 1 + (matching_bits(&pos->id.hashPubKey, target) * matching_bits(&pos->id.hashPubKey, target));
2828 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);
2829 sum += match_num / (double)total_distance;
2836 fprintf(stdout, "Sum is %f\n", sum);
2839 real_selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_real_distance);
2840 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2842 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2844 pos = k_buckets[bc].head;
2846 while ((pos != NULL) && (count < bucket_size))
2848 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2849 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2851 if (GNUNET_YES == use_real_distance)
2853 distance = inverse_distance (target, &pos->id.hashPubKey);
2854 if (distance > real_selected)
2856 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Selected peer with %u matching bits to route to\n", distance);
2859 real_selected -= distance;
2863 distance = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target, &pos->id.hashPubKey));
2864 if (distance > selected)
2866 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Selected peer with %u matching bits to route to\n", distance);
2869 selected -= distance;
2875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2876 "`%s:%s': peer %s matches bloomfilter.\n",
2877 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2886 "`%s:%s': peer %s matches bloomfilter.\n",
2887 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2889 increment_stats("# failed to select peer");
2890 GNUNET_assert(only_closer == GNUNET_NO);
2896 * Task used to remove recent entries, either
2897 * after timeout, when full, or on shutdown.
2899 * @param cls the entry to remove
2900 * @param tc context, reason, etc.
2903 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2905 struct RecentRequest *req = cls;
2906 static GNUNET_HashCode hash;
2908 GNUNET_assert(req != NULL);
2909 hash_from_uid(req->uid, &hash);
2910 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
2911 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
2912 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
2915 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
2917 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
2918 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
2924 * Task used to remove forwarding entries, either
2925 * after timeout, when full, or on shutdown.
2927 * @param cls the entry to remove
2928 * @param tc context, reason, etc.
2931 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2933 struct DHTRouteSource *source_info = cls;
2934 struct DHTQueryRecord *record;
2935 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2936 record = source_info->record;
2937 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2939 if (record->head == NULL) /* No more entries in DLL */
2941 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2942 GNUNET_free(record);
2944 if (source_info->find_peers_responded != NULL)
2945 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
2946 GNUNET_free(source_info);
2950 * Remember this routing request so that if a reply is
2951 * received we can either forward it to the correct peer
2952 * or return the result locally.
2954 * @param cls DHT service closure
2955 * @param msg_ctx Context of the route request
2957 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2959 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2961 struct DHTQueryRecord *record;
2962 struct DHTRouteSource *source_info;
2963 struct DHTRouteSource *pos;
2964 struct GNUNET_TIME_Absolute now;
2965 unsigned int current_size;
2967 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2968 while (current_size >= MAX_OUTSTANDING_FORWARDS)
2970 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2971 GNUNET_assert(source_info != NULL);
2972 record = source_info->record;
2973 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2974 if (record->head == NULL) /* No more entries in DLL */
2976 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2977 GNUNET_free(record);
2979 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2980 if (source_info->find_peers_responded != NULL)
2981 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
2982 GNUNET_free(source_info);
2983 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2985 now = GNUNET_TIME_absolute_get();
2986 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2987 if (record != NULL) /* Already know this request! */
2992 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
2993 break; /* Already have this peer in reply list! */
2996 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
2998 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3004 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3005 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3006 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3009 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3010 source_info->record = record;
3011 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3012 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3013 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3014 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3015 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3017 source_info->client = msg_ctx->client;
3018 now = GNUNET_TIME_absolute_get_forever();
3020 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3023 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3024 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
3031 * Main function that handles whether or not to route a message to other
3034 * @param cls closure for dht service (NULL)
3035 * @param msg the message to be routed
3036 * @param message_context the context containing all pertinent information about the message
3038 * @return the number of peers the message was routed to,
3039 * GNUNET_SYSERR on failure
3041 static int route_message(void *cls,
3042 const struct GNUNET_MessageHeader *msg,
3043 struct DHT_MessageContext *message_context)
3047 struct PeerInfo *selected;
3048 #if DEBUG_DHT_ROUTING > 1
3049 struct PeerInfo *nearest;
3051 unsigned int forward_count;
3052 struct RecentRequest *recent_req;
3053 GNUNET_HashCode unique_hash;
3054 char *stat_forward_count;
3055 #if DEBUG_DHT_ROUTING
3059 if (malicious_dropper == GNUNET_YES)
3061 #if DEBUG_DHT_ROUTING
3062 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3064 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3065 message_context->hop_count, GNUNET_SYSERR,
3066 &my_identity, &message_context->key, message_context->peer,
3070 if (message_context->bloom != NULL)
3071 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3075 increment_stats(STAT_ROUTES);
3076 /* Semantics of this call means we find whether we are the closest peer out of those already
3077 * routed to on this messages path.
3079 global_closest = am_closest_peer(&message_context->key, NULL);
3080 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3081 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3082 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3083 increment_stats(stat_forward_count);
3084 GNUNET_free(stat_forward_count);
3085 if (message_context->bloom == NULL)
3086 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3088 if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3091 #if DEBUG_DHT_ROUTING
3092 if (forward_count == 0)
3093 ret = GNUNET_SYSERR;
3097 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3099 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3100 message_context->hop_count, ret,
3101 &my_identity, &message_context->key, message_context->peer,
3106 switch (ntohs(msg->type))
3108 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3109 cache_response (cls, message_context);
3110 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3113 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3114 increment_stats(STAT_PUTS);
3115 message_context->closest = global_closest;
3116 handle_dht_put (cls, msg, message_context);
3118 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3119 increment_stats(STAT_FIND_PEER);
3120 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3122 cache_response (cls, message_context);
3123 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3124 handle_dht_find_peer (cls, msg, message_context);
3126 #if DEBUG_DHT_ROUTING
3127 if (message_context->hop_count == 0) /* Locally initiated request */
3129 if ((debug_routes) && (dhtlog_handle != NULL))
3131 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3132 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3133 message_context->hop_count, GNUNET_NO, &my_identity,
3134 &message_context->key);
3140 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3141 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3144 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3145 hash_from_uid(message_context->unique_id, &unique_hash);
3146 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent.hashmap, &unique_hash))
3148 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3149 GNUNET_assert(recent_req != NULL);
3150 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3151 increment_stats(STAT_DUPLICATE_UID);
3154 increment_stats(STAT_RECENT_SEEN);
3155 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3160 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3161 recent_req->uid = message_context->unique_id;
3162 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3163 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3164 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3165 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3166 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3169 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3171 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3172 GNUNET_assert(recent_req != NULL);
3173 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3174 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3177 for (i = 0; i < forward_count; i++)
3179 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3181 if (selected != NULL)
3183 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3184 #if DEBUG_DHT_ROUTING > 1
3185 nearest = find_closest_peer(&message_context->key);
3186 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3187 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3188 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3189 "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));
3190 GNUNET_free(nearest_buf);
3192 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3194 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3195 message_context->hop_count, GNUNET_NO,
3196 &my_identity, &message_context->key, message_context->peer,
3199 forward_message(cls, msg, selected, message_context);
3203 increment_stats("# NULL returned from select_peer");
3204 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3205 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
3210 #if DEBUG_DHT_ROUTING > 1
3211 if (forward_count == 0)
3213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3214 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
3215 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
3219 if (message_context->bloom != NULL)
3221 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3222 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3225 return forward_count;
3229 * Iterator for local get request results,
3231 * @param cls closure for iterator, NULL
3232 * @param exp when does this value expire?
3233 * @param key the key this data is stored under
3234 * @param size the size of the data identified by key
3235 * @param data the actual data
3236 * @param type the type of the data
3238 * @return GNUNET_OK to continue iteration, anything else
3239 * to stop iteration.
3242 republish_content_iterator (void *cls,
3243 struct GNUNET_TIME_Absolute exp,
3244 const GNUNET_HashCode * key,
3245 uint32_t size, const char *data, uint32_t type)
3248 struct DHT_MessageContext *new_msg_ctx;
3249 struct GNUNET_DHT_PutMessage *put_msg;
3251 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3252 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3254 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3257 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3258 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3259 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3260 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3261 put_msg->type = htons (type);
3262 memcpy (&put_msg[1], data, size);
3263 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3264 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3265 new_msg_ctx->msg_options = ntohl (0);
3266 new_msg_ctx->network_size = estimate_diameter();
3267 new_msg_ctx->peer = &my_identity;
3268 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3269 new_msg_ctx->hop_count = 0;
3270 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3271 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3272 increment_stats(STAT_PUT_START);
3273 route_message(cls, &put_msg->header, new_msg_ctx);
3275 GNUNET_free(new_msg_ctx);
3276 GNUNET_free (put_msg);
3281 * Task used to republish data.
3283 * @param cls closure (a struct RepublishContext)
3284 * @param tc runtime context for this task
3287 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3289 struct RepublishContext *put_context = cls;
3291 unsigned int results;
3293 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3295 GNUNET_free(put_context);
3299 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3300 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3301 if (results == 0) /* Data must have expired */
3302 GNUNET_free(put_context);
3303 else /* Reschedule task for next time period */
3304 GNUNET_SCHEDULER_add_delayed(sched, DHT_REPUBLISH_FREQUENCY, &republish_content, put_context);
3309 * Find a client if it exists, add it otherwise.
3311 * @param client the server handle to the client
3313 * @return the client if found, a new client otherwise
3315 static struct ClientList *
3316 find_active_client (struct GNUNET_SERVER_Client *client)
3318 struct ClientList *pos = client_list;
3319 struct ClientList *ret;
3323 if (pos->client_handle == client)
3328 ret = GNUNET_malloc (sizeof (struct ClientList));
3329 ret->client_handle = client;
3330 ret->next = client_list;
3336 * Task to send a malicious put message across the network.
3338 * @param cls closure for this task
3339 * @param tc the context under which the task is running
3342 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3344 static struct GNUNET_DHT_PutMessage put_message;
3345 static struct DHT_MessageContext message_context;
3346 static GNUNET_HashCode key;
3347 uint32_t random_key;
3349 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3352 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3353 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3354 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3355 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3356 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3357 message_context.client = NULL;
3358 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3359 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3360 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3361 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3362 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3363 message_context.msg_options = ntohl (0);
3364 message_context.network_size = estimate_diameter();
3365 message_context.peer = &my_identity;
3366 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3367 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3368 if (dhtlog_handle != NULL)
3369 dhtlog_handle->insert_dhtkey(NULL, &key);
3370 increment_stats(STAT_PUT_START);
3371 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3372 route_message(NULL, &put_message.header, &message_context);
3373 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3378 * Task to send a malicious put message across the network.
3380 * @param cls closure for this task
3381 * @param tc the context under which the task is running
3384 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3386 static struct GNUNET_DHT_GetMessage get_message;
3387 struct DHT_MessageContext message_context;
3388 static GNUNET_HashCode key;
3389 uint32_t random_key;
3391 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3394 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3395 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3396 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3397 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3398 message_context.client = NULL;
3399 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3400 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3401 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3402 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3403 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3404 message_context.msg_options = ntohl (0);
3405 message_context.network_size = estimate_diameter();
3406 message_context.peer = &my_identity;
3407 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3408 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3409 if (dhtlog_handle != NULL)
3410 dhtlog_handle->insert_dhtkey(NULL, &key);
3411 increment_stats(STAT_GET_START);
3412 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3413 route_message (NULL, &get_message.header, &message_context);
3414 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3418 * Iterator over hash map entries.
3420 * @param cls closure
3421 * @param key current key code
3422 * @param value value in the hash map
3423 * @return GNUNET_YES if we should continue to
3428 add_known_to_bloom (void *cls,
3429 const GNUNET_HashCode * key,
3432 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3433 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3438 * Task to send a find peer message for our own peer identifier
3439 * so that we can find the closest peers in the network to ourselves
3440 * and attempt to connect to them.
3442 * @param cls closure for this task
3443 * @param tc the context under which the task is running
3446 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3448 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3449 struct DHT_MessageContext message_context;
3451 struct GNUNET_TIME_Relative next_send_time;
3452 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3454 struct GNUNET_TIME_Relative time_diff;
3455 struct GNUNET_TIME_Absolute end;
3457 double count_per_interval;
3459 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3462 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! */
3464 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3465 GNUNET_SCHEDULER_add_delayed (sched,
3466 GNUNET_TIME_UNIT_MINUTES,
3467 &send_find_peer_message, NULL);
3468 newly_found_peers = 0;
3472 increment_stats(STAT_FIND_PEER_START);
3474 end = GNUNET_TIME_absolute_get();
3475 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3477 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3479 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3480 count_per_interval = find_peer_context.count / multiplier;
3484 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3485 count_per_interval = find_peer_context.count * multiplier;
3489 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3490 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3491 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3492 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3493 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3494 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3495 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3496 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3497 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3498 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3499 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3500 message_context.network_size = estimate_diameter();
3501 message_context.peer = &my_identity;
3502 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3503 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3505 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3506 GNUNET_free(find_peer_msg);
3507 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3508 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3510 if (newly_found_peers < bucket_size)
3512 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3513 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3514 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3518 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3519 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3520 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3523 GNUNET_assert (next_send_time.value != 0);
3524 find_peer_context.count = 0;
3525 newly_found_peers = 0;
3526 find_peer_context.start = GNUNET_TIME_absolute_get();
3527 if (GNUNET_YES == do_find_peer)
3529 GNUNET_SCHEDULER_add_delayed (sched,
3531 &send_find_peer_message, NULL);
3536 * Handler for any generic DHT messages, calls the appropriate handler
3537 * depending on message type, sends confirmation if responses aren't otherwise
3540 * @param cls closure for the service
3541 * @param client the client we received this message from
3542 * @param message the actual message received
3545 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3546 const struct GNUNET_MessageHeader *message)
3548 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3549 const struct GNUNET_MessageHeader *enc_msg;
3550 struct DHT_MessageContext message_context;
3551 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3553 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3554 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3555 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3556 GNUNET_ntohll (dht_msg->unique_id));
3558 #if DEBUG_DHT_ROUTING
3559 if (dhtlog_handle != NULL)
3560 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3562 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3563 message_context.client = find_active_client (client);
3564 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3565 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3566 message_context.replication = ntohl (dht_msg->desired_replication_level);
3567 message_context.msg_options = ntohl (dht_msg->options);
3568 message_context.network_size = estimate_diameter();
3569 message_context.peer = &my_identity;
3570 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3571 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3572 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3573 increment_stats(STAT_GET_START);
3574 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3575 increment_stats(STAT_PUT_START);
3576 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3577 increment_stats(STAT_FIND_PEER_START);
3579 route_message(cls, enc_msg, &message_context);
3581 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3586 * Handler for any locally received DHT control messages,
3587 * sets malicious flags mostly for now.
3589 * @param cls closure for the service
3590 * @param client the client we received this message from
3591 * @param message the actual message received
3595 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3596 const struct GNUNET_MessageHeader *message)
3598 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3599 (const struct GNUNET_DHT_ControlMessage *) message;
3601 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3602 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3603 "CONTROL", ntohs(dht_control_msg->command));
3606 switch (ntohs(dht_control_msg->command))
3608 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3609 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3610 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3612 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3613 if (ntohs(dht_control_msg->variable) > 0)
3614 malicious_get_frequency = ntohs(dht_control_msg->variable);
3615 if (malicious_get_frequency == 0)
3616 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3617 if (malicious_getter != GNUNET_YES)
3618 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3619 malicious_getter = GNUNET_YES;
3620 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3622 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3623 if (ntohs(dht_control_msg->variable) > 0)
3624 malicious_put_frequency = ntohs(dht_control_msg->variable);
3625 if (malicious_put_frequency == 0)
3626 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3627 if (malicious_putter != GNUNET_YES)
3628 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3629 malicious_putter = GNUNET_YES;
3630 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3632 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3633 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3634 dhtlog_handle->set_malicious(&my_identity);
3635 malicious_dropper = GNUNET_YES;
3636 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3639 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3642 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3646 * Handler for any generic DHT stop messages, calls the appropriate handler
3647 * depending on message type (if processed locally)
3649 * @param cls closure for the service
3650 * @param client the client we received this message from
3651 * @param message the actual message received
3655 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3656 const struct GNUNET_MessageHeader *message)
3659 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3660 (const struct GNUNET_DHT_StopMessage *) message;
3661 struct DHTQueryRecord *record;
3662 struct DHTRouteSource *pos;
3664 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3665 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3666 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3668 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3675 if ((pos->client != NULL) && (pos->client->client_handle == client))
3677 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3678 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3684 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3689 * Core handler for p2p route requests.
3692 handle_dht_p2p_route_request (void *cls,
3693 const struct GNUNET_PeerIdentity *peer,
3694 const struct GNUNET_MessageHeader *message,
3695 struct GNUNET_TIME_Relative latency, uint32_t distance)
3698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3699 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3701 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3702 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3703 struct DHT_MessageContext *message_context;
3705 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
3707 fprintf(stderr, "Sending of previous replies took far too long, backing off!\n");
3708 decrease_max_send_delay(get_max_send_delay());
3712 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3715 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3720 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3725 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3726 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3727 GNUNET_assert(message_context->bloom != NULL);
3728 message_context->hop_count = ntohl(incoming->hop_count);
3729 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
3730 message_context->replication = ntohl(incoming->desired_replication_level);
3731 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3732 message_context->msg_options = ntohl(incoming->options);
3733 message_context->network_size = ntohl(incoming->network_size);
3734 message_context->peer = peer;
3735 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3736 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3737 route_message(cls, enc_msg, message_context);
3738 GNUNET_free(message_context);
3744 * Core handler for p2p route results.
3747 handle_dht_p2p_route_result (void *cls,
3748 const struct GNUNET_PeerIdentity *peer,
3749 const struct GNUNET_MessageHeader *message,
3750 struct GNUNET_TIME_Relative latency, uint32_t distance)
3753 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3754 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3756 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3757 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3758 struct DHT_MessageContext message_context;
3760 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3766 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3767 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3768 GNUNET_assert(message_context.bloom != NULL);
3769 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
3770 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3771 message_context.msg_options = ntohl(incoming->options);
3772 message_context.hop_count = ntohl(incoming->hop_count);
3773 message_context.peer = peer;
3774 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3775 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3776 route_result_message(cls, enc_msg, &message_context);
3782 * Receive the HELLO from transport service,
3783 * free current and replace if necessary.
3786 * @param message HELLO message of peer
3789 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3792 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3793 "Received our `%s' from transport service\n",
3797 GNUNET_assert (message != NULL);
3798 GNUNET_free_non_null(my_hello);
3799 my_hello = GNUNET_malloc(ntohs(message->size));
3800 memcpy(my_hello, message, ntohs(message->size));
3805 * Task run during shutdown.
3811 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3814 struct PeerInfo *pos;
3815 if (transport_handle != NULL)
3817 GNUNET_free_non_null(my_hello);
3818 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3819 GNUNET_TRANSPORT_disconnect(transport_handle);
3822 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3824 while (k_buckets[bucket_count].head != NULL)
3826 pos = k_buckets[bucket_count].head;
3828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3829 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3831 delete_peer(pos, bucket_count);
3834 if (coreAPI != NULL)
3837 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3838 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3840 GNUNET_CORE_disconnect (coreAPI);
3842 if (datacache != NULL)
3845 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3846 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3848 GNUNET_DATACACHE_destroy (datacache);
3853 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3856 if (dhtlog_handle != NULL)
3857 GNUNET_DHTLOG_disconnect(dhtlog_handle);
3859 GNUNET_free_non_null(my_short_id);
3864 * To be called on core init/fail.
3866 * @param cls service closure
3867 * @param server handle to the server for this service
3868 * @param identity the public identity of this peer
3869 * @param publicKey the public key of this peer
3872 core_init (void *cls,
3873 struct GNUNET_CORE_Handle *server,
3874 const struct GNUNET_PeerIdentity *identity,
3875 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3882 "%s: Connection to core FAILED!\n", "dht",
3883 GNUNET_i2s (identity));
3885 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
3886 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3891 "%s: Core connection initialized, I am peer: %s\n", "dht",
3892 GNUNET_i2s (identity));
3895 /* Copy our identity so we can use it */
3896 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3897 if (my_short_id != NULL)
3898 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3899 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3900 /* Set the server to local variable */
3903 if (dhtlog_handle != NULL)
3904 dhtlog_handle->insert_node (NULL, &my_identity);
3908 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3909 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3910 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3911 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
3916 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3917 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
3918 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
3923 * Method called whenever a peer connects.
3925 * @param cls closure
3926 * @param peer peer identity this notification is about
3927 * @param latency reported latency of the connection with peer
3928 * @param distance reported distance (DV) to peer
3930 void handle_core_connect (void *cls,
3931 const struct GNUNET_PeerIdentity * peer,
3932 struct GNUNET_TIME_Relative latency,
3935 struct PeerInfo *ret;
3938 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3939 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
3942 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3944 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));
3948 if (datacache != NULL)
3949 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
3950 ret = try_add_peer(peer,
3951 find_current_bucket(&peer->hashPubKey),
3956 newly_found_peers++;
3957 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3960 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3961 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
3966 * Method called whenever a peer disconnects.
3968 * @param cls closure
3969 * @param peer peer identity this notification is about
3971 void handle_core_disconnect (void *cls,
3973 GNUNET_PeerIdentity * peer)
3975 struct PeerInfo *to_remove;
3978 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");
3980 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3982 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));
3985 increment_stats(STAT_DISCONNECTS);
3986 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
3987 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
3988 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
3989 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
3990 delete_peer(to_remove, current_bucket);
3994 * Process dht requests.
3996 * @param cls closure
3997 * @param scheduler scheduler to use
3998 * @param server the initialized server
3999 * @param c configuration to use
4003 struct GNUNET_SCHEDULER_Handle *scheduler,
4004 struct GNUNET_SERVER_Handle *server,
4005 const struct GNUNET_CONFIGURATION_Handle *c)
4008 struct GNUNET_TIME_Relative next_send_time;
4012 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4013 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4014 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4015 cfg, /* Main configuration */
4016 GNUNET_TIME_UNIT_FOREVER_REL,
4017 NULL, /* Closure passed to DHT functions */
4018 &core_init, /* Call core_init once connected */
4019 &handle_core_connect, /* Handle connects */
4020 &handle_core_disconnect, /* remove peers on disconnects */
4021 NULL, /* Do we care about "status" updates? */
4022 NULL, /* Don't want notified about all incoming messages */
4023 GNUNET_NO, /* For header only inbound notification */
4024 NULL, /* Don't want notified about all outbound messages */
4025 GNUNET_NO, /* For header only outbound notification */
4026 core_handlers); /* Register these handlers */
4028 if (coreAPI == NULL)
4030 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
4031 NULL, NULL, NULL, NULL, NULL);
4032 if (transport_handle != NULL)
4033 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4035 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4037 lowest_bucket = MAX_BUCKETS - 1;
4038 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4039 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4040 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4041 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4042 GNUNET_assert(all_known_peers != NULL);
4043 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4045 debug_routes = GNUNET_YES;
4049 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4052 strict_kademlia = GNUNET_YES;
4056 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4059 stop_on_closest = GNUNET_YES;
4063 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4066 stop_on_found = GNUNET_YES;
4070 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4071 "malicious_getter"))
4073 malicious_getter = GNUNET_YES;
4074 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4075 "MALICIOUS_GET_FREQUENCY",
4076 &malicious_get_frequency))
4077 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4081 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4082 "malicious_putter"))
4084 malicious_putter = GNUNET_YES;
4085 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4086 "MALICIOUS_PUT_FREQUENCY",
4087 &malicious_put_frequency))
4088 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4092 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4093 "malicious_dropper"))
4095 malicious_dropper = GNUNET_YES;
4099 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4102 do_find_peer = GNUNET_NO;
4105 do_find_peer = GNUNET_YES;
4108 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4109 "use_real_distance"))
4110 use_real_distance = GNUNET_YES;
4113 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4114 "mysql_logging_extended"))
4116 debug_routes = GNUNET_YES;
4117 debug_routes_extended = GNUNET_YES;
4120 if (GNUNET_YES == debug_routes)
4122 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4123 if (dhtlog_handle == NULL)
4125 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4126 "Could not connect to mysql logging server, logging will not happen!");
4130 converge_option = DHT_CONVERGE_SQUARE;
4132 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4135 converge_option = DHT_CONVERGE_LINEAR;
4138 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4142 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4143 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4144 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4145 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4146 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4147 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4148 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4149 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4150 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4151 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4152 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4153 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4154 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4155 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4156 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4157 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4158 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4159 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4160 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4161 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4163 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4164 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4165 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4166 if (GNUNET_YES == do_find_peer)
4168 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4169 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4170 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4171 find_peer_context.start = GNUNET_TIME_absolute_get();
4172 GNUNET_SCHEDULER_add_delayed (sched,
4174 &send_find_peer_message, &find_peer_context);
4177 /* Scheduled the task to clean up when shutdown is called */
4178 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4179 GNUNET_TIME_UNIT_FOREVER_REL,
4180 &shutdown_task, NULL);
4184 * The main function for the dht service.
4186 * @param argc number of arguments from the command line
4187 * @param argv command line arguments
4188 * @return 0 ok, 1 on error
4191 main (int argc, char *const *argv)
4193 return (GNUNET_OK ==
4194 GNUNET_SERVICE_run (argc,
4197 GNUNET_SERVICE_OPTION_NONE,
4198 &run, NULL)) ? 0 : 1;