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 GNUnet DHT service
24 * @author Christian Grothoff
25 * @author Nathan Evans
29 #include "gnunet_block_lib.h"
30 #include "gnunet_client_lib.h"
31 #include "gnunet_getopt_lib.h"
32 #include "gnunet_os_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_service_lib.h"
35 #include "gnunet_core_service.h"
36 #include "gnunet_signal_lib.h"
37 #include "gnunet_util_lib.h"
38 #include "gnunet_datacache_lib.h"
39 #include "gnunet_transport_service.h"
40 #include "gnunet_hello_lib.h"
41 #include "gnunet_dht_service.h"
42 #include "gnunet_statistics_service.h"
47 #define PRINT_TABLES GNUNET_NO
49 #define REAL_DISTANCE GNUNET_NO
51 #define EXTRA_CHECKS GNUNET_NO
54 * How many buckets will we allow total.
56 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
59 * Should the DHT issue FIND_PEER requests to get better routing tables?
61 #define DEFAULT_DO_FIND_PEER GNUNET_YES
64 * Defines whether find peer requests send their HELLO's outgoing,
65 * or expect replies to contain hellos.
67 #define FIND_PEER_WITH_HELLO GNUNET_YES
70 * What is the maximum number of peers in a given bucket.
72 #define DEFAULT_BUCKET_SIZE 4
74 #define DEFAULT_CORE_QUEUE_SIZE 32
77 * Minimum number of peers we need for "good" routing,
78 * any less than this and we will allow messages to
79 * travel much further through the network!
81 #define MINIMUM_PEER_THRESHOLD 20
83 #define DHT_MAX_RECENT 1000
85 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
88 * Default time to wait to send messages on behalf of other peers.
90 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
93 * Default importance for handling messages on behalf of other peers.
95 #define DHT_DEFAULT_P2P_IMPORTANCE 0
98 * How long to keep recent requests around by default.
100 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
103 * Default time to wait to send find peer messages sent by the dht service.
105 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
108 * Default importance for find peer messages sent by the dht service.
110 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
113 * Default replication parameter for find peer messages sent by the dht service.
115 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
118 * Default options for find peer requests sent by the dht service.
120 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
121 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
124 * How long at least to wait before sending another find peer request.
126 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
129 * How long at most to wait before sending another find peer request.
131 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
134 * How often to update our preference levels for peers in our routing tables.
136 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
139 * How long at most on average will we allow a reply forward to take
140 * (before we quit sending out new requests)
142 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
145 * How many initial requests to send out (in true Kademlia fashion)
147 #define DEFAULT_KADEMLIA_REPLICATION 3
150 * Default frequency for sending malicious get messages
152 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
155 * Default frequency for sending malicious put messages
157 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
160 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
163 * Real maximum number of hops, at which point we refuse
164 * to forward the message.
166 #define DEFAULT_MAX_HOPS 10
169 * How many time differences between requesting a core send and
170 * the actual callback to remember.
172 #define MAX_REPLY_TIMES 8
174 enum ConvergenceOptions
177 * Use the linear method for convergence.
182 * Converge using a fast converging square
188 * Converge using a slower exponential
191 DHT_CONVERGE_EXPONENTIAL,
194 * Don't do any special convergence, allow
195 * the algorithm to hopefully route to closer
201 * Binary convergence, start routing to closest
202 * only after set number of hops.
208 * Linked list of messages to send to clients.
210 struct P2PPendingMessage
213 * Pointer to next item in the list
215 struct P2PPendingMessage *next;
218 * Pointer to previous item in the list
220 struct P2PPendingMessage *prev;
223 * Message importance level.
225 unsigned int importance;
228 * Time when this request was scheduled to be sent.
230 struct GNUNET_TIME_Absolute scheduled;
233 * How long to wait before sending message.
235 struct GNUNET_TIME_Relative timeout;
238 * Actual message to be sent; // avoid allocation
240 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
245 * Per-peer information.
250 * Next peer entry (DLL)
252 struct PeerInfo *next;
255 * Prev peer entry (DLL)
257 struct PeerInfo *prev;
260 * Count of outstanding messages for peer.
262 unsigned int pending_count;
265 * Head of pending messages to be sent to this peer.
267 struct P2PPendingMessage *head;
270 * Tail of pending messages to be sent to this peer.
272 struct P2PPendingMessage *tail;
275 * Core handle for sending messages to this peer.
277 struct GNUNET_CORE_TransmitHandle *th;
280 * Task for scheduling message sends.
282 GNUNET_SCHEDULER_TaskIdentifier send_task;
285 * Task for scheduling preference updates
287 GNUNET_SCHEDULER_TaskIdentifier preference_task;
290 * Preference update context
292 struct GNUNET_CORE_InformationRequestContext *info_ctx;
295 * What is the identity of the peer?
297 struct GNUNET_PeerIdentity id;
301 * What is the average latency for replies received?
303 struct GNUNET_TIME_Relative latency;
306 * Transport level distance to peer.
308 unsigned int distance;
312 * Holds matching bits from peer to current target,
313 * used for distance comparisons between peers. May
314 * be considered a really bad idea.
315 * FIXME: remove this value (create struct which holds
316 * a single peerinfo and the matching bits, use
317 * that to pass to comparator)
319 unsigned int matching_bits;
322 * Task for scheduling periodic ping messages for this peer.
324 GNUNET_SCHEDULER_TaskIdentifier ping_task;
328 * Peers are grouped into buckets.
335 struct PeerInfo *head;
340 struct PeerInfo *tail;
343 * Number of peers in the bucket.
345 unsigned int peers_size;
349 * Linked list of messages to send to clients.
351 struct PendingMessage
354 * Pointer to next item in the list
356 struct PendingMessage *next;
359 * Pointer to previous item in the list
361 struct PendingMessage *prev;
364 * Actual message to be sent; // avoid allocation
366 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
371 * Struct containing information about a client,
372 * handle to connect to it, and any pending messages
373 * that need to be sent to it.
378 * Linked list of active clients
380 struct ClientList *next;
383 * The handle to this client
385 struct GNUNET_SERVER_Client *client_handle;
388 * Handle to the current transmission request, NULL
391 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
394 * Linked list of pending messages for this client
396 struct PendingMessage *pending_head;
399 * Tail of linked list of pending messages for this client
401 struct PendingMessage *pending_tail;
406 * Context containing information about a DHT message received.
408 struct DHT_MessageContext
411 * The client this request was received from.
412 * (NULL if received from another peer)
414 struct ClientList *client;
417 * The peer this request was received from.
418 * (NULL if received from local client)
420 const struct GNUNET_PeerIdentity *peer;
423 * Bloomfilter for this routing request.
425 struct GNUNET_CONTAINER_BloomFilter *bloom;
428 * extended query (see gnunet_block_lib.h).
433 * Bloomfilter to filter out duplicate replies.
435 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
438 * The key this request was about
443 * How long should we wait to transmit this request?
445 struct GNUNET_TIME_Relative timeout;
448 * The unique identifier of this request
453 * Number of bytes in xquery.
458 * Mutator value for the reply_bf, see gnunet_block_lib.h
460 uint32_t reply_bf_mutator;
463 * Desired replication level
465 uint32_t replication;
468 * Network size estimate, either ours or the sum of
469 * those routed to thus far. =~ Log of number of peers
470 * chosen from for this request.
472 uint32_t network_size;
475 * Any message options for this request
477 uint32_t msg_options;
480 * How many hops has the message already traversed?
485 * How many peer identities are present in the path history?
487 uint32_t path_history_len;
495 * How important is this message?
497 unsigned int importance;
500 * Should we (still) forward the request on to other peers?
505 * Did we forward this message? (may need to remember it!)
510 * Are we the closest known peer to this key (out of our neighbors?)
516 * Record used for remembering what peers are waiting for what
517 * responses (based on search key).
519 struct DHTRouteSource
524 struct DHTRouteSource *next;
529 struct DHTRouteSource *prev;
532 * Source of the request. Replies should be forwarded to
535 struct GNUNET_PeerIdentity source;
538 * If this was a local request, remember the client; otherwise NULL.
540 struct ClientList *client;
543 * Pointer to this nodes heap location (for removal)
545 struct GNUNET_CONTAINER_HeapNode *hnode;
548 * Back pointer to the record storing this information.
550 struct DHTQueryRecord *record;
553 * Task to remove this entry on timeout.
555 GNUNET_SCHEDULER_TaskIdentifier delete_task;
558 * Bloomfilter of peers we have already sent back as
559 * replies to the initial request. Allows us to not
560 * forward the same peer multiple times for a find peer
563 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
568 * Entry in the DHT routing table.
570 struct DHTQueryRecord
573 * Head of DLL for result forwarding.
575 struct DHTRouteSource *head;
578 * Tail of DLL for result forwarding.
580 struct DHTRouteSource *tail;
583 * Key that the record concerns.
588 * GET message of this record (what we already forwarded?).
590 //DV_DHT_MESSAGE get; Try to get away with not saving this.
593 * Bloomfilter of the peers we've replied to so far
595 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
600 * Context used to calculate the number of find peer messages
601 * per X time units since our last scheduled find peer message
602 * was sent. If we have seen too many messages, delay or don't
605 struct FindPeerMessageContext
609 struct GNUNET_TIME_Absolute start;
611 struct GNUNET_TIME_Absolute end;
615 * DHT Routing results structure
620 * Min heap for removal upon reaching limit
622 struct GNUNET_CONTAINER_Heap *minHeap;
625 * Hashmap for fast key based lookup
627 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
632 * DHT structure for recent requests.
634 struct RecentRequests
637 * Min heap for removal upon reaching limit
639 struct GNUNET_CONTAINER_Heap *minHeap;
642 * Hashmap for key based lookup
644 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
650 * Position of this node in the min heap.
652 struct GNUNET_CONTAINER_HeapNode *heap_node;
655 * Bloomfilter containing entries for peers
656 * we forwarded this request to.
658 struct GNUNET_CONTAINER_BloomFilter *bloom;
661 * Timestamp of this request, for ordering
664 struct GNUNET_TIME_Absolute timestamp;
667 * Key of this request.
672 * Unique identifier for this request.
677 * Task to remove this entry on timeout.
679 GNUNET_SCHEDULER_TaskIdentifier remove_task;
682 struct RepublishContext
697 * Which kind of convergence will we be using?
699 static enum ConvergenceOptions converge_option;
702 * Modifier for the convergence function
704 static float converge_modifier;
707 * Recent requests by hash/uid and by time inserted.
709 static struct RecentRequests recent;
712 * Context to use to calculate find peer rates.
714 static struct FindPeerMessageContext find_peer_context;
717 * Don't use our routing algorithm, always route
718 * to closest peer; initially send requests to 3
721 static unsigned int strict_kademlia;
724 * Routing option to end routing when closest peer found.
726 static unsigned int stop_on_closest;
729 * Routing option to end routing when data is found.
731 static unsigned int stop_on_found;
734 * Whether DHT needs to manage find peer requests, or
735 * an external force will do it on behalf of the DHT.
737 static unsigned int do_find_peer;
740 * Once we have stored an item in the DHT, refresh it
741 * according to our republish interval.
743 static unsigned int do_republish;
746 * Use exactly the forwarding formula as described in
747 * the paper if set to GNUNET_YES, otherwise use the
748 * slightly modified version.
750 static unsigned int paper_forwarding;
753 * PUT Peer Identities of peers we know about into
756 static unsigned int put_peer_identities;
759 * Use the "real" distance metric when selecting the
760 * next routing hop. Can be less accurate.
762 static unsigned int use_real_distance;
765 * How many peers have we added since we sent out our last
768 static unsigned int newly_found_peers;
771 * Container of active queries we should remember
773 static struct DHTResults forward_list;
776 * Handle to the datacache service (for inserting/retrieving data)
778 static struct GNUNET_DATACACHE_Handle *datacache;
781 * Handle for the statistics service.
783 struct GNUNET_STATISTICS_Handle *stats;
787 * The configuration the DHT service is running with
789 static const struct GNUNET_CONFIGURATION_Handle *cfg;
792 * Handle to the core service
794 static struct GNUNET_CORE_Handle *coreAPI;
797 * Handle to the transport service, for getting our hello
799 static struct GNUNET_TRANSPORT_Handle *transport_handle;
802 * The identity of our peer.
804 static struct GNUNET_PeerIdentity my_identity;
807 * Short id of the peer, for printing
809 static char *my_short_id;
814 static struct GNUNET_MessageHeader *my_hello;
817 * Task to run when we shut down, cleaning up all our trash
819 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
822 * The lowest currently used bucket.
824 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
827 * The maximum number of hops before we stop routing messages.
829 static unsigned long long max_hops;
832 * How often to republish content we have previously stored.
834 static struct GNUNET_TIME_Relative dht_republish_frequency;
837 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
839 static int use_max_hops;
842 * The buckets (Kademlia routing table, complete with growth).
843 * Array of size MAX_BUCKET_SIZE.
845 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
848 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
850 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
853 * Recently seen find peer requests.
855 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
858 * Maximum size for each bucket.
860 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
863 * List of active clients.
865 static struct ClientList *client_list;
868 * Handle to the DHT logger.
870 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
873 * Whether or not to send routing debugging information
874 * to the dht logging server
876 static unsigned int debug_routes;
879 * Whether or not to send FULL route information to
882 static unsigned int debug_routes_extended;
885 * GNUNET_YES or GNUNET_NO, whether or not to act as
886 * a malicious node which drops all messages
888 static unsigned int malicious_dropper;
891 * GNUNET_YES or GNUNET_NO, whether or not to act as
892 * a malicious node which sends out lots of GETS
894 static unsigned int malicious_getter;
897 * GNUNET_YES or GNUNET_NO, whether or not to act as
898 * a malicious node which sends out lots of PUTS
900 static unsigned int malicious_putter;
903 * Frequency for malicious get requests.
905 static unsigned long long malicious_get_frequency;
908 * Frequency for malicious put requests.
910 static unsigned long long malicious_put_frequency;
913 * Kademlia replication
915 static unsigned long long kademlia_replication;
918 * Reply times for requests, if we are busy, don't send any
921 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
924 * Current counter for replies.
926 static unsigned int reply_counter;
929 * Our handle to the BLOCK library.
931 static struct GNUNET_BLOCK_Context *block_context;
935 * Forward declaration.
937 static size_t send_generic_reply (void *cls, size_t size, void *buf);
940 /** Declare here so retry_core_send is aware of it */
941 static size_t core_transmit_notify (void *cls, size_t size, void *buf);
944 * Convert unique ID to hash code.
946 * @param uid unique ID to convert
947 * @param hash set to uid (extended with zeros)
950 hash_from_uid (uint64_t uid, GNUNET_HashCode * hash)
952 memset (hash, 0, sizeof (GNUNET_HashCode));
953 *((uint64_t *) hash) = uid;
958 * Calculate the average send time between messages so that we can
959 * ignore certain requests if we get too busy.
961 * @return the average time between asking core to send a message
962 * and when the buffer for copying it is passed
964 static struct GNUNET_TIME_Relative
965 get_average_send_delay ()
968 unsigned int divisor;
969 struct GNUNET_TIME_Relative average_time;
970 average_time = GNUNET_TIME_relative_get_zero ();
972 for (i = 0; i < MAX_REPLY_TIMES; i++)
974 average_time = GNUNET_TIME_relative_add (average_time, reply_times[i]);
975 if (reply_times[i].abs_value == (uint64_t) 0)
985 average_time = GNUNET_TIME_relative_divide (average_time, divisor);
987 "Avg send delay: %u sends is %llu\n",
988 divisor, (unsigned long long) average_time.abs_value);
994 * Given the largest send delay, artificially decrease it
995 * so the next time around we may have a chance at sending
999 decrease_max_send_delay (struct GNUNET_TIME_Relative max_time)
1002 for (i = 0; i < MAX_REPLY_TIMES; i++)
1004 if (reply_times[i].rel_value == max_time.rel_value)
1006 reply_times[i].rel_value = reply_times[i].rel_value / 2;
1013 * Find the maximum send time of the recently sent values.
1015 * @return the average time between asking core to send a message
1016 * and when the buffer for copying it is passed
1018 static struct GNUNET_TIME_Relative
1019 get_max_send_delay ()
1022 struct GNUNET_TIME_Relative max_time;
1023 max_time = GNUNET_TIME_relative_get_zero ();
1025 for (i = 0; i < MAX_REPLY_TIMES; i++)
1027 if (reply_times[i].rel_value > max_time.rel_value)
1028 max_time.rel_value = reply_times[i].rel_value;
1031 if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
1032 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n",
1033 (unsigned long long) max_time.rel_value);
1039 increment_stats (const char *value)
1043 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
1048 decrement_stats (const char *value)
1052 GNUNET_STATISTICS_update (stats, value, -1, GNUNET_NO);
1057 * Try to send another message from our core send list
1060 try_core_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1062 struct PeerInfo *peer = cls;
1063 struct P2PPendingMessage *pending;
1066 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
1068 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1071 if (peer->th != NULL)
1072 return; /* Message send already in progress */
1074 pending = peer->head;
1075 if (pending != NULL)
1077 ssize = ntohs (pending->msg->size);
1079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1080 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n",
1081 my_short_id, "DHT", ssize, GNUNET_i2s (&peer->id));
1083 pending->scheduled = GNUNET_TIME_absolute_get ();
1085 if (reply_counter >= MAX_REPLY_TIMES)
1088 GNUNET_CORE_notify_transmit_ready (coreAPI,
1090 pending->importance,
1091 pending->timeout, &peer->id, ssize,
1092 &core_transmit_notify, peer);
1093 if (peer->th == NULL)
1094 increment_stats ("# notify transmit ready failed");
1099 * Function called to send a request out to another peer.
1100 * Called both for locally initiated requests and those
1101 * received from other peers.
1103 * @param msg the encapsulated message
1104 * @param peer the peer to forward the message to
1105 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1108 forward_result_message (const struct GNUNET_MessageHeader *msg,
1109 struct PeerInfo *peer,
1110 struct DHT_MessageContext *msg_ctx)
1112 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1113 struct P2PPendingMessage *pending;
1122 increment_stats (STAT_RESULT_FORWARDS);
1124 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs (msg->size) + (sizeof(struct GNUNET_PeerIdentity) * msg_ctx->path_history_len);
1125 GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1126 psize = sizeof (struct P2PPendingMessage) + msize;
1127 pending = GNUNET_malloc (psize);
1128 pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1129 pending->importance = DHT_SEND_PRIORITY;
1130 pending->timeout = GNUNET_TIME_relative_get_forever ();
1131 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *) pending->msg;
1132 result_message->header.size = htons (msize);
1133 result_message->header.type =
1134 htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1135 result_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1136 if (msg_ctx->path_history_len > 0)
1138 /* End of pending is where enc_msg starts */
1139 path_start = (char *)&pending[1];
1140 /* Offset by the size of the enc_msg */
1141 path_start += ntohs (msg->size);
1142 memcpy(path_start, msg_ctx->path_history, msg_ctx->path_history_len * (sizeof(struct GNUNET_PeerIdentity)));
1144 for (i = 0; i < msg_ctx->path_history_len; i++)
1146 path_offset = &msg_ctx->path_history[i * sizeof(struct GNUNET_PeerIdentity)];
1147 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "(forward_result) Key %s Found peer %d:%s\n", GNUNET_h2s(&msg_ctx->key), i, GNUNET_i2s((struct GNUNET_PeerIdentity *)path_offset));
1151 result_message->options = htonl (msg_ctx->msg_options);
1152 result_message->hop_count = htonl (msg_ctx->hop_count + 1);
1153 GNUNET_assert (GNUNET_OK ==
1154 GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1158 result_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1159 memcpy (&result_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1160 /* Copy the enc_msg, then the path history as well! */
1161 memcpy (&result_message[1], msg, ntohs (msg->size));
1162 path_offset = (char *)&result_message[1];
1163 path_offset += ntohs (msg->size);
1164 /* If we have path history, copy it to the end of the whole thing */
1165 if (msg_ctx->path_history_len > 0)
1166 memcpy(path_offset, msg_ctx->path_history, msg_ctx->path_history_len * (sizeof(struct GNUNET_PeerIdentity)));
1168 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1169 "%s:%s Adding pending message size %d for peer %s\n",
1170 my_short_id, "DHT", msize, GNUNET_i2s (&peer->id));
1172 peer->pending_count++;
1173 increment_stats ("# pending messages scheduled");
1174 GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1176 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1177 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1182 * Called when core is ready to send a message we asked for
1183 * out to the destination.
1185 * @param cls closure (NULL)
1186 * @param size number of bytes available in buf
1187 * @param buf where the callee should write the message
1188 * @return number of bytes written to buf
1191 core_transmit_notify (void *cls, size_t size, void *buf)
1193 struct PeerInfo *peer = cls;
1195 struct P2PPendingMessage *pending;
1202 /* client disconnected */
1204 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n",
1205 my_short_id, "DHT");
1210 if (peer->head == NULL)
1214 pending = peer->head;
1216 reply_times[reply_counter] =
1217 GNUNET_TIME_absolute_get_difference (pending->scheduled,
1218 GNUNET_TIME_absolute_get ());
1219 msize = ntohs (pending->msg->size);
1223 memcpy (cbuf, pending->msg, msize);
1224 peer->pending_count--;
1225 increment_stats ("# pending messages sent");
1226 GNUNET_assert (peer->pending_count >= 0);
1227 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1228 GNUNET_free (pending);
1231 while (NULL != pending &&
1232 (size - off >= (msize = ntohs (pending->msg->size))))
1234 memcpy (&cbuf[off], pending->msg, msize);
1236 peer->pending_count--;
1237 increment_stats ("# pending messages sent");
1238 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1239 GNUNET_free (pending);
1240 pending = peer->head;
1243 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1244 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1251 * Compute the distance between have and target as a 32-bit value.
1252 * Differences in the lower bits must count stronger than differences
1253 * in the higher bits.
1255 * @return 0 if have==target, otherwise a number
1256 * that is larger as the distance between
1257 * the two hash codes increases
1260 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1262 unsigned int bucket;
1267 /* We have to represent the distance between two 2^9 (=512)-bit
1268 numbers as a 2^5 (=32)-bit number with "0" being used for the
1269 two numbers being identical; furthermore, we need to
1270 guarantee that a difference in the number of matching
1271 bits is always represented in the result.
1273 We use 2^32/2^9 numerical values to distinguish between
1274 hash codes that have the same LSB bit distance and
1275 use the highest 2^9 bits of the result to signify the
1276 number of (mis)matching LSB bits; if we have 0 matching
1277 and hence 512 mismatching LSB bits we return -1 (since
1278 512 itself cannot be represented with 9 bits) */
1280 /* first, calculate the most significant 9 bits of our
1281 result, aka the number of LSBs */
1282 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1283 /* bucket is now a value between 0 and 512 */
1285 return 0; /* perfect match */
1287 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1288 below, we'd end up with max+1 (overflow)) */
1290 /* calculate the most significant bits of the final result */
1291 msb = (512 - bucket) << (32 - 9);
1292 /* calculate the 32-9 least significant bits of the final result by
1293 looking at the differences in the 32-9 bits following the
1294 mismatching bit at 'bucket' */
1296 for (i = bucket + 1;
1297 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1299 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
1300 GNUNET_CRYPTO_hash_get_bit (have, i))
1301 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1302 last bit set will be 31 -- if
1303 i does not reach 512 first... */
1309 * Return a number that is larger the closer the
1310 * "have" GNUNET_hash code is to the "target".
1312 * @return inverse distance metric, non-zero.
1313 * Must fudge the value if NO bits match.
1316 inverse_distance (const GNUNET_HashCode * target,
1317 const GNUNET_HashCode * have)
1319 if (GNUNET_CRYPTO_hash_matching_bits (target, have) == 0)
1320 return 1; /* Never return 0! */
1321 return ((unsigned int) -1) - distance (target, have);
1326 * Find the optimal bucket for this key, regardless
1327 * of the current number of buckets in use.
1329 * @param hc the hashcode to compare our identity to
1331 * @return the proper bucket index, or GNUNET_SYSERR
1332 * on error (same hashcode)
1335 find_bucket (const GNUNET_HashCode * hc)
1339 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
1340 if (bits == MAX_BUCKETS)
1341 return GNUNET_SYSERR;
1342 return MAX_BUCKETS - bits - 1;
1347 * Find which k-bucket this peer should go into,
1348 * taking into account the size of the k-bucket
1349 * array. This means that if more bits match than
1350 * there are currently buckets, lowest_bucket will
1353 * @param hc GNUNET_HashCode we are finding the bucket for.
1355 * @return the proper bucket index for this key,
1356 * or GNUNET_SYSERR on error (same hashcode)
1359 find_current_bucket (const GNUNET_HashCode * hc)
1363 actual_bucket = find_bucket (hc);
1364 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1365 return lowest_bucket;
1366 if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1367 return lowest_bucket;
1368 return actual_bucket;
1373 * Find a routing table entry from a peer identity
1375 * @param peer the peer to look up
1377 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1380 find_bucket_by_peer (const struct PeerInfo *peer)
1383 struct PeerInfo *pos;
1385 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1387 pos = k_buckets[bucket].head;
1396 return GNUNET_SYSERR; /* No such peer. */
1402 * Print the complete routing table for this peer.
1405 print_routing_table ()
1408 struct PeerInfo *pos;
1409 char char_buf[30000];
1411 memset (char_buf, 0, sizeof (char_buf));
1414 sprintf (&char_buf[char_pos], "Printing routing table for peer %s\n",
1416 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1417 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1419 pos = k_buckets[bucket].head;
1420 char_pos += sprintf (&char_buf[char_pos], "Bucket %d:\n", bucket);
1421 //fprintf(stderr, "Bucket %d:\n", bucket);
1424 //fprintf(stderr, "\tPeer %s, best bucket %d, %d bits match\n", GNUNET_i2s(&pos->id), find_bucket(&pos->id.hashPubKey), GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey));
1426 sprintf (&char_buf[char_pos],
1427 "\tPeer %s, best bucket %d, %d bits match\n",
1428 GNUNET_i2s (&pos->id), find_bucket (&pos->id.hashPubKey),
1429 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
1435 fprintf (stderr, "%s", char_buf);
1441 * Find a routing table entry from a peer identity
1443 * @param peer the peer identity to look up
1445 * @return the routing table entry, or NULL if not found
1447 static struct PeerInfo *
1448 find_peer_by_id (const struct GNUNET_PeerIdentity *peer)
1451 struct PeerInfo *pos;
1452 bucket = find_current_bucket (&peer->hashPubKey);
1454 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
1457 pos = k_buckets[bucket].head;
1460 if (0 == memcmp (&pos->id, peer, sizeof (struct GNUNET_PeerIdentity)))
1464 return NULL; /* No such peer. */
1467 /* Forward declaration */
1469 update_core_preference (void *cls,
1470 const struct GNUNET_SCHEDULER_TaskContext *tc);
1472 * Function called with statistics about the given peer.
1474 * @param cls closure
1475 * @param peer identifies the peer
1476 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1477 * @param amount set to the amount that was actually reserved or unreserved;
1478 * either the full requested amount or zero (no partial reservations)
1479 * @param res_delay if the reservation could not be satisfied (amount was 0), how
1480 * long should the client wait until re-trying?
1481 * @param preference current traffic preference for the given peer
1484 update_core_preference_finish (void *cls,
1485 const struct GNUNET_PeerIdentity *peer,
1486 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1488 struct GNUNET_TIME_Relative res_delay,
1489 uint64_t preference)
1491 struct PeerInfo *peer_info = cls;
1493 peer_info->info_ctx = NULL;
1494 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
1495 &update_core_preference, peer_info);
1499 update_core_preference (void *cls,
1500 const struct GNUNET_SCHEDULER_TaskContext *tc)
1502 struct PeerInfo *peer = cls;
1503 uint64_t preference;
1504 unsigned int matching;
1505 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1510 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
1511 &peer->id.hashPubKey);
1515 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1516 "Peer identifier matches by %u bits, only shifting as much as we can!\n",
1521 preference = 1LL << matching;
1522 peer->info_ctx = GNUNET_CORE_peer_change_preference (coreAPI,
1524 GNUNET_TIME_UNIT_FOREVER_REL,
1525 GNUNET_BANDWIDTH_VALUE_MAX,
1528 &update_core_preference_finish,
1534 * Given a peer and its corresponding bucket,
1535 * remove it from that bucket. Does not free
1536 * the PeerInfo struct, nor cancel messages
1537 * or free messages waiting to be sent to this
1540 * @param peer the peer to remove
1541 * @param bucket the bucket the peer belongs to
1544 remove_peer (struct PeerInfo *peer, unsigned int bucket)
1546 GNUNET_assert (k_buckets[bucket].peers_size > 0);
1547 GNUNET_CONTAINER_DLL_remove (k_buckets[bucket].head,
1548 k_buckets[bucket].tail, peer);
1549 k_buckets[bucket].peers_size--;
1551 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0)
1552 && (lowest_bucket < MAX_BUCKETS - 1))
1558 * Removes peer from a bucket, then frees associated
1559 * resources and frees peer.
1561 * @param peer peer to be removed and freed
1562 * @param bucket which bucket this peer belongs to
1565 delete_peer (struct PeerInfo *peer, unsigned int bucket)
1567 struct P2PPendingMessage *pos;
1568 struct P2PPendingMessage *next;
1570 struct PeerInfo *peer_pos;
1572 peer_pos = k_buckets[bucket].head;
1573 while ((peer_pos != NULL) && (peer_pos != peer))
1574 peer_pos = peer_pos->next;
1575 if (peer_pos == NULL)
1577 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1578 "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id,
1579 "DHT", GNUNET_i2s (&peer->id), bucket);
1580 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1581 "%s:%s: Lowest bucket: %d, find_current_bucket: %d, peer resides in bucket: %d\n",
1582 my_short_id, "DHT", lowest_bucket,
1583 find_current_bucket (&peer->id.hashPubKey),
1584 find_bucket_by_peer (peer));
1586 GNUNET_assert (peer_pos != NULL);
1588 remove_peer (peer, bucket); /* First remove the peer from its bucket */
1590 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1591 GNUNET_SCHEDULER_cancel (peer->send_task);
1592 if ((peer->th != NULL) && (coreAPI != NULL))
1593 GNUNET_CORE_notify_transmit_ready_cancel (peer->th);
1596 while (pos != NULL) /* Remove any pending messages for this peer */
1599 ("# dht pending messages discarded (due to disconnect/shutdown)");
1605 GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
1606 (all_known_peers, &peer->id.hashPubKey));
1607 GNUNET_assert (GNUNET_YES ==
1608 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
1609 &peer->id.hashPubKey,
1612 decrement_stats(STAT_PEERS_KNOWN);
1617 * Iterator over hash map entries.
1619 * @param cls closure
1620 * @param key current key code
1621 * @param value PeerInfo of the peer to move to new lowest bucket
1622 * @return GNUNET_YES if we should continue to
1627 move_lowest_bucket (void *cls, const GNUNET_HashCode * key, void *value)
1629 struct PeerInfo *peer = value;
1632 GNUNET_assert (lowest_bucket > 0);
1633 new_bucket = lowest_bucket - 1;
1634 remove_peer (peer, lowest_bucket);
1635 GNUNET_CONTAINER_DLL_insert_after (k_buckets[new_bucket].head,
1636 k_buckets[new_bucket].tail,
1637 k_buckets[new_bucket].tail, peer);
1638 k_buckets[new_bucket].peers_size++;
1644 * The current lowest bucket is full, so change the lowest
1645 * bucket to the next lower down, and move any appropriate
1646 * entries in the current lowest bucket to the new bucket.
1649 enable_next_bucket ()
1651 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1652 struct PeerInfo *pos;
1653 GNUNET_assert (lowest_bucket > 0);
1654 to_remove = GNUNET_CONTAINER_multihashmap_create (bucket_size);
1655 pos = k_buckets[lowest_bucket].head;
1658 fprintf (stderr, "Printing RT before new bucket\n");
1659 print_routing_table ();
1661 /* Populate the array of peers which should be in the next lowest bucket */
1664 if (find_bucket (&pos->id.hashPubKey) < lowest_bucket)
1665 GNUNET_CONTAINER_multihashmap_put (to_remove, &pos->id.hashPubKey,
1667 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1671 /* Remove peers from lowest bucket, insert into next lowest bucket */
1672 GNUNET_CONTAINER_multihashmap_iterate (to_remove, &move_lowest_bucket,
1674 GNUNET_CONTAINER_multihashmap_destroy (to_remove);
1675 lowest_bucket = lowest_bucket - 1;
1677 fprintf (stderr, "Printing RT after new bucket\n");
1678 print_routing_table ();
1683 * Find the closest peer in our routing table to the
1686 * @return The closest peer in our routing table to the
1687 * key, or NULL on error.
1689 static struct PeerInfo *
1690 find_closest_peer (const GNUNET_HashCode * hc)
1692 struct PeerInfo *pos;
1693 struct PeerInfo *current_closest;
1694 unsigned int lowest_distance;
1695 unsigned int temp_distance;
1699 lowest_distance = -1;
1701 if (k_buckets[lowest_bucket].peers_size == 0)
1704 current_closest = NULL;
1705 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1707 pos = k_buckets[bucket].head;
1709 while ((pos != NULL) && (count < bucket_size))
1711 temp_distance = distance (&pos->id.hashPubKey, hc);
1712 if (temp_distance <= lowest_distance)
1714 lowest_distance = temp_distance;
1715 current_closest = pos;
1721 GNUNET_assert (current_closest != NULL);
1722 return current_closest;
1727 * Function called to send a request out to another peer.
1728 * Called both for locally initiated requests and those
1729 * received from other peers.
1731 * @param msg the encapsulated message
1732 * @param peer the peer to forward the message to
1733 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1736 forward_message (const struct GNUNET_MessageHeader *msg,
1737 struct PeerInfo *peer, struct DHT_MessageContext *msg_ctx)
1739 struct GNUNET_DHT_P2PRouteMessage *route_message;
1740 struct P2PPendingMessage *pending;
1745 increment_stats (STAT_ROUTE_FORWARDS);
1746 GNUNET_assert (peer != NULL);
1747 if ((msg_ctx->closest != GNUNET_YES)
1748 && (peer == find_closest_peer (&msg_ctx->key)))
1749 increment_stats (STAT_ROUTE_FORWARDS_CLOSEST);
1751 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs (msg->size) + (msg_ctx->path_history_len * sizeof(struct GNUNET_PeerIdentity));
1752 GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1753 psize = sizeof (struct P2PPendingMessage) + msize;
1754 pending = GNUNET_malloc (psize);
1755 pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1756 pending->importance = msg_ctx->importance;
1757 pending->timeout = msg_ctx->timeout;
1758 route_message = (struct GNUNET_DHT_P2PRouteMessage *) pending->msg;
1759 route_message->header.size = htons (msize);
1760 route_message->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1761 route_message->options = htonl (msg_ctx->msg_options);
1762 route_message->hop_count = htonl (msg_ctx->hop_count + 1);
1763 route_message->network_size = htonl (msg_ctx->network_size);
1764 route_message->desired_replication_level = htonl (msg_ctx->replication);
1765 route_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1766 if (msg_ctx->bloom != NULL)
1767 GNUNET_assert (GNUNET_OK ==
1768 GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1772 memcpy (&route_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1773 memcpy (&route_message[1], msg, ntohs (msg->size));
1774 if (GNUNET_DHT_RO_RECORD_ROUTE == (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
1776 route_message->outgoing_path_length = htonl(msg_ctx->path_history_len);
1777 /* Set pointer to start of enc_msg */
1778 route_path = (char *)&route_message[1];
1779 /* Offset to the end of the enc_msg */
1780 route_path += ntohs (msg->size);
1781 /* Copy the route_path after enc_msg */
1782 memcpy (route_path, msg_ctx->path_history, msg_ctx->path_history_len * sizeof(struct GNUNET_PeerIdentity));
1785 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1786 "%s:%s Adding pending message size %d for peer %s\n",
1787 my_short_id, "DHT", msize, GNUNET_i2s (&peer->id));
1789 peer->pending_count++;
1790 increment_stats ("# pending messages scheduled");
1791 GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1793 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1794 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1799 * Task used to send ping messages to peers so that
1800 * they don't get disconnected.
1802 * @param cls the peer to send a ping message to
1803 * @param tc context, reason, etc.
1806 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1808 struct PeerInfo *peer = cls;
1809 struct GNUNET_MessageHeader ping_message;
1810 struct DHT_MessageContext msg_ctx;
1812 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1815 ping_message.size = htons (sizeof (struct GNUNET_MessageHeader));
1816 ping_message.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1818 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
1820 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1821 "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT",
1822 GNUNET_i2s (&peer->id));
1824 forward_message (&ping_message, peer, &msg_ctx);
1826 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PING_DELAY, &periodic_ping_task,
1831 * Schedule PING messages for the top X peers in each
1832 * bucket of the routing table (so core won't disconnect them!)
1835 schedule_ping_messages ()
1837 unsigned int bucket;
1839 struct PeerInfo *pos;
1840 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1842 pos = k_buckets[bucket].head;
1846 if ((count < bucket_size)
1847 && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1848 GNUNET_SCHEDULER_add_now (&periodic_ping_task, pos);
1849 else if ((count >= bucket_size)
1850 && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1852 GNUNET_SCHEDULER_cancel (pos->ping_task);
1853 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1864 * Task run to check for messages that need to be sent to a client.
1866 * @param client a ClientList, containing the client and any messages to be sent to it
1869 process_pending_messages (struct ClientList *client)
1871 if (client->pending_head == NULL)
1873 if (client->transmit_handle != NULL)
1876 client->transmit_handle =
1877 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1878 ntohs (client->pending_head->
1880 GNUNET_TIME_UNIT_FOREVER_REL,
1881 &send_generic_reply, client);
1885 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1886 * request. A ClientList is passed as closure, take the head of the list
1887 * and copy it into buf, which has the result of sending the message to the
1890 * @param cls closure to this call
1891 * @param size maximum number of bytes available to send
1892 * @param buf where to copy the actual message to
1894 * @return the number of bytes actually copied, 0 indicates failure
1897 send_generic_reply (void *cls, size_t size, void *buf)
1899 struct ClientList *client = cls;
1901 struct PendingMessage *reply;
1905 client->transmit_handle = NULL;
1908 /* client disconnected */
1912 while ((NULL != (reply = client->pending_head)) &&
1913 (size >= off + (msize = ntohs (reply->msg->size))))
1915 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1916 client->pending_tail, reply);
1917 memcpy (&cbuf[off], reply->msg, msize);
1918 GNUNET_free (reply);
1921 process_pending_messages (client);
1923 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1924 "Transmitted %u bytes of replies to client\n",
1925 (unsigned int) off);
1932 * Add a PendingMessage to the clients list of messages to be sent
1934 * @param client the active client to send the message to
1935 * @param pending_message the actual message to send
1938 add_pending_message (struct ClientList *client,
1939 struct PendingMessage *pending_message)
1941 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1942 client->pending_tail,
1943 client->pending_tail, pending_message);
1944 process_pending_messages (client);
1949 * Called when a reply needs to be sent to a client, as
1950 * a result it found to a GET or FIND PEER request.
1952 * @param client the client to send the reply to
1953 * @param message the encapsulated message to send
1954 * @param msg_ctx the context of the received message
1957 send_reply_to_client (struct ClientList *client,
1958 const struct GNUNET_MessageHeader *message,
1959 struct DHT_MessageContext *msg_ctx)
1961 struct GNUNET_DHT_RouteResultMessage *reply;
1962 struct PendingMessage *pending_message;
1971 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1972 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1974 msize = ntohs (message->size);
1975 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize + (msg_ctx->path_history_len * sizeof(struct GNUNET_PeerIdentity));
1976 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1978 GNUNET_break_op (0);
1981 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1982 pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1983 reply = (struct GNUNET_DHT_RouteResultMessage *) &pending_message[1];
1984 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1985 reply->header.size = htons (tsize);
1986 reply->outgoing_path_length = htonl(msg_ctx->path_history_len);
1987 reply->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1988 memcpy (&reply->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1989 reply_offset = (char *)&reply[1];
1990 memcpy (&reply[1], message, msize);
1991 if (msg_ctx->path_history_len > 0)
1993 reply_offset += msize;
1994 memcpy(reply_offset, msg_ctx->path_history, msg_ctx->path_history_len * sizeof(struct GNUNET_PeerIdentity));
1997 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Returning message with outgoing path length %d\n", msg_ctx->path_history_len);
1998 for (i = 0; i < msg_ctx->path_history_len; i++)
2000 path_offset = &msg_ctx->path_history[i * sizeof(struct GNUNET_PeerIdentity)];
2001 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Found peer %d:%s\n", i, GNUNET_i2s((struct GNUNET_PeerIdentity *)path_offset));
2004 add_pending_message (client, pending_message);
2008 * Consider whether or not we would like to have this peer added to
2009 * our routing table. Check whether bucket for this peer is full,
2010 * if so return negative; if not return positive. Since peers are
2011 * only added on CORE level connect, this doesn't actually add the
2012 * peer to the routing table.
2014 * @param peer the peer we are considering adding
2016 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
2020 consider_peer (struct GNUNET_PeerIdentity *peer)
2025 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
2028 memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity))))
2029 return GNUNET_NO; /* We already know this peer (are connected even!) */
2030 bucket = find_current_bucket (&peer->hashPubKey);
2032 if ((k_buckets[bucket].peers_size < bucket_size)
2033 || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
2041 * Task used to remove forwarding entries, either
2042 * after timeout, when full, or on shutdown.
2044 * @param cls the entry to remove
2045 * @param tc context, reason, etc.
2048 remove_forward_entry (void *cls,
2049 const struct GNUNET_SCHEDULER_TaskContext *tc)
2051 struct DHTRouteSource *source_info = cls;
2052 struct DHTQueryRecord *record;
2054 GNUNET_CONTAINER_heap_remove_node (source_info->hnode);
2055 record = source_info->record;
2056 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
2058 if (record->head == NULL) /* No more entries in DLL */
2060 GNUNET_assert (GNUNET_YES ==
2061 GNUNET_CONTAINER_multihashmap_remove
2062 (forward_list.hashmap, &record->key, record));
2063 GNUNET_free (record);
2065 if (source_info->find_peers_responded != NULL)
2066 GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
2067 GNUNET_free (source_info);
2071 * Main function that handles whether or not to route a result
2072 * message to other peers, or to send to our local client.
2074 * @param msg the result message to be routed
2075 * @param msg_ctx context of the message we are routing
2077 * @return the number of peers the message was routed to,
2078 * GNUNET_SYSERR on failure
2081 route_result_message (struct GNUNET_MessageHeader *msg,
2082 struct DHT_MessageContext *msg_ctx)
2084 struct GNUNET_PeerIdentity new_peer;
2085 struct DHTQueryRecord *record;
2086 struct DHTRouteSource *pos;
2087 struct PeerInfo *peer_info;
2088 const struct GNUNET_MessageHeader *hello_msg;
2093 increment_stats (STAT_RESULTS);
2095 * If a find peer result message is received and contains a valid
2096 * HELLO for another peer, offer it to the transport service.
2098 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
2100 if (ntohs (msg->size) <= sizeof (struct GNUNET_MessageHeader))
2101 GNUNET_break_op (0);
2103 hello_msg = &msg[1];
2104 if ((ntohs (hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO)
2105 || (GNUNET_SYSERR ==
2106 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *)
2107 hello_msg, &new_peer)))
2109 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2110 "%s:%s Received non-HELLO message type in find peer result message!\n",
2111 my_short_id, "DHT");
2112 GNUNET_break_op (0);
2115 else /* We have a valid hello, and peer id stored in new_peer */
2117 find_peer_context.count++;
2118 increment_stats (STAT_FIND_PEER_REPLY);
2119 if (GNUNET_YES == consider_peer (&new_peer))
2121 increment_stats (STAT_HELLOS_PROVIDED);
2122 GNUNET_TRANSPORT_offer_hello (transport_handle, hello_msg, NULL, NULL);
2123 GNUNET_CORE_peer_request_connect (coreAPI,
2124 &new_peer, NULL, NULL);
2129 if (malicious_dropper == GNUNET_YES)
2133 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
2135 if (record == NULL) /* No record of this message! */
2138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2139 "`%s:%s': Have no record of response key %s uid %llu\n",
2140 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2141 msg_ctx->unique_id);
2143 #if DEBUG_DHT_ROUTING
2144 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2146 dhtlog_handle->insert_route (NULL,
2152 &msg_ctx->key, msg_ctx->peer, NULL);
2155 if (msg_ctx->bloom != NULL)
2157 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
2158 msg_ctx->bloom = NULL;
2166 #if STRICT_FORWARDING
2167 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2170 GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded,
2171 &new_peer.hashPubKey))
2174 ("# find peer responses NOT forwarded (bloom match)");
2179 GNUNET_CONTAINER_bloomfilter_add (pos->find_peers_responded,
2180 &new_peer.hashPubKey);
2184 if (0 == memcmp (&pos->source, &my_identity, sizeof (struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2187 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2188 "`%s:%s': Sending response key %s uid %llu to client\n",
2189 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2190 msg_ctx->unique_id);
2192 #if DEBUG_DHT_ROUTING
2193 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2195 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id,
2196 DHTLOG_RESULT, msg_ctx->hop_count,
2197 GNUNET_YES, &my_identity,
2198 &msg_ctx->key, msg_ctx->peer,
2202 increment_stats (STAT_RESULTS_TO_CLIENT);
2203 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2204 increment_stats (STAT_GET_REPLY);
2206 for (i = 0; i < msg_ctx->path_history_len; i++)
2210 path_offset = &msg_ctx->path_history[i * sizeof(struct GNUNET_PeerIdentity)];
2211 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2212 "(before client) Key %s Found peer %d:%s\n",
2213 GNUNET_h2s(&msg_ctx->key), i,
2214 GNUNET_i2s((struct GNUNET_PeerIdentity *)path_offset));
2217 send_reply_to_client (pos->client, msg, msg_ctx);
2219 else /* Send to peer */
2221 peer_info = find_peer_by_id (&pos->source);
2222 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2228 if (msg_ctx->bloom == NULL)
2230 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
2232 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
2233 &my_identity.hashPubKey);
2235 GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom,
2236 &peer_info->id.hashPubKey)))
2239 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2240 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n",
2241 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2242 msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2244 #if DEBUG_DHT_ROUTING
2245 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2247 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id,
2250 GNUNET_NO, &my_identity,
2251 &msg_ctx->key, msg_ctx->peer,
2255 forward_result_message (msg, peer_info, msg_ctx);
2256 /* Try removing forward entries after sending once, only allows ONE response per request */
2257 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
2259 GNUNET_SCHEDULER_cancel (pos->delete_task);
2261 GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
2267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2268 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n",
2269 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2270 msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2276 if (msg_ctx->bloom != NULL)
2278 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
2279 msg_ctx->bloom = NULL;
2285 * Iterator for local get request results,
2287 * @param cls closure for iterator, a DatacacheGetContext
2288 * @param exp when does this value expire?
2289 * @param key the key this data is stored under
2290 * @param size the size of the data identified by key
2291 * @param data the actual data
2292 * @param type the type of the data
2294 * @return GNUNET_OK to continue iteration, anything else
2295 * to stop iteration.
2298 datacache_get_iterator (void *cls,
2299 struct GNUNET_TIME_Absolute exp,
2300 const GNUNET_HashCode * key,
2301 size_t size, const char *data,
2302 enum GNUNET_BLOCK_Type type)
2304 struct DHT_MessageContext *msg_ctx = cls;
2305 struct DHT_MessageContext *new_msg_ctx;
2306 struct GNUNET_DHT_GetResultMessage *get_result;
2307 enum GNUNET_BLOCK_EvaluationResult eval;
2308 const struct DHTPutEntry *put_entry;
2316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2317 "`%s:%s': Received `%s' response from datacache\n", my_short_id,
2321 put_entry = (const struct DHTPutEntry *)data;
2323 if (size != sizeof(struct DHTPutEntry) +
2324 put_entry->data_size +
2325 (put_entry->path_length * sizeof(struct GNUNET_PeerIdentity)))
2328 GNUNET_ERROR_TYPE_WARNING,
2329 "Path + data size doesn't add up for data inserted into datacache!\nData size %d, path length %d, expected %d, got %d\n",
2330 put_entry->data_size, put_entry->path_length,
2331 sizeof(struct DHTPutEntry) + put_entry->data_size
2332 + (put_entry->path_length * sizeof(struct GNUNET_PeerIdentity)),
2334 msg_ctx->do_forward = GNUNET_NO;
2338 eval = GNUNET_BLOCK_evaluate (block_context,
2342 msg_ctx->reply_bf_mutator,
2344 msg_ctx->xquery_size, &put_entry[1], put_entry->data_size);
2348 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2349 msg_ctx->do_forward = GNUNET_NO;
2350 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2351 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2352 memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2353 if (GNUNET_DHT_RO_RECORD_ROUTE == (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2355 new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2356 new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2357 /* Assign to previous msg_ctx path history, caller should free after our return */
2358 new_msg_ctx->path_history = msg_ctx->path_history;
2360 for (i = 0; i < new_msg_ctx->path_history_len; i++)
2362 path_offset = &new_msg_ctx->path_history[i * sizeof(struct GNUNET_PeerIdentity)];
2363 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "(get_iterator) Key %s Found peer %d:%s\n", GNUNET_h2s(&msg_ctx->key), i, GNUNET_i2s((struct GNUNET_PeerIdentity *)path_offset));
2368 get_size = sizeof (struct GNUNET_DHT_GetResultMessage) + put_entry->data_size + (put_entry->path_length * sizeof(struct GNUNET_PeerIdentity));
2369 get_result = GNUNET_malloc (get_size);
2370 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2371 get_result->header.size = htons (get_size);
2372 get_result->expiration = GNUNET_TIME_absolute_hton (exp);
2373 get_result->type = htons (type);
2374 get_result->put_path_length = htons(put_entry->path_length);
2375 path_offset = (char *)&put_entry[1];
2376 path_offset += put_entry->data_size;
2378 for (i = 0; i < put_entry->path_length; i++)
2380 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "(get_iterator PUT path) Key %s Found peer %d:%s\n", GNUNET_h2s(&msg_ctx->key), i, GNUNET_i2s((struct GNUNET_PeerIdentity *)&path_offset[i * sizeof(struct GNUNET_PeerIdentity)]));
2383 /* Copy the actual data and the path_history to the end of the get result */
2384 memcpy (&get_result[1], &put_entry[1], put_entry->data_size + (put_entry->path_length * sizeof(struct GNUNET_PeerIdentity)));
2385 new_msg_ctx->peer = &my_identity;
2386 new_msg_ctx->bloom =
2387 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2388 new_msg_ctx->hop_count = 0;
2389 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
2390 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2391 increment_stats (STAT_GET_RESPONSE_START);
2392 route_result_message (&get_result->header, new_msg_ctx);
2393 GNUNET_free (new_msg_ctx);
2394 GNUNET_free (get_result);
2396 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2399 "`%s:%s': Duplicate block error\n", my_short_id, "DHT");
2402 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2404 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2405 "`%s:%s': Invalid request error\n", my_short_id, "DHT");
2408 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2410 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2411 "`%s:%s': Valid request, no results.\n", my_short_id,
2416 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2417 GNUNET_break_op (0);
2418 msg_ctx->do_forward = GNUNET_NO;
2420 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2422 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2423 "`%s:%s': Unsupported block type (%u) in response!\n",
2424 my_short_id, "DHT", type);
2426 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2434 * Main function that handles whether or not to route a message to other
2437 * @param msg the message to be routed
2438 * @param msg_ctx the context containing all pertinent information about the message
2441 route_message (const struct GNUNET_MessageHeader *msg,
2442 struct DHT_MessageContext *msg_ctx);
2446 * Server handler for all dht get requests, look for data,
2447 * if found, send response either to clients or other peers.
2449 * @param msg the actual get message
2450 * @param msg_ctx struct containing pertinent information about the get request
2452 * @return number of items found for GET request
2455 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2456 struct DHT_MessageContext *msg_ctx)
2458 const struct GNUNET_DHT_GetMessage *get_msg;
2461 unsigned int results;
2463 enum GNUNET_BLOCK_Type type;
2465 msize = ntohs (msg->size);
2466 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2471 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2472 bf_size = ntohs (get_msg->bf_size);
2473 msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2474 msg_ctx->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2476 sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2481 end = (const char *) &get_msg[1];
2482 if (msg_ctx->xquery_size == 0)
2484 msg_ctx->xquery = NULL;
2488 msg_ctx->xquery = (const void *) end;
2489 end += msg_ctx->xquery_size;
2493 msg_ctx->reply_bf = NULL;
2497 msg_ctx->reply_bf = GNUNET_CONTAINER_bloomfilter_init (end,
2499 GNUNET_DHT_GET_BLOOMFILTER_K);
2501 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2503 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2504 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2507 type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2509 increment_stats (STAT_GETS);
2512 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2514 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2518 msg_ctx->do_forward = GNUNET_YES;
2519 if (datacache != NULL)
2521 = GNUNET_DATACACHE_get (datacache,
2522 &msg_ctx->key, type,
2523 &datacache_get_iterator, msg_ctx);
2525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2526 "`%s:%s': Found %d results for `%s' request uid %llu\n",
2527 my_short_id, "DHT", results, "GET", msg_ctx->unique_id);
2531 #if DEBUG_DHT_ROUTING
2532 if ((debug_routes) && (dhtlog_handle != NULL))
2534 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2535 msg_ctx->hop_count, GNUNET_YES,
2536 &my_identity, &msg_ctx->key);
2539 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2541 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2542 msg_ctx->hop_count, GNUNET_YES,
2543 &my_identity, &msg_ctx->key,
2544 msg_ctx->peer, NULL);
2550 /* check query valid */
2551 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID
2552 == GNUNET_BLOCK_evaluate (block_context,
2556 msg_ctx->reply_bf_mutator,
2558 msg_ctx->xquery_size, NULL, 0))
2560 GNUNET_break_op (0);
2561 msg_ctx->do_forward = GNUNET_NO;
2565 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2567 #if DEBUG_DHT_ROUTING
2568 if ((debug_routes) && (dhtlog_handle != NULL))
2570 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2571 msg_ctx->hop_count, GNUNET_NO,
2572 &my_identity, &msg_ctx->key);
2576 if (msg_ctx->do_forward == GNUNET_YES)
2577 route_message (msg, msg_ctx);
2578 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2583 remove_recent_find_peer (void *cls,
2584 const struct GNUNET_SCHEDULER_TaskContext *tc)
2586 GNUNET_HashCode *key = cls;
2588 GNUNET_assert (GNUNET_YES ==
2589 GNUNET_CONTAINER_multihashmap_remove
2590 (recent_find_peer_requests, key, NULL));
2595 * Server handler for initiating local dht find peer requests
2597 * @param find_msg the actual find peer message
2598 * @param msg_ctx struct containing pertinent information about the request
2602 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2603 struct DHT_MessageContext *msg_ctx)
2605 struct GNUNET_MessageHeader *find_peer_result;
2606 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2607 struct DHT_MessageContext *new_msg_ctx;
2608 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2611 GNUNET_HashCode *recent_hash;
2612 struct GNUNET_MessageHeader *other_hello;
2613 size_t other_hello_size;
2614 struct GNUNET_PeerIdentity peer_id;
2616 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *) find_msg;
2617 GNUNET_break_op (ntohs (find_msg->size) >=
2618 (sizeof (struct GNUNET_DHT_FindPeerMessage)));
2619 if (ntohs (find_msg->size) < sizeof (struct GNUNET_DHT_FindPeerMessage))
2622 other_hello_size = 0;
2623 if (ntohs (find_msg->size) > sizeof (struct GNUNET_DHT_FindPeerMessage))
2626 ntohs (find_msg->size) - sizeof (struct GNUNET_DHT_FindPeerMessage);
2627 other_hello = GNUNET_malloc (other_hello_size);
2628 memcpy (other_hello, &find_peer_message[1], other_hello_size);
2629 if ((GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) other_hello) ==
2632 GNUNET_HELLO_get_id ((struct GNUNET_HELLO_Message *)
2633 other_hello, &peer_id)))
2635 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2636 "Received invalid HELLO message in find peer request!\n");
2637 GNUNET_free (other_hello);
2640 #if FIND_PEER_WITH_HELLO
2641 if (GNUNET_YES == consider_peer (&peer_id))
2643 increment_stats (STAT_HELLOS_PROVIDED);
2644 GNUNET_TRANSPORT_offer_hello (transport_handle, other_hello, NULL, NULL);
2645 GNUNET_CORE_peer_request_connect (coreAPI,
2646 &peer_id, NULL, NULL);
2647 route_message (find_msg, msg_ctx);
2648 GNUNET_free (other_hello);
2651 else /* We don't want this peer! */
2653 route_message (find_msg, msg_ctx);
2654 GNUNET_free (other_hello);
2661 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2662 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2663 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2664 ntohs (find_msg->size), sizeof (struct GNUNET_MessageHeader));
2666 if (my_hello == NULL)
2669 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2670 "`%s': Our HELLO is null, can't return.\n", "DHT");
2672 GNUNET_free_non_null (other_hello);
2673 route_message (find_msg, msg_ctx);
2678 GNUNET_CONTAINER_bloomfilter_init (find_peer_message->bloomfilter,
2679 DHT_BLOOM_SIZE, DHT_BLOOM_K);
2681 GNUNET_CONTAINER_bloomfilter_test (incoming_bloom,
2682 &my_identity.hashPubKey))
2684 increment_stats (STAT_BLOOM_FIND_PEER);
2685 GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2686 GNUNET_free_non_null (other_hello);
2687 route_message (find_msg, msg_ctx);
2688 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!) */
2690 GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2692 #if RESTRICT_FIND_PEER
2695 * Ignore any find peer requests from a peer we have seen very recently.
2697 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent_find_peer_requests, &msg_ctx->key)) /* We have recently responded to a find peer request for this peer! */
2699 increment_stats ("# dht find peer requests ignored (recently seen!)");
2700 GNUNET_free_non_null (other_hello);
2705 * Use this check to only allow the peer to respond to find peer requests if
2706 * it would be beneficial to have the requesting peer in this peers routing
2707 * table. Can be used to thwart peers flooding the network with find peer
2708 * requests that we don't care about. However, if a new peer is joining
2709 * the network and has no other peers this is a problem (assume all buckets
2710 * full, no one will respond!).
2712 memcpy (&peer_id.hashPubKey, &msg_ctx->key, sizeof (GNUNET_HashCode));
2713 if (GNUNET_NO == consider_peer (&peer_id))
2715 increment_stats ("# dht find peer requests ignored (do not need!)");
2716 GNUNET_free_non_null (other_hello);
2717 route_message (find_msg, msg_ctx);
2722 recent_hash = GNUNET_malloc (sizeof (GNUNET_HashCode));
2723 memcpy (recent_hash, &msg_ctx->key, sizeof (GNUNET_HashCode));
2724 if (GNUNET_SYSERR !=
2725 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2726 &msg_ctx->key, NULL,
2727 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2730 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2731 "Adding recent remove task for key `%s`!\n",
2732 GNUNET_h2s (&msg_ctx->key));
2734 /* Only add a task if there wasn't one for this key already! */
2735 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2736 (GNUNET_TIME_UNIT_SECONDS, 30),
2737 &remove_recent_find_peer, recent_hash);
2741 GNUNET_free (recent_hash);
2743 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2744 "Received duplicate find peer request too soon!\n");
2748 /* Simplistic find_peer functionality, always return our hello */
2749 hello_size = ntohs (my_hello->size);
2750 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2752 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2754 GNUNET_break_op (0);
2755 GNUNET_free_non_null (other_hello);
2759 find_peer_result = GNUNET_malloc (tsize);
2760 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2761 find_peer_result->size = htons (tsize);
2762 memcpy (&find_peer_result[1], my_hello, hello_size);
2764 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2765 "`%s': Sending hello size %d to requesting peer.\n",
2769 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2770 memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2771 new_msg_ctx->peer = &my_identity;
2772 new_msg_ctx->bloom =
2773 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2774 new_msg_ctx->hop_count = 0;
2775 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make find peer requests a higher priority */
2776 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2777 increment_stats (STAT_FIND_PEER_ANSWER);
2778 if (GNUNET_DHT_RO_RECORD_ROUTE == (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2780 new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2781 new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2782 /* Assign to previous msg_ctx path history, caller should free after our return */
2783 new_msg_ctx->path_history = msg_ctx->path_history;
2785 route_result_message (find_peer_result, new_msg_ctx);
2786 GNUNET_free (new_msg_ctx);
2787 #if DEBUG_DHT_ROUTING
2788 if ((debug_routes) && (dhtlog_handle != NULL))
2790 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2791 msg_ctx->hop_count, GNUNET_YES,
2792 &my_identity, &msg_ctx->key);
2795 GNUNET_free_non_null (other_hello);
2796 GNUNET_free (find_peer_result);
2797 route_message (find_msg, msg_ctx);
2801 * Task used to republish data.
2802 * Forward declaration; function call loop.
2804 * @param cls closure (a struct RepublishContext)
2805 * @param tc runtime context for this task
2808 republish_content (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2811 * Server handler for initiating local dht put requests
2813 * @param msg the actual put message
2814 * @param msg_ctx struct containing pertinent information about the request
2817 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2818 struct DHT_MessageContext *msg_ctx)
2820 const struct GNUNET_DHT_PutMessage *put_msg;
2821 struct DHTPutEntry *put_entry;
2822 unsigned int put_size;
2824 enum GNUNET_BLOCK_Type put_type;
2827 struct RepublishContext *put_context;
2828 GNUNET_HashCode key;
2830 GNUNET_assert (ntohs (msg->size) >= sizeof (struct GNUNET_DHT_PutMessage));
2832 put_msg = (const struct GNUNET_DHT_PutMessage *) msg;
2833 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2835 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2837 #if DEBUG_DHT_ROUTING
2838 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2840 /** Log routes that die due to high load! */
2841 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2842 msg_ctx->hop_count, GNUNET_SYSERR,
2843 &my_identity, &msg_ctx->key,
2844 msg_ctx->peer, NULL);
2851 ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2853 GNUNET_BLOCK_get_key (block_context, put_type, &put_msg[1], data_size,
2855 if (GNUNET_NO == ret)
2857 #if DEBUG_DHT_ROUTING
2858 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2860 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2861 msg_ctx->hop_count, GNUNET_SYSERR,
2862 &my_identity, &msg_ctx->key,
2863 msg_ctx->peer, NULL);
2867 GNUNET_break_op (0);
2870 if ((GNUNET_YES == ret) &&
2871 (0 != memcmp (&key, &msg_ctx->key, sizeof (GNUNET_HashCode))))
2873 #if DEBUG_DHT_ROUTING
2874 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2876 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2877 msg_ctx->hop_count, GNUNET_SYSERR,
2878 &my_identity, &msg_ctx->key,
2879 msg_ctx->peer, NULL);
2882 /* invalid wrapper: key mismatch! */
2883 GNUNET_break_op (0);
2886 /* ret == GNUNET_SYSERR means that there is no known relationship between
2887 data and the key, so we cannot check it */
2889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2890 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2891 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2892 msg_ctx->unique_id);
2894 #if DEBUG_DHT_ROUTING
2895 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2897 if ((debug_routes) && (dhtlog_handle != NULL))
2899 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2900 msg_ctx->hop_count, GNUNET_NO,
2901 &my_identity, &msg_ctx->key);
2906 if (msg_ctx->closest != GNUNET_YES)
2908 route_message (msg, msg_ctx);
2913 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2914 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2915 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2916 msg_ctx->unique_id);
2919 #if DEBUG_DHT_ROUTING
2920 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2922 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2923 msg_ctx->hop_count, GNUNET_YES,
2924 &my_identity, &msg_ctx->key, msg_ctx->peer,
2928 if ((debug_routes) && (dhtlog_handle != NULL))
2930 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2931 msg_ctx->hop_count, GNUNET_YES,
2932 &my_identity, &msg_ctx->key);
2936 increment_stats (STAT_PUTS_INSERTED);
2937 if (datacache != NULL)
2939 /* Put size is actual data size plus struct overhead plus path length (if any) */
2940 put_size = data_size + sizeof(struct DHTPutEntry) + (msg_ctx->path_history_len * sizeof(struct GNUNET_PeerIdentity));
2941 put_entry = GNUNET_malloc(put_size);
2942 put_entry->data_size = data_size;
2943 put_entry->path_length = msg_ctx->path_history_len;
2944 /* Copy data to end of put entry */
2945 memcpy(&put_entry[1], &put_msg[1], data_size);
2946 if (msg_ctx->path_history_len > 0)
2948 /* Copy path after data */
2949 path_offset = (char *)&put_entry[1];
2950 path_offset += data_size;
2951 memcpy(path_offset, msg_ctx->path_history, msg_ctx->path_history_len * sizeof(struct GNUNET_PeerIdentity));
2954 ret = GNUNET_DATACACHE_put (datacache, &msg_ctx->key, put_size,
2955 (const char *) put_entry, put_type,
2956 GNUNET_TIME_absolute_ntoh
2957 (put_msg->expiration));
2958 GNUNET_free (put_entry);
2960 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2962 put_context = GNUNET_malloc (sizeof (struct RepublishContext));
2963 memcpy (&put_context->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
2964 put_context->type = put_type;
2965 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency,
2966 &republish_content, put_context);
2970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2971 "`%s:%s': %s request received, but have no datacache!\n",
2972 my_short_id, "DHT", "PUT");
2974 if (stop_on_closest == GNUNET_NO)
2975 route_message (msg, msg_ctx);
2979 * Estimate the diameter of the network based
2980 * on how many buckets are currently in use.
2981 * Concept here is that the diameter of the network
2982 * is roughly the distance a message must travel in
2983 * order to reach its intended destination. Since
2984 * at each hop we expect to get one bit closer, and
2985 * we have one bit per bucket, the number of buckets
2986 * in use should be the largest number of hops for
2987 * a successful message. (of course, this assumes we
2988 * know all peers in the network!)
2990 * @return ballpark diameter figure
2993 estimate_diameter ()
2995 return MAX_BUCKETS - lowest_bucket;
2999 * To how many peers should we (on average)
3000 * forward the request to obtain the desired
3001 * target_replication count (on average).
3003 * returns: target_replication / (est. hops) + (target_replication * hop_count)
3004 * where est. hops is typically 2 * the routing table depth
3006 * @param hop_count number of hops the message has traversed
3007 * @param target_replication the number of total paths desired
3009 * @return Some number of peers to forward the message to
3012 get_forward_count (unsigned int hop_count, size_t target_replication)
3014 uint32_t random_value;
3015 unsigned int forward_count;
3017 unsigned int diameter;
3019 diameter = estimate_diameter ();
3021 if (GNUNET_NO == use_max_hops)
3022 max_hops = (diameter + 1) * 2;
3025 * If we are behaving in strict kademlia mode, send multiple initial requests,
3026 * but then only send to 1 or 0 peers based strictly on the number of hops.
3028 if (strict_kademlia == GNUNET_YES)
3031 return kademlia_replication;
3032 else if (hop_count < max_hops)
3038 /* FIXME: the smaller we think the network is the more lenient we should be for
3039 * routing right? The estimation below only works if we think we have reasonably
3040 * full routing tables, which for our RR topologies may not be the case!
3042 if (hop_count > max_hops)
3045 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3046 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n",
3047 my_short_id, "DHT", estimate_diameter (), lowest_bucket);
3049 /* FIXME: does this work as intended, isn't the decision to forward or not made based on closeness as well? */
3050 if (GNUNET_YES == paper_forwarding) /* Once we have reached our ideal number of hops, don't stop forwarding! */
3058 if (GNUNET_YES == paper_forwarding)
3060 /* FIXME: re-run replication trials with this formula */
3061 target_value = 1 + (target_replication - 1.0) / (diameter
3062 + ((float) (target_replication - 1.0) * hop_count));
3063 /* Set forward count to floor of target_value */
3064 forward_count = (unsigned int) target_value;
3065 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
3066 target_value = target_value - forward_count;
3067 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG,
3070 if (random_value < (target_value * UINT32_MAX))
3077 target_value = target_replication / (diameter
3078 + ((float) target_replication * hop_count));
3079 if (target_value > 1)
3081 /* Set forward count to floor of target_value */
3082 forward_count = (unsigned int) target_value;
3083 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
3084 target_value = target_value - forward_count;
3087 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG,
3090 if (random_value < (target_value * UINT32_MAX))
3094 return forward_count;
3098 * Check whether my identity is closer than any known peers.
3099 * If a non-null bloomfilter is given, check if this is the closest
3100 * peer that hasn't already been routed to.
3102 * @param target hash code to check closeness to
3103 * @param bloom bloomfilter, exclude these entries from the decision
3105 * Return GNUNET_YES if node location is closest, GNUNET_NO
3109 am_closest_peer (const GNUNET_HashCode * target,
3110 struct GNUNET_CONTAINER_BloomFilter *bloom)
3116 struct PeerInfo *pos;
3117 unsigned int my_distance;
3119 if (0 == memcmp (&my_identity.hashPubKey, target, sizeof (GNUNET_HashCode)))
3122 bucket_num = find_current_bucket (target);
3124 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, target);
3125 my_distance = distance (&my_identity.hashPubKey, target);
3126 pos = k_buckets[bucket_num].head;
3128 while ((pos != NULL) && (count < bucket_size))
3132 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
3135 continue; /* Skip already checked entries */
3139 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, target);
3140 if (other_bits > bits)
3142 else if (other_bits == bits) /* We match the same number of bits */
3144 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
3146 else if (distance (&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
3152 /* No peers closer, we are the closest! */
3158 * Return this peers adjusted value based on the convergence
3159 * function chosen. This is the key function for randomized
3160 * routing decisions.
3162 * @param target the key of the request
3163 * @param peer the peer we would like the value of
3164 * @param hops number of hops this message has already traveled
3166 * @return bit distance from target to peer raised to an exponent
3167 * adjusted based on the current routing convergence algorithm
3170 static unsigned long long
3171 converge_distance (const GNUNET_HashCode * target,
3172 struct PeerInfo *peer, unsigned int hops)
3174 unsigned long long ret;
3175 unsigned int other_matching_bits;
3176 double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
3177 double temp_modifier;
3183 curr_max_hops = max_hops;
3185 curr_max_hops = (estimate_diameter () + 1) * 2;
3187 if (converge_modifier > 0)
3188 temp_modifier = converge_modifier * base_converge_modifier;
3191 temp_modifier = base_converge_modifier;
3192 base_converge_modifier = 0.0;
3195 GNUNET_assert (temp_modifier > 0);
3197 other_matching_bits =
3198 GNUNET_CRYPTO_hash_matching_bits (target, &peer->id.hashPubKey);
3200 switch (converge_option)
3202 case DHT_CONVERGE_RANDOM:
3203 return 1; /* Always return 1, choose equally among all peers */
3204 case DHT_CONVERGE_LINEAR:
3205 calc_value = hops * curr_max_hops * temp_modifier;
3207 case DHT_CONVERGE_SQUARE:
3209 * Simple square based curve.
3212 (sqrt (hops) / sqrt (curr_max_hops)) * (curr_max_hops /
3216 case DHT_CONVERGE_EXPONENTIAL:
3218 * Simple exponential curve.
3220 if (base_converge_modifier > 0)
3221 calc_value = (temp_modifier * hops * hops) / curr_max_hops;
3223 calc_value = (hops * hops) / curr_max_hops;
3225 case DHT_CONVERGE_BINARY:
3227 * If below the cutoff, route randomly (return 1),
3228 * If above the cutoff, return the maximum possible
3229 * value first (always route to closest, because
3233 if (hops >= converge_modifier) /* Past cutoff */
3242 /* Take the log (base e) of the number of bits matching the other peer */
3243 exponent = log (other_matching_bits);
3245 /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
3246 if (exponent * calc_value >= 44.361419555836498)
3249 /* Clear errno and all math exceptions */
3251 feclearexcept (FE_ALL_EXCEPT);
3252 ret = (unsigned long long) pow (other_matching_bits, calc_value);
3253 if ((errno != 0) || fetestexcept (FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
3256 if (0 != fetestexcept (FE_OVERFLOW))
3257 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
3258 if (0 != fetestexcept (FE_INVALID))
3259 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
3260 if (0 != fetestexcept (FE_UNDERFLOW))
3261 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
3269 * Comparison function for two struct PeerInfo's
3270 * which have already had their matching bits to
3271 * some target calculated.
3273 * @param p1 a pointer pointer to a struct PeerInfo
3274 * @param p2 a pointer pointer to a struct PeerInfo
3276 * @return 0 if equidistant to target,
3277 * -1 if p1 is closer,
3281 compare_peers (const void *p1, const void *p2)
3283 struct PeerInfo **first = (struct PeerInfo **) p1;
3284 struct PeerInfo **second = (struct PeerInfo **) p2;
3286 if ((*first)->matching_bits > (*second)->matching_bits)
3288 if ((*first)->matching_bits < (*second)->matching_bits)
3296 * Select a peer from the routing table that would be a good routing
3297 * destination for sending a message for "target". The resulting peer
3298 * must not be in the set of blocked peers.<p>
3300 * Note that we should not ALWAYS select the closest peer to the
3301 * target, peers further away from the target should be chosen with
3302 * exponentially declining probability.
3304 * @param target the key we are selecting a peer to route to
3305 * @param bloom a bloomfilter containing entries this request has seen already
3306 * @param hops how many hops has this message traversed thus far
3308 * @return Peer to route to, or NULL on error
3310 static struct PeerInfo *
3311 select_peer (const GNUNET_HashCode * target,
3312 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3317 unsigned int offset;
3319 struct PeerInfo *pos;
3320 struct PeerInfo *sorted_closest[bucket_size];
3321 unsigned long long temp_converge_distance;
3322 unsigned long long total_distance;
3323 unsigned long long selected;
3325 unsigned long long stats_total_distance;
3329 unsigned int distance;
3330 unsigned int largest_distance;
3331 struct PeerInfo *chosen;
3334 /** If we are doing kademlia routing, or converge is binary (saves some cycles) */
3335 if ((strict_kademlia == GNUNET_YES) ||
3336 ((converge_option == DHT_CONVERGE_BINARY)
3337 && (hops >= converge_modifier)))
3339 largest_distance = 0;
3341 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3343 pos = k_buckets[bc].head;
3345 while ((pos != NULL) && (count < bucket_size))
3347 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3349 GNUNET_CONTAINER_bloomfilter_test (bloom,
3350 &pos->id.hashPubKey))
3352 distance = inverse_distance (target, &pos->id.hashPubKey);
3353 if (distance > largest_distance)
3356 largest_distance = distance;
3364 if ((largest_distance > 0) && (chosen != NULL))
3366 GNUNET_CONTAINER_bloomfilter_add (bloom, &chosen->id.hashPubKey);
3377 /* Three steps: order peers in closest bucket (most matching bits).
3378 * Then go over all LOWER buckets (matching same bits we do)
3379 * Then go over all HIGHER buckets (matching less then we do)
3382 closest_bucket = find_current_bucket (target);
3383 GNUNET_assert (closest_bucket >= lowest_bucket);
3384 pos = k_buckets[closest_bucket].head;
3386 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3387 memset (sorted_closest, 0, sizeof (sorted_closest));
3388 /* Put any peers in the closest bucket in the sorting array */
3389 while ((pos != NULL) && (count < bucket_size))
3392 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3396 continue; /* Ignore bloomfiltered peers */
3398 pos->matching_bits =
3399 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, target);
3400 sorted_closest[offset] = pos;
3406 /* Sort the peers in descending order */
3407 qsort (&sorted_closest[0], offset, sizeof (struct PeerInfo *),
3410 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3411 for (i = 0; i < offset; i++)
3413 temp_converge_distance =
3414 converge_distance (target, sorted_closest[i], hops);
3416 GNUNET_CONTAINER_bloomfilter_test (bloom,
3417 &sorted_closest[i]->id.
3419 break; /* Ignore bloomfiltered peers */
3420 if (total_distance + temp_converge_distance > total_distance) /* Handle largest case and overflow */
3421 total_distance += temp_converge_distance;
3423 break; /* overflow case */
3426 /* Now handle peers in lower buckets (matches same # of bits as target) */
3427 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3429 pos = k_buckets[bc].head;
3431 while ((pos != NULL) && (count < bucket_size))
3434 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3438 continue; /* Ignore bloomfiltered peers */
3440 temp_converge_distance = converge_distance (target, pos, hops);
3441 if (total_distance + temp_converge_distance > total_distance) /* Handle largest case and overflow */
3442 total_distance += temp_converge_distance;
3444 break; /* overflow case */
3450 /* Now handle all the further away peers */
3451 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3453 pos = k_buckets[bc].head;
3455 while ((pos != NULL) && (count < bucket_size))
3458 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3462 continue; /* Ignore bloomfiltered peers */
3464 temp_converge_distance = converge_distance (target, pos, hops);
3465 if (total_distance + temp_converge_distance > total_distance) /* Handle largest case and overflow */
3466 total_distance += temp_converge_distance;
3468 break; /* overflow case */
3474 if (total_distance == 0) /* No peers to select from! */
3476 increment_stats ("# failed to select peer");
3480 #if DEBUG_DHT_ROUTING > 1
3483 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3484 stats_total_distance = 0;
3485 for (i = 0; i < offset; i++)
3488 GNUNET_CONTAINER_bloomfilter_test (bloom,
3489 &sorted_closest[i]->id.
3491 break; /* Ignore bloomfiltered peers */
3492 temp_converge_distance =
3493 converge_distance (target, sorted_closest[i], hops);
3494 if (stats_total_distance + temp_converge_distance > stats_total_distance) /* Handle largest case and overflow */
3495 stats_total_distance += temp_converge_distance;
3497 break; /* overflow case */
3498 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3499 "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n",
3500 GNUNET_CRYPTO_hash_matching_bits (&sorted_closest[i]->id.
3501 hashPubKey, target),
3502 GNUNET_CRYPTO_hash_matching_bits (&sorted_closest[i]->id.
3504 &my_identity.hashPubKey),
3505 (temp_converge_distance / (double) total_distance) * 100,
3506 temp_converge_distance);
3509 /* Now handle peers in lower buckets (matches same # of bits as target) */
3510 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3512 pos = k_buckets[bc].head;
3514 while ((pos != NULL) && (count < bucket_size))
3517 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3521 continue; /* Ignore bloomfiltered peers */
3523 temp_converge_distance = converge_distance (target, pos, hops);
3524 if (stats_total_distance + temp_converge_distance > stats_total_distance) /* Handle largest case and overflow */
3525 stats_total_distance += temp_converge_distance;
3527 break; /* overflow case */
3528 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3529 "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n",
3530 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
3532 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
3535 (temp_converge_distance / (double) total_distance) *
3536 100, temp_converge_distance);
3542 /* Now handle all the further away peers */
3543 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3545 pos = k_buckets[bc].head;
3547 while ((pos != NULL) && (count < bucket_size))
3550 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3554 continue; /* Ignore bloomfiltered peers */
3556 temp_converge_distance = converge_distance (target, pos, hops);
3557 if (stats_total_distance + temp_converge_distance > stats_total_distance) /* Handle largest case and overflow */
3558 stats_total_distance += temp_converge_distance;
3560 break; /* overflow case */
3561 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3562 "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n",
3563 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
3565 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
3568 (temp_converge_distance / (double) total_distance) *
3569 100, temp_converge_distance);
3574 /* END PRINT STATS */
3577 /* Now actually choose a peer */
3579 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3581 /* Go over closest sorted peers. */
3582 for (i = 0; i < offset; i++)
3585 GNUNET_CONTAINER_bloomfilter_test (bloom,
3586 &sorted_closest[i]->id.
3588 break; /* Ignore bloomfiltered peers */
3589 temp_converge_distance =
3590 converge_distance (target, sorted_closest[i], hops);
3591 if (temp_converge_distance >= selected)
3592 return sorted_closest[i];
3594 selected -= temp_converge_distance;
3597 /* Now handle peers in lower buckets (matches same # of bits as target) */
3598 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3600 pos = k_buckets[bc].head;
3602 while ((pos != NULL) && (count < bucket_size))
3605 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3609 continue; /* Ignore bloomfiltered peers */
3611 temp_converge_distance = converge_distance (target, pos, hops);
3612 if (temp_converge_distance >= selected)
3615 selected -= temp_converge_distance;
3621 /* Now handle all the further away peers */
3622 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3624 pos = k_buckets[bc].head;
3626 while ((pos != NULL) && (count < bucket_size))
3629 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3633 continue; /* Ignore bloomfiltered peers */
3635 temp_converge_distance = converge_distance (target, pos, hops);
3636 if (temp_converge_distance >= selected)
3639 selected -= temp_converge_distance;
3645 increment_stats ("# failed to select peer");
3651 * Task used to remove recent entries, either
3652 * after timeout, when full, or on shutdown.
3654 * @param cls the entry to remove
3655 * @param tc context, reason, etc.
3658 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3660 struct RecentRequest *req = cls;
3661 static GNUNET_HashCode hash;
3663 GNUNET_assert (req != NULL);
3664 hash_from_uid (req->uid, &hash);
3665 GNUNET_assert (GNUNET_YES ==
3666 GNUNET_CONTAINER_multihashmap_remove (recent.hashmap, &hash,
3668 GNUNET_CONTAINER_heap_remove_node (req->heap_node);
3669 GNUNET_CONTAINER_bloomfilter_free (req->bloom);
3673 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3675 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3676 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3682 * Remember this routing request so that if a reply is
3683 * received we can either forward it to the correct peer
3684 * or return the result locally.
3686 * @param msg_ctx Context of the route request
3688 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3691 cache_response (struct DHT_MessageContext *msg_ctx)
3693 struct DHTQueryRecord *record;
3694 struct DHTRouteSource *source_info;
3695 struct DHTRouteSource *pos;
3696 struct GNUNET_TIME_Absolute now;
3697 unsigned int current_size;
3699 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3701 #if DELETE_WHEN_FULL
3702 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3704 source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3705 GNUNET_assert (source_info != NULL);
3706 record = source_info->record;
3707 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3708 if (record->head == NULL) /* No more entries in DLL */
3710 GNUNET_assert (GNUNET_YES ==
3711 GNUNET_CONTAINER_multihashmap_remove
3712 (forward_list.hashmap, &record->key, record));
3713 GNUNET_free (record);
3715 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3717 GNUNET_SCHEDULER_cancel (source_info->delete_task);
3718 source_info->delete_task = GNUNET_SCHEDULER_NO_TASK;
3720 if (source_info->find_peers_responded != NULL)
3721 GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
3722 GNUNET_free (source_info);
3724 GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3727 /** Non-local request and have too many outstanding forwards, discard! */
3728 if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3731 now = GNUNET_TIME_absolute_get ();
3733 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
3734 if (record != NULL) /* Already know this request! */
3740 memcmp (msg_ctx->peer, &pos->source,
3741 sizeof (struct GNUNET_PeerIdentity)))
3742 break; /* Already have this peer in reply list! */
3745 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3747 GNUNET_CONTAINER_heap_update_cost (forward_list.minHeap, pos->hnode,
3754 record = GNUNET_malloc (sizeof (struct DHTQueryRecord));
3755 GNUNET_assert (GNUNET_OK ==
3756 GNUNET_CONTAINER_multihashmap_put (forward_list.hashmap,
3757 &msg_ctx->key, record,
3758 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3759 memcpy (&record->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3762 source_info = GNUNET_malloc (sizeof (struct DHTRouteSource));
3763 source_info->record = record;
3764 source_info->delete_task =
3765 GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry,
3767 source_info->find_peers_responded =
3768 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3769 memcpy (&source_info->source, msg_ctx->peer,
3770 sizeof (struct GNUNET_PeerIdentity));
3771 GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail,
3773 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3775 source_info->client = msg_ctx->client;
3776 now = GNUNET_TIME_absolute_get_forever ();
3778 source_info->hnode =
3779 GNUNET_CONTAINER_heap_insert (forward_list.minHeap, source_info,
3782 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3783 "`%s:%s': Created new forward source info for %s uid %llu\n",
3784 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3785 msg_ctx->unique_id);
3792 * Main function that handles whether or not to route a message to other
3795 * @param msg the message to be routed
3796 * @param msg_ctx the context containing all pertinent information about the message
3799 route_message (const struct GNUNET_MessageHeader *msg,
3800 struct DHT_MessageContext *msg_ctx)
3803 struct PeerInfo *selected;
3804 #if DEBUG_DHT_ROUTING > 1
3805 struct PeerInfo *nearest;
3807 unsigned int target_forward_count;
3808 unsigned int forward_count;
3809 struct RecentRequest *recent_req;
3810 GNUNET_HashCode unique_hash;
3811 char *stat_forward_count;
3812 char *temp_stat_str;
3813 #if DEBUG_DHT_ROUTING
3817 if (malicious_dropper == GNUNET_YES)
3819 #if DEBUG_DHT_ROUTING
3820 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3822 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3823 msg_ctx->hop_count, GNUNET_SYSERR,
3824 &my_identity, &msg_ctx->key,
3825 msg_ctx->peer, NULL);
3828 if (msg_ctx->bloom != NULL)
3830 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3831 msg_ctx->bloom = NULL;
3836 increment_stats (STAT_ROUTES);
3837 target_forward_count =
3838 get_forward_count (msg_ctx->hop_count, msg_ctx->replication);
3839 GNUNET_asprintf (&stat_forward_count, "# forward counts of %d",
3840 target_forward_count);
3841 increment_stats (stat_forward_count);
3842 GNUNET_free (stat_forward_count);
3843 if (msg_ctx->bloom == NULL)
3845 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3847 if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES)
3848 && (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3849 target_forward_count = 0;
3852 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3853 * any closer peers (which is being checked for below). Since we are doing recursive
3854 * routing we have no choice but to stop forwarding in this case. This means that at
3855 * any given step the request may NOT be forwarded to alpha peers (because routes will
3856 * stop and the parallel route will not be aware of it). Of course, assuming that we
3857 * have fulfilled the Kademlia requirements for routing table fullness this will never
3858 * ever ever be a problem.
3860 * However, is this fair?
3862 * Since we use these requests to build our routing tables (and we build them in the
3863 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3864 * routing tables still get constructed.
3866 if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES)
3867 && (msg_ctx->hop_count > 0)
3868 && (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3869 target_forward_count = 0;
3872 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3873 hash_from_uid (msg_ctx->unique_id, &unique_hash);
3875 GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3878 GNUNET_CONTAINER_multihashmap_get (recent.hashmap, &unique_hash);
3879 GNUNET_assert (recent_req != NULL);
3881 memcmp (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode)))
3882 increment_stats (STAT_DUPLICATE_UID);
3885 increment_stats (STAT_RECENT_SEEN);
3886 GNUNET_CONTAINER_bloomfilter_or2 (msg_ctx->bloom, recent_req->bloom,
3892 recent_req = GNUNET_malloc (sizeof (struct RecentRequest));
3893 recent_req->uid = msg_ctx->unique_id;
3894 memcpy (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3895 recent_req->remove_task =
3896 GNUNET_SCHEDULER_add_delayed (DEFAULT_RECENT_REMOVAL, &remove_recent,
3898 recent_req->heap_node =
3899 GNUNET_CONTAINER_heap_insert (recent.minHeap, recent_req,
3900 GNUNET_TIME_absolute_get ().abs_value);
3902 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3903 GNUNET_CONTAINER_multihashmap_put (recent.hashmap, &unique_hash,
3905 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3908 if (GNUNET_CONTAINER_multihashmap_size (recent.hashmap) > DHT_MAX_RECENT)
3910 recent_req = GNUNET_CONTAINER_heap_peek (recent.minHeap);
3911 GNUNET_assert (recent_req != NULL);
3912 GNUNET_SCHEDULER_cancel (recent_req->remove_task);
3913 GNUNET_SCHEDULER_add_now (&remove_recent, recent_req);
3917 for (i = 0; i < target_forward_count; i++)
3920 select_peer (&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3922 if (selected != NULL)
3925 if (GNUNET_CRYPTO_hash_matching_bits
3926 (&selected->id.hashPubKey,
3928 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
3930 GNUNET_asprintf (&temp_stat_str,
3931 "# requests routed to close(r) peer hop %u",
3932 msg_ctx->hop_count);
3934 GNUNET_asprintf (&temp_stat_str,
3935 "# requests routed to less close peer hop %u",
3936 msg_ctx->hop_count);
3937 if (temp_stat_str != NULL)
3939 increment_stats (temp_stat_str);
3940 GNUNET_free (temp_stat_str);
3942 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
3943 &selected->id.hashPubKey);
3944 #if DEBUG_DHT_ROUTING > 1
3945 nearest = find_closest_peer (&msg_ctx->key);
3946 nearest_buf = GNUNET_strdup (GNUNET_i2s (&nearest->id));
3947 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3948 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n",
3949 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3950 msg_ctx->unique_id, GNUNET_i2s (&selected->id),
3952 GNUNET_CRYPTO_hash_matching_bits (&nearest->id.
3955 distance (&nearest->id.hashPubKey, msg_ctx->key));
3956 GNUNET_free (nearest_buf);
3958 #if DEBUG_DHT_ROUTING
3959 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3961 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id,
3962 DHTLOG_ROUTE, msg_ctx->hop_count,
3963 GNUNET_NO, &my_identity,
3964 &msg_ctx->key, msg_ctx->peer,
3968 forward_message (msg, selected, msg_ctx);
3972 if (msg_ctx->bloom != NULL)
3974 GNUNET_CONTAINER_bloomfilter_or2 (recent_req->bloom, msg_ctx->bloom,
3976 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3977 msg_ctx->bloom = NULL;
3980 #if DEBUG_DHT_ROUTING
3981 if (forward_count == 0)
3982 ret = GNUNET_SYSERR;
3986 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3988 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3989 msg_ctx->hop_count, ret,
3990 &my_identity, &msg_ctx->key, msg_ctx->peer,
3999 * Main function that handles whether or not to route a message to other
4002 * @param msg the message to be routed
4003 * @param msg_ctx the context containing all pertinent information about the message
4006 demultiplex_message (const struct GNUNET_MessageHeader *msg,
4007 struct DHT_MessageContext *msg_ctx)
4009 /* FIXME: Should we use closest excluding those we won't route to (the bloomfilter problem)? */
4010 msg_ctx->closest = am_closest_peer (&msg_ctx->key, msg_ctx->bloom);
4012 switch (ntohs (msg->type))
4014 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
4015 cache_response (msg_ctx);
4016 handle_dht_get (msg, msg_ctx);
4018 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
4019 increment_stats (STAT_PUTS);
4020 handle_dht_put (msg, msg_ctx);
4022 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
4023 increment_stats (STAT_FIND_PEER);
4024 if (((msg_ctx->hop_count > 0)
4026 memcmp (msg_ctx->peer, &my_identity,
4027 sizeof (struct GNUNET_PeerIdentity))))
4028 || (msg_ctx->client != NULL))
4030 cache_response (msg_ctx);
4031 if ((msg_ctx->closest == GNUNET_YES)
4032 || (msg_ctx->msg_options ==
4033 GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
4034 handle_dht_find_peer (msg, msg_ctx);
4037 route_message (msg, msg_ctx);
4038 #if DEBUG_DHT_ROUTING
4039 if (msg_ctx->hop_count == 0) /* Locally initiated request */
4041 if ((debug_routes) && (dhtlog_handle != NULL))
4043 dhtlog_handle->insert_dhtkey (NULL, &msg_ctx->key);
4044 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id,
4046 msg_ctx->hop_count, GNUNET_NO,
4047 &my_identity, &msg_ctx->key);
4053 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4054 "`%s': Message type (%d) not handled, forwarding anyway!\n",
4055 "DHT", ntohs (msg->type));
4056 route_message (msg, msg_ctx);
4064 * Iterator for local get request results,
4066 * @param cls closure for iterator, NULL
4067 * @param exp when does this value expire?
4068 * @param key the key this data is stored under
4069 * @param size the size of the data identified by key
4070 * @param data the actual data
4071 * @param type the type of the data
4073 * @return GNUNET_OK to continue iteration, anything else
4074 * to stop iteration.
4077 republish_content_iterator (void *cls,
4078 struct GNUNET_TIME_Absolute exp,
4079 const GNUNET_HashCode * key,
4080 size_t size, const char *data, uint32_t type)
4083 struct DHT_MessageContext *new_msg_ctx;
4084 struct GNUNET_DHT_PutMessage *put_msg;
4086 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4087 "`%s:%s': Received `%s' response from datacache\n", my_short_id,
4090 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
4092 put_msg = GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
4093 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
4094 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
4095 put_msg->expiration = GNUNET_TIME_absolute_hton (exp);
4096 put_msg->type = htons (type);
4097 memcpy (&put_msg[1], data, size);
4098 new_msg_ctx->unique_id =
4099 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
4100 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
4101 new_msg_ctx->replication = ntohl (DEFAULT_PUT_REPLICATION);
4102 new_msg_ctx->msg_options = ntohl (0);
4103 new_msg_ctx->network_size = estimate_diameter ();
4104 new_msg_ctx->peer = &my_identity;
4105 new_msg_ctx->bloom =
4106 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4107 new_msg_ctx->hop_count = 0;
4108 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4109 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4110 increment_stats (STAT_PUT_START);
4111 demultiplex_message (&put_msg->header, new_msg_ctx);
4113 GNUNET_free (new_msg_ctx);
4114 GNUNET_free (put_msg);
4119 * Task used to republish data.
4121 * @param cls closure (a struct RepublishContext)
4122 * @param tc runtime context for this task
4125 republish_content (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4127 struct RepublishContext *put_context = cls;
4129 unsigned int results;
4131 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4133 GNUNET_free (put_context);
4137 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
4139 GNUNET_DATACACHE_get (datacache, &put_context->key, put_context->type,
4140 &republish_content_iterator, NULL);
4141 if (results == 0) /* Data must have expired */
4142 GNUNET_free (put_context);
4143 else /* Reschedule task for next time period */
4144 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content,
4151 * Iterator over hash map entries.
4153 * @param cls client to search for in source routes
4154 * @param key current key code (ignored)
4155 * @param value value in the hash map, a DHTQueryRecord
4156 * @return GNUNET_YES if we should continue to
4161 find_client_records (void *cls, const GNUNET_HashCode * key, void *value)
4163 struct ClientList *client = cls;
4164 struct DHTQueryRecord *record = value;
4165 struct DHTRouteSource *pos;
4169 if (pos->client == client)
4175 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, pos);
4176 GNUNET_CONTAINER_heap_remove_node (pos->hnode);
4177 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
4179 GNUNET_SCHEDULER_cancel (pos->delete_task);
4180 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4182 if (pos->find_peers_responded != NULL)
4183 GNUNET_CONTAINER_bloomfilter_free (pos->find_peers_responded);
4186 if (record->head == NULL) /* No more entries in DLL */
4188 GNUNET_assert (GNUNET_YES ==
4189 GNUNET_CONTAINER_multihashmap_remove
4190 (forward_list.hashmap, &record->key, record));
4191 GNUNET_free (record);
4197 * Functions with this signature are called whenever a client
4198 * is disconnected on the network level.
4200 * @param cls closure (NULL for dht)
4201 * @param client identification of the client; NULL
4202 * for the last call when the server is destroyed
4205 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4207 struct ClientList *pos = client_list;
4208 struct ClientList *prev;
4209 struct ClientList *found;
4210 struct PendingMessage *reply;
4216 if (pos->client_handle == client)
4219 prev->next = pos->next;
4221 client_list = pos->next;
4231 if (found->transmit_handle != NULL)
4232 GNUNET_CONNECTION_notify_transmit_ready_cancel
4233 (found->transmit_handle);
4235 while (NULL != (reply = found->pending_head))
4237 GNUNET_CONTAINER_DLL_remove (found->pending_head,
4238 found->pending_tail, reply);
4239 GNUNET_free (reply);
4241 GNUNET_CONTAINER_multihashmap_iterate (forward_list.hashmap,
4242 &find_client_records, found);
4243 GNUNET_free (found);
4248 * Find a client if it exists, add it otherwise.
4250 * @param client the server handle to the client
4252 * @return the client if found, a new client otherwise
4254 static struct ClientList *
4255 find_active_client (struct GNUNET_SERVER_Client *client)
4257 struct ClientList *pos = client_list;
4258 struct ClientList *ret;
4262 if (pos->client_handle == client)
4267 ret = GNUNET_malloc (sizeof (struct ClientList));
4268 ret->client_handle = client;
4269 ret->next = client_list;
4277 * Task to send a malicious put message across the network.
4279 * @param cls closure for this task
4280 * @param tc the context under which the task is running
4283 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4285 static struct GNUNET_DHT_PutMessage put_message;
4286 static struct DHT_MessageContext msg_ctx;
4287 static GNUNET_HashCode key;
4288 uint32_t random_key;
4290 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4292 put_message.header.size = htons (sizeof (struct GNUNET_DHT_PutMessage));
4293 put_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
4294 put_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
4295 put_message.expiration =
4296 GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_forever ());
4297 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4299 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
4300 GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
4301 memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
4303 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
4304 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
4305 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
4306 msg_ctx.msg_options = ntohl (0);
4307 msg_ctx.network_size = estimate_diameter ();
4308 msg_ctx.peer = &my_identity;
4309 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
4310 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4311 #if DEBUG_DHT_ROUTING
4312 if (dhtlog_handle != NULL)
4313 dhtlog_handle->insert_dhtkey (NULL, &key);
4315 increment_stats (STAT_PUT_START);
4316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4317 "%s:%s Sending malicious PUT message with hash %s\n",
4318 my_short_id, "DHT", GNUNET_h2s (&key));
4319 demultiplex_message (&put_message.header, &msg_ctx);
4320 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4321 (GNUNET_TIME_UNIT_MILLISECONDS,
4322 malicious_put_frequency),
4323 &malicious_put_task, NULL);
4328 * Task to send a malicious put message across the network.
4330 * @param cls closure for this task
4331 * @param tc the context under which the task is running
4334 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4336 static struct GNUNET_DHT_GetMessage get_message;
4337 struct DHT_MessageContext msg_ctx;
4338 static GNUNET_HashCode key;
4339 uint32_t random_key;
4341 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4344 get_message.header.size = htons (sizeof (struct GNUNET_DHT_GetMessage));
4345 get_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET);
4346 get_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
4347 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4349 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
4350 GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
4351 memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
4353 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
4354 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
4355 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
4356 msg_ctx.msg_options = ntohl (0);
4357 msg_ctx.network_size = estimate_diameter ();
4358 msg_ctx.peer = &my_identity;
4359 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
4360 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4361 #if DEBUG_DHT_ROUTING
4362 if (dhtlog_handle != NULL)
4363 dhtlog_handle->insert_dhtkey (NULL, &key);
4365 increment_stats (STAT_GET_START);
4366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4367 "%s:%s Sending malicious GET message with hash %s\n",
4368 my_short_id, "DHT", GNUNET_h2s (&key));
4369 demultiplex_message (&get_message.header, &msg_ctx);
4370 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4371 (GNUNET_TIME_UNIT_MILLISECONDS,
4372 malicious_get_frequency),
4373 &malicious_get_task, NULL);
4379 * Iterator over hash map entries.
4381 * @param cls closure
4382 * @param key current key code
4383 * @param value value in the hash map
4384 * @return GNUNET_YES if we should continue to
4389 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
4391 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
4392 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
4397 * Task to send a find peer message for our own peer identifier
4398 * so that we can find the closest peers in the network to ourselves
4399 * and attempt to connect to them.
4401 * @param cls closure for this task
4402 * @param tc the context under which the task is running
4405 send_find_peer_message (void *cls,
4406 const struct GNUNET_SCHEDULER_TaskContext *tc)
4408 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
4409 struct DHT_MessageContext msg_ctx;
4410 struct GNUNET_TIME_Relative next_send_time;
4411 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
4413 struct GNUNET_TIME_Relative time_diff;
4414 struct GNUNET_TIME_Absolute end;
4416 double count_per_interval;
4418 if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4421 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! */
4423 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4424 "Have %d newly found peers since last find peer message sent!\n",
4426 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
4427 &send_find_peer_message, NULL);
4428 newly_found_peers = 0;
4432 increment_stats (STAT_FIND_PEER_START);
4434 end = GNUNET_TIME_absolute_get ();
4436 GNUNET_TIME_absolute_get_difference (find_peer_context.start, end);
4438 if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
4440 multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
4441 count_per_interval = find_peer_context.count / multiplier;
4445 multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
4446 count_per_interval = find_peer_context.count * multiplier;
4450 #if FIND_PEER_WITH_HELLO
4452 GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage) +
4453 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *)
4455 find_peer_msg->header.size =
4456 htons (sizeof (struct GNUNET_DHT_FindPeerMessage) +
4457 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
4458 memcpy (&find_peer_msg[1], my_hello,
4459 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
4461 find_peer_msg = GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage));
4462 find_peer_msg->header.size =
4463 htons (sizeof (struct GNUNET_DHT_FindPeerMessage));
4465 find_peer_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4467 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4468 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
4470 GNUNET_assert (GNUNET_OK ==
4471 GNUNET_CONTAINER_bloomfilter_get_raw_data (temp_bloom,
4475 GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
4476 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4477 memcpy (&msg_ctx.key, &my_identity.hashPubKey, sizeof (GNUNET_HashCode));
4479 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
4480 (GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX));
4481 msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4482 msg_ctx.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4483 msg_ctx.network_size = estimate_diameter ();
4484 msg_ctx.peer = &my_identity;
4485 msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4486 msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4488 demultiplex_message (&find_peer_msg->header, &msg_ctx);
4489 GNUNET_free (find_peer_msg);
4490 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4491 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id,
4492 "DHT", "FIND PEER");
4493 if (newly_found_peers < bucket_size)
4495 next_send_time.rel_value =
4496 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4497 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
4498 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value /
4503 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4504 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
4505 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value -
4506 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4509 GNUNET_assert (next_send_time.rel_value != 0);
4510 find_peer_context.count = 0;
4511 newly_found_peers = 0;
4512 find_peer_context.start = GNUNET_TIME_absolute_get ();
4513 if (GNUNET_YES == do_find_peer)
4515 GNUNET_SCHEDULER_add_delayed (next_send_time,
4516 &send_find_peer_message, NULL);
4521 * Handler for any generic DHT messages, calls the appropriate handler
4522 * depending on message type, sends confirmation if responses aren't otherwise
4525 * @param cls closure for the service
4526 * @param client the client we received this message from
4527 * @param message the actual message received
4530 handle_dht_local_route_request (void *cls,
4531 struct GNUNET_SERVER_Client *client,
4532 const struct GNUNET_MessageHeader *message)
4534 const struct GNUNET_DHT_RouteMessage *dht_msg =
4535 (const struct GNUNET_DHT_RouteMessage *) message;
4536 const struct GNUNET_MessageHeader *enc_msg;
4537 struct DHT_MessageContext msg_ctx;
4539 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4542 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4546 ntohs (message->type),
4547 GNUNET_h2s (&dht_msg->key), GNUNET_ntohll (dht_msg->unique_id));
4549 #if DEBUG_DHT_ROUTING
4550 if (dhtlog_handle != NULL)
4551 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4554 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4555 msg_ctx.client = find_active_client (client);
4556 memcpy (&msg_ctx.key, &dht_msg->key, sizeof (GNUNET_HashCode));
4557 msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4558 msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
4559 msg_ctx.msg_options = ntohl (dht_msg->options);
4560 if (GNUNET_DHT_RO_RECORD_ROUTE == (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
4562 msg_ctx.path_history = GNUNET_malloc(sizeof(struct GNUNET_PeerIdentity));
4563 memcpy(msg_ctx.path_history, &my_identity, sizeof(struct GNUNET_PeerIdentity));
4564 msg_ctx.path_history_len = 1;
4566 msg_ctx.network_size = estimate_diameter ();
4567 msg_ctx.peer = &my_identity;
4568 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
4569 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4571 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4572 increment_stats (STAT_GET_START);
4573 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4574 increment_stats (STAT_PUT_START);
4575 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4576 increment_stats (STAT_FIND_PEER_START);
4578 if (GNUNET_YES == malicious_dropper)
4580 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4582 #if DEBUG_DHT_ROUTING
4583 if ((debug_routes) && (dhtlog_handle != NULL))
4585 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id,
4586 DHTLOG_GET, msg_ctx.hop_count,
4587 GNUNET_NO, &my_identity,
4592 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4594 #if DEBUG_DHT_ROUTING
4595 if ((debug_routes) && (dhtlog_handle != NULL))
4597 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id,
4598 DHTLOG_PUT, msg_ctx.hop_count,
4599 GNUNET_NO, &my_identity,
4604 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4605 GNUNET_free_non_null(msg_ctx.path_history);
4609 demultiplex_message (enc_msg, &msg_ctx);
4610 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4615 * Handler for any locally received DHT control messages,
4616 * sets malicious flags mostly for now.
4618 * @param cls closure for the service
4619 * @param client the client we received this message from
4620 * @param message the actual message received
4624 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4625 const struct GNUNET_MessageHeader *message)
4627 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4628 (const struct GNUNET_DHT_ControlMessage *) message;
4631 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4632 "`%s:%s': Received `%s' request from client, command %d\n",
4633 my_short_id, "DHT", "CONTROL",
4634 ntohs (dht_control_msg->command));
4637 switch (ntohs (dht_control_msg->command))
4639 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4640 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4641 "Sending self seeking find peer request!\n");
4642 GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
4645 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4646 if (ntohs (dht_control_msg->variable) > 0)
4647 malicious_get_frequency = ntohs (dht_control_msg->variable);
4648 if (malicious_get_frequency == 0)
4649 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4650 if (malicious_getter != GNUNET_YES)
4651 GNUNET_SCHEDULER_add_now (&malicious_get_task, NULL);
4652 malicious_getter = GNUNET_YES;
4653 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4654 "%s:%s Initiating malicious GET behavior, frequency %d\n",
4655 my_short_id, "DHT", malicious_get_frequency);
4657 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4658 if (ntohs (dht_control_msg->variable) > 0)
4659 malicious_put_frequency = ntohs (dht_control_msg->variable);
4660 if (malicious_put_frequency == 0)
4661 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4662 if (malicious_putter != GNUNET_YES)
4663 GNUNET_SCHEDULER_add_now (&malicious_put_task, NULL);
4664 malicious_putter = GNUNET_YES;
4665 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4666 "%s:%s Initiating malicious PUT behavior, frequency %d\n",
4667 my_short_id, "DHT", malicious_put_frequency);
4669 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4670 #if DEBUG_DHT_ROUTING
4671 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4672 dhtlog_handle->set_malicious (&my_identity);
4674 malicious_dropper = GNUNET_YES;
4675 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4676 "%s:%s Initiating malicious DROP behavior\n", my_short_id,
4681 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4682 "%s:%s Unknown control command type `%d'!\n",
4683 my_short_id, "DHT", ntohs (dht_control_msg->command));
4687 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4691 * Handler for any generic DHT stop messages, calls the appropriate handler
4692 * depending on message type (if processed locally)
4694 * @param cls closure for the service
4695 * @param client the client we received this message from
4696 * @param message the actual message received
4700 handle_dht_local_route_stop (void *cls, struct GNUNET_SERVER_Client *client,
4701 const struct GNUNET_MessageHeader *message)
4704 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4705 (const struct GNUNET_DHT_StopMessage *) message;
4706 struct DHTQueryRecord *record;
4707 struct DHTRouteSource *pos;
4709 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4710 "`%s:%s': Received `%s' request from client, uid %llu\n",
4711 my_short_id, "DHT", "GENERIC STOP",
4712 GNUNET_ntohll (dht_stop_msg->unique_id));
4715 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap,
4716 &dht_stop_msg->key);
4723 /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
4724 if ((pos->client != NULL) && (pos->client->client_handle == client))
4726 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
4727 GNUNET_SCHEDULER_cancel (pos->delete_task);
4728 pos->delete_task = GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
4734 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4739 * Core handler for p2p route requests.
4741 * @param cls closure
4742 * @param message message
4743 * @param peer peer identity this notification is about
4744 * @param atsi performance data
4748 handle_dht_p2p_route_request (void *cls,
4749 const struct GNUNET_PeerIdentity *peer,
4750 const struct GNUNET_MessageHeader *message,
4751 const struct GNUNET_TRANSPORT_ATS_Information
4755 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4756 "`%s:%s': Received P2P request from peer %s\n", my_short_id,
4757 "DHT", GNUNET_i2s (peer));
4759 struct GNUNET_DHT_P2PRouteMessage *incoming =
4760 (struct GNUNET_DHT_P2PRouteMessage *) message;
4761 struct GNUNET_MessageHeader *enc_msg =
4762 (struct GNUNET_MessageHeader *) &incoming[1];
4763 struct DHT_MessageContext *msg_ctx;
4767 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply) */
4770 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4771 "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4776 if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4778 GNUNET_break_op (0);
4782 if (malicious_dropper == GNUNET_YES)
4784 #if DEBUG_DHT_ROUTING
4785 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4787 /** Log routes that die due to high load! */
4788 dhtlog_handle->insert_route (NULL,
4789 GNUNET_ntohll (incoming->unique_id),
4791 ntohl (incoming->hop_count),
4792 GNUNET_SYSERR, &my_identity,
4793 &incoming->key, peer, NULL);
4799 if (get_max_send_delay ().rel_value > MAX_REQUEST_TIME.rel_value)
4801 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4802 "Sending of previous replies took too long, backing off!\n");
4803 increment_stats ("# route requests dropped due to high load");
4804 decrease_max_send_delay (get_max_send_delay ());
4805 #if DEBUG_DHT_ROUTING
4806 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4808 /** Log routes that die due to high load! */
4809 dhtlog_handle->insert_route (NULL,
4810 GNUNET_ntohll (incoming->unique_id),
4812 ntohl (incoming->hop_count),
4813 GNUNET_SYSERR, &my_identity,
4814 &incoming->key, peer, NULL);
4819 msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
4821 GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4823 GNUNET_assert (msg_ctx->bloom != NULL);
4824 msg_ctx->hop_count = ntohl (incoming->hop_count);
4825 memcpy (&msg_ctx->key, &incoming->key, sizeof (GNUNET_HashCode));
4826 msg_ctx->replication = ntohl (incoming->desired_replication_level);
4827 msg_ctx->unique_id = GNUNET_ntohll (incoming->unique_id);
4828 msg_ctx->msg_options = ntohl (incoming->options);
4829 if (GNUNET_DHT_RO_RECORD_ROUTE == (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
4831 path_size = ntohl(incoming->outgoing_path_length) * sizeof(struct GNUNET_PeerIdentity);
4832 GNUNET_assert(ntohs(message->size) ==
4833 (sizeof(struct GNUNET_DHT_P2PRouteMessage) +
4834 ntohs(enc_msg->size) +
4836 route_path = (char *)&incoming[1];
4837 route_path = route_path + ntohs(enc_msg->size);
4838 msg_ctx->path_history = GNUNET_malloc(sizeof(struct GNUNET_PeerIdentity) + path_size);
4839 memcpy(msg_ctx->path_history, route_path, path_size);
4840 memcpy(&msg_ctx->path_history[path_size], &my_identity, sizeof(struct GNUNET_PeerIdentity));
4841 msg_ctx->path_history_len = ntohl(incoming->outgoing_path_length) + 1;
4843 msg_ctx->network_size = ntohl (incoming->network_size);
4844 msg_ctx->peer = peer;
4845 msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4846 msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4847 demultiplex_message (enc_msg, msg_ctx);
4848 if (msg_ctx->bloom != NULL)
4850 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4851 msg_ctx->bloom = NULL;
4853 GNUNET_free (msg_ctx);
4859 * Core handler for p2p route results.
4861 * @param cls closure
4862 * @param message message
4863 * @param peer peer identity this notification is about
4864 * @param atsi performance data
4868 handle_dht_p2p_route_result (void *cls,
4869 const struct GNUNET_PeerIdentity *peer,
4870 const struct GNUNET_MessageHeader *message,
4871 const struct GNUNET_TRANSPORT_ATS_Information
4875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4876 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT",
4879 struct GNUNET_DHT_P2PRouteResultMessage *incoming =
4880 (struct GNUNET_DHT_P2PRouteResultMessage *) message;
4881 struct GNUNET_MessageHeader *enc_msg =
4882 (struct GNUNET_MessageHeader *) &incoming[1];
4883 struct DHT_MessageContext msg_ctx;
4888 if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4890 GNUNET_break_op (0);
4894 if (malicious_dropper == GNUNET_YES)
4896 #if DEBUG_DHT_ROUTING
4897 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4899 /** Log routes that die due to high load! */
4900 dhtlog_handle->insert_route (NULL,
4901 GNUNET_ntohll (incoming->unique_id),
4903 ntohl (incoming->hop_count),
4904 GNUNET_SYSERR, &my_identity,
4905 &incoming->key, peer, NULL);
4911 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4912 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4913 memcpy (&msg_ctx.key, &incoming->key, sizeof (GNUNET_HashCode));
4914 msg_ctx.unique_id = GNUNET_ntohll (incoming->unique_id);
4915 msg_ctx.msg_options = ntohl (incoming->options);
4916 msg_ctx.hop_count = ntohl (incoming->hop_count);
4917 msg_ctx.peer = peer;
4918 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4919 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4920 if ((GNUNET_DHT_RO_RECORD_ROUTE == (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE)) && (ntohl (incoming->outgoing_path_length) > 0))
4922 if (ntohs(message->size) - sizeof(struct GNUNET_DHT_P2PRouteResultMessage) - ntohs(enc_msg->size) !=
4923 ntohl (incoming->outgoing_path_length) * sizeof(struct GNUNET_PeerIdentity))
4926 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4927 "Return message indicated a path was included, but sizes are wrong: Total size %d, enc size %d, left %d, expected %d\n",
4928 ntohs(message->size),
4929 ntohs(enc_msg->size),
4930 ntohs(message->size) - sizeof(struct GNUNET_DHT_P2PRouteResultMessage) - ntohs(enc_msg->size),
4931 ntohl(incoming->outgoing_path_length) * sizeof(struct GNUNET_PeerIdentity));
4933 GNUNET_break_op (0);
4936 msg_ctx.path_history = (char *)&incoming[1];
4937 msg_ctx.path_history += ntohs(enc_msg->size);
4938 msg_ctx.path_history_len = ntohl (incoming->outgoing_path_length);
4940 for (i = 0; i < msg_ctx.path_history_len; i++)
4942 path_offset = &msg_ctx.path_history[i * sizeof(struct GNUNET_PeerIdentity)];
4943 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4944 "(handle_p2p_route_result) Key %s Found peer %d:%s\n",
4945 GNUNET_h2s(&msg_ctx.key),
4947 GNUNET_i2s((struct GNUNET_PeerIdentity *)path_offset));
4952 GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4954 GNUNET_assert (msg_ctx.bloom != NULL);
4955 route_result_message (enc_msg, &msg_ctx);
4961 * Receive the HELLO from transport service,
4962 * free current and replace if necessary.
4965 * @param message HELLO message of peer
4968 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4971 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4972 "Received our `%s' from transport service\n", "HELLO");
4975 GNUNET_assert (message != NULL);
4976 GNUNET_free_non_null (my_hello);
4977 my_hello = GNUNET_malloc (ntohs (message->size));
4978 memcpy (my_hello, message, ntohs (message->size));
4983 * Task run during shutdown.
4989 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4992 struct PeerInfo *pos;
4994 if (transport_handle != NULL)
4996 GNUNET_free_non_null (my_hello);
4997 GNUNET_TRANSPORT_get_hello_cancel (transport_handle, &process_hello,
4999 GNUNET_TRANSPORT_disconnect (transport_handle);
5001 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS;
5004 while (k_buckets[bucket_count].head != NULL)
5006 pos = k_buckets[bucket_count].head;
5008 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5009 "%s:%s Removing peer %s from bucket %d!\n", my_short_id,
5010 "DHT", GNUNET_i2s (&pos->id), bucket_count);
5012 delete_peer (pos, bucket_count);
5015 if (coreAPI != NULL)
5018 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5019 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
5021 GNUNET_CORE_disconnect (coreAPI);
5024 if (datacache != NULL)
5027 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5028 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
5030 GNUNET_DATACACHE_destroy (datacache);
5035 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
5038 if (dhtlog_handle != NULL)
5040 GNUNET_DHTLOG_disconnect (dhtlog_handle);
5041 dhtlog_handle = NULL;
5043 if (block_context != NULL)
5045 GNUNET_BLOCK_context_destroy (block_context);
5046 block_context = NULL;
5048 GNUNET_free_non_null (my_short_id);
5054 * To be called on core init/fail.
5056 * @param cls service closure
5057 * @param server handle to the server for this service
5058 * @param identity the public identity of this peer
5059 * @param publicKey the public key of this peer
5062 core_init (void *cls,
5063 struct GNUNET_CORE_Handle *server,
5064 const struct GNUNET_PeerIdentity *identity,
5065 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
5071 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5072 "%s: Connection to core FAILED!\n", "dht",
5073 GNUNET_i2s (identity));
5075 GNUNET_SCHEDULER_cancel (cleanup_task);
5076 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
5080 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5081 "%s: Core connection initialized, I am peer: %s\n", "dht",
5082 GNUNET_i2s (identity));
5085 /* Copy our identity so we can use it */
5086 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
5087 if (my_short_id != NULL)
5088 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5089 "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n",
5091 my_short_id = GNUNET_strdup (GNUNET_i2s (&my_identity));
5092 /* Set the server to local variable */
5095 if (dhtlog_handle != NULL)
5096 dhtlog_handle->insert_node (NULL, &my_identity);
5100 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
5101 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE,
5103 {&handle_dht_local_route_stop, NULL,
5104 GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
5105 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
5110 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5111 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
5112 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
5118 * Method called whenever a peer connects.
5120 * @param cls closure
5121 * @param peer peer identity this notification is about
5122 * @param atsi performance data
5125 handle_core_connect (void *cls,
5126 const struct GNUNET_PeerIdentity *peer,
5127 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
5129 struct PeerInfo *ret;
5130 struct DHTPutEntry *put_entry;
5133 /* Check for connect to self message */
5134 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
5138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5139 "%s:%s Receives core connect message for peer %s distance %d!\n",
5140 my_short_id, "dht", GNUNET_i2s (peer), distance);
5144 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
5148 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5149 "%s:%s Received %s message for peer %s, but already have peer in RT!",
5150 my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s (peer));
5156 if ((datacache != NULL) && (GNUNET_YES == put_peer_identities))
5158 put_entry = GNUNET_malloc(sizeof(struct DHTPutEntry) + sizeof (struct GNUNET_PeerIdentity));
5159 put_entry->path_length = 0;
5160 put_entry->data_size = sizeof (struct GNUNET_PeerIdentity);
5161 memcpy(&put_entry[1], peer, sizeof (struct GNUNET_PeerIdentity));
5162 GNUNET_DATACACHE_put (datacache, &peer->hashPubKey,
5163 sizeof(struct DHTPutEntry) + sizeof (struct GNUNET_PeerIdentity),
5164 (char *)put_entry, GNUNET_BLOCK_TYPE_DHT_HELLO,
5165 GNUNET_TIME_absolute_get_forever ());
5166 GNUNET_free (put_entry);
5168 else if (datacache == NULL)
5169 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "DHT has no connection to datacache!\n");
5171 peer_bucket = find_current_bucket (&peer->hashPubKey);
5172 GNUNET_assert (peer_bucket >= lowest_bucket);
5173 GNUNET_assert (peer_bucket < MAX_BUCKETS);
5174 ret = GNUNET_malloc (sizeof (struct PeerInfo));
5176 ret->latency = latency;
5177 ret->distance = distance;
5180 GNUNET_CONTAINER_DLL_insert_after (k_buckets[peer_bucket].head,
5181 k_buckets[peer_bucket].tail,
5182 k_buckets[peer_bucket].tail,
5184 k_buckets[peer_bucket].peers_size++;
5185 #if DO_UPDATE_PREFERENCE
5186 if ( (GNUNET_CRYPTO_hash_matching_bits
5187 (&my_identity.hashPubKey, &peer->hashPubKey) > 0) &&
5188 (k_buckets[peer_bucket].peers_size <= bucket_size) )
5189 ret->preference_task = GNUNET_SCHEDULER_add_now (&update_core_preference,
5192 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
5193 enable_next_bucket ();
5195 schedule_ping_messages ();
5197 newly_found_peers++;
5198 GNUNET_CONTAINER_multihashmap_put (all_known_peers, &peer->hashPubKey,
5200 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5201 increment_stats (STAT_PEERS_KNOWN);
5204 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5205 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT",
5206 ret == NULL ? "NOT ADDED" : "PEER ADDED");
5212 * Method called whenever a peer disconnects.
5214 * @param cls closure
5215 * @param peer peer identity this notification is about
5218 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5220 struct PeerInfo *to_remove;
5223 /* Check for disconnect from self message */
5224 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
5227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5228 "%s:%s: Received peer disconnect message for peer `%s' from %s\n",
5229 my_short_id, "DHT", GNUNET_i2s (peer), "CORE");
5233 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
5238 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5239 "%s:%s: do not have peer `%s' in RT, can't disconnect!\n",
5240 my_short_id, "DHT", GNUNET_i2s (peer));
5244 increment_stats (STAT_DISCONNECTS);
5245 GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
5246 (all_known_peers, &peer->hashPubKey));
5248 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
5249 GNUNET_assert (to_remove != NULL);
5250 if (NULL != to_remove->info_ctx)
5252 GNUNET_CORE_peer_change_preference_cancel (to_remove->info_ctx);
5253 to_remove->info_ctx = NULL;
5256 memcmp (peer, &to_remove->id,
5257 sizeof (struct GNUNET_PeerIdentity)));
5258 current_bucket = find_current_bucket (&to_remove->id.hashPubKey);
5259 delete_peer (to_remove, current_bucket);
5264 * Process dht requests.
5266 * @param cls closure
5267 * @param server the initialized server
5268 * @param c configuration to use
5272 struct GNUNET_SERVER_Handle *server,
5273 const struct GNUNET_CONFIGURATION_Handle *c)
5275 struct GNUNET_TIME_Relative next_send_time;
5276 unsigned long long temp_config_num;
5277 char *converge_modifier_buf;
5280 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
5281 GNUNET_SERVER_add_handlers (server, plugin_handlers);
5282 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
5283 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
5284 DEFAULT_CORE_QUEUE_SIZE, /* queue size */
5285 NULL, /* Closure passed to DHT functions */
5286 &core_init, /* Call core_init once connected */
5287 &handle_core_connect, /* Handle connects */
5288 &handle_core_disconnect, /* remove peers on disconnects */
5289 NULL, /* Do we care about "status" updates? */
5290 NULL, /* Don't want notified about all incoming messages */
5291 GNUNET_NO, /* For header only inbound notification */
5292 NULL, /* Don't want notified about all outbound messages */
5293 GNUNET_NO, /* For header only outbound notification */
5294 core_handlers); /* Register these handlers */
5296 if (coreAPI == NULL)
5298 transport_handle = GNUNET_TRANSPORT_connect (cfg,
5299 NULL, NULL, NULL, NULL, NULL);
5300 if (transport_handle != NULL)
5301 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
5303 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5304 "Failed to connect to transport service!\n");
5305 block_context = GNUNET_BLOCK_context_create (cfg);
5306 lowest_bucket = MAX_BUCKETS - 1;
5307 forward_list.hashmap =
5308 GNUNET_CONTAINER_multihashmap_create (MAX_OUTSTANDING_FORWARDS / 10);
5309 forward_list.minHeap =
5310 GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
5311 all_known_peers = GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
5312 recent_find_peer_requests =
5313 GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
5314 GNUNET_assert (all_known_peers != NULL);
5316 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
5319 debug_routes = GNUNET_YES;
5323 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "strict_kademlia"))
5325 strict_kademlia = GNUNET_YES;
5329 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_on_closest"))
5331 stop_on_closest = GNUNET_YES;
5335 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_found"))
5337 stop_on_found = GNUNET_YES;
5341 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_getter"))
5343 malicious_getter = GNUNET_YES;
5344 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
5345 "MALICIOUS_GET_FREQUENCY",
5346 &malicious_get_frequency))
5347 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
5350 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
5354 max_hops = DEFAULT_MAX_HOPS;
5357 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
5360 use_max_hops = GNUNET_YES;
5364 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_putter"))
5366 malicious_putter = GNUNET_YES;
5367 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
5368 "MALICIOUS_PUT_FREQUENCY",
5369 &malicious_put_frequency))
5370 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
5373 dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
5375 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
5376 "REPLICATION_FREQUENCY",
5379 dht_republish_frequency =
5380 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES,
5385 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "bucket_size",
5388 bucket_size = (unsigned int) temp_config_num;
5392 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "kad_alpha",
5393 &kademlia_replication))
5395 kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
5399 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_dropper"))
5401 malicious_dropper = GNUNET_YES;
5405 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "republish"))
5406 do_republish = GNUNET_NO;
5409 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "do_find_peer"))
5411 do_find_peer = GNUNET_NO;
5414 do_find_peer = GNUNET_YES;
5417 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "use_real_distance"))
5418 use_real_distance = GNUNET_YES;
5421 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
5422 "mysql_logging_extended"))
5424 debug_routes = GNUNET_YES;
5425 debug_routes_extended = GNUNET_YES;
5428 #if DEBUG_DHT_ROUTING
5429 if (GNUNET_YES == debug_routes)
5431 dhtlog_handle = GNUNET_DHTLOG_connect (cfg);
5432 if (dhtlog_handle == NULL)
5434 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5435 "Could not connect to mysql logging server, logging will not happen!");
5440 converge_option = DHT_CONVERGE_BINARY;
5442 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "converge_linear"))
5444 converge_option = DHT_CONVERGE_LINEAR;
5446 else if (GNUNET_YES ==
5447 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht",
5448 "converge_exponential"))
5450 converge_option = DHT_CONVERGE_EXPONENTIAL;
5452 else if (GNUNET_YES ==
5453 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht",
5456 converge_option = DHT_CONVERGE_RANDOM;
5458 else if (GNUNET_YES ==
5459 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht",
5462 converge_option = DHT_CONVERGE_BINARY;
5465 converge_modifier = 4.0;
5467 GNUNET_CONFIGURATION_get_value_string (cfg, "dht", "converge_modifier",
5468 &converge_modifier_buf))
5470 if (1 != sscanf (converge_modifier_buf, "%f", &converge_modifier))
5472 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5473 "Failed to read decimal value for %s from `%s'\n",
5474 "CONVERGE_MODIFIER", converge_modifier_buf);
5475 converge_modifier = 0.0;
5477 GNUNET_free (converge_modifier_buf);
5481 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "paper_forwarding"))
5482 paper_forwarding = GNUNET_YES;
5485 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "put_peer_identities"))
5486 put_peer_identities = GNUNET_YES;
5488 stats = GNUNET_STATISTICS_create ("dht", cfg);
5492 GNUNET_STATISTICS_set (stats, STAT_ROUTES, 0, GNUNET_NO);
5493 GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
5494 GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS_CLOSEST, 0,
5496 GNUNET_STATISTICS_set (stats, STAT_RESULTS, 0, GNUNET_NO);
5497 GNUNET_STATISTICS_set (stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
5498 GNUNET_STATISTICS_set (stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
5499 GNUNET_STATISTICS_set (stats, STAT_GETS, 0, GNUNET_NO);
5500 GNUNET_STATISTICS_set (stats, STAT_PUTS, 0, GNUNET_NO);
5501 GNUNET_STATISTICS_set (stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
5502 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER, 0, GNUNET_NO);
5503 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
5504 GNUNET_STATISTICS_set (stats, STAT_GET_START, 0, GNUNET_NO);
5505 GNUNET_STATISTICS_set (stats, STAT_PUT_START, 0, GNUNET_NO);
5506 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
5507 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
5508 GNUNET_STATISTICS_set (stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
5509 GNUNET_STATISTICS_set (stats, STAT_GET_REPLY, 0, GNUNET_NO);
5510 GNUNET_STATISTICS_set (stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
5511 GNUNET_STATISTICS_set (stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
5512 GNUNET_STATISTICS_set (stats, STAT_DISCONNECTS, 0, GNUNET_NO);
5514 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
5515 recent.hashmap = GNUNET_CONTAINER_multihashmap_create (DHT_MAX_RECENT / 2);
5517 GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
5518 if (GNUNET_YES == do_find_peer)
5520 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
5521 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
5522 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value /
5524 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
5525 find_peer_context.start = GNUNET_TIME_absolute_get ();
5526 GNUNET_SCHEDULER_add_delayed (next_send_time,
5527 &send_find_peer_message,
5528 &find_peer_context);
5531 /* Scheduled the task to clean up when shutdown is called */
5532 cleanup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
5533 &shutdown_task, NULL);
5537 * The main function for the dht service.
5539 * @param argc number of arguments from the command line
5540 * @param argv command line arguments
5541 * @return 0 ok, 1 on error
5544 main (int argc, char *const *argv)
5549 GNUNET_SERVICE_run (argc,
5552 GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
5553 if (NULL != recent.hashmap)
5555 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (recent.hashmap));
5556 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
5557 recent.hashmap = NULL;
5559 if (NULL != recent.minHeap)
5561 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (recent.minHeap));
5562 GNUNET_CONTAINER_heap_destroy (recent.minHeap);
5563 recent.minHeap = NULL;
5565 if (NULL != recent_find_peer_requests)
5567 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
5568 recent_find_peer_requests = NULL;