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_YES
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_FIND_PEER_REPLICATION 4
107 * Default options for find peer requests sent by the dht service.
109 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
110 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
113 * How long at least to wait before sending another find peer request.
115 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
118 * How long at most to wait before sending another find peer request.
120 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
123 * How often to update our preference levels for peers in our routing tables.
125 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
128 * How long at most on average will we allow a reply forward to take
129 * (before we quit sending out new requests)
131 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
134 * How many initial requests to send out (in true Kademlia fashion)
136 #define DHT_KADEMLIA_REPLICATION 3
139 * Default frequency for sending malicious get messages
141 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
144 * Default frequency for sending malicious put messages
146 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
149 * Type for a malicious request, so we can ignore it during testing
151 #define DHT_MALICIOUS_MESSAGE_TYPE 42
153 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
156 * Real maximum number of hops, at which point we refuse
157 * to forward the message.
162 * How many time differences between requesting a core send and
163 * the actual callback to remember.
165 #define MAX_REPLY_TIMES 8
167 enum ConvergenceOptions
170 * Use the linear method for convergence.
175 * Converge using a fast converging square
181 * Converge using a slower exponential
184 DHT_CONVERGE_EXPONENTIAL,
187 * Don't do any special convergence, allow
188 * the algorithm to hopefully route to closer
195 * Linked list of messages to send to clients.
197 struct P2PPendingMessage
200 * Pointer to next item in the list
202 struct P2PPendingMessage *next;
205 * Pointer to previous item in the list
207 struct P2PPendingMessage *prev;
210 * Message importance level.
212 unsigned int importance;
215 * Time when this request was scheduled to be sent.
217 struct GNUNET_TIME_Absolute scheduled;
220 * How long to wait before sending message.
222 struct GNUNET_TIME_Relative timeout;
225 * Actual message to be sent; // avoid allocation
227 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
232 * Per-peer information.
237 * Next peer entry (DLL)
239 struct PeerInfo *next;
242 * Prev peer entry (DLL)
244 struct PeerInfo *prev;
247 * Head of pending messages to be sent to this peer.
249 struct P2PPendingMessage *head;
252 * Tail of pending messages to be sent to this peer.
254 struct P2PPendingMessage *tail;
257 * Core handle for sending messages to this peer.
259 struct GNUNET_CORE_TransmitHandle *th;
262 * Task for scheduling message sends.
264 GNUNET_SCHEDULER_TaskIdentifier send_task;
267 * Task for scheduling preference updates
269 GNUNET_SCHEDULER_TaskIdentifier preference_task;
272 * Preference update context
274 struct GNUNET_CORE_InformationRequestContext *info_ctx;
277 * What is the average latency for replies received?
279 struct GNUNET_TIME_Relative latency;
282 * What is the identity of the peer?
284 struct GNUNET_PeerIdentity id;
287 * Transport level distance to peer.
289 unsigned int distance;
292 * Task for scheduling periodic ping messages for this peer.
294 GNUNET_SCHEDULER_TaskIdentifier ping_task;
298 * Peers are grouped into buckets.
305 struct PeerInfo *head;
310 struct PeerInfo *tail;
313 * Number of peers in the bucket.
315 unsigned int peers_size;
319 * Linked list of messages to send to clients.
321 struct PendingMessage
324 * Pointer to next item in the list
326 struct PendingMessage *next;
329 * Pointer to previous item in the list
331 struct PendingMessage *prev;
334 * Actual message to be sent; // avoid allocation
336 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
341 * Struct containing information about a client,
342 * handle to connect to it, and any pending messages
343 * that need to be sent to it.
348 * Linked list of active clients
350 struct ClientList *next;
353 * The handle to this client
355 struct GNUNET_SERVER_Client *client_handle;
358 * Handle to the current transmission request, NULL
361 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
364 * Linked list of pending messages for this client
366 struct PendingMessage *pending_head;
369 * Tail of linked list of pending messages for this client
371 struct PendingMessage *pending_tail;
376 * Context containing information about a DHT message received.
378 struct DHT_MessageContext
381 * The client this request was received from.
382 * (NULL if received from another peer)
384 struct ClientList *client;
387 * The peer this request was received from.
388 * (NULL if received from local client)
390 const struct GNUNET_PeerIdentity *peer;
393 * The key this request was about
398 * The unique identifier of this request
403 * Desired replication level
405 uint32_t replication;
408 * Network size estimate, either ours or the sum of
409 * those routed to thus far. =~ Log of number of peers
410 * chosen from for this request.
412 uint32_t network_size;
415 * Any message options for this request
417 uint32_t msg_options;
420 * How many hops has the message already traversed?
425 * How important is this message?
427 unsigned int importance;
430 * How long should we wait to transmit this request?
432 struct GNUNET_TIME_Relative timeout;
435 * Bloomfilter for this routing request.
437 struct GNUNET_CONTAINER_BloomFilter *bloom;
440 * Did we forward this message? (may need to remember it!)
445 * Are we the closest known peer to this key (out of our neighbors?)
451 * Record used for remembering what peers are waiting for what
452 * responses (based on search key).
454 struct DHTRouteSource
459 struct DHTRouteSource *next;
464 struct DHTRouteSource *prev;
467 * Source of the request. Replies should be forwarded to
470 struct GNUNET_PeerIdentity source;
473 * If this was a local request, remember the client; otherwise NULL.
475 struct ClientList *client;
478 * Pointer to this nodes heap location (for removal)
480 struct GNUNET_CONTAINER_HeapNode *hnode;
483 * Back pointer to the record storing this information.
485 struct DHTQueryRecord *record;
488 * Task to remove this entry on timeout.
490 GNUNET_SCHEDULER_TaskIdentifier delete_task;
493 * Bloomfilter of peers we have already sent back as
494 * replies to the initial request. Allows us to not
495 * forward the same peer multiple times for a find peer
498 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
503 * Entry in the DHT routing table.
505 struct DHTQueryRecord
508 * Head of DLL for result forwarding.
510 struct DHTRouteSource *head;
513 * Tail of DLL for result forwarding.
515 struct DHTRouteSource *tail;
518 * Key that the record concerns.
523 * GET message of this record (what we already forwarded?).
525 //DV_DHT_MESSAGE get; Try to get away with not saving this.
528 * Bloomfilter of the peers we've replied to so far
530 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
535 * Context used to calculate the number of find peer messages
536 * per X time units since our last scheduled find peer message
537 * was sent. If we have seen too many messages, delay or don't
540 struct FindPeerMessageContext
544 struct GNUNET_TIME_Absolute start;
546 struct GNUNET_TIME_Absolute end;
550 * DHT Routing results structure
555 * Min heap for removal upon reaching limit
557 struct GNUNET_CONTAINER_Heap *minHeap;
560 * Hashmap for fast key based lookup
562 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
567 * DHT structure for recent requests.
569 struct RecentRequests
572 * Min heap for removal upon reaching limit
574 struct GNUNET_CONTAINER_Heap *minHeap;
577 * Hashmap for key based lookup
579 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
585 * Position of this node in the min heap.
587 struct GNUNET_CONTAINER_HeapNode *heap_node;
590 * Bloomfilter containing entries for peers
591 * we forwarded this request to.
593 struct GNUNET_CONTAINER_BloomFilter *bloom;
596 * Timestamp of this request, for ordering
599 struct GNUNET_TIME_Absolute timestamp;
602 * Key of this request.
607 * Unique identifier for this request.
612 * Task to remove this entry on timeout.
614 GNUNET_SCHEDULER_TaskIdentifier remove_task;
618 * Which kind of convergence will we be using?
620 enum ConvergenceOptions converge_option;
623 * Recent requests by hash/uid and by time inserted.
625 static struct RecentRequests recent;
628 * Context to use to calculate find peer rates.
630 static struct FindPeerMessageContext find_peer_context;
633 * Don't use our routing algorithm, always route
634 * to closest peer; initially send requests to 3
637 static int strict_kademlia;
640 * Routing option to end routing when closest peer found.
642 static int stop_on_closest;
645 * Routing option to end routing when data is found.
647 static int stop_on_found;
650 * Whether DHT needs to manage find peer requests, or
651 * an external force will do it on behalf of the DHT.
653 static int do_find_peer;
656 * How many peers have we added since we sent out our last
659 static unsigned int newly_found_peers;
662 * Container of active queries we should remember
664 static struct DHTResults forward_list;
667 * Handle to the datacache service (for inserting/retrieving data)
669 static struct GNUNET_DATACACHE_Handle *datacache;
672 * Handle for the statistics service.
674 struct GNUNET_STATISTICS_Handle *stats;
677 * The main scheduler to use for the DHT service
679 static struct GNUNET_SCHEDULER_Handle *sched;
682 * The configuration the DHT service is running with
684 static const struct GNUNET_CONFIGURATION_Handle *cfg;
687 * Handle to the core service
689 static struct GNUNET_CORE_Handle *coreAPI;
692 * Handle to the transport service, for getting our hello
694 static struct GNUNET_TRANSPORT_Handle *transport_handle;
697 * The identity of our peer.
699 static struct GNUNET_PeerIdentity my_identity;
702 * Short id of the peer, for printing
704 static char *my_short_id;
709 static struct GNUNET_MessageHeader *my_hello;
712 * Task to run when we shut down, cleaning up all our trash
714 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
717 * The lowest currently used bucket.
719 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
722 * The buckets (Kademlia routing table, complete with growth).
723 * Array of size MAX_BUCKET_SIZE.
725 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
728 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
730 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
733 * Recently seen find peer requests.
735 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
738 * Maximum size for each bucket.
740 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
743 * List of active clients.
745 static struct ClientList *client_list;
748 * Handle to the DHT logger.
750 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
753 * Whether or not to send routing debugging information
754 * to the dht logging server
756 static unsigned int debug_routes;
759 * Whether or not to send FULL route information to
762 static unsigned int debug_routes_extended;
765 * GNUNET_YES or GNUNET_NO, whether or not to act as
766 * a malicious node which drops all messages
768 static unsigned int malicious_dropper;
771 * GNUNET_YES or GNUNET_NO, whether or not to act as
772 * a malicious node which sends out lots of GETS
774 static unsigned int malicious_getter;
777 * GNUNET_YES or GNUNET_NO, whether or not to act as
778 * a malicious node which sends out lots of PUTS
780 static unsigned int malicious_putter;
783 * Frequency for malicious get requests.
785 static unsigned long long malicious_get_frequency;
788 * Frequency for malicious put requests.
790 static unsigned long long malicious_put_frequency;
793 * Reply times for requests, if we are busy, don't send any
796 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
799 * Current counter for replies.
801 static unsigned int reply_counter;
804 * Forward declaration.
806 static size_t send_generic_reply (void *cls, size_t size, void *buf);
808 /** Declare here so retry_core_send is aware of it */
809 size_t core_transmit_notify (void *cls,
810 size_t size, void *buf);
813 * Convert unique ID to hash code.
815 * @param uid unique ID to convert
816 * @param hash set to uid (extended with zeros)
819 hash_from_uid (uint64_t uid,
820 GNUNET_HashCode *hash)
822 memset (hash, 0, sizeof(GNUNET_HashCode));
823 *((uint64_t*)hash) = uid;
828 * Calculate the average send time between messages so that we can
829 * ignore certain requests if we get too busy.
831 * @return the average time between asking core to send a message
832 * and when the buffer for copying it is passed
834 static struct GNUNET_TIME_Relative get_average_send_delay()
837 unsigned int divisor;
838 struct GNUNET_TIME_Relative average_time;
839 average_time = GNUNET_TIME_relative_get_zero();
841 for (i = 0; i < MAX_REPLY_TIMES; i++)
843 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
844 if (reply_times[i].value == (uint64_t)0)
854 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
855 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
861 * Given the largest send delay, artificially decrease it
862 * so the next time around we may have a chance at sending
865 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
868 for (i = 0; i < MAX_REPLY_TIMES; i++)
870 if (reply_times[i].value == max_time.value)
872 reply_times[i].value = reply_times[i].value / 2;
879 * Find the maximum send time of the recently sent values.
881 * @return the average time between asking core to send a message
882 * and when the buffer for copying it is passed
884 static struct GNUNET_TIME_Relative get_max_send_delay()
887 struct GNUNET_TIME_Relative max_time;
888 max_time = GNUNET_TIME_relative_get_zero();
890 for (i = 0; i < MAX_REPLY_TIMES; i++)
892 if (reply_times[i].value > max_time.value)
893 max_time.value = reply_times[i].value;
896 if (max_time.value > MAX_REQUEST_TIME.value)
897 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
902 increment_stats(const char *value)
906 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
911 * Try to send another message from our core send list
914 try_core_send (void *cls,
915 const struct GNUNET_SCHEDULER_TaskContext *tc)
917 struct PeerInfo *peer = cls;
918 struct P2PPendingMessage *pending;
921 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
923 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
926 if (peer->th != NULL)
927 return; /* Message send already in progress */
929 pending = peer->head;
932 ssize = ntohs(pending->msg->size);
934 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
935 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
936 "DHT", ssize, GNUNET_i2s(&peer->id));
938 pending->scheduled = GNUNET_TIME_absolute_get();
940 if (reply_counter >= MAX_REPLY_TIMES)
942 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
943 pending->timeout, &peer->id,
944 ssize, &core_transmit_notify, peer);
949 * Function called to send a request out to another peer.
950 * Called both for locally initiated requests and those
951 * received from other peers.
953 * @param cls DHT service closure argument
954 * @param msg the encapsulated message
955 * @param peer the peer to forward the message to
956 * @param msg_ctx the context of the message (hop count, bloom, etc.)
958 static void forward_result_message (void *cls,
959 const struct GNUNET_MessageHeader *msg,
960 struct PeerInfo *peer,
961 struct DHT_MessageContext *msg_ctx)
963 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
964 struct P2PPendingMessage *pending;
968 increment_stats(STAT_RESULT_FORWARDS);
969 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
970 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
971 psize = sizeof(struct P2PPendingMessage) + msize;
972 pending = GNUNET_malloc(psize);
973 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
974 pending->importance = DHT_SEND_PRIORITY;
975 pending->timeout = GNUNET_TIME_relative_get_forever();
976 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
977 result_message->header.size = htons(msize);
978 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
979 result_message->options = htonl(msg_ctx->msg_options);
980 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
981 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
982 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
983 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
984 memcpy(&result_message[1], msg, ntohs(msg->size));
986 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));
988 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
989 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
990 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
993 * Called when core is ready to send a message we asked for
994 * out to the destination.
996 * @param cls closure (NULL)
997 * @param size number of bytes available in buf
998 * @param buf where the callee should write the message
999 * @return number of bytes written to buf
1001 size_t core_transmit_notify (void *cls,
1002 size_t size, void *buf)
1004 struct PeerInfo *peer = cls;
1006 struct P2PPendingMessage *pending;
1013 /* client disconnected */
1015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1020 if (peer->head == NULL)
1025 pending = peer->head;
1026 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1027 msize = ntohs(pending->msg->size);
1031 memcpy (cbuf, pending->msg, msize);
1032 GNUNET_CONTAINER_DLL_remove (peer->head,
1036 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));
1038 GNUNET_free (pending);
1041 while (NULL != pending &&
1042 (size - off >= (msize = ntohs (pending->msg->size))))
1044 #if DEBUG_DHT_ROUTING
1045 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);
1047 memcpy (&cbuf[off], pending->msg, msize);
1049 GNUNET_CONTAINER_DLL_remove (peer->head,
1052 GNUNET_free (pending);
1053 pending = peer->head;
1056 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1057 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1059 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);
1065 * Determine how many low order bits match in two
1066 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
1067 * the first two lowest order bits, and therefore the
1068 * return value is two (NOT XOR distance, nor how many
1069 * bits match absolutely!).
1071 * @param first the first hashcode
1072 * @param second the hashcode to compare first to
1074 * @return the number of bits that match
1076 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
1080 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
1081 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
1083 return sizeof (GNUNET_HashCode) * 8;
1087 * Compute the distance between have and target as a 32-bit value.
1088 * Differences in the lower bits must count stronger than differences
1089 * in the higher bits.
1091 * @return 0 if have==target, otherwise a number
1092 * that is larger as the distance between
1093 * the two hash codes increases
1096 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1098 unsigned int bucket;
1103 /* We have to represent the distance between two 2^9 (=512)-bit
1104 numbers as a 2^5 (=32)-bit number with "0" being used for the
1105 two numbers being identical; furthermore, we need to
1106 guarantee that a difference in the number of matching
1107 bits is always represented in the result.
1109 We use 2^32/2^9 numerical values to distinguish between
1110 hash codes that have the same LSB bit distance and
1111 use the highest 2^9 bits of the result to signify the
1112 number of (mis)matching LSB bits; if we have 0 matching
1113 and hence 512 mismatching LSB bits we return -1 (since
1114 512 itself cannot be represented with 9 bits) */
1116 /* first, calculate the most significant 9 bits of our
1117 result, aka the number of LSBs */
1118 bucket = matching_bits (target, have);
1119 /* bucket is now a value between 0 and 512 */
1121 return 0; /* perfect match */
1123 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1124 below, we'd end up with max+1 (overflow)) */
1126 /* calculate the most significant bits of the final result */
1127 msb = (512 - bucket) << (32 - 9);
1128 /* calculate the 32-9 least significant bits of the final result by
1129 looking at the differences in the 32-9 bits following the
1130 mismatching bit at 'bucket' */
1132 for (i = bucket + 1;
1133 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1135 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1136 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1137 last bit set will be 31 -- if
1138 i does not reach 512 first... */
1144 * Return a number that is larger the closer the
1145 * "have" GNUNET_hash code is to the "target".
1147 * @return inverse distance metric, non-zero.
1148 * Must fudge the value if NO bits match.
1151 inverse_distance (const GNUNET_HashCode * target,
1152 const GNUNET_HashCode * have)
1154 if (matching_bits(target, have) == 0)
1155 return 1; /* Never return 0! */
1156 return ((unsigned int) -1) - distance (target, have);
1160 * Find the optimal bucket for this key, regardless
1161 * of the current number of buckets in use.
1163 * @param hc the hashcode to compare our identity to
1165 * @return the proper bucket index, or GNUNET_SYSERR
1166 * on error (same hashcode)
1168 static int find_bucket(const GNUNET_HashCode *hc)
1172 bits = matching_bits(&my_identity.hashPubKey, hc);
1173 if (bits == MAX_BUCKETS)
1174 return GNUNET_SYSERR;
1175 return MAX_BUCKETS - bits - 1;
1179 * Find which k-bucket this peer should go into,
1180 * taking into account the size of the k-bucket
1181 * array. This means that if more bits match than
1182 * there are currently buckets, lowest_bucket will
1185 * @param hc GNUNET_HashCode we are finding the bucket for.
1187 * @return the proper bucket index for this key,
1188 * or GNUNET_SYSERR on error (same hashcode)
1190 static int find_current_bucket(const GNUNET_HashCode *hc)
1193 actual_bucket = find_bucket(hc);
1195 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1196 return GNUNET_SYSERR;
1197 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1198 return lowest_bucket;
1200 return actual_bucket;
1205 * Find a routing table entry from a peer identity
1207 * @param peer the peer to look up
1209 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1212 find_bucket_by_peer(const struct PeerInfo *peer)
1215 struct PeerInfo *pos;
1217 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1219 pos = k_buckets[bucket].head;
1228 return GNUNET_SYSERR; /* No such peer. */
1234 * Print the complete routing table for this peer.
1237 print_routing_table ()
1240 struct PeerInfo *pos;
1241 char char_buf[30000];
1243 memset(char_buf, 0, sizeof(char_buf));
1245 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1246 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1247 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1249 pos = k_buckets[bucket].head;
1250 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1251 //fprintf(stderr, "Bucket %d:\n", bucket);
1254 //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));
1255 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));
1259 fprintf(stderr, "%s", char_buf);
1265 * Find a routing table entry from a peer identity
1267 * @param peer the peer identity to look up
1269 * @return the routing table entry, or NULL if not found
1271 static struct PeerInfo *
1272 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1275 struct PeerInfo *pos;
1276 bucket = find_current_bucket(&peer->hashPubKey);
1278 if (bucket == GNUNET_SYSERR)
1281 pos = k_buckets[bucket].head;
1284 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1288 return NULL; /* No such peer. */
1291 /* Forward declaration */
1293 update_core_preference (void *cls,
1294 const struct GNUNET_SCHEDULER_TaskContext *tc);
1296 * Function called with statistics about the given peer.
1298 * @param cls closure
1299 * @param peer identifies the peer
1300 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1301 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1302 * @param latency current latency estimate, "FOREVER" if we have been
1304 * @param amount set to the amount that was actually reserved or unreserved;
1305 * either the full requested amount or zero (no partial reservations)
1306 * @param preference current traffic preference for the given peer
1309 update_core_preference_finish (void *cls,
1311 GNUNET_PeerIdentity * peer,
1312 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1313 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1315 uint64_t preference)
1317 struct PeerInfo *peer_info = cls;
1318 peer_info->info_ctx = NULL;
1319 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1323 update_core_preference (void *cls,
1324 const struct GNUNET_SCHEDULER_TaskContext *tc)
1326 struct PeerInfo *peer = cls;
1327 uint64_t preference;
1329 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1334 preference = 2 << matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1335 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1337 GNUNET_TIME_relative_get_forever(),
1338 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1341 &update_core_preference_finish,
1346 * Really add a peer to a bucket (only do assertions
1349 * @param peer GNUNET_PeerIdentity of the peer to add
1350 * @param bucket the already figured out bucket to add
1352 * @param latency the core reported latency of this peer
1353 * @param distance the transport level distance to this peer
1355 * @return the newly added PeerInfo
1357 static struct PeerInfo *
1358 add_peer(const struct GNUNET_PeerIdentity *peer,
1359 unsigned int bucket,
1360 struct GNUNET_TIME_Relative latency,
1361 unsigned int distance)
1363 struct PeerInfo *new_peer;
1364 GNUNET_assert(bucket < MAX_BUCKETS);
1365 GNUNET_assert(peer != NULL);
1366 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1367 new_peer->latency = latency;
1368 new_peer->distance = distance;
1370 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1372 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1373 k_buckets[bucket].tail,
1374 k_buckets[bucket].tail,
1376 k_buckets[bucket].peers_size++;
1378 if ((matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1380 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1387 * Given a peer and its corresponding bucket,
1388 * remove it from that bucket. Does not free
1389 * the PeerInfo struct, nor cancel messages
1390 * or free messages waiting to be sent to this
1393 * @param peer the peer to remove
1394 * @param bucket the bucket the peer belongs to
1396 static void remove_peer (struct PeerInfo *peer,
1397 unsigned int bucket)
1399 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1400 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1401 k_buckets[bucket].tail,
1403 k_buckets[bucket].peers_size--;
1404 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1409 * Removes peer from a bucket, then frees associated
1410 * resources and frees peer.
1412 * @param peer peer to be removed and freed
1413 * @param bucket which bucket this peer belongs to
1415 static void delete_peer (struct PeerInfo *peer,
1416 unsigned int bucket)
1418 struct P2PPendingMessage *pos;
1419 struct P2PPendingMessage *next;
1421 struct PeerInfo *peer_pos;
1423 peer_pos = k_buckets[bucket].head;
1424 while ((peer_pos != NULL) && (peer_pos != peer))
1425 peer_pos = peer_pos->next;
1426 if (peer_pos == NULL)
1428 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1429 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));
1431 GNUNET_assert(peer_pos != NULL);
1433 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1435 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1436 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1437 if (peer->th != NULL)
1438 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1441 while (pos != NULL) /* Remove any pending messages for this peer */
1448 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1449 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1455 * Iterator over hash map entries.
1457 * @param cls closure
1458 * @param key current key code
1459 * @param value PeerInfo of the peer to move to new lowest bucket
1460 * @return GNUNET_YES if we should continue to
1464 static int move_lowest_bucket (void *cls,
1465 const GNUNET_HashCode * key,
1468 struct PeerInfo *peer = value;
1471 GNUNET_assert(lowest_bucket > 0);
1472 new_bucket = lowest_bucket - 1;
1473 remove_peer(peer, lowest_bucket);
1474 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1475 k_buckets[new_bucket].tail,
1476 k_buckets[new_bucket].tail,
1478 k_buckets[new_bucket].peers_size++;
1484 * The current lowest bucket is full, so change the lowest
1485 * bucket to the next lower down, and move any appropriate
1486 * entries in the current lowest bucket to the new bucket.
1488 static void enable_next_bucket()
1490 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1491 struct PeerInfo *pos;
1492 GNUNET_assert(lowest_bucket > 0);
1493 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1494 pos = k_buckets[lowest_bucket].head;
1497 fprintf(stderr, "Printing RT before new bucket\n");
1498 print_routing_table();
1500 /* Populate the array of peers which should be in the next lowest bucket */
1503 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1504 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1508 /* Remove peers from lowest bucket, insert into next lowest bucket */
1509 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1510 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1511 lowest_bucket = lowest_bucket - 1;
1513 fprintf(stderr, "Printing RT after new bucket\n");
1514 print_routing_table();
1519 * Find the closest peer in our routing table to the
1522 * @return The closest peer in our routing table to the
1523 * key, or NULL on error.
1525 static struct PeerInfo *
1526 find_closest_peer (const GNUNET_HashCode *hc)
1528 struct PeerInfo *pos;
1529 struct PeerInfo *current_closest;
1530 unsigned int lowest_distance;
1531 unsigned int temp_distance;
1535 lowest_distance = -1;
1537 if (k_buckets[lowest_bucket].peers_size == 0)
1540 current_closest = NULL;
1541 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1543 pos = k_buckets[bucket].head;
1545 while ((pos != NULL) && (count < bucket_size))
1547 temp_distance = distance(&pos->id.hashPubKey, hc);
1548 if (temp_distance <= lowest_distance)
1550 lowest_distance = temp_distance;
1551 current_closest = pos;
1557 GNUNET_assert(current_closest != NULL);
1558 return current_closest;
1563 * Function called to send a request out to another peer.
1564 * Called both for locally initiated requests and those
1565 * received from other peers.
1567 * @param cls DHT service closure argument (unused)
1568 * @param msg the encapsulated message
1569 * @param peer the peer to forward the message to
1570 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1572 static void forward_message (void *cls,
1573 const struct GNUNET_MessageHeader *msg,
1574 struct PeerInfo *peer,
1575 struct DHT_MessageContext *msg_ctx)
1577 struct GNUNET_DHT_P2PRouteMessage *route_message;
1578 struct P2PPendingMessage *pending;
1582 increment_stats(STAT_ROUTE_FORWARDS);
1584 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1585 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1587 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1588 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1589 psize = sizeof(struct P2PPendingMessage) + msize;
1590 pending = GNUNET_malloc(psize);
1591 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1592 pending->importance = msg_ctx->importance;
1593 pending->timeout = msg_ctx->timeout;
1594 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1595 route_message->header.size = htons(msize);
1596 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1597 route_message->options = htonl(msg_ctx->msg_options);
1598 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1599 route_message->network_size = htonl(msg_ctx->network_size);
1600 route_message->desired_replication_level = htonl(msg_ctx->replication);
1601 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1602 if (msg_ctx->bloom != NULL)
1603 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1604 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1605 memcpy(&route_message[1], msg, ntohs(msg->size));
1607 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));
1609 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1610 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1611 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1616 * Task used to send ping messages to peers so that
1617 * they don't get disconnected.
1619 * @param cls the peer to send a ping message to
1620 * @param tc context, reason, etc.
1623 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1625 struct PeerInfo *peer = cls;
1626 struct GNUNET_MessageHeader ping_message;
1627 struct DHT_MessageContext message_context;
1629 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1632 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1633 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1635 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1637 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1639 forward_message(NULL, &ping_message, peer, &message_context);
1640 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1644 * Schedule PING messages for the top X peers in each
1645 * bucket of the routing table (so core won't disconnect them!)
1647 void schedule_ping_messages()
1649 unsigned int bucket;
1651 struct PeerInfo *pos;
1652 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1654 pos = k_buckets[bucket].head;
1658 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1659 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1660 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1662 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1663 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1673 * Attempt to add a peer to our k-buckets.
1675 * @param peer, the peer identity of the peer being added
1677 * @return NULL if the peer was not added,
1678 * pointer to PeerInfo for new peer otherwise
1680 static struct PeerInfo *
1681 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1682 unsigned int bucket,
1683 struct GNUNET_TIME_Relative latency,
1684 unsigned int distance)
1687 struct PeerInfo *new_peer;
1688 peer_bucket = find_current_bucket(&peer->hashPubKey);
1689 if (peer_bucket == GNUNET_SYSERR)
1692 GNUNET_assert(peer_bucket >= lowest_bucket);
1693 new_peer = add_peer(peer, peer_bucket, latency, distance);
1695 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1696 enable_next_bucket();
1698 schedule_ping_messages();
1705 * Task run to check for messages that need to be sent to a client.
1707 * @param client a ClientList, containing the client and any messages to be sent to it
1710 process_pending_messages (struct ClientList *client)
1712 if (client->pending_head == NULL)
1714 if (client->transmit_handle != NULL)
1716 client->transmit_handle =
1717 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1718 ntohs (client->pending_head->msg->
1720 GNUNET_TIME_UNIT_FOREVER_REL,
1721 &send_generic_reply, client);
1725 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1726 * request. A ClientList is passed as closure, take the head of the list
1727 * and copy it into buf, which has the result of sending the message to the
1730 * @param cls closure to this call
1731 * @param size maximum number of bytes available to send
1732 * @param buf where to copy the actual message to
1734 * @return the number of bytes actually copied, 0 indicates failure
1737 send_generic_reply (void *cls, size_t size, void *buf)
1739 struct ClientList *client = cls;
1741 struct PendingMessage *reply;
1745 client->transmit_handle = NULL;
1748 /* client disconnected */
1752 while ( (NULL != (reply = client->pending_head)) &&
1753 (size >= off + (msize = ntohs (reply->msg->size))))
1755 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1756 client->pending_tail,
1758 memcpy (&cbuf[off], reply->msg, msize);
1759 GNUNET_free (reply);
1762 process_pending_messages (client);
1768 * Add a PendingMessage to the clients list of messages to be sent
1770 * @param client the active client to send the message to
1771 * @param pending_message the actual message to send
1774 add_pending_message (struct ClientList *client,
1775 struct PendingMessage *pending_message)
1777 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1778 client->pending_tail,
1779 client->pending_tail,
1781 process_pending_messages (client);
1788 * Called when a reply needs to be sent to a client, as
1789 * a result it found to a GET or FIND PEER request.
1791 * @param client the client to send the reply to
1792 * @param message the encapsulated message to send
1793 * @param uid the unique identifier of this request
1796 send_reply_to_client (struct ClientList *client,
1797 const struct GNUNET_MessageHeader *message,
1798 unsigned long long uid)
1800 struct GNUNET_DHT_RouteResultMessage *reply;
1801 struct PendingMessage *pending_message;
1805 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1806 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1808 msize = ntohs (message->size);
1809 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1810 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1812 GNUNET_break_op (0);
1816 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1817 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1818 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1819 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1820 reply->header.size = htons (tsize);
1821 reply->unique_id = GNUNET_htonll (uid);
1822 memcpy (&reply[1], message, msize);
1824 add_pending_message (client, pending_message);
1828 * Consider whether or not we would like to have this peer added to
1829 * our routing table. Check whether bucket for this peer is full,
1830 * if so return negative; if not return positive. Since peers are
1831 * only added on CORE level connect, this doesn't actually add the
1832 * peer to the routing table.
1834 * @param peer the peer we are considering adding
1836 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1839 * FIXME: Think about making a context for this call so that we can
1840 * ping the oldest peer in the current bucket and consider
1841 * removing it in lieu of the new peer.
1843 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1847 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1848 return GNUNET_NO; /* We already know this peer (are connected even!) */
1849 bucket = find_current_bucket(&peer->hashPubKey);
1850 if (bucket == GNUNET_SYSERR)
1852 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1859 * Main function that handles whether or not to route a result
1860 * message to other peers, or to send to our local client.
1862 * @param msg the result message to be routed
1863 * @return the number of peers the message was routed to,
1864 * GNUNET_SYSERR on failure
1866 static int route_result_message(void *cls,
1867 struct GNUNET_MessageHeader *msg,
1868 struct DHT_MessageContext *message_context)
1870 struct GNUNET_PeerIdentity new_peer;
1871 struct DHTQueryRecord *record;
1872 struct DHTRouteSource *pos;
1873 struct PeerInfo *peer_info;
1874 const struct GNUNET_MessageHeader *hello_msg;
1876 increment_stats(STAT_RESULTS);
1878 * If a find peer result message is received and contains a valid
1879 * HELLO for another peer, offer it to the transport service.
1881 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1883 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1886 hello_msg = &msg[1];
1887 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1889 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1893 else /* We have a valid hello, and peer id stored in new_peer */
1895 find_peer_context.count++;
1896 increment_stats(STAT_FIND_PEER_REPLY);
1897 if (GNUNET_YES == consider_peer(&new_peer))
1899 increment_stats(STAT_HELLOS_PROVIDED);
1900 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1901 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_UNIT_FOREVER_REL, &new_peer, NULL, NULL);
1906 if (malicious_dropper == GNUNET_YES)
1909 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1911 if (record == NULL) /* No record of this message! */
1914 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1915 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1916 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1918 #if DEBUG_DHT_ROUTING
1920 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1922 dhtlog_handle->insert_route (NULL,
1923 message_context->unique_id,
1925 message_context->hop_count,
1928 &message_context->key,
1929 message_context->peer, NULL);
1932 if (message_context->bloom != NULL)
1934 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1935 message_context->bloom = NULL;
1943 #if STRICT_FORWARDING
1944 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
1946 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
1948 increment_stats("# find peer responses NOT forwarded (bloom match)");
1953 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
1957 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1960 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1961 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
1962 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1964 #if DEBUG_DHT_ROUTING
1965 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1967 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
1968 message_context->hop_count,
1969 GNUNET_YES, &my_identity, &message_context->key,
1970 message_context->peer, NULL);
1973 increment_stats(STAT_RESULTS_TO_CLIENT);
1974 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
1975 increment_stats(STAT_GET_REPLY);
1977 send_reply_to_client(pos->client, msg, message_context->unique_id);
1979 else /* Send to peer */
1981 peer_info = find_peer_by_id(&pos->source);
1982 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
1988 if (message_context->bloom == NULL)
1989 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1990 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
1991 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
1994 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1995 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
1996 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1998 #if DEBUG_DHT_ROUTING
1999 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2001 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2003 message_context->hop_count,
2004 GNUNET_NO, &my_identity, &message_context->key,
2005 message_context->peer, &pos->source);
2008 forward_result_message(cls, msg, peer_info, message_context);
2013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2014 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2015 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2021 if (message_context->bloom != NULL)
2022 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2027 * Iterator for local get request results,
2029 * @param cls closure for iterator, a DatacacheGetContext
2030 * @param exp when does this value expire?
2031 * @param key the key this data is stored under
2032 * @param size the size of the data identified by key
2033 * @param data the actual data
2034 * @param type the type of the data
2036 * @return GNUNET_OK to continue iteration, anything else
2037 * to stop iteration.
2040 datacache_get_iterator (void *cls,
2041 struct GNUNET_TIME_Absolute exp,
2042 const GNUNET_HashCode * key,
2043 uint32_t size, const char *data, uint32_t type)
2045 struct DHT_MessageContext *msg_ctx = cls;
2046 struct DHT_MessageContext *new_msg_ctx;
2047 struct GNUNET_DHT_GetResultMessage *get_result;
2049 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2050 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2052 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2053 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2055 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2056 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2057 get_result->header.size =
2058 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2059 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2060 get_result->type = htons (type);
2061 memcpy (&get_result[1], data, size);
2062 new_msg_ctx->peer = &my_identity;
2063 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2064 new_msg_ctx->hop_count = 0;
2065 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2066 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2067 increment_stats(STAT_GET_RESPONSE_START);
2068 route_result_message(cls, &get_result->header, new_msg_ctx);
2069 GNUNET_free(new_msg_ctx);
2070 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2071 // datacache_get_ctx->unique_id);
2072 GNUNET_free (get_result);
2078 * Server handler for all dht get requests, look for data,
2079 * if found, send response either to clients or other peers.
2081 * @param cls closure for service
2082 * @param msg the actual get message
2083 * @param message_context struct containing pertinent information about the get request
2085 * @return number of items found for GET request
2088 handle_dht_get (void *cls,
2089 const struct GNUNET_MessageHeader *msg,
2090 struct DHT_MessageContext *message_context)
2092 const struct GNUNET_DHT_GetMessage *get_msg;
2094 unsigned int results;
2096 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2097 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2103 get_type = ntohs (get_msg->type);
2105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2106 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2107 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2108 message_context->unique_id);
2110 increment_stats(STAT_GETS);
2112 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2115 if (datacache != NULL)
2117 GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2118 &datacache_get_iterator, message_context);
2123 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2124 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2125 results, "GET", message_context->unique_id);
2127 #if DEBUG_DHT_ROUTING
2128 if ((debug_routes) && (dhtlog_handle != NULL))
2130 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2131 message_context->hop_count, GNUNET_YES, &my_identity,
2132 &message_context->key);
2135 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2137 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2138 message_context->hop_count, GNUNET_YES,
2139 &my_identity, &message_context->key, message_context->peer,
2145 if (message_context->hop_count == 0) /* Locally initiated request */
2147 #if DEBUG_DHT_ROUTING
2148 if ((debug_routes) && (dhtlog_handle != NULL))
2150 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2151 message_context->hop_count, GNUNET_NO, &my_identity,
2152 &message_context->key);
2161 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2163 GNUNET_HashCode *key = cls;
2164 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2171 * Server handler for initiating local dht find peer requests
2173 * @param cls closure for service
2174 * @param find_msg the actual find peer message
2175 * @param message_context struct containing pertinent information about the request
2179 handle_dht_find_peer (void *cls,
2180 const struct GNUNET_MessageHeader *find_msg,
2181 struct DHT_MessageContext *message_context)
2183 struct GNUNET_MessageHeader *find_peer_result;
2184 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2185 struct DHT_MessageContext *new_msg_ctx;
2186 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2189 GNUNET_HashCode *recent_hash;
2190 #if RESTRICT_FIND_PEER
2191 struct GNUNET_PeerIdentity peer_id;
2194 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2196 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2197 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2198 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2199 ntohs (find_msg->size),
2200 sizeof (struct GNUNET_MessageHeader));
2202 if (my_hello == NULL)
2205 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2206 "`%s': Our HELLO is null, can't return.\n",
2212 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2213 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2215 increment_stats(STAT_BLOOM_FIND_PEER);
2216 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2217 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2219 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2221 #if RESTRICT_FIND_PEER
2224 * Ignore any find peer requests from a peer we have seen very recently.
2226 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! */
2228 increment_stats("# dht find peer requests ignored (recently seen!)");
2233 * Use this check to only allow the peer to respond to find peer requests if
2234 * it would be beneficial to have the requesting peer in this peers routing
2235 * table. Can be used to thwart peers flooding the network with find peer
2236 * requests that we don't care about. However, if a new peer is joining
2237 * the network and has no other peers this is a problem (assume all buckets
2238 * full, no one will respond!).
2240 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2241 if (GNUNET_NO == consider_peer(&peer_id))
2243 increment_stats("# dht find peer requests ignored (do not need!)");
2248 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2249 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2250 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2251 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2253 /* Simplistic find_peer functionality, always return our hello */
2254 hello_size = ntohs(my_hello->size);
2255 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2257 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2259 GNUNET_break_op (0);
2263 find_peer_result = GNUNET_malloc (tsize);
2264 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2265 find_peer_result->size = htons (tsize);
2266 memcpy (&find_peer_result[1], my_hello, hello_size);
2268 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2269 "`%s': Sending hello size %d to requesting peer.\n",
2272 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2273 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2274 new_msg_ctx->peer = &my_identity;
2275 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2276 new_msg_ctx->hop_count = 0;
2277 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2278 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2279 increment_stats(STAT_FIND_PEER_ANSWER);
2280 route_result_message(cls, find_peer_result, new_msg_ctx);
2281 GNUNET_free(new_msg_ctx);
2282 #if DEBUG_DHT_ROUTING
2283 if ((debug_routes) && (dhtlog_handle != NULL))
2285 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2286 message_context->hop_count, GNUNET_YES, &my_identity,
2287 &message_context->key);
2290 GNUNET_free(find_peer_result);
2295 * Server handler for initiating local dht put requests
2297 * @param cls closure for service
2298 * @param msg the actual put message
2299 * @param message_context struct containing pertinent information about the request
2302 handle_dht_put (void *cls,
2303 const struct GNUNET_MessageHeader *msg,
2304 struct DHT_MessageContext *message_context)
2306 struct GNUNET_DHT_PutMessage *put_msg;
2310 GNUNET_assert (ntohs (msg->size) >=
2311 sizeof (struct GNUNET_DHT_PutMessage));
2314 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2315 put_type = ntohs (put_msg->type);
2317 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2320 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2322 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2323 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2324 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2326 #if DEBUG_DHT_ROUTING
2327 if (message_context->hop_count == 0) /* Locally initiated request */
2329 if ((debug_routes) && (dhtlog_handle != NULL))
2331 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2332 message_context->hop_count, GNUNET_NO, &my_identity,
2333 &message_context->key);
2338 if (message_context->closest != GNUNET_YES)
2341 #if DEBUG_DHT_ROUTING
2342 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2344 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2345 message_context->hop_count, GNUNET_YES,
2346 &my_identity, &message_context->key, message_context->peer,
2350 if ((debug_routes) && (dhtlog_handle != NULL))
2352 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2353 message_context->hop_count, GNUNET_YES, &my_identity,
2354 &message_context->key);
2358 increment_stats(STAT_PUTS_INSERTED);
2359 if (datacache != NULL)
2360 GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2361 (char *) &put_msg[1], put_type,
2362 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2364 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2365 "`%s:%s': %s request received, but have no datacache!\n",
2366 my_short_id, "DHT", "PUT");
2370 * Estimate the diameter of the network based
2371 * on how many buckets are currently in use.
2372 * Concept here is that the diameter of the network
2373 * is roughly the distance a message must travel in
2374 * order to reach its intended destination. Since
2375 * at each hop we expect to get one bit closer, and
2376 * we have one bit per bucket, the number of buckets
2377 * in use should be the largest number of hops for
2378 * a sucessful message. (of course, this assumes we
2379 * know all peers in the network!)
2381 * @return ballpark diameter figure
2383 static unsigned int estimate_diameter()
2385 return MAX_BUCKETS - lowest_bucket;
2389 * To how many peers should we (on average)
2390 * forward the request to obtain the desired
2391 * target_replication count (on average).
2393 * Always 0, 1 or 2 (don't send, send once, split)
2396 get_forward_count (unsigned int hop_count, size_t target_replication)
2399 double target_count;
2400 double random_probability;
2402 uint32_t random_value;
2404 unsigned int target_value;
2405 unsigned int diameter;
2408 * If we are behaving in strict kademlia mode, send multiple initial requests,
2409 * but then only send to 1 or 0 peers based strictly on the number of hops.
2411 if (strict_kademlia == GNUNET_YES)
2414 return DHT_KADEMLIA_REPLICATION;
2415 else if (hop_count < MAX_HOPS)
2421 /* FIXME: the smaller we think the network is the more lenient we should be for
2422 * routing right? The estimation below only works if we think we have reasonably
2423 * full routing tables, which for our RR topologies may not be the case!
2425 diameter = estimate_diameter ();
2426 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2429 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2430 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2431 "DHT", estimate_diameter(), lowest_bucket);
2435 else if (hop_count > MAX_HOPS)
2438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2439 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2446 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2447 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2448 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2449 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2450 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2451 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2452 RAND_MAX)) / RAND_MAX;
2453 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2456 //while (target_value < target_count)
2457 if (target_value < target_count)
2458 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? */
2461 //if ((target_count + 1 - (double)target_value) > random_probability)
2462 if ((target_count) > random_probability)
2466 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2467 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));
2469 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2470 if (random_value < target_replication)
2473 return target_value;
2477 * Check whether my identity is closer than any known peers.
2478 * If a non-null bloomfilter is given, check if this is the closest
2479 * peer that hasn't already been routed to.
2481 * @param target hash code to check closeness to
2482 * @param bloom bloomfilter, exclude these entries from the decision
2484 * Return GNUNET_YES if node location is closest, GNUNET_NO
2488 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2494 struct PeerInfo *pos;
2495 unsigned int my_distance;
2497 bucket_num = find_current_bucket(target);
2498 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2501 bits = matching_bits(&my_identity.hashPubKey, target);
2502 my_distance = distance(&my_identity.hashPubKey, target);
2503 pos = k_buckets[bucket_num].head;
2505 while ((pos != NULL) && (count < bucket_size))
2507 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2510 continue; /* Skip already checked entries */
2513 other_bits = matching_bits(&pos->id.hashPubKey, target);
2514 if (other_bits > bits)
2516 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2518 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2520 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2527 GNUNET_GE_LOG (coreAPI->ectx,
2528 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2529 GNUNET_GE_BULK, "closest peer\n");
2530 printPeerBits (&closest);
2531 GNUNET_GE_LOG (coreAPI->ectx,
2532 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2533 GNUNET_GE_BULK, "me\n");
2534 printPeerBits (coreAPI->my_identity);
2535 GNUNET_GE_LOG (coreAPI->ectx,
2536 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2537 GNUNET_GE_BULK, "key\n");
2538 printKeyBits (target);
2539 GNUNET_GE_LOG (coreAPI->ectx,
2540 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2542 "closest peer inverse distance is %u, mine is %u\n",
2543 inverse_distance (target, &closest.hashPubKey),
2544 inverse_distance (target,
2545 &coreAPI->my_identity->hashPubKey));
2548 /* No peers closer, we are the closest! */
2554 * Decide whether to route this request exclusively
2555 * to a closer peer (if closer peers exist) or to choose
2556 * from the whole set of peers.
2558 * @param hops number of hops this message has already traveled
2561 route_closer (const GNUNET_HashCode *target, struct GNUNET_CONTAINER_BloomFilter *bloom,
2564 unsigned int my_matching_bits;
2566 uint32_t random_value;
2567 struct PeerInfo *pos;
2570 my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2573 * First check if we know any close (as close as us or closer) peers.
2575 have_closer = GNUNET_NO;
2577 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2579 pos = k_buckets[bc].head;
2581 while ((pos != NULL) && (count < bucket_size))
2583 if ((matching_bits(target, &pos->id.hashPubKey) > my_matching_bits) &&
2584 (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
2586 have_closer = GNUNET_YES;
2592 if (have_closer == GNUNET_YES)
2596 if (have_closer == GNUNET_NO) /* We don't have a same distance or closer node, can't enforce closer only! */
2599 switch (converge_option)
2601 case DHT_CONVERGE_LINEAR:
2603 * Simple linear curve for choosing whether or not to converge.
2604 * Choose to route only closer with probability hops/MAX_HOPS.
2606 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, MAX_HOPS);
2607 if (random_value < hops)
2611 case DHT_CONVERGE_SQUARE:
2613 * Simple square based curve.
2615 if ((GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1) / (double)(uint32_t)-1) < (sqrt(hops) / sqrt(MAX_HOPS)))
2625 * Select a peer from the routing table that would be a good routing
2626 * destination for sending a message for "target". The resulting peer
2627 * must not be in the set of blocked peers.<p>
2629 * Note that we should not ALWAYS select the closest peer to the
2630 * target, peers further away from the target should be chosen with
2631 * exponentially declining probability.
2633 * @param target the key we are selecting a peer to route to
2634 * @param bloom a bloomfilter containing entries this request has seen already
2636 * @return Peer to route to, or NULL on error
2638 static struct PeerInfo *
2639 select_peer (const GNUNET_HashCode * target,
2640 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2642 unsigned int distance;
2645 unsigned int my_matching_bits;
2646 unsigned long long largest_distance;
2648 unsigned long long total_distance;
2649 unsigned long long selected;
2651 unsigned int total_distance;
2652 unsigned int selected;
2656 struct PeerInfo *pos;
2657 struct PeerInfo *chosen;
2660 my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2661 only_closer = route_closer(target, bloom, hops);
2663 if (GNUNET_YES == only_closer)
2665 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "only routing to closer peers!\n");
2666 GNUNET_asprintf(&temp_stat, "# closer only routes at hop %u", hops);
2667 increment_stats(temp_stat);
2671 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "routing to all possible peers!\n");
2672 GNUNET_asprintf(&temp_stat, "# NOT closer only routes at hop %u", hops);
2673 increment_stats(temp_stat);
2676 GNUNET_free(temp_stat);
2678 if (strict_kademlia == GNUNET_YES)
2680 largest_distance = 0;
2682 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2684 pos = k_buckets[bc].head;
2686 while ((pos != NULL) && (count < bucket_size))
2688 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2689 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2691 distance = inverse_distance (target, &pos->id.hashPubKey);
2692 if (distance > largest_distance)
2695 largest_distance = distance;
2703 if ((largest_distance > 0) && (chosen != NULL))
2705 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2717 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2719 pos = k_buckets[bc].head;
2721 while ((pos != NULL) && (count < bucket_size))
2723 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2724 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2726 #if REAL_DISTANCE /* Use the "real" distance as computed by the inverse_distance function */
2727 /** The "real" distance is best for routing to the closest peer, but in practice
2728 * (with our routing algorithm) it is usually better to use the squared bit distance.
2729 * This gives us a higher probability of routing towards close peers.
2731 total_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2733 total_distance += matching_bits(target, &pos->id.hashPubKey) * matching_bits(target ,&pos->id.hashPubKey);
2737 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2738 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2739 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2745 if (total_distance == 0)
2747 increment_stats("# select_peer, total_distance == 0");
2751 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2752 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2754 pos = k_buckets[bc].head;
2756 while ((pos != NULL) && (count < bucket_size))
2758 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2759 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2762 distance = inverse_distance (target, &pos->id.hashPubKey);
2764 distance = matching_bits(target, &pos->id.hashPubKey) * matching_bits(target, &pos->id.hashPubKey);
2766 if (distance > selected)
2768 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Selected peer with %u matching bits to route to\n", distance);
2771 selected -= distance;
2776 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2777 "`%s:%s': peer %s matches bloomfilter.\n",
2778 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2787 "`%s:%s': peer %s matches bloomfilter.\n",
2788 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2790 increment_stats("# failed to select peer");
2791 GNUNET_assert(only_closer == GNUNET_NO);
2797 * Task used to remove recent entries, either
2798 * after timeout, when full, or on shutdown.
2800 * @param cls the entry to remove
2801 * @param tc context, reason, etc.
2804 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2806 struct RecentRequest *req = cls;
2807 static GNUNET_HashCode hash;
2809 GNUNET_assert(req != NULL);
2810 hash_from_uid(req->uid, &hash);
2811 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
2812 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
2813 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
2816 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
2818 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
2819 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
2825 * Task used to remove forwarding entries, either
2826 * after timeout, when full, or on shutdown.
2828 * @param cls the entry to remove
2829 * @param tc context, reason, etc.
2832 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2834 struct DHTRouteSource *source_info = cls;
2835 struct DHTQueryRecord *record;
2836 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2837 record = source_info->record;
2838 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2840 if (record->head == NULL) /* No more entries in DLL */
2842 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2843 GNUNET_free(record);
2845 if (source_info->find_peers_responded != NULL)
2846 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
2847 GNUNET_free(source_info);
2851 * Remember this routing request so that if a reply is
2852 * received we can either forward it to the correct peer
2853 * or return the result locally.
2855 * @param cls DHT service closure
2856 * @param msg_ctx Context of the route request
2858 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2860 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2862 struct DHTQueryRecord *record;
2863 struct DHTRouteSource *source_info;
2864 struct DHTRouteSource *pos;
2865 struct GNUNET_TIME_Absolute now;
2866 unsigned int current_size;
2868 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2869 while (current_size >= MAX_OUTSTANDING_FORWARDS)
2871 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2872 GNUNET_assert(source_info != NULL);
2873 record = source_info->record;
2874 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2875 if (record->head == NULL) /* No more entries in DLL */
2877 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2878 GNUNET_free(record);
2880 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2881 if (source_info->find_peers_responded != NULL)
2882 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
2883 GNUNET_free(source_info);
2884 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2886 now = GNUNET_TIME_absolute_get();
2887 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2888 if (record != NULL) /* Already know this request! */
2893 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
2894 break; /* Already have this peer in reply list! */
2897 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
2899 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
2905 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
2906 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2907 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
2910 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
2911 source_info->record = record;
2912 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
2913 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2914 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
2915 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
2916 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
2918 source_info->client = msg_ctx->client;
2919 now = GNUNET_TIME_absolute_get_forever();
2921 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
2923 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2924 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
2925 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
2932 * Main function that handles whether or not to route a message to other
2935 * @param cls closure for dht service (NULL)
2936 * @param msg the message to be routed
2937 * @param message_context the context containing all pertinent information about the message
2939 * @return the number of peers the message was routed to,
2940 * GNUNET_SYSERR on failure
2942 static int route_message(void *cls,
2943 const struct GNUNET_MessageHeader *msg,
2944 struct DHT_MessageContext *message_context)
2948 struct PeerInfo *selected;
2949 #if DEBUG_DHT_ROUTING > 1
2950 struct PeerInfo *nearest;
2952 unsigned int forward_count;
2953 struct RecentRequest *recent_req;
2954 GNUNET_HashCode unique_hash;
2955 char *stat_forward_count;
2956 #if DEBUG_DHT_ROUTING
2960 if (malicious_dropper == GNUNET_YES)
2962 #if DEBUG_DHT_ROUTING
2963 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2965 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2966 message_context->hop_count, GNUNET_SYSERR,
2967 &my_identity, &message_context->key, message_context->peer,
2971 if (message_context->bloom != NULL)
2972 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2976 increment_stats(STAT_ROUTES);
2977 /* Semantics of this call means we find whether we are the closest peer out of those already
2978 * routed to on this messages path.
2980 global_closest = am_closest_peer(&message_context->key, NULL);
2981 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
2982 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
2983 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
2984 increment_stats(stat_forward_count);
2985 GNUNET_free(stat_forward_count);
2986 if (message_context->bloom == NULL)
2987 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2989 if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
2992 #if DEBUG_DHT_ROUTING
2993 if (forward_count == 0)
2994 ret = GNUNET_SYSERR;
2998 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3000 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3001 message_context->hop_count, ret,
3002 &my_identity, &message_context->key, message_context->peer,
3007 switch (ntohs(msg->type))
3009 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3010 cache_response (cls, message_context);
3011 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3014 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3015 increment_stats(STAT_PUTS);
3016 message_context->closest = global_closest;
3017 handle_dht_put (cls, msg, message_context);
3019 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3020 increment_stats(STAT_FIND_PEER);
3021 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3023 cache_response (cls, message_context);
3024 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3025 handle_dht_find_peer (cls, msg, message_context);
3027 #if DEBUG_DHT_ROUTING
3028 if (message_context->hop_count == 0) /* Locally initiated request */
3030 if ((debug_routes) && (dhtlog_handle != NULL))
3032 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3033 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3034 message_context->hop_count, GNUNET_NO, &my_identity,
3035 &message_context->key);
3041 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3042 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3045 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3046 hash_from_uid(message_context->unique_id, &unique_hash);
3047 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent.hashmap, &unique_hash))
3049 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3050 GNUNET_assert(recent_req != NULL);
3051 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3052 increment_stats(STAT_DUPLICATE_UID);
3055 increment_stats(STAT_RECENT_SEEN);
3056 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3061 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3062 recent_req->uid = message_context->unique_id;
3063 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3064 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3065 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3066 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3067 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3070 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3072 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3073 GNUNET_assert(recent_req != NULL);
3074 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3075 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3078 for (i = 0; i < forward_count; i++)
3080 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3082 if (selected != NULL)
3084 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3085 #if DEBUG_DHT_ROUTING > 1
3086 nearest = find_closest_peer(&message_context->key);
3087 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3088 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3089 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3090 "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));
3091 GNUNET_free(nearest_buf);
3093 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3095 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3096 message_context->hop_count, GNUNET_NO,
3097 &my_identity, &message_context->key, message_context->peer,
3100 forward_message(cls, msg, selected, message_context);
3104 increment_stats("# NULL returned from select_peer");
3105 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3106 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
3111 #if DEBUG_DHT_ROUTING > 1
3112 if (forward_count == 0)
3114 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3115 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
3116 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
3120 if (message_context->bloom != NULL)
3122 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3123 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3126 return forward_count;
3130 * Find a client if it exists, add it otherwise.
3132 * @param client the server handle to the client
3134 * @return the client if found, a new client otherwise
3136 static struct ClientList *
3137 find_active_client (struct GNUNET_SERVER_Client *client)
3139 struct ClientList *pos = client_list;
3140 struct ClientList *ret;
3144 if (pos->client_handle == client)
3149 ret = GNUNET_malloc (sizeof (struct ClientList));
3150 ret->client_handle = client;
3151 ret->next = client_list;
3157 * Task to send a malicious put message across the network.
3159 * @param cls closure for this task
3160 * @param tc the context under which the task is running
3163 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3165 static struct GNUNET_DHT_PutMessage put_message;
3166 static struct DHT_MessageContext message_context;
3167 static GNUNET_HashCode key;
3168 uint32_t random_key;
3170 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3173 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3174 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3175 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3176 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3177 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3178 message_context.client = NULL;
3179 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3180 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3181 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3182 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3183 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3184 message_context.msg_options = ntohl (0);
3185 message_context.network_size = estimate_diameter();
3186 message_context.peer = &my_identity;
3187 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3188 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3189 if (dhtlog_handle != NULL)
3190 dhtlog_handle->insert_dhtkey(NULL, &key);
3191 increment_stats(STAT_PUT_START);
3192 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3193 route_message(NULL, &put_message.header, &message_context);
3194 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3199 * Task to send a malicious put message across the network.
3201 * @param cls closure for this task
3202 * @param tc the context under which the task is running
3205 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3207 static struct GNUNET_DHT_GetMessage get_message;
3208 struct DHT_MessageContext message_context;
3209 static GNUNET_HashCode key;
3210 uint32_t random_key;
3212 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3215 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3216 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3217 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3218 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3219 message_context.client = NULL;
3220 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3221 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3222 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3223 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3224 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3225 message_context.msg_options = ntohl (0);
3226 message_context.network_size = estimate_diameter();
3227 message_context.peer = &my_identity;
3228 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3229 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3230 if (dhtlog_handle != NULL)
3231 dhtlog_handle->insert_dhtkey(NULL, &key);
3232 increment_stats(STAT_GET_START);
3233 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3234 route_message (NULL, &get_message.header, &message_context);
3235 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3239 * Iterator over hash map entries.
3241 * @param cls closure
3242 * @param key current key code
3243 * @param value value in the hash map
3244 * @return GNUNET_YES if we should continue to
3249 add_known_to_bloom (void *cls,
3250 const GNUNET_HashCode * key,
3253 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3254 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3259 * Task to send a find peer message for our own peer identifier
3260 * so that we can find the closest peers in the network to ourselves
3261 * and attempt to connect to them.
3263 * @param cls closure for this task
3264 * @param tc the context under which the task is running
3267 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3269 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3270 struct DHT_MessageContext message_context;
3272 struct GNUNET_TIME_Relative next_send_time;
3273 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3275 struct GNUNET_TIME_Relative time_diff;
3276 struct GNUNET_TIME_Absolute end;
3278 double count_per_interval;
3280 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3283 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! */
3285 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3286 GNUNET_SCHEDULER_add_delayed (sched,
3287 GNUNET_TIME_UNIT_MINUTES,
3288 &send_find_peer_message, NULL);
3289 newly_found_peers = 0;
3293 increment_stats(STAT_FIND_PEER_START);
3295 end = GNUNET_TIME_absolute_get();
3296 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3298 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3300 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3301 count_per_interval = find_peer_context.count / multiplier;
3305 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3306 count_per_interval = find_peer_context.count * multiplier;
3310 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3311 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3312 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3313 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3314 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3315 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3316 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3317 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3318 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3319 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3320 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3321 message_context.network_size = estimate_diameter();
3322 message_context.peer = &my_identity;
3323 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3324 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3326 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3327 GNUNET_free(find_peer_msg);
3328 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3329 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3331 if (newly_found_peers < bucket_size)
3333 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3334 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3335 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3339 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3340 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3341 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3344 GNUNET_assert (next_send_time.value != 0);
3345 find_peer_context.count = 0;
3346 newly_found_peers = 0;
3347 find_peer_context.start = GNUNET_TIME_absolute_get();
3348 if (GNUNET_YES == do_find_peer)
3350 GNUNET_SCHEDULER_add_delayed (sched,
3352 &send_find_peer_message, NULL);
3357 * Handler for any generic DHT messages, calls the appropriate handler
3358 * depending on message type, sends confirmation if responses aren't otherwise
3361 * @param cls closure for the service
3362 * @param client the client we received this message from
3363 * @param message the actual message received
3366 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3367 const struct GNUNET_MessageHeader *message)
3369 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3370 const struct GNUNET_MessageHeader *enc_msg;
3371 struct DHT_MessageContext message_context;
3372 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3374 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3375 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3376 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3377 GNUNET_ntohll (dht_msg->unique_id));
3379 #if DEBUG_DHT_ROUTING
3380 if (dhtlog_handle != NULL)
3381 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3383 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3384 message_context.client = find_active_client (client);
3385 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3386 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3387 message_context.replication = ntohl (dht_msg->desired_replication_level);
3388 message_context.msg_options = ntohl (dht_msg->options);
3389 message_context.network_size = estimate_diameter();
3390 message_context.peer = &my_identity;
3391 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3392 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3393 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3394 increment_stats(STAT_GET_START);
3395 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3396 increment_stats(STAT_PUT_START);
3397 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3398 increment_stats(STAT_FIND_PEER_START);
3400 route_message(cls, enc_msg, &message_context);
3402 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3407 * Handler for any locally received DHT control messages,
3408 * sets malicious flags mostly for now.
3410 * @param cls closure for the service
3411 * @param client the client we received this message from
3412 * @param message the actual message received
3416 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3417 const struct GNUNET_MessageHeader *message)
3419 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3420 (const struct GNUNET_DHT_ControlMessage *) message;
3422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3423 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3424 "CONTROL", ntohs(dht_control_msg->command));
3427 switch (ntohs(dht_control_msg->command))
3429 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3430 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3431 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3433 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3434 if (ntohs(dht_control_msg->variable) > 0)
3435 malicious_get_frequency = ntohs(dht_control_msg->variable);
3436 if (malicious_get_frequency == 0)
3437 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3438 if (malicious_getter != GNUNET_YES)
3439 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3440 malicious_getter = GNUNET_YES;
3441 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3443 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3444 if (ntohs(dht_control_msg->variable) > 0)
3445 malicious_put_frequency = ntohs(dht_control_msg->variable);
3446 if (malicious_put_frequency == 0)
3447 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3448 if (malicious_putter != GNUNET_YES)
3449 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3450 malicious_putter = GNUNET_YES;
3451 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3453 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3454 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3455 dhtlog_handle->set_malicious(&my_identity);
3456 malicious_dropper = GNUNET_YES;
3457 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3460 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3463 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3467 * Handler for any generic DHT stop messages, calls the appropriate handler
3468 * depending on message type (if processed locally)
3470 * @param cls closure for the service
3471 * @param client the client we received this message from
3472 * @param message the actual message received
3476 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3477 const struct GNUNET_MessageHeader *message)
3480 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3481 (const struct GNUNET_DHT_StopMessage *) message;
3482 struct DHTQueryRecord *record;
3483 struct DHTRouteSource *pos;
3485 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3486 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3487 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3489 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3496 if ((pos->client != NULL) && (pos->client->client_handle == client))
3498 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3499 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3505 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3510 * Core handler for p2p route requests.
3513 handle_dht_p2p_route_request (void *cls,
3514 const struct GNUNET_PeerIdentity *peer,
3515 const struct GNUNET_MessageHeader *message,
3516 struct GNUNET_TIME_Relative latency, uint32_t distance)
3519 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3520 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3522 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3523 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3524 struct DHT_MessageContext *message_context;
3526 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
3528 fprintf(stderr, "Sending of previous replies took far too long, backing off!\n");
3529 decrease_max_send_delay(get_max_send_delay());
3533 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3536 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3541 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3546 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3547 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3548 GNUNET_assert(message_context->bloom != NULL);
3549 message_context->hop_count = ntohl(incoming->hop_count);
3550 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
3551 message_context->replication = ntohl(incoming->desired_replication_level);
3552 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3553 message_context->msg_options = ntohl(incoming->options);
3554 message_context->network_size = ntohl(incoming->network_size);
3555 message_context->peer = peer;
3556 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3557 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3558 route_message(cls, enc_msg, message_context);
3559 GNUNET_free(message_context);
3565 * Core handler for p2p route results.
3568 handle_dht_p2p_route_result (void *cls,
3569 const struct GNUNET_PeerIdentity *peer,
3570 const struct GNUNET_MessageHeader *message,
3571 struct GNUNET_TIME_Relative latency, uint32_t distance)
3574 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3575 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3577 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3578 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3579 struct DHT_MessageContext message_context;
3581 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3587 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3588 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3589 GNUNET_assert(message_context.bloom != NULL);
3590 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
3591 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3592 message_context.msg_options = ntohl(incoming->options);
3593 message_context.hop_count = ntohl(incoming->hop_count);
3594 message_context.peer = peer;
3595 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3596 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3597 route_result_message(cls, enc_msg, &message_context);
3603 * Receive the HELLO from transport service,
3604 * free current and replace if necessary.
3607 * @param message HELLO message of peer
3610 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3614 "Received our `%s' from transport service\n",
3618 GNUNET_assert (message != NULL);
3619 GNUNET_free_non_null(my_hello);
3620 my_hello = GNUNET_malloc(ntohs(message->size));
3621 memcpy(my_hello, message, ntohs(message->size));
3626 * Task run during shutdown.
3632 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3635 struct PeerInfo *pos;
3636 if (transport_handle != NULL)
3638 GNUNET_free_non_null(my_hello);
3639 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3640 GNUNET_TRANSPORT_disconnect(transport_handle);
3643 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3645 while (k_buckets[bucket_count].head != NULL)
3647 pos = k_buckets[bucket_count].head;
3649 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3650 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3652 delete_peer(pos, bucket_count);
3655 if (coreAPI != NULL)
3658 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3659 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3661 GNUNET_CORE_disconnect (coreAPI);
3663 if (datacache != NULL)
3666 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3667 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3669 GNUNET_DATACACHE_destroy (datacache);
3674 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3677 if (dhtlog_handle != NULL)
3678 GNUNET_DHTLOG_disconnect(dhtlog_handle);
3680 GNUNET_free_non_null(my_short_id);
3685 * To be called on core init/fail.
3687 * @param cls service closure
3688 * @param server handle to the server for this service
3689 * @param identity the public identity of this peer
3690 * @param publicKey the public key of this peer
3693 core_init (void *cls,
3694 struct GNUNET_CORE_Handle *server,
3695 const struct GNUNET_PeerIdentity *identity,
3696 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3702 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3703 "%s: Connection to core FAILED!\n", "dht",
3704 GNUNET_i2s (identity));
3706 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
3707 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3711 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3712 "%s: Core connection initialized, I am peer: %s\n", "dht",
3713 GNUNET_i2s (identity));
3716 /* Copy our identity so we can use it */
3717 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3718 if (my_short_id != NULL)
3719 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3720 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3721 /* Set the server to local variable */
3724 if (dhtlog_handle != NULL)
3725 dhtlog_handle->insert_node (NULL, &my_identity);
3729 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3730 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3731 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3732 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
3737 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3738 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
3739 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
3744 * Method called whenever a peer connects.
3746 * @param cls closure
3747 * @param peer peer identity this notification is about
3748 * @param latency reported latency of the connection with peer
3749 * @param distance reported distance (DV) to peer
3751 void handle_core_connect (void *cls,
3752 const struct GNUNET_PeerIdentity * peer,
3753 struct GNUNET_TIME_Relative latency,
3756 struct PeerInfo *ret;
3759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3760 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
3763 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3765 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));
3769 if (datacache != NULL)
3770 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
3771 ret = try_add_peer(peer,
3772 find_current_bucket(&peer->hashPubKey),
3777 newly_found_peers++;
3778 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3781 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3782 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
3787 * Method called whenever a peer disconnects.
3789 * @param cls closure
3790 * @param peer peer identity this notification is about
3792 void handle_core_disconnect (void *cls,
3794 GNUNET_PeerIdentity * peer)
3796 struct PeerInfo *to_remove;
3799 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");
3801 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3803 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));
3806 increment_stats(STAT_DISCONNECTS);
3807 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
3808 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
3809 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
3810 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
3811 delete_peer(to_remove, current_bucket);
3815 * Process dht requests.
3817 * @param cls closure
3818 * @param scheduler scheduler to use
3819 * @param server the initialized server
3820 * @param c configuration to use
3824 struct GNUNET_SCHEDULER_Handle *scheduler,
3825 struct GNUNET_SERVER_Handle *server,
3826 const struct GNUNET_CONFIGURATION_Handle *c)
3829 struct GNUNET_TIME_Relative next_send_time;
3833 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
3834 GNUNET_SERVER_add_handlers (server, plugin_handlers);
3835 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
3836 cfg, /* Main configuration */
3837 GNUNET_TIME_UNIT_FOREVER_REL,
3838 NULL, /* Closure passed to DHT functions */
3839 &core_init, /* Call core_init once connected */
3840 &handle_core_connect, /* Handle connects */
3841 &handle_core_disconnect, /* remove peers on disconnects */
3842 NULL, /* Do we care about "status" updates? */
3843 NULL, /* Don't want notified about all incoming messages */
3844 GNUNET_NO, /* For header only inbound notification */
3845 NULL, /* Don't want notified about all outbound messages */
3846 GNUNET_NO, /* For header only outbound notification */
3847 core_handlers); /* Register these handlers */
3849 if (coreAPI == NULL)
3851 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
3852 NULL, NULL, NULL, NULL, NULL);
3853 if (transport_handle != NULL)
3854 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
3856 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
3858 lowest_bucket = MAX_BUCKETS - 1;
3859 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
3860 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3861 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
3862 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
3863 GNUNET_assert(all_known_peers != NULL);
3864 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
3866 debug_routes = GNUNET_YES;
3870 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3873 strict_kademlia = GNUNET_YES;
3877 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3880 stop_on_closest = GNUNET_YES;
3884 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3887 stop_on_found = GNUNET_YES;
3891 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3892 "malicious_getter"))
3894 malicious_getter = GNUNET_YES;
3895 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3896 "MALICIOUS_GET_FREQUENCY",
3897 &malicious_get_frequency))
3898 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3902 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3903 "malicious_putter"))
3905 malicious_putter = GNUNET_YES;
3906 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3907 "MALICIOUS_PUT_FREQUENCY",
3908 &malicious_put_frequency))
3909 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3913 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3914 "malicious_dropper"))
3916 malicious_dropper = GNUNET_YES;
3920 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3923 do_find_peer = GNUNET_NO;
3926 do_find_peer = GNUNET_YES;
3929 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
3930 "mysql_logging_extended"))
3932 debug_routes = GNUNET_YES;
3933 debug_routes_extended = GNUNET_YES;
3936 if (GNUNET_YES == debug_routes)
3938 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
3939 if (dhtlog_handle == NULL)
3941 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3942 "Could not connect to mysql logging server, logging will not happen!");
3946 converge_option = DHT_CONVERGE_SQUARE;
3948 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
3951 converge_option = DHT_CONVERGE_LINEAR;
3954 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
3958 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
3959 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
3960 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
3961 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
3962 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
3963 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
3964 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
3965 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
3966 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
3967 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
3968 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
3969 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
3970 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
3971 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
3972 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
3973 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
3974 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
3975 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
3976 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
3977 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
3979 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
3980 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
3981 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3982 if (GNUNET_YES == do_find_peer)
3984 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3985 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3986 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3987 find_peer_context.start = GNUNET_TIME_absolute_get();
3988 GNUNET_SCHEDULER_add_delayed (sched,
3990 &send_find_peer_message, &find_peer_context);
3993 /* Scheduled the task to clean up when shutdown is called */
3994 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
3995 GNUNET_TIME_UNIT_FOREVER_REL,
3996 &shutdown_task, NULL);
4000 * The main function for the dht service.
4002 * @param argc number of arguments from the command line
4003 * @param argv command line arguments
4004 * @return 0 ok, 1 on error
4007 main (int argc, char *const *argv)
4009 return (GNUNET_OK ==
4010 GNUNET_SERVICE_run (argc,
4013 GNUNET_SERVICE_OPTION_NONE,
4014 &run, NULL)) ? 0 : 1;