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--;
1458 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1463 * Removes peer from a bucket, then frees associated
1464 * resources and frees peer.
1466 * @param peer peer to be removed and freed
1467 * @param bucket which bucket this peer belongs to
1469 static void delete_peer (struct PeerInfo *peer,
1470 unsigned int bucket)
1472 struct P2PPendingMessage *pos;
1473 struct P2PPendingMessage *next;
1475 struct PeerInfo *peer_pos;
1477 peer_pos = k_buckets[bucket].head;
1478 while ((peer_pos != NULL) && (peer_pos != peer))
1479 peer_pos = peer_pos->next;
1480 if (peer_pos == NULL)
1482 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1483 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));
1485 GNUNET_assert(peer_pos != NULL);
1487 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1489 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1490 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1491 if (peer->th != NULL)
1492 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1495 while (pos != NULL) /* Remove any pending messages for this peer */
1502 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1503 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1509 * Iterator over hash map entries.
1511 * @param cls closure
1512 * @param key current key code
1513 * @param value PeerInfo of the peer to move to new lowest bucket
1514 * @return GNUNET_YES if we should continue to
1518 static int move_lowest_bucket (void *cls,
1519 const GNUNET_HashCode * key,
1522 struct PeerInfo *peer = value;
1525 GNUNET_assert(lowest_bucket > 0);
1526 new_bucket = lowest_bucket - 1;
1527 remove_peer(peer, lowest_bucket);
1528 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1529 k_buckets[new_bucket].tail,
1530 k_buckets[new_bucket].tail,
1532 k_buckets[new_bucket].peers_size++;
1538 * The current lowest bucket is full, so change the lowest
1539 * bucket to the next lower down, and move any appropriate
1540 * entries in the current lowest bucket to the new bucket.
1542 static void enable_next_bucket()
1544 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1545 struct PeerInfo *pos;
1546 GNUNET_assert(lowest_bucket > 0);
1547 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1548 pos = k_buckets[lowest_bucket].head;
1551 fprintf(stderr, "Printing RT before new bucket\n");
1552 print_routing_table();
1554 /* Populate the array of peers which should be in the next lowest bucket */
1557 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1558 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1562 /* Remove peers from lowest bucket, insert into next lowest bucket */
1563 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1564 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1565 lowest_bucket = lowest_bucket - 1;
1567 fprintf(stderr, "Printing RT after new bucket\n");
1568 print_routing_table();
1573 * Find the closest peer in our routing table to the
1576 * @return The closest peer in our routing table to the
1577 * key, or NULL on error.
1579 static struct PeerInfo *
1580 find_closest_peer (const GNUNET_HashCode *hc)
1582 struct PeerInfo *pos;
1583 struct PeerInfo *current_closest;
1584 unsigned int lowest_distance;
1585 unsigned int temp_distance;
1589 lowest_distance = -1;
1591 if (k_buckets[lowest_bucket].peers_size == 0)
1594 current_closest = NULL;
1595 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1597 pos = k_buckets[bucket].head;
1599 while ((pos != NULL) && (count < bucket_size))
1601 temp_distance = distance(&pos->id.hashPubKey, hc);
1602 if (temp_distance <= lowest_distance)
1604 lowest_distance = temp_distance;
1605 current_closest = pos;
1611 GNUNET_assert(current_closest != NULL);
1612 return current_closest;
1617 * Function called to send a request out to another peer.
1618 * Called both for locally initiated requests and those
1619 * received from other peers.
1621 * @param cls DHT service closure argument (unused)
1622 * @param msg the encapsulated message
1623 * @param peer the peer to forward the message to
1624 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1626 static void forward_message (void *cls,
1627 const struct GNUNET_MessageHeader *msg,
1628 struct PeerInfo *peer,
1629 struct DHT_MessageContext *msg_ctx)
1631 struct GNUNET_DHT_P2PRouteMessage *route_message;
1632 struct P2PPendingMessage *pending;
1636 increment_stats(STAT_ROUTE_FORWARDS);
1638 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1639 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1641 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1642 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1643 psize = sizeof(struct P2PPendingMessage) + msize;
1644 pending = GNUNET_malloc(psize);
1645 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1646 pending->importance = msg_ctx->importance;
1647 pending->timeout = msg_ctx->timeout;
1648 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1649 route_message->header.size = htons(msize);
1650 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1651 route_message->options = htonl(msg_ctx->msg_options);
1652 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1653 route_message->network_size = htonl(msg_ctx->network_size);
1654 route_message->desired_replication_level = htonl(msg_ctx->replication);
1655 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1656 if (msg_ctx->bloom != NULL)
1657 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1658 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1659 memcpy(&route_message[1], msg, ntohs(msg->size));
1661 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));
1663 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1664 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1665 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1670 * Task used to send ping messages to peers so that
1671 * they don't get disconnected.
1673 * @param cls the peer to send a ping message to
1674 * @param tc context, reason, etc.
1677 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1679 struct PeerInfo *peer = cls;
1680 struct GNUNET_MessageHeader ping_message;
1681 struct DHT_MessageContext message_context;
1683 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1686 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1687 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1689 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1691 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1693 forward_message(NULL, &ping_message, peer, &message_context);
1694 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1698 * Schedule PING messages for the top X peers in each
1699 * bucket of the routing table (so core won't disconnect them!)
1701 void schedule_ping_messages()
1703 unsigned int bucket;
1705 struct PeerInfo *pos;
1706 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1708 pos = k_buckets[bucket].head;
1712 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1713 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1714 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1716 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1717 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1727 * Attempt to add a peer to our k-buckets.
1729 * @param peer the peer identity of the peer being added
1730 * @param bucket the bucket that we want this peer to go in
1731 * @param latency transport latency of this peer
1732 * @param distance transport distance to this peer
1734 * @return NULL if the peer was not added,
1735 * pointer to PeerInfo for new peer otherwise
1737 static struct PeerInfo *
1738 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1739 unsigned int bucket,
1740 struct GNUNET_TIME_Relative latency,
1741 unsigned int distance)
1744 struct PeerInfo *new_peer;
1745 peer_bucket = find_current_bucket(&peer->hashPubKey);
1746 if (peer_bucket == GNUNET_SYSERR)
1749 GNUNET_assert(peer_bucket >= lowest_bucket);
1750 new_peer = add_peer(peer, peer_bucket, latency, distance);
1752 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1753 enable_next_bucket();
1755 schedule_ping_messages();
1762 * Task run to check for messages that need to be sent to a client.
1764 * @param client a ClientList, containing the client and any messages to be sent to it
1767 process_pending_messages (struct ClientList *client)
1769 if (client->pending_head == NULL)
1771 if (client->transmit_handle != NULL)
1773 client->transmit_handle =
1774 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1775 ntohs (client->pending_head->msg->
1777 GNUNET_TIME_UNIT_FOREVER_REL,
1778 &send_generic_reply, client);
1782 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1783 * request. A ClientList is passed as closure, take the head of the list
1784 * and copy it into buf, which has the result of sending the message to the
1787 * @param cls closure to this call
1788 * @param size maximum number of bytes available to send
1789 * @param buf where to copy the actual message to
1791 * @return the number of bytes actually copied, 0 indicates failure
1794 send_generic_reply (void *cls, size_t size, void *buf)
1796 struct ClientList *client = cls;
1798 struct PendingMessage *reply;
1802 client->transmit_handle = NULL;
1805 /* client disconnected */
1809 while ( (NULL != (reply = client->pending_head)) &&
1810 (size >= off + (msize = ntohs (reply->msg->size))))
1812 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1813 client->pending_tail,
1815 memcpy (&cbuf[off], reply->msg, msize);
1816 GNUNET_free (reply);
1819 process_pending_messages (client);
1825 * Add a PendingMessage to the clients list of messages to be sent
1827 * @param client the active client to send the message to
1828 * @param pending_message the actual message to send
1831 add_pending_message (struct ClientList *client,
1832 struct PendingMessage *pending_message)
1834 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1835 client->pending_tail,
1836 client->pending_tail,
1838 process_pending_messages (client);
1845 * Called when a reply needs to be sent to a client, as
1846 * a result it found to a GET or FIND PEER request.
1848 * @param client the client to send the reply to
1849 * @param message the encapsulated message to send
1850 * @param uid the unique identifier of this request
1853 send_reply_to_client (struct ClientList *client,
1854 const struct GNUNET_MessageHeader *message,
1855 unsigned long long uid)
1857 struct GNUNET_DHT_RouteResultMessage *reply;
1858 struct PendingMessage *pending_message;
1862 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1863 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1865 msize = ntohs (message->size);
1866 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1867 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1869 GNUNET_break_op (0);
1873 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1874 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1875 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1876 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1877 reply->header.size = htons (tsize);
1878 reply->unique_id = GNUNET_htonll (uid);
1879 memcpy (&reply[1], message, msize);
1881 add_pending_message (client, pending_message);
1885 * Consider whether or not we would like to have this peer added to
1886 * our routing table. Check whether bucket for this peer is full,
1887 * if so return negative; if not return positive. Since peers are
1888 * only added on CORE level connect, this doesn't actually add the
1889 * peer to the routing table.
1891 * @param peer the peer we are considering adding
1893 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1896 * FIXME: Think about making a context for this call so that we can
1897 * ping the oldest peer in the current bucket and consider
1898 * removing it in lieu of the new peer.
1900 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1904 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1905 return GNUNET_NO; /* We already know this peer (are connected even!) */
1906 bucket = find_current_bucket(&peer->hashPubKey);
1907 if (bucket == GNUNET_SYSERR)
1909 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1916 * Main function that handles whether or not to route a result
1917 * message to other peers, or to send to our local client.
1919 * @param cls closure (unused, always should be NULL)
1920 * @param msg the result message to be routed
1921 * @param message_context context of the message we are routing
1923 * @return the number of peers the message was routed to,
1924 * GNUNET_SYSERR on failure
1926 static int route_result_message(void *cls,
1927 struct GNUNET_MessageHeader *msg,
1928 struct DHT_MessageContext *message_context)
1930 struct GNUNET_PeerIdentity new_peer;
1931 struct DHTQueryRecord *record;
1932 struct DHTRouteSource *pos;
1933 struct PeerInfo *peer_info;
1934 const struct GNUNET_MessageHeader *hello_msg;
1936 increment_stats(STAT_RESULTS);
1938 * If a find peer result message is received and contains a valid
1939 * HELLO for another peer, offer it to the transport service.
1941 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1943 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1946 hello_msg = &msg[1];
1947 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1949 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1953 else /* We have a valid hello, and peer id stored in new_peer */
1955 find_peer_context.count++;
1956 increment_stats(STAT_FIND_PEER_REPLY);
1957 if (GNUNET_YES == consider_peer(&new_peer))
1959 increment_stats(STAT_HELLOS_PROVIDED);
1960 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1961 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1966 if (malicious_dropper == GNUNET_YES)
1969 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1971 if (record == NULL) /* No record of this message! */
1974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1975 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1976 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1978 #if DEBUG_DHT_ROUTING
1979 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1981 dhtlog_handle->insert_route (NULL,
1982 message_context->unique_id,
1984 message_context->hop_count,
1987 &message_context->key,
1988 message_context->peer, NULL);
1991 if (message_context->bloom != NULL)
1993 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1994 message_context->bloom = NULL;
2002 #if STRICT_FORWARDING
2003 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2005 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2007 increment_stats("# find peer responses NOT forwarded (bloom match)");
2012 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2016 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2019 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2020 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2021 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2023 #if DEBUG_DHT_ROUTING
2024 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2026 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2027 message_context->hop_count,
2028 GNUNET_YES, &my_identity, &message_context->key,
2029 message_context->peer, NULL);
2032 increment_stats(STAT_RESULTS_TO_CLIENT);
2033 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2034 increment_stats(STAT_GET_REPLY);
2036 send_reply_to_client(pos->client, msg, message_context->unique_id);
2038 else /* Send to peer */
2040 peer_info = find_peer_by_id(&pos->source);
2041 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2047 if (message_context->bloom == NULL)
2048 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2049 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2050 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2054 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2055 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2057 #if DEBUG_DHT_ROUTING
2058 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2060 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2062 message_context->hop_count,
2063 GNUNET_NO, &my_identity, &message_context->key,
2064 message_context->peer, &pos->source);
2067 forward_result_message(cls, msg, peer_info, message_context);
2072 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2073 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2074 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2080 if (message_context->bloom != NULL)
2081 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2086 * Iterator for local get request results,
2088 * @param cls closure for iterator, a DatacacheGetContext
2089 * @param exp when does this value expire?
2090 * @param key the key this data is stored under
2091 * @param size the size of the data identified by key
2092 * @param data the actual data
2093 * @param type the type of the data
2095 * @return GNUNET_OK to continue iteration, anything else
2096 * to stop iteration.
2099 datacache_get_iterator (void *cls,
2100 struct GNUNET_TIME_Absolute exp,
2101 const GNUNET_HashCode * key,
2102 uint32_t size, const char *data, uint32_t type)
2104 struct DHT_MessageContext *msg_ctx = cls;
2105 struct DHT_MessageContext *new_msg_ctx;
2106 struct GNUNET_DHT_GetResultMessage *get_result;
2108 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2109 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2111 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2112 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2114 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2115 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2116 get_result->header.size =
2117 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2118 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2119 get_result->type = htons (type);
2120 memcpy (&get_result[1], data, size);
2121 new_msg_ctx->peer = &my_identity;
2122 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2123 new_msg_ctx->hop_count = 0;
2124 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2125 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2126 increment_stats(STAT_GET_RESPONSE_START);
2127 route_result_message(cls, &get_result->header, new_msg_ctx);
2128 GNUNET_free(new_msg_ctx);
2129 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2130 // datacache_get_ctx->unique_id);
2131 GNUNET_free (get_result);
2137 * Server handler for all dht get requests, look for data,
2138 * if found, send response either to clients or other peers.
2140 * @param cls closure for service
2141 * @param msg the actual get message
2142 * @param message_context struct containing pertinent information about the get request
2144 * @return number of items found for GET request
2147 handle_dht_get (void *cls,
2148 const struct GNUNET_MessageHeader *msg,
2149 struct DHT_MessageContext *message_context)
2151 const struct GNUNET_DHT_GetMessage *get_msg;
2153 unsigned int results;
2155 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2156 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2162 get_type = ntohs (get_msg->type);
2164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2165 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2166 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2167 message_context->unique_id);
2169 increment_stats(STAT_GETS);
2171 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2174 if (datacache != NULL)
2176 GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2177 &datacache_get_iterator, message_context);
2182 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2183 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2184 results, "GET", message_context->unique_id);
2186 #if DEBUG_DHT_ROUTING
2187 if ((debug_routes) && (dhtlog_handle != NULL))
2189 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2190 message_context->hop_count, GNUNET_YES, &my_identity,
2191 &message_context->key);
2194 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2196 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2197 message_context->hop_count, GNUNET_YES,
2198 &my_identity, &message_context->key, message_context->peer,
2204 if (message_context->hop_count == 0) /* Locally initiated request */
2206 #if DEBUG_DHT_ROUTING
2207 if ((debug_routes) && (dhtlog_handle != NULL))
2209 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2210 message_context->hop_count, GNUNET_NO, &my_identity,
2211 &message_context->key);
2220 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2222 GNUNET_HashCode *key = cls;
2223 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2230 * Server handler for initiating local dht find peer requests
2232 * @param cls closure for service
2233 * @param find_msg the actual find peer message
2234 * @param message_context struct containing pertinent information about the request
2238 handle_dht_find_peer (void *cls,
2239 const struct GNUNET_MessageHeader *find_msg,
2240 struct DHT_MessageContext *message_context)
2242 struct GNUNET_MessageHeader *find_peer_result;
2243 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2244 struct DHT_MessageContext *new_msg_ctx;
2245 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2248 GNUNET_HashCode *recent_hash;
2249 #if RESTRICT_FIND_PEER
2250 struct GNUNET_PeerIdentity peer_id;
2253 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2256 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2257 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2258 ntohs (find_msg->size),
2259 sizeof (struct GNUNET_MessageHeader));
2261 if (my_hello == NULL)
2264 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2265 "`%s': Our HELLO is null, can't return.\n",
2271 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2272 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2274 increment_stats(STAT_BLOOM_FIND_PEER);
2275 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2276 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2278 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2280 #if RESTRICT_FIND_PEER
2283 * Ignore any find peer requests from a peer we have seen very recently.
2285 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! */
2287 increment_stats("# dht find peer requests ignored (recently seen!)");
2292 * Use this check to only allow the peer to respond to find peer requests if
2293 * it would be beneficial to have the requesting peer in this peers routing
2294 * table. Can be used to thwart peers flooding the network with find peer
2295 * requests that we don't care about. However, if a new peer is joining
2296 * the network and has no other peers this is a problem (assume all buckets
2297 * full, no one will respond!).
2299 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2300 if (GNUNET_NO == consider_peer(&peer_id))
2302 increment_stats("# dht find peer requests ignored (do not need!)");
2307 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2308 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2309 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2310 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2312 /* Simplistic find_peer functionality, always return our hello */
2313 hello_size = ntohs(my_hello->size);
2314 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2316 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2318 GNUNET_break_op (0);
2322 find_peer_result = GNUNET_malloc (tsize);
2323 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2324 find_peer_result->size = htons (tsize);
2325 memcpy (&find_peer_result[1], my_hello, hello_size);
2327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2328 "`%s': Sending hello size %d to requesting peer.\n",
2331 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2332 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2333 new_msg_ctx->peer = &my_identity;
2334 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2335 new_msg_ctx->hop_count = 0;
2336 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2337 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2338 increment_stats(STAT_FIND_PEER_ANSWER);
2339 route_result_message(cls, find_peer_result, new_msg_ctx);
2340 GNUNET_free(new_msg_ctx);
2341 #if DEBUG_DHT_ROUTING
2342 if ((debug_routes) && (dhtlog_handle != NULL))
2344 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2345 message_context->hop_count, GNUNET_YES, &my_identity,
2346 &message_context->key);
2349 GNUNET_free(find_peer_result);
2353 * Task used to republish data.
2354 * Forward declaration; function call loop.
2356 * @param cls closure (a struct RepublishContext)
2357 * @param tc runtime context for this task
2360 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2363 * Server handler for initiating local dht put requests
2365 * @param cls closure for service
2366 * @param msg the actual put message
2367 * @param message_context struct containing pertinent information about the request
2370 handle_dht_put (void *cls,
2371 const struct GNUNET_MessageHeader *msg,
2372 struct DHT_MessageContext *message_context)
2374 struct GNUNET_DHT_PutMessage *put_msg;
2378 struct RepublishContext *put_context;
2380 GNUNET_assert (ntohs (msg->size) >=
2381 sizeof (struct GNUNET_DHT_PutMessage));
2384 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2385 put_type = ntohs (put_msg->type);
2387 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2390 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2392 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2393 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2394 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2396 #if DEBUG_DHT_ROUTING
2397 if (message_context->hop_count == 0) /* Locally initiated request */
2399 if ((debug_routes) && (dhtlog_handle != NULL))
2401 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2402 message_context->hop_count, GNUNET_NO, &my_identity,
2403 &message_context->key);
2408 if (message_context->closest != GNUNET_YES)
2411 #if DEBUG_DHT_ROUTING
2412 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2414 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2415 message_context->hop_count, GNUNET_YES,
2416 &my_identity, &message_context->key, message_context->peer,
2420 if ((debug_routes) && (dhtlog_handle != NULL))
2422 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2423 message_context->hop_count, GNUNET_YES, &my_identity,
2424 &message_context->key);
2428 increment_stats(STAT_PUTS_INSERTED);
2429 if (datacache != NULL)
2431 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2432 (char *) &put_msg[1], put_type,
2433 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2435 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2437 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2438 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2439 put_context->type = put_type;
2440 GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
2444 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2445 "`%s:%s': %s request received, but have no datacache!\n",
2446 my_short_id, "DHT", "PUT");
2450 * Estimate the diameter of the network based
2451 * on how many buckets are currently in use.
2452 * Concept here is that the diameter of the network
2453 * is roughly the distance a message must travel in
2454 * order to reach its intended destination. Since
2455 * at each hop we expect to get one bit closer, and
2456 * we have one bit per bucket, the number of buckets
2457 * in use should be the largest number of hops for
2458 * a sucessful message. (of course, this assumes we
2459 * know all peers in the network!)
2461 * @return ballpark diameter figure
2463 static unsigned int estimate_diameter()
2465 return MAX_BUCKETS - lowest_bucket;
2469 * To how many peers should we (on average)
2470 * forward the request to obtain the desired
2471 * target_replication count (on average).
2473 * Always 0, 1 or 2 (don't send, send once, split)
2476 get_forward_count (unsigned int hop_count, size_t target_replication)
2479 double target_count;
2480 double random_probability;
2482 uint32_t random_value;
2484 unsigned int target_value;
2485 unsigned int diameter;
2488 * If we are behaving in strict kademlia mode, send multiple initial requests,
2489 * but then only send to 1 or 0 peers based strictly on the number of hops.
2491 if (strict_kademlia == GNUNET_YES)
2494 return DHT_KADEMLIA_REPLICATION;
2495 else if (hop_count < max_hops)
2501 /* FIXME: the smaller we think the network is the more lenient we should be for
2502 * routing right? The estimation below only works if we think we have reasonably
2503 * full routing tables, which for our RR topologies may not be the case!
2505 diameter = estimate_diameter ();
2506 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2509 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2510 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2511 "DHT", estimate_diameter(), lowest_bucket);
2515 else if (hop_count > max_hops)
2518 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2519 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2526 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2527 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2528 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2529 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2530 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2531 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2532 RAND_MAX)) / RAND_MAX;
2533 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2536 //while (target_value < target_count)
2537 if (target_value < target_count)
2538 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? */
2541 //if ((target_count + 1 - (double)target_value) > random_probability)
2542 if ((target_count) > random_probability)
2546 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2547 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));
2549 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2550 if (random_value < target_replication)
2553 return target_value;
2557 * Check whether my identity is closer than any known peers.
2558 * If a non-null bloomfilter is given, check if this is the closest
2559 * peer that hasn't already been routed to.
2561 * @param target hash code to check closeness to
2562 * @param bloom bloomfilter, exclude these entries from the decision
2564 * Return GNUNET_YES if node location is closest, GNUNET_NO
2568 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2574 struct PeerInfo *pos;
2575 unsigned int my_distance;
2577 bucket_num = find_current_bucket(target);
2578 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2581 bits = matching_bits(&my_identity.hashPubKey, target);
2582 my_distance = distance(&my_identity.hashPubKey, target);
2583 pos = k_buckets[bucket_num].head;
2585 while ((pos != NULL) && (count < bucket_size))
2587 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2590 continue; /* Skip already checked entries */
2593 other_bits = matching_bits(&pos->id.hashPubKey, target);
2594 if (other_bits > bits)
2596 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2598 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2600 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2607 GNUNET_GE_LOG (coreAPI->ectx,
2608 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2609 GNUNET_GE_BULK, "closest peer\n");
2610 printPeerBits (&closest);
2611 GNUNET_GE_LOG (coreAPI->ectx,
2612 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2613 GNUNET_GE_BULK, "me\n");
2614 printPeerBits (coreAPI->my_identity);
2615 GNUNET_GE_LOG (coreAPI->ectx,
2616 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2617 GNUNET_GE_BULK, "key\n");
2618 printKeyBits (target);
2619 GNUNET_GE_LOG (coreAPI->ectx,
2620 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2622 "closest peer inverse distance is %u, mine is %u\n",
2623 inverse_distance (target, &closest.hashPubKey),
2624 inverse_distance (target,
2625 &coreAPI->my_identity->hashPubKey));
2628 /* No peers closer, we are the closest! */
2634 * Decide whether to route this request exclusively
2635 * to a closer peer (if closer peers exist) or to choose
2636 * from the whole set of peers.
2638 * @param target the key of the request
2639 * @param bloom bloomfilter of peers this request has already traversed
2640 * @param hops number of hops this message has already traveled
2642 * @return GNUNET_YES if we should try to route to a closer peer
2643 * than ourselves (and one exists), GNUNET_NO if we should
2644 * choose from the set of all known peers
2648 route_closer (const GNUNET_HashCode *target,
2649 struct GNUNET_CONTAINER_BloomFilter *bloom,
2652 unsigned int my_matching_bits;
2654 uint32_t random_value;
2655 struct PeerInfo *pos;
2660 my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2662 if (GNUNET_YES == use_max_hops)
2663 curr_max_hops = max_hops;
2665 curr_max_hops = max_hops; /* FIXME: replace with heuristic! */
2667 * First check if we know any close (as close as us or closer) peers.
2669 have_closer = GNUNET_NO;
2671 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2673 pos = k_buckets[bc].head;
2675 while ((pos != NULL) && (count < bucket_size))
2677 if ((matching_bits(target, &pos->id.hashPubKey) > my_matching_bits) &&
2678 (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
2680 have_closer = GNUNET_YES;
2686 if (have_closer == GNUNET_YES)
2690 if (have_closer == GNUNET_NO) /* We don't have a same distance or closer node, can't enforce closer only! */
2693 switch (converge_option)
2695 case DHT_CONVERGE_LINEAR:
2697 * Simple linear curve for choosing whether or not to converge.
2698 * Choose to route only closer with probability hops/MAX_HOPS.
2700 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, curr_max_hops);
2701 if (random_value < hops)
2705 case DHT_CONVERGE_SQUARE:
2707 * Simple square based curve.
2709 if ((GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1) / (double)(uint32_t)-1) < (sqrt(hops) / sqrt(curr_max_hops)))
2713 case DHT_CONVERGE_EXPONENTIAL:
2715 * Simple exponential curve.
2717 if (converge_modifier > 0)
2718 calc_value = ((converge_modifier * (hops * hops)) / (curr_max_hops * curr_max_hops)) / curr_max_hops;
2720 calc_value = ((hops * hops) / (curr_max_hops * curr_max_hops)) / curr_max_hops;
2722 if ((GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1) / (double)(uint32_t)-1) < calc_value)
2733 * Select a peer from the routing table that would be a good routing
2734 * destination for sending a message for "target". The resulting peer
2735 * must not be in the set of blocked peers.<p>
2737 * Note that we should not ALWAYS select the closest peer to the
2738 * target, peers further away from the target should be chosen with
2739 * exponentially declining probability.
2741 * @param target the key we are selecting a peer to route to
2742 * @param bloom a bloomfilter containing entries this request has seen already
2743 * @param hops the number of hops this message has already traversed
2745 * @return Peer to route to, or NULL on error
2747 static struct PeerInfo *
2748 select_peer (const GNUNET_HashCode * target,
2749 struct GNUNET_CONTAINER_BloomFilter *bloom,
2752 unsigned int distance;
2755 unsigned int my_matching_bits;
2756 unsigned long long largest_distance;
2757 unsigned long long total_real_distance;
2758 unsigned long long real_selected;
2759 unsigned int total_distance;
2760 unsigned int selected;
2761 unsigned int match_num;
2763 struct PeerInfo *pos;
2764 struct PeerInfo *chosen;
2766 #if DEBUG_DHT_ROUTING > 1
2770 my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2771 only_closer = route_closer(target, bloom, hops);
2773 if (GNUNET_YES == only_closer)
2775 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "only routing to closer peers!\n");
2776 GNUNET_asprintf(&temp_stat, "# closer only routes at hop %u", hops);
2777 increment_stats(temp_stat);
2781 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "routing to all possible peers!\n");
2782 GNUNET_asprintf(&temp_stat, "# NOT closer only routes at hop %u", hops);
2783 increment_stats(temp_stat);
2786 GNUNET_free(temp_stat);
2787 total_real_distance = 0;
2788 if (strict_kademlia == GNUNET_YES)
2790 largest_distance = 0;
2792 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2794 pos = k_buckets[bc].head;
2796 while ((pos != NULL) && (count < bucket_size))
2798 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2799 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2801 distance = inverse_distance (target, &pos->id.hashPubKey);
2802 if (distance > largest_distance)
2805 largest_distance = distance;
2813 if ((largest_distance > 0) && (chosen != NULL))
2815 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2827 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2829 pos = k_buckets[bc].head;
2831 while ((pos != NULL) && (count < bucket_size))
2833 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2834 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2836 if (GNUNET_YES == use_real_distance)
2837 total_real_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2840 /* Always add 1, in case 0 bits match! */
2841 match_num = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target ,&pos->id.hashPubKey));
2842 total_distance += match_num;
2846 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2847 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2848 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2855 if (((GNUNET_YES == use_real_distance) && (total_real_distance == 0)) || (total_distance == 0))
2857 increment_stats("# select_peer, total_distance == 0");
2861 #if DEBUG_DHT_ROUTING > 1
2863 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2865 pos = k_buckets[bc].head;
2867 while ((pos != NULL) && (count < bucket_size))
2869 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2870 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2872 if (GNUNET_YES == use_real_distance)
2874 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);
2875 sum += inverse_distance (target, &pos->id.hashPubKey) / (double)total_real_distance;
2879 match_num = 1 + (matching_bits(&pos->id.hashPubKey, target) * matching_bits(&pos->id.hashPubKey, target));
2880 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);
2881 sum += match_num / (double)total_distance;
2891 if (use_real_distance)
2893 GNUNET_assert(total_real_distance != 0);
2894 real_selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_real_distance);
2898 GNUNET_assert(total_distance != 0);
2899 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2902 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2904 pos = k_buckets[bc].head;
2906 while ((pos != NULL) && (count < bucket_size))
2908 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2909 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2911 if (GNUNET_YES == use_real_distance)
2913 distance = inverse_distance (target, &pos->id.hashPubKey);
2914 if (distance > real_selected)
2916 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "(REAL) Selected peer with %u matching bits to route to\n", matching_bits(target, &pos->id.hashPubKey));
2919 real_selected -= distance;
2923 distance = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target, &pos->id.hashPubKey));
2924 if (distance > selected)
2926 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Selected peer with %u matching bits to route to\n", matching_bits(target, &pos->id.hashPubKey));
2929 selected -= distance;
2935 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2936 "`%s:%s': peer %s matches bloomfilter.\n",
2937 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2945 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2946 "`%s:%s': peer %s matches bloomfilter.\n",
2947 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2949 increment_stats("# failed to select peer");
2950 GNUNET_assert(only_closer == GNUNET_NO);
2956 * Task used to remove recent entries, either
2957 * after timeout, when full, or on shutdown.
2959 * @param cls the entry to remove
2960 * @param tc context, reason, etc.
2963 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2965 struct RecentRequest *req = cls;
2966 static GNUNET_HashCode hash;
2968 GNUNET_assert(req != NULL);
2969 hash_from_uid(req->uid, &hash);
2970 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
2971 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
2972 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
2975 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
2977 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
2978 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
2984 * Task used to remove forwarding entries, either
2985 * after timeout, when full, or on shutdown.
2987 * @param cls the entry to remove
2988 * @param tc context, reason, etc.
2991 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2993 struct DHTRouteSource *source_info = cls;
2994 struct DHTQueryRecord *record;
2995 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2996 record = source_info->record;
2997 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2999 if (record->head == NULL) /* No more entries in DLL */
3001 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3002 GNUNET_free(record);
3004 if (source_info->find_peers_responded != NULL)
3005 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3006 GNUNET_free(source_info);
3010 * Remember this routing request so that if a reply is
3011 * received we can either forward it to the correct peer
3012 * or return the result locally.
3014 * @param cls DHT service closure
3015 * @param msg_ctx Context of the route request
3017 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3019 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
3021 struct DHTQueryRecord *record;
3022 struct DHTRouteSource *source_info;
3023 struct DHTRouteSource *pos;
3024 struct GNUNET_TIME_Absolute now;
3025 unsigned int current_size;
3027 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3028 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3030 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3031 GNUNET_assert(source_info != NULL);
3032 record = source_info->record;
3033 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3034 if (record->head == NULL) /* No more entries in DLL */
3036 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3037 GNUNET_free(record);
3039 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
3040 if (source_info->find_peers_responded != NULL)
3041 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3042 GNUNET_free(source_info);
3043 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3045 now = GNUNET_TIME_absolute_get();
3046 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3047 if (record != NULL) /* Already know this request! */
3052 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3053 break; /* Already have this peer in reply list! */
3056 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3058 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3064 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3065 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3066 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3069 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3070 source_info->record = record;
3071 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3072 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3073 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3074 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3075 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3077 source_info->client = msg_ctx->client;
3078 now = GNUNET_TIME_absolute_get_forever();
3080 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3082 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3083 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3084 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
3091 * Main function that handles whether or not to route a message to other
3094 * @param cls closure for dht service (NULL)
3095 * @param msg the message to be routed
3096 * @param message_context the context containing all pertinent information about the message
3098 * @return the number of peers the message was routed to,
3099 * GNUNET_SYSERR on failure
3101 static int route_message(void *cls,
3102 const struct GNUNET_MessageHeader *msg,
3103 struct DHT_MessageContext *message_context)
3107 struct PeerInfo *selected;
3108 #if DEBUG_DHT_ROUTING > 1
3109 struct PeerInfo *nearest;
3111 unsigned int forward_count;
3112 struct RecentRequest *recent_req;
3113 GNUNET_HashCode unique_hash;
3114 char *stat_forward_count;
3115 #if DEBUG_DHT_ROUTING
3119 if (malicious_dropper == GNUNET_YES)
3121 #if DEBUG_DHT_ROUTING
3122 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3124 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3125 message_context->hop_count, GNUNET_SYSERR,
3126 &my_identity, &message_context->key, message_context->peer,
3130 if (message_context->bloom != NULL)
3131 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3135 increment_stats(STAT_ROUTES);
3136 /* Semantics of this call means we find whether we are the closest peer out of those already
3137 * routed to on this messages path.
3139 global_closest = am_closest_peer(&message_context->key, NULL);
3140 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3141 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3142 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3143 increment_stats(stat_forward_count);
3144 GNUNET_free(stat_forward_count);
3145 if (message_context->bloom == NULL)
3146 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3148 if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3152 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3153 * any closer peers (which is being checked for below). Since we are doing recursive
3154 * routing we have no choice but to stop forwarding in this case. This means that at
3155 * any given step the request may NOT be forwarded to alpha peers (because routes will
3156 * stop and the parallel route will not be aware of it). Of course, assuming that we
3157 * have fulfilled the Kademlia requirements for routing table fullness this will never
3158 * ever ever be a problem.
3160 * However, is this fair?
3162 * Since we use these requests to build our routing tables (and we build them in the
3163 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3164 * routing tables still get constructed.
3166 if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3169 #if DEBUG_DHT_ROUTING
3170 if (forward_count == 0)
3171 ret = GNUNET_SYSERR;
3175 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3177 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3178 message_context->hop_count, ret,
3179 &my_identity, &message_context->key, message_context->peer,
3184 switch (ntohs(msg->type))
3186 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3187 cache_response (cls, message_context);
3188 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3191 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3192 increment_stats(STAT_PUTS);
3193 message_context->closest = global_closest;
3194 handle_dht_put (cls, msg, message_context);
3196 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3197 increment_stats(STAT_FIND_PEER);
3198 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3200 cache_response (cls, message_context);
3201 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3202 handle_dht_find_peer (cls, msg, message_context);
3204 #if DEBUG_DHT_ROUTING
3205 if (message_context->hop_count == 0) /* Locally initiated request */
3207 if ((debug_routes) && (dhtlog_handle != NULL))
3209 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3210 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3211 message_context->hop_count, GNUNET_NO, &my_identity,
3212 &message_context->key);
3218 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3219 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3222 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3223 hash_from_uid (message_context->unique_id, &unique_hash);
3224 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3226 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3227 GNUNET_assert(recent_req != NULL);
3228 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3229 increment_stats(STAT_DUPLICATE_UID);
3232 increment_stats(STAT_RECENT_SEEN);
3233 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3238 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3239 recent_req->uid = message_context->unique_id;
3240 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3241 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3242 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3243 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3244 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3247 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3249 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3250 GNUNET_assert(recent_req != NULL);
3251 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3252 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3255 for (i = 0; i < forward_count; i++)
3257 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3259 if (selected != NULL)
3261 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3262 #if DEBUG_DHT_ROUTING > 1
3263 nearest = find_closest_peer(&message_context->key);
3264 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3265 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3266 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3267 "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));
3268 GNUNET_free(nearest_buf);
3270 #if DEBUG_DHT_ROUTING
3271 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3273 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3274 message_context->hop_count, GNUNET_NO,
3275 &my_identity, &message_context->key, message_context->peer,
3279 forward_message(cls, msg, selected, message_context);
3283 increment_stats("# NULL returned from select_peer");
3284 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3285 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
3290 #if DEBUG_DHT_ROUTING > 1
3291 if (forward_count == 0)
3293 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3294 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
3295 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
3299 if (message_context->bloom != NULL)
3301 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3302 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3305 return forward_count;
3309 * Iterator for local get request results,
3311 * @param cls closure for iterator, NULL
3312 * @param exp when does this value expire?
3313 * @param key the key this data is stored under
3314 * @param size the size of the data identified by key
3315 * @param data the actual data
3316 * @param type the type of the data
3318 * @return GNUNET_OK to continue iteration, anything else
3319 * to stop iteration.
3322 republish_content_iterator (void *cls,
3323 struct GNUNET_TIME_Absolute exp,
3324 const GNUNET_HashCode * key,
3325 uint32_t size, const char *data, uint32_t type)
3328 struct DHT_MessageContext *new_msg_ctx;
3329 struct GNUNET_DHT_PutMessage *put_msg;
3331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3332 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3334 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3337 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3338 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3339 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3340 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3341 put_msg->type = htons (type);
3342 memcpy (&put_msg[1], data, size);
3343 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3344 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3345 new_msg_ctx->msg_options = ntohl (0);
3346 new_msg_ctx->network_size = estimate_diameter();
3347 new_msg_ctx->peer = &my_identity;
3348 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3349 new_msg_ctx->hop_count = 0;
3350 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3351 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3352 increment_stats(STAT_PUT_START);
3353 route_message(cls, &put_msg->header, new_msg_ctx);
3355 GNUNET_free(new_msg_ctx);
3356 GNUNET_free (put_msg);
3361 * Task used to republish data.
3363 * @param cls closure (a struct RepublishContext)
3364 * @param tc runtime context for this task
3367 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3369 struct RepublishContext *put_context = cls;
3371 unsigned int results;
3373 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3375 GNUNET_free(put_context);
3379 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3380 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3381 if (results == 0) /* Data must have expired */
3382 GNUNET_free(put_context);
3383 else /* Reschedule task for next time period */
3384 GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);
3389 * Find a client if it exists, add it otherwise.
3391 * @param client the server handle to the client
3393 * @return the client if found, a new client otherwise
3395 static struct ClientList *
3396 find_active_client (struct GNUNET_SERVER_Client *client)
3398 struct ClientList *pos = client_list;
3399 struct ClientList *ret;
3403 if (pos->client_handle == client)
3408 ret = GNUNET_malloc (sizeof (struct ClientList));
3409 ret->client_handle = client;
3410 ret->next = client_list;
3416 * Task to send a malicious put message across the network.
3418 * @param cls closure for this task
3419 * @param tc the context under which the task is running
3422 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3424 static struct GNUNET_DHT_PutMessage put_message;
3425 static struct DHT_MessageContext message_context;
3426 static GNUNET_HashCode key;
3427 uint32_t random_key;
3429 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3432 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3433 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3434 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3435 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3436 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3437 message_context.client = NULL;
3438 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3439 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3440 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3441 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3442 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3443 message_context.msg_options = ntohl (0);
3444 message_context.network_size = estimate_diameter();
3445 message_context.peer = &my_identity;
3446 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3447 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3448 #if DEBUG_DHT_ROUTING
3449 if (dhtlog_handle != NULL)
3450 dhtlog_handle->insert_dhtkey(NULL, &key);
3452 increment_stats(STAT_PUT_START);
3453 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3454 route_message(NULL, &put_message.header, &message_context);
3455 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3460 * Task to send a malicious put message across the network.
3462 * @param cls closure for this task
3463 * @param tc the context under which the task is running
3466 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3468 static struct GNUNET_DHT_GetMessage get_message;
3469 struct DHT_MessageContext message_context;
3470 static GNUNET_HashCode key;
3471 uint32_t random_key;
3473 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3476 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3477 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3478 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3479 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3480 message_context.client = NULL;
3481 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3482 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3483 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3484 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3485 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3486 message_context.msg_options = ntohl (0);
3487 message_context.network_size = estimate_diameter();
3488 message_context.peer = &my_identity;
3489 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3490 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3491 #if DEBUG_DHT_ROUTING
3492 if (dhtlog_handle != NULL)
3493 dhtlog_handle->insert_dhtkey(NULL, &key);
3495 increment_stats(STAT_GET_START);
3496 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3497 route_message (NULL, &get_message.header, &message_context);
3498 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3502 * Iterator over hash map entries.
3504 * @param cls closure
3505 * @param key current key code
3506 * @param value value in the hash map
3507 * @return GNUNET_YES if we should continue to
3512 add_known_to_bloom (void *cls,
3513 const GNUNET_HashCode * key,
3516 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3517 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3522 * Task to send a find peer message for our own peer identifier
3523 * so that we can find the closest peers in the network to ourselves
3524 * and attempt to connect to them.
3526 * @param cls closure for this task
3527 * @param tc the context under which the task is running
3530 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3532 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3533 struct DHT_MessageContext message_context;
3535 struct GNUNET_TIME_Relative next_send_time;
3536 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3538 struct GNUNET_TIME_Relative time_diff;
3539 struct GNUNET_TIME_Absolute end;
3541 double count_per_interval;
3543 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3546 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! */
3548 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3549 GNUNET_SCHEDULER_add_delayed (sched,
3550 GNUNET_TIME_UNIT_MINUTES,
3551 &send_find_peer_message, NULL);
3552 newly_found_peers = 0;
3556 increment_stats(STAT_FIND_PEER_START);
3558 end = GNUNET_TIME_absolute_get();
3559 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3561 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3563 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3564 count_per_interval = find_peer_context.count / multiplier;
3568 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3569 count_per_interval = find_peer_context.count * multiplier;
3573 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3574 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3575 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3576 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3577 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3578 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3579 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3580 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3581 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3582 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3583 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3584 message_context.network_size = estimate_diameter();
3585 message_context.peer = &my_identity;
3586 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3587 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3589 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3590 GNUNET_free(find_peer_msg);
3591 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3592 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3594 if (newly_found_peers < bucket_size)
3596 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3597 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3598 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3602 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3603 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3604 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3607 GNUNET_assert (next_send_time.value != 0);
3608 find_peer_context.count = 0;
3609 newly_found_peers = 0;
3610 find_peer_context.start = GNUNET_TIME_absolute_get();
3611 if (GNUNET_YES == do_find_peer)
3613 GNUNET_SCHEDULER_add_delayed (sched,
3615 &send_find_peer_message, NULL);
3620 * Handler for any generic DHT messages, calls the appropriate handler
3621 * depending on message type, sends confirmation if responses aren't otherwise
3624 * @param cls closure for the service
3625 * @param client the client we received this message from
3626 * @param message the actual message received
3629 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3630 const struct GNUNET_MessageHeader *message)
3632 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3633 const struct GNUNET_MessageHeader *enc_msg;
3634 struct DHT_MessageContext message_context;
3635 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3638 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3639 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3640 GNUNET_ntohll (dht_msg->unique_id));
3642 #if DEBUG_DHT_ROUTING
3643 if (dhtlog_handle != NULL)
3644 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3646 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3647 message_context.client = find_active_client (client);
3648 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3649 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3650 message_context.replication = ntohl (dht_msg->desired_replication_level);
3651 message_context.msg_options = ntohl (dht_msg->options);
3652 message_context.network_size = estimate_diameter();
3653 message_context.peer = &my_identity;
3654 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3655 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3656 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3657 increment_stats(STAT_GET_START);
3658 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3659 increment_stats(STAT_PUT_START);
3660 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3661 increment_stats(STAT_FIND_PEER_START);
3663 route_message(cls, enc_msg, &message_context);
3665 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3670 * Handler for any locally received DHT control messages,
3671 * sets malicious flags mostly for now.
3673 * @param cls closure for the service
3674 * @param client the client we received this message from
3675 * @param message the actual message received
3679 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3680 const struct GNUNET_MessageHeader *message)
3682 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3683 (const struct GNUNET_DHT_ControlMessage *) message;
3685 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3686 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3687 "CONTROL", ntohs(dht_control_msg->command));
3690 switch (ntohs(dht_control_msg->command))
3692 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3693 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3694 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3696 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3697 if (ntohs(dht_control_msg->variable) > 0)
3698 malicious_get_frequency = ntohs(dht_control_msg->variable);
3699 if (malicious_get_frequency == 0)
3700 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3701 if (malicious_getter != GNUNET_YES)
3702 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3703 malicious_getter = GNUNET_YES;
3704 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3706 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3707 if (ntohs(dht_control_msg->variable) > 0)
3708 malicious_put_frequency = ntohs(dht_control_msg->variable);
3709 if (malicious_put_frequency == 0)
3710 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3711 if (malicious_putter != GNUNET_YES)
3712 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3713 malicious_putter = GNUNET_YES;
3714 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3716 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3717 #if DEBUG_DHT_ROUTING
3718 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3719 dhtlog_handle->set_malicious(&my_identity);
3721 malicious_dropper = GNUNET_YES;
3722 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3725 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3728 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3732 * Handler for any generic DHT stop messages, calls the appropriate handler
3733 * depending on message type (if processed locally)
3735 * @param cls closure for the service
3736 * @param client the client we received this message from
3737 * @param message the actual message received
3741 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3742 const struct GNUNET_MessageHeader *message)
3745 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3746 (const struct GNUNET_DHT_StopMessage *) message;
3747 struct DHTQueryRecord *record;
3748 struct DHTRouteSource *pos;
3750 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3751 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3752 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3754 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3761 if ((pos->client != NULL) && (pos->client->client_handle == client))
3763 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3764 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3770 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3775 * Core handler for p2p route requests.
3778 handle_dht_p2p_route_request (void *cls,
3779 const struct GNUNET_PeerIdentity *peer,
3780 const struct GNUNET_MessageHeader *message,
3781 struct GNUNET_TIME_Relative latency, uint32_t distance)
3784 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3785 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3787 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3788 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3789 struct DHT_MessageContext *message_context;
3791 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
3793 fprintf(stderr, "Sending of previous replies took far too long, backing off!\n");
3794 decrease_max_send_delay(get_max_send_delay());
3798 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3801 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3806 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
3811 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3812 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3813 GNUNET_assert(message_context->bloom != NULL);
3814 message_context->hop_count = ntohl(incoming->hop_count);
3815 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
3816 message_context->replication = ntohl(incoming->desired_replication_level);
3817 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3818 message_context->msg_options = ntohl(incoming->options);
3819 message_context->network_size = ntohl(incoming->network_size);
3820 message_context->peer = peer;
3821 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3822 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3823 route_message(cls, enc_msg, message_context);
3824 GNUNET_free(message_context);
3830 * Core handler for p2p route results.
3833 handle_dht_p2p_route_result (void *cls,
3834 const struct GNUNET_PeerIdentity *peer,
3835 const struct GNUNET_MessageHeader *message,
3836 struct GNUNET_TIME_Relative latency, uint32_t distance)
3839 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3840 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3842 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3843 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3844 struct DHT_MessageContext message_context;
3846 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
3852 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3853 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3854 GNUNET_assert(message_context.bloom != NULL);
3855 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
3856 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3857 message_context.msg_options = ntohl(incoming->options);
3858 message_context.hop_count = ntohl(incoming->hop_count);
3859 message_context.peer = peer;
3860 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3861 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3862 route_result_message(cls, enc_msg, &message_context);
3868 * Receive the HELLO from transport service,
3869 * free current and replace if necessary.
3872 * @param message HELLO message of peer
3875 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3878 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3879 "Received our `%s' from transport service\n",
3883 GNUNET_assert (message != NULL);
3884 GNUNET_free_non_null(my_hello);
3885 my_hello = GNUNET_malloc(ntohs(message->size));
3886 memcpy(my_hello, message, ntohs(message->size));
3891 * Task run during shutdown.
3897 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3900 struct PeerInfo *pos;
3901 if (transport_handle != NULL)
3903 GNUNET_free_non_null(my_hello);
3904 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3905 GNUNET_TRANSPORT_disconnect(transport_handle);
3908 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3910 while (k_buckets[bucket_count].head != NULL)
3912 pos = k_buckets[bucket_count].head;
3914 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3915 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3917 delete_peer(pos, bucket_count);
3920 if (coreAPI != NULL)
3923 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3924 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3926 GNUNET_CORE_disconnect (coreAPI);
3928 if (datacache != NULL)
3931 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3932 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3934 GNUNET_DATACACHE_destroy (datacache);
3939 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3942 if (dhtlog_handle != NULL)
3943 GNUNET_DHTLOG_disconnect(dhtlog_handle);
3945 GNUNET_free_non_null(my_short_id);
3950 * To be called on core init/fail.
3952 * @param cls service closure
3953 * @param server handle to the server for this service
3954 * @param identity the public identity of this peer
3955 * @param publicKey the public key of this peer
3958 core_init (void *cls,
3959 struct GNUNET_CORE_Handle *server,
3960 const struct GNUNET_PeerIdentity *identity,
3961 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3968 "%s: Connection to core FAILED!\n", "dht",
3969 GNUNET_i2s (identity));
3971 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
3972 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3977 "%s: Core connection initialized, I am peer: %s\n", "dht",
3978 GNUNET_i2s (identity));
3981 /* Copy our identity so we can use it */
3982 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3983 if (my_short_id != NULL)
3984 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3985 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3986 /* Set the server to local variable */
3989 if (dhtlog_handle != NULL)
3990 dhtlog_handle->insert_node (NULL, &my_identity);
3994 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3995 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3996 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3997 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4002 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4003 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4004 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4009 * Method called whenever a peer connects.
4011 * @param cls closure
4012 * @param peer peer identity this notification is about
4013 * @param latency reported latency of the connection with peer
4014 * @param distance reported distance (DV) to peer
4016 void handle_core_connect (void *cls,
4017 const struct GNUNET_PeerIdentity * peer,
4018 struct GNUNET_TIME_Relative latency,
4021 struct PeerInfo *ret;
4024 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4025 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4028 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4030 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));
4034 if (datacache != NULL)
4035 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
4036 ret = try_add_peer(peer,
4037 find_current_bucket(&peer->hashPubKey),
4042 newly_found_peers++;
4043 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4046 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4047 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4052 * Method called whenever a peer disconnects.
4054 * @param cls closure
4055 * @param peer peer identity this notification is about
4057 void handle_core_disconnect (void *cls,
4059 GNUNET_PeerIdentity * peer)
4061 struct PeerInfo *to_remove;
4064 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");
4066 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4068 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));
4071 increment_stats(STAT_DISCONNECTS);
4072 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4073 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4074 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4075 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4076 delete_peer(to_remove, current_bucket);
4080 * Process dht requests.
4082 * @param cls closure
4083 * @param scheduler scheduler to use
4084 * @param server the initialized server
4085 * @param c configuration to use
4089 struct GNUNET_SCHEDULER_Handle *scheduler,
4090 struct GNUNET_SERVER_Handle *server,
4091 const struct GNUNET_CONFIGURATION_Handle *c)
4094 struct GNUNET_TIME_Relative next_send_time;
4096 unsigned long long temp_config_num;
4097 char *converge_modifier_buf;
4100 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4101 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4102 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4103 cfg, /* Main configuration */
4104 GNUNET_TIME_UNIT_FOREVER_REL,
4105 NULL, /* Closure passed to DHT functions */
4106 &core_init, /* Call core_init once connected */
4107 &handle_core_connect, /* Handle connects */
4108 &handle_core_disconnect, /* remove peers on disconnects */
4109 NULL, /* Do we care about "status" updates? */
4110 NULL, /* Don't want notified about all incoming messages */
4111 GNUNET_NO, /* For header only inbound notification */
4112 NULL, /* Don't want notified about all outbound messages */
4113 GNUNET_NO, /* For header only outbound notification */
4114 core_handlers); /* Register these handlers */
4116 if (coreAPI == NULL)
4118 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
4119 NULL, NULL, NULL, NULL, NULL);
4120 if (transport_handle != NULL)
4121 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4123 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4125 lowest_bucket = MAX_BUCKETS - 1;
4126 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4127 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4128 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4129 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4130 GNUNET_assert(all_known_peers != NULL);
4131 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4133 debug_routes = GNUNET_YES;
4137 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4140 strict_kademlia = GNUNET_YES;
4144 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4147 stop_on_closest = GNUNET_YES;
4151 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4154 stop_on_found = GNUNET_YES;
4158 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4159 "malicious_getter"))
4161 malicious_getter = GNUNET_YES;
4162 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4163 "MALICIOUS_GET_FREQUENCY",
4164 &malicious_get_frequency))
4165 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4168 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4172 max_hops = DEFAULT_MAX_HOPS;
4175 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4178 use_max_hops = GNUNET_YES;
4182 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4183 "malicious_putter"))
4185 malicious_putter = GNUNET_YES;
4186 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4187 "MALICIOUS_PUT_FREQUENCY",
4188 &malicious_put_frequency))
4189 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4192 dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
4193 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4195 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4199 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4200 "malicious_dropper"))
4202 malicious_dropper = GNUNET_YES;
4206 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4208 do_republish = GNUNET_NO;
4211 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4214 do_find_peer = GNUNET_NO;
4217 do_find_peer = GNUNET_YES;
4220 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4221 "use_real_distance"))
4222 use_real_distance = GNUNET_YES;
4225 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4226 "mysql_logging_extended"))
4228 debug_routes = GNUNET_YES;
4229 debug_routes_extended = GNUNET_YES;
4232 #if DEBUG_DHT_ROUTING
4233 if (GNUNET_YES == debug_routes)
4235 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4236 if (dhtlog_handle == NULL)
4238 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4239 "Could not connect to mysql logging server, logging will not happen!");
4244 converge_option = DHT_CONVERGE_SQUARE;
4246 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4249 converge_option = DHT_CONVERGE_LINEAR;
4251 else if (GNUNET_YES ==
4252 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4253 "converge_exponential"))
4255 converge_option = DHT_CONVERGE_EXPONENTIAL;
4258 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4260 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4262 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4263 converge_modifier = 0.0;
4265 GNUNET_free(converge_modifier_buf);
4268 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4272 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4273 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4274 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4275 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4276 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4277 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4278 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4279 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4280 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4281 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4282 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4283 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4284 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4285 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4286 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4287 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4288 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4289 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4290 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4291 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4293 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4294 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4295 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4296 if (GNUNET_YES == do_find_peer)
4298 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4299 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4300 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4301 find_peer_context.start = GNUNET_TIME_absolute_get();
4302 GNUNET_SCHEDULER_add_delayed (sched,
4304 &send_find_peer_message, &find_peer_context);
4307 /* Scheduled the task to clean up when shutdown is called */
4308 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4309 GNUNET_TIME_UNIT_FOREVER_REL,
4310 &shutdown_task, NULL);
4314 * The main function for the dht service.
4316 * @param argc number of arguments from the command line
4317 * @param argv command line arguments
4318 * @return 0 ok, 1 on error
4321 main (int argc, char *const *argv)
4323 return (GNUNET_OK ==
4324 GNUNET_SERVICE_run (argc,
4327 GNUNET_SERVICE_OPTION_NONE,
4328 &run, NULL)) ? 0 : 1;