2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file dht/gnunet-service-dht.c
23 * @brief main DHT service shell, building block for DHT implementations
24 * @author Christian Grothoff
25 * @author Nathan Evans
29 #include "gnunet_client_lib.h"
30 #include "gnunet_getopt_lib.h"
31 #include "gnunet_os_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_core_service.h"
35 #include "gnunet_signal_lib.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_datacache_lib.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_hello_lib.h"
40 #include "gnunet_dht_service.h"
41 #include "gnunet_statistics_service.h"
45 #define PRINT_TABLES GNUNET_NO
47 #define REAL_DISTANCE GNUNET_NO
49 #define EXTRA_CHECKS GNUNET_NO
51 * How many buckets will we allow total.
53 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
56 * Should the DHT issue FIND_PEER requests to get better routing tables?
58 #define DO_FIND_PEER GNUNET_YES
61 * What is the maximum number of peers in a given bucket.
63 #define DEFAULT_BUCKET_SIZE 4
66 * Minimum number of peers we need for "good" routing,
67 * any less than this and we will allow messages to
68 * travel much further through the network!
70 #define MINIMUM_PEER_THRESHOLD 20
72 #define DHT_MAX_RECENT 1000
74 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
77 * Default time to wait to send messages on behalf of other peers.
79 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
82 * Default importance for handling messages on behalf of other peers.
84 #define DHT_DEFAULT_P2P_IMPORTANCE 0
87 * How long to keep recent requests around by default.
89 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
92 * Default time to wait to send find peer messages sent by the dht service.
94 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
97 * Default importance for find peer messages sent by the dht service.
99 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
102 * Default replication parameter for find peer messages sent by the dht service.
104 #define DHT_DEFAULT_PUT_REPLICATION 4
107 * Default replication parameter for find peer messages sent by the dht service.
109 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
112 * Default options for find peer requests sent by the dht service.
114 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
115 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
118 * How long at least to wait before sending another find peer request.
120 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
123 * How long at most to wait before sending another find peer request.
125 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
128 * How often to update our preference levels for peers in our routing tables.
130 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
133 * How long at most on average will we allow a reply forward to take
134 * (before we quit sending out new requests)
136 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
139 * How many initial requests to send out (in true Kademlia fashion)
141 #define DHT_KADEMLIA_REPLICATION 3
144 * Default frequency for sending malicious get messages
146 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
149 * Default frequency for sending malicious put messages
151 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
154 * Type for a malicious request, so we can ignore it during testing
156 #define DHT_MALICIOUS_MESSAGE_TYPE 42
158 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
161 * Real maximum number of hops, at which point we refuse
162 * to forward the message.
164 #define DEFAULT_MAX_HOPS 10
167 * How many time differences between requesting a core send and
168 * the actual callback to remember.
170 #define MAX_REPLY_TIMES 8
172 enum ConvergenceOptions
175 * Use the linear method for convergence.
180 * Converge using a fast converging square
186 * Converge using a slower exponential
189 DHT_CONVERGE_EXPONENTIAL,
192 * Don't do any special convergence, allow
193 * the algorithm to hopefully route to closer
200 * Linked list of messages to send to clients.
202 struct P2PPendingMessage
205 * Pointer to next item in the list
207 struct P2PPendingMessage *next;
210 * Pointer to previous item in the list
212 struct P2PPendingMessage *prev;
215 * Message importance level.
217 unsigned int importance;
220 * Time when this request was scheduled to be sent.
222 struct GNUNET_TIME_Absolute scheduled;
225 * How long to wait before sending message.
227 struct GNUNET_TIME_Relative timeout;
230 * Actual message to be sent; // avoid allocation
232 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
237 * Per-peer information.
242 * Next peer entry (DLL)
244 struct PeerInfo *next;
247 * Prev peer entry (DLL)
249 struct PeerInfo *prev;
252 * Head of pending messages to be sent to this peer.
254 struct P2PPendingMessage *head;
257 * Tail of pending messages to be sent to this peer.
259 struct P2PPendingMessage *tail;
262 * Core handle for sending messages to this peer.
264 struct GNUNET_CORE_TransmitHandle *th;
267 * Task for scheduling message sends.
269 GNUNET_SCHEDULER_TaskIdentifier send_task;
272 * Task for scheduling preference updates
274 GNUNET_SCHEDULER_TaskIdentifier preference_task;
277 * Preference update context
279 struct GNUNET_CORE_InformationRequestContext *info_ctx;
282 * What is the average latency for replies received?
284 struct GNUNET_TIME_Relative latency;
287 * What is the identity of the peer?
289 struct GNUNET_PeerIdentity id;
292 * Transport level distance to peer.
294 unsigned int distance;
297 * Task for scheduling periodic ping messages for this peer.
299 GNUNET_SCHEDULER_TaskIdentifier ping_task;
303 * Peers are grouped into buckets.
310 struct PeerInfo *head;
315 struct PeerInfo *tail;
318 * Number of peers in the bucket.
320 unsigned int peers_size;
324 * Linked list of messages to send to clients.
326 struct PendingMessage
329 * Pointer to next item in the list
331 struct PendingMessage *next;
334 * Pointer to previous item in the list
336 struct PendingMessage *prev;
339 * Actual message to be sent; // avoid allocation
341 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
346 * Struct containing information about a client,
347 * handle to connect to it, and any pending messages
348 * that need to be sent to it.
353 * Linked list of active clients
355 struct ClientList *next;
358 * The handle to this client
360 struct GNUNET_SERVER_Client *client_handle;
363 * Handle to the current transmission request, NULL
366 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
369 * Linked list of pending messages for this client
371 struct PendingMessage *pending_head;
374 * Tail of linked list of pending messages for this client
376 struct PendingMessage *pending_tail;
381 * Context containing information about a DHT message received.
383 struct DHT_MessageContext
386 * The client this request was received from.
387 * (NULL if received from another peer)
389 struct ClientList *client;
392 * The peer this request was received from.
393 * (NULL if received from local client)
395 const struct GNUNET_PeerIdentity *peer;
398 * The key this request was about
403 * The unique identifier of this request
408 * Desired replication level
410 uint32_t replication;
413 * Network size estimate, either ours or the sum of
414 * those routed to thus far. =~ Log of number of peers
415 * chosen from for this request.
417 uint32_t network_size;
420 * Any message options for this request
422 uint32_t msg_options;
425 * How many hops has the message already traversed?
430 * How important is this message?
432 unsigned int importance;
435 * How long should we wait to transmit this request?
437 struct GNUNET_TIME_Relative timeout;
440 * Bloomfilter for this routing request.
442 struct GNUNET_CONTAINER_BloomFilter *bloom;
445 * Did we forward this message? (may need to remember it!)
450 * Are we the closest known peer to this key (out of our neighbors?)
456 * Record used for remembering what peers are waiting for what
457 * responses (based on search key).
459 struct DHTRouteSource
464 struct DHTRouteSource *next;
469 struct DHTRouteSource *prev;
472 * Source of the request. Replies should be forwarded to
475 struct GNUNET_PeerIdentity source;
478 * If this was a local request, remember the client; otherwise NULL.
480 struct ClientList *client;
483 * Pointer to this nodes heap location (for removal)
485 struct GNUNET_CONTAINER_HeapNode *hnode;
488 * Back pointer to the record storing this information.
490 struct DHTQueryRecord *record;
493 * Task to remove this entry on timeout.
495 GNUNET_SCHEDULER_TaskIdentifier delete_task;
498 * Bloomfilter of peers we have already sent back as
499 * replies to the initial request. Allows us to not
500 * forward the same peer multiple times for a find peer
503 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
508 * Entry in the DHT routing table.
510 struct DHTQueryRecord
513 * Head of DLL for result forwarding.
515 struct DHTRouteSource *head;
518 * Tail of DLL for result forwarding.
520 struct DHTRouteSource *tail;
523 * Key that the record concerns.
528 * GET message of this record (what we already forwarded?).
530 //DV_DHT_MESSAGE get; Try to get away with not saving this.
533 * Bloomfilter of the peers we've replied to so far
535 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
540 * Context used to calculate the number of find peer messages
541 * per X time units since our last scheduled find peer message
542 * was sent. If we have seen too many messages, delay or don't
545 struct FindPeerMessageContext
549 struct GNUNET_TIME_Absolute start;
551 struct GNUNET_TIME_Absolute end;
555 * DHT Routing results structure
560 * Min heap for removal upon reaching limit
562 struct GNUNET_CONTAINER_Heap *minHeap;
565 * Hashmap for fast key based lookup
567 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
572 * DHT structure for recent requests.
574 struct RecentRequests
577 * Min heap for removal upon reaching limit
579 struct GNUNET_CONTAINER_Heap *minHeap;
582 * Hashmap for key based lookup
584 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
590 * Position of this node in the min heap.
592 struct GNUNET_CONTAINER_HeapNode *heap_node;
595 * Bloomfilter containing entries for peers
596 * we forwarded this request to.
598 struct GNUNET_CONTAINER_BloomFilter *bloom;
601 * Timestamp of this request, for ordering
604 struct GNUNET_TIME_Absolute timestamp;
607 * Key of this request.
612 * Unique identifier for this request.
617 * Task to remove this entry on timeout.
619 GNUNET_SCHEDULER_TaskIdentifier remove_task;
622 struct RepublishContext
637 * Which kind of convergence will we be using?
639 enum ConvergenceOptions converge_option;
642 * Modifier for the convergence function
644 float converge_modifier;
647 * Recent requests by hash/uid and by time inserted.
649 static struct RecentRequests recent;
652 * Context to use to calculate find peer rates.
654 static struct FindPeerMessageContext find_peer_context;
657 * Don't use our routing algorithm, always route
658 * to closest peer; initially send requests to 3
661 static unsigned int strict_kademlia;
664 * Routing option to end routing when closest peer found.
666 static unsigned int stop_on_closest;
669 * Routing option to end routing when data is found.
671 static unsigned int stop_on_found;
674 * Whether DHT needs to manage find peer requests, or
675 * an external force will do it on behalf of the DHT.
677 static unsigned int do_find_peer;
680 * Once we have stored an item in the DHT, refresh it
681 * according to our republish interval.
683 static unsigned int do_republish;
686 * Use the "real" distance metric when selecting the
687 * next routing hop. Can be less accurate.
689 static unsigned int use_real_distance;
692 * How many peers have we added since we sent out our last
695 static unsigned int newly_found_peers;
698 * Container of active queries we should remember
700 static struct DHTResults forward_list;
703 * Handle to the datacache service (for inserting/retrieving data)
705 static struct GNUNET_DATACACHE_Handle *datacache;
708 * Handle for the statistics service.
710 struct GNUNET_STATISTICS_Handle *stats;
713 * The main scheduler to use for the DHT service
715 static struct GNUNET_SCHEDULER_Handle *sched;
718 * The configuration the DHT service is running with
720 static const struct GNUNET_CONFIGURATION_Handle *cfg;
723 * Handle to the core service
725 static struct GNUNET_CORE_Handle *coreAPI;
728 * Handle to the transport service, for getting our hello
730 static struct GNUNET_TRANSPORT_Handle *transport_handle;
733 * The identity of our peer.
735 static struct GNUNET_PeerIdentity my_identity;
738 * Short id of the peer, for printing
740 static char *my_short_id;
745 static struct GNUNET_MessageHeader *my_hello;
748 * Task to run when we shut down, cleaning up all our trash
750 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
753 * The lowest currently used bucket.
755 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
758 * The maximum number of hops before we stop routing messages.
760 static unsigned long long max_hops;
763 * How often to republish content we have previously stored.
765 static struct GNUNET_TIME_Relative dht_republish_frequency;
768 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
770 static int use_max_hops;
773 * The buckets (Kademlia routing table, complete with growth).
774 * Array of size MAX_BUCKET_SIZE.
776 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
779 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
781 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
784 * Recently seen find peer requests.
786 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
789 * Maximum size for each bucket.
791 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
794 * List of active clients.
796 static struct ClientList *client_list;
799 * Handle to the DHT logger.
801 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
804 * Whether or not to send routing debugging information
805 * to the dht logging server
807 static unsigned int debug_routes;
810 * Whether or not to send FULL route information to
813 static unsigned int debug_routes_extended;
816 * GNUNET_YES or GNUNET_NO, whether or not to act as
817 * a malicious node which drops all messages
819 static unsigned int malicious_dropper;
822 * GNUNET_YES or GNUNET_NO, whether or not to act as
823 * a malicious node which sends out lots of GETS
825 static unsigned int malicious_getter;
828 * GNUNET_YES or GNUNET_NO, whether or not to act as
829 * a malicious node which sends out lots of PUTS
831 static unsigned int malicious_putter;
834 * Frequency for malicious get requests.
836 static unsigned long long malicious_get_frequency;
839 * Frequency for malicious put requests.
841 static unsigned long long malicious_put_frequency;
844 * Reply times for requests, if we are busy, don't send any
847 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
850 * Current counter for replies.
852 static unsigned int reply_counter;
855 * Forward declaration.
857 static size_t send_generic_reply (void *cls, size_t size, void *buf);
859 /** Declare here so retry_core_send is aware of it */
860 size_t core_transmit_notify (void *cls,
861 size_t size, void *buf);
864 * Convert unique ID to hash code.
866 * @param uid unique ID to convert
867 * @param hash set to uid (extended with zeros)
870 hash_from_uid (uint64_t uid,
871 GNUNET_HashCode *hash)
873 memset (hash, 0, sizeof(GNUNET_HashCode));
874 *((uint64_t*)hash) = uid;
879 * Calculate the average send time between messages so that we can
880 * ignore certain requests if we get too busy.
882 * @return the average time between asking core to send a message
883 * and when the buffer for copying it is passed
885 static struct GNUNET_TIME_Relative get_average_send_delay()
888 unsigned int divisor;
889 struct GNUNET_TIME_Relative average_time;
890 average_time = GNUNET_TIME_relative_get_zero();
892 for (i = 0; i < MAX_REPLY_TIMES; i++)
894 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
895 if (reply_times[i].value == (uint64_t)0)
905 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
906 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
912 * Given the largest send delay, artificially decrease it
913 * so the next time around we may have a chance at sending
916 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
919 for (i = 0; i < MAX_REPLY_TIMES; i++)
921 if (reply_times[i].value == max_time.value)
923 reply_times[i].value = reply_times[i].value / 2;
930 * Find the maximum send time of the recently sent values.
932 * @return the average time between asking core to send a message
933 * and when the buffer for copying it is passed
935 static struct GNUNET_TIME_Relative get_max_send_delay()
938 struct GNUNET_TIME_Relative max_time;
939 max_time = GNUNET_TIME_relative_get_zero();
941 for (i = 0; i < MAX_REPLY_TIMES; i++)
943 if (reply_times[i].value > max_time.value)
944 max_time.value = reply_times[i].value;
947 if (max_time.value > MAX_REQUEST_TIME.value)
948 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
953 increment_stats(const char *value)
957 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
962 * Try to send another message from our core send list
965 try_core_send (void *cls,
966 const struct GNUNET_SCHEDULER_TaskContext *tc)
968 struct PeerInfo *peer = cls;
969 struct P2PPendingMessage *pending;
972 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
974 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
977 if (peer->th != NULL)
978 return; /* Message send already in progress */
980 pending = peer->head;
983 ssize = ntohs(pending->msg->size);
985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
986 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
987 "DHT", ssize, GNUNET_i2s(&peer->id));
989 pending->scheduled = GNUNET_TIME_absolute_get();
991 if (reply_counter >= MAX_REPLY_TIMES)
993 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
994 pending->timeout, &peer->id,
995 ssize, &core_transmit_notify, peer);
1000 * Function called to send a request out to another peer.
1001 * Called both for locally initiated requests and those
1002 * received from other peers.
1004 * @param cls DHT service closure argument
1005 * @param msg the encapsulated message
1006 * @param peer the peer to forward the message to
1007 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1009 static void forward_result_message (void *cls,
1010 const struct GNUNET_MessageHeader *msg,
1011 struct PeerInfo *peer,
1012 struct DHT_MessageContext *msg_ctx)
1014 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1015 struct P2PPendingMessage *pending;
1019 increment_stats(STAT_RESULT_FORWARDS);
1020 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1021 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1022 psize = sizeof(struct P2PPendingMessage) + msize;
1023 pending = GNUNET_malloc(psize);
1024 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1025 pending->importance = DHT_SEND_PRIORITY;
1026 pending->timeout = GNUNET_TIME_relative_get_forever();
1027 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1028 result_message->header.size = htons(msize);
1029 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1030 result_message->options = htonl(msg_ctx->msg_options);
1031 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1032 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1033 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1034 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1035 memcpy(&result_message[1], msg, ntohs(msg->size));
1037 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));
1039 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1040 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1041 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1044 * Called when core is ready to send a message we asked for
1045 * out to the destination.
1047 * @param cls closure (NULL)
1048 * @param size number of bytes available in buf
1049 * @param buf where the callee should write the message
1050 * @return number of bytes written to buf
1052 size_t core_transmit_notify (void *cls,
1053 size_t size, void *buf)
1055 struct PeerInfo *peer = cls;
1057 struct P2PPendingMessage *pending;
1064 /* client disconnected */
1066 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1071 if (peer->head == NULL)
1076 pending = peer->head;
1077 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1078 msize = ntohs(pending->msg->size);
1082 memcpy (cbuf, pending->msg, msize);
1083 GNUNET_CONTAINER_DLL_remove (peer->head,
1087 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));
1089 GNUNET_free (pending);
1092 while (NULL != pending &&
1093 (size - off >= (msize = ntohs (pending->msg->size))))
1095 #if DEBUG_DHT_ROUTING
1096 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);
1098 memcpy (&cbuf[off], pending->msg, msize);
1100 GNUNET_CONTAINER_DLL_remove (peer->head,
1103 GNUNET_free (pending);
1104 pending = peer->head;
1107 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1108 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1110 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);
1116 * Determine how many low order bits match in two
1117 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
1118 * the first two lowest order bits, and therefore the
1119 * return value is two (NOT XOR distance, nor how many
1120 * bits match absolutely!).
1122 * @param first the first hashcode
1123 * @param second the hashcode to compare first to
1125 * @return the number of bits that match
1127 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
1131 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
1132 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
1134 return sizeof (GNUNET_HashCode) * 8;
1138 * Compute the distance between have and target as a 32-bit value.
1139 * Differences in the lower bits must count stronger than differences
1140 * in the higher bits.
1142 * @return 0 if have==target, otherwise a number
1143 * that is larger as the distance between
1144 * the two hash codes increases
1147 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1149 unsigned int bucket;
1154 /* We have to represent the distance between two 2^9 (=512)-bit
1155 numbers as a 2^5 (=32)-bit number with "0" being used for the
1156 two numbers being identical; furthermore, we need to
1157 guarantee that a difference in the number of matching
1158 bits is always represented in the result.
1160 We use 2^32/2^9 numerical values to distinguish between
1161 hash codes that have the same LSB bit distance and
1162 use the highest 2^9 bits of the result to signify the
1163 number of (mis)matching LSB bits; if we have 0 matching
1164 and hence 512 mismatching LSB bits we return -1 (since
1165 512 itself cannot be represented with 9 bits) */
1167 /* first, calculate the most significant 9 bits of our
1168 result, aka the number of LSBs */
1169 bucket = matching_bits (target, have);
1170 /* bucket is now a value between 0 and 512 */
1172 return 0; /* perfect match */
1174 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1175 below, we'd end up with max+1 (overflow)) */
1177 /* calculate the most significant bits of the final result */
1178 msb = (512 - bucket) << (32 - 9);
1179 /* calculate the 32-9 least significant bits of the final result by
1180 looking at the differences in the 32-9 bits following the
1181 mismatching bit at 'bucket' */
1183 for (i = bucket + 1;
1184 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1186 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1187 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1188 last bit set will be 31 -- if
1189 i does not reach 512 first... */
1195 * Return a number that is larger the closer the
1196 * "have" GNUNET_hash code is to the "target".
1198 * @return inverse distance metric, non-zero.
1199 * Must fudge the value if NO bits match.
1202 inverse_distance (const GNUNET_HashCode * target,
1203 const GNUNET_HashCode * have)
1205 if (matching_bits(target, have) == 0)
1206 return 1; /* Never return 0! */
1207 return ((unsigned int) -1) - distance (target, have);
1211 * Find the optimal bucket for this key, regardless
1212 * of the current number of buckets in use.
1214 * @param hc the hashcode to compare our identity to
1216 * @return the proper bucket index, or GNUNET_SYSERR
1217 * on error (same hashcode)
1219 static int find_bucket(const GNUNET_HashCode *hc)
1223 bits = matching_bits(&my_identity.hashPubKey, hc);
1224 if (bits == MAX_BUCKETS)
1225 return GNUNET_SYSERR;
1226 return MAX_BUCKETS - bits - 1;
1230 * Find which k-bucket this peer should go into,
1231 * taking into account the size of the k-bucket
1232 * array. This means that if more bits match than
1233 * there are currently buckets, lowest_bucket will
1236 * @param hc GNUNET_HashCode we are finding the bucket for.
1238 * @return the proper bucket index for this key,
1239 * or GNUNET_SYSERR on error (same hashcode)
1241 static int find_current_bucket(const GNUNET_HashCode *hc)
1244 actual_bucket = find_bucket(hc);
1246 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1247 return GNUNET_SYSERR;
1248 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1249 return lowest_bucket;
1251 return actual_bucket;
1256 * Find a routing table entry from a peer identity
1258 * @param peer the peer to look up
1260 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1263 find_bucket_by_peer(const struct PeerInfo *peer)
1266 struct PeerInfo *pos;
1268 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1270 pos = k_buckets[bucket].head;
1279 return GNUNET_SYSERR; /* No such peer. */
1285 * Print the complete routing table for this peer.
1288 print_routing_table ()
1291 struct PeerInfo *pos;
1292 char char_buf[30000];
1294 memset(char_buf, 0, sizeof(char_buf));
1296 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1297 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1298 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1300 pos = k_buckets[bucket].head;
1301 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1302 //fprintf(stderr, "Bucket %d:\n", bucket);
1305 //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));
1306 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));
1310 fprintf(stderr, "%s", char_buf);
1316 * Find a routing table entry from a peer identity
1318 * @param peer the peer identity to look up
1320 * @return the routing table entry, or NULL if not found
1322 static struct PeerInfo *
1323 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1326 struct PeerInfo *pos;
1327 bucket = find_current_bucket(&peer->hashPubKey);
1329 if (bucket == GNUNET_SYSERR)
1332 pos = k_buckets[bucket].head;
1335 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1339 return NULL; /* No such peer. */
1342 /* Forward declaration */
1344 update_core_preference (void *cls,
1345 const struct GNUNET_SCHEDULER_TaskContext *tc);
1347 * Function called with statistics about the given peer.
1349 * @param cls closure
1350 * @param peer identifies the peer
1351 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1352 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1353 * @param amount set to the amount that was actually reserved or unreserved;
1354 * either the full requested amount or zero (no partial reservations)
1355 * @param preference current traffic preference for the given peer
1358 update_core_preference_finish (void *cls,
1359 const struct GNUNET_PeerIdentity * peer,
1360 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1361 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1362 int amount, uint64_t preference)
1364 struct PeerInfo *peer_info = cls;
1365 peer_info->info_ctx = NULL;
1366 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1370 update_core_preference (void *cls,
1371 const struct GNUNET_SCHEDULER_TaskContext *tc)
1373 struct PeerInfo *peer = cls;
1374 uint64_t preference;
1375 unsigned int matching;
1376 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1380 matching = matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1383 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching_bits);
1386 preference = 1LL << matching;
1387 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1389 GNUNET_TIME_relative_get_forever(),
1390 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1393 &update_core_preference_finish,
1398 * Really add a peer to a bucket (only do assertions
1401 * @param peer GNUNET_PeerIdentity of the peer to add
1402 * @param bucket the already figured out bucket to add
1404 * @param latency the core reported latency of this peer
1405 * @param distance the transport level distance to this peer
1407 * @return the newly added PeerInfo
1409 static struct PeerInfo *
1410 add_peer(const struct GNUNET_PeerIdentity *peer,
1411 unsigned int bucket,
1412 struct GNUNET_TIME_Relative latency,
1413 unsigned int distance)
1415 struct PeerInfo *new_peer;
1416 GNUNET_assert(bucket < MAX_BUCKETS);
1417 GNUNET_assert(peer != NULL);
1418 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1419 new_peer->latency = latency;
1420 new_peer->distance = distance;
1422 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1424 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1425 k_buckets[bucket].tail,
1426 k_buckets[bucket].tail,
1428 k_buckets[bucket].peers_size++;
1430 if ((matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1432 #if DO_UPDATE_PREFERENCE
1433 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1441 * Given a peer and its corresponding bucket,
1442 * remove it from that bucket. Does not free
1443 * the PeerInfo struct, nor cancel messages
1444 * or free messages waiting to be sent to this
1447 * @param peer the peer to remove
1448 * @param bucket the bucket the peer belongs to
1450 static void remove_peer (struct PeerInfo *peer,
1451 unsigned int bucket)
1453 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1454 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1455 k_buckets[bucket].tail,
1457 k_buckets[bucket].peers_size--;
1459 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1465 * Removes peer from a bucket, then frees associated
1466 * resources and frees peer.
1468 * @param peer peer to be removed and freed
1469 * @param bucket which bucket this peer belongs to
1471 static void delete_peer (struct PeerInfo *peer,
1472 unsigned int bucket)
1474 struct P2PPendingMessage *pos;
1475 struct P2PPendingMessage *next;
1477 struct PeerInfo *peer_pos;
1479 peer_pos = k_buckets[bucket].head;
1480 while ((peer_pos != NULL) && (peer_pos != peer))
1481 peer_pos = peer_pos->next;
1482 if (peer_pos == NULL)
1484 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1485 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));
1487 GNUNET_assert(peer_pos != NULL);
1489 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1491 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1492 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1493 if (peer->th != NULL)
1494 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1497 while (pos != NULL) /* Remove any pending messages for this peer */
1504 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1505 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1511 * Iterator over hash map entries.
1513 * @param cls closure
1514 * @param key current key code
1515 * @param value PeerInfo of the peer to move to new lowest bucket
1516 * @return GNUNET_YES if we should continue to
1520 static int move_lowest_bucket (void *cls,
1521 const GNUNET_HashCode * key,
1524 struct PeerInfo *peer = value;
1527 GNUNET_assert(lowest_bucket > 0);
1528 new_bucket = lowest_bucket - 1;
1529 remove_peer(peer, lowest_bucket);
1530 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1531 k_buckets[new_bucket].tail,
1532 k_buckets[new_bucket].tail,
1534 k_buckets[new_bucket].peers_size++;
1540 * The current lowest bucket is full, so change the lowest
1541 * bucket to the next lower down, and move any appropriate
1542 * entries in the current lowest bucket to the new bucket.
1544 static void enable_next_bucket()
1546 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1547 struct PeerInfo *pos;
1548 GNUNET_assert(lowest_bucket > 0);
1549 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1550 pos = k_buckets[lowest_bucket].head;
1553 fprintf(stderr, "Printing RT before new bucket\n");
1554 print_routing_table();
1556 /* Populate the array of peers which should be in the next lowest bucket */
1559 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1560 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1564 /* Remove peers from lowest bucket, insert into next lowest bucket */
1565 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1566 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1567 lowest_bucket = lowest_bucket - 1;
1569 fprintf(stderr, "Printing RT after new bucket\n");
1570 print_routing_table();
1575 * Find the closest peer in our routing table to the
1578 * @return The closest peer in our routing table to the
1579 * key, or NULL on error.
1581 static struct PeerInfo *
1582 find_closest_peer (const GNUNET_HashCode *hc)
1584 struct PeerInfo *pos;
1585 struct PeerInfo *current_closest;
1586 unsigned int lowest_distance;
1587 unsigned int temp_distance;
1591 lowest_distance = -1;
1593 if (k_buckets[lowest_bucket].peers_size == 0)
1596 current_closest = NULL;
1597 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1599 pos = k_buckets[bucket].head;
1601 while ((pos != NULL) && (count < bucket_size))
1603 temp_distance = distance(&pos->id.hashPubKey, hc);
1604 if (temp_distance <= lowest_distance)
1606 lowest_distance = temp_distance;
1607 current_closest = pos;
1613 GNUNET_assert(current_closest != NULL);
1614 return current_closest;
1619 * Function called to send a request out to another peer.
1620 * Called both for locally initiated requests and those
1621 * received from other peers.
1623 * @param cls DHT service closure argument (unused)
1624 * @param msg the encapsulated message
1625 * @param peer the peer to forward the message to
1626 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1628 static void forward_message (void *cls,
1629 const struct GNUNET_MessageHeader *msg,
1630 struct PeerInfo *peer,
1631 struct DHT_MessageContext *msg_ctx)
1633 struct GNUNET_DHT_P2PRouteMessage *route_message;
1634 struct P2PPendingMessage *pending;
1638 increment_stats(STAT_ROUTE_FORWARDS);
1640 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1641 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1643 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1644 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1645 psize = sizeof(struct P2PPendingMessage) + msize;
1646 pending = GNUNET_malloc(psize);
1647 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1648 pending->importance = msg_ctx->importance;
1649 pending->timeout = msg_ctx->timeout;
1650 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1651 route_message->header.size = htons(msize);
1652 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1653 route_message->options = htonl(msg_ctx->msg_options);
1654 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1655 route_message->network_size = htonl(msg_ctx->network_size);
1656 route_message->desired_replication_level = htonl(msg_ctx->replication);
1657 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1658 if (msg_ctx->bloom != NULL)
1659 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1660 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1661 memcpy(&route_message[1], msg, ntohs(msg->size));
1663 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));
1665 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1666 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1667 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1672 * Task used to send ping messages to peers so that
1673 * they don't get disconnected.
1675 * @param cls the peer to send a ping message to
1676 * @param tc context, reason, etc.
1679 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1681 struct PeerInfo *peer = cls;
1682 struct GNUNET_MessageHeader ping_message;
1683 struct DHT_MessageContext message_context;
1685 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1688 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1689 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1691 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1693 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1695 forward_message(NULL, &ping_message, peer, &message_context);
1696 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1700 * Schedule PING messages for the top X peers in each
1701 * bucket of the routing table (so core won't disconnect them!)
1703 void schedule_ping_messages()
1705 unsigned int bucket;
1707 struct PeerInfo *pos;
1708 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1710 pos = k_buckets[bucket].head;
1714 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1715 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1716 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1718 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1719 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1729 * Attempt to add a peer to our k-buckets.
1731 * @param peer the peer identity of the peer being added
1732 * @param bucket the bucket that we want this peer to go in
1733 * @param latency transport latency of this peer
1734 * @param distance transport distance to this peer
1736 * @return NULL if the peer was not added,
1737 * pointer to PeerInfo for new peer otherwise
1739 static struct PeerInfo *
1740 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1741 unsigned int bucket,
1742 struct GNUNET_TIME_Relative latency,
1743 unsigned int distance)
1746 struct PeerInfo *new_peer;
1747 peer_bucket = find_current_bucket(&peer->hashPubKey);
1748 if (peer_bucket == GNUNET_SYSERR)
1751 GNUNET_assert(peer_bucket >= lowest_bucket);
1752 new_peer = add_peer(peer, peer_bucket, latency, distance);
1754 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1755 enable_next_bucket();
1757 schedule_ping_messages();
1764 * Task run to check for messages that need to be sent to a client.
1766 * @param client a ClientList, containing the client and any messages to be sent to it
1769 process_pending_messages (struct ClientList *client)
1771 if (client->pending_head == NULL)
1773 if (client->transmit_handle != NULL)
1775 client->transmit_handle =
1776 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1777 ntohs (client->pending_head->msg->
1779 GNUNET_TIME_UNIT_FOREVER_REL,
1780 &send_generic_reply, client);
1784 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1785 * request. A ClientList is passed as closure, take the head of the list
1786 * and copy it into buf, which has the result of sending the message to the
1789 * @param cls closure to this call
1790 * @param size maximum number of bytes available to send
1791 * @param buf where to copy the actual message to
1793 * @return the number of bytes actually copied, 0 indicates failure
1796 send_generic_reply (void *cls, size_t size, void *buf)
1798 struct ClientList *client = cls;
1800 struct PendingMessage *reply;
1804 client->transmit_handle = NULL;
1807 /* client disconnected */
1811 while ( (NULL != (reply = client->pending_head)) &&
1812 (size >= off + (msize = ntohs (reply->msg->size))))
1814 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1815 client->pending_tail,
1817 memcpy (&cbuf[off], reply->msg, msize);
1818 GNUNET_free (reply);
1821 process_pending_messages (client);
1827 * Add a PendingMessage to the clients list of messages to be sent
1829 * @param client the active client to send the message to
1830 * @param pending_message the actual message to send
1833 add_pending_message (struct ClientList *client,
1834 struct PendingMessage *pending_message)
1836 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1837 client->pending_tail,
1838 client->pending_tail,
1840 process_pending_messages (client);
1847 * Called when a reply needs to be sent to a client, as
1848 * a result it found to a GET or FIND PEER request.
1850 * @param client the client to send the reply to
1851 * @param message the encapsulated message to send
1852 * @param uid the unique identifier of this request
1855 send_reply_to_client (struct ClientList *client,
1856 const struct GNUNET_MessageHeader *message,
1857 unsigned long long uid)
1859 struct GNUNET_DHT_RouteResultMessage *reply;
1860 struct PendingMessage *pending_message;
1864 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1865 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1867 msize = ntohs (message->size);
1868 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1869 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1871 GNUNET_break_op (0);
1875 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1876 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1877 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1878 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1879 reply->header.size = htons (tsize);
1880 reply->unique_id = GNUNET_htonll (uid);
1881 memcpy (&reply[1], message, msize);
1883 add_pending_message (client, pending_message);
1887 * Consider whether or not we would like to have this peer added to
1888 * our routing table. Check whether bucket for this peer is full,
1889 * if so return negative; if not return positive. Since peers are
1890 * only added on CORE level connect, this doesn't actually add the
1891 * peer to the routing table.
1893 * @param peer the peer we are considering adding
1895 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1898 * FIXME: Think about making a context for this call so that we can
1899 * ping the oldest peer in the current bucket and consider
1900 * removing it in lieu of the new peer.
1902 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1906 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1907 return GNUNET_NO; /* We already know this peer (are connected even!) */
1908 bucket = find_current_bucket(&peer->hashPubKey);
1909 if (bucket == GNUNET_SYSERR)
1911 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1918 * Main function that handles whether or not to route a result
1919 * message to other peers, or to send to our local client.
1921 * @param cls closure (unused, always should be NULL)
1922 * @param msg the result message to be routed
1923 * @param message_context context of the message we are routing
1925 * @return the number of peers the message was routed to,
1926 * GNUNET_SYSERR on failure
1928 static int route_result_message(void *cls,
1929 struct GNUNET_MessageHeader *msg,
1930 struct DHT_MessageContext *message_context)
1932 struct GNUNET_PeerIdentity new_peer;
1933 struct DHTQueryRecord *record;
1934 struct DHTRouteSource *pos;
1935 struct PeerInfo *peer_info;
1936 const struct GNUNET_MessageHeader *hello_msg;
1938 increment_stats(STAT_RESULTS);
1940 * If a find peer result message is received and contains a valid
1941 * HELLO for another peer, offer it to the transport service.
1943 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1945 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1948 hello_msg = &msg[1];
1949 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1951 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1955 else /* We have a valid hello, and peer id stored in new_peer */
1957 find_peer_context.count++;
1958 increment_stats(STAT_FIND_PEER_REPLY);
1959 if (GNUNET_YES == consider_peer(&new_peer))
1961 increment_stats(STAT_HELLOS_PROVIDED);
1962 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1963 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1968 if (malicious_dropper == GNUNET_YES)
1971 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1973 if (record == NULL) /* No record of this message! */
1976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1977 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1978 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1980 #if DEBUG_DHT_ROUTING
1981 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1983 dhtlog_handle->insert_route (NULL,
1984 message_context->unique_id,
1986 message_context->hop_count,
1989 &message_context->key,
1990 message_context->peer, NULL);
1993 if (message_context->bloom != NULL)
1995 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1996 message_context->bloom = NULL;
2004 #if STRICT_FORWARDING
2005 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2007 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2009 increment_stats("# find peer responses NOT forwarded (bloom match)");
2014 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2018 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2021 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2022 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2023 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2025 #if DEBUG_DHT_ROUTING
2026 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2028 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2029 message_context->hop_count,
2030 GNUNET_YES, &my_identity, &message_context->key,
2031 message_context->peer, NULL);
2034 increment_stats(STAT_RESULTS_TO_CLIENT);
2035 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2036 increment_stats(STAT_GET_REPLY);
2038 send_reply_to_client(pos->client, msg, message_context->unique_id);
2040 else /* Send to peer */
2042 peer_info = find_peer_by_id(&pos->source);
2043 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2049 if (message_context->bloom == NULL)
2050 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2051 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2052 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2055 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2056 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2057 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2059 #if DEBUG_DHT_ROUTING
2060 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2062 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2064 message_context->hop_count,
2065 GNUNET_NO, &my_identity, &message_context->key,
2066 message_context->peer, &pos->source);
2069 forward_result_message(cls, msg, peer_info, message_context);
2074 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2075 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2076 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2082 if (message_context->bloom != NULL)
2083 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2088 * Iterator for local get request results,
2090 * @param cls closure for iterator, a DatacacheGetContext
2091 * @param exp when does this value expire?
2092 * @param key the key this data is stored under
2093 * @param size the size of the data identified by key
2094 * @param data the actual data
2095 * @param type the type of the data
2097 * @return GNUNET_OK to continue iteration, anything else
2098 * to stop iteration.
2101 datacache_get_iterator (void *cls,
2102 struct GNUNET_TIME_Absolute exp,
2103 const GNUNET_HashCode * key,
2104 uint32_t size, const char *data, uint32_t type)
2106 struct DHT_MessageContext *msg_ctx = cls;
2107 struct DHT_MessageContext *new_msg_ctx;
2108 struct GNUNET_DHT_GetResultMessage *get_result;
2110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2111 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2113 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2114 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2116 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2117 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2118 get_result->header.size =
2119 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2120 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2121 get_result->type = htons (type);
2122 memcpy (&get_result[1], data, size);
2123 new_msg_ctx->peer = &my_identity;
2124 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2125 new_msg_ctx->hop_count = 0;
2126 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2127 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2128 increment_stats(STAT_GET_RESPONSE_START);
2129 route_result_message(cls, &get_result->header, new_msg_ctx);
2130 GNUNET_free(new_msg_ctx);
2131 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2132 // datacache_get_ctx->unique_id);
2133 GNUNET_free (get_result);
2139 * Server handler for all dht get requests, look for data,
2140 * if found, send response either to clients or other peers.
2142 * @param cls closure for service
2143 * @param msg the actual get message
2144 * @param message_context struct containing pertinent information about the get request
2146 * @return number of items found for GET request
2149 handle_dht_get (void *cls,
2150 const struct GNUNET_MessageHeader *msg,
2151 struct DHT_MessageContext *message_context)
2153 const struct GNUNET_DHT_GetMessage *get_msg;
2155 unsigned int results;
2157 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2158 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2164 get_type = ntohs (get_msg->type);
2166 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2167 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2168 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2169 message_context->unique_id);
2171 increment_stats(STAT_GETS);
2173 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2176 if (datacache != NULL)
2178 GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2179 &datacache_get_iterator, message_context);
2184 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2185 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2186 results, "GET", message_context->unique_id);
2188 #if DEBUG_DHT_ROUTING
2189 if ((debug_routes) && (dhtlog_handle != NULL))
2191 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2192 message_context->hop_count, GNUNET_YES, &my_identity,
2193 &message_context->key);
2196 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2198 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2199 message_context->hop_count, GNUNET_YES,
2200 &my_identity, &message_context->key, message_context->peer,
2206 if (message_context->hop_count == 0) /* Locally initiated request */
2208 #if DEBUG_DHT_ROUTING
2209 if ((debug_routes) && (dhtlog_handle != NULL))
2211 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2212 message_context->hop_count, GNUNET_NO, &my_identity,
2213 &message_context->key);
2222 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2224 GNUNET_HashCode *key = cls;
2225 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2232 * Server handler for initiating local dht find peer requests
2234 * @param cls closure for service
2235 * @param find_msg the actual find peer message
2236 * @param message_context struct containing pertinent information about the request
2240 handle_dht_find_peer (void *cls,
2241 const struct GNUNET_MessageHeader *find_msg,
2242 struct DHT_MessageContext *message_context)
2244 struct GNUNET_MessageHeader *find_peer_result;
2245 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2246 struct DHT_MessageContext *new_msg_ctx;
2247 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2250 GNUNET_HashCode *recent_hash;
2251 #if RESTRICT_FIND_PEER
2252 struct GNUNET_PeerIdentity peer_id;
2255 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2257 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2258 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2259 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2260 ntohs (find_msg->size),
2261 sizeof (struct GNUNET_MessageHeader));
2263 if (my_hello == NULL)
2266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2267 "`%s': Our HELLO is null, can't return.\n",
2273 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2274 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2276 increment_stats(STAT_BLOOM_FIND_PEER);
2277 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2278 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2280 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2282 #if RESTRICT_FIND_PEER
2285 * Ignore any find peer requests from a peer we have seen very recently.
2287 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! */
2289 increment_stats("# dht find peer requests ignored (recently seen!)");
2294 * Use this check to only allow the peer to respond to find peer requests if
2295 * it would be beneficial to have the requesting peer in this peers routing
2296 * table. Can be used to thwart peers flooding the network with find peer
2297 * requests that we don't care about. However, if a new peer is joining
2298 * the network and has no other peers this is a problem (assume all buckets
2299 * full, no one will respond!).
2301 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2302 if (GNUNET_NO == consider_peer(&peer_id))
2304 increment_stats("# dht find peer requests ignored (do not need!)");
2309 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2310 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2311 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2312 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2314 /* Simplistic find_peer functionality, always return our hello */
2315 hello_size = ntohs(my_hello->size);
2316 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2318 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2320 GNUNET_break_op (0);
2324 find_peer_result = GNUNET_malloc (tsize);
2325 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2326 find_peer_result->size = htons (tsize);
2327 memcpy (&find_peer_result[1], my_hello, hello_size);
2329 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2330 "`%s': Sending hello size %d to requesting peer.\n",
2333 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2334 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2335 new_msg_ctx->peer = &my_identity;
2336 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2337 new_msg_ctx->hop_count = 0;
2338 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2339 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2340 increment_stats(STAT_FIND_PEER_ANSWER);
2341 route_result_message(cls, find_peer_result, new_msg_ctx);
2342 GNUNET_free(new_msg_ctx);
2343 #if DEBUG_DHT_ROUTING
2344 if ((debug_routes) && (dhtlog_handle != NULL))
2346 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2347 message_context->hop_count, GNUNET_YES, &my_identity,
2348 &message_context->key);
2351 GNUNET_free(find_peer_result);
2355 * Task used to republish data.
2356 * Forward declaration; function call loop.
2358 * @param cls closure (a struct RepublishContext)
2359 * @param tc runtime context for this task
2362 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2365 * Server handler for initiating local dht put requests
2367 * @param cls closure for service
2368 * @param msg the actual put message
2369 * @param message_context struct containing pertinent information about the request
2372 handle_dht_put (void *cls,
2373 const struct GNUNET_MessageHeader *msg,
2374 struct DHT_MessageContext *message_context)
2376 struct GNUNET_DHT_PutMessage *put_msg;
2380 struct RepublishContext *put_context;
2382 GNUNET_assert (ntohs (msg->size) >=
2383 sizeof (struct GNUNET_DHT_PutMessage));
2386 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2387 put_type = ntohs (put_msg->type);
2389 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2392 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2394 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2395 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2396 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2398 #if DEBUG_DHT_ROUTING
2399 if (message_context->hop_count == 0) /* Locally initiated request */
2401 if ((debug_routes) && (dhtlog_handle != NULL))
2403 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2404 message_context->hop_count, GNUNET_NO, &my_identity,
2405 &message_context->key);
2410 if (message_context->closest != GNUNET_YES)
2413 #if DEBUG_DHT_ROUTING
2414 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2416 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2417 message_context->hop_count, GNUNET_YES,
2418 &my_identity, &message_context->key, message_context->peer,
2422 if ((debug_routes) && (dhtlog_handle != NULL))
2424 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2425 message_context->hop_count, GNUNET_YES, &my_identity,
2426 &message_context->key);
2430 increment_stats(STAT_PUTS_INSERTED);
2431 if (datacache != NULL)
2433 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2434 (char *) &put_msg[1], put_type,
2435 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2437 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2439 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2440 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2441 put_context->type = put_type;
2442 GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
2446 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2447 "`%s:%s': %s request received, but have no datacache!\n",
2448 my_short_id, "DHT", "PUT");
2452 * Estimate the diameter of the network based
2453 * on how many buckets are currently in use.
2454 * Concept here is that the diameter of the network
2455 * is roughly the distance a message must travel in
2456 * order to reach its intended destination. Since
2457 * at each hop we expect to get one bit closer, and
2458 * we have one bit per bucket, the number of buckets
2459 * in use should be the largest number of hops for
2460 * a sucessful message. (of course, this assumes we
2461 * know all peers in the network!)
2463 * @return ballpark diameter figure
2465 static unsigned int estimate_diameter()
2467 return MAX_BUCKETS - lowest_bucket;
2471 * To how many peers should we (on average)
2472 * forward the request to obtain the desired
2473 * target_replication count (on average).
2475 * Always 0, 1 or 2 (don't send, send once, split)
2478 get_forward_count (unsigned int hop_count, size_t target_replication)
2481 double target_count;
2482 double random_probability;
2484 uint32_t random_value;
2486 unsigned int target_value;
2487 unsigned int diameter;
2490 * If we are behaving in strict kademlia mode, send multiple initial requests,
2491 * but then only send to 1 or 0 peers based strictly on the number of hops.
2493 if (strict_kademlia == GNUNET_YES)
2496 return DHT_KADEMLIA_REPLICATION;
2497 else if (hop_count < max_hops)
2503 /* FIXME: the smaller we think the network is the more lenient we should be for
2504 * routing right? The estimation below only works if we think we have reasonably
2505 * full routing tables, which for our RR topologies may not be the case!
2507 diameter = estimate_diameter ();
2508 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2511 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2512 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2513 "DHT", estimate_diameter(), lowest_bucket);
2517 else if (hop_count > max_hops)
2520 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2521 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2528 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2529 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2530 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2531 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2532 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2533 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2534 RAND_MAX)) / RAND_MAX;
2535 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2538 //while (target_value < target_count)
2539 if (target_value < target_count)
2540 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? */
2543 //if ((target_count + 1 - (double)target_value) > random_probability)
2544 if ((target_count) > random_probability)
2548 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2549 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));
2551 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2552 if (random_value < target_replication)
2555 return target_value;
2559 * Check whether my identity is closer than any known peers.
2560 * If a non-null bloomfilter is given, check if this is the closest
2561 * peer that hasn't already been routed to.
2563 * @param target hash code to check closeness to
2564 * @param bloom bloomfilter, exclude these entries from the decision
2566 * Return GNUNET_YES if node location is closest, GNUNET_NO
2570 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2576 struct PeerInfo *pos;
2577 unsigned int my_distance;
2579 bucket_num = find_current_bucket(target);
2580 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2583 bits = matching_bits(&my_identity.hashPubKey, target);
2584 my_distance = distance(&my_identity.hashPubKey, target);
2585 pos = k_buckets[bucket_num].head;
2587 while ((pos != NULL) && (count < bucket_size))
2589 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2592 continue; /* Skip already checked entries */
2595 other_bits = matching_bits(&pos->id.hashPubKey, target);
2596 if (other_bits > bits)
2598 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2600 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2602 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2609 GNUNET_GE_LOG (coreAPI->ectx,
2610 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2611 GNUNET_GE_BULK, "closest peer\n");
2612 printPeerBits (&closest);
2613 GNUNET_GE_LOG (coreAPI->ectx,
2614 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2615 GNUNET_GE_BULK, "me\n");
2616 printPeerBits (coreAPI->my_identity);
2617 GNUNET_GE_LOG (coreAPI->ectx,
2618 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2619 GNUNET_GE_BULK, "key\n");
2620 printKeyBits (target);
2621 GNUNET_GE_LOG (coreAPI->ectx,
2622 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2624 "closest peer inverse distance is %u, mine is %u\n",
2625 inverse_distance (target, &closest.hashPubKey),
2626 inverse_distance (target,
2627 &coreAPI->my_identity->hashPubKey));
2630 /* No peers closer, we are the closest! */
2636 * Decide whether to route this request exclusively
2637 * to a closer peer (if closer peers exist) or to choose
2638 * from the whole set of peers.
2640 * @param target the key of the request
2641 * @param bloom bloomfilter of peers this request has already traversed
2642 * @param hops number of hops this message has already traveled
2644 * @return GNUNET_YES if we should try to route to a closer peer
2645 * than ourselves (and one exists), GNUNET_NO if we should
2646 * choose from the set of all known peers
2650 route_closer (const GNUNET_HashCode *target,
2651 struct GNUNET_CONTAINER_BloomFilter *bloom,
2654 unsigned int my_matching_bits;
2656 uint32_t random_value;
2657 struct PeerInfo *pos;
2662 my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2664 if (GNUNET_YES == use_max_hops)
2665 curr_max_hops = max_hops;
2667 curr_max_hops = max_hops; /* FIXME: replace with heuristic! */
2669 * First check if we know any close (as close as us or closer) peers.
2671 have_closer = GNUNET_NO;
2673 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2675 pos = k_buckets[bc].head;
2677 while ((pos != NULL) && (count < bucket_size))
2679 if ((matching_bits(target, &pos->id.hashPubKey) > my_matching_bits) &&
2680 (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
2682 have_closer = GNUNET_YES;
2688 if (have_closer == GNUNET_YES)
2692 if (have_closer == GNUNET_NO) /* We don't have a same distance or closer node, can't enforce closer only! */
2695 switch (converge_option)
2697 case DHT_CONVERGE_LINEAR:
2699 * Simple linear curve for choosing whether or not to converge.
2700 * Choose to route only closer with probability hops/MAX_HOPS.
2702 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, curr_max_hops);
2703 if (random_value < hops)
2707 case DHT_CONVERGE_SQUARE:
2709 * Simple square based curve.
2711 if ((GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1) / (double)(uint32_t)-1) < (sqrt(hops) / sqrt(curr_max_hops)))
2715 case DHT_CONVERGE_EXPONENTIAL:
2717 * Simple exponential curve.
2719 if (converge_modifier > 0)
2720 calc_value = ((converge_modifier * (hops * hops)) / (curr_max_hops * curr_max_hops)) / curr_max_hops;
2722 calc_value = ((hops * hops) / (curr_max_hops * curr_max_hops)) / curr_max_hops;
2724 if ((GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1) / (double)(uint32_t)-1) < calc_value)
2735 * Select a peer from the routing table that would be a good routing
2736 * destination for sending a message for "target". The resulting peer
2737 * must not be in the set of blocked peers.<p>
2739 * Note that we should not ALWAYS select the closest peer to the
2740 * target, peers further away from the target should be chosen with
2741 * exponentially declining probability.
2743 * @param target the key we are selecting a peer to route to
2744 * @param bloom a bloomfilter containing entries this request has seen already
2745 * @param hops the number of hops this message has already traversed
2747 * @return Peer to route to, or NULL on error
2749 static struct PeerInfo *
2750 select_peer (const GNUNET_HashCode * target,
2751 struct GNUNET_CONTAINER_BloomFilter *bloom,
2754 unsigned int distance;
2757 unsigned int my_matching_bits;
2758 unsigned long long largest_distance;
2759 unsigned long long total_real_distance;
2760 unsigned long long real_selected;
2761 unsigned int total_distance;
2762 unsigned int selected;
2763 unsigned int match_num;
2765 struct PeerInfo *pos;
2766 struct PeerInfo *chosen;
2768 #if DEBUG_DHT_ROUTING > 1
2772 my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2773 only_closer = route_closer(target, bloom, hops);
2775 if (GNUNET_YES == only_closer)
2777 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "only routing to closer peers!\n");
2778 GNUNET_asprintf(&temp_stat, "# closer only routes at hop %u", hops);
2779 increment_stats(temp_stat);
2783 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "routing to all possible peers!\n");
2784 GNUNET_asprintf(&temp_stat, "# NOT closer only routes at hop %u", hops);
2785 increment_stats(temp_stat);
2788 GNUNET_free(temp_stat);
2789 total_real_distance = 0;
2790 if (strict_kademlia == GNUNET_YES)
2792 largest_distance = 0;
2794 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2796 pos = k_buckets[bc].head;
2798 while ((pos != NULL) && (count < bucket_size))
2800 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2801 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2803 distance = inverse_distance (target, &pos->id.hashPubKey);
2804 if (distance > largest_distance)
2807 largest_distance = distance;
2815 if ((largest_distance > 0) && (chosen != NULL))
2817 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2829 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2831 pos = k_buckets[bc].head;
2833 while ((pos != NULL) && (count < bucket_size))
2835 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2836 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2838 if (GNUNET_YES == use_real_distance)
2839 total_real_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2842 /* Always add 1, in case 0 bits match! */
2843 match_num = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target ,&pos->id.hashPubKey));
2844 total_distance += match_num;
2848 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2849 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2850 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2857 if (((GNUNET_YES == use_real_distance) && (total_real_distance == 0)) || (total_distance == 0))
2859 increment_stats("# select_peer, total_distance == 0");
2863 #if DEBUG_DHT_ROUTING > 1
2865 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2867 pos = k_buckets[bc].head;
2869 while ((pos != NULL) && (count < bucket_size))
2871 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2872 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2874 if (GNUNET_YES == use_real_distance)
2876 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "REAL: Choose peer with %d matching bits (%.2f percent)\n", matching_bits(&pos->id.hashPubKey, target), (inverse_distance (target, &pos->id.hashPubKey) / (double)total_real_distance) * 100);
2877 sum += inverse_distance (target, &pos->id.hashPubKey) / (double)total_real_distance;
2881 match_num = 1 + (matching_bits(&pos->id.hashPubKey, target) * matching_bits(&pos->id.hashPubKey, target));
2882 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose peer with %d matching bits (%.2f percent)\n", matching_bits(&pos->id.hashPubKey, target), (match_num / (double)total_distance) * 100);
2883 sum += match_num / (double)total_distance;
2893 if (use_real_distance)
2895 GNUNET_assert(total_real_distance != 0);
2896 real_selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_real_distance);
2900 GNUNET_assert(total_distance != 0);
2901 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2904 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2906 pos = k_buckets[bc].head;
2908 while ((pos != NULL) && (count < bucket_size))
2910 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2911 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2913 if (GNUNET_YES == use_real_distance)
2915 distance = inverse_distance (target, &pos->id.hashPubKey);
2916 if (distance > real_selected)
2918 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "(REAL) Selected peer with %u matching bits to route to\n", matching_bits(target, &pos->id.hashPubKey));
2921 real_selected -= distance;
2925 distance = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target, &pos->id.hashPubKey));
2926 if (distance > selected)
2928 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Selected peer with %u matching bits to route to\n", matching_bits(target, &pos->id.hashPubKey));
2931 selected -= distance;
2937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2938 "`%s:%s': peer %s matches bloomfilter.\n",
2939 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2947 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2948 "`%s:%s': peer %s matches bloomfilter.\n",
2949 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2951 increment_stats("# failed to select peer");
2952 GNUNET_assert(only_closer == GNUNET_NO);
2958 * Task used to remove recent entries, either
2959 * after timeout, when full, or on shutdown.
2961 * @param cls the entry to remove
2962 * @param tc context, reason, etc.
2965 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2967 struct RecentRequest *req = cls;
2968 static GNUNET_HashCode hash;
2970 GNUNET_assert(req != NULL);
2971 hash_from_uid(req->uid, &hash);
2972 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
2973 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
2974 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
2977 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
2979 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
2980 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
2986 * Task used to remove forwarding entries, either
2987 * after timeout, when full, or on shutdown.
2989 * @param cls the entry to remove
2990 * @param tc context, reason, etc.
2993 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2995 struct DHTRouteSource *source_info = cls;
2996 struct DHTQueryRecord *record;
2997 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2998 record = source_info->record;
2999 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3001 if (record->head == NULL) /* No more entries in DLL */
3003 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3004 GNUNET_free(record);
3006 if (source_info->find_peers_responded != NULL)
3007 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3008 GNUNET_free(source_info);
3012 * Remember this routing request so that if a reply is
3013 * received we can either forward it to the correct peer
3014 * or return the result locally.
3016 * @param cls DHT service closure
3017 * @param msg_ctx Context of the route request
3019 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3021 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
3023 struct DHTQueryRecord *record;
3024 struct DHTRouteSource *source_info;
3025 struct DHTRouteSource *pos;
3026 struct GNUNET_TIME_Absolute now;
3027 unsigned int current_size;
3029 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3030 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3032 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3033 GNUNET_assert(source_info != NULL);
3034 record = source_info->record;
3035 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3036 if (record->head == NULL) /* No more entries in DLL */
3038 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3039 GNUNET_free(record);
3041 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
3042 if (source_info->find_peers_responded != NULL)
3043 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3044 GNUNET_free(source_info);
3045 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3047 now = GNUNET_TIME_absolute_get();
3048 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3049 if (record != NULL) /* Already know this request! */
3054 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3055 break; /* Already have this peer in reply list! */
3058 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3060 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3066 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3067 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3068 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3071 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3072 source_info->record = record;
3073 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3074 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3075 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3076 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3077 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3079 source_info->client = msg_ctx->client;
3080 now = GNUNET_TIME_absolute_get_forever();
3082 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3084 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3085 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3086 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
3093 * Main function that handles whether or not to route a message to other
3096 * @param cls closure for dht service (NULL)
3097 * @param msg the message to be routed
3098 * @param message_context the context containing all pertinent information about the message
3100 * @return the number of peers the message was routed to,
3101 * GNUNET_SYSERR on failure
3103 static int route_message(void *cls,
3104 const struct GNUNET_MessageHeader *msg,
3105 struct DHT_MessageContext *message_context)
3109 struct PeerInfo *selected;
3110 #if DEBUG_DHT_ROUTING > 1
3111 struct PeerInfo *nearest;
3113 unsigned int forward_count;
3114 struct RecentRequest *recent_req;
3115 GNUNET_HashCode unique_hash;
3116 char *stat_forward_count;
3117 #if DEBUG_DHT_ROUTING
3121 if (malicious_dropper == GNUNET_YES)
3123 #if DEBUG_DHT_ROUTING
3124 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3126 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3127 message_context->hop_count, GNUNET_SYSERR,
3128 &my_identity, &message_context->key, message_context->peer,
3132 if (message_context->bloom != NULL)
3133 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3137 increment_stats(STAT_ROUTES);
3138 /* Semantics of this call means we find whether we are the closest peer out of those already
3139 * routed to on this messages path.
3141 global_closest = am_closest_peer(&message_context->key, NULL);
3142 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3143 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3144 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3145 increment_stats(stat_forward_count);
3146 GNUNET_free(stat_forward_count);
3147 if (message_context->bloom == NULL)
3148 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3150 if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3154 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3155 * any closer peers (which is being checked for below). Since we are doing recursive
3156 * routing we have no choice but to stop forwarding in this case. This means that at
3157 * any given step the request may NOT be forwarded to alpha peers (because routes will
3158 * stop and the parallel route will not be aware of it). Of course, assuming that we
3159 * have fulfilled the Kademlia requirements for routing table fullness this will never
3160 * ever ever be a problem.
3162 * However, is this fair?
3164 * Since we use these requests to build our routing tables (and we build them in the
3165 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3166 * routing tables still get constructed.
3168 if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3171 #if DEBUG_DHT_ROUTING
3172 if (forward_count == 0)
3173 ret = GNUNET_SYSERR;
3177 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3179 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3180 message_context->hop_count, ret,
3181 &my_identity, &message_context->key, message_context->peer,
3186 switch (ntohs(msg->type))
3188 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3189 cache_response (cls, message_context);
3190 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3193 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3194 increment_stats(STAT_PUTS);
3195 message_context->closest = global_closest;
3196 handle_dht_put (cls, msg, message_context);
3198 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3199 increment_stats(STAT_FIND_PEER);
3200 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3202 cache_response (cls, message_context);
3203 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3204 handle_dht_find_peer (cls, msg, message_context);
3206 #if DEBUG_DHT_ROUTING
3207 if (message_context->hop_count == 0) /* Locally initiated request */
3209 if ((debug_routes) && (dhtlog_handle != NULL))
3211 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3212 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3213 message_context->hop_count, GNUNET_NO, &my_identity,
3214 &message_context->key);
3220 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3221 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3224 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3225 hash_from_uid (message_context->unique_id, &unique_hash);
3226 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3228 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3229 GNUNET_assert(recent_req != NULL);
3230 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3231 increment_stats(STAT_DUPLICATE_UID);
3234 increment_stats(STAT_RECENT_SEEN);
3235 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3240 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3241 recent_req->uid = message_context->unique_id;
3242 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3243 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3244 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3245 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3246 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3249 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3251 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3252 GNUNET_assert(recent_req != NULL);
3253 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3254 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3257 for (i = 0; i < forward_count; i++)
3259 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3261 if (selected != NULL)
3263 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3264 #if DEBUG_DHT_ROUTING > 1
3265 nearest = find_closest_peer(&message_context->key);
3266 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3268 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3269 "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));
3270 GNUNET_free(nearest_buf);
3272 #if DEBUG_DHT_ROUTING
3273 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3275 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3276 message_context->hop_count, GNUNET_NO,
3277 &my_identity, &message_context->key, message_context->peer,
3281 forward_message(cls, msg, selected, message_context);
3285 increment_stats("# NULL returned from select_peer");
3286 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3287 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
3292 #if DEBUG_DHT_ROUTING > 1
3293 if (forward_count == 0)
3295 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3296 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
3297 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
3301 if (message_context->bloom != NULL)
3303 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3304 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3307 return forward_count;
3311 * Iterator for local get request results,
3313 * @param cls closure for iterator, NULL
3314 * @param exp when does this value expire?
3315 * @param key the key this data is stored under
3316 * @param size the size of the data identified by key
3317 * @param data the actual data
3318 * @param type the type of the data
3320 * @return GNUNET_OK to continue iteration, anything else
3321 * to stop iteration.
3324 republish_content_iterator (void *cls,
3325 struct GNUNET_TIME_Absolute exp,
3326 const GNUNET_HashCode * key,
3327 uint32_t size, const char *data, uint32_t type)
3330 struct DHT_MessageContext *new_msg_ctx;
3331 struct GNUNET_DHT_PutMessage *put_msg;
3333 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3334 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3336 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3339 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3340 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3341 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3342 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3343 put_msg->type = htons (type);
3344 memcpy (&put_msg[1], data, size);
3345 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3346 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3347 new_msg_ctx->msg_options = ntohl (0);
3348 new_msg_ctx->network_size = estimate_diameter();
3349 new_msg_ctx->peer = &my_identity;
3350 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3351 new_msg_ctx->hop_count = 0;
3352 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3353 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3354 increment_stats(STAT_PUT_START);
3355 route_message(cls, &put_msg->header, new_msg_ctx);
3357 GNUNET_free(new_msg_ctx);
3358 GNUNET_free (put_msg);
3363 * Task used to republish data.
3365 * @param cls closure (a struct RepublishContext)
3366 * @param tc runtime context for this task
3369 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3371 struct RepublishContext *put_context = cls;
3373 unsigned int results;
3375 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3377 GNUNET_free(put_context);
3381 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3382 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3383 if (results == 0) /* Data must have expired */
3384 GNUNET_free(put_context);
3385 else /* Reschedule task for next time period */
3386 GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);
3391 * Find a client if it exists, add it otherwise.
3393 * @param client the server handle to the client
3395 * @return the client if found, a new client otherwise
3397 static struct ClientList *
3398 find_active_client (struct GNUNET_SERVER_Client *client)
3400 struct ClientList *pos = client_list;
3401 struct ClientList *ret;
3405 if (pos->client_handle == client)
3410 ret = GNUNET_malloc (sizeof (struct ClientList));
3411 ret->client_handle = client;
3412 ret->next = client_list;
3418 * Task to send a malicious put message across the network.
3420 * @param cls closure for this task
3421 * @param tc the context under which the task is running
3424 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3426 static struct GNUNET_DHT_PutMessage put_message;
3427 static struct DHT_MessageContext message_context;
3428 static GNUNET_HashCode key;
3429 uint32_t random_key;
3431 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3434 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3435 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3436 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3437 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3438 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3439 message_context.client = NULL;
3440 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3441 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3442 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3443 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3444 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3445 message_context.msg_options = ntohl (0);
3446 message_context.network_size = estimate_diameter();
3447 message_context.peer = &my_identity;
3448 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3449 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3450 #if DEBUG_DHT_ROUTING
3451 if (dhtlog_handle != NULL)
3452 dhtlog_handle->insert_dhtkey(NULL, &key);
3454 increment_stats(STAT_PUT_START);
3455 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3456 route_message(NULL, &put_message.header, &message_context);
3457 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3462 * Task to send a malicious put message across the network.
3464 * @param cls closure for this task
3465 * @param tc the context under which the task is running
3468 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3470 static struct GNUNET_DHT_GetMessage get_message;
3471 struct DHT_MessageContext message_context;
3472 static GNUNET_HashCode key;
3473 uint32_t random_key;
3475 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3478 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3479 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3480 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3481 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3482 message_context.client = NULL;
3483 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3484 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3485 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3486 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3487 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3488 message_context.msg_options = ntohl (0);
3489 message_context.network_size = estimate_diameter();
3490 message_context.peer = &my_identity;
3491 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3492 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3493 #if DEBUG_DHT_ROUTING
3494 if (dhtlog_handle != NULL)
3495 dhtlog_handle->insert_dhtkey(NULL, &key);
3497 increment_stats(STAT_GET_START);
3498 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3499 route_message (NULL, &get_message.header, &message_context);
3500 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3504 * Iterator over hash map entries.
3506 * @param cls closure
3507 * @param key current key code
3508 * @param value value in the hash map
3509 * @return GNUNET_YES if we should continue to
3514 add_known_to_bloom (void *cls,
3515 const GNUNET_HashCode * key,
3518 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3519 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3524 * Task to send a find peer message for our own peer identifier
3525 * so that we can find the closest peers in the network to ourselves
3526 * and attempt to connect to them.
3528 * @param cls closure for this task
3529 * @param tc the context under which the task is running
3532 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3534 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3535 struct DHT_MessageContext message_context;
3537 struct GNUNET_TIME_Relative next_send_time;
3538 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3540 struct GNUNET_TIME_Relative time_diff;
3541 struct GNUNET_TIME_Absolute end;
3543 double count_per_interval;
3545 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3548 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! */
3550 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3551 GNUNET_SCHEDULER_add_delayed (sched,
3552 GNUNET_TIME_UNIT_MINUTES,
3553 &send_find_peer_message, NULL);
3554 newly_found_peers = 0;
3558 increment_stats(STAT_FIND_PEER_START);
3560 end = GNUNET_TIME_absolute_get();
3561 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3563 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3565 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3566 count_per_interval = find_peer_context.count / multiplier;
3570 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3571 count_per_interval = find_peer_context.count * multiplier;
3575 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3576 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3577 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3578 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3579 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3580 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3581 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3582 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3583 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3584 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3585 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3586 message_context.network_size = estimate_diameter();
3587 message_context.peer = &my_identity;
3588 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3589 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3591 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3592 GNUNET_free(find_peer_msg);
3593 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3594 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3596 if (newly_found_peers < bucket_size)
3598 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3599 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3600 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3604 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3605 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3606 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3609 GNUNET_assert (next_send_time.value != 0);
3610 find_peer_context.count = 0;
3611 newly_found_peers = 0;
3612 find_peer_context.start = GNUNET_TIME_absolute_get();
3613 if (GNUNET_YES == do_find_peer)
3615 GNUNET_SCHEDULER_add_delayed (sched,
3617 &send_find_peer_message, NULL);
3622 * Handler for any generic DHT messages, calls the appropriate handler
3623 * depending on message type, sends confirmation if responses aren't otherwise
3626 * @param cls closure for the service
3627 * @param client the client we received this message from
3628 * @param message the actual message received
3631 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3632 const struct GNUNET_MessageHeader *message)
3634 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3635 const struct GNUNET_MessageHeader *enc_msg;
3636 struct DHT_MessageContext message_context;
3637 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3639 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3640 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3641 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3642 GNUNET_ntohll (dht_msg->unique_id));
3644 #if DEBUG_DHT_ROUTING
3645 if (dhtlog_handle != NULL)
3646 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3648 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3649 message_context.client = find_active_client (client);
3650 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3651 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3652 message_context.replication = ntohl (dht_msg->desired_replication_level);
3653 message_context.msg_options = ntohl (dht_msg->options);
3654 message_context.network_size = estimate_diameter();
3655 message_context.peer = &my_identity;
3656 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3657 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3658 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3659 increment_stats(STAT_GET_START);
3660 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3661 increment_stats(STAT_PUT_START);
3662 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3663 increment_stats(STAT_FIND_PEER_START);
3665 route_message(cls, enc_msg, &message_context);
3667 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3672 * Handler for any locally received DHT control messages,
3673 * sets malicious flags mostly for now.
3675 * @param cls closure for the service
3676 * @param client the client we received this message from
3677 * @param message the actual message received
3681 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3682 const struct GNUNET_MessageHeader *message)
3684 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3685 (const struct GNUNET_DHT_ControlMessage *) message;
3687 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3688 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3689 "CONTROL", ntohs(dht_control_msg->command));
3692 switch (ntohs(dht_control_msg->command))
3694 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3695 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3696 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3698 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3699 if (ntohs(dht_control_msg->variable) > 0)
3700 malicious_get_frequency = ntohs(dht_control_msg->variable);
3701 if (malicious_get_frequency == 0)
3702 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3703 if (malicious_getter != GNUNET_YES)
3704 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3705 malicious_getter = GNUNET_YES;
3706 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3708 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3709 if (ntohs(dht_control_msg->variable) > 0)
3710 malicious_put_frequency = ntohs(dht_control_msg->variable);
3711 if (malicious_put_frequency == 0)
3712 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3713 if (malicious_putter != GNUNET_YES)
3714 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3715 malicious_putter = GNUNET_YES;
3716 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3718 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3719 #if DEBUG_DHT_ROUTING
3720 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3721 dhtlog_handle->set_malicious(&my_identity);
3723 malicious_dropper = GNUNET_YES;
3724 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3727 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3730 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3734 * Handler for any generic DHT stop messages, calls the appropriate handler
3735 * depending on message type (if processed locally)
3737 * @param cls closure for the service
3738 * @param client the client we received this message from
3739 * @param message the actual message received
3743 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3744 const struct GNUNET_MessageHeader *message)
3747 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3748 (const struct GNUNET_DHT_StopMessage *) message;
3749 struct DHTQueryRecord *record;
3750 struct DHTRouteSource *pos;
3752 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3753 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3754 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3756 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3763 if ((pos->client != NULL) && (pos->client->client_handle == client))
3765 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3766 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3772 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3777 * Core handler for p2p route requests.
3780 handle_dht_p2p_route_request (void *cls,
3781 const struct GNUNET_PeerIdentity *peer,
3782 const struct GNUNET_MessageHeader *message,
3783 struct GNUNET_TIME_Relative latency, uint32_t distance)
3786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3787 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3789 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3790 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3791 struct DHT_MessageContext *message_context;
3793 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
3795 fprintf(stderr, "Sending of previous replies took far too long, backing off!\n");
3796 decrease_max_send_delay(get_max_send_delay());
3800 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3803 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3808 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
3813 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3814 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3815 GNUNET_assert(message_context->bloom != NULL);
3816 message_context->hop_count = ntohl(incoming->hop_count);
3817 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
3818 message_context->replication = ntohl(incoming->desired_replication_level);
3819 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3820 message_context->msg_options = ntohl(incoming->options);
3821 message_context->network_size = ntohl(incoming->network_size);
3822 message_context->peer = peer;
3823 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3824 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3825 route_message(cls, enc_msg, message_context);
3826 GNUNET_free(message_context);
3832 * Core handler for p2p route results.
3835 handle_dht_p2p_route_result (void *cls,
3836 const struct GNUNET_PeerIdentity *peer,
3837 const struct GNUNET_MessageHeader *message,
3838 struct GNUNET_TIME_Relative latency, uint32_t distance)
3841 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3842 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3844 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3845 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3846 struct DHT_MessageContext message_context;
3848 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
3854 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3855 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3856 GNUNET_assert(message_context.bloom != NULL);
3857 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
3858 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3859 message_context.msg_options = ntohl(incoming->options);
3860 message_context.hop_count = ntohl(incoming->hop_count);
3861 message_context.peer = peer;
3862 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3863 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3864 route_result_message(cls, enc_msg, &message_context);
3870 * Receive the HELLO from transport service,
3871 * free current and replace if necessary.
3874 * @param message HELLO message of peer
3877 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3880 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3881 "Received our `%s' from transport service\n",
3885 GNUNET_assert (message != NULL);
3886 GNUNET_free_non_null(my_hello);
3887 my_hello = GNUNET_malloc(ntohs(message->size));
3888 memcpy(my_hello, message, ntohs(message->size));
3893 * Task run during shutdown.
3899 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3902 struct PeerInfo *pos;
3903 if (transport_handle != NULL)
3905 GNUNET_free_non_null(my_hello);
3906 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3907 GNUNET_TRANSPORT_disconnect(transport_handle);
3910 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3912 while (k_buckets[bucket_count].head != NULL)
3914 pos = k_buckets[bucket_count].head;
3916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3917 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3919 delete_peer(pos, bucket_count);
3922 if (coreAPI != NULL)
3925 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3926 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3928 GNUNET_CORE_disconnect (coreAPI);
3930 if (datacache != NULL)
3933 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3934 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3936 GNUNET_DATACACHE_destroy (datacache);
3941 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3944 if (dhtlog_handle != NULL)
3945 GNUNET_DHTLOG_disconnect(dhtlog_handle);
3947 GNUNET_free_non_null(my_short_id);
3952 * To be called on core init/fail.
3954 * @param cls service closure
3955 * @param server handle to the server for this service
3956 * @param identity the public identity of this peer
3957 * @param publicKey the public key of this peer
3960 core_init (void *cls,
3961 struct GNUNET_CORE_Handle *server,
3962 const struct GNUNET_PeerIdentity *identity,
3963 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3970 "%s: Connection to core FAILED!\n", "dht",
3971 GNUNET_i2s (identity));
3973 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
3974 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3979 "%s: Core connection initialized, I am peer: %s\n", "dht",
3980 GNUNET_i2s (identity));
3983 /* Copy our identity so we can use it */
3984 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3985 if (my_short_id != NULL)
3986 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3987 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3988 /* Set the server to local variable */
3991 if (dhtlog_handle != NULL)
3992 dhtlog_handle->insert_node (NULL, &my_identity);
3996 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3997 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3998 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3999 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4004 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4005 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4006 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4011 * Method called whenever a peer connects.
4013 * @param cls closure
4014 * @param peer peer identity this notification is about
4015 * @param latency reported latency of the connection with peer
4016 * @param distance reported distance (DV) to peer
4018 void handle_core_connect (void *cls,
4019 const struct GNUNET_PeerIdentity * peer,
4020 struct GNUNET_TIME_Relative latency,
4023 struct PeerInfo *ret;
4026 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4027 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4030 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4032 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));
4036 if (datacache != NULL)
4037 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
4038 ret = try_add_peer(peer,
4039 find_current_bucket(&peer->hashPubKey),
4044 newly_found_peers++;
4045 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4048 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4049 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4054 * Method called whenever a peer disconnects.
4056 * @param cls closure
4057 * @param peer peer identity this notification is about
4059 void handle_core_disconnect (void *cls,
4061 GNUNET_PeerIdentity * peer)
4063 struct PeerInfo *to_remove;
4066 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");
4068 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4070 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));
4073 increment_stats(STAT_DISCONNECTS);
4074 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4075 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4076 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4077 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4078 delete_peer(to_remove, current_bucket);
4082 * Process dht requests.
4084 * @param cls closure
4085 * @param scheduler scheduler to use
4086 * @param server the initialized server
4087 * @param c configuration to use
4091 struct GNUNET_SCHEDULER_Handle *scheduler,
4092 struct GNUNET_SERVER_Handle *server,
4093 const struct GNUNET_CONFIGURATION_Handle *c)
4096 struct GNUNET_TIME_Relative next_send_time;
4098 unsigned long long temp_config_num;
4099 char *converge_modifier_buf;
4102 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4103 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4104 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4105 cfg, /* Main configuration */
4106 GNUNET_TIME_UNIT_FOREVER_REL,
4107 NULL, /* Closure passed to DHT functions */
4108 &core_init, /* Call core_init once connected */
4109 &handle_core_connect, /* Handle connects */
4110 &handle_core_disconnect, /* remove peers on disconnects */
4111 NULL, /* Do we care about "status" updates? */
4112 NULL, /* Don't want notified about all incoming messages */
4113 GNUNET_NO, /* For header only inbound notification */
4114 NULL, /* Don't want notified about all outbound messages */
4115 GNUNET_NO, /* For header only outbound notification */
4116 core_handlers); /* Register these handlers */
4118 if (coreAPI == NULL)
4120 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
4121 NULL, NULL, NULL, NULL, NULL);
4122 if (transport_handle != NULL)
4123 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4125 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4127 lowest_bucket = MAX_BUCKETS - 1;
4128 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4129 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4130 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4131 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4132 GNUNET_assert(all_known_peers != NULL);
4133 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4135 debug_routes = GNUNET_YES;
4139 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4142 strict_kademlia = GNUNET_YES;
4146 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4149 stop_on_closest = GNUNET_YES;
4153 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4156 stop_on_found = GNUNET_YES;
4160 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4161 "malicious_getter"))
4163 malicious_getter = GNUNET_YES;
4164 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4165 "MALICIOUS_GET_FREQUENCY",
4166 &malicious_get_frequency))
4167 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4170 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4174 max_hops = DEFAULT_MAX_HOPS;
4177 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4180 use_max_hops = GNUNET_YES;
4184 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4185 "malicious_putter"))
4187 malicious_putter = GNUNET_YES;
4188 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4189 "MALICIOUS_PUT_FREQUENCY",
4190 &malicious_put_frequency))
4191 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4194 dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
4195 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4197 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4201 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4202 "malicious_dropper"))
4204 malicious_dropper = GNUNET_YES;
4208 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4210 do_republish = GNUNET_NO;
4213 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4216 do_find_peer = GNUNET_NO;
4219 do_find_peer = GNUNET_YES;
4222 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4223 "use_real_distance"))
4224 use_real_distance = GNUNET_YES;
4227 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4228 "mysql_logging_extended"))
4230 debug_routes = GNUNET_YES;
4231 debug_routes_extended = GNUNET_YES;
4234 #if DEBUG_DHT_ROUTING
4235 if (GNUNET_YES == debug_routes)
4237 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4238 if (dhtlog_handle == NULL)
4240 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4241 "Could not connect to mysql logging server, logging will not happen!");
4246 converge_option = DHT_CONVERGE_SQUARE;
4248 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4251 converge_option = DHT_CONVERGE_LINEAR;
4253 else if (GNUNET_YES ==
4254 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4255 "converge_exponential"))
4257 converge_option = DHT_CONVERGE_EXPONENTIAL;
4260 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4262 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4264 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4265 converge_modifier = 0.0;
4267 GNUNET_free(converge_modifier_buf);
4270 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4274 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4275 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4276 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4277 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4278 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4279 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4280 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4281 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4282 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4283 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4284 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4285 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4286 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4287 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4288 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4289 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4290 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4291 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4292 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4293 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4295 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4296 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4297 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4298 if (GNUNET_YES == do_find_peer)
4300 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4301 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4302 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4303 find_peer_context.start = GNUNET_TIME_absolute_get();
4304 GNUNET_SCHEDULER_add_delayed (sched,
4306 &send_find_peer_message, &find_peer_context);
4309 /* Scheduled the task to clean up when shutdown is called */
4310 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4311 GNUNET_TIME_UNIT_FOREVER_REL,
4312 &shutdown_task, NULL);
4316 * The main function for the dht service.
4318 * @param argc number of arguments from the command line
4319 * @param argv command line arguments
4320 * @return 0 ok, 1 on error
4323 main (int argc, char *const *argv)
4325 return (GNUNET_OK ==
4326 GNUNET_SERVICE_run (argc,
4329 GNUNET_SERVICE_OPTION_NONE,
4330 &run, NULL)) ? 0 : 1;