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;
786 * Handle to get our current HELLO.
788 static struct GNUNET_TRANSPORT_GetHelloHandle *ghh;
791 * The configuration the DHT service is running with
793 static const struct GNUNET_CONFIGURATION_Handle *cfg;
796 * Handle to the core service
798 static struct GNUNET_CORE_Handle *coreAPI;
801 * Handle to the transport service, for getting our hello
803 static struct GNUNET_TRANSPORT_Handle *transport_handle;
806 * The identity of our peer.
808 static struct GNUNET_PeerIdentity my_identity;
811 * Short id of the peer, for printing
813 static char *my_short_id;
818 static struct GNUNET_MessageHeader *my_hello;
821 * Task to run when we shut down, cleaning up all our trash
823 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
826 * The lowest currently used bucket.
828 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
831 * The maximum number of hops before we stop routing messages.
833 static unsigned long long max_hops;
836 * How often to republish content we have previously stored.
838 static struct GNUNET_TIME_Relative dht_republish_frequency;
841 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
843 static int use_max_hops;
846 * The buckets (Kademlia routing table, complete with growth).
847 * Array of size MAX_BUCKET_SIZE.
849 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
852 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
854 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
857 * Recently seen find peer requests.
859 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
862 * Maximum size for each bucket.
864 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
867 * List of active clients.
869 static struct ClientList *client_list;
872 * Handle to the DHT logger.
874 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
877 * Whether or not to send routing debugging information
878 * to the dht logging server
880 static unsigned int debug_routes;
883 * Whether or not to send FULL route information to
886 static unsigned int debug_routes_extended;
889 * GNUNET_YES or GNUNET_NO, whether or not to act as
890 * a malicious node which drops all messages
892 static unsigned int malicious_dropper;
895 * GNUNET_YES or GNUNET_NO, whether or not to act as
896 * a malicious node which sends out lots of GETS
898 static unsigned int malicious_getter;
901 * GNUNET_YES or GNUNET_NO, whether or not to act as
902 * a malicious node which sends out lots of PUTS
904 static unsigned int malicious_putter;
907 * Frequency for malicious get requests.
909 static unsigned long long malicious_get_frequency;
912 * Frequency for malicious put requests.
914 static unsigned long long malicious_put_frequency;
917 * Kademlia replication
919 static unsigned long long kademlia_replication;
922 * Reply times for requests, if we are busy, don't send any
925 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
928 * Current counter for replies.
930 static unsigned int reply_counter;
933 * Our handle to the BLOCK library.
935 static struct GNUNET_BLOCK_Context *block_context;
939 * Forward declaration.
942 send_generic_reply (void *cls, size_t size, void *buf);
945 /** Declare here so retry_core_send is aware of it */
947 core_transmit_notify (void *cls, size_t size, void *buf);
950 * Convert unique ID to hash code.
952 * @param uid unique ID to convert
953 * @param hash set to uid (extended with zeros)
956 hash_from_uid (uint64_t uid, GNUNET_HashCode * hash)
958 memset (hash, 0, sizeof (GNUNET_HashCode));
959 *((uint64_t *) hash) = uid;
964 * Calculate the average send time between messages so that we can
965 * ignore certain requests if we get too busy.
967 * @return the average time between asking core to send a message
968 * and when the buffer for copying it is passed
970 static struct GNUNET_TIME_Relative
971 get_average_send_delay ()
974 unsigned int divisor;
975 struct GNUNET_TIME_Relative average_time;
977 average_time = GNUNET_TIME_relative_get_zero ();
979 for (i = 0; i < MAX_REPLY_TIMES; i++)
981 average_time = GNUNET_TIME_relative_add (average_time, reply_times[i]);
982 if (reply_times[i].abs_value == (uint64_t) 0)
992 average_time = GNUNET_TIME_relative_divide (average_time, divisor);
993 fprintf (stderr, "Avg send delay: %u sends is %llu\n", divisor,
994 (unsigned long long) average_time.abs_value);
1000 * Given the largest send delay, artificially decrease it
1001 * so the next time around we may have a chance at sending
1005 decrease_max_send_delay (struct GNUNET_TIME_Relative max_time)
1009 for (i = 0; i < MAX_REPLY_TIMES; i++)
1011 if (reply_times[i].rel_value == max_time.rel_value)
1013 reply_times[i].rel_value = reply_times[i].rel_value / 2;
1020 * Find the maximum send time of the recently sent values.
1022 * @return the average time between asking core to send a message
1023 * and when the buffer for copying it is passed
1025 static struct GNUNET_TIME_Relative
1026 get_max_send_delay ()
1029 struct GNUNET_TIME_Relative max_time;
1031 max_time = GNUNET_TIME_relative_get_zero ();
1033 for (i = 0; i < MAX_REPLY_TIMES; i++)
1035 if (reply_times[i].rel_value > max_time.rel_value)
1036 max_time.rel_value = reply_times[i].rel_value;
1039 if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
1040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n",
1041 (unsigned long long) max_time.rel_value);
1047 increment_stats (const char *value)
1051 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
1056 decrement_stats (const char *value)
1060 GNUNET_STATISTICS_update (stats, value, -1, GNUNET_NO);
1065 * Try to send another message from our core send list
1068 try_core_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1070 struct PeerInfo *peer = cls;
1071 struct P2PPendingMessage *pending;
1074 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
1076 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1079 if (peer->th != NULL)
1080 return; /* Message send already in progress */
1082 pending = peer->head;
1083 if (pending != NULL)
1085 ssize = ntohs (pending->msg->size);
1087 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1088 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n",
1089 my_short_id, "DHT", ssize, GNUNET_i2s (&peer->id));
1091 pending->scheduled = GNUNET_TIME_absolute_get ();
1093 if (reply_counter >= MAX_REPLY_TIMES)
1096 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
1097 pending->importance,
1098 pending->timeout, &peer->id, ssize,
1099 &core_transmit_notify, peer);
1100 if (peer->th == NULL)
1101 increment_stats ("# notify transmit ready failed");
1106 * Function called to send a request out to another peer.
1107 * Called both for locally initiated requests and those
1108 * received from other peers.
1110 * @param msg the encapsulated message
1111 * @param peer the peer to forward the message to
1112 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1115 forward_result_message (const struct GNUNET_MessageHeader *msg,
1116 struct PeerInfo *peer,
1117 struct DHT_MessageContext *msg_ctx)
1119 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1120 struct P2PPendingMessage *pending;
1130 increment_stats (STAT_RESULT_FORWARDS);
1132 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs (msg->size) +
1133 (sizeof (struct GNUNET_PeerIdentity) * msg_ctx->path_history_len);
1134 GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1135 psize = sizeof (struct P2PPendingMessage) + msize;
1136 pending = GNUNET_malloc (psize);
1137 pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1138 pending->importance = DHT_SEND_PRIORITY;
1139 pending->timeout = GNUNET_TIME_relative_get_forever ();
1140 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *) pending->msg;
1141 result_message->header.size = htons (msize);
1142 result_message->header.type =
1143 htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1144 result_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1145 if (msg_ctx->path_history_len > 0)
1147 /* End of pending is where enc_msg starts */
1148 path_start = (char *) &pending[1];
1149 /* Offset by the size of the enc_msg */
1150 path_start += ntohs (msg->size);
1151 memcpy (path_start, msg_ctx->path_history,
1152 msg_ctx->path_history_len * (sizeof (struct GNUNET_PeerIdentity)));
1154 for (i = 0; i < msg_ctx->path_history_len; i++)
1157 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1159 "(forward_result) Key %s Found peer %d:%s\n",
1160 GNUNET_h2s (&msg_ctx->key), i,
1161 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1165 result_message->options = htonl (msg_ctx->msg_options);
1166 result_message->hop_count = htonl (msg_ctx->hop_count + 1);
1167 GNUNET_assert (GNUNET_OK ==
1168 GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1172 result_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1173 memcpy (&result_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1174 /* Copy the enc_msg, then the path history as well! */
1175 memcpy (&result_message[1], msg, ntohs (msg->size));
1176 path_offset = (char *) &result_message[1];
1177 path_offset += ntohs (msg->size);
1178 /* If we have path history, copy it to the end of the whole thing */
1179 if (msg_ctx->path_history_len > 0)
1180 memcpy (path_offset, msg_ctx->path_history,
1181 msg_ctx->path_history_len * (sizeof (struct GNUNET_PeerIdentity)));
1183 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1184 "%s:%s Adding pending message size %d for peer %s\n", my_short_id,
1185 "DHT", msize, GNUNET_i2s (&peer->id));
1187 peer->pending_count++;
1188 increment_stats ("# pending messages scheduled");
1189 GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1191 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1192 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1197 * Called when core is ready to send a message we asked for
1198 * out to the destination.
1200 * @param cls closure (NULL)
1201 * @param size number of bytes available in buf
1202 * @param buf where the callee should write the message
1203 * @return number of bytes written to buf
1206 core_transmit_notify (void *cls, size_t size, void *buf)
1208 struct PeerInfo *peer = cls;
1210 struct P2PPendingMessage *pending;
1218 /* client disconnected */
1220 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n",
1221 my_short_id, "DHT");
1226 if (peer->head == NULL)
1230 pending = peer->head;
1232 reply_times[reply_counter] =
1233 GNUNET_TIME_absolute_get_difference (pending->scheduled,
1234 GNUNET_TIME_absolute_get ());
1235 msize = ntohs (pending->msg->size);
1239 memcpy (cbuf, pending->msg, msize);
1240 peer->pending_count--;
1241 increment_stats ("# pending messages sent");
1242 GNUNET_assert (peer->pending_count >= 0);
1243 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1244 GNUNET_free (pending);
1247 while (NULL != pending &&
1248 (size - off >= (msize = ntohs (pending->msg->size))))
1250 memcpy (&cbuf[off], pending->msg, msize);
1252 peer->pending_count--;
1253 increment_stats ("# pending messages sent");
1254 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1255 GNUNET_free (pending);
1256 pending = peer->head;
1259 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1260 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1267 * Compute the distance between have and target as a 32-bit value.
1268 * Differences in the lower bits must count stronger than differences
1269 * in the higher bits.
1271 * @return 0 if have==target, otherwise a number
1272 * that is larger as the distance between
1273 * the two hash codes increases
1276 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1278 unsigned int bucket;
1283 /* We have to represent the distance between two 2^9 (=512)-bit
1284 * numbers as a 2^5 (=32)-bit number with "0" being used for the
1285 * two numbers being identical; furthermore, we need to
1286 * guarantee that a difference in the number of matching
1287 * bits is always represented in the result.
1289 * We use 2^32/2^9 numerical values to distinguish between
1290 * hash codes that have the same LSB bit distance and
1291 * use the highest 2^9 bits of the result to signify the
1292 * number of (mis)matching LSB bits; if we have 0 matching
1293 * and hence 512 mismatching LSB bits we return -1 (since
1294 * 512 itself cannot be represented with 9 bits) */
1296 /* first, calculate the most significant 9 bits of our
1297 * result, aka the number of LSBs */
1298 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1299 /* bucket is now a value between 0 and 512 */
1301 return 0; /* perfect match */
1303 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1304 * below, we'd end up with max+1 (overflow)) */
1306 /* calculate the most significant bits of the final result */
1307 msb = (512 - bucket) << (32 - 9);
1308 /* calculate the 32-9 least significant bits of the final result by
1309 * looking at the differences in the 32-9 bits following the
1310 * mismatching bit at 'bucket' */
1312 for (i = bucket + 1;
1313 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1315 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
1316 GNUNET_CRYPTO_hash_get_bit (have, i))
1317 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1318 * last bit set will be 31 -- if
1319 * i does not reach 512 first... */
1325 * Return a number that is larger the closer the
1326 * "have" GNUNET_hash code is to the "target".
1328 * @return inverse distance metric, non-zero.
1329 * Must fudge the value if NO bits match.
1332 inverse_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1334 if (GNUNET_CRYPTO_hash_matching_bits (target, have) == 0)
1335 return 1; /* Never return 0! */
1336 return ((unsigned int) -1) - distance (target, have);
1341 * Find the optimal bucket for this key, regardless
1342 * of the current number of buckets in use.
1344 * @param hc the hashcode to compare our identity to
1346 * @return the proper bucket index, or GNUNET_SYSERR
1347 * on error (same hashcode)
1350 find_bucket (const GNUNET_HashCode * hc)
1354 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
1355 if (bits == MAX_BUCKETS)
1356 return GNUNET_SYSERR;
1357 return MAX_BUCKETS - bits - 1;
1362 * Find which k-bucket this peer should go into,
1363 * taking into account the size of the k-bucket
1364 * array. This means that if more bits match than
1365 * there are currently buckets, lowest_bucket will
1368 * @param hc GNUNET_HashCode we are finding the bucket for.
1370 * @return the proper bucket index for this key,
1371 * or GNUNET_SYSERR on error (same hashcode)
1374 find_current_bucket (const GNUNET_HashCode * hc)
1378 actual_bucket = find_bucket (hc);
1379 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1380 return lowest_bucket;
1381 if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1382 return lowest_bucket;
1383 return actual_bucket;
1388 * Find a routing table entry from a peer identity
1390 * @param peer the peer to look up
1392 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1395 find_bucket_by_peer (const struct PeerInfo *peer)
1398 struct PeerInfo *pos;
1400 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1402 pos = k_buckets[bucket].head;
1411 return GNUNET_SYSERR; /* No such peer. */
1417 * Print the complete routing table for this peer.
1420 print_routing_table ()
1423 struct PeerInfo *pos;
1424 char char_buf[30000];
1427 memset (char_buf, 0, sizeof (char_buf));
1430 sprintf (&char_buf[char_pos], "Printing routing table for peer %s\n",
1432 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1433 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1435 pos = k_buckets[bucket].head;
1436 char_pos += sprintf (&char_buf[char_pos], "Bucket %d:\n", bucket);
1437 //fprintf(stderr, "Bucket %d:\n", bucket);
1440 //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));
1442 sprintf (&char_buf[char_pos],
1443 "\tPeer %s, best bucket %d, %d bits match\n",
1444 GNUNET_i2s (&pos->id), find_bucket (&pos->id.hashPubKey),
1445 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
1446 &my_identity.hashPubKey));
1450 fprintf (stderr, "%s", char_buf);
1456 * Find a routing table entry from a peer identity
1458 * @param peer the peer identity to look up
1460 * @return the routing table entry, or NULL if not found
1462 static struct PeerInfo *
1463 find_peer_by_id (const struct GNUNET_PeerIdentity *peer)
1466 struct PeerInfo *pos;
1468 bucket = find_current_bucket (&peer->hashPubKey);
1470 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
1473 pos = k_buckets[bucket].head;
1476 if (0 == memcmp (&pos->id, peer, sizeof (struct GNUNET_PeerIdentity)))
1480 return NULL; /* No such peer. */
1483 /* Forward declaration */
1485 update_core_preference (void *cls,
1486 const struct GNUNET_SCHEDULER_TaskContext *tc);
1488 * Function called with statistics about the given peer.
1490 * @param cls closure
1491 * @param peer identifies the peer
1492 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1493 * @param amount set to the amount that was actually reserved or unreserved;
1494 * either the full requested amount or zero (no partial reservations)
1495 * @param res_delay if the reservation could not be satisfied (amount was 0), how
1496 * long should the client wait until re-trying?
1497 * @param preference current traffic preference for the given peer
1500 update_core_preference_finish (void *cls,
1501 const struct GNUNET_PeerIdentity *peer,
1502 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1504 struct GNUNET_TIME_Relative res_delay,
1505 uint64_t preference)
1507 struct PeerInfo *peer_info = cls;
1509 peer_info->info_ctx = NULL;
1510 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
1511 &update_core_preference, peer_info);
1515 update_core_preference (void *cls,
1516 const struct GNUNET_SCHEDULER_TaskContext *tc)
1518 struct PeerInfo *peer = cls;
1519 uint64_t preference;
1520 unsigned int matching;
1522 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1527 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
1528 &peer->id.hashPubKey);
1532 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1533 "Peer identifier matches by %u bits, only shifting as much as we can!\n",
1538 preference = 1LL << matching;
1540 GNUNET_CORE_peer_change_preference (coreAPI, &peer->id,
1541 GNUNET_TIME_UNIT_FOREVER_REL,
1542 GNUNET_BANDWIDTH_VALUE_MAX, 0,
1544 &update_core_preference_finish, peer);
1549 * Given a peer and its corresponding bucket,
1550 * remove it from that bucket. Does not free
1551 * the PeerInfo struct, nor cancel messages
1552 * or free messages waiting to be sent to this
1555 * @param peer the peer to remove
1556 * @param bucket the bucket the peer belongs to
1559 remove_peer (struct PeerInfo *peer, unsigned int bucket)
1561 GNUNET_assert (k_buckets[bucket].peers_size > 0);
1562 GNUNET_CONTAINER_DLL_remove (k_buckets[bucket].head, k_buckets[bucket].tail,
1564 k_buckets[bucket].peers_size--;
1566 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) &&
1567 (lowest_bucket < MAX_BUCKETS - 1))
1573 * Removes peer from a bucket, then frees associated
1574 * resources and frees peer.
1576 * @param peer peer to be removed and freed
1577 * @param bucket which bucket this peer belongs to
1580 delete_peer (struct PeerInfo *peer, unsigned int bucket)
1582 struct P2PPendingMessage *pos;
1583 struct P2PPendingMessage *next;
1586 struct PeerInfo *peer_pos;
1588 peer_pos = k_buckets[bucket].head;
1589 while ((peer_pos != NULL) && (peer_pos != peer))
1590 peer_pos = peer_pos->next;
1591 if (peer_pos == NULL)
1593 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1594 "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT",
1595 GNUNET_i2s (&peer->id), bucket);
1596 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1597 "%s:%s: Lowest bucket: %d, find_current_bucket: %d, peer resides in bucket: %d\n",
1598 my_short_id, "DHT", lowest_bucket,
1599 find_current_bucket (&peer->id.hashPubKey),
1600 find_bucket_by_peer (peer));
1602 GNUNET_assert (peer_pos != NULL);
1604 remove_peer (peer, bucket); /* First remove the peer from its bucket */
1606 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1607 GNUNET_SCHEDULER_cancel (peer->send_task);
1608 if ((peer->th != NULL) && (coreAPI != NULL))
1609 GNUNET_CORE_notify_transmit_ready_cancel (peer->th);
1612 while (pos != NULL) /* Remove any pending messages for this peer */
1615 ("# dht pending messages discarded (due to disconnect/shutdown)");
1621 GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
1622 (all_known_peers, &peer->id.hashPubKey));
1623 GNUNET_assert (GNUNET_YES ==
1624 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
1625 &peer->id.hashPubKey,
1628 decrement_stats (STAT_PEERS_KNOWN);
1633 * Iterator over hash map entries.
1635 * @param cls closure
1636 * @param key current key code
1637 * @param value PeerInfo of the peer to move to new lowest bucket
1638 * @return GNUNET_YES if we should continue to
1643 move_lowest_bucket (void *cls, const GNUNET_HashCode * key, void *value)
1645 struct PeerInfo *peer = value;
1648 GNUNET_assert (lowest_bucket > 0);
1649 new_bucket = lowest_bucket - 1;
1650 remove_peer (peer, lowest_bucket);
1651 GNUNET_CONTAINER_DLL_insert_after (k_buckets[new_bucket].head,
1652 k_buckets[new_bucket].tail,
1653 k_buckets[new_bucket].tail, peer);
1654 k_buckets[new_bucket].peers_size++;
1660 * The current lowest bucket is full, so change the lowest
1661 * bucket to the next lower down, and move any appropriate
1662 * entries in the current lowest bucket to the new bucket.
1665 enable_next_bucket ()
1667 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1668 struct PeerInfo *pos;
1670 GNUNET_assert (lowest_bucket > 0);
1671 to_remove = GNUNET_CONTAINER_multihashmap_create (bucket_size);
1672 pos = k_buckets[lowest_bucket].head;
1675 fprintf (stderr, "Printing RT before new bucket\n");
1676 print_routing_table ();
1678 /* Populate the array of peers which should be in the next lowest bucket */
1681 if (find_bucket (&pos->id.hashPubKey) < lowest_bucket)
1682 GNUNET_CONTAINER_multihashmap_put (to_remove, &pos->id.hashPubKey, pos,
1683 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1687 /* Remove peers from lowest bucket, insert into next lowest bucket */
1688 GNUNET_CONTAINER_multihashmap_iterate (to_remove, &move_lowest_bucket, NULL);
1689 GNUNET_CONTAINER_multihashmap_destroy (to_remove);
1690 lowest_bucket = lowest_bucket - 1;
1692 fprintf (stderr, "Printing RT after new bucket\n");
1693 print_routing_table ();
1698 * Find the closest peer in our routing table to the
1701 * @return The closest peer in our routing table to the
1702 * key, or NULL on error.
1704 static struct PeerInfo *
1705 find_closest_peer (const GNUNET_HashCode * hc)
1707 struct PeerInfo *pos;
1708 struct PeerInfo *current_closest;
1709 unsigned int lowest_distance;
1710 unsigned int temp_distance;
1714 lowest_distance = -1;
1716 if (k_buckets[lowest_bucket].peers_size == 0)
1719 current_closest = NULL;
1720 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1722 pos = k_buckets[bucket].head;
1724 while ((pos != NULL) && (count < bucket_size))
1726 temp_distance = distance (&pos->id.hashPubKey, hc);
1727 if (temp_distance <= lowest_distance)
1729 lowest_distance = temp_distance;
1730 current_closest = pos;
1736 GNUNET_assert (current_closest != NULL);
1737 return current_closest;
1742 * Function called to send a request out to another peer.
1743 * Called both for locally initiated requests and those
1744 * received from other peers.
1746 * @param msg the encapsulated message
1747 * @param peer the peer to forward the message to
1748 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1751 forward_message (const struct GNUNET_MessageHeader *msg, struct PeerInfo *peer,
1752 struct DHT_MessageContext *msg_ctx)
1754 struct GNUNET_DHT_P2PRouteMessage *route_message;
1755 struct P2PPendingMessage *pending;
1760 increment_stats (STAT_ROUTE_FORWARDS);
1761 GNUNET_assert (peer != NULL);
1762 if ((msg_ctx->closest != GNUNET_YES) &&
1763 (peer == find_closest_peer (&msg_ctx->key)))
1764 increment_stats (STAT_ROUTE_FORWARDS_CLOSEST);
1767 sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs (msg->size) +
1768 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1769 GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1770 psize = sizeof (struct P2PPendingMessage) + msize;
1771 pending = GNUNET_malloc (psize);
1772 pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1773 pending->importance = msg_ctx->importance;
1774 pending->timeout = msg_ctx->timeout;
1775 route_message = (struct GNUNET_DHT_P2PRouteMessage *) pending->msg;
1776 route_message->header.size = htons (msize);
1777 route_message->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1778 route_message->options = htonl (msg_ctx->msg_options);
1779 route_message->hop_count = htonl (msg_ctx->hop_count + 1);
1780 route_message->network_size = htonl (msg_ctx->network_size);
1781 route_message->desired_replication_level = htonl (msg_ctx->replication);
1782 route_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1783 if (msg_ctx->bloom != NULL)
1784 GNUNET_assert (GNUNET_OK ==
1785 GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1789 memcpy (&route_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1790 memcpy (&route_message[1], msg, ntohs (msg->size));
1791 if (GNUNET_DHT_RO_RECORD_ROUTE ==
1792 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
1794 route_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1795 /* Set pointer to start of enc_msg */
1796 route_path = (char *) &route_message[1];
1797 /* Offset to the end of the enc_msg */
1798 route_path += ntohs (msg->size);
1799 /* Copy the route_path after enc_msg */
1800 memcpy (route_path, msg_ctx->path_history,
1801 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1804 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1805 "%s:%s Adding pending message size %d for peer %s\n", my_short_id,
1806 "DHT", msize, GNUNET_i2s (&peer->id));
1808 peer->pending_count++;
1809 increment_stats ("# pending messages scheduled");
1810 GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1812 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1813 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1818 * Task used to send ping messages to peers so that
1819 * they don't get disconnected.
1821 * @param cls the peer to send a ping message to
1822 * @param tc context, reason, etc.
1825 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1827 struct PeerInfo *peer = cls;
1828 struct GNUNET_MessageHeader ping_message;
1829 struct DHT_MessageContext msg_ctx;
1831 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1834 ping_message.size = htons (sizeof (struct GNUNET_MessageHeader));
1835 ping_message.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1837 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
1839 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n",
1840 my_short_id, "DHT", GNUNET_i2s (&peer->id));
1842 forward_message (&ping_message, peer, &msg_ctx);
1844 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PING_DELAY, &periodic_ping_task,
1849 * Schedule PING messages for the top X peers in each
1850 * bucket of the routing table (so core won't disconnect them!)
1853 schedule_ping_messages ()
1855 unsigned int bucket;
1857 struct PeerInfo *pos;
1859 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1861 pos = k_buckets[bucket].head;
1865 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1866 GNUNET_SCHEDULER_add_now (&periodic_ping_task, pos);
1867 else if ((count >= bucket_size) &&
1868 (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1870 GNUNET_SCHEDULER_cancel (pos->ping_task);
1871 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1882 * Task run to check for messages that need to be sent to a client.
1884 * @param client a ClientList, containing the client and any messages to be sent to it
1887 process_pending_messages (struct ClientList *client)
1889 if (client->pending_head == NULL)
1891 if (client->transmit_handle != NULL)
1894 client->transmit_handle =
1895 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1896 ntohs (client->pending_head->
1898 GNUNET_TIME_UNIT_FOREVER_REL,
1899 &send_generic_reply, client);
1903 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1904 * request. A ClientList is passed as closure, take the head of the list
1905 * and copy it into buf, which has the result of sending the message to the
1908 * @param cls closure to this call
1909 * @param size maximum number of bytes available to send
1910 * @param buf where to copy the actual message to
1912 * @return the number of bytes actually copied, 0 indicates failure
1915 send_generic_reply (void *cls, size_t size, void *buf)
1917 struct ClientList *client = cls;
1919 struct PendingMessage *reply;
1923 client->transmit_handle = NULL;
1926 /* client disconnected */
1930 while ((NULL != (reply = client->pending_head)) &&
1931 (size >= off + (msize = ntohs (reply->msg->size))))
1933 GNUNET_CONTAINER_DLL_remove (client->pending_head, client->pending_tail,
1935 memcpy (&cbuf[off], reply->msg, msize);
1936 GNUNET_free (reply);
1939 process_pending_messages (client);
1941 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1942 "Transmitted %u bytes of replies to client\n",
1943 (unsigned int) off);
1950 * Add a PendingMessage to the clients list of messages to be sent
1952 * @param client the active client to send the message to
1953 * @param pending_message the actual message to send
1956 add_pending_message (struct ClientList *client,
1957 struct PendingMessage *pending_message)
1959 GNUNET_CONTAINER_DLL_insert_after (client->pending_head, client->pending_tail,
1960 client->pending_tail, pending_message);
1961 process_pending_messages (client);
1966 * Called when a reply needs to be sent to a client, as
1967 * a result it found to a GET or FIND PEER request.
1969 * @param client the client to send the reply to
1970 * @param message the encapsulated message to send
1971 * @param msg_ctx the context of the received message
1974 send_reply_to_client (struct ClientList *client,
1975 const struct GNUNET_MessageHeader *message,
1976 struct DHT_MessageContext *msg_ctx)
1978 struct GNUNET_DHT_RouteResultMessage *reply;
1979 struct PendingMessage *pending_message;
1989 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': Sending reply to client.\n",
1990 my_short_id, "DHT");
1992 msize = ntohs (message->size);
1994 sizeof (struct GNUNET_DHT_RouteResultMessage) + msize +
1995 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1996 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1998 GNUNET_break_op (0);
2001 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
2002 pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
2003 reply = (struct GNUNET_DHT_RouteResultMessage *) &pending_message[1];
2004 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
2005 reply->header.size = htons (tsize);
2006 reply->outgoing_path_length = htonl (msg_ctx->path_history_len);
2007 reply->unique_id = GNUNET_htonll (msg_ctx->unique_id);
2008 memcpy (&reply->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
2009 reply_offset = (char *) &reply[1];
2010 memcpy (&reply[1], message, msize);
2011 if (msg_ctx->path_history_len > 0)
2013 reply_offset += msize;
2014 memcpy (reply_offset, msg_ctx->path_history,
2015 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2018 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2019 "Returning message with outgoing path length %d\n",
2020 msg_ctx->path_history_len);
2021 for (i = 0; i < msg_ctx->path_history_len; i++)
2024 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
2025 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found peer %d:%s\n", i,
2026 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
2029 add_pending_message (client, pending_message);
2033 * Consider whether or not we would like to have this peer added to
2034 * our routing table. Check whether bucket for this peer is full,
2035 * if so return negative; if not return positive. Since peers are
2036 * only added on CORE level connect, this doesn't actually add the
2037 * peer to the routing table.
2039 * @param peer the peer we are considering adding
2041 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
2045 consider_peer (struct GNUNET_PeerIdentity *peer)
2050 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
2051 &peer->hashPubKey)) ||
2052 (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity))))
2053 return GNUNET_NO; /* We already know this peer (are connected even!) */
2054 bucket = find_current_bucket (&peer->hashPubKey);
2056 if ((k_buckets[bucket].peers_size < bucket_size) ||
2057 ((bucket == lowest_bucket) && (lowest_bucket > 0)))
2065 * Task used to remove forwarding entries, either
2066 * after timeout, when full, or on shutdown.
2068 * @param cls the entry to remove
2069 * @param tc context, reason, etc.
2072 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2074 struct DHTRouteSource *source_info = cls;
2075 struct DHTQueryRecord *record;
2077 source_info = GNUNET_CONTAINER_heap_remove_node (source_info->hnode);
2078 record = source_info->record;
2079 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
2081 if (record->head == NULL) /* No more entries in DLL */
2083 GNUNET_assert (GNUNET_YES ==
2084 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
2085 &record->key, record));
2086 GNUNET_free (record);
2088 if (source_info->find_peers_responded != NULL)
2089 GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
2090 GNUNET_free (source_info);
2094 * Main function that handles whether or not to route a result
2095 * message to other peers, or to send to our local client.
2097 * @param msg the result message to be routed
2098 * @param msg_ctx context of the message we are routing
2100 * @return the number of peers the message was routed to,
2101 * GNUNET_SYSERR on failure
2104 route_result_message (struct GNUNET_MessageHeader *msg,
2105 struct DHT_MessageContext *msg_ctx)
2107 struct GNUNET_PeerIdentity new_peer;
2108 struct DHTQueryRecord *record;
2109 struct DHTRouteSource *pos;
2110 struct PeerInfo *peer_info;
2111 const struct GNUNET_MessageHeader *hello_msg;
2117 increment_stats (STAT_RESULTS);
2119 * If a find peer result message is received and contains a valid
2120 * HELLO for another peer, offer it to the transport service.
2122 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
2124 if (ntohs (msg->size) <= sizeof (struct GNUNET_MessageHeader))
2125 GNUNET_break_op (0);
2127 hello_msg = &msg[1];
2128 if ((ntohs (hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2130 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello_msg,
2133 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2134 "%s:%s Received non-HELLO message type in find peer result message!\n",
2135 my_short_id, "DHT");
2136 GNUNET_break_op (0);
2139 else /* We have a valid hello, and peer id stored in new_peer */
2141 find_peer_context.count++;
2142 increment_stats (STAT_FIND_PEER_REPLY);
2143 if (GNUNET_YES == consider_peer (&new_peer))
2145 increment_stats (STAT_HELLOS_PROVIDED);
2146 GNUNET_TRANSPORT_offer_hello (transport_handle, hello_msg, NULL, NULL);
2147 GNUNET_CORE_peer_request_connect (coreAPI, &new_peer, NULL, NULL);
2152 if (malicious_dropper == GNUNET_YES)
2156 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
2158 if (record == NULL) /* No record of this message! */
2161 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2162 "`%s:%s': Have no record of response key %s uid %llu\n",
2163 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2164 msg_ctx->unique_id);
2166 #if DEBUG_DHT_ROUTING
2167 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2169 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2170 msg_ctx->hop_count, GNUNET_SYSERR,
2171 &my_identity, &msg_ctx->key, msg_ctx->peer,
2175 if (msg_ctx->bloom != NULL)
2177 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
2178 msg_ctx->bloom = NULL;
2186 #if STRICT_FORWARDING
2187 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2190 GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded,
2191 &new_peer.hashPubKey))
2193 increment_stats ("# find peer responses NOT forwarded (bloom match)");
2198 GNUNET_CONTAINER_bloomfilter_add (pos->find_peers_responded,
2199 &new_peer.hashPubKey);
2203 if (0 == memcmp (&pos->source, &my_identity, sizeof (struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2206 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2207 "`%s:%s': Sending response key %s uid %llu to client\n",
2208 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2209 msg_ctx->unique_id);
2211 #if DEBUG_DHT_ROUTING
2212 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2214 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2215 msg_ctx->hop_count, GNUNET_YES,
2216 &my_identity, &msg_ctx->key, msg_ctx->peer,
2220 increment_stats (STAT_RESULTS_TO_CLIENT);
2221 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2222 increment_stats (STAT_GET_REPLY);
2224 for (i = 0; i < msg_ctx->path_history_len; i++)
2229 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
2230 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2231 "(before client) Key %s Found peer %d:%s\n",
2232 GNUNET_h2s (&msg_ctx->key), i,
2233 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
2236 send_reply_to_client (pos->client, msg, msg_ctx);
2238 else /* Send to peer */
2240 peer_info = find_peer_by_id (&pos->source);
2241 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2247 if (msg_ctx->bloom == NULL)
2249 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
2251 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
2252 &my_identity.hashPubKey);
2254 GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom,
2255 &peer_info->id.hashPubKey)))
2258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2259 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n",
2260 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2261 msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2263 #if DEBUG_DHT_ROUTING
2264 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2266 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2267 msg_ctx->hop_count, GNUNET_NO,
2268 &my_identity, &msg_ctx->key,
2269 msg_ctx->peer, &pos->source);
2272 forward_result_message (msg, peer_info, msg_ctx);
2273 /* Try removing forward entries after sending once, only allows ONE response per request */
2274 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
2276 GNUNET_SCHEDULER_cancel (pos->delete_task);
2278 GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
2284 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2285 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n",
2286 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2287 msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2293 if (msg_ctx->bloom != NULL)
2295 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
2296 msg_ctx->bloom = NULL;
2303 * Iterator for local get request results,
2305 * @param cls closure for iterator, a DatacacheGetContext
2306 * @param exp when does this value expire?
2307 * @param key the key this data is stored under
2308 * @param size the size of the data identified by key
2309 * @param data the actual data
2310 * @param type the type of the data
2312 * @return GNUNET_OK to continue iteration, anything else
2313 * to stop iteration.
2316 datacache_get_iterator (void *cls, struct GNUNET_TIME_Absolute exp,
2317 const GNUNET_HashCode * key, size_t size,
2318 const char *data, enum GNUNET_BLOCK_Type type)
2320 struct DHT_MessageContext *msg_ctx = cls;
2321 struct DHT_MessageContext *new_msg_ctx;
2322 struct GNUNET_DHT_GetResultMessage *get_result;
2323 enum GNUNET_BLOCK_EvaluationResult eval;
2324 const struct DHTPutEntry *put_entry;
2333 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2334 "`%s:%s': Received `%s' response from datacache\n", my_short_id,
2338 put_entry = (const struct DHTPutEntry *) data;
2341 sizeof (struct DHTPutEntry) + put_entry->data_size +
2342 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)))
2344 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2345 "Path + data size doesn't add up for data inserted into datacache!\nData size %d, path length %d, expected %d, got %d\n",
2346 put_entry->data_size, put_entry->path_length,
2347 sizeof (struct DHTPutEntry) + put_entry->data_size +
2348 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)),
2350 msg_ctx->do_forward = GNUNET_NO;
2355 GNUNET_BLOCK_evaluate (block_context, type, key, &msg_ctx->reply_bf,
2356 msg_ctx->reply_bf_mutator, msg_ctx->xquery,
2357 msg_ctx->xquery_size, &put_entry[1],
2358 put_entry->data_size);
2362 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2363 msg_ctx->do_forward = GNUNET_NO;
2364 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2365 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2366 memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2367 if (GNUNET_DHT_RO_RECORD_ROUTE ==
2368 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2370 new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2371 new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2372 /* Assign to previous msg_ctx path history, caller should free after our return */
2373 new_msg_ctx->path_history = msg_ctx->path_history;
2375 for (i = 0; i < new_msg_ctx->path_history_len; i++)
2378 &new_msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
2379 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2380 "(get_iterator) Key %s Found peer %d:%s\n",
2381 GNUNET_h2s (&msg_ctx->key), i,
2382 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
2388 sizeof (struct GNUNET_DHT_GetResultMessage) + put_entry->data_size +
2389 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity));
2390 get_result = GNUNET_malloc (get_size);
2391 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2392 get_result->header.size = htons (get_size);
2393 get_result->expiration = GNUNET_TIME_absolute_hton (exp);
2394 get_result->type = htons (type);
2395 get_result->put_path_length = htons (put_entry->path_length);
2396 path_offset = (char *) &put_entry[1];
2397 path_offset += put_entry->data_size;
2399 for (i = 0; i < put_entry->path_length; i++)
2401 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2402 "(get_iterator PUT path) Key %s Found peer %d:%s\n",
2403 GNUNET_h2s (&msg_ctx->key), i,
2404 GNUNET_i2s ((struct GNUNET_PeerIdentity *)
2407 GNUNET_PeerIdentity)]));
2410 /* Copy the actual data and the path_history to the end of the get result */
2411 memcpy (&get_result[1], &put_entry[1],
2412 put_entry->data_size +
2413 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)));
2414 new_msg_ctx->peer = &my_identity;
2415 new_msg_ctx->bloom =
2416 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2417 new_msg_ctx->hop_count = 0;
2418 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
2419 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2420 increment_stats (STAT_GET_RESPONSE_START);
2421 route_result_message (&get_result->header, new_msg_ctx);
2422 GNUNET_free (new_msg_ctx);
2423 GNUNET_free (get_result);
2425 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2427 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': Duplicate block error\n",
2428 my_short_id, "DHT");
2431 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2433 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "`%s:%s': Invalid request error\n",
2434 my_short_id, "DHT");
2437 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2439 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2440 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2444 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2445 GNUNET_break_op (0);
2446 msg_ctx->do_forward = GNUNET_NO;
2448 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2450 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2451 "`%s:%s': Unsupported block type (%u) in response!\n",
2452 my_short_id, "DHT", type);
2454 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2462 * Main function that handles whether or not to route a message to other
2465 * @param msg the message to be routed
2466 * @param msg_ctx the context containing all pertinent information about the message
2469 route_message (const struct GNUNET_MessageHeader *msg,
2470 struct DHT_MessageContext *msg_ctx);
2474 * Server handler for all dht get requests, look for data,
2475 * if found, send response either to clients or other peers.
2477 * @param msg the actual get message
2478 * @param msg_ctx struct containing pertinent information about the get request
2480 * @return number of items found for GET request
2483 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2484 struct DHT_MessageContext *msg_ctx)
2486 const struct GNUNET_DHT_GetMessage *get_msg;
2489 unsigned int results;
2491 enum GNUNET_BLOCK_Type type;
2493 msize = ntohs (msg->size);
2494 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2499 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2500 bf_size = ntohs (get_msg->bf_size);
2501 msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2502 msg_ctx->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2504 sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2509 end = (const char *) &get_msg[1];
2510 if (msg_ctx->xquery_size == 0)
2512 msg_ctx->xquery = NULL;
2516 msg_ctx->xquery = (const void *) end;
2517 end += msg_ctx->xquery_size;
2521 msg_ctx->reply_bf = NULL;
2526 GNUNET_CONTAINER_bloomfilter_init (end, bf_size,
2527 GNUNET_DHT_GET_BLOOMFILTER_K);
2529 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2531 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2532 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2533 my_short_id, "DHT", "GET", type, GNUNET_h2s (&msg_ctx->key),
2534 msg_ctx->unique_id);
2536 increment_stats (STAT_GETS);
2539 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2541 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2545 msg_ctx->do_forward = GNUNET_YES;
2546 if (datacache != NULL)
2548 GNUNET_DATACACHE_get (datacache, &msg_ctx->key, type,
2549 &datacache_get_iterator, msg_ctx);
2551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2552 "`%s:%s': Found %d results for `%s' request uid %llu\n",
2553 my_short_id, "DHT", results, "GET", msg_ctx->unique_id);
2557 #if DEBUG_DHT_ROUTING
2558 if ((debug_routes) && (dhtlog_handle != NULL))
2560 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2561 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2565 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2567 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2568 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2569 &msg_ctx->key, msg_ctx->peer, NULL);
2575 /* check query valid */
2576 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID ==
2577 GNUNET_BLOCK_evaluate (block_context, type, &msg_ctx->key,
2578 &msg_ctx->reply_bf, msg_ctx->reply_bf_mutator,
2579 msg_ctx->xquery, msg_ctx->xquery_size, NULL, 0))
2581 GNUNET_break_op (0);
2582 msg_ctx->do_forward = GNUNET_NO;
2586 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2588 #if DEBUG_DHT_ROUTING
2589 if ((debug_routes) && (dhtlog_handle != NULL))
2591 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2592 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2597 if (msg_ctx->do_forward == GNUNET_YES)
2598 route_message (msg, msg_ctx);
2599 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2604 remove_recent_find_peer (void *cls,
2605 const struct GNUNET_SCHEDULER_TaskContext *tc)
2607 GNUNET_HashCode *key = cls;
2609 GNUNET_assert (GNUNET_YES ==
2610 GNUNET_CONTAINER_multihashmap_remove
2611 (recent_find_peer_requests, key, NULL));
2616 * Server handler for initiating local dht find peer requests
2618 * @param find_msg the actual find peer message
2619 * @param msg_ctx struct containing pertinent information about the request
2623 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2624 struct DHT_MessageContext *msg_ctx)
2626 struct GNUNET_MessageHeader *find_peer_result;
2627 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2628 struct DHT_MessageContext *new_msg_ctx;
2629 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2632 GNUNET_HashCode *recent_hash;
2633 struct GNUNET_MessageHeader *other_hello;
2634 size_t other_hello_size;
2635 struct GNUNET_PeerIdentity peer_id;
2637 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *) find_msg;
2638 GNUNET_break_op (ntohs (find_msg->size) >=
2639 (sizeof (struct GNUNET_DHT_FindPeerMessage)));
2640 if (ntohs (find_msg->size) < sizeof (struct GNUNET_DHT_FindPeerMessage))
2643 other_hello_size = 0;
2644 if (ntohs (find_msg->size) > sizeof (struct GNUNET_DHT_FindPeerMessage))
2647 ntohs (find_msg->size) - sizeof (struct GNUNET_DHT_FindPeerMessage);
2648 other_hello = GNUNET_malloc (other_hello_size);
2649 memcpy (other_hello, &find_peer_message[1], other_hello_size);
2650 if ((GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) other_hello) == 0)
2652 GNUNET_HELLO_get_id ((struct GNUNET_HELLO_Message *) other_hello,
2655 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2656 "Received invalid HELLO message in find peer request!\n");
2657 GNUNET_free (other_hello);
2660 #if FIND_PEER_WITH_HELLO
2661 if (GNUNET_YES == consider_peer (&peer_id))
2663 increment_stats (STAT_HELLOS_PROVIDED);
2664 GNUNET_TRANSPORT_offer_hello (transport_handle, other_hello, NULL, NULL);
2665 GNUNET_CORE_peer_request_connect (coreAPI, &peer_id, NULL, NULL);
2666 route_message (find_msg, msg_ctx);
2667 GNUNET_free (other_hello);
2670 else /* We don't want this peer! */
2672 route_message (find_msg, msg_ctx);
2673 GNUNET_free (other_hello);
2680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2681 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2682 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2683 ntohs (find_msg->size), sizeof (struct GNUNET_MessageHeader));
2685 if (my_hello == NULL)
2688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2689 "`%s': Our HELLO is null, can't return.\n", "DHT");
2691 GNUNET_free_non_null (other_hello);
2692 route_message (find_msg, msg_ctx);
2697 GNUNET_CONTAINER_bloomfilter_init (find_peer_message->bloomfilter,
2698 DHT_BLOOM_SIZE, DHT_BLOOM_K);
2700 GNUNET_CONTAINER_bloomfilter_test (incoming_bloom,
2701 &my_identity.hashPubKey))
2703 increment_stats (STAT_BLOOM_FIND_PEER);
2704 GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2705 GNUNET_free_non_null (other_hello);
2706 route_message (find_msg, msg_ctx);
2707 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!) */
2709 GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2711 #if RESTRICT_FIND_PEER
2714 * Ignore any find peer requests from a peer we have seen very recently.
2716 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! */
2718 increment_stats ("# dht find peer requests ignored (recently seen!)");
2719 GNUNET_free_non_null (other_hello);
2724 * Use this check to only allow the peer to respond to find peer requests if
2725 * it would be beneficial to have the requesting peer in this peers routing
2726 * table. Can be used to thwart peers flooding the network with find peer
2727 * requests that we don't care about. However, if a new peer is joining
2728 * the network and has no other peers this is a problem (assume all buckets
2729 * full, no one will respond!).
2731 memcpy (&peer_id.hashPubKey, &msg_ctx->key, sizeof (GNUNET_HashCode));
2732 if (GNUNET_NO == consider_peer (&peer_id))
2734 increment_stats ("# dht find peer requests ignored (do not need!)");
2735 GNUNET_free_non_null (other_hello);
2736 route_message (find_msg, msg_ctx);
2741 recent_hash = GNUNET_malloc (sizeof (GNUNET_HashCode));
2742 memcpy (recent_hash, &msg_ctx->key, sizeof (GNUNET_HashCode));
2743 if (GNUNET_SYSERR !=
2744 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2745 &msg_ctx->key, NULL,
2746 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2750 "Adding recent remove task for key `%s`!\n",
2751 GNUNET_h2s (&msg_ctx->key));
2753 /* Only add a task if there wasn't one for this key already! */
2754 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2755 (GNUNET_TIME_UNIT_SECONDS, 30),
2756 &remove_recent_find_peer, recent_hash);
2760 GNUNET_free (recent_hash);
2762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2763 "Received duplicate find peer request too soon!\n");
2767 /* Simplistic find_peer functionality, always return our hello */
2768 hello_size = ntohs (my_hello->size);
2769 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2771 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2773 GNUNET_break_op (0);
2774 GNUNET_free_non_null (other_hello);
2778 find_peer_result = GNUNET_malloc (tsize);
2779 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2780 find_peer_result->size = htons (tsize);
2781 memcpy (&find_peer_result[1], my_hello, hello_size);
2783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2784 "`%s': Sending hello size %d to requesting peer.\n", "DHT",
2788 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2789 memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2790 new_msg_ctx->peer = &my_identity;
2791 new_msg_ctx->bloom =
2792 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2793 new_msg_ctx->hop_count = 0;
2794 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make find peer requests a higher priority */
2795 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2796 increment_stats (STAT_FIND_PEER_ANSWER);
2797 if (GNUNET_DHT_RO_RECORD_ROUTE ==
2798 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2800 new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2801 new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2802 /* Assign to previous msg_ctx path history, caller should free after our return */
2803 new_msg_ctx->path_history = msg_ctx->path_history;
2805 route_result_message (find_peer_result, new_msg_ctx);
2806 GNUNET_free (new_msg_ctx);
2807 #if DEBUG_DHT_ROUTING
2808 if ((debug_routes) && (dhtlog_handle != NULL))
2810 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2811 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2815 GNUNET_free_non_null (other_hello);
2816 GNUNET_free (find_peer_result);
2817 route_message (find_msg, msg_ctx);
2821 * Task used to republish data.
2822 * Forward declaration; function call loop.
2824 * @param cls closure (a struct RepublishContext)
2825 * @param tc runtime context for this task
2828 republish_content (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2831 * Server handler for initiating local dht put requests
2833 * @param msg the actual put message
2834 * @param msg_ctx struct containing pertinent information about the request
2837 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2838 struct DHT_MessageContext *msg_ctx)
2840 const struct GNUNET_DHT_PutMessage *put_msg;
2841 struct DHTPutEntry *put_entry;
2842 unsigned int put_size;
2844 enum GNUNET_BLOCK_Type put_type;
2847 struct RepublishContext *put_context;
2848 GNUNET_HashCode key;
2849 struct DHTQueryRecord *record;
2851 GNUNET_assert (ntohs (msg->size) >= sizeof (struct GNUNET_DHT_PutMessage));
2853 put_msg = (const struct GNUNET_DHT_PutMessage *) msg;
2854 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2856 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2858 #if DEBUG_DHT_ROUTING
2859 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2861 /** Log routes that die due to high load! */
2862 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2863 msg_ctx->hop_count, GNUNET_SYSERR,
2864 &my_identity, &msg_ctx->key, msg_ctx->peer,
2872 ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2874 GNUNET_BLOCK_get_key (block_context, put_type, &put_msg[1], data_size,
2876 if (GNUNET_NO == ret)
2878 #if DEBUG_DHT_ROUTING
2879 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2881 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2882 msg_ctx->hop_count, GNUNET_SYSERR,
2883 &my_identity, &msg_ctx->key, msg_ctx->peer,
2888 GNUNET_break_op (0);
2891 if ((GNUNET_YES == ret) &&
2892 (0 != memcmp (&key, &msg_ctx->key, sizeof (GNUNET_HashCode))))
2894 #if DEBUG_DHT_ROUTING
2895 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2897 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2898 msg_ctx->hop_count, GNUNET_SYSERR,
2899 &my_identity, &msg_ctx->key, msg_ctx->peer,
2903 /* invalid wrapper: key mismatch! */
2904 GNUNET_break_op (0);
2907 /* ret == GNUNET_SYSERR means that there is no known relationship between
2908 * data and the key, so we cannot check it */
2910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2911 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2912 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2913 msg_ctx->unique_id);
2915 #if DEBUG_DHT_ROUTING
2916 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2918 if ((debug_routes) && (dhtlog_handle != NULL))
2920 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2921 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2927 // GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT 1\n");
2928 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2931 struct DHTRouteSource *pos;
2932 struct GNUNET_DHT_GetMessage *gmsg;
2935 // GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT 2\n");
2939 /* TODO: do only for local started requests? or also for remote peers? */
2940 /* TODO: include this in statistics? under what? */
2941 if (NULL == pos->client)
2944 gsize = data_size + sizeof(struct GNUNET_DHT_GetMessage);
2945 gmsg = GNUNET_malloc(gsize);
2946 gmsg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2947 gmsg->header.size = htons(gsize);
2948 gmsg->type = put_msg->type;
2949 memcpy(&gmsg[1], &put_msg[1], data_size);
2951 /* TODO: duplicate and reverse order of path_history? */
2952 send_reply_to_client (pos->client, &gmsg->header, msg_ctx);
2956 // GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT END\n");
2958 if (msg_ctx->closest != GNUNET_YES)
2960 route_message (msg, msg_ctx);
2965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2966 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2967 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2968 msg_ctx->unique_id);
2971 #if DEBUG_DHT_ROUTING
2972 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2974 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2975 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2976 &msg_ctx->key, msg_ctx->peer, NULL);
2979 if ((debug_routes) && (dhtlog_handle != NULL))
2981 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2982 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2987 increment_stats (STAT_PUTS_INSERTED);
2988 if (datacache != NULL)
2990 /* Put size is actual data size plus struct overhead plus path length (if any) */
2992 data_size + sizeof (struct DHTPutEntry) +
2993 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2994 put_entry = GNUNET_malloc (put_size);
2995 put_entry->data_size = data_size;
2996 put_entry->path_length = msg_ctx->path_history_len;
2997 /* Copy data to end of put entry */
2998 memcpy (&put_entry[1], &put_msg[1], data_size);
2999 if (msg_ctx->path_history_len > 0)
3001 /* Copy path after data */
3002 path_offset = (char *) &put_entry[1];
3003 path_offset += data_size;
3004 memcpy (path_offset, msg_ctx->path_history,
3005 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
3009 GNUNET_DATACACHE_put (datacache, &msg_ctx->key, put_size,
3010 (const char *) put_entry, put_type,
3011 GNUNET_TIME_absolute_ntoh (put_msg->expiration));
3012 GNUNET_free (put_entry);
3014 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
3016 put_context = GNUNET_malloc (sizeof (struct RepublishContext));
3017 memcpy (&put_context->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3018 put_context->type = put_type;
3019 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content,
3024 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3025 "`%s:%s': %s request received, but have no datacache!\n",
3026 my_short_id, "DHT", "PUT");
3028 if (stop_on_closest == GNUNET_NO)
3029 route_message (msg, msg_ctx);
3033 * Estimate the diameter of the network based
3034 * on how many buckets are currently in use.
3035 * Concept here is that the diameter of the network
3036 * is roughly the distance a message must travel in
3037 * order to reach its intended destination. Since
3038 * at each hop we expect to get one bit closer, and
3039 * we have one bit per bucket, the number of buckets
3040 * in use should be the largest number of hops for
3041 * a successful message. (of course, this assumes we
3042 * know all peers in the network!)
3044 * @return ballpark diameter figure
3047 estimate_diameter ()
3049 return MAX_BUCKETS - lowest_bucket;
3053 * To how many peers should we (on average)
3054 * forward the request to obtain the desired
3055 * target_replication count (on average).
3057 * returns: target_replication / (est. hops) + (target_replication * hop_count)
3058 * where est. hops is typically 2 * the routing table depth
3060 * @param hop_count number of hops the message has traversed
3061 * @param target_replication the number of total paths desired
3063 * @return Some number of peers to forward the message to
3066 get_forward_count (unsigned int hop_count, size_t target_replication)
3068 uint32_t random_value;
3069 unsigned int forward_count;
3071 unsigned int diameter;
3073 diameter = estimate_diameter ();
3075 if (GNUNET_NO == use_max_hops)
3076 max_hops = (diameter + 1) * 2;
3079 * If we are behaving in strict kademlia mode, send multiple initial requests,
3080 * but then only send to 1 or 0 peers based strictly on the number of hops.
3082 if (strict_kademlia == GNUNET_YES)
3085 return kademlia_replication;
3086 else if (hop_count < max_hops)
3092 /* FIXME: the smaller we think the network is the more lenient we should be for
3093 * routing right? The estimation below only works if we think we have reasonably
3094 * full routing tables, which for our RR topologies may not be the case!
3096 if (hop_count > max_hops)
3099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3100 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n",
3101 my_short_id, "DHT", estimate_diameter (), lowest_bucket);
3103 /* FIXME: does this work as intended, isn't the decision to forward or not made based on closeness as well? */
3104 if (GNUNET_YES == paper_forwarding) /* Once we have reached our ideal number of hops, don't stop forwarding! */
3112 if (GNUNET_YES == paper_forwarding)
3114 /* FIXME: re-run replication trials with this formula */
3116 1 + (target_replication - 1.0) / (diameter +
3117 ((float) (target_replication - 1.0) *
3119 /* Set forward count to floor of target_value */
3120 forward_count = (unsigned int) target_value;
3121 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
3122 target_value = target_value - forward_count;
3124 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
3126 if (random_value < (target_value * UINT32_MAX))
3134 target_replication / (diameter +
3135 ((float) target_replication * hop_count));
3136 if (target_value > 1)
3138 /* Set forward count to floor of target_value */
3139 forward_count = (unsigned int) target_value;
3140 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
3141 target_value = target_value - forward_count;
3145 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
3147 if (random_value < (target_value * UINT32_MAX))
3151 return forward_count;
3155 * Check whether my identity is closer than any known peers.
3156 * If a non-null bloomfilter is given, check if this is the closest
3157 * peer that hasn't already been routed to.
3159 * @param target hash code to check closeness to
3160 * @param bloom bloomfilter, exclude these entries from the decision
3162 * Return GNUNET_YES if node location is closest, GNUNET_NO
3166 am_closest_peer (const GNUNET_HashCode * target,
3167 struct GNUNET_CONTAINER_BloomFilter *bloom)
3173 struct PeerInfo *pos;
3174 unsigned int my_distance;
3176 if (0 == memcmp (&my_identity.hashPubKey, target, sizeof (GNUNET_HashCode)))
3179 bucket_num = find_current_bucket (target);
3181 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, target);
3182 my_distance = distance (&my_identity.hashPubKey, target);
3183 pos = k_buckets[bucket_num].head;
3185 while ((pos != NULL) && (count < bucket_size))
3187 if ((bloom != NULL) &&
3189 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
3192 continue; /* Skip already checked entries */
3195 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, target);
3196 if (other_bits > bits)
3198 else if (other_bits == bits) /* We match the same number of bits */
3200 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
3202 else if (distance (&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
3208 /* No peers closer, we are the closest! */
3214 * Return this peers adjusted value based on the convergence
3215 * function chosen. This is the key function for randomized
3216 * routing decisions.
3218 * @param target the key of the request
3219 * @param peer the peer we would like the value of
3220 * @param hops number of hops this message has already traveled
3222 * @return bit distance from target to peer raised to an exponent
3223 * adjusted based on the current routing convergence algorithm
3226 static unsigned long long
3227 converge_distance (const GNUNET_HashCode * target, struct PeerInfo *peer,
3230 unsigned long long ret;
3231 unsigned int other_matching_bits;
3232 double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
3233 double temp_modifier;
3239 curr_max_hops = max_hops;
3241 curr_max_hops = (estimate_diameter () + 1) * 2;
3243 if (converge_modifier > 0)
3244 temp_modifier = converge_modifier * base_converge_modifier;
3247 temp_modifier = base_converge_modifier;
3248 base_converge_modifier = 0.0;
3251 GNUNET_assert (temp_modifier > 0);
3253 other_matching_bits =
3254 GNUNET_CRYPTO_hash_matching_bits (target, &peer->id.hashPubKey);
3256 switch (converge_option)
3258 case DHT_CONVERGE_RANDOM:
3259 return 1; /* Always return 1, choose equally among all peers */
3260 case DHT_CONVERGE_LINEAR:
3261 calc_value = hops * curr_max_hops * temp_modifier;
3263 case DHT_CONVERGE_SQUARE:
3265 * Simple square based curve.
3268 (sqrt (hops) / sqrt (curr_max_hops)) * (curr_max_hops /
3272 case DHT_CONVERGE_EXPONENTIAL:
3274 * Simple exponential curve.
3276 if (base_converge_modifier > 0)
3277 calc_value = (temp_modifier * hops * hops) / curr_max_hops;
3279 calc_value = (hops * hops) / curr_max_hops;
3281 case DHT_CONVERGE_BINARY:
3283 * If below the cutoff, route randomly (return 1),
3284 * If above the cutoff, return the maximum possible
3285 * value first (always route to closest, because
3289 if (hops >= converge_modifier) /* Past cutoff */
3298 /* Take the log (base e) of the number of bits matching the other peer */
3299 exponent = log (other_matching_bits);
3301 /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
3302 if (exponent * calc_value >= 44.361419555836498)
3305 /* Clear errno and all math exceptions */
3307 feclearexcept (FE_ALL_EXCEPT);
3308 ret = (unsigned long long) pow (other_matching_bits, calc_value);
3310 fetestexcept (FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW | FE_UNDERFLOW))
3312 if (0 != fetestexcept (FE_OVERFLOW))
3313 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
3314 if (0 != fetestexcept (FE_INVALID))
3315 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
3316 if (0 != fetestexcept (FE_UNDERFLOW))
3317 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
3325 * Comparison function for two struct PeerInfo's
3326 * which have already had their matching bits to
3327 * some target calculated.
3329 * @param p1 a pointer pointer to a struct PeerInfo
3330 * @param p2 a pointer pointer to a struct PeerInfo
3332 * @return 0 if equidistant to target,
3333 * -1 if p1 is closer,
3337 compare_peers (const void *p1, const void *p2)
3339 struct PeerInfo **first = (struct PeerInfo **) p1;
3340 struct PeerInfo **second = (struct PeerInfo **) p2;
3342 if ((*first)->matching_bits > (*second)->matching_bits)
3344 if ((*first)->matching_bits < (*second)->matching_bits)
3352 * Select a peer from the routing table that would be a good routing
3353 * destination for sending a message for "target". The resulting peer
3354 * must not be in the set of blocked peers.<p>
3356 * Note that we should not ALWAYS select the closest peer to the
3357 * target, peers further away from the target should be chosen with
3358 * exponentially declining probability.
3360 * @param target the key we are selecting a peer to route to
3361 * @param bloom a bloomfilter containing entries this request has seen already
3362 * @param hops how many hops has this message traversed thus far
3364 * @return Peer to route to, or NULL on error
3366 static struct PeerInfo *
3367 select_peer (const GNUNET_HashCode * target,
3368 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3373 unsigned int offset;
3375 struct PeerInfo *pos;
3376 struct PeerInfo *sorted_closest[bucket_size];
3377 unsigned long long temp_converge_distance;
3378 unsigned long long total_distance;
3379 unsigned long long selected;
3382 unsigned long long stats_total_distance;
3386 unsigned int distance;
3387 unsigned int largest_distance;
3388 struct PeerInfo *chosen;
3391 /** If we are doing kademlia routing, or converge is binary (saves some cycles) */
3392 if ((strict_kademlia == GNUNET_YES) ||
3393 ((converge_option == DHT_CONVERGE_BINARY) && (hops >= converge_modifier)))
3395 largest_distance = 0;
3397 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3399 pos = k_buckets[bc].head;
3401 while ((pos != NULL) && (count < bucket_size))
3403 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3405 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3407 distance = inverse_distance (target, &pos->id.hashPubKey);
3408 if (distance > largest_distance)
3411 largest_distance = distance;
3419 if ((largest_distance > 0) && (chosen != NULL))
3421 GNUNET_CONTAINER_bloomfilter_add (bloom, &chosen->id.hashPubKey);
3432 /* Three steps: order peers in closest bucket (most matching bits).
3433 * Then go over all LOWER buckets (matching same bits we do)
3434 * Then go over all HIGHER buckets (matching less then we do)
3437 closest_bucket = find_current_bucket (target);
3438 GNUNET_assert (closest_bucket >= lowest_bucket);
3439 pos = k_buckets[closest_bucket].head;
3441 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3442 memset (sorted_closest, 0, sizeof (sorted_closest));
3443 /* Put any peers in the closest bucket in the sorting array */
3444 while ((pos != NULL) && (count < bucket_size))
3447 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3451 continue; /* Ignore bloomfiltered peers */
3453 pos->matching_bits =
3454 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, target);
3455 sorted_closest[offset] = pos;
3461 /* Sort the peers in descending order */
3462 qsort (&sorted_closest[0], offset, sizeof (struct PeerInfo *),
3465 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3466 for (i = 0; i < offset; i++)
3468 temp_converge_distance =
3469 converge_distance (target, sorted_closest[i], hops);
3471 GNUNET_CONTAINER_bloomfilter_test (bloom,
3472 &sorted_closest[i]->id.hashPubKey))
3473 break; /* Ignore bloomfiltered peers */
3474 if (total_distance + temp_converge_distance > total_distance) /* Handle largest case and overflow */
3475 total_distance += temp_converge_distance;
3477 break; /* overflow case */
3480 /* Now handle peers in lower buckets (matches same # of bits as target) */
3481 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3483 pos = k_buckets[bc].head;
3485 while ((pos != NULL) && (count < bucket_size))
3488 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3492 continue; /* Ignore bloomfiltered peers */
3494 temp_converge_distance = converge_distance (target, pos, hops);
3495 if (total_distance + temp_converge_distance > total_distance) /* Handle largest case and overflow */
3496 total_distance += temp_converge_distance;
3498 break; /* overflow case */
3504 /* Now handle all the further away peers */
3505 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3507 pos = k_buckets[bc].head;
3509 while ((pos != NULL) && (count < bucket_size))
3512 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3516 continue; /* Ignore bloomfiltered peers */
3518 temp_converge_distance = converge_distance (target, pos, hops);
3519 if (total_distance + temp_converge_distance > total_distance) /* Handle largest case and overflow */
3520 total_distance += temp_converge_distance;
3522 break; /* overflow case */
3528 if (total_distance == 0) /* No peers to select from! */
3530 increment_stats ("# failed to select peer");
3534 #if DEBUG_DHT_ROUTING > 1
3537 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3538 stats_total_distance = 0;
3539 for (i = 0; i < offset; i++)
3542 GNUNET_CONTAINER_bloomfilter_test (bloom,
3543 &sorted_closest[i]->id.hashPubKey))
3544 break; /* Ignore bloomfiltered peers */
3545 temp_converge_distance =
3546 converge_distance (target, sorted_closest[i], hops);
3547 if (stats_total_distance + temp_converge_distance > stats_total_distance) /* Handle largest case and overflow */
3548 stats_total_distance += temp_converge_distance;
3550 break; /* overflow case */
3551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3552 "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n",
3553 GNUNET_CRYPTO_hash_matching_bits (&sorted_closest[i]->id.
3554 hashPubKey, target),
3555 GNUNET_CRYPTO_hash_matching_bits (&sorted_closest[i]->id.
3557 &my_identity.hashPubKey),
3558 (temp_converge_distance / (double) total_distance) * 100,
3559 temp_converge_distance);
3562 /* Now handle peers in lower buckets (matches same # of bits as target) */
3563 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3565 pos = k_buckets[bc].head;
3567 while ((pos != NULL) && (count < bucket_size))
3570 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3574 continue; /* Ignore bloomfiltered peers */
3576 temp_converge_distance = converge_distance (target, pos, hops);
3577 if (stats_total_distance + temp_converge_distance > stats_total_distance) /* Handle largest case and overflow */
3578 stats_total_distance += temp_converge_distance;
3580 break; /* overflow case */
3581 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3582 "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n",
3583 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
3585 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
3586 &my_identity.hashPubKey),
3587 (temp_converge_distance / (double) total_distance) * 100,
3588 temp_converge_distance);
3594 /* Now handle all the further away peers */
3595 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3597 pos = k_buckets[bc].head;
3599 while ((pos != NULL) && (count < bucket_size))
3602 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3606 continue; /* Ignore bloomfiltered peers */
3608 temp_converge_distance = converge_distance (target, pos, hops);
3609 if (stats_total_distance + temp_converge_distance > stats_total_distance) /* Handle largest case and overflow */
3610 stats_total_distance += temp_converge_distance;
3612 break; /* overflow case */
3613 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3614 "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n",
3615 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
3617 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
3618 &my_identity.hashPubKey),
3619 (temp_converge_distance / (double) total_distance) * 100,
3620 temp_converge_distance);
3625 /* END PRINT STATS */
3628 /* Now actually choose a peer */
3630 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3632 /* Go over closest sorted peers. */
3633 for (i = 0; i < offset; i++)
3636 GNUNET_CONTAINER_bloomfilter_test (bloom,
3637 &sorted_closest[i]->id.hashPubKey))
3638 break; /* Ignore bloomfiltered peers */
3639 temp_converge_distance =
3640 converge_distance (target, sorted_closest[i], hops);
3641 if (temp_converge_distance >= selected)
3642 return sorted_closest[i];
3644 selected -= temp_converge_distance;
3647 /* Now handle peers in lower buckets (matches same # of bits as target) */
3648 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3650 pos = k_buckets[bc].head;
3652 while ((pos != NULL) && (count < bucket_size))
3655 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3659 continue; /* Ignore bloomfiltered peers */
3661 temp_converge_distance = converge_distance (target, pos, hops);
3662 if (temp_converge_distance >= selected)
3665 selected -= temp_converge_distance;
3671 /* Now handle all the further away peers */
3672 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3674 pos = k_buckets[bc].head;
3676 while ((pos != NULL) && (count < bucket_size))
3679 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3683 continue; /* Ignore bloomfiltered peers */
3685 temp_converge_distance = converge_distance (target, pos, hops);
3686 if (temp_converge_distance >= selected)
3689 selected -= temp_converge_distance;
3695 increment_stats ("# failed to select peer");
3701 * Task used to remove recent entries, either
3702 * after timeout, when full, or on shutdown.
3704 * @param cls the entry to remove
3705 * @param tc context, reason, etc.
3708 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3710 struct RecentRequest *req = cls;
3711 static GNUNET_HashCode hash;
3713 GNUNET_assert (req != NULL);
3714 hash_from_uid (req->uid, &hash);
3715 GNUNET_assert (GNUNET_YES ==
3716 GNUNET_CONTAINER_multihashmap_remove (recent.hashmap, &hash,
3718 GNUNET_CONTAINER_heap_remove_node (req->heap_node);
3719 GNUNET_CONTAINER_bloomfilter_free (req->bloom);
3723 * if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3725 * GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3726 * GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3732 * Remember this routing request so that if a reply is
3733 * received we can either forward it to the correct peer
3734 * or return the result locally.
3736 * @param msg_ctx Context of the route request
3738 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3741 cache_response (struct DHT_MessageContext *msg_ctx)
3743 struct DHTQueryRecord *record;
3744 struct DHTRouteSource *source_info;
3745 struct DHTRouteSource *pos;
3746 struct GNUNET_TIME_Absolute now;
3747 unsigned int current_size;
3749 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3751 #if DELETE_WHEN_FULL
3752 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3754 source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3755 GNUNET_assert (source_info != NULL);
3756 record = source_info->record;
3757 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3758 if (record->head == NULL) /* No more entries in DLL */
3760 GNUNET_assert (GNUNET_YES ==
3761 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
3764 GNUNET_free (record);
3766 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3768 GNUNET_SCHEDULER_cancel (source_info->delete_task);
3769 source_info->delete_task = GNUNET_SCHEDULER_NO_TASK;
3771 if (source_info->find_peers_responded != NULL)
3772 GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
3773 GNUNET_free (source_info);
3774 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3777 /** Non-local request and have too many outstanding forwards, discard! */
3778 if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3781 now = GNUNET_TIME_absolute_get ();
3783 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
3784 if (record != NULL) /* Already know this request! */
3790 memcmp (msg_ctx->peer, &pos->source,
3791 sizeof (struct GNUNET_PeerIdentity)))
3792 break; /* Already have this peer in reply list! */
3795 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3797 GNUNET_CONTAINER_heap_update_cost (forward_list.minHeap, pos->hnode,
3804 record = GNUNET_malloc (sizeof (struct DHTQueryRecord));
3805 GNUNET_assert (GNUNET_OK ==
3806 GNUNET_CONTAINER_multihashmap_put (forward_list.hashmap,
3807 &msg_ctx->key, record,
3808 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3809 memcpy (&record->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3812 source_info = GNUNET_malloc (sizeof (struct DHTRouteSource));
3813 source_info->record = record;
3814 source_info->delete_task =
3815 GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry,
3817 source_info->find_peers_responded =
3818 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3819 memcpy (&source_info->source, msg_ctx->peer,
3820 sizeof (struct GNUNET_PeerIdentity));
3821 GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail,
3823 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3825 source_info->client = msg_ctx->client;
3826 now = GNUNET_TIME_absolute_get_forever ();
3828 source_info->hnode =
3829 GNUNET_CONTAINER_heap_insert (forward_list.minHeap, source_info,
3832 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3833 "`%s:%s': Created new forward source info for %s uid %llu\n",
3834 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3835 msg_ctx->unique_id);
3842 * Main function that handles whether or not to route a message to other
3845 * @param msg the message to be routed
3846 * @param msg_ctx the context containing all pertinent information about the message
3849 route_message (const struct GNUNET_MessageHeader *msg,
3850 struct DHT_MessageContext *msg_ctx)
3853 struct PeerInfo *selected;
3855 #if DEBUG_DHT_ROUTING > 1
3856 struct PeerInfo *nearest;
3858 unsigned int target_forward_count;
3859 unsigned int forward_count;
3860 struct RecentRequest *recent_req;
3861 GNUNET_HashCode unique_hash;
3862 char *stat_forward_count;
3863 char *temp_stat_str;
3865 #if DEBUG_DHT_ROUTING
3869 if (malicious_dropper == GNUNET_YES)
3871 #if DEBUG_DHT_ROUTING
3872 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3874 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3875 msg_ctx->hop_count, GNUNET_SYSERR,
3876 &my_identity, &msg_ctx->key, msg_ctx->peer,
3880 if (msg_ctx->bloom != NULL)
3882 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3883 msg_ctx->bloom = NULL;
3888 increment_stats (STAT_ROUTES);
3889 target_forward_count =
3890 get_forward_count (msg_ctx->hop_count, msg_ctx->replication);
3891 GNUNET_asprintf (&stat_forward_count, "# forward counts of %d",
3892 target_forward_count);
3893 increment_stats (stat_forward_count);
3894 GNUNET_free (stat_forward_count);
3895 if (msg_ctx->bloom == NULL)
3897 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3899 if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) &&
3900 (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3901 target_forward_count = 0;
3904 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3905 * any closer peers (which is being checked for below). Since we are doing recursive
3906 * routing we have no choice but to stop forwarding in this case. This means that at
3907 * any given step the request may NOT be forwarded to alpha peers (because routes will
3908 * stop and the parallel route will not be aware of it). Of course, assuming that we
3909 * have fulfilled the Kademlia requirements for routing table fullness this will never
3910 * ever ever be a problem.
3912 * However, is this fair?
3914 * Since we use these requests to build our routing tables (and we build them in the
3915 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3916 * routing tables still get constructed.
3918 if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) &&
3919 (msg_ctx->hop_count > 0) &&
3920 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3921 target_forward_count = 0;
3924 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3925 hash_from_uid (msg_ctx->unique_id, &unique_hash);
3927 GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3930 GNUNET_CONTAINER_multihashmap_get (recent.hashmap, &unique_hash);
3931 GNUNET_assert (recent_req != NULL);
3932 if (0 != memcmp (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode)))
3933 increment_stats (STAT_DUPLICATE_UID);
3936 increment_stats (STAT_RECENT_SEEN);
3937 GNUNET_CONTAINER_bloomfilter_or2 (msg_ctx->bloom, recent_req->bloom,
3943 recent_req = GNUNET_malloc (sizeof (struct RecentRequest));
3944 recent_req->uid = msg_ctx->unique_id;
3945 memcpy (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3946 recent_req->remove_task =
3947 GNUNET_SCHEDULER_add_delayed (DEFAULT_RECENT_REMOVAL, &remove_recent,
3949 recent_req->heap_node =
3950 GNUNET_CONTAINER_heap_insert (recent.minHeap, recent_req,
3951 GNUNET_TIME_absolute_get ().abs_value);
3953 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3954 GNUNET_CONTAINER_multihashmap_put (recent.hashmap, &unique_hash, recent_req,
3955 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3958 if (GNUNET_CONTAINER_multihashmap_size (recent.hashmap) > DHT_MAX_RECENT)
3960 recent_req = GNUNET_CONTAINER_heap_peek (recent.minHeap);
3961 GNUNET_assert (recent_req != NULL);
3962 GNUNET_SCHEDULER_cancel (recent_req->remove_task);
3963 GNUNET_SCHEDULER_add_now (&remove_recent, recent_req);
3967 for (i = 0; i < target_forward_count; i++)
3969 selected = select_peer (&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3971 if (selected != NULL)
3974 if (GNUNET_CRYPTO_hash_matching_bits
3975 (&selected->id.hashPubKey,
3977 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
3979 GNUNET_asprintf (&temp_stat_str,
3980 "# requests routed to close(r) peer hop %u",
3981 msg_ctx->hop_count);
3983 GNUNET_asprintf (&temp_stat_str,
3984 "# requests routed to less close peer hop %u",
3985 msg_ctx->hop_count);
3986 if (temp_stat_str != NULL)
3988 increment_stats (temp_stat_str);
3989 GNUNET_free (temp_stat_str);
3991 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
3992 &selected->id.hashPubKey);
3993 #if DEBUG_DHT_ROUTING > 1
3994 nearest = find_closest_peer (&msg_ctx->key);
3995 nearest_buf = GNUNET_strdup (GNUNET_i2s (&nearest->id));
3996 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3997 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n",
3998 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3999 msg_ctx->unique_id, GNUNET_i2s (&selected->id), nearest_buf,
4000 GNUNET_CRYPTO_hash_matching_bits (&nearest->id.hashPubKey,
4002 distance (&nearest->id.hashPubKey, msg_ctx->key));
4003 GNUNET_free (nearest_buf);
4005 #if DEBUG_DHT_ROUTING
4006 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4008 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
4009 msg_ctx->hop_count, GNUNET_NO,
4010 &my_identity, &msg_ctx->key, msg_ctx->peer,
4014 forward_message (msg, selected, msg_ctx);
4018 if (msg_ctx->bloom != NULL)
4020 GNUNET_CONTAINER_bloomfilter_or2 (recent_req->bloom, msg_ctx->bloom,
4022 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4023 msg_ctx->bloom = NULL;
4026 #if DEBUG_DHT_ROUTING
4027 if (forward_count == 0)
4028 ret = GNUNET_SYSERR;
4032 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4034 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
4035 msg_ctx->hop_count, ret, &my_identity,
4036 &msg_ctx->key, msg_ctx->peer, NULL);
4044 * Main function that handles whether or not to route a message to other
4047 * @param msg the message to be routed
4048 * @param msg_ctx the context containing all pertinent information about the message
4051 demultiplex_message (const struct GNUNET_MessageHeader *msg,
4052 struct DHT_MessageContext *msg_ctx)
4054 /* FIXME: Should we use closest excluding those we won't route to (the bloomfilter problem)? */
4055 msg_ctx->closest = am_closest_peer (&msg_ctx->key, msg_ctx->bloom);
4057 switch (ntohs (msg->type))
4059 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
4060 cache_response (msg_ctx);
4061 handle_dht_get (msg, msg_ctx);
4063 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
4064 increment_stats (STAT_PUTS);
4065 handle_dht_put (msg, msg_ctx);
4067 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
4068 increment_stats (STAT_FIND_PEER);
4069 if (((msg_ctx->hop_count > 0) &&
4071 memcmp (msg_ctx->peer, &my_identity,
4072 sizeof (struct GNUNET_PeerIdentity)))) ||
4073 (msg_ctx->client != NULL))
4075 cache_response (msg_ctx);
4076 if ((msg_ctx->closest == GNUNET_YES) ||
4077 (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
4078 handle_dht_find_peer (msg, msg_ctx);
4081 route_message (msg, msg_ctx);
4082 #if DEBUG_DHT_ROUTING
4083 if (msg_ctx->hop_count == 0) /* Locally initiated request */
4085 if ((debug_routes) && (dhtlog_handle != NULL))
4087 dhtlog_handle->insert_dhtkey (NULL, &msg_ctx->key);
4088 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
4089 msg_ctx->hop_count, GNUNET_NO,
4090 &my_identity, &msg_ctx->key);
4096 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4097 "`%s': Message type (%d) not handled, forwarding anyway!\n",
4098 "DHT", ntohs (msg->type));
4099 route_message (msg, msg_ctx);
4107 * Iterator for local get request results,
4109 * @param cls closure for iterator, NULL
4110 * @param exp when does this value expire?
4111 * @param key the key this data is stored under
4112 * @param size the size of the data identified by key
4113 * @param data the actual data
4114 * @param type the type of the data
4116 * @return GNUNET_OK to continue iteration, anything else
4117 * to stop iteration.
4120 republish_content_iterator (void *cls, struct GNUNET_TIME_Absolute exp,
4121 const GNUNET_HashCode * key, size_t size,
4122 const char *data, uint32_t type)
4125 struct DHT_MessageContext *new_msg_ctx;
4126 struct GNUNET_DHT_PutMessage *put_msg;
4129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4130 "`%s:%s': Received `%s' response from datacache\n", my_short_id,
4133 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
4135 put_msg = GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
4136 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
4137 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
4138 put_msg->expiration = GNUNET_TIME_absolute_hton (exp);
4139 put_msg->type = htons (type);
4140 memcpy (&put_msg[1], data, size);
4141 new_msg_ctx->unique_id =
4142 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
4143 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
4144 new_msg_ctx->replication = ntohl (DEFAULT_PUT_REPLICATION);
4145 new_msg_ctx->msg_options = ntohl (0);
4146 new_msg_ctx->network_size = estimate_diameter ();
4147 new_msg_ctx->peer = &my_identity;
4148 new_msg_ctx->bloom =
4149 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4150 new_msg_ctx->hop_count = 0;
4151 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4152 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4153 increment_stats (STAT_PUT_START);
4154 demultiplex_message (&put_msg->header, new_msg_ctx);
4156 GNUNET_free (new_msg_ctx);
4157 GNUNET_free (put_msg);
4162 * Task used to republish data.
4164 * @param cls closure (a struct RepublishContext)
4165 * @param tc runtime context for this task
4168 republish_content (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4170 struct RepublishContext *put_context = cls;
4172 unsigned int results;
4174 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4176 GNUNET_free (put_context);
4180 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
4182 GNUNET_DATACACHE_get (datacache, &put_context->key, put_context->type,
4183 &republish_content_iterator, NULL);
4184 if (results == 0) /* Data must have expired */
4185 GNUNET_free (put_context);
4186 else /* Reschedule task for next time period */
4187 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content,
4194 * Iterator over hash map entries.
4196 * @param cls client to search for in source routes
4197 * @param key current key code (ignored)
4198 * @param value value in the hash map, a DHTQueryRecord
4199 * @return GNUNET_YES if we should continue to
4204 find_client_records (void *cls, const GNUNET_HashCode * key, void *value)
4206 struct ClientList *client = cls;
4207 struct DHTQueryRecord *record = value;
4208 struct DHTRouteSource *pos;
4213 if (pos->client == client)
4219 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, pos);
4220 GNUNET_CONTAINER_heap_remove_node (pos->hnode);
4221 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
4223 GNUNET_SCHEDULER_cancel (pos->delete_task);
4224 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4226 if (pos->find_peers_responded != NULL)
4227 GNUNET_CONTAINER_bloomfilter_free (pos->find_peers_responded);
4230 if (record->head == NULL) /* No more entries in DLL */
4232 GNUNET_assert (GNUNET_YES ==
4233 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
4234 &record->key, record));
4235 GNUNET_free (record);
4241 * Functions with this signature are called whenever a client
4242 * is disconnected on the network level.
4244 * @param cls closure (NULL for dht)
4245 * @param client identification of the client; NULL
4246 * for the last call when the server is destroyed
4249 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
4251 struct ClientList *pos = client_list;
4252 struct ClientList *prev;
4253 struct ClientList *found;
4254 struct PendingMessage *reply;
4260 if (pos->client_handle == client)
4263 prev->next = pos->next;
4265 client_list = pos->next;
4275 if (found->transmit_handle != NULL)
4276 GNUNET_CONNECTION_notify_transmit_ready_cancel (found->transmit_handle);
4278 while (NULL != (reply = found->pending_head))
4280 GNUNET_CONTAINER_DLL_remove (found->pending_head, found->pending_tail,
4282 GNUNET_free (reply);
4284 GNUNET_CONTAINER_multihashmap_iterate (forward_list.hashmap,
4285 &find_client_records, found);
4286 GNUNET_free (found);
4291 * Find a client if it exists, add it otherwise.
4293 * @param client the server handle to the client
4295 * @return the client if found, a new client otherwise
4297 static struct ClientList *
4298 find_active_client (struct GNUNET_SERVER_Client *client)
4300 struct ClientList *pos = client_list;
4301 struct ClientList *ret;
4305 if (pos->client_handle == client)
4310 ret = GNUNET_malloc (sizeof (struct ClientList));
4311 ret->client_handle = client;
4312 ret->next = client_list;
4320 * Task to send a malicious put message across the network.
4322 * @param cls closure for this task
4323 * @param tc the context under which the task is running
4326 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4328 static struct GNUNET_DHT_PutMessage put_message;
4329 static struct DHT_MessageContext msg_ctx;
4330 static GNUNET_HashCode key;
4331 uint32_t random_key;
4333 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4335 put_message.header.size = htons (sizeof (struct GNUNET_DHT_PutMessage));
4336 put_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
4337 put_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
4338 put_message.expiration =
4339 GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_forever ());
4340 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4342 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
4343 GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
4344 memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
4346 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
4347 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
4348 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
4349 msg_ctx.msg_options = ntohl (0);
4350 msg_ctx.network_size = estimate_diameter ();
4351 msg_ctx.peer = &my_identity;
4352 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
4353 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4354 #if DEBUG_DHT_ROUTING
4355 if (dhtlog_handle != NULL)
4356 dhtlog_handle->insert_dhtkey (NULL, &key);
4358 increment_stats (STAT_PUT_START);
4359 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4360 "%s:%s Sending malicious PUT message with hash %s\n", my_short_id,
4361 "DHT", GNUNET_h2s (&key));
4362 demultiplex_message (&put_message.header, &msg_ctx);
4363 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4364 (GNUNET_TIME_UNIT_MILLISECONDS,
4365 malicious_put_frequency), &malicious_put_task,
4371 * Task to send a malicious put message across the network.
4373 * @param cls closure for this task
4374 * @param tc the context under which the task is running
4377 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4379 static struct GNUNET_DHT_GetMessage get_message;
4380 struct DHT_MessageContext msg_ctx;
4381 static GNUNET_HashCode key;
4382 uint32_t random_key;
4384 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4387 get_message.header.size = htons (sizeof (struct GNUNET_DHT_GetMessage));
4388 get_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET);
4389 get_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
4390 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4392 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
4393 GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
4394 memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
4396 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
4397 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
4398 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
4399 msg_ctx.msg_options = ntohl (0);
4400 msg_ctx.network_size = estimate_diameter ();
4401 msg_ctx.peer = &my_identity;
4402 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
4403 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4404 #if DEBUG_DHT_ROUTING
4405 if (dhtlog_handle != NULL)
4406 dhtlog_handle->insert_dhtkey (NULL, &key);
4408 increment_stats (STAT_GET_START);
4409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4410 "%s:%s Sending malicious GET message with hash %s\n", my_short_id,
4411 "DHT", GNUNET_h2s (&key));
4412 demultiplex_message (&get_message.header, &msg_ctx);
4413 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
4414 (GNUNET_TIME_UNIT_MILLISECONDS,
4415 malicious_get_frequency), &malicious_get_task,
4422 * Iterator over hash map entries.
4424 * @param cls closure
4425 * @param key current key code
4426 * @param value value in the hash map
4427 * @return GNUNET_YES if we should continue to
4432 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
4434 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
4436 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
4441 * Task to send a find peer message for our own peer identifier
4442 * so that we can find the closest peers in the network to ourselves
4443 * and attempt to connect to them.
4445 * @param cls closure for this task
4446 * @param tc the context under which the task is running
4449 send_find_peer_message (void *cls,
4450 const struct GNUNET_SCHEDULER_TaskContext *tc)
4452 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
4453 struct DHT_MessageContext msg_ctx;
4454 struct GNUNET_TIME_Relative next_send_time;
4455 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
4458 struct GNUNET_TIME_Relative time_diff;
4459 struct GNUNET_TIME_Absolute end;
4461 double count_per_interval;
4463 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
4466 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! */
4468 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4469 "Have %d newly found peers since last find peer message sent!\n",
4471 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
4472 &send_find_peer_message, NULL);
4473 newly_found_peers = 0;
4477 increment_stats (STAT_FIND_PEER_START);
4479 end = GNUNET_TIME_absolute_get ();
4481 GNUNET_TIME_absolute_get_difference (find_peer_context.start, end);
4483 if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
4485 multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
4486 count_per_interval = find_peer_context.count / multiplier;
4490 multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
4491 count_per_interval = find_peer_context.count * multiplier;
4495 #if FIND_PEER_WITH_HELLO
4497 GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage) +
4498 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *)
4500 find_peer_msg->header.size =
4501 htons (sizeof (struct GNUNET_DHT_FindPeerMessage) +
4502 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
4503 memcpy (&find_peer_msg[1], my_hello,
4504 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
4506 find_peer_msg = GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage));
4507 find_peer_msg->header.size =
4508 htons (sizeof (struct GNUNET_DHT_FindPeerMessage));
4510 find_peer_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4512 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4513 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
4515 GNUNET_assert (GNUNET_OK ==
4516 GNUNET_CONTAINER_bloomfilter_get_raw_data (temp_bloom,
4520 GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
4521 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4522 memcpy (&msg_ctx.key, &my_identity.hashPubKey, sizeof (GNUNET_HashCode));
4524 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
4525 (GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX));
4526 msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4527 msg_ctx.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4528 msg_ctx.network_size = estimate_diameter ();
4529 msg_ctx.peer = &my_identity;
4530 msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4531 msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4533 demultiplex_message (&find_peer_msg->header, &msg_ctx);
4534 GNUNET_free (find_peer_msg);
4535 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4536 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id,
4537 "DHT", "FIND PEER");
4538 if (newly_found_peers < bucket_size)
4540 next_send_time.rel_value =
4541 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4542 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
4543 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4547 next_send_time.rel_value =
4548 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4549 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
4550 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value -
4551 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4554 GNUNET_assert (next_send_time.rel_value != 0);
4555 find_peer_context.count = 0;
4556 newly_found_peers = 0;
4557 find_peer_context.start = GNUNET_TIME_absolute_get ();
4558 if (GNUNET_YES == do_find_peer)
4560 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
4566 * Handler for any generic DHT messages, calls the appropriate handler
4567 * depending on message type, sends confirmation if responses aren't otherwise
4570 * @param cls closure for the service
4571 * @param client the client we received this message from
4572 * @param message the actual message received
4575 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4576 const struct GNUNET_MessageHeader *message)
4578 const struct GNUNET_DHT_RouteMessage *dht_msg =
4579 (const struct GNUNET_DHT_RouteMessage *) message;
4580 const struct GNUNET_MessageHeader *enc_msg;
4581 struct DHT_MessageContext msg_ctx;
4583 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4585 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4586 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4587 my_short_id, "DHT", "GENERIC", ntohs (message->type),
4588 GNUNET_h2s (&dht_msg->key), GNUNET_ntohll (dht_msg->unique_id));
4590 #if DEBUG_DHT_ROUTING
4591 if (dhtlog_handle != NULL)
4592 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4595 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4596 msg_ctx.client = find_active_client (client);
4597 memcpy (&msg_ctx.key, &dht_msg->key, sizeof (GNUNET_HashCode));
4598 msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4599 msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
4600 msg_ctx.msg_options = ntohl (dht_msg->options);
4601 if (GNUNET_DHT_RO_RECORD_ROUTE ==
4602 (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
4604 msg_ctx.path_history = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
4605 memcpy (msg_ctx.path_history, &my_identity,
4606 sizeof (struct GNUNET_PeerIdentity));
4607 msg_ctx.path_history_len = 1;
4609 msg_ctx.network_size = estimate_diameter ();
4610 msg_ctx.peer = &my_identity; /* FIXME bart NULL? Fix doxygen? */
4611 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
4612 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4614 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4615 increment_stats (STAT_GET_START);
4616 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4617 increment_stats (STAT_PUT_START);
4618 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4619 increment_stats (STAT_FIND_PEER_START);
4621 if (GNUNET_YES == malicious_dropper)
4623 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4625 #if DEBUG_DHT_ROUTING
4626 if ((debug_routes) && (dhtlog_handle != NULL))
4628 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_GET,
4629 msg_ctx.hop_count, GNUNET_NO, &my_identity,
4634 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4636 #if DEBUG_DHT_ROUTING
4637 if ((debug_routes) && (dhtlog_handle != NULL))
4639 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_PUT,
4640 msg_ctx.hop_count, GNUNET_NO, &my_identity,
4645 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4646 GNUNET_free_non_null (msg_ctx.path_history);
4650 demultiplex_message (enc_msg, &msg_ctx);
4651 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4656 * Handler for any locally received DHT control messages,
4657 * sets malicious flags mostly for now.
4659 * @param cls closure for the service
4660 * @param client the client we received this message from
4661 * @param message the actual message received
4665 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4666 const struct GNUNET_MessageHeader *message)
4668 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4669 (const struct GNUNET_DHT_ControlMessage *) message;
4672 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4673 "`%s:%s': Received `%s' request from client, command %d\n",
4674 my_short_id, "DHT", "CONTROL", ntohs (dht_control_msg->command));
4677 switch (ntohs (dht_control_msg->command))
4679 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4681 "Sending self seeking find peer request!\n");
4682 GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
4685 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4686 if (ntohs (dht_control_msg->variable) > 0)
4687 malicious_get_frequency = ntohs (dht_control_msg->variable);
4688 if (malicious_get_frequency == 0)
4689 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4690 if (malicious_getter != GNUNET_YES)
4691 GNUNET_SCHEDULER_add_now (&malicious_get_task, NULL);
4692 malicious_getter = GNUNET_YES;
4693 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4694 "%s:%s Initiating malicious GET behavior, frequency %d\n",
4695 my_short_id, "DHT", malicious_get_frequency);
4697 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4698 if (ntohs (dht_control_msg->variable) > 0)
4699 malicious_put_frequency = ntohs (dht_control_msg->variable);
4700 if (malicious_put_frequency == 0)
4701 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4702 if (malicious_putter != GNUNET_YES)
4703 GNUNET_SCHEDULER_add_now (&malicious_put_task, NULL);
4704 malicious_putter = GNUNET_YES;
4705 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4706 "%s:%s Initiating malicious PUT behavior, frequency %d\n",
4707 my_short_id, "DHT", malicious_put_frequency);
4709 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4710 #if DEBUG_DHT_ROUTING
4711 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4712 dhtlog_handle->set_malicious (&my_identity);
4714 malicious_dropper = GNUNET_YES;
4715 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4716 "%s:%s Initiating malicious DROP behavior\n", my_short_id,
4721 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4722 "%s:%s Unknown control command type `%d'!\n", my_short_id,
4723 "DHT", ntohs (dht_control_msg->command));
4727 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4731 * Handler for any generic DHT stop messages, calls the appropriate handler
4732 * depending on message type (if processed locally)
4734 * @param cls closure for the service
4735 * @param client the client we received this message from
4736 * @param message the actual message received
4740 handle_dht_local_route_stop (void *cls, struct GNUNET_SERVER_Client *client,
4741 const struct GNUNET_MessageHeader *message)
4744 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4745 (const struct GNUNET_DHT_StopMessage *) message;
4746 struct DHTQueryRecord *record;
4747 struct DHTRouteSource *pos;
4750 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4751 "`%s:%s': Received `%s' request from client, uid %llu\n",
4752 my_short_id, "DHT", "GENERIC STOP",
4753 GNUNET_ntohll (dht_stop_msg->unique_id));
4756 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap,
4757 &dht_stop_msg->key);
4764 /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
4765 if ((pos->client != NULL) && (pos->client->client_handle == client))
4767 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
4768 GNUNET_SCHEDULER_cancel (pos->delete_task);
4770 GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
4776 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4781 * Core handler for p2p route requests.
4783 * @param cls closure
4784 * @param message message
4785 * @param peer peer identity this notification is about
4786 * @param atsi performance data
4790 handle_dht_p2p_route_request (void *cls, const struct GNUNET_PeerIdentity *peer,
4791 const struct GNUNET_MessageHeader *message,
4792 const struct GNUNET_TRANSPORT_ATS_Information
4796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4797 "`%s:%s': Received P2P request from peer %s\n", my_short_id,
4798 "DHT", GNUNET_i2s (peer));
4800 struct GNUNET_DHT_P2PRouteMessage *incoming =
4801 (struct GNUNET_DHT_P2PRouteMessage *) message;
4802 struct GNUNET_MessageHeader *enc_msg =
4803 (struct GNUNET_MessageHeader *) &incoming[1];
4804 struct DHT_MessageContext *msg_ctx;
4808 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply) */
4811 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n",
4812 my_short_id, "DHT");
4817 if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4819 GNUNET_break_op (0);
4823 if (malicious_dropper == GNUNET_YES)
4825 #if DEBUG_DHT_ROUTING
4826 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4828 /** Log routes that die due to high load! */
4829 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4830 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4831 GNUNET_SYSERR, &my_identity, &incoming->key,
4838 if (get_max_send_delay ().rel_value > MAX_REQUEST_TIME.rel_value)
4840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4841 "Sending of previous replies took too long, backing off!\n");
4842 increment_stats ("# route requests dropped due to high load");
4843 decrease_max_send_delay (get_max_send_delay ());
4844 #if DEBUG_DHT_ROUTING
4845 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4847 /** Log routes that die due to high load! */
4848 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4849 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4850 GNUNET_SYSERR, &my_identity, &incoming->key,
4856 msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
4858 GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4860 GNUNET_assert (msg_ctx->bloom != NULL);
4861 msg_ctx->hop_count = ntohl (incoming->hop_count);
4862 memcpy (&msg_ctx->key, &incoming->key, sizeof (GNUNET_HashCode));
4863 msg_ctx->replication = ntohl (incoming->desired_replication_level);
4864 msg_ctx->unique_id = GNUNET_ntohll (incoming->unique_id);
4865 msg_ctx->msg_options = ntohl (incoming->options);
4866 if (GNUNET_DHT_RO_RECORD_ROUTE ==
4867 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
4870 ntohl (incoming->outgoing_path_length) *
4871 sizeof (struct GNUNET_PeerIdentity);
4872 /* FIXME bart: assert? remote peer can kill DHT sending malformed packets! */
4873 // GNUNET_assert (ntohs (message->size) ==
4874 // (sizeof (struct GNUNET_DHT_P2PRouteMessage) +
4875 // ntohs (enc_msg->size) + path_size));
4876 if (ntohs (message->size) !=
4877 (sizeof (struct GNUNET_DHT_P2PRouteMessage) +
4878 ntohs (enc_msg->size) + path_size))
4881 return GNUNET_YES; /* FIXME bart GNUNET_NO? */
4883 route_path = (char *) &incoming[1];
4884 route_path = route_path + ntohs (enc_msg->size);
4885 msg_ctx->path_history =
4886 GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) + path_size);
4887 memcpy (msg_ctx->path_history, route_path, path_size);
4888 memcpy (&msg_ctx->path_history[path_size], &my_identity,
4889 sizeof (struct GNUNET_PeerIdentity));
4890 msg_ctx->path_history_len = ntohl (incoming->outgoing_path_length) + 1;
4892 msg_ctx->network_size = ntohl (incoming->network_size);
4893 msg_ctx->peer = peer;
4894 msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4895 msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4896 demultiplex_message (enc_msg, msg_ctx);
4897 if (msg_ctx->bloom != NULL)
4899 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4900 msg_ctx->bloom = NULL;
4902 GNUNET_free (msg_ctx);
4908 * Core handler for p2p route results.
4910 * @param cls closure
4911 * @param message message
4912 * @param peer peer identity this notification is about
4913 * @param atsi performance data
4917 handle_dht_p2p_route_result (void *cls, const struct GNUNET_PeerIdentity *peer,
4918 const struct GNUNET_MessageHeader *message,
4919 const struct GNUNET_TRANSPORT_ATS_Information
4923 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4924 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT",
4927 struct GNUNET_DHT_P2PRouteResultMessage *incoming =
4928 (struct GNUNET_DHT_P2PRouteResultMessage *) message;
4929 struct GNUNET_MessageHeader *enc_msg =
4930 (struct GNUNET_MessageHeader *) &incoming[1];
4931 struct DHT_MessageContext msg_ctx;
4937 if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4939 GNUNET_break_op (0);
4943 if (malicious_dropper == GNUNET_YES)
4945 #if DEBUG_DHT_ROUTING
4946 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4948 /** Log routes that die due to high load! */
4949 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4950 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4951 GNUNET_SYSERR, &my_identity, &incoming->key,
4958 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4959 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4960 memcpy (&msg_ctx.key, &incoming->key, sizeof (GNUNET_HashCode));
4961 msg_ctx.unique_id = GNUNET_ntohll (incoming->unique_id);
4962 msg_ctx.msg_options = ntohl (incoming->options);
4963 msg_ctx.hop_count = ntohl (incoming->hop_count);
4964 msg_ctx.peer = peer;
4965 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4966 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4967 if ((GNUNET_DHT_RO_RECORD_ROUTE ==
4968 (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE)) &&
4969 (ntohl (incoming->outgoing_path_length) > 0))
4971 if (ntohs (message->size) -
4972 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) -
4973 ntohs (enc_msg->size) !=
4974 ntohl (incoming->outgoing_path_length) *
4975 sizeof (struct GNUNET_PeerIdentity))
4978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4979 "Return message indicated a path was included, but sizes are wrong: Total size %d, enc size %d, left %d, expected %d\n",
4980 ntohs (message->size), ntohs (enc_msg->size),
4981 ntohs (message->size) -
4982 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) -
4983 ntohs (enc_msg->size),
4984 ntohl (incoming->outgoing_path_length) *
4985 sizeof (struct GNUNET_PeerIdentity));
4987 GNUNET_break_op (0);
4990 msg_ctx.path_history = (char *) &incoming[1];
4991 msg_ctx.path_history += ntohs (enc_msg->size);
4992 msg_ctx.path_history_len = ntohl (incoming->outgoing_path_length);
4994 for (i = 0; i < msg_ctx.path_history_len; i++)
4997 &msg_ctx.path_history[i * sizeof (struct GNUNET_PeerIdentity)];
4998 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4999 "(handle_p2p_route_result) Key %s Found peer %d:%s\n",
5000 GNUNET_h2s (&msg_ctx.key), i,
5001 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
5006 GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
5008 GNUNET_assert (msg_ctx.bloom != NULL);
5009 route_result_message (enc_msg, &msg_ctx);
5015 * Receive the HELLO from transport service,
5016 * free current and replace if necessary.
5019 * @param message HELLO message of peer
5022 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
5025 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5026 "Received our `%s' from transport service\n", "HELLO");
5029 GNUNET_assert (message != NULL);
5030 GNUNET_free_non_null (my_hello);
5031 my_hello = GNUNET_malloc (ntohs (message->size));
5032 memcpy (my_hello, message, ntohs (message->size));
5037 * Task run during shutdown.
5043 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
5046 struct PeerInfo *pos;
5050 GNUNET_TRANSPORT_get_hello_cancel (ghh);
5053 if (transport_handle != NULL)
5055 GNUNET_free_non_null (my_hello);
5056 GNUNET_TRANSPORT_disconnect (transport_handle);
5057 transport_handle = NULL;
5059 if (coreAPI != NULL)
5062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Disconnecting core!\n",
5063 my_short_id, "DHT");
5065 GNUNET_CORE_disconnect (coreAPI);
5068 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
5070 while (k_buckets[bucket_count].head != NULL)
5072 pos = k_buckets[bucket_count].head;
5074 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5075 "%s:%s Removing peer %s from bucket %d!\n", my_short_id,
5076 "DHT", GNUNET_i2s (&pos->id), bucket_count);
5078 delete_peer (pos, bucket_count);
5081 if (datacache != NULL)
5084 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Destroying datacache!\n",
5085 my_short_id, "DHT");
5087 GNUNET_DATACACHE_destroy (datacache);
5092 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
5095 if (dhtlog_handle != NULL)
5097 GNUNET_DHTLOG_disconnect (dhtlog_handle);
5098 dhtlog_handle = NULL;
5100 if (block_context != NULL)
5102 GNUNET_BLOCK_context_destroy (block_context);
5103 block_context = NULL;
5105 GNUNET_free_non_null (my_short_id);
5111 * To be called on core init/fail.
5113 * @param cls service closure
5114 * @param server handle to the server for this service
5115 * @param identity the public identity of this peer
5116 * @param publicKey the public key of this peer
5119 core_init (void *cls, struct GNUNET_CORE_Handle *server,
5120 const struct GNUNET_PeerIdentity *identity,
5121 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
5127 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s: Connection to core FAILED!\n",
5128 "dht", GNUNET_i2s (identity));
5130 GNUNET_SCHEDULER_cancel (cleanup_task);
5131 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
5135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5136 "%s: Core connection initialized, I am peer: %s\n", "dht",
5137 GNUNET_i2s (identity));
5140 /* Copy our identity so we can use it */
5141 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
5142 if (my_short_id != NULL)
5143 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5144 "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n",
5146 my_short_id = GNUNET_strdup (GNUNET_i2s (&my_identity));
5147 /* Set the server to local variable */
5150 if (dhtlog_handle != NULL)
5151 dhtlog_handle->insert_node (NULL, &my_identity);
5155 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
5156 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE,
5158 {&handle_dht_local_route_stop, NULL,
5159 GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
5160 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
5165 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
5166 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
5167 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
5173 * Method called whenever a peer connects.
5175 * @param cls closure
5176 * @param peer peer identity this notification is about
5177 * @param atsi performance data
5180 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
5181 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
5183 struct PeerInfo *ret;
5184 struct DHTPutEntry *put_entry;
5187 /* Check for connect to self message */
5188 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
5192 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5193 "%s:%s Receives core connect message for peer %s distance %d!\n",
5194 my_short_id, "dht", GNUNET_i2s (peer), distance);
5198 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
5202 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5203 "%s:%s Received %s message for peer %s, but already have peer in RT!",
5204 my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s (peer));
5210 if ((datacache != NULL) && (GNUNET_YES == put_peer_identities))
5213 GNUNET_malloc (sizeof (struct DHTPutEntry) +
5214 sizeof (struct GNUNET_PeerIdentity));
5215 put_entry->path_length = 0;
5216 put_entry->data_size = sizeof (struct GNUNET_PeerIdentity);
5217 memcpy (&put_entry[1], peer, sizeof (struct GNUNET_PeerIdentity));
5218 GNUNET_DATACACHE_put (datacache, &peer->hashPubKey,
5219 sizeof (struct DHTPutEntry) +
5220 sizeof (struct GNUNET_PeerIdentity),
5221 (char *) put_entry, GNUNET_BLOCK_TYPE_DHT_HELLO,
5222 GNUNET_TIME_absolute_get_forever ());
5223 GNUNET_free (put_entry);
5225 else if (datacache == NULL)
5226 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5227 "DHT has no connection to datacache!\n");
5229 peer_bucket = find_current_bucket (&peer->hashPubKey);
5230 GNUNET_assert (peer_bucket >= lowest_bucket);
5231 GNUNET_assert (peer_bucket < MAX_BUCKETS);
5232 ret = GNUNET_malloc (sizeof (struct PeerInfo));
5234 ret->latency = latency;
5235 ret->distance = distance;
5238 GNUNET_CONTAINER_DLL_insert_after (k_buckets[peer_bucket].head,
5239 k_buckets[peer_bucket].tail,
5240 k_buckets[peer_bucket].tail, ret);
5241 k_buckets[peer_bucket].peers_size++;
5242 #if DO_UPDATE_PREFERENCE
5243 if ((GNUNET_CRYPTO_hash_matching_bits
5244 (&my_identity.hashPubKey, &peer->hashPubKey) > 0) &&
5245 (k_buckets[peer_bucket].peers_size <= bucket_size))
5246 ret->preference_task =
5247 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
5249 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
5250 enable_next_bucket ();
5252 schedule_ping_messages ();
5254 newly_found_peers++;
5255 GNUNET_CONTAINER_multihashmap_put (all_known_peers, &peer->hashPubKey, ret,
5256 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
5257 increment_stats (STAT_PEERS_KNOWN);
5260 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5261 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT",
5262 ret == NULL ? "NOT ADDED" : "PEER ADDED");
5268 * Method called whenever a peer disconnects.
5270 * @param cls closure
5271 * @param peer peer identity this notification is about
5274 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
5276 struct PeerInfo *to_remove;
5279 /* Check for disconnect from self message */
5280 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
5283 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5284 "%s:%s: Received peer disconnect message for peer `%s' from %s\n",
5285 my_short_id, "DHT", GNUNET_i2s (peer), "CORE");
5289 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
5294 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
5295 "%s:%s: do not have peer `%s' in RT, can't disconnect!\n",
5296 my_short_id, "DHT", GNUNET_i2s (peer));
5300 increment_stats (STAT_DISCONNECTS);
5301 GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
5302 (all_known_peers, &peer->hashPubKey));
5304 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
5305 GNUNET_assert (to_remove != NULL);
5306 if (NULL != to_remove->info_ctx)
5308 GNUNET_CORE_peer_change_preference_cancel (to_remove->info_ctx);
5309 to_remove->info_ctx = NULL;
5312 memcmp (peer, &to_remove->id,
5313 sizeof (struct GNUNET_PeerIdentity)));
5314 current_bucket = find_current_bucket (&to_remove->id.hashPubKey);
5315 delete_peer (to_remove, current_bucket);
5320 * Process dht requests.
5322 * @param cls closure
5323 * @param server the initialized server
5324 * @param c configuration to use
5327 run (void *cls, struct GNUNET_SERVER_Handle *server,
5328 const struct GNUNET_CONFIGURATION_Handle *c)
5330 struct GNUNET_TIME_Relative next_send_time;
5331 unsigned long long temp_config_num;
5332 char *converge_modifier_buf;
5335 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
5336 GNUNET_SERVER_add_handlers (server, plugin_handlers);
5337 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
5338 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
5339 DEFAULT_CORE_QUEUE_SIZE, /* queue size */
5340 NULL, /* Closure passed to DHT functions */
5341 &core_init, /* Call core_init once connected */
5342 &handle_core_connect, /* Handle connects */
5343 &handle_core_disconnect, /* remove peers on disconnects */
5344 NULL, /* Do we care about "status" updates? */
5345 NULL, /* Don't want notified about all incoming messages */
5346 GNUNET_NO, /* For header only inbound notification */
5347 NULL, /* Don't want notified about all outbound messages */
5348 GNUNET_NO, /* For header only outbound notification */
5349 core_handlers); /* Register these handlers */
5351 if (coreAPI == NULL)
5354 GNUNET_TRANSPORT_connect (cfg, NULL, NULL, NULL, NULL, NULL);
5355 if (transport_handle != NULL)
5356 ghh = GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
5358 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5359 "Failed to connect to transport service!\n");
5360 block_context = GNUNET_BLOCK_context_create (cfg);
5361 lowest_bucket = MAX_BUCKETS - 1;
5362 forward_list.hashmap =
5363 GNUNET_CONTAINER_multihashmap_create (MAX_OUTSTANDING_FORWARDS / 10);
5364 forward_list.minHeap =
5365 GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
5366 all_known_peers = GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
5367 recent_find_peer_requests =
5368 GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
5369 GNUNET_assert (all_known_peers != NULL);
5371 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
5374 debug_routes = GNUNET_YES;
5378 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "strict_kademlia"))
5380 strict_kademlia = GNUNET_YES;
5384 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_on_closest"))
5386 stop_on_closest = GNUNET_YES;
5390 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_found"))
5392 stop_on_found = GNUNET_YES;
5396 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_getter"))
5398 malicious_getter = GNUNET_YES;
5400 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
5401 "MALICIOUS_GET_FREQUENCY",
5402 &malicious_get_frequency))
5403 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
5407 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "MAX_HOPS", &max_hops))
5409 max_hops = DEFAULT_MAX_HOPS;
5413 GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT", "USE_MAX_HOPS"))
5415 use_max_hops = GNUNET_YES;
5419 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_putter"))
5421 malicious_putter = GNUNET_YES;
5423 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
5424 "MALICIOUS_PUT_FREQUENCY",
5425 &malicious_put_frequency))
5426 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
5429 dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
5431 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
5432 "REPLICATION_FREQUENCY",
5435 dht_republish_frequency =
5436 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES,
5441 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "bucket_size",
5444 bucket_size = (unsigned int) temp_config_num;
5448 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "kad_alpha",
5449 &kademlia_replication))
5451 kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
5455 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_dropper"))
5457 malicious_dropper = GNUNET_YES;
5461 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "republish"))
5462 do_republish = GNUNET_NO;
5465 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "do_find_peer"))
5467 do_find_peer = GNUNET_NO;
5470 do_find_peer = GNUNET_YES;
5473 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "use_real_distance"))
5474 use_real_distance = GNUNET_YES;
5477 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
5478 "mysql_logging_extended"))
5480 debug_routes = GNUNET_YES;
5481 debug_routes_extended = GNUNET_YES;
5484 #if DEBUG_DHT_ROUTING
5485 if (GNUNET_YES == debug_routes)
5487 dhtlog_handle = GNUNET_DHTLOG_connect (cfg);
5488 if (dhtlog_handle == NULL)
5490 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5491 "Could not connect to mysql logging server, logging will not happen!");
5496 converge_option = DHT_CONVERGE_BINARY;
5498 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "converge_linear"))
5500 converge_option = DHT_CONVERGE_LINEAR;
5502 else if (GNUNET_YES ==
5503 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht",
5504 "converge_exponential"))
5506 converge_option = DHT_CONVERGE_EXPONENTIAL;
5508 else if (GNUNET_YES ==
5509 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "converge_random"))
5511 converge_option = DHT_CONVERGE_RANDOM;
5513 else if (GNUNET_YES ==
5514 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "converge_binary"))
5516 converge_option = DHT_CONVERGE_BINARY;
5519 converge_modifier = 4.0;
5521 GNUNET_CONFIGURATION_get_value_string (cfg, "dht", "converge_modifier",
5522 &converge_modifier_buf))
5524 if (1 != sscanf (converge_modifier_buf, "%f", &converge_modifier))
5526 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
5527 "Failed to read decimal value for %s from `%s'\n",
5528 "CONVERGE_MODIFIER", converge_modifier_buf);
5529 converge_modifier = 0.0;
5531 GNUNET_free (converge_modifier_buf);
5535 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "paper_forwarding"))
5536 paper_forwarding = GNUNET_YES;
5539 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "put_peer_identities"))
5540 put_peer_identities = GNUNET_YES;
5542 stats = GNUNET_STATISTICS_create ("dht", cfg);
5546 GNUNET_STATISTICS_set (stats, STAT_ROUTES, 0, GNUNET_NO);
5547 GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
5548 GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
5549 GNUNET_STATISTICS_set (stats, STAT_RESULTS, 0, GNUNET_NO);
5550 GNUNET_STATISTICS_set (stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
5551 GNUNET_STATISTICS_set (stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
5552 GNUNET_STATISTICS_set (stats, STAT_GETS, 0, GNUNET_NO);
5553 GNUNET_STATISTICS_set (stats, STAT_PUTS, 0, GNUNET_NO);
5554 GNUNET_STATISTICS_set (stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
5555 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER, 0, GNUNET_NO);
5556 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
5557 GNUNET_STATISTICS_set (stats, STAT_GET_START, 0, GNUNET_NO);
5558 GNUNET_STATISTICS_set (stats, STAT_PUT_START, 0, GNUNET_NO);
5559 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
5560 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
5561 GNUNET_STATISTICS_set (stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
5562 GNUNET_STATISTICS_set (stats, STAT_GET_REPLY, 0, GNUNET_NO);
5563 GNUNET_STATISTICS_set (stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
5564 GNUNET_STATISTICS_set (stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
5565 GNUNET_STATISTICS_set (stats, STAT_DISCONNECTS, 0, GNUNET_NO);
5567 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
5568 recent.hashmap = GNUNET_CONTAINER_multihashmap_create (DHT_MAX_RECENT / 2);
5570 GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
5571 if (GNUNET_YES == do_find_peer)
5573 next_send_time.rel_value =
5574 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
5575 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
5576 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value /
5578 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
5579 find_peer_context.start = GNUNET_TIME_absolute_get ();
5580 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
5581 &find_peer_context);
5584 /* Scheduled the task to clean up when shutdown is called */
5586 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
5587 &shutdown_task, NULL);
5591 * The main function for the dht service.
5593 * @param argc number of arguments from the command line
5594 * @param argv command line arguments
5595 * @return 0 ok, 1 on error
5598 main (int argc, char *const *argv)
5604 GNUNET_SERVICE_run (argc, argv, "dht", GNUNET_SERVICE_OPTION_NONE, &run,
5606 if (NULL != recent.hashmap)
5608 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (recent.hashmap));
5609 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
5610 recent.hashmap = NULL;
5612 if (NULL != recent.minHeap)
5614 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (recent.minHeap));
5615 GNUNET_CONTAINER_heap_destroy (recent.minHeap);
5616 recent.minHeap = NULL;
5618 if (NULL != recent_find_peer_requests)
5620 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
5621 recent_find_peer_requests = NULL;