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.
938 send_generic_reply (void *cls, size_t size, void *buf);
941 /** Declare here so retry_core_send is aware of it */
943 core_transmit_notify (void *cls, size_t size, void *buf);
946 * Convert unique ID to hash code.
948 * @param uid unique ID to convert
949 * @param hash set to uid (extended with zeros)
952 hash_from_uid (uint64_t uid, GNUNET_HashCode * hash)
954 memset (hash, 0, sizeof (GNUNET_HashCode));
955 *((uint64_t *) hash) = uid;
960 * Calculate the average send time between messages so that we can
961 * ignore certain requests if we get too busy.
963 * @return the average time between asking core to send a message
964 * and when the buffer for copying it is passed
966 static struct GNUNET_TIME_Relative
967 get_average_send_delay ()
970 unsigned int divisor;
971 struct GNUNET_TIME_Relative average_time;
973 average_time = GNUNET_TIME_relative_get_zero ();
975 for (i = 0; i < MAX_REPLY_TIMES; i++)
977 average_time = GNUNET_TIME_relative_add (average_time, reply_times[i]);
978 if (reply_times[i].abs_value == (uint64_t) 0)
988 average_time = GNUNET_TIME_relative_divide (average_time, divisor);
989 fprintf (stderr, "Avg send delay: %u sends is %llu\n", divisor,
990 (unsigned long long) average_time.abs_value);
996 * Given the largest send delay, artificially decrease it
997 * so the next time around we may have a chance at sending
1001 decrease_max_send_delay (struct GNUNET_TIME_Relative max_time)
1005 for (i = 0; i < MAX_REPLY_TIMES; i++)
1007 if (reply_times[i].rel_value == max_time.rel_value)
1009 reply_times[i].rel_value = reply_times[i].rel_value / 2;
1016 * Find the maximum send time of the recently sent values.
1018 * @return the average time between asking core to send a message
1019 * and when the buffer for copying it is passed
1021 static struct GNUNET_TIME_Relative
1022 get_max_send_delay ()
1025 struct GNUNET_TIME_Relative max_time;
1027 max_time = GNUNET_TIME_relative_get_zero ();
1029 for (i = 0; i < MAX_REPLY_TIMES; i++)
1031 if (reply_times[i].rel_value > max_time.rel_value)
1032 max_time.rel_value = reply_times[i].rel_value;
1035 if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
1036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n",
1037 (unsigned long long) max_time.rel_value);
1043 increment_stats (const char *value)
1047 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
1052 decrement_stats (const char *value)
1056 GNUNET_STATISTICS_update (stats, value, -1, GNUNET_NO);
1061 * Try to send another message from our core send list
1064 try_core_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1066 struct PeerInfo *peer = cls;
1067 struct P2PPendingMessage *pending;
1070 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
1072 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1075 if (peer->th != NULL)
1076 return; /* Message send already in progress */
1078 pending = peer->head;
1079 if (pending != NULL)
1081 ssize = ntohs (pending->msg->size);
1083 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1084 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n",
1085 my_short_id, "DHT", ssize, GNUNET_i2s (&peer->id));
1087 pending->scheduled = GNUNET_TIME_absolute_get ();
1089 if (reply_counter >= MAX_REPLY_TIMES)
1092 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
1093 pending->importance,
1094 pending->timeout, &peer->id, ssize,
1095 &core_transmit_notify, peer);
1096 if (peer->th == NULL)
1097 increment_stats ("# notify transmit ready failed");
1102 * Function called to send a request out to another peer.
1103 * Called both for locally initiated requests and those
1104 * received from other peers.
1106 * @param msg the encapsulated message
1107 * @param peer the peer to forward the message to
1108 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1111 forward_result_message (const struct GNUNET_MessageHeader *msg,
1112 struct PeerInfo *peer,
1113 struct DHT_MessageContext *msg_ctx)
1115 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1116 struct P2PPendingMessage *pending;
1126 increment_stats (STAT_RESULT_FORWARDS);
1128 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs (msg->size) +
1129 (sizeof (struct GNUNET_PeerIdentity) * msg_ctx->path_history_len);
1130 GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1131 psize = sizeof (struct P2PPendingMessage) + msize;
1132 pending = GNUNET_malloc (psize);
1133 pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1134 pending->importance = DHT_SEND_PRIORITY;
1135 pending->timeout = GNUNET_TIME_relative_get_forever ();
1136 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *) pending->msg;
1137 result_message->header.size = htons (msize);
1138 result_message->header.type =
1139 htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1140 result_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1141 if (msg_ctx->path_history_len > 0)
1143 /* End of pending is where enc_msg starts */
1144 path_start = (char *) &pending[1];
1145 /* Offset by the size of the enc_msg */
1146 path_start += ntohs (msg->size);
1147 memcpy (path_start, msg_ctx->path_history,
1148 msg_ctx->path_history_len * (sizeof (struct GNUNET_PeerIdentity)));
1150 for (i = 0; i < msg_ctx->path_history_len; i++)
1153 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1154 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1155 "(forward_result) Key %s Found peer %d:%s\n",
1156 GNUNET_h2s (&msg_ctx->key), i,
1157 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1161 result_message->options = htonl (msg_ctx->msg_options);
1162 result_message->hop_count = htonl (msg_ctx->hop_count + 1);
1163 GNUNET_assert (GNUNET_OK ==
1164 GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1168 result_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1169 memcpy (&result_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1170 /* Copy the enc_msg, then the path history as well! */
1171 memcpy (&result_message[1], msg, ntohs (msg->size));
1172 path_offset = (char *) &result_message[1];
1173 path_offset += ntohs (msg->size);
1174 /* If we have path history, copy it to the end of the whole thing */
1175 if (msg_ctx->path_history_len > 0)
1176 memcpy (path_offset, msg_ctx->path_history,
1177 msg_ctx->path_history_len * (sizeof (struct GNUNET_PeerIdentity)));
1179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1180 "%s:%s Adding pending message size %d for peer %s\n", my_short_id,
1181 "DHT", msize, GNUNET_i2s (&peer->id));
1183 peer->pending_count++;
1184 increment_stats ("# pending messages scheduled");
1185 GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1187 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1188 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1193 * Called when core is ready to send a message we asked for
1194 * out to the destination.
1196 * @param cls closure (NULL)
1197 * @param size number of bytes available in buf
1198 * @param buf where the callee should write the message
1199 * @return number of bytes written to buf
1202 core_transmit_notify (void *cls, size_t size, void *buf)
1204 struct PeerInfo *peer = cls;
1206 struct P2PPendingMessage *pending;
1214 /* client disconnected */
1216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n",
1217 my_short_id, "DHT");
1222 if (peer->head == NULL)
1226 pending = peer->head;
1228 reply_times[reply_counter] =
1229 GNUNET_TIME_absolute_get_difference (pending->scheduled,
1230 GNUNET_TIME_absolute_get ());
1231 msize = ntohs (pending->msg->size);
1235 memcpy (cbuf, pending->msg, msize);
1236 peer->pending_count--;
1237 increment_stats ("# pending messages sent");
1238 GNUNET_assert (peer->pending_count >= 0);
1239 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1240 GNUNET_free (pending);
1243 while (NULL != pending &&
1244 (size - off >= (msize = ntohs (pending->msg->size))))
1246 memcpy (&cbuf[off], pending->msg, msize);
1248 peer->pending_count--;
1249 increment_stats ("# pending messages sent");
1250 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1251 GNUNET_free (pending);
1252 pending = peer->head;
1255 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1256 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1263 * Compute the distance between have and target as a 32-bit value.
1264 * Differences in the lower bits must count stronger than differences
1265 * in the higher bits.
1267 * @return 0 if have==target, otherwise a number
1268 * that is larger as the distance between
1269 * the two hash codes increases
1272 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1274 unsigned int bucket;
1279 /* We have to represent the distance between two 2^9 (=512)-bit
1280 * numbers as a 2^5 (=32)-bit number with "0" being used for the
1281 * two numbers being identical; furthermore, we need to
1282 * guarantee that a difference in the number of matching
1283 * bits is always represented in the result.
1285 * We use 2^32/2^9 numerical values to distinguish between
1286 * hash codes that have the same LSB bit distance and
1287 * use the highest 2^9 bits of the result to signify the
1288 * number of (mis)matching LSB bits; if we have 0 matching
1289 * and hence 512 mismatching LSB bits we return -1 (since
1290 * 512 itself cannot be represented with 9 bits) */
1292 /* first, calculate the most significant 9 bits of our
1293 * result, aka the number of LSBs */
1294 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1295 /* bucket is now a value between 0 and 512 */
1297 return 0; /* perfect match */
1299 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1300 * below, we'd end up with max+1 (overflow)) */
1302 /* calculate the most significant bits of the final result */
1303 msb = (512 - bucket) << (32 - 9);
1304 /* calculate the 32-9 least significant bits of the final result by
1305 * looking at the differences in the 32-9 bits following the
1306 * mismatching bit at 'bucket' */
1308 for (i = bucket + 1;
1309 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1311 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
1312 GNUNET_CRYPTO_hash_get_bit (have, i))
1313 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1314 * last bit set will be 31 -- if
1315 * i does not reach 512 first... */
1321 * Return a number that is larger the closer the
1322 * "have" GNUNET_hash code is to the "target".
1324 * @return inverse distance metric, non-zero.
1325 * Must fudge the value if NO bits match.
1328 inverse_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1330 if (GNUNET_CRYPTO_hash_matching_bits (target, have) == 0)
1331 return 1; /* Never return 0! */
1332 return ((unsigned int) -1) - distance (target, have);
1337 * Find the optimal bucket for this key, regardless
1338 * of the current number of buckets in use.
1340 * @param hc the hashcode to compare our identity to
1342 * @return the proper bucket index, or GNUNET_SYSERR
1343 * on error (same hashcode)
1346 find_bucket (const GNUNET_HashCode * hc)
1350 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
1351 if (bits == MAX_BUCKETS)
1352 return GNUNET_SYSERR;
1353 return MAX_BUCKETS - bits - 1;
1358 * Find which k-bucket this peer should go into,
1359 * taking into account the size of the k-bucket
1360 * array. This means that if more bits match than
1361 * there are currently buckets, lowest_bucket will
1364 * @param hc GNUNET_HashCode we are finding the bucket for.
1366 * @return the proper bucket index for this key,
1367 * or GNUNET_SYSERR on error (same hashcode)
1370 find_current_bucket (const GNUNET_HashCode * hc)
1374 actual_bucket = find_bucket (hc);
1375 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1376 return lowest_bucket;
1377 if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1378 return lowest_bucket;
1379 return actual_bucket;
1384 * Find a routing table entry from a peer identity
1386 * @param peer the peer to look up
1388 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1391 find_bucket_by_peer (const struct PeerInfo *peer)
1394 struct PeerInfo *pos;
1396 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1398 pos = k_buckets[bucket].head;
1407 return GNUNET_SYSERR; /* No such peer. */
1413 * Print the complete routing table for this peer.
1416 print_routing_table ()
1419 struct PeerInfo *pos;
1420 char char_buf[30000];
1423 memset (char_buf, 0, sizeof (char_buf));
1426 sprintf (&char_buf[char_pos], "Printing routing table for peer %s\n",
1428 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1429 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1431 pos = k_buckets[bucket].head;
1432 char_pos += sprintf (&char_buf[char_pos], "Bucket %d:\n", bucket);
1433 //fprintf(stderr, "Bucket %d:\n", bucket);
1436 //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));
1438 sprintf (&char_buf[char_pos],
1439 "\tPeer %s, best bucket %d, %d bits match\n",
1440 GNUNET_i2s (&pos->id), find_bucket (&pos->id.hashPubKey),
1441 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
1442 &my_identity.hashPubKey));
1446 fprintf (stderr, "%s", char_buf);
1452 * Find a routing table entry from a peer identity
1454 * @param peer the peer identity to look up
1456 * @return the routing table entry, or NULL if not found
1458 static struct PeerInfo *
1459 find_peer_by_id (const struct GNUNET_PeerIdentity *peer)
1462 struct PeerInfo *pos;
1464 bucket = find_current_bucket (&peer->hashPubKey);
1466 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
1469 pos = k_buckets[bucket].head;
1472 if (0 == memcmp (&pos->id, peer, sizeof (struct GNUNET_PeerIdentity)))
1476 return NULL; /* No such peer. */
1479 /* Forward declaration */
1481 update_core_preference (void *cls,
1482 const struct GNUNET_SCHEDULER_TaskContext *tc);
1484 * Function called with statistics about the given peer.
1486 * @param cls closure
1487 * @param peer identifies the peer
1488 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1489 * @param amount set to the amount that was actually reserved or unreserved;
1490 * either the full requested amount or zero (no partial reservations)
1491 * @param res_delay if the reservation could not be satisfied (amount was 0), how
1492 * long should the client wait until re-trying?
1493 * @param preference current traffic preference for the given peer
1496 update_core_preference_finish (void *cls,
1497 const struct GNUNET_PeerIdentity *peer,
1498 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1500 struct GNUNET_TIME_Relative res_delay,
1501 uint64_t preference)
1503 struct PeerInfo *peer_info = cls;
1505 peer_info->info_ctx = NULL;
1506 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
1507 &update_core_preference, peer_info);
1511 update_core_preference (void *cls,
1512 const struct GNUNET_SCHEDULER_TaskContext *tc)
1514 struct PeerInfo *peer = cls;
1515 uint64_t preference;
1516 unsigned int matching;
1518 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1523 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
1524 &peer->id.hashPubKey);
1528 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1529 "Peer identifier matches by %u bits, only shifting as much as we can!\n",
1534 preference = 1LL << matching;
1536 GNUNET_CORE_peer_change_preference (coreAPI, &peer->id,
1537 GNUNET_TIME_UNIT_FOREVER_REL,
1538 GNUNET_BANDWIDTH_VALUE_MAX, 0,
1540 &update_core_preference_finish, peer);
1545 * Given a peer and its corresponding bucket,
1546 * remove it from that bucket. Does not free
1547 * the PeerInfo struct, nor cancel messages
1548 * or free messages waiting to be sent to this
1551 * @param peer the peer to remove
1552 * @param bucket the bucket the peer belongs to
1555 remove_peer (struct PeerInfo *peer, unsigned int bucket)
1557 GNUNET_assert (k_buckets[bucket].peers_size > 0);
1558 GNUNET_CONTAINER_DLL_remove (k_buckets[bucket].head, k_buckets[bucket].tail,
1560 k_buckets[bucket].peers_size--;
1562 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) &&
1563 (lowest_bucket < MAX_BUCKETS - 1))
1569 * Removes peer from a bucket, then frees associated
1570 * resources and frees peer.
1572 * @param peer peer to be removed and freed
1573 * @param bucket which bucket this peer belongs to
1576 delete_peer (struct PeerInfo *peer, unsigned int bucket)
1578 struct P2PPendingMessage *pos;
1579 struct P2PPendingMessage *next;
1582 struct PeerInfo *peer_pos;
1584 peer_pos = k_buckets[bucket].head;
1585 while ((peer_pos != NULL) && (peer_pos != peer))
1586 peer_pos = peer_pos->next;
1587 if (peer_pos == NULL)
1589 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1590 "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT",
1591 GNUNET_i2s (&peer->id), bucket);
1592 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1593 "%s:%s: Lowest bucket: %d, find_current_bucket: %d, peer resides in bucket: %d\n",
1594 my_short_id, "DHT", lowest_bucket,
1595 find_current_bucket (&peer->id.hashPubKey),
1596 find_bucket_by_peer (peer));
1598 GNUNET_assert (peer_pos != NULL);
1600 remove_peer (peer, bucket); /* First remove the peer from its bucket */
1602 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1603 GNUNET_SCHEDULER_cancel (peer->send_task);
1604 if ((peer->th != NULL) && (coreAPI != NULL))
1605 GNUNET_CORE_notify_transmit_ready_cancel (peer->th);
1608 while (pos != NULL) /* Remove any pending messages for this peer */
1611 ("# dht pending messages discarded (due to disconnect/shutdown)");
1617 GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
1618 (all_known_peers, &peer->id.hashPubKey));
1619 GNUNET_assert (GNUNET_YES ==
1620 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
1621 &peer->id.hashPubKey,
1624 decrement_stats (STAT_PEERS_KNOWN);
1629 * Iterator over hash map entries.
1631 * @param cls closure
1632 * @param key current key code
1633 * @param value PeerInfo of the peer to move to new lowest bucket
1634 * @return GNUNET_YES if we should continue to
1639 move_lowest_bucket (void *cls, const GNUNET_HashCode * key, void *value)
1641 struct PeerInfo *peer = value;
1644 GNUNET_assert (lowest_bucket > 0);
1645 new_bucket = lowest_bucket - 1;
1646 remove_peer (peer, lowest_bucket);
1647 GNUNET_CONTAINER_DLL_insert_after (k_buckets[new_bucket].head,
1648 k_buckets[new_bucket].tail,
1649 k_buckets[new_bucket].tail, peer);
1650 k_buckets[new_bucket].peers_size++;
1656 * The current lowest bucket is full, so change the lowest
1657 * bucket to the next lower down, and move any appropriate
1658 * entries in the current lowest bucket to the new bucket.
1661 enable_next_bucket ()
1663 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1664 struct PeerInfo *pos;
1666 GNUNET_assert (lowest_bucket > 0);
1667 to_remove = GNUNET_CONTAINER_multihashmap_create (bucket_size);
1668 pos = k_buckets[lowest_bucket].head;
1671 fprintf (stderr, "Printing RT before new bucket\n");
1672 print_routing_table ();
1674 /* Populate the array of peers which should be in the next lowest bucket */
1677 if (find_bucket (&pos->id.hashPubKey) < lowest_bucket)
1678 GNUNET_CONTAINER_multihashmap_put (to_remove, &pos->id.hashPubKey, pos,
1679 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1683 /* Remove peers from lowest bucket, insert into next lowest bucket */
1684 GNUNET_CONTAINER_multihashmap_iterate (to_remove, &move_lowest_bucket, NULL);
1685 GNUNET_CONTAINER_multihashmap_destroy (to_remove);
1686 lowest_bucket = lowest_bucket - 1;
1688 fprintf (stderr, "Printing RT after new bucket\n");
1689 print_routing_table ();
1694 * Find the closest peer in our routing table to the
1697 * @return The closest peer in our routing table to the
1698 * key, or NULL on error.
1700 static struct PeerInfo *
1701 find_closest_peer (const GNUNET_HashCode * hc)
1703 struct PeerInfo *pos;
1704 struct PeerInfo *current_closest;
1705 unsigned int lowest_distance;
1706 unsigned int temp_distance;
1710 lowest_distance = -1;
1712 if (k_buckets[lowest_bucket].peers_size == 0)
1715 current_closest = NULL;
1716 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1718 pos = k_buckets[bucket].head;
1720 while ((pos != NULL) && (count < bucket_size))
1722 temp_distance = distance (&pos->id.hashPubKey, hc);
1723 if (temp_distance <= lowest_distance)
1725 lowest_distance = temp_distance;
1726 current_closest = pos;
1732 GNUNET_assert (current_closest != NULL);
1733 return current_closest;
1738 * Function called to send a request out to another peer.
1739 * Called both for locally initiated requests and those
1740 * received from other peers.
1742 * @param msg the encapsulated message
1743 * @param peer the peer to forward the message to
1744 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1747 forward_message (const struct GNUNET_MessageHeader *msg, struct PeerInfo *peer,
1748 struct DHT_MessageContext *msg_ctx)
1750 struct GNUNET_DHT_P2PRouteMessage *route_message;
1751 struct P2PPendingMessage *pending;
1756 increment_stats (STAT_ROUTE_FORWARDS);
1757 GNUNET_assert (peer != NULL);
1758 if ((msg_ctx->closest != GNUNET_YES) &&
1759 (peer == find_closest_peer (&msg_ctx->key)))
1760 increment_stats (STAT_ROUTE_FORWARDS_CLOSEST);
1763 sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs (msg->size) +
1764 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1765 GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1766 psize = sizeof (struct P2PPendingMessage) + msize;
1767 pending = GNUNET_malloc (psize);
1768 pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1769 pending->importance = msg_ctx->importance;
1770 pending->timeout = msg_ctx->timeout;
1771 route_message = (struct GNUNET_DHT_P2PRouteMessage *) pending->msg;
1772 route_message->header.size = htons (msize);
1773 route_message->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1774 route_message->options = htonl (msg_ctx->msg_options);
1775 route_message->hop_count = htonl (msg_ctx->hop_count + 1);
1776 route_message->network_size = htonl (msg_ctx->network_size);
1777 route_message->desired_replication_level = htonl (msg_ctx->replication);
1778 route_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1779 if (msg_ctx->bloom != NULL)
1780 GNUNET_assert (GNUNET_OK ==
1781 GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1785 memcpy (&route_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1786 memcpy (&route_message[1], msg, ntohs (msg->size));
1787 if (GNUNET_DHT_RO_RECORD_ROUTE ==
1788 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
1790 route_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1791 /* Set pointer to start of enc_msg */
1792 route_path = (char *) &route_message[1];
1793 /* Offset to the end of the enc_msg */
1794 route_path += ntohs (msg->size);
1795 /* Copy the route_path after enc_msg */
1796 memcpy (route_path, msg_ctx->path_history,
1797 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1800 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1801 "%s:%s Adding pending message size %d for peer %s\n", my_short_id,
1802 "DHT", msize, GNUNET_i2s (&peer->id));
1804 peer->pending_count++;
1805 increment_stats ("# pending messages scheduled");
1806 GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1808 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1809 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1814 * Task used to send ping messages to peers so that
1815 * they don't get disconnected.
1817 * @param cls the peer to send a ping message to
1818 * @param tc context, reason, etc.
1821 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1823 struct PeerInfo *peer = cls;
1824 struct GNUNET_MessageHeader ping_message;
1825 struct DHT_MessageContext msg_ctx;
1827 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1830 ping_message.size = htons (sizeof (struct GNUNET_MessageHeader));
1831 ping_message.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1833 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
1835 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n",
1836 my_short_id, "DHT", GNUNET_i2s (&peer->id));
1838 forward_message (&ping_message, peer, &msg_ctx);
1840 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PING_DELAY, &periodic_ping_task,
1845 * Schedule PING messages for the top X peers in each
1846 * bucket of the routing table (so core won't disconnect them!)
1849 schedule_ping_messages ()
1851 unsigned int bucket;
1853 struct PeerInfo *pos;
1855 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1857 pos = k_buckets[bucket].head;
1861 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1862 GNUNET_SCHEDULER_add_now (&periodic_ping_task, pos);
1863 else if ((count >= bucket_size) &&
1864 (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1866 GNUNET_SCHEDULER_cancel (pos->ping_task);
1867 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1878 * Task run to check for messages that need to be sent to a client.
1880 * @param client a ClientList, containing the client and any messages to be sent to it
1883 process_pending_messages (struct ClientList *client)
1885 if (client->pending_head == NULL)
1887 if (client->transmit_handle != NULL)
1890 client->transmit_handle =
1891 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1892 ntohs (client->pending_head->
1894 GNUNET_TIME_UNIT_FOREVER_REL,
1895 &send_generic_reply, client);
1899 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1900 * request. A ClientList is passed as closure, take the head of the list
1901 * and copy it into buf, which has the result of sending the message to the
1904 * @param cls closure to this call
1905 * @param size maximum number of bytes available to send
1906 * @param buf where to copy the actual message to
1908 * @return the number of bytes actually copied, 0 indicates failure
1911 send_generic_reply (void *cls, size_t size, void *buf)
1913 struct ClientList *client = cls;
1915 struct PendingMessage *reply;
1919 client->transmit_handle = NULL;
1922 /* client disconnected */
1926 while ((NULL != (reply = client->pending_head)) &&
1927 (size >= off + (msize = ntohs (reply->msg->size))))
1929 GNUNET_CONTAINER_DLL_remove (client->pending_head, client->pending_tail,
1931 memcpy (&cbuf[off], reply->msg, msize);
1932 GNUNET_free (reply);
1935 process_pending_messages (client);
1937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1938 "Transmitted %u bytes of replies to client\n",
1939 (unsigned int) off);
1946 * Add a PendingMessage to the clients list of messages to be sent
1948 * @param client the active client to send the message to
1949 * @param pending_message the actual message to send
1952 add_pending_message (struct ClientList *client,
1953 struct PendingMessage *pending_message)
1955 GNUNET_CONTAINER_DLL_insert_after (client->pending_head, client->pending_tail,
1956 client->pending_tail, pending_message);
1957 process_pending_messages (client);
1962 * Called when a reply needs to be sent to a client, as
1963 * a result it found to a GET or FIND PEER request.
1965 * @param client the client to send the reply to
1966 * @param message the encapsulated message to send
1967 * @param msg_ctx the context of the received message
1970 send_reply_to_client (struct ClientList *client,
1971 const struct GNUNET_MessageHeader *message,
1972 struct DHT_MessageContext *msg_ctx)
1974 struct GNUNET_DHT_RouteResultMessage *reply;
1975 struct PendingMessage *pending_message;
1985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': Sending reply to client.\n",
1986 my_short_id, "DHT");
1988 msize = ntohs (message->size);
1990 sizeof (struct GNUNET_DHT_RouteResultMessage) + msize +
1991 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1992 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1994 GNUNET_break_op (0);
1997 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1998 pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1999 reply = (struct GNUNET_DHT_RouteResultMessage *) &pending_message[1];
2000 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
2001 reply->header.size = htons (tsize);
2002 reply->outgoing_path_length = htonl (msg_ctx->path_history_len);
2003 reply->unique_id = GNUNET_htonll (msg_ctx->unique_id);
2004 memcpy (&reply->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
2005 reply_offset = (char *) &reply[1];
2006 memcpy (&reply[1], message, msize);
2007 if (msg_ctx->path_history_len > 0)
2009 reply_offset += msize;
2010 memcpy (reply_offset, msg_ctx->path_history,
2011 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2015 "Returning message with outgoing path length %d\n",
2016 msg_ctx->path_history_len);
2017 for (i = 0; i < msg_ctx->path_history_len; i++)
2020 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
2021 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found peer %d:%s\n", i,
2022 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
2025 add_pending_message (client, pending_message);
2029 * Consider whether or not we would like to have this peer added to
2030 * our routing table. Check whether bucket for this peer is full,
2031 * if so return negative; if not return positive. Since peers are
2032 * only added on CORE level connect, this doesn't actually add the
2033 * peer to the routing table.
2035 * @param peer the peer we are considering adding
2037 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
2041 consider_peer (struct GNUNET_PeerIdentity *peer)
2046 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
2047 &peer->hashPubKey)) ||
2048 (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity))))
2049 return GNUNET_NO; /* We already know this peer (are connected even!) */
2050 bucket = find_current_bucket (&peer->hashPubKey);
2052 if ((k_buckets[bucket].peers_size < bucket_size) ||
2053 ((bucket == lowest_bucket) && (lowest_bucket > 0)))
2061 * Task used to remove forwarding entries, either
2062 * after timeout, when full, or on shutdown.
2064 * @param cls the entry to remove
2065 * @param tc context, reason, etc.
2068 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2070 struct DHTRouteSource *source_info = cls;
2071 struct DHTQueryRecord *record;
2073 source_info = GNUNET_CONTAINER_heap_remove_node (source_info->hnode);
2074 record = source_info->record;
2075 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
2077 if (record->head == NULL) /* No more entries in DLL */
2079 GNUNET_assert (GNUNET_YES ==
2080 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
2081 &record->key, record));
2082 GNUNET_free (record);
2084 if (source_info->find_peers_responded != NULL)
2085 GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
2086 GNUNET_free (source_info);
2090 * Main function that handles whether or not to route a result
2091 * message to other peers, or to send to our local client.
2093 * @param msg the result message to be routed
2094 * @param msg_ctx context of the message we are routing
2096 * @return the number of peers the message was routed to,
2097 * GNUNET_SYSERR on failure
2100 route_result_message (struct GNUNET_MessageHeader *msg,
2101 struct DHT_MessageContext *msg_ctx)
2103 struct GNUNET_PeerIdentity new_peer;
2104 struct DHTQueryRecord *record;
2105 struct DHTRouteSource *pos;
2106 struct PeerInfo *peer_info;
2107 const struct GNUNET_MessageHeader *hello_msg;
2113 increment_stats (STAT_RESULTS);
2115 * If a find peer result message is received and contains a valid
2116 * HELLO for another peer, offer it to the transport service.
2118 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
2120 if (ntohs (msg->size) <= sizeof (struct GNUNET_MessageHeader))
2121 GNUNET_break_op (0);
2123 hello_msg = &msg[1];
2124 if ((ntohs (hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2126 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello_msg,
2129 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2130 "%s:%s Received non-HELLO message type in find peer result message!\n",
2131 my_short_id, "DHT");
2132 GNUNET_break_op (0);
2135 else /* We have a valid hello, and peer id stored in new_peer */
2137 find_peer_context.count++;
2138 increment_stats (STAT_FIND_PEER_REPLY);
2139 if (GNUNET_YES == consider_peer (&new_peer))
2141 increment_stats (STAT_HELLOS_PROVIDED);
2142 GNUNET_TRANSPORT_offer_hello (transport_handle, hello_msg, NULL, NULL);
2143 GNUNET_CORE_peer_request_connect (coreAPI, &new_peer, NULL, NULL);
2148 if (malicious_dropper == GNUNET_YES)
2152 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
2154 if (record == NULL) /* No record of this message! */
2157 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2158 "`%s:%s': Have no record of response key %s uid %llu\n",
2159 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2160 msg_ctx->unique_id);
2162 #if DEBUG_DHT_ROUTING
2163 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2165 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2166 msg_ctx->hop_count, GNUNET_SYSERR,
2167 &my_identity, &msg_ctx->key, msg_ctx->peer,
2171 if (msg_ctx->bloom != NULL)
2173 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
2174 msg_ctx->bloom = NULL;
2182 #if STRICT_FORWARDING
2183 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2186 GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded,
2187 &new_peer.hashPubKey))
2189 increment_stats ("# find peer responses NOT forwarded (bloom match)");
2194 GNUNET_CONTAINER_bloomfilter_add (pos->find_peers_responded,
2195 &new_peer.hashPubKey);
2199 if (0 == memcmp (&pos->source, &my_identity, sizeof (struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2203 "`%s:%s': Sending response key %s uid %llu to client\n",
2204 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2205 msg_ctx->unique_id);
2207 #if DEBUG_DHT_ROUTING
2208 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2210 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2211 msg_ctx->hop_count, GNUNET_YES,
2212 &my_identity, &msg_ctx->key, msg_ctx->peer,
2216 increment_stats (STAT_RESULTS_TO_CLIENT);
2217 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2218 increment_stats (STAT_GET_REPLY);
2220 for (i = 0; i < msg_ctx->path_history_len; i++)
2225 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
2226 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2227 "(before client) Key %s Found peer %d:%s\n",
2228 GNUNET_h2s (&msg_ctx->key), i,
2229 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
2232 send_reply_to_client (pos->client, msg, msg_ctx);
2234 else /* Send to peer */
2236 peer_info = find_peer_by_id (&pos->source);
2237 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2243 if (msg_ctx->bloom == NULL)
2245 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
2247 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
2248 &my_identity.hashPubKey);
2250 GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom,
2251 &peer_info->id.hashPubKey)))
2254 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2255 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n",
2256 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2257 msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2259 #if DEBUG_DHT_ROUTING
2260 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2262 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2263 msg_ctx->hop_count, GNUNET_NO,
2264 &my_identity, &msg_ctx->key,
2265 msg_ctx->peer, &pos->source);
2268 forward_result_message (msg, peer_info, msg_ctx);
2269 /* Try removing forward entries after sending once, only allows ONE response per request */
2270 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
2272 GNUNET_SCHEDULER_cancel (pos->delete_task);
2274 GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
2280 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2281 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n",
2282 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2283 msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2289 if (msg_ctx->bloom != NULL)
2291 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
2292 msg_ctx->bloom = NULL;
2299 * Iterator for local get request results,
2301 * @param cls closure for iterator, a DatacacheGetContext
2302 * @param exp when does this value expire?
2303 * @param key the key this data is stored under
2304 * @param size the size of the data identified by key
2305 * @param data the actual data
2306 * @param type the type of the data
2308 * @return GNUNET_OK to continue iteration, anything else
2309 * to stop iteration.
2312 datacache_get_iterator (void *cls, struct GNUNET_TIME_Absolute exp,
2313 const GNUNET_HashCode * key, size_t size,
2314 const char *data, enum GNUNET_BLOCK_Type type)
2316 struct DHT_MessageContext *msg_ctx = cls;
2317 struct DHT_MessageContext *new_msg_ctx;
2318 struct GNUNET_DHT_GetResultMessage *get_result;
2319 enum GNUNET_BLOCK_EvaluationResult eval;
2320 const struct DHTPutEntry *put_entry;
2329 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2330 "`%s:%s': Received `%s' response from datacache\n", my_short_id,
2334 put_entry = (const struct DHTPutEntry *) data;
2337 sizeof (struct DHTPutEntry) + put_entry->data_size +
2338 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)))
2340 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2341 "Path + data size doesn't add up for data inserted into datacache!\nData size %d, path length %d, expected %d, got %d\n",
2342 put_entry->data_size, put_entry->path_length,
2343 sizeof (struct DHTPutEntry) + put_entry->data_size +
2344 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)),
2346 msg_ctx->do_forward = GNUNET_NO;
2351 GNUNET_BLOCK_evaluate (block_context, type, key, &msg_ctx->reply_bf,
2352 msg_ctx->reply_bf_mutator, msg_ctx->xquery,
2353 msg_ctx->xquery_size, &put_entry[1],
2354 put_entry->data_size);
2358 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2359 msg_ctx->do_forward = GNUNET_NO;
2360 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2361 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2362 memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2363 if (GNUNET_DHT_RO_RECORD_ROUTE ==
2364 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2366 new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2367 new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2368 /* Assign to previous msg_ctx path history, caller should free after our return */
2369 new_msg_ctx->path_history = msg_ctx->path_history;
2371 for (i = 0; i < new_msg_ctx->path_history_len; i++)
2374 &new_msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
2375 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2376 "(get_iterator) Key %s Found peer %d:%s\n",
2377 GNUNET_h2s (&msg_ctx->key), i,
2378 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
2384 sizeof (struct GNUNET_DHT_GetResultMessage) + put_entry->data_size +
2385 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity));
2386 get_result = GNUNET_malloc (get_size);
2387 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2388 get_result->header.size = htons (get_size);
2389 get_result->expiration = GNUNET_TIME_absolute_hton (exp);
2390 get_result->type = htons (type);
2391 get_result->put_path_length = htons (put_entry->path_length);
2392 path_offset = (char *) &put_entry[1];
2393 path_offset += put_entry->data_size;
2395 for (i = 0; i < put_entry->path_length; i++)
2397 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2398 "(get_iterator PUT path) Key %s Found peer %d:%s\n",
2399 GNUNET_h2s (&msg_ctx->key), i,
2400 GNUNET_i2s ((struct GNUNET_PeerIdentity *)
2403 GNUNET_PeerIdentity)]));
2406 /* Copy the actual data and the path_history to the end of the get result */
2407 memcpy (&get_result[1], &put_entry[1],
2408 put_entry->data_size +
2409 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)));
2410 new_msg_ctx->peer = &my_identity;
2411 new_msg_ctx->bloom =
2412 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2413 new_msg_ctx->hop_count = 0;
2414 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
2415 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2416 increment_stats (STAT_GET_RESPONSE_START);
2417 route_result_message (&get_result->header, new_msg_ctx);
2418 GNUNET_free (new_msg_ctx);
2419 GNUNET_free (get_result);
2421 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': Duplicate block error\n",
2424 my_short_id, "DHT");
2427 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2429 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "`%s:%s': Invalid request error\n",
2430 my_short_id, "DHT");
2433 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2435 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2436 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2440 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2441 GNUNET_break_op (0);
2442 msg_ctx->do_forward = GNUNET_NO;
2444 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2446 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2447 "`%s:%s': Unsupported block type (%u) in response!\n",
2448 my_short_id, "DHT", type);
2450 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2458 * Main function that handles whether or not to route a message to other
2461 * @param msg the message to be routed
2462 * @param msg_ctx the context containing all pertinent information about the message
2465 route_message (const struct GNUNET_MessageHeader *msg,
2466 struct DHT_MessageContext *msg_ctx);
2470 * Server handler for all dht get requests, look for data,
2471 * if found, send response either to clients or other peers.
2473 * @param msg the actual get message
2474 * @param msg_ctx struct containing pertinent information about the get request
2476 * @return number of items found for GET request
2479 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2480 struct DHT_MessageContext *msg_ctx)
2482 const struct GNUNET_DHT_GetMessage *get_msg;
2485 unsigned int results;
2487 enum GNUNET_BLOCK_Type type;
2489 msize = ntohs (msg->size);
2490 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2495 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2496 bf_size = ntohs (get_msg->bf_size);
2497 msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2498 msg_ctx->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2500 sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2505 end = (const char *) &get_msg[1];
2506 if (msg_ctx->xquery_size == 0)
2508 msg_ctx->xquery = NULL;
2512 msg_ctx->xquery = (const void *) end;
2513 end += msg_ctx->xquery_size;
2517 msg_ctx->reply_bf = NULL;
2522 GNUNET_CONTAINER_bloomfilter_init (end, bf_size,
2523 GNUNET_DHT_GET_BLOOMFILTER_K);
2525 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2527 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2528 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2529 my_short_id, "DHT", "GET", type, GNUNET_h2s (&msg_ctx->key),
2530 msg_ctx->unique_id);
2532 increment_stats (STAT_GETS);
2535 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2537 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2541 msg_ctx->do_forward = GNUNET_YES;
2542 if (datacache != NULL)
2544 GNUNET_DATACACHE_get (datacache, &msg_ctx->key, type,
2545 &datacache_get_iterator, msg_ctx);
2547 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2548 "`%s:%s': Found %d results for `%s' request uid %llu\n",
2549 my_short_id, "DHT", results, "GET", msg_ctx->unique_id);
2553 #if DEBUG_DHT_ROUTING
2554 if ((debug_routes) && (dhtlog_handle != NULL))
2556 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2557 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2561 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2563 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2564 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2565 &msg_ctx->key, msg_ctx->peer, NULL);
2571 /* check query valid */
2572 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID ==
2573 GNUNET_BLOCK_evaluate (block_context, type, &msg_ctx->key,
2574 &msg_ctx->reply_bf, msg_ctx->reply_bf_mutator,
2575 msg_ctx->xquery, msg_ctx->xquery_size, NULL, 0))
2577 GNUNET_break_op (0);
2578 msg_ctx->do_forward = GNUNET_NO;
2582 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2584 #if DEBUG_DHT_ROUTING
2585 if ((debug_routes) && (dhtlog_handle != NULL))
2587 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2588 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2593 if (msg_ctx->do_forward == GNUNET_YES)
2594 route_message (msg, msg_ctx);
2595 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2600 remove_recent_find_peer (void *cls,
2601 const struct GNUNET_SCHEDULER_TaskContext *tc)
2603 GNUNET_HashCode *key = cls;
2605 GNUNET_assert (GNUNET_YES ==
2606 GNUNET_CONTAINER_multihashmap_remove
2607 (recent_find_peer_requests, key, NULL));
2612 * Server handler for initiating local dht find peer requests
2614 * @param find_msg the actual find peer message
2615 * @param msg_ctx struct containing pertinent information about the request
2619 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2620 struct DHT_MessageContext *msg_ctx)
2622 struct GNUNET_MessageHeader *find_peer_result;
2623 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2624 struct DHT_MessageContext *new_msg_ctx;
2625 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2628 GNUNET_HashCode *recent_hash;
2629 struct GNUNET_MessageHeader *other_hello;
2630 size_t other_hello_size;
2631 struct GNUNET_PeerIdentity peer_id;
2633 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *) find_msg;
2634 GNUNET_break_op (ntohs (find_msg->size) >=
2635 (sizeof (struct GNUNET_DHT_FindPeerMessage)));
2636 if (ntohs (find_msg->size) < sizeof (struct GNUNET_DHT_FindPeerMessage))
2639 other_hello_size = 0;
2640 if (ntohs (find_msg->size) > sizeof (struct GNUNET_DHT_FindPeerMessage))
2643 ntohs (find_msg->size) - sizeof (struct GNUNET_DHT_FindPeerMessage);
2644 other_hello = GNUNET_malloc (other_hello_size);
2645 memcpy (other_hello, &find_peer_message[1], other_hello_size);
2646 if ((GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) other_hello) == 0)
2648 GNUNET_HELLO_get_id ((struct GNUNET_HELLO_Message *) other_hello,
2651 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2652 "Received invalid HELLO message in find peer request!\n");
2653 GNUNET_free (other_hello);
2656 #if FIND_PEER_WITH_HELLO
2657 if (GNUNET_YES == consider_peer (&peer_id))
2659 increment_stats (STAT_HELLOS_PROVIDED);
2660 GNUNET_TRANSPORT_offer_hello (transport_handle, other_hello, NULL, NULL);
2661 GNUNET_CORE_peer_request_connect (coreAPI, &peer_id, NULL, NULL);
2662 route_message (find_msg, msg_ctx);
2663 GNUNET_free (other_hello);
2666 else /* We don't want this peer! */
2668 route_message (find_msg, msg_ctx);
2669 GNUNET_free (other_hello);
2676 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2677 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2678 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2679 ntohs (find_msg->size), sizeof (struct GNUNET_MessageHeader));
2681 if (my_hello == NULL)
2684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2685 "`%s': Our HELLO is null, can't return.\n", "DHT");
2687 GNUNET_free_non_null (other_hello);
2688 route_message (find_msg, msg_ctx);
2693 GNUNET_CONTAINER_bloomfilter_init (find_peer_message->bloomfilter,
2694 DHT_BLOOM_SIZE, DHT_BLOOM_K);
2696 GNUNET_CONTAINER_bloomfilter_test (incoming_bloom,
2697 &my_identity.hashPubKey))
2699 increment_stats (STAT_BLOOM_FIND_PEER);
2700 GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2701 GNUNET_free_non_null (other_hello);
2702 route_message (find_msg, msg_ctx);
2703 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!) */
2705 GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2707 #if RESTRICT_FIND_PEER
2710 * Ignore any find peer requests from a peer we have seen very recently.
2712 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! */
2714 increment_stats ("# dht find peer requests ignored (recently seen!)");
2715 GNUNET_free_non_null (other_hello);
2720 * Use this check to only allow the peer to respond to find peer requests if
2721 * it would be beneficial to have the requesting peer in this peers routing
2722 * table. Can be used to thwart peers flooding the network with find peer
2723 * requests that we don't care about. However, if a new peer is joining
2724 * the network and has no other peers this is a problem (assume all buckets
2725 * full, no one will respond!).
2727 memcpy (&peer_id.hashPubKey, &msg_ctx->key, sizeof (GNUNET_HashCode));
2728 if (GNUNET_NO == consider_peer (&peer_id))
2730 increment_stats ("# dht find peer requests ignored (do not need!)");
2731 GNUNET_free_non_null (other_hello);
2732 route_message (find_msg, msg_ctx);
2737 recent_hash = GNUNET_malloc (sizeof (GNUNET_HashCode));
2738 memcpy (recent_hash, &msg_ctx->key, sizeof (GNUNET_HashCode));
2739 if (GNUNET_SYSERR !=
2740 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2741 &msg_ctx->key, NULL,
2742 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2745 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2746 "Adding recent remove task for key `%s`!\n",
2747 GNUNET_h2s (&msg_ctx->key));
2749 /* Only add a task if there wasn't one for this key already! */
2750 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2751 (GNUNET_TIME_UNIT_SECONDS, 30),
2752 &remove_recent_find_peer, recent_hash);
2756 GNUNET_free (recent_hash);
2758 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2759 "Received duplicate find peer request too soon!\n");
2763 /* Simplistic find_peer functionality, always return our hello */
2764 hello_size = ntohs (my_hello->size);
2765 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2767 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2769 GNUNET_break_op (0);
2770 GNUNET_free_non_null (other_hello);
2774 find_peer_result = GNUNET_malloc (tsize);
2775 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2776 find_peer_result->size = htons (tsize);
2777 memcpy (&find_peer_result[1], my_hello, hello_size);
2779 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2780 "`%s': Sending hello size %d to requesting peer.\n", "DHT",
2784 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2785 memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2786 new_msg_ctx->peer = &my_identity;
2787 new_msg_ctx->bloom =
2788 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2789 new_msg_ctx->hop_count = 0;
2790 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make find peer requests a higher priority */
2791 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2792 increment_stats (STAT_FIND_PEER_ANSWER);
2793 if (GNUNET_DHT_RO_RECORD_ROUTE ==
2794 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2796 new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2797 new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2798 /* Assign to previous msg_ctx path history, caller should free after our return */
2799 new_msg_ctx->path_history = msg_ctx->path_history;
2801 route_result_message (find_peer_result, new_msg_ctx);
2802 GNUNET_free (new_msg_ctx);
2803 #if DEBUG_DHT_ROUTING
2804 if ((debug_routes) && (dhtlog_handle != NULL))
2806 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2807 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2811 GNUNET_free_non_null (other_hello);
2812 GNUNET_free (find_peer_result);
2813 route_message (find_msg, msg_ctx);
2817 * Task used to republish data.
2818 * Forward declaration; function call loop.
2820 * @param cls closure (a struct RepublishContext)
2821 * @param tc runtime context for this task
2824 republish_content (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2827 * Server handler for initiating local dht put requests
2829 * @param msg the actual put message
2830 * @param msg_ctx struct containing pertinent information about the request
2833 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2834 struct DHT_MessageContext *msg_ctx)
2836 const struct GNUNET_DHT_PutMessage *put_msg;
2837 struct DHTPutEntry *put_entry;
2838 unsigned int put_size;
2840 enum GNUNET_BLOCK_Type put_type;
2843 struct RepublishContext *put_context;
2844 GNUNET_HashCode key;
2846 GNUNET_assert (ntohs (msg->size) >= sizeof (struct GNUNET_DHT_PutMessage));
2848 put_msg = (const struct GNUNET_DHT_PutMessage *) msg;
2849 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2851 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2853 #if DEBUG_DHT_ROUTING
2854 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2856 /** Log routes that die due to high load! */
2857 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2858 msg_ctx->hop_count, GNUNET_SYSERR,
2859 &my_identity, &msg_ctx->key, msg_ctx->peer,
2867 ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2869 GNUNET_BLOCK_get_key (block_context, put_type, &put_msg[1], data_size,
2871 if (GNUNET_NO == ret)
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, msg_ctx->peer,
2883 GNUNET_break_op (0);
2886 if ((GNUNET_YES == ret) &&
2887 (0 != memcmp (&key, &msg_ctx->key, sizeof (GNUNET_HashCode))))
2889 #if DEBUG_DHT_ROUTING
2890 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2892 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2893 msg_ctx->hop_count, GNUNET_SYSERR,
2894 &my_identity, &msg_ctx->key, msg_ctx->peer,
2898 /* invalid wrapper: key mismatch! */
2899 GNUNET_break_op (0);
2902 /* ret == GNUNET_SYSERR means that there is no known relationship between
2903 * data and the key, so we cannot check it */
2905 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2906 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2907 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2908 msg_ctx->unique_id);
2910 #if DEBUG_DHT_ROUTING
2911 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2913 if ((debug_routes) && (dhtlog_handle != NULL))
2915 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2916 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2922 if (msg_ctx->closest != GNUNET_YES)
2924 route_message (msg, msg_ctx);
2929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2930 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2931 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2932 msg_ctx->unique_id);
2935 #if DEBUG_DHT_ROUTING
2936 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2938 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2939 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2940 &msg_ctx->key, msg_ctx->peer, NULL);
2943 if ((debug_routes) && (dhtlog_handle != NULL))
2945 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2946 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2951 increment_stats (STAT_PUTS_INSERTED);
2952 if (datacache != NULL)
2954 /* Put size is actual data size plus struct overhead plus path length (if any) */
2956 data_size + sizeof (struct DHTPutEntry) +
2957 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2958 put_entry = GNUNET_malloc (put_size);
2959 put_entry->data_size = data_size;
2960 put_entry->path_length = msg_ctx->path_history_len;
2961 /* Copy data to end of put entry */
2962 memcpy (&put_entry[1], &put_msg[1], data_size);
2963 if (msg_ctx->path_history_len > 0)
2965 /* Copy path after data */
2966 path_offset = (char *) &put_entry[1];
2967 path_offset += data_size;
2968 memcpy (path_offset, msg_ctx->path_history,
2969 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2973 GNUNET_DATACACHE_put (datacache, &msg_ctx->key, put_size,
2974 (const char *) put_entry, put_type,
2975 GNUNET_TIME_absolute_ntoh (put_msg->expiration));
2976 GNUNET_free (put_entry);
2978 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2980 put_context = GNUNET_malloc (sizeof (struct RepublishContext));
2981 memcpy (&put_context->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
2982 put_context->type = put_type;
2983 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content,
2988 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2989 "`%s:%s': %s request received, but have no datacache!\n",
2990 my_short_id, "DHT", "PUT");
2992 if (stop_on_closest == GNUNET_NO)
2993 route_message (msg, msg_ctx);
2997 * Estimate the diameter of the network based
2998 * on how many buckets are currently in use.
2999 * Concept here is that the diameter of the network
3000 * is roughly the distance a message must travel in
3001 * order to reach its intended destination. Since
3002 * at each hop we expect to get one bit closer, and
3003 * we have one bit per bucket, the number of buckets
3004 * in use should be the largest number of hops for
3005 * a successful message. (of course, this assumes we
3006 * know all peers in the network!)
3008 * @return ballpark diameter figure
3011 estimate_diameter ()
3013 return MAX_BUCKETS - lowest_bucket;
3017 * To how many peers should we (on average)
3018 * forward the request to obtain the desired
3019 * target_replication count (on average).
3021 * returns: target_replication / (est. hops) + (target_replication * hop_count)
3022 * where est. hops is typically 2 * the routing table depth
3024 * @param hop_count number of hops the message has traversed
3025 * @param target_replication the number of total paths desired
3027 * @return Some number of peers to forward the message to
3030 get_forward_count (unsigned int hop_count, size_t target_replication)
3032 uint32_t random_value;
3033 unsigned int forward_count;
3035 unsigned int diameter;
3037 diameter = estimate_diameter ();
3039 if (GNUNET_NO == use_max_hops)
3040 max_hops = (diameter + 1) * 2;
3043 * If we are behaving in strict kademlia mode, send multiple initial requests,
3044 * but then only send to 1 or 0 peers based strictly on the number of hops.
3046 if (strict_kademlia == GNUNET_YES)
3049 return kademlia_replication;
3050 else if (hop_count < max_hops)
3056 /* FIXME: the smaller we think the network is the more lenient we should be for
3057 * routing right? The estimation below only works if we think we have reasonably
3058 * full routing tables, which for our RR topologies may not be the case!
3060 if (hop_count > max_hops)
3063 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3064 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n",
3065 my_short_id, "DHT", estimate_diameter (), lowest_bucket);
3067 /* FIXME: does this work as intended, isn't the decision to forward or not made based on closeness as well? */
3068 if (GNUNET_YES == paper_forwarding) /* Once we have reached our ideal number of hops, don't stop forwarding! */
3076 if (GNUNET_YES == paper_forwarding)
3078 /* FIXME: re-run replication trials with this formula */
3080 1 + (target_replication - 1.0) / (diameter +
3081 ((float) (target_replication - 1.0) *
3083 /* Set forward count to floor of target_value */
3084 forward_count = (unsigned int) target_value;
3085 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
3086 target_value = target_value - forward_count;
3088 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
3090 if (random_value < (target_value * UINT32_MAX))
3098 target_replication / (diameter +
3099 ((float) target_replication * hop_count));
3100 if (target_value > 1)
3102 /* Set forward count to floor of target_value */
3103 forward_count = (unsigned int) target_value;
3104 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
3105 target_value = target_value - forward_count;
3109 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
3111 if (random_value < (target_value * UINT32_MAX))
3115 return forward_count;
3119 * Check whether my identity is closer than any known peers.
3120 * If a non-null bloomfilter is given, check if this is the closest
3121 * peer that hasn't already been routed to.
3123 * @param target hash code to check closeness to
3124 * @param bloom bloomfilter, exclude these entries from the decision
3126 * Return GNUNET_YES if node location is closest, GNUNET_NO
3130 am_closest_peer (const GNUNET_HashCode * target,
3131 struct GNUNET_CONTAINER_BloomFilter *bloom)
3137 struct PeerInfo *pos;
3138 unsigned int my_distance;
3140 if (0 == memcmp (&my_identity.hashPubKey, target, sizeof (GNUNET_HashCode)))
3143 bucket_num = find_current_bucket (target);
3145 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, target);
3146 my_distance = distance (&my_identity.hashPubKey, target);
3147 pos = k_buckets[bucket_num].head;
3149 while ((pos != NULL) && (count < bucket_size))
3151 if ((bloom != NULL) &&
3153 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
3156 continue; /* Skip already checked entries */
3159 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, target);
3160 if (other_bits > bits)
3162 else if (other_bits == bits) /* We match the same number of bits */
3164 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
3166 else if (distance (&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
3172 /* No peers closer, we are the closest! */
3178 * Return this peers adjusted value based on the convergence
3179 * function chosen. This is the key function for randomized
3180 * routing decisions.
3182 * @param target the key of the request
3183 * @param peer the peer we would like the value of
3184 * @param hops number of hops this message has already traveled
3186 * @return bit distance from target to peer raised to an exponent
3187 * adjusted based on the current routing convergence algorithm
3190 static unsigned long long
3191 converge_distance (const GNUNET_HashCode * target, struct PeerInfo *peer,
3194 unsigned long long ret;
3195 unsigned int other_matching_bits;
3196 double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
3197 double temp_modifier;
3203 curr_max_hops = max_hops;
3205 curr_max_hops = (estimate_diameter () + 1) * 2;
3207 if (converge_modifier > 0)
3208 temp_modifier = converge_modifier * base_converge_modifier;
3211 temp_modifier = base_converge_modifier;
3212 base_converge_modifier = 0.0;
3215 GNUNET_assert (temp_modifier > 0);
3217 other_matching_bits =
3218 GNUNET_CRYPTO_hash_matching_bits (target, &peer->id.hashPubKey);
3220 switch (converge_option)
3222 case DHT_CONVERGE_RANDOM:
3223 return 1; /* Always return 1, choose equally among all peers */
3224 case DHT_CONVERGE_LINEAR:
3225 calc_value = hops * curr_max_hops * temp_modifier;
3227 case DHT_CONVERGE_SQUARE:
3229 * Simple square based curve.
3232 (sqrt (hops) / sqrt (curr_max_hops)) * (curr_max_hops /
3236 case DHT_CONVERGE_EXPONENTIAL:
3238 * Simple exponential curve.
3240 if (base_converge_modifier > 0)
3241 calc_value = (temp_modifier * hops * hops) / curr_max_hops;
3243 calc_value = (hops * hops) / curr_max_hops;
3245 case DHT_CONVERGE_BINARY:
3247 * If below the cutoff, route randomly (return 1),
3248 * If above the cutoff, return the maximum possible
3249 * value first (always route to closest, because
3253 if (hops >= converge_modifier) /* Past cutoff */
3262 /* Take the log (base e) of the number of bits matching the other peer */
3263 exponent = log (other_matching_bits);
3265 /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
3266 if (exponent * calc_value >= 44.361419555836498)
3269 /* Clear errno and all math exceptions */
3271 feclearexcept (FE_ALL_EXCEPT);
3272 ret = (unsigned long long) pow (other_matching_bits, calc_value);
3274 fetestexcept (FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW))
3276 if (0 != fetestexcept (FE_OVERFLOW))
3277 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
3278 if (0 != fetestexcept (FE_INVALID))
3279 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
3280 if (0 != fetestexcept (FE_UNDERFLOW))
3281 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
3289 * Comparison function for two struct PeerInfo's
3290 * which have already had their matching bits to
3291 * some target calculated.
3293 * @param p1 a pointer pointer to a struct PeerInfo
3294 * @param p2 a pointer pointer to a struct PeerInfo
3296 * @return 0 if equidistant to target,
3297 * -1 if p1 is closer,
3301 compare_peers (const void *p1, const void *p2)
3303 struct PeerInfo **first = (struct PeerInfo **) p1;
3304 struct PeerInfo **second = (struct PeerInfo **) p2;
3306 if ((*first)->matching_bits > (*second)->matching_bits)
3308 if ((*first)->matching_bits < (*second)->matching_bits)
3316 * Select a peer from the routing table that would be a good routing
3317 * destination for sending a message for "target". The resulting peer
3318 * must not be in the set of blocked peers.<p>
3320 * Note that we should not ALWAYS select the closest peer to the
3321 * target, peers further away from the target should be chosen with
3322 * exponentially declining probability.
3324 * @param target the key we are selecting a peer to route to
3325 * @param bloom a bloomfilter containing entries this request has seen already
3326 * @param hops how many hops has this message traversed thus far
3328 * @return Peer to route to, or NULL on error
3330 static struct PeerInfo *
3331 select_peer (const GNUNET_HashCode * target,
3332 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3337 unsigned int offset;
3339 struct PeerInfo *pos;
3340 struct PeerInfo *sorted_closest[bucket_size];
3341 unsigned long long temp_converge_distance;
3342 unsigned long long total_distance;
3343 unsigned long long selected;
3346 unsigned long long stats_total_distance;
3350 unsigned int distance;
3351 unsigned int largest_distance;
3352 struct PeerInfo *chosen;
3355 /** If we are doing kademlia routing, or converge is binary (saves some cycles) */
3356 if ((strict_kademlia == GNUNET_YES) ||
3357 ((converge_option == DHT_CONVERGE_BINARY) && (hops >= converge_modifier)))
3359 largest_distance = 0;
3361 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3363 pos = k_buckets[bc].head;
3365 while ((pos != NULL) && (count < bucket_size))
3367 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3369 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3371 distance = inverse_distance (target, &pos->id.hashPubKey);
3372 if (distance > largest_distance)
3375 largest_distance = distance;
3383 if ((largest_distance > 0) && (chosen != NULL))
3385 GNUNET_CONTAINER_bloomfilter_add (bloom, &chosen->id.hashPubKey);
3396 /* Three steps: order peers in closest bucket (most matching bits).
3397 * Then go over all LOWER buckets (matching same bits we do)
3398 * Then go over all HIGHER buckets (matching less then we do)
3401 closest_bucket = find_current_bucket (target);
3402 GNUNET_assert (closest_bucket >= lowest_bucket);
3403 pos = k_buckets[closest_bucket].head;
3405 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3406 memset (sorted_closest, 0, sizeof (sorted_closest));
3407 /* Put any peers in the closest bucket in the sorting array */
3408 while ((pos != NULL) && (count < bucket_size))
3411 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3415 continue; /* Ignore bloomfiltered peers */
3417 pos->matching_bits =
3418 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, target);
3419 sorted_closest[offset] = pos;
3425 /* Sort the peers in descending order */
3426 qsort (&sorted_closest[0], offset, sizeof (struct PeerInfo *),
3429 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3430 for (i = 0; i < offset; i++)
3432 temp_converge_distance =
3433 converge_distance (target, sorted_closest[i], hops);
3435 GNUNET_CONTAINER_bloomfilter_test (bloom,
3436 &sorted_closest[i]->id.hashPubKey))
3437 break; /* Ignore bloomfiltered peers */
3438 if (total_distance + temp_converge_distance > total_distance) /* Handle largest case and overflow */
3439 total_distance += temp_converge_distance;
3441 break; /* overflow case */
3444 /* Now handle peers in lower buckets (matches same # of bits as target) */
3445 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3447 pos = k_buckets[bc].head;
3449 while ((pos != NULL) && (count < bucket_size))
3452 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3456 continue; /* Ignore bloomfiltered peers */
3458 temp_converge_distance = converge_distance (target, pos, hops);
3459 if (total_distance + temp_converge_distance > total_distance) /* Handle largest case and overflow */
3460 total_distance += temp_converge_distance;
3462 break; /* overflow case */
3468 /* Now handle all the further away peers */
3469 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3471 pos = k_buckets[bc].head;
3473 while ((pos != NULL) && (count < bucket_size))
3476 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3480 continue; /* Ignore bloomfiltered peers */
3482 temp_converge_distance = converge_distance (target, pos, hops);
3483 if (total_distance + temp_converge_distance > total_distance) /* Handle largest case and overflow */
3484 total_distance += temp_converge_distance;
3486 break; /* overflow case */
3492 if (total_distance == 0) /* No peers to select from! */
3494 increment_stats ("# failed to select peer");
3498 #if DEBUG_DHT_ROUTING > 1
3501 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3502 stats_total_distance = 0;
3503 for (i = 0; i < offset; i++)
3506 GNUNET_CONTAINER_bloomfilter_test (bloom,
3507 &sorted_closest[i]->id.hashPubKey))
3508 break; /* Ignore bloomfiltered peers */
3509 temp_converge_distance =
3510 converge_distance (target, sorted_closest[i], hops);
3511 if (stats_total_distance + temp_converge_distance > stats_total_distance) /* Handle largest case and overflow */
3512 stats_total_distance += temp_converge_distance;
3514 break; /* overflow case */
3515 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3516 "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n",
3517 GNUNET_CRYPTO_hash_matching_bits (&sorted_closest[i]->id.
3518 hashPubKey, target),
3519 GNUNET_CRYPTO_hash_matching_bits (&sorted_closest[i]->id.
3521 &my_identity.hashPubKey),
3522 (temp_converge_distance / (double) total_distance) * 100,
3523 temp_converge_distance);
3526 /* Now handle peers in lower buckets (matches same # of bits as target) */
3527 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3529 pos = k_buckets[bc].head;
3531 while ((pos != NULL) && (count < bucket_size))
3534 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3538 continue; /* Ignore bloomfiltered peers */
3540 temp_converge_distance = converge_distance (target, pos, hops);
3541 if (stats_total_distance + temp_converge_distance > stats_total_distance) /* Handle largest case and overflow */
3542 stats_total_distance += temp_converge_distance;
3544 break; /* overflow case */
3545 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3546 "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n",
3547 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
3549 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
3550 &my_identity.hashPubKey),
3551 (temp_converge_distance / (double) total_distance) * 100,
3552 temp_converge_distance);
3558 /* Now handle all the further away peers */
3559 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3561 pos = k_buckets[bc].head;
3563 while ((pos != NULL) && (count < bucket_size))
3566 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3570 continue; /* Ignore bloomfiltered peers */
3572 temp_converge_distance = converge_distance (target, pos, hops);
3573 if (stats_total_distance + temp_converge_distance > stats_total_distance) /* Handle largest case and overflow */
3574 stats_total_distance += temp_converge_distance;
3576 break; /* overflow case */
3577 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3578 "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n",
3579 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
3581 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
3582 &my_identity.hashPubKey),
3583 (temp_converge_distance / (double) total_distance) * 100,
3584 temp_converge_distance);
3589 /* END PRINT STATS */
3592 /* Now actually choose a peer */
3594 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3596 /* Go over closest sorted peers. */
3597 for (i = 0; i < offset; i++)
3600 GNUNET_CONTAINER_bloomfilter_test (bloom,
3601 &sorted_closest[i]->id.hashPubKey))
3602 break; /* Ignore bloomfiltered peers */
3603 temp_converge_distance =
3604 converge_distance (target, sorted_closest[i], hops);
3605 if (temp_converge_distance >= selected)
3606 return sorted_closest[i];
3608 selected -= temp_converge_distance;
3611 /* Now handle peers in lower buckets (matches same # of bits as target) */
3612 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3614 pos = k_buckets[bc].head;
3616 while ((pos != NULL) && (count < bucket_size))
3619 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3623 continue; /* Ignore bloomfiltered peers */
3625 temp_converge_distance = converge_distance (target, pos, hops);
3626 if (temp_converge_distance >= selected)
3629 selected -= temp_converge_distance;
3635 /* Now handle all the further away peers */
3636 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3638 pos = k_buckets[bc].head;
3640 while ((pos != NULL) && (count < bucket_size))
3643 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3647 continue; /* Ignore bloomfiltered peers */
3649 temp_converge_distance = converge_distance (target, pos, hops);
3650 if (temp_converge_distance >= selected)
3653 selected -= temp_converge_distance;
3659 increment_stats ("# failed to select peer");
3665 * Task used to remove recent entries, either
3666 * after timeout, when full, or on shutdown.
3668 * @param cls the entry to remove
3669 * @param tc context, reason, etc.
3672 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3674 struct RecentRequest *req = cls;
3675 static GNUNET_HashCode hash;
3677 GNUNET_assert (req != NULL);
3678 hash_from_uid (req->uid, &hash);
3679 GNUNET_assert (GNUNET_YES ==
3680 GNUNET_CONTAINER_multihashmap_remove (recent.hashmap, &hash,
3682 GNUNET_CONTAINER_heap_remove_node (req->heap_node);
3683 GNUNET_CONTAINER_bloomfilter_free (req->bloom);
3687 * if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3689 * GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3690 * GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3696 * Remember this routing request so that if a reply is
3697 * received we can either forward it to the correct peer
3698 * or return the result locally.
3700 * @param msg_ctx Context of the route request
3702 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3705 cache_response (struct DHT_MessageContext *msg_ctx)
3707 struct DHTQueryRecord *record;
3708 struct DHTRouteSource *source_info;
3709 struct DHTRouteSource *pos;
3710 struct GNUNET_TIME_Absolute now;
3711 unsigned int current_size;
3713 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3715 #if DELETE_WHEN_FULL
3716 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3718 source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3719 GNUNET_assert (source_info != NULL);
3720 record = source_info->record;
3721 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3722 if (record->head == NULL) /* No more entries in DLL */
3724 GNUNET_assert (GNUNET_YES ==
3725 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
3728 GNUNET_free (record);
3730 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3732 GNUNET_SCHEDULER_cancel (source_info->delete_task);
3733 source_info->delete_task = GNUNET_SCHEDULER_NO_TASK;
3735 if (source_info->find_peers_responded != NULL)
3736 GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
3737 GNUNET_free (source_info);
3738 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3741 /** Non-local request and have too many outstanding forwards, discard! */
3742 if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3745 now = GNUNET_TIME_absolute_get ();
3747 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
3748 if (record != NULL) /* Already know this request! */
3754 memcmp (msg_ctx->peer, &pos->source,
3755 sizeof (struct GNUNET_PeerIdentity)))
3756 break; /* Already have this peer in reply list! */
3759 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3761 GNUNET_CONTAINER_heap_update_cost (forward_list.minHeap, pos->hnode,
3768 record = GNUNET_malloc (sizeof (struct DHTQueryRecord));
3769 GNUNET_assert (GNUNET_OK ==
3770 GNUNET_CONTAINER_multihashmap_put (forward_list.hashmap,
3771 &msg_ctx->key, record,
3772 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3773 memcpy (&record->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3776 source_info = GNUNET_malloc (sizeof (struct DHTRouteSource));
3777 source_info->record = record;
3778 source_info->delete_task =
3779 GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry,
3781 source_info->find_peers_responded =
3782 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3783 memcpy (&source_info->source, msg_ctx->peer,
3784 sizeof (struct GNUNET_PeerIdentity));
3785 GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail,
3787 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3789 source_info->client = msg_ctx->client;
3790 now = GNUNET_TIME_absolute_get_forever ();
3792 source_info->hnode =
3793 GNUNET_CONTAINER_heap_insert (forward_list.minHeap, source_info,
3796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3797 "`%s:%s': Created new forward source info for %s uid %llu\n",
3798 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3799 msg_ctx->unique_id);
3806 * Main function that handles whether or not to route a message to other
3809 * @param msg the message to be routed
3810 * @param msg_ctx the context containing all pertinent information about the message
3813 route_message (const struct GNUNET_MessageHeader *msg,
3814 struct DHT_MessageContext *msg_ctx)
3817 struct PeerInfo *selected;
3819 #if DEBUG_DHT_ROUTING > 1
3820 struct PeerInfo *nearest;
3822 unsigned int target_forward_count;
3823 unsigned int forward_count;
3824 struct RecentRequest *recent_req;
3825 GNUNET_HashCode unique_hash;
3826 char *stat_forward_count;
3827 char *temp_stat_str;
3829 #if DEBUG_DHT_ROUTING
3833 if (malicious_dropper == GNUNET_YES)
3835 #if DEBUG_DHT_ROUTING
3836 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3838 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3839 msg_ctx->hop_count, GNUNET_SYSERR,
3840 &my_identity, &msg_ctx->key, msg_ctx->peer,
3844 if (msg_ctx->bloom != NULL)
3846 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3847 msg_ctx->bloom = NULL;
3852 increment_stats (STAT_ROUTES);
3853 target_forward_count =
3854 get_forward_count (msg_ctx->hop_count, msg_ctx->replication);
3855 GNUNET_asprintf (&stat_forward_count, "# forward counts of %d",
3856 target_forward_count);
3857 increment_stats (stat_forward_count);
3858 GNUNET_free (stat_forward_count);
3859 if (msg_ctx->bloom == NULL)
3861 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3863 if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) &&
3864 (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3865 target_forward_count = 0;
3868 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3869 * any closer peers (which is being checked for below). Since we are doing recursive
3870 * routing we have no choice but to stop forwarding in this case. This means that at
3871 * any given step the request may NOT be forwarded to alpha peers (because routes will
3872 * stop and the parallel route will not be aware of it). Of course, assuming that we
3873 * have fulfilled the Kademlia requirements for routing table fullness this will never
3874 * ever ever be a problem.
3876 * However, is this fair?
3878 * Since we use these requests to build our routing tables (and we build them in the
3879 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3880 * routing tables still get constructed.
3882 if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) &&
3883 (msg_ctx->hop_count > 0) &&
3884 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3885 target_forward_count = 0;
3888 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3889 hash_from_uid (msg_ctx->unique_id, &unique_hash);
3891 GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3894 GNUNET_CONTAINER_multihashmap_get (recent.hashmap, &unique_hash);
3895 GNUNET_assert (recent_req != NULL);
3896 if (0 != memcmp (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode)))
3897 increment_stats (STAT_DUPLICATE_UID);
3900 increment_stats (STAT_RECENT_SEEN);
3901 GNUNET_CONTAINER_bloomfilter_or2 (msg_ctx->bloom, recent_req->bloom,
3907 recent_req = GNUNET_malloc (sizeof (struct RecentRequest));
3908 recent_req->uid = msg_ctx->unique_id;
3909 memcpy (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3910 recent_req->remove_task =
3911 GNUNET_SCHEDULER_add_delayed (DEFAULT_RECENT_REMOVAL, &remove_recent,
3913 recent_req->heap_node =
3914 GNUNET_CONTAINER_heap_insert (recent.minHeap, recent_req,
3915 GNUNET_TIME_absolute_get ().abs_value);
3917 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3918 GNUNET_CONTAINER_multihashmap_put (recent.hashmap, &unique_hash, recent_req,
3919 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3922 if (GNUNET_CONTAINER_multihashmap_size (recent.hashmap) > DHT_MAX_RECENT)
3924 recent_req = GNUNET_CONTAINER_heap_peek (recent.minHeap);
3925 GNUNET_assert (recent_req != NULL);
3926 GNUNET_SCHEDULER_cancel (recent_req->remove_task);
3927 GNUNET_SCHEDULER_add_now (&remove_recent, recent_req);
3931 for (i = 0; i < target_forward_count; i++)
3933 selected = select_peer (&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3935 if (selected != NULL)
3938 if (GNUNET_CRYPTO_hash_matching_bits
3939 (&selected->id.hashPubKey,
3941 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
3943 GNUNET_asprintf (&temp_stat_str,
3944 "# requests routed to close(r) peer hop %u",
3945 msg_ctx->hop_count);
3947 GNUNET_asprintf (&temp_stat_str,
3948 "# requests routed to less close peer hop %u",
3949 msg_ctx->hop_count);
3950 if (temp_stat_str != NULL)
3952 increment_stats (temp_stat_str);
3953 GNUNET_free (temp_stat_str);
3955 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
3956 &selected->id.hashPubKey);
3957 #if DEBUG_DHT_ROUTING > 1
3958 nearest = find_closest_peer (&msg_ctx->key);
3959 nearest_buf = GNUNET_strdup (GNUNET_i2s (&nearest->id));
3960 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3961 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n",
3962 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3963 msg_ctx->unique_id, GNUNET_i2s (&selected->id), nearest_buf,
3964 GNUNET_CRYPTO_hash_matching_bits (&nearest->id.hashPubKey,
3966 distance (&nearest->id.hashPubKey, msg_ctx->key));
3967 GNUNET_free (nearest_buf);
3969 #if DEBUG_DHT_ROUTING
3970 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3972 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3973 msg_ctx->hop_count, GNUNET_NO,
3974 &my_identity, &msg_ctx->key, msg_ctx->peer,
3978 forward_message (msg, selected, msg_ctx);
3982 if (msg_ctx->bloom != NULL)
3984 GNUNET_CONTAINER_bloomfilter_or2 (recent_req->bloom, msg_ctx->bloom,
3986 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3987 msg_ctx->bloom = NULL;
3990 #if DEBUG_DHT_ROUTING
3991 if (forward_count == 0)
3992 ret = GNUNET_SYSERR;
3996 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3998 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3999 msg_ctx->hop_count, ret, &my_identity,
4000 &msg_ctx->key, msg_ctx->peer, NULL);
4008 * Main function that handles whether or not to route a message to other
4011 * @param msg the message to be routed
4012 * @param msg_ctx the context containing all pertinent information about the message
4015 demultiplex_message (const struct GNUNET_MessageHeader *msg,
4016 struct DHT_MessageContext *msg_ctx)
4018 /* FIXME: Should we use closest excluding those we won't route to (the bloomfilter problem)? */
4019 msg_ctx->closest = am_closest_peer (&msg_ctx->key, msg_ctx->bloom);
4021 switch (ntohs (msg->type))
4023 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
4024 cache_response (msg_ctx);
4025 handle_dht_get (msg, msg_ctx);
4027 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
4028 increment_stats (STAT_PUTS);
4029 handle_dht_put (msg, msg_ctx);
4031 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
4032 increment_stats (STAT_FIND_PEER);
4033 if (((msg_ctx->hop_count > 0) &&
4035 memcmp (msg_ctx->peer, &my_identity,
4036 sizeof (struct GNUNET_PeerIdentity)))) ||
4037 (msg_ctx->client != NULL))
4039 cache_response (msg_ctx);
4040 if ((msg_ctx->closest == GNUNET_YES) ||
4041 (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
4042 handle_dht_find_peer (msg, msg_ctx);
4045 route_message (msg, msg_ctx);
4046 #if DEBUG_DHT_ROUTING
4047 if (msg_ctx->hop_count == 0) /* Locally initiated request */
4049 if ((debug_routes) && (dhtlog_handle != NULL))
4051 dhtlog_handle->insert_dhtkey (NULL, &msg_ctx->key);
4052 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
4053 msg_ctx->hop_count, GNUNET_NO,
4054 &my_identity, &msg_ctx->key);
4060 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4061 "`%s': Message type (%d) not handled, forwarding anyway!\n",
4062 "DHT", ntohs (msg->type));
4063 route_message (msg, msg_ctx);
4071 * Iterator for local get request results,
4073 * @param cls closure for iterator, NULL
4074 * @param exp when does this value expire?
4075 * @param key the key this data is stored under
4076 * @param size the size of the data identified by key
4077 * @param data the actual data
4078 * @param type the type of the data
4080 * @return GNUNET_OK to continue iteration, anything else
4081 * to stop iteration.
4084 republish_content_iterator (void *cls, struct GNUNET_TIME_Absolute exp,
4085 const GNUNET_HashCode * key, size_t size,
4086 const char *data, uint32_t type)
4089 struct DHT_MessageContext *new_msg_ctx;
4090 struct GNUNET_DHT_PutMessage *put_msg;
4093 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4094 "`%s:%s': Received `%s' response from datacache\n", my_short_id,
4097 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
4099 put_msg = GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
4100 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
4101 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
4102 put_msg->expiration = GNUNET_TIME_absolute_hton (exp);
4103 put_msg->type = htons (type);
4104 memcpy (&put_msg[1], data, size);
4105 new_msg_ctx->unique_id =
4106 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
4107 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
4108 new_msg_ctx->replication = ntohl (DEFAULT_PUT_REPLICATION);
4109 new_msg_ctx->msg_options = ntohl (0);
4110 new_msg_ctx->network_size = estimate_diameter ();
4111 new_msg_ctx->peer = &my_identity;
4112 new_msg_ctx->bloom =
4113 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4114 new_msg_ctx->hop_count = 0;
4115 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4116 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4117 increment_stats (STAT_PUT_START);
4118 demultiplex_message (&put_msg->header, new_msg_ctx);
4120 GNUNET_free (new_msg_ctx);
4121 GNUNET_free (put_msg);
4126 * Task used to republish data.
4128 * @param cls closure (a struct RepublishContext)
4129 * @param tc runtime context for this task
4132 republish_content (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4134 struct RepublishContext *put_context = cls;
4136 unsigned int results;
4138 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4140 GNUNET_free (put_context);
4144 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
4146 GNUNET_DATACACHE_get (datacache, &put_context->key, put_context->type,
4147 &republish_content_iterator, NULL);
4148 if (results == 0) /* Data must have expired */
4149 GNUNET_free (put_context);
4150 else /* Reschedule task for next time period */
4151 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content,
4158 * Iterator over hash map entries.
4160 * @param cls client to search for in source routes
4161 * @param key current key code (ignored)
4162 * @param value value in the hash map, a DHTQueryRecord
4163 * @return GNUNET_YES if we should continue to
4168 find_client_records (void *cls, const GNUNET_HashCode * key, void *value)
4170 struct ClientList *client = cls;
4171 struct DHTQueryRecord *record = value;
4172 struct DHTRouteSource *pos;
4177 if (pos->client == client)
4183 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, pos);
4184 GNUNET_CONTAINER_heap_remove_node (pos->hnode);
4185 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
4187 GNUNET_SCHEDULER_cancel (pos->delete_task);
4188 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4190 if (pos->find_peers_responded != NULL)
4191 GNUNET_CONTAINER_bloomfilter_free (pos->find_peers_responded);
4194 if (record->head == NULL) /* No more entries in DLL */
4196 GNUNET_assert (GNUNET_YES ==
4197 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
4198 &record->key, record));
4199 GNUNET_free (record);
4205 * Functions with this signature are called whenever a client
4206 * is disconnected on the network level.
4208 * @param cls closure (NULL for dht)
4209 * @param client identification of the client; NULL
4210 * for the last call when the server is destroyed
4213 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4215 struct ClientList *pos = client_list;
4216 struct ClientList *prev;
4217 struct ClientList *found;
4218 struct PendingMessage *reply;
4224 if (pos->client_handle == client)
4227 prev->next = pos->next;
4229 client_list = pos->next;
4239 if (found->transmit_handle != NULL)
4240 GNUNET_CONNECTION_notify_transmit_ready_cancel (found->transmit_handle);
4242 while (NULL != (reply = found->pending_head))
4244 GNUNET_CONTAINER_DLL_remove (found->pending_head, found->pending_tail,
4246 GNUNET_free (reply);
4248 GNUNET_CONTAINER_multihashmap_iterate (forward_list.hashmap,
4249 &find_client_records, found);
4250 GNUNET_free (found);
4255 * Find a client if it exists, add it otherwise.
4257 * @param client the server handle to the client
4259 * @return the client if found, a new client otherwise
4261 static struct ClientList *
4262 find_active_client (struct GNUNET_SERVER_Client *client)
4264 struct ClientList *pos = client_list;
4265 struct ClientList *ret;
4269 if (pos->client_handle == client)
4274 ret = GNUNET_malloc (sizeof (struct ClientList));
4275 ret->client_handle = client;
4276 ret->next = client_list;
4284 * Task to send a malicious put message across the network.
4286 * @param cls closure for this task
4287 * @param tc the context under which the task is running
4290 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4292 static struct GNUNET_DHT_PutMessage put_message;
4293 static struct DHT_MessageContext msg_ctx;
4294 static GNUNET_HashCode key;
4295 uint32_t random_key;
4297 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4299 put_message.header.size = htons (sizeof (struct GNUNET_DHT_PutMessage));
4300 put_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
4301 put_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
4302 put_message.expiration =
4303 GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_forever ());
4304 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4306 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
4307 GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
4308 memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
4310 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
4311 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
4312 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
4313 msg_ctx.msg_options = ntohl (0);
4314 msg_ctx.network_size = estimate_diameter ();
4315 msg_ctx.peer = &my_identity;
4316 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
4317 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4318 #if DEBUG_DHT_ROUTING
4319 if (dhtlog_handle != NULL)
4320 dhtlog_handle->insert_dhtkey (NULL, &key);
4322 increment_stats (STAT_PUT_START);
4323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4324 "%s:%s Sending malicious PUT message with hash %s\n", my_short_id,
4325 "DHT", GNUNET_h2s (&key));
4326 demultiplex_message (&put_message.header, &msg_ctx);
4327 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4328 (GNUNET_TIME_UNIT_MILLISECONDS,
4329 malicious_put_frequency), &malicious_put_task,
4335 * Task to send a malicious put message across the network.
4337 * @param cls closure for this task
4338 * @param tc the context under which the task is running
4341 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4343 static struct GNUNET_DHT_GetMessage get_message;
4344 struct DHT_MessageContext msg_ctx;
4345 static GNUNET_HashCode key;
4346 uint32_t random_key;
4348 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4351 get_message.header.size = htons (sizeof (struct GNUNET_DHT_GetMessage));
4352 get_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET);
4353 get_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
4354 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4356 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
4357 GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
4358 memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
4360 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
4361 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
4362 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
4363 msg_ctx.msg_options = ntohl (0);
4364 msg_ctx.network_size = estimate_diameter ();
4365 msg_ctx.peer = &my_identity;
4366 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
4367 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4368 #if DEBUG_DHT_ROUTING
4369 if (dhtlog_handle != NULL)
4370 dhtlog_handle->insert_dhtkey (NULL, &key);
4372 increment_stats (STAT_GET_START);
4373 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4374 "%s:%s Sending malicious GET message with hash %s\n", my_short_id,
4375 "DHT", GNUNET_h2s (&key));
4376 demultiplex_message (&get_message.header, &msg_ctx);
4377 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4378 (GNUNET_TIME_UNIT_MILLISECONDS,
4379 malicious_get_frequency), &malicious_get_task,
4386 * Iterator over hash map entries.
4388 * @param cls closure
4389 * @param key current key code
4390 * @param value value in the hash map
4391 * @return GNUNET_YES if we should continue to
4396 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
4398 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
4400 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
4405 * Task to send a find peer message for our own peer identifier
4406 * so that we can find the closest peers in the network to ourselves
4407 * and attempt to connect to them.
4409 * @param cls closure for this task
4410 * @param tc the context under which the task is running
4413 send_find_peer_message (void *cls,
4414 const struct GNUNET_SCHEDULER_TaskContext *tc)
4416 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
4417 struct DHT_MessageContext msg_ctx;
4418 struct GNUNET_TIME_Relative next_send_time;
4419 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
4422 struct GNUNET_TIME_Relative time_diff;
4423 struct GNUNET_TIME_Absolute end;
4425 double count_per_interval;
4427 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4430 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! */
4432 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4433 "Have %d newly found peers since last find peer message sent!\n",
4435 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
4436 &send_find_peer_message, NULL);
4437 newly_found_peers = 0;
4441 increment_stats (STAT_FIND_PEER_START);
4443 end = GNUNET_TIME_absolute_get ();
4445 GNUNET_TIME_absolute_get_difference (find_peer_context.start, end);
4447 if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
4449 multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
4450 count_per_interval = find_peer_context.count / multiplier;
4454 multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
4455 count_per_interval = find_peer_context.count * multiplier;
4459 #if FIND_PEER_WITH_HELLO
4461 GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage) +
4462 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *)
4464 find_peer_msg->header.size =
4465 htons (sizeof (struct GNUNET_DHT_FindPeerMessage) +
4466 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
4467 memcpy (&find_peer_msg[1], my_hello,
4468 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
4470 find_peer_msg = GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage));
4471 find_peer_msg->header.size =
4472 htons (sizeof (struct GNUNET_DHT_FindPeerMessage));
4474 find_peer_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4476 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4477 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
4479 GNUNET_assert (GNUNET_OK ==
4480 GNUNET_CONTAINER_bloomfilter_get_raw_data (temp_bloom,
4484 GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
4485 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4486 memcpy (&msg_ctx.key, &my_identity.hashPubKey, sizeof (GNUNET_HashCode));
4488 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
4489 (GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX));
4490 msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4491 msg_ctx.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4492 msg_ctx.network_size = estimate_diameter ();
4493 msg_ctx.peer = &my_identity;
4494 msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4495 msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4497 demultiplex_message (&find_peer_msg->header, &msg_ctx);
4498 GNUNET_free (find_peer_msg);
4499 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4500 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id,
4501 "DHT", "FIND PEER");
4502 if (newly_found_peers < bucket_size)
4504 next_send_time.rel_value =
4505 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4506 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
4507 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4511 next_send_time.rel_value =
4512 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4513 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
4514 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value -
4515 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4518 GNUNET_assert (next_send_time.rel_value != 0);
4519 find_peer_context.count = 0;
4520 newly_found_peers = 0;
4521 find_peer_context.start = GNUNET_TIME_absolute_get ();
4522 if (GNUNET_YES == do_find_peer)
4524 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
4530 * Handler for any generic DHT messages, calls the appropriate handler
4531 * depending on message type, sends confirmation if responses aren't otherwise
4534 * @param cls closure for the service
4535 * @param client the client we received this message from
4536 * @param message the actual message received
4539 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4540 const struct GNUNET_MessageHeader *message)
4542 const struct GNUNET_DHT_RouteMessage *dht_msg =
4543 (const struct GNUNET_DHT_RouteMessage *) message;
4544 const struct GNUNET_MessageHeader *enc_msg;
4545 struct DHT_MessageContext msg_ctx;
4547 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4549 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4550 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4551 my_short_id, "DHT", "GENERIC", ntohs (message->type),
4552 GNUNET_h2s (&dht_msg->key), GNUNET_ntohll (dht_msg->unique_id));
4554 #if DEBUG_DHT_ROUTING
4555 if (dhtlog_handle != NULL)
4556 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4559 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4560 msg_ctx.client = find_active_client (client);
4561 memcpy (&msg_ctx.key, &dht_msg->key, sizeof (GNUNET_HashCode));
4562 msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4563 msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
4564 msg_ctx.msg_options = ntohl (dht_msg->options);
4565 if (GNUNET_DHT_RO_RECORD_ROUTE ==
4566 (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
4568 msg_ctx.path_history = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
4569 memcpy (msg_ctx.path_history, &my_identity,
4570 sizeof (struct GNUNET_PeerIdentity));
4571 msg_ctx.path_history_len = 1;
4573 msg_ctx.network_size = estimate_diameter ();
4574 msg_ctx.peer = &my_identity;
4575 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
4576 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4578 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4579 increment_stats (STAT_GET_START);
4580 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4581 increment_stats (STAT_PUT_START);
4582 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4583 increment_stats (STAT_FIND_PEER_START);
4585 if (GNUNET_YES == malicious_dropper)
4587 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4589 #if DEBUG_DHT_ROUTING
4590 if ((debug_routes) && (dhtlog_handle != NULL))
4592 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_GET,
4593 msg_ctx.hop_count, GNUNET_NO, &my_identity,
4598 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4600 #if DEBUG_DHT_ROUTING
4601 if ((debug_routes) && (dhtlog_handle != NULL))
4603 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_PUT,
4604 msg_ctx.hop_count, GNUNET_NO, &my_identity,
4609 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4610 GNUNET_free_non_null (msg_ctx.path_history);
4614 demultiplex_message (enc_msg, &msg_ctx);
4615 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4620 * Handler for any locally received DHT control messages,
4621 * sets malicious flags mostly for now.
4623 * @param cls closure for the service
4624 * @param client the client we received this message from
4625 * @param message the actual message received
4629 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4630 const struct GNUNET_MessageHeader *message)
4632 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4633 (const struct GNUNET_DHT_ControlMessage *) message;
4636 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4637 "`%s:%s': Received `%s' request from client, command %d\n",
4638 my_short_id, "DHT", "CONTROL", ntohs (dht_control_msg->command));
4641 switch (ntohs (dht_control_msg->command))
4643 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4644 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4645 "Sending self seeking find peer request!\n");
4646 GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
4649 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4650 if (ntohs (dht_control_msg->variable) > 0)
4651 malicious_get_frequency = ntohs (dht_control_msg->variable);
4652 if (malicious_get_frequency == 0)
4653 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4654 if (malicious_getter != GNUNET_YES)
4655 GNUNET_SCHEDULER_add_now (&malicious_get_task, NULL);
4656 malicious_getter = GNUNET_YES;
4657 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4658 "%s:%s Initiating malicious GET behavior, frequency %d\n",
4659 my_short_id, "DHT", malicious_get_frequency);
4661 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4662 if (ntohs (dht_control_msg->variable) > 0)
4663 malicious_put_frequency = ntohs (dht_control_msg->variable);
4664 if (malicious_put_frequency == 0)
4665 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4666 if (malicious_putter != GNUNET_YES)
4667 GNUNET_SCHEDULER_add_now (&malicious_put_task, NULL);
4668 malicious_putter = GNUNET_YES;
4669 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4670 "%s:%s Initiating malicious PUT behavior, frequency %d\n",
4671 my_short_id, "DHT", malicious_put_frequency);
4673 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4674 #if DEBUG_DHT_ROUTING
4675 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4676 dhtlog_handle->set_malicious (&my_identity);
4678 malicious_dropper = GNUNET_YES;
4679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4680 "%s:%s Initiating malicious DROP behavior\n", my_short_id,
4685 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4686 "%s:%s Unknown control command type `%d'!\n", my_short_id,
4687 "DHT", ntohs (dht_control_msg->command));
4691 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4695 * Handler for any generic DHT stop messages, calls the appropriate handler
4696 * depending on message type (if processed locally)
4698 * @param cls closure for the service
4699 * @param client the client we received this message from
4700 * @param message the actual message received
4704 handle_dht_local_route_stop (void *cls, struct GNUNET_SERVER_Client *client,
4705 const struct GNUNET_MessageHeader *message)
4708 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4709 (const struct GNUNET_DHT_StopMessage *) message;
4710 struct DHTQueryRecord *record;
4711 struct DHTRouteSource *pos;
4714 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4715 "`%s:%s': Received `%s' request from client, uid %llu\n",
4716 my_short_id, "DHT", "GENERIC STOP",
4717 GNUNET_ntohll (dht_stop_msg->unique_id));
4720 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap,
4721 &dht_stop_msg->key);
4728 /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
4729 if ((pos->client != NULL) && (pos->client->client_handle == client))
4731 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
4732 GNUNET_SCHEDULER_cancel (pos->delete_task);
4734 GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
4740 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4745 * Core handler for p2p route requests.
4747 * @param cls closure
4748 * @param message message
4749 * @param peer peer identity this notification is about
4750 * @param atsi performance data
4754 handle_dht_p2p_route_request (void *cls, const struct GNUNET_PeerIdentity *peer,
4755 const struct GNUNET_MessageHeader *message,
4756 const struct GNUNET_TRANSPORT_ATS_Information
4760 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4761 "`%s:%s': Received P2P request from peer %s\n", my_short_id,
4762 "DHT", GNUNET_i2s (peer));
4764 struct GNUNET_DHT_P2PRouteMessage *incoming =
4765 (struct GNUNET_DHT_P2PRouteMessage *) message;
4766 struct GNUNET_MessageHeader *enc_msg =
4767 (struct GNUNET_MessageHeader *) &incoming[1];
4768 struct DHT_MessageContext *msg_ctx;
4772 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply) */
4775 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n",
4776 my_short_id, "DHT");
4781 if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4783 GNUNET_break_op (0);
4787 if (malicious_dropper == GNUNET_YES)
4789 #if DEBUG_DHT_ROUTING
4790 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4792 /** Log routes that die due to high load! */
4793 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4794 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4795 GNUNET_SYSERR, &my_identity, &incoming->key,
4802 if (get_max_send_delay ().rel_value > MAX_REQUEST_TIME.rel_value)
4804 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4805 "Sending of previous replies took too long, backing off!\n");
4806 increment_stats ("# route requests dropped due to high load");
4807 decrease_max_send_delay (get_max_send_delay ());
4808 #if DEBUG_DHT_ROUTING
4809 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4811 /** Log routes that die due to high load! */
4812 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4813 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4814 GNUNET_SYSERR, &my_identity, &incoming->key,
4820 msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
4822 GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4824 GNUNET_assert (msg_ctx->bloom != NULL);
4825 msg_ctx->hop_count = ntohl (incoming->hop_count);
4826 memcpy (&msg_ctx->key, &incoming->key, sizeof (GNUNET_HashCode));
4827 msg_ctx->replication = ntohl (incoming->desired_replication_level);
4828 msg_ctx->unique_id = GNUNET_ntohll (incoming->unique_id);
4829 msg_ctx->msg_options = ntohl (incoming->options);
4830 if (GNUNET_DHT_RO_RECORD_ROUTE ==
4831 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
4834 ntohl (incoming->outgoing_path_length) *
4835 sizeof (struct GNUNET_PeerIdentity);
4836 GNUNET_assert (ntohs (message->size) ==
4837 (sizeof (struct GNUNET_DHT_P2PRouteMessage) +
4838 ntohs (enc_msg->size) + path_size));
4839 route_path = (char *) &incoming[1];
4840 route_path = route_path + ntohs (enc_msg->size);
4841 msg_ctx->path_history =
4842 GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) + path_size);
4843 memcpy (msg_ctx->path_history, route_path, path_size);
4844 memcpy (&msg_ctx->path_history[path_size], &my_identity,
4845 sizeof (struct GNUNET_PeerIdentity));
4846 msg_ctx->path_history_len = ntohl (incoming->outgoing_path_length) + 1;
4848 msg_ctx->network_size = ntohl (incoming->network_size);
4849 msg_ctx->peer = peer;
4850 msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4851 msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4852 demultiplex_message (enc_msg, msg_ctx);
4853 if (msg_ctx->bloom != NULL)
4855 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4856 msg_ctx->bloom = NULL;
4858 GNUNET_free (msg_ctx);
4864 * Core handler for p2p route results.
4866 * @param cls closure
4867 * @param message message
4868 * @param peer peer identity this notification is about
4869 * @param atsi performance data
4873 handle_dht_p2p_route_result (void *cls, const struct GNUNET_PeerIdentity *peer,
4874 const struct GNUNET_MessageHeader *message,
4875 const struct GNUNET_TRANSPORT_ATS_Information
4879 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4880 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT",
4883 struct GNUNET_DHT_P2PRouteResultMessage *incoming =
4884 (struct GNUNET_DHT_P2PRouteResultMessage *) message;
4885 struct GNUNET_MessageHeader *enc_msg =
4886 (struct GNUNET_MessageHeader *) &incoming[1];
4887 struct DHT_MessageContext msg_ctx;
4893 if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4895 GNUNET_break_op (0);
4899 if (malicious_dropper == GNUNET_YES)
4901 #if DEBUG_DHT_ROUTING
4902 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4904 /** Log routes that die due to high load! */
4905 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4906 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4907 GNUNET_SYSERR, &my_identity, &incoming->key,
4914 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4915 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4916 memcpy (&msg_ctx.key, &incoming->key, sizeof (GNUNET_HashCode));
4917 msg_ctx.unique_id = GNUNET_ntohll (incoming->unique_id);
4918 msg_ctx.msg_options = ntohl (incoming->options);
4919 msg_ctx.hop_count = ntohl (incoming->hop_count);
4920 msg_ctx.peer = peer;
4921 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4922 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4923 if ((GNUNET_DHT_RO_RECORD_ROUTE ==
4924 (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE)) &&
4925 (ntohl (incoming->outgoing_path_length) > 0))
4927 if (ntohs (message->size) -
4928 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) -
4929 ntohs (enc_msg->size) !=
4930 ntohl (incoming->outgoing_path_length) *
4931 sizeof (struct GNUNET_PeerIdentity))
4934 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4935 "Return message indicated a path was included, but sizes are wrong: Total size %d, enc size %d, left %d, expected %d\n",
4936 ntohs (message->size), ntohs (enc_msg->size),
4937 ntohs (message->size) -
4938 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) -
4939 ntohs (enc_msg->size),
4940 ntohl (incoming->outgoing_path_length) *
4941 sizeof (struct GNUNET_PeerIdentity));
4943 GNUNET_break_op (0);
4946 msg_ctx.path_history = (char *) &incoming[1];
4947 msg_ctx.path_history += ntohs (enc_msg->size);
4948 msg_ctx.path_history_len = ntohl (incoming->outgoing_path_length);
4950 for (i = 0; i < msg_ctx.path_history_len; i++)
4953 &msg_ctx.path_history[i * sizeof (struct GNUNET_PeerIdentity)];
4954 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4955 "(handle_p2p_route_result) Key %s Found peer %d:%s\n",
4956 GNUNET_h2s (&msg_ctx.key), i,
4957 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
4962 GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4964 GNUNET_assert (msg_ctx.bloom != NULL);
4965 route_result_message (enc_msg, &msg_ctx);
4971 * Receive the HELLO from transport service,
4972 * free current and replace if necessary.
4975 * @param message HELLO message of peer
4978 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4982 "Received our `%s' from transport service\n", "HELLO");
4985 GNUNET_assert (message != NULL);
4986 GNUNET_free_non_null (my_hello);
4987 my_hello = GNUNET_malloc (ntohs (message->size));
4988 memcpy (my_hello, message, ntohs (message->size));
4993 * Task run during shutdown.
4999 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5002 struct PeerInfo *pos;
5004 if (transport_handle != NULL)
5006 GNUNET_free_non_null (my_hello);
5007 GNUNET_TRANSPORT_get_hello_cancel (transport_handle, &process_hello, NULL);
5008 GNUNET_TRANSPORT_disconnect (transport_handle);
5010 if (coreAPI != NULL)
5013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Disconnecting core!\n",
5014 my_short_id, "DHT");
5016 GNUNET_CORE_disconnect (coreAPI);
5019 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
5021 while (k_buckets[bucket_count].head != NULL)
5023 pos = k_buckets[bucket_count].head;
5025 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5026 "%s:%s Removing peer %s from bucket %d!\n", my_short_id,
5027 "DHT", GNUNET_i2s (&pos->id), bucket_count);
5029 delete_peer (pos, bucket_count);
5032 if (datacache != NULL)
5035 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Destroying datacache!\n",
5036 my_short_id, "DHT");
5038 GNUNET_DATACACHE_destroy (datacache);
5043 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
5046 if (dhtlog_handle != NULL)
5048 GNUNET_DHTLOG_disconnect (dhtlog_handle);
5049 dhtlog_handle = NULL;
5051 if (block_context != NULL)
5053 GNUNET_BLOCK_context_destroy (block_context);
5054 block_context = NULL;
5056 GNUNET_free_non_null (my_short_id);
5062 * To be called on core init/fail.
5064 * @param cls service closure
5065 * @param server handle to the server for this service
5066 * @param identity the public identity of this peer
5067 * @param publicKey the public key of this peer
5070 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5071 const struct GNUNET_PeerIdentity *identity,
5072 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
5078 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s: Connection to core FAILED!\n",
5079 "dht", GNUNET_i2s (identity));
5081 GNUNET_SCHEDULER_cancel (cleanup_task);
5082 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
5086 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5087 "%s: Core connection initialized, I am peer: %s\n", "dht",
5088 GNUNET_i2s (identity));
5091 /* Copy our identity so we can use it */
5092 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
5093 if (my_short_id != NULL)
5094 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5095 "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n",
5097 my_short_id = GNUNET_strdup (GNUNET_i2s (&my_identity));
5098 /* Set the server to local variable */
5101 if (dhtlog_handle != NULL)
5102 dhtlog_handle->insert_node (NULL, &my_identity);
5106 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
5107 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE,
5109 {&handle_dht_local_route_stop, NULL,
5110 GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
5111 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
5116 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5117 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
5118 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
5124 * Method called whenever a peer connects.
5126 * @param cls closure
5127 * @param peer peer identity this notification is about
5128 * @param atsi performance data
5131 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
5132 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
5134 struct PeerInfo *ret;
5135 struct DHTPutEntry *put_entry;
5138 /* Check for connect to self message */
5139 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
5143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5144 "%s:%s Receives core connect message for peer %s distance %d!\n",
5145 my_short_id, "dht", GNUNET_i2s (peer), distance);
5149 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
5153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5154 "%s:%s Received %s message for peer %s, but already have peer in RT!",
5155 my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s (peer));
5161 if ((datacache != NULL) && (GNUNET_YES == put_peer_identities))
5164 GNUNET_malloc (sizeof (struct DHTPutEntry) +
5165 sizeof (struct GNUNET_PeerIdentity));
5166 put_entry->path_length = 0;
5167 put_entry->data_size = sizeof (struct GNUNET_PeerIdentity);
5168 memcpy (&put_entry[1], peer, sizeof (struct GNUNET_PeerIdentity));
5169 GNUNET_DATACACHE_put (datacache, &peer->hashPubKey,
5170 sizeof (struct DHTPutEntry) +
5171 sizeof (struct GNUNET_PeerIdentity),
5172 (char *) put_entry, GNUNET_BLOCK_TYPE_DHT_HELLO,
5173 GNUNET_TIME_absolute_get_forever ());
5174 GNUNET_free (put_entry);
5176 else if (datacache == NULL)
5177 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5178 "DHT has no connection to datacache!\n");
5180 peer_bucket = find_current_bucket (&peer->hashPubKey);
5181 GNUNET_assert (peer_bucket >= lowest_bucket);
5182 GNUNET_assert (peer_bucket < MAX_BUCKETS);
5183 ret = GNUNET_malloc (sizeof (struct PeerInfo));
5185 ret->latency = latency;
5186 ret->distance = distance;
5189 GNUNET_CONTAINER_DLL_insert_after (k_buckets[peer_bucket].head,
5190 k_buckets[peer_bucket].tail,
5191 k_buckets[peer_bucket].tail, ret);
5192 k_buckets[peer_bucket].peers_size++;
5193 #if DO_UPDATE_PREFERENCE
5194 if ((GNUNET_CRYPTO_hash_matching_bits
5195 (&my_identity.hashPubKey, &peer->hashPubKey) > 0) &&
5196 (k_buckets[peer_bucket].peers_size <= bucket_size))
5197 ret->preference_task =
5198 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
5200 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
5201 enable_next_bucket ();
5203 schedule_ping_messages ();
5205 newly_found_peers++;
5206 GNUNET_CONTAINER_multihashmap_put (all_known_peers, &peer->hashPubKey, ret,
5207 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5208 increment_stats (STAT_PEERS_KNOWN);
5211 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5212 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT",
5213 ret == NULL ? "NOT ADDED" : "PEER ADDED");
5219 * Method called whenever a peer disconnects.
5221 * @param cls closure
5222 * @param peer peer identity this notification is about
5225 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5227 struct PeerInfo *to_remove;
5230 /* Check for disconnect from self message */
5231 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
5234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5235 "%s:%s: Received peer disconnect message for peer `%s' from %s\n",
5236 my_short_id, "DHT", GNUNET_i2s (peer), "CORE");
5240 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
5245 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5246 "%s:%s: do not have peer `%s' in RT, can't disconnect!\n",
5247 my_short_id, "DHT", GNUNET_i2s (peer));
5251 increment_stats (STAT_DISCONNECTS);
5252 GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
5253 (all_known_peers, &peer->hashPubKey));
5255 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
5256 GNUNET_assert (to_remove != NULL);
5257 if (NULL != to_remove->info_ctx)
5259 GNUNET_CORE_peer_change_preference_cancel (to_remove->info_ctx);
5260 to_remove->info_ctx = NULL;
5263 memcmp (peer, &to_remove->id,
5264 sizeof (struct GNUNET_PeerIdentity)));
5265 current_bucket = find_current_bucket (&to_remove->id.hashPubKey);
5266 delete_peer (to_remove, current_bucket);
5271 * Process dht requests.
5273 * @param cls closure
5274 * @param server the initialized server
5275 * @param c configuration to use
5278 run (void *cls, struct GNUNET_SERVER_Handle *server,
5279 const struct GNUNET_CONFIGURATION_Handle *c)
5281 struct GNUNET_TIME_Relative next_send_time;
5282 unsigned long long temp_config_num;
5283 char *converge_modifier_buf;
5286 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
5287 GNUNET_SERVER_add_handlers (server, plugin_handlers);
5288 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
5289 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
5290 DEFAULT_CORE_QUEUE_SIZE, /* queue size */
5291 NULL, /* Closure passed to DHT functions */
5292 &core_init, /* Call core_init once connected */
5293 &handle_core_connect, /* Handle connects */
5294 &handle_core_disconnect, /* remove peers on disconnects */
5295 NULL, /* Do we care about "status" updates? */
5296 NULL, /* Don't want notified about all incoming messages */
5297 GNUNET_NO, /* For header only inbound notification */
5298 NULL, /* Don't want notified about all outbound messages */
5299 GNUNET_NO, /* For header only outbound notification */
5300 core_handlers); /* Register these handlers */
5302 if (coreAPI == NULL)
5305 GNUNET_TRANSPORT_connect (cfg, NULL, NULL, NULL, NULL, NULL);
5306 if (transport_handle != NULL)
5307 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
5309 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5310 "Failed to connect to transport service!\n");
5311 block_context = GNUNET_BLOCK_context_create (cfg);
5312 lowest_bucket = MAX_BUCKETS - 1;
5313 forward_list.hashmap =
5314 GNUNET_CONTAINER_multihashmap_create (MAX_OUTSTANDING_FORWARDS / 10);
5315 forward_list.minHeap =
5316 GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
5317 all_known_peers = GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
5318 recent_find_peer_requests =
5319 GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
5320 GNUNET_assert (all_known_peers != NULL);
5322 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
5325 debug_routes = GNUNET_YES;
5329 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "strict_kademlia"))
5331 strict_kademlia = GNUNET_YES;
5335 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_on_closest"))
5337 stop_on_closest = GNUNET_YES;
5341 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_found"))
5343 stop_on_found = GNUNET_YES;
5347 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_getter"))
5349 malicious_getter = GNUNET_YES;
5351 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
5352 "MALICIOUS_GET_FREQUENCY",
5353 &malicious_get_frequency))
5354 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
5358 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "MAX_HOPS", &max_hops))
5360 max_hops = DEFAULT_MAX_HOPS;
5364 GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT", "USE_MAX_HOPS"))
5366 use_max_hops = GNUNET_YES;
5370 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_putter"))
5372 malicious_putter = GNUNET_YES;
5374 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
5375 "MALICIOUS_PUT_FREQUENCY",
5376 &malicious_put_frequency))
5377 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
5380 dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
5382 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
5383 "REPLICATION_FREQUENCY",
5386 dht_republish_frequency =
5387 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES,
5392 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "bucket_size",
5395 bucket_size = (unsigned int) temp_config_num;
5399 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "kad_alpha",
5400 &kademlia_replication))
5402 kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
5406 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_dropper"))
5408 malicious_dropper = GNUNET_YES;
5412 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "republish"))
5413 do_republish = GNUNET_NO;
5416 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "do_find_peer"))
5418 do_find_peer = GNUNET_NO;
5421 do_find_peer = GNUNET_YES;
5424 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "use_real_distance"))
5425 use_real_distance = GNUNET_YES;
5428 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
5429 "mysql_logging_extended"))
5431 debug_routes = GNUNET_YES;
5432 debug_routes_extended = GNUNET_YES;
5435 #if DEBUG_DHT_ROUTING
5436 if (GNUNET_YES == debug_routes)
5438 dhtlog_handle = GNUNET_DHTLOG_connect (cfg);
5439 if (dhtlog_handle == NULL)
5441 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5442 "Could not connect to mysql logging server, logging will not happen!");
5447 converge_option = DHT_CONVERGE_BINARY;
5449 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "converge_linear"))
5451 converge_option = DHT_CONVERGE_LINEAR;
5453 else if (GNUNET_YES ==
5454 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht",
5455 "converge_exponential"))
5457 converge_option = DHT_CONVERGE_EXPONENTIAL;
5459 else if (GNUNET_YES ==
5460 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "converge_random"))
5462 converge_option = DHT_CONVERGE_RANDOM;
5464 else if (GNUNET_YES ==
5465 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "converge_binary"))
5467 converge_option = DHT_CONVERGE_BINARY;
5470 converge_modifier = 4.0;
5472 GNUNET_CONFIGURATION_get_value_string (cfg, "dht", "converge_modifier",
5473 &converge_modifier_buf))
5475 if (1 != sscanf (converge_modifier_buf, "%f", &converge_modifier))
5477 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5478 "Failed to read decimal value for %s from `%s'\n",
5479 "CONVERGE_MODIFIER", converge_modifier_buf);
5480 converge_modifier = 0.0;
5482 GNUNET_free (converge_modifier_buf);
5486 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "paper_forwarding"))
5487 paper_forwarding = GNUNET_YES;
5490 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "put_peer_identities"))
5491 put_peer_identities = GNUNET_YES;
5493 stats = GNUNET_STATISTICS_create ("dht", cfg);
5497 GNUNET_STATISTICS_set (stats, STAT_ROUTES, 0, GNUNET_NO);
5498 GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
5499 GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
5500 GNUNET_STATISTICS_set (stats, STAT_RESULTS, 0, GNUNET_NO);
5501 GNUNET_STATISTICS_set (stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
5502 GNUNET_STATISTICS_set (stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
5503 GNUNET_STATISTICS_set (stats, STAT_GETS, 0, GNUNET_NO);
5504 GNUNET_STATISTICS_set (stats, STAT_PUTS, 0, GNUNET_NO);
5505 GNUNET_STATISTICS_set (stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
5506 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER, 0, GNUNET_NO);
5507 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
5508 GNUNET_STATISTICS_set (stats, STAT_GET_START, 0, GNUNET_NO);
5509 GNUNET_STATISTICS_set (stats, STAT_PUT_START, 0, GNUNET_NO);
5510 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
5511 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
5512 GNUNET_STATISTICS_set (stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
5513 GNUNET_STATISTICS_set (stats, STAT_GET_REPLY, 0, GNUNET_NO);
5514 GNUNET_STATISTICS_set (stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
5515 GNUNET_STATISTICS_set (stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
5516 GNUNET_STATISTICS_set (stats, STAT_DISCONNECTS, 0, GNUNET_NO);
5518 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
5519 recent.hashmap = GNUNET_CONTAINER_multihashmap_create (DHT_MAX_RECENT / 2);
5521 GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
5522 if (GNUNET_YES == do_find_peer)
5524 next_send_time.rel_value =
5525 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
5526 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
5527 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value /
5529 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
5530 find_peer_context.start = GNUNET_TIME_absolute_get ();
5531 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
5532 &find_peer_context);
5535 /* Scheduled the task to clean up when shutdown is called */
5537 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
5538 &shutdown_task, NULL);
5542 * The main function for the dht service.
5544 * @param argc number of arguments from the command line
5545 * @param argv command line arguments
5546 * @return 0 ok, 1 on error
5549 main (int argc, char *const *argv)
5555 GNUNET_SERVICE_run (argc, argv, "dht", GNUNET_SERVICE_OPTION_NONE, &run,
5557 if (NULL != recent.hashmap)
5559 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (recent.hashmap));
5560 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
5561 recent.hashmap = NULL;
5563 if (NULL != recent.minHeap)
5565 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (recent.minHeap));
5566 GNUNET_CONTAINER_heap_destroy (recent.minHeap);
5567 recent.minHeap = NULL;
5569 if (NULL != recent_find_peer_requests)
5571 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
5572 recent_find_peer_requests = NULL;