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
75 * Minimum number of peers we need for "good" routing,
76 * any less than this and we will allow messages to
77 * travel much further through the network!
79 #define MINIMUM_PEER_THRESHOLD 20
81 #define DHT_MAX_RECENT 1000
83 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
86 * Default time to wait to send messages on behalf of other peers.
88 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
91 * Default importance for handling messages on behalf of other peers.
93 #define DHT_DEFAULT_P2P_IMPORTANCE 0
96 * How long to keep recent requests around by default.
98 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
101 * Default time to wait to send find peer messages sent by the dht service.
103 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
106 * Default importance for find peer messages sent by the dht service.
108 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
111 * Default replication parameter for find peer messages sent by the dht service.
113 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
116 * Default options for find peer requests sent by the dht service.
118 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
119 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
122 * How long at least to wait before sending another find peer request.
124 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
127 * How long at most to wait before sending another find peer request.
129 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
132 * How often to update our preference levels for peers in our routing tables.
134 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
137 * How long at most on average will we allow a reply forward to take
138 * (before we quit sending out new requests)
140 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
143 * How many initial requests to send out (in true Kademlia fashion)
145 #define DHT_KADEMLIA_REPLICATION 3
148 * Default frequency for sending malicious get messages
150 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
153 * Default frequency for sending malicious put messages
155 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
158 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
161 * Real maximum number of hops, at which point we refuse
162 * to forward the message.
164 #define DEFAULT_MAX_HOPS 10
167 * How many time differences between requesting a core send and
168 * the actual callback to remember.
170 #define MAX_REPLY_TIMES 8
172 enum ConvergenceOptions
175 * Use the linear method for convergence.
180 * Converge using a fast converging square
186 * Converge using a slower exponential
189 DHT_CONVERGE_EXPONENTIAL,
192 * Don't do any special convergence, allow
193 * the algorithm to hopefully route to closer
199 * Binary convergence, start routing to closest
200 * only after set number of hops.
206 * Linked list of messages to send to clients.
208 struct P2PPendingMessage
211 * Pointer to next item in the list
213 struct P2PPendingMessage *next;
216 * Pointer to previous item in the list
218 struct P2PPendingMessage *prev;
221 * Message importance level.
223 unsigned int importance;
226 * Time when this request was scheduled to be sent.
228 struct GNUNET_TIME_Absolute scheduled;
231 * How long to wait before sending message.
233 struct GNUNET_TIME_Relative timeout;
236 * Actual message to be sent; // avoid allocation
238 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
243 * Per-peer information.
248 * Next peer entry (DLL)
250 struct PeerInfo *next;
253 * Prev peer entry (DLL)
255 struct PeerInfo *prev;
258 * Head of pending messages to be sent to this peer.
260 struct P2PPendingMessage *head;
263 * Tail of pending messages to be sent to this peer.
265 struct P2PPendingMessage *tail;
268 * Core handle for sending messages to this peer.
270 struct GNUNET_CORE_TransmitHandle *th;
273 * Task for scheduling message sends.
275 GNUNET_SCHEDULER_TaskIdentifier send_task;
278 * Task for scheduling preference updates
280 GNUNET_SCHEDULER_TaskIdentifier preference_task;
283 * Preference update context
285 struct GNUNET_CORE_InformationRequestContext *info_ctx;
288 * What is the average latency for replies received?
290 struct GNUNET_TIME_Relative latency;
293 * What is the identity of the peer?
295 struct GNUNET_PeerIdentity id;
298 * Transport level distance to peer.
300 unsigned int distance;
303 * Holds matching bits from peer to current target,
304 * used for distance comparisons between peers. May
305 * be considered a really bad idea.
306 * FIXME: remove this value (create struct which holds
307 * a single peerinfo and the matching bits, use
308 * that to pass to comparitor)
310 unsigned int matching_bits;
313 * Task for scheduling periodic ping messages for this peer.
315 GNUNET_SCHEDULER_TaskIdentifier ping_task;
319 * Peers are grouped into buckets.
326 struct PeerInfo *head;
331 struct PeerInfo *tail;
334 * Number of peers in the bucket.
336 unsigned int peers_size;
340 * Linked list of messages to send to clients.
342 struct PendingMessage
345 * Pointer to next item in the list
347 struct PendingMessage *next;
350 * Pointer to previous item in the list
352 struct PendingMessage *prev;
355 * Actual message to be sent; // avoid allocation
357 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
362 * Struct containing information about a client,
363 * handle to connect to it, and any pending messages
364 * that need to be sent to it.
369 * Linked list of active clients
371 struct ClientList *next;
374 * The handle to this client
376 struct GNUNET_SERVER_Client *client_handle;
379 * Handle to the current transmission request, NULL
382 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
385 * Linked list of pending messages for this client
387 struct PendingMessage *pending_head;
390 * Tail of linked list of pending messages for this client
392 struct PendingMessage *pending_tail;
397 * Context containing information about a DHT message received.
399 struct DHT_MessageContext
402 * The client this request was received from.
403 * (NULL if received from another peer)
405 struct ClientList *client;
408 * The peer this request was received from.
409 * (NULL if received from local client)
411 const struct GNUNET_PeerIdentity *peer;
414 * Bloomfilter for this routing request.
416 struct GNUNET_CONTAINER_BloomFilter *bloom;
419 * extended query (see gnunet_block_lib.h).
424 * Bloomfilter to filter out duplicate replies.
426 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
429 * The key this request was about
434 * How long should we wait to transmit this request?
436 struct GNUNET_TIME_Relative timeout;
439 * The unique identifier of this request
444 * Number of bytes in xquery.
449 * Mutator value for the reply_bf, see gnunet_block_lib.h
451 uint32_t reply_bf_mutator;
454 * Desired replication level
456 uint32_t replication;
459 * Network size estimate, either ours or the sum of
460 * those routed to thus far. =~ Log of number of peers
461 * chosen from for this request.
463 uint32_t network_size;
466 * Any message options for this request
468 uint32_t msg_options;
471 * How many hops has the message already traversed?
476 * How important is this message?
478 unsigned int importance;
481 * Should we (still) forward the request on to other peers?
486 * Did we forward this message? (may need to remember it!)
491 * Are we the closest known peer to this key (out of our neighbors?)
497 * Record used for remembering what peers are waiting for what
498 * responses (based on search key).
500 struct DHTRouteSource
505 struct DHTRouteSource *next;
510 struct DHTRouteSource *prev;
513 * Source of the request. Replies should be forwarded to
516 struct GNUNET_PeerIdentity source;
519 * If this was a local request, remember the client; otherwise NULL.
521 struct ClientList *client;
524 * Pointer to this nodes heap location (for removal)
526 struct GNUNET_CONTAINER_HeapNode *hnode;
529 * Back pointer to the record storing this information.
531 struct DHTQueryRecord *record;
534 * Task to remove this entry on timeout.
536 GNUNET_SCHEDULER_TaskIdentifier delete_task;
539 * Bloomfilter of peers we have already sent back as
540 * replies to the initial request. Allows us to not
541 * forward the same peer multiple times for a find peer
544 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
549 * Entry in the DHT routing table.
551 struct DHTQueryRecord
554 * Head of DLL for result forwarding.
556 struct DHTRouteSource *head;
559 * Tail of DLL for result forwarding.
561 struct DHTRouteSource *tail;
564 * Key that the record concerns.
569 * GET message of this record (what we already forwarded?).
571 //DV_DHT_MESSAGE get; Try to get away with not saving this.
574 * Bloomfilter of the peers we've replied to so far
576 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
581 * Context used to calculate the number of find peer messages
582 * per X time units since our last scheduled find peer message
583 * was sent. If we have seen too many messages, delay or don't
586 struct FindPeerMessageContext
590 struct GNUNET_TIME_Absolute start;
592 struct GNUNET_TIME_Absolute end;
596 * DHT Routing results structure
601 * Min heap for removal upon reaching limit
603 struct GNUNET_CONTAINER_Heap *minHeap;
606 * Hashmap for fast key based lookup
608 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
613 * DHT structure for recent requests.
615 struct RecentRequests
618 * Min heap for removal upon reaching limit
620 struct GNUNET_CONTAINER_Heap *minHeap;
623 * Hashmap for key based lookup
625 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
631 * Position of this node in the min heap.
633 struct GNUNET_CONTAINER_HeapNode *heap_node;
636 * Bloomfilter containing entries for peers
637 * we forwarded this request to.
639 struct GNUNET_CONTAINER_BloomFilter *bloom;
642 * Timestamp of this request, for ordering
645 struct GNUNET_TIME_Absolute timestamp;
648 * Key of this request.
653 * Unique identifier for this request.
658 * Task to remove this entry on timeout.
660 GNUNET_SCHEDULER_TaskIdentifier remove_task;
663 struct RepublishContext
678 * Which kind of convergence will we be using?
680 static enum ConvergenceOptions converge_option;
683 * Modifier for the convergence function
685 static float converge_modifier;
688 * Recent requests by hash/uid and by time inserted.
690 static struct RecentRequests recent;
693 * Context to use to calculate find peer rates.
695 static struct FindPeerMessageContext find_peer_context;
698 * Don't use our routing algorithm, always route
699 * to closest peer; initially send requests to 3
702 static unsigned int strict_kademlia;
705 * Routing option to end routing when closest peer found.
707 static unsigned int stop_on_closest;
710 * Routing option to end routing when data is found.
712 static unsigned int stop_on_found;
715 * Whether DHT needs to manage find peer requests, or
716 * an external force will do it on behalf of the DHT.
718 static unsigned int do_find_peer;
721 * Once we have stored an item in the DHT, refresh it
722 * according to our republish interval.
724 static unsigned int do_republish;
727 * Use the "real" distance metric when selecting the
728 * next routing hop. Can be less accurate.
730 static unsigned int use_real_distance;
733 * How many peers have we added since we sent out our last
736 static unsigned int newly_found_peers;
739 * Container of active queries we should remember
741 static struct DHTResults forward_list;
744 * Handle to the datacache service (for inserting/retrieving data)
746 static struct GNUNET_DATACACHE_Handle *datacache;
749 * Handle for the statistics service.
751 struct GNUNET_STATISTICS_Handle *stats;
755 * The configuration the DHT service is running with
757 static const struct GNUNET_CONFIGURATION_Handle *cfg;
760 * Handle to the core service
762 static struct GNUNET_CORE_Handle *coreAPI;
765 * Handle to the transport service, for getting our hello
767 static struct GNUNET_TRANSPORT_Handle *transport_handle;
770 * The identity of our peer.
772 static struct GNUNET_PeerIdentity my_identity;
775 * Short id of the peer, for printing
777 static char *my_short_id;
782 static struct GNUNET_MessageHeader *my_hello;
785 * Task to run when we shut down, cleaning up all our trash
787 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
790 * The lowest currently used bucket.
792 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
795 * The maximum number of hops before we stop routing messages.
797 static unsigned long long max_hops;
800 * How often to republish content we have previously stored.
802 static struct GNUNET_TIME_Relative dht_republish_frequency;
805 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
807 static int use_max_hops;
810 * The buckets (Kademlia routing table, complete with growth).
811 * Array of size MAX_BUCKET_SIZE.
813 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
816 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
818 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
821 * Recently seen find peer requests.
823 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
826 * Maximum size for each bucket.
828 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
831 * List of active clients.
833 static struct ClientList *client_list;
836 * Handle to the DHT logger.
838 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
841 * Whether or not to send routing debugging information
842 * to the dht logging server
844 static unsigned int debug_routes;
847 * Whether or not to send FULL route information to
850 static unsigned int debug_routes_extended;
853 * GNUNET_YES or GNUNET_NO, whether or not to act as
854 * a malicious node which drops all messages
856 static unsigned int malicious_dropper;
859 * GNUNET_YES or GNUNET_NO, whether or not to act as
860 * a malicious node which sends out lots of GETS
862 static unsigned int malicious_getter;
865 * GNUNET_YES or GNUNET_NO, whether or not to act as
866 * a malicious node which sends out lots of PUTS
868 static unsigned int malicious_putter;
871 * Frequency for malicious get requests.
873 static unsigned long long malicious_get_frequency;
876 * Frequency for malicious put requests.
878 static unsigned long long malicious_put_frequency;
881 * Reply times for requests, if we are busy, don't send any
884 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
887 * Current counter for replies.
889 static unsigned int reply_counter;
892 * Our handle to the BLOCK library.
894 static struct GNUNET_BLOCK_Context *block_context;
898 * Forward declaration.
901 send_generic_reply (void *cls, size_t size, void *buf);
904 /** Declare here so retry_core_send is aware of it */
906 core_transmit_notify (void *cls,
907 size_t size, void *buf);
910 * Convert unique ID to hash code.
912 * @param uid unique ID to convert
913 * @param hash set to uid (extended with zeros)
916 hash_from_uid (uint64_t uid,
917 GNUNET_HashCode *hash)
919 memset (hash, 0, sizeof(GNUNET_HashCode));
920 *((uint64_t*)hash) = uid;
925 * Calculate the average send time between messages so that we can
926 * ignore certain requests if we get too busy.
928 * @return the average time between asking core to send a message
929 * and when the buffer for copying it is passed
931 static struct GNUNET_TIME_Relative get_average_send_delay()
934 unsigned int divisor;
935 struct GNUNET_TIME_Relative average_time;
936 average_time = GNUNET_TIME_relative_get_zero();
938 for (i = 0; i < MAX_REPLY_TIMES; i++)
940 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
941 if (reply_times[i].abs_value == (uint64_t)0)
951 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
953 "Avg send delay: %u sends is %llu\n",
955 (unsigned long long) average_time.abs_value);
961 * Given the largest send delay, artificially decrease it
962 * so the next time around we may have a chance at sending
965 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
968 for (i = 0; i < MAX_REPLY_TIMES; i++)
970 if (reply_times[i].rel_value == max_time.rel_value)
972 reply_times[i].rel_value = reply_times[i].rel_value / 2;
979 * Find the maximum send time of the recently sent values.
981 * @return the average time between asking core to send a message
982 * and when the buffer for copying it is passed
984 static struct GNUNET_TIME_Relative get_max_send_delay()
987 struct GNUNET_TIME_Relative max_time;
988 max_time = GNUNET_TIME_relative_get_zero();
990 for (i = 0; i < MAX_REPLY_TIMES; i++)
992 if (reply_times[i].rel_value > max_time.rel_value)
993 max_time.rel_value = reply_times[i].rel_value;
996 if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
997 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n",
998 (unsigned long long) max_time.rel_value);
1003 increment_stats(const char *value)
1007 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
1012 * Try to send another message from our core send list
1015 try_core_send (void *cls,
1016 const struct GNUNET_SCHEDULER_TaskContext *tc)
1018 struct PeerInfo *peer = cls;
1019 struct P2PPendingMessage *pending;
1022 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
1024 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1027 if (peer->th != NULL)
1028 return; /* Message send already in progress */
1030 pending = peer->head;
1031 if (pending != NULL)
1033 ssize = ntohs(pending->msg->size);
1035 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1036 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
1037 "DHT", ssize, GNUNET_i2s(&peer->id));
1039 pending->scheduled = GNUNET_TIME_absolute_get();
1041 if (reply_counter >= MAX_REPLY_TIMES)
1043 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
1044 pending->timeout, &peer->id,
1045 ssize, &core_transmit_notify, peer);
1050 * Function called to send a request out to another peer.
1051 * Called both for locally initiated requests and those
1052 * received from other peers.
1054 * @param msg the encapsulated message
1055 * @param peer the peer to forward the message to
1056 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1059 forward_result_message (const struct GNUNET_MessageHeader *msg,
1060 struct PeerInfo *peer,
1061 struct DHT_MessageContext *msg_ctx)
1063 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1064 struct P2PPendingMessage *pending;
1068 increment_stats(STAT_RESULT_FORWARDS);
1069 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1070 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1071 psize = sizeof(struct P2PPendingMessage) + msize;
1072 pending = GNUNET_malloc(psize);
1073 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1074 pending->importance = DHT_SEND_PRIORITY;
1075 pending->timeout = GNUNET_TIME_relative_get_forever();
1076 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1077 result_message->header.size = htons(msize);
1078 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1079 result_message->put_path_length = htons(0); /* FIXME: implement */
1080 result_message->get_path_length = htons(0); /* FIXME: implement */
1081 result_message->options = htonl(msg_ctx->msg_options);
1082 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1083 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1084 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1085 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1086 memcpy(&result_message[1], msg, ntohs(msg->size));
1088 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Adding pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
1090 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1091 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1092 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1097 * Called when core is ready to send a message we asked for
1098 * out to the destination.
1100 * @param cls closure (NULL)
1101 * @param size number of bytes available in buf
1102 * @param buf where the callee should write the message
1103 * @return number of bytes written to buf
1106 core_transmit_notify (void *cls,
1107 size_t size, void *buf)
1109 struct PeerInfo *peer = cls;
1111 struct P2PPendingMessage *pending;
1118 /* client disconnected */
1120 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1125 if (peer->head == NULL)
1129 pending = peer->head;
1130 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1131 msize = ntohs(pending->msg->size);
1135 memcpy (cbuf, pending->msg, msize);
1136 GNUNET_CONTAINER_DLL_remove (peer->head,
1140 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Removing pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
1142 GNUNET_free (pending);
1145 while (NULL != pending &&
1146 (size - off >= (msize = ntohs (pending->msg->size))))
1148 #if DEBUG_DHT_ROUTING
1149 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s:%s' : transmit_notify (core) called with size %d, available %d\n", my_short_id, "dht service", msize, size);
1151 memcpy (&cbuf[off], pending->msg, msize);
1153 GNUNET_CONTAINER_DLL_remove (peer->head,
1156 GNUNET_free (pending);
1157 pending = peer->head;
1160 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1161 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1163 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s:%s' : transmit_notify (core) called with size %d, available %d, returning %d\n", my_short_id, "dht service", msize, size, off);
1170 * Compute the distance between have and target as a 32-bit value.
1171 * Differences in the lower bits must count stronger than differences
1172 * in the higher bits.
1174 * @return 0 if have==target, otherwise a number
1175 * that is larger as the distance between
1176 * the two hash codes increases
1179 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1181 unsigned int bucket;
1186 /* We have to represent the distance between two 2^9 (=512)-bit
1187 numbers as a 2^5 (=32)-bit number with "0" being used for the
1188 two numbers being identical; furthermore, we need to
1189 guarantee that a difference in the number of matching
1190 bits is always represented in the result.
1192 We use 2^32/2^9 numerical values to distinguish between
1193 hash codes that have the same LSB bit distance and
1194 use the highest 2^9 bits of the result to signify the
1195 number of (mis)matching LSB bits; if we have 0 matching
1196 and hence 512 mismatching LSB bits we return -1 (since
1197 512 itself cannot be represented with 9 bits) */
1199 /* first, calculate the most significant 9 bits of our
1200 result, aka the number of LSBs */
1201 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1202 /* bucket is now a value between 0 and 512 */
1204 return 0; /* perfect match */
1206 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1207 below, we'd end up with max+1 (overflow)) */
1209 /* calculate the most significant bits of the final result */
1210 msb = (512 - bucket) << (32 - 9);
1211 /* calculate the 32-9 least significant bits of the final result by
1212 looking at the differences in the 32-9 bits following the
1213 mismatching bit at 'bucket' */
1215 for (i = bucket + 1;
1216 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1218 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1219 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1220 last bit set will be 31 -- if
1221 i does not reach 512 first... */
1227 * Return a number that is larger the closer the
1228 * "have" GNUNET_hash code is to the "target".
1230 * @return inverse distance metric, non-zero.
1231 * Must fudge the value if NO bits match.
1234 inverse_distance (const GNUNET_HashCode * target,
1235 const GNUNET_HashCode * have)
1237 if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1238 return 1; /* Never return 0! */
1239 return ((unsigned int) -1) - distance (target, have);
1243 * Find the optimal bucket for this key, regardless
1244 * of the current number of buckets in use.
1246 * @param hc the hashcode to compare our identity to
1248 * @return the proper bucket index, or GNUNET_SYSERR
1249 * on error (same hashcode)
1251 static int find_bucket(const GNUNET_HashCode *hc)
1255 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1256 if (bits == MAX_BUCKETS)
1257 return GNUNET_SYSERR;
1258 return MAX_BUCKETS - bits - 1;
1262 * Find which k-bucket this peer should go into,
1263 * taking into account the size of the k-bucket
1264 * array. This means that if more bits match than
1265 * there are currently buckets, lowest_bucket will
1268 * @param hc GNUNET_HashCode we are finding the bucket for.
1270 * @return the proper bucket index for this key,
1271 * or GNUNET_SYSERR on error (same hashcode)
1273 static int find_current_bucket(const GNUNET_HashCode *hc)
1276 actual_bucket = find_bucket(hc);
1278 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1279 return lowest_bucket;
1280 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1281 return lowest_bucket;
1283 return actual_bucket;
1288 * Find a routing table entry from a peer identity
1290 * @param peer the peer to look up
1292 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1295 find_bucket_by_peer(const struct PeerInfo *peer)
1298 struct PeerInfo *pos;
1300 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1302 pos = k_buckets[bucket].head;
1311 return GNUNET_SYSERR; /* No such peer. */
1317 * Print the complete routing table for this peer.
1320 print_routing_table ()
1323 struct PeerInfo *pos;
1324 char char_buf[30000];
1326 memset(char_buf, 0, sizeof(char_buf));
1328 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1329 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1330 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1332 pos = k_buckets[bucket].head;
1333 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1334 //fprintf(stderr, "Bucket %d:\n", bucket);
1337 //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));
1338 char_pos += sprintf(&char_buf[char_pos], "\tPeer %s, best bucket %d, %d bits match\n", GNUNET_i2s(&pos->id), find_bucket(&pos->id.hashPubKey), GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey));
1342 fprintf(stderr, "%s", char_buf);
1348 * Find a routing table entry from a peer identity
1350 * @param peer the peer identity to look up
1352 * @return the routing table entry, or NULL if not found
1354 static struct PeerInfo *
1355 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1358 struct PeerInfo *pos;
1359 bucket = find_current_bucket(&peer->hashPubKey);
1361 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1364 pos = k_buckets[bucket].head;
1367 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1371 return NULL; /* No such peer. */
1374 /* Forward declaration */
1376 update_core_preference (void *cls,
1377 const struct GNUNET_SCHEDULER_TaskContext *tc);
1379 * Function called with statistics about the given peer.
1381 * @param cls closure
1382 * @param peer identifies the peer
1383 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1384 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1385 * @param amount set to the amount that was actually reserved or unreserved;
1386 * either the full requested amount or zero (no partial reservations)
1387 * @param preference current traffic preference for the given peer
1390 update_core_preference_finish (void *cls,
1391 const struct GNUNET_PeerIdentity * peer,
1392 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1393 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1394 int amount, uint64_t preference)
1396 struct PeerInfo *peer_info = cls;
1397 peer_info->info_ctx = NULL;
1398 GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1402 update_core_preference (void *cls,
1403 const struct GNUNET_SCHEDULER_TaskContext *tc)
1405 struct PeerInfo *peer = cls;
1406 uint64_t preference;
1407 unsigned int matching;
1408 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1412 matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1415 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1418 preference = 1LL << matching;
1419 peer->info_ctx = GNUNET_CORE_peer_change_preference (cfg,
1421 GNUNET_TIME_relative_get_forever(),
1422 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1425 &update_core_preference_finish,
1430 * Really add a peer to a bucket (only do assertions
1433 * @param peer GNUNET_PeerIdentity of the peer to add
1434 * @param bucket the already figured out bucket to add
1436 * @param latency the core reported latency of this peer
1437 * @param distance the transport level distance to this peer
1439 * @return the newly added PeerInfo
1441 static struct PeerInfo *
1442 add_peer(const struct GNUNET_PeerIdentity *peer,
1443 unsigned int bucket,
1444 struct GNUNET_TIME_Relative latency,
1445 unsigned int distance)
1447 struct PeerInfo *new_peer;
1448 GNUNET_assert(bucket < MAX_BUCKETS);
1449 GNUNET_assert(peer != NULL);
1450 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1451 new_peer->latency = latency;
1452 new_peer->distance = distance;
1454 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1456 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1457 k_buckets[bucket].tail,
1458 k_buckets[bucket].tail,
1460 k_buckets[bucket].peers_size++;
1462 if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1464 #if DO_UPDATE_PREFERENCE
1465 new_peer->preference_task = GNUNET_SCHEDULER_add_now(&update_core_preference, new_peer);
1473 * Given a peer and its corresponding bucket,
1474 * remove it from that bucket. Does not free
1475 * the PeerInfo struct, nor cancel messages
1476 * or free messages waiting to be sent to this
1479 * @param peer the peer to remove
1480 * @param bucket the bucket the peer belongs to
1482 static void remove_peer (struct PeerInfo *peer,
1483 unsigned int bucket)
1485 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1486 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1487 k_buckets[bucket].tail,
1489 k_buckets[bucket].peers_size--;
1491 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1497 * Removes peer from a bucket, then frees associated
1498 * resources and frees peer.
1500 * @param peer peer to be removed and freed
1501 * @param bucket which bucket this peer belongs to
1503 static void delete_peer (struct PeerInfo *peer,
1504 unsigned int bucket)
1506 struct P2PPendingMessage *pos;
1507 struct P2PPendingMessage *next;
1509 struct PeerInfo *peer_pos;
1511 peer_pos = k_buckets[bucket].head;
1512 while ((peer_pos != NULL) && (peer_pos != peer))
1513 peer_pos = peer_pos->next;
1514 if (peer_pos == NULL)
1516 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1517 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Lowest bucket: %d, find_current_bucket: %d, peer resides in bucket: %d\n", my_short_id, "DHT", lowest_bucket, find_current_bucket(&peer->id.hashPubKey), find_bucket_by_peer(peer));
1519 GNUNET_assert(peer_pos != NULL);
1521 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1523 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1524 GNUNET_SCHEDULER_cancel(peer->send_task);
1525 if ((peer->th != NULL) && (coreAPI != NULL))
1526 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1529 while (pos != NULL) /* Remove any pending messages for this peer */
1536 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1537 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer));
1543 * Iterator over hash map entries.
1545 * @param cls closure
1546 * @param key current key code
1547 * @param value PeerInfo of the peer to move to new lowest bucket
1548 * @return GNUNET_YES if we should continue to
1552 static int move_lowest_bucket (void *cls,
1553 const GNUNET_HashCode * key,
1556 struct PeerInfo *peer = value;
1559 GNUNET_assert(lowest_bucket > 0);
1560 new_bucket = lowest_bucket - 1;
1561 remove_peer(peer, lowest_bucket);
1562 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1563 k_buckets[new_bucket].tail,
1564 k_buckets[new_bucket].tail,
1566 k_buckets[new_bucket].peers_size++;
1572 * The current lowest bucket is full, so change the lowest
1573 * bucket to the next lower down, and move any appropriate
1574 * entries in the current lowest bucket to the new bucket.
1576 static void enable_next_bucket()
1578 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1579 struct PeerInfo *pos;
1580 GNUNET_assert(lowest_bucket > 0);
1581 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1582 pos = k_buckets[lowest_bucket].head;
1585 fprintf(stderr, "Printing RT before new bucket\n");
1586 print_routing_table();
1588 /* Populate the array of peers which should be in the next lowest bucket */
1591 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1592 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1596 /* Remove peers from lowest bucket, insert into next lowest bucket */
1597 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1598 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1599 lowest_bucket = lowest_bucket - 1;
1601 fprintf(stderr, "Printing RT after new bucket\n");
1602 print_routing_table();
1607 * Find the closest peer in our routing table to the
1610 * @return The closest peer in our routing table to the
1611 * key, or NULL on error.
1613 static struct PeerInfo *
1614 find_closest_peer (const GNUNET_HashCode *hc)
1616 struct PeerInfo *pos;
1617 struct PeerInfo *current_closest;
1618 unsigned int lowest_distance;
1619 unsigned int temp_distance;
1623 lowest_distance = -1;
1625 if (k_buckets[lowest_bucket].peers_size == 0)
1628 current_closest = NULL;
1629 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1631 pos = k_buckets[bucket].head;
1633 while ((pos != NULL) && (count < bucket_size))
1635 temp_distance = distance(&pos->id.hashPubKey, hc);
1636 if (temp_distance <= lowest_distance)
1638 lowest_distance = temp_distance;
1639 current_closest = pos;
1645 GNUNET_assert(current_closest != NULL);
1646 return current_closest;
1651 * Function called to send a request out to another peer.
1652 * Called both for locally initiated requests and those
1653 * received from other peers.
1655 * @param msg the encapsulated message
1656 * @param peer the peer to forward the message to
1657 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1659 static void forward_message (const struct GNUNET_MessageHeader *msg,
1660 struct PeerInfo *peer,
1661 struct DHT_MessageContext *msg_ctx)
1663 struct GNUNET_DHT_P2PRouteMessage *route_message;
1664 struct P2PPendingMessage *pending;
1668 increment_stats(STAT_ROUTE_FORWARDS);
1669 GNUNET_assert(peer != NULL);
1670 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1671 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1673 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1674 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1675 psize = sizeof(struct P2PPendingMessage) + msize;
1676 pending = GNUNET_malloc(psize);
1677 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1678 pending->importance = msg_ctx->importance;
1679 pending->timeout = msg_ctx->timeout;
1680 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1681 route_message->header.size = htons(msize);
1682 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1683 route_message->options = htonl(msg_ctx->msg_options);
1684 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1685 route_message->network_size = htonl(msg_ctx->network_size);
1686 route_message->desired_replication_level = htonl(msg_ctx->replication);
1687 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1688 if (msg_ctx->bloom != NULL)
1689 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1690 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1691 memcpy(&route_message[1], msg, ntohs(msg->size));
1693 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Adding pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
1695 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1696 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1697 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1702 * Task used to send ping messages to peers so that
1703 * they don't get disconnected.
1705 * @param cls the peer to send a ping message to
1706 * @param tc context, reason, etc.
1709 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1711 struct PeerInfo *peer = cls;
1712 struct GNUNET_MessageHeader ping_message;
1713 struct DHT_MessageContext msg_ctx;
1715 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1718 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1719 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1721 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
1723 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1725 forward_message(&ping_message, peer, &msg_ctx);
1726 peer->ping_task = GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1730 * Schedule PING messages for the top X peers in each
1731 * bucket of the routing table (so core won't disconnect them!)
1733 void schedule_ping_messages()
1735 unsigned int bucket;
1737 struct PeerInfo *pos;
1738 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1740 pos = k_buckets[bucket].head;
1744 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1745 GNUNET_SCHEDULER_add_now(&periodic_ping_task, pos);
1746 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1748 GNUNET_SCHEDULER_cancel(pos->ping_task);
1749 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1759 * Attempt to add a peer to our k-buckets.
1761 * @param peer the peer identity of the peer being added
1762 * @param bucket the bucket that we want this peer to go in
1763 * @param latency transport latency of this peer
1764 * @param distance transport distance to this peer
1766 * @return NULL if the peer was not added,
1767 * pointer to PeerInfo for new peer otherwise
1769 static struct PeerInfo *
1770 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1771 unsigned int bucket,
1772 struct GNUNET_TIME_Relative latency,
1773 unsigned int distance)
1776 struct PeerInfo *new_peer;
1778 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1781 peer_bucket = find_current_bucket(&peer->hashPubKey);
1783 GNUNET_assert(peer_bucket >= lowest_bucket);
1784 new_peer = add_peer(peer, peer_bucket, latency, distance);
1786 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1787 enable_next_bucket();
1789 schedule_ping_messages();
1796 * Task run to check for messages that need to be sent to a client.
1798 * @param client a ClientList, containing the client and any messages to be sent to it
1801 process_pending_messages (struct ClientList *client)
1803 if (client->pending_head == NULL)
1805 if (client->transmit_handle != NULL)
1808 client->transmit_handle =
1809 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1810 ntohs (client->pending_head->msg->
1812 GNUNET_TIME_UNIT_FOREVER_REL,
1813 &send_generic_reply, client);
1817 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1818 * request. A ClientList is passed as closure, take the head of the list
1819 * and copy it into buf, which has the result of sending the message to the
1822 * @param cls closure to this call
1823 * @param size maximum number of bytes available to send
1824 * @param buf where to copy the actual message to
1826 * @return the number of bytes actually copied, 0 indicates failure
1829 send_generic_reply (void *cls, size_t size, void *buf)
1831 struct ClientList *client = cls;
1833 struct PendingMessage *reply;
1837 client->transmit_handle = NULL;
1840 /* client disconnected */
1844 while ( (NULL != (reply = client->pending_head)) &&
1845 (size >= off + (msize = ntohs (reply->msg->size))))
1847 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1848 client->pending_tail,
1850 memcpy (&cbuf[off], reply->msg, msize);
1851 GNUNET_free (reply);
1854 process_pending_messages (client);
1856 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1857 "Transmitted %u bytes of replies to client\n",
1858 (unsigned int) off);
1865 * Add a PendingMessage to the clients list of messages to be sent
1867 * @param client the active client to send the message to
1868 * @param pending_message the actual message to send
1871 add_pending_message (struct ClientList *client,
1872 struct PendingMessage *pending_message)
1874 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1875 client->pending_tail,
1876 client->pending_tail,
1878 process_pending_messages (client);
1883 * Called when a reply needs to be sent to a client, as
1884 * a result it found to a GET or FIND PEER request.
1886 * @param client the client to send the reply to
1887 * @param message the encapsulated message to send
1888 * @param uid the unique identifier of this request
1891 send_reply_to_client (struct ClientList *client,
1892 const struct GNUNET_MessageHeader *message,
1893 unsigned long long uid,
1894 const GNUNET_HashCode *key)
1896 struct GNUNET_DHT_RouteResultMessage *reply;
1897 struct PendingMessage *pending_message;
1901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1902 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1904 msize = ntohs (message->size);
1905 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1906 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1908 GNUNET_break_op (0);
1911 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1912 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1913 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1914 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1915 reply->header.size = htons (tsize);
1916 reply->put_path_length = htons(0); /* FIXME: implement */
1917 reply->get_path_length = htons(0); /* FIXME: implement */
1918 reply->unique_id = GNUNET_htonll (uid);
1920 memcpy (&reply[1], message, msize);
1921 add_pending_message (client, pending_message);
1925 * Consider whether or not we would like to have this peer added to
1926 * our routing table. Check whether bucket for this peer is full,
1927 * if so return negative; if not return positive. Since peers are
1928 * only added on CORE level connect, this doesn't actually add the
1929 * peer to the routing table.
1931 * @param peer the peer we are considering adding
1933 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1936 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1940 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1941 return GNUNET_NO; /* We already know this peer (are connected even!) */
1942 bucket = find_current_bucket(&peer->hashPubKey);
1944 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1951 * Main function that handles whether or not to route a result
1952 * message to other peers, or to send to our local client.
1954 * @param msg the result message to be routed
1955 * @param msg_ctx context of the message we are routing
1957 * @return the number of peers the message was routed to,
1958 * GNUNET_SYSERR on failure
1960 static int route_result_message(struct GNUNET_MessageHeader *msg,
1961 struct DHT_MessageContext *msg_ctx)
1963 struct GNUNET_PeerIdentity new_peer;
1964 struct DHTQueryRecord *record;
1965 struct DHTRouteSource *pos;
1966 struct PeerInfo *peer_info;
1967 const struct GNUNET_MessageHeader *hello_msg;
1969 increment_stats(STAT_RESULTS);
1971 * If a find peer result message is received and contains a valid
1972 * HELLO for another peer, offer it to the transport service.
1974 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1976 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1979 hello_msg = &msg[1];
1980 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1982 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1986 else /* We have a valid hello, and peer id stored in new_peer */
1988 find_peer_context.count++;
1989 increment_stats(STAT_FIND_PEER_REPLY);
1990 if (GNUNET_YES == consider_peer(&new_peer))
1992 increment_stats(STAT_HELLOS_PROVIDED);
1993 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1994 GNUNET_CORE_peer_request_connect(cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1999 if (malicious_dropper == GNUNET_YES)
2002 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2004 if (record == NULL) /* No record of this message! */
2007 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2008 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
2009 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2011 #if DEBUG_DHT_ROUTING
2012 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2014 dhtlog_handle->insert_route (NULL,
2021 msg_ctx->peer, NULL);
2024 if (msg_ctx->bloom != NULL)
2026 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
2027 msg_ctx->bloom = NULL;
2035 #if STRICT_FORWARDING
2036 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2038 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2040 increment_stats("# find peer responses NOT forwarded (bloom match)");
2045 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2049 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2053 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2054 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2056 #if DEBUG_DHT_ROUTING
2057 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2059 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2061 GNUNET_YES, &my_identity, &msg_ctx->key,
2062 msg_ctx->peer, NULL);
2065 increment_stats(STAT_RESULTS_TO_CLIENT);
2066 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2067 increment_stats(STAT_GET_REPLY);
2069 send_reply_to_client(pos->client, msg,
2073 else /* Send to peer */
2075 peer_info = find_peer_by_id(&pos->source);
2076 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2082 if (msg_ctx->bloom == NULL)
2083 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2084 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
2085 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom, &peer_info->id.hashPubKey)))
2088 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2089 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2090 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&peer_info->id));
2092 #if DEBUG_DHT_ROUTING
2093 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2095 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id,
2098 GNUNET_NO, &my_identity, &msg_ctx->key,
2099 msg_ctx->peer, &pos->source);
2102 forward_result_message(msg, peer_info, msg_ctx);
2107 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2108 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2109 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&peer_info->id));
2115 if (msg_ctx->bloom != NULL)
2116 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
2121 * Iterator for local get request results,
2123 * @param cls closure for iterator, a DatacacheGetContext
2124 * @param exp when does this value expire?
2125 * @param key the key this data is stored under
2126 * @param size the size of the data identified by key
2127 * @param data the actual data
2128 * @param type the type of the data
2130 * @return GNUNET_OK to continue iteration, anything else
2131 * to stop iteration.
2134 datacache_get_iterator (void *cls,
2135 struct GNUNET_TIME_Absolute exp,
2136 const GNUNET_HashCode * key,
2137 size_t size, const char *data,
2138 enum GNUNET_BLOCK_Type type)
2140 struct DHT_MessageContext *msg_ctx = cls;
2141 struct DHT_MessageContext *new_msg_ctx;
2142 struct GNUNET_DHT_GetResultMessage *get_result;
2143 enum GNUNET_BLOCK_EvaluationResult eval;
2146 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2147 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2149 eval = GNUNET_BLOCK_evaluate (block_context,
2153 msg_ctx->reply_bf_mutator,
2155 msg_ctx->xquery_size,
2160 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2161 msg_ctx->do_forward = GNUNET_NO;
2162 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2163 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2164 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2166 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2167 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2168 get_result->header.size =
2169 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2170 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2171 get_result->type = htons (type);
2172 memcpy (&get_result[1], data, size);
2173 new_msg_ctx->peer = &my_identity;
2174 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2175 new_msg_ctx->hop_count = 0;
2176 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
2177 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2178 increment_stats(STAT_GET_RESPONSE_START);
2179 route_result_message(&get_result->header, new_msg_ctx);
2180 GNUNET_free(new_msg_ctx);
2181 GNUNET_free (get_result);
2183 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2185 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2186 "`%s:%s': Duplicate block error\n", my_short_id, "DHT");
2189 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2192 "`%s:%s': Invalid request error\n", my_short_id, "DHT");
2195 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2198 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2202 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2203 GNUNET_break_op (0);
2204 msg_ctx->do_forward = GNUNET_NO;
2206 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2208 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2209 "`%s:%s': Unsupported block type (%u) in response!\n", my_short_id, "DHT", type);
2211 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2219 * Main function that handles whether or not to route a message to other
2222 * @param msg the message to be routed
2223 * @param msg_ctx the context containing all pertinent information about the message
2226 route_message(const struct GNUNET_MessageHeader *msg,
2227 struct DHT_MessageContext *msg_ctx);
2231 * Server handler for all dht get requests, look for data,
2232 * if found, send response either to clients or other peers.
2234 * @param msg the actual get message
2235 * @param msg_ctx struct containing pertinent information about the get request
2237 * @return number of items found for GET request
2240 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2241 struct DHT_MessageContext *msg_ctx)
2243 const struct GNUNET_DHT_GetMessage *get_msg;
2246 unsigned int results;
2248 enum GNUNET_BLOCK_Type type;
2250 msize = ntohs (msg->size);
2251 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2256 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2257 bf_size = ntohs (get_msg->bf_size);
2258 msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2259 msg_ctx->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2260 if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2265 end = (const char*) &get_msg[1];
2266 if (msg_ctx->xquery_size == 0)
2268 msg_ctx->xquery = NULL;
2272 msg_ctx->xquery = (const void*) end;
2273 end += msg_ctx->xquery_size;
2277 msg_ctx->reply_bf = NULL;
2281 msg_ctx->reply_bf = GNUNET_CONTAINER_bloomfilter_init (end,
2283 GNUNET_DHT_GET_BLOOMFILTER_K);
2285 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2288 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2292 GNUNET_h2s (&msg_ctx->key),
2293 msg_ctx->unique_id);
2295 increment_stats(STAT_GETS);
2298 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2300 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2304 msg_ctx->do_forward = GNUNET_YES;
2305 if (datacache != NULL)
2307 = GNUNET_DATACACHE_get (datacache,
2308 &msg_ctx->key, type,
2309 &datacache_get_iterator,
2312 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2313 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2314 results, "GET", msg_ctx->unique_id);
2318 #if DEBUG_DHT_ROUTING
2319 if ((debug_routes) && (dhtlog_handle != NULL))
2321 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2322 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2326 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2328 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2329 msg_ctx->hop_count, GNUNET_YES,
2330 &my_identity, &msg_ctx->key, msg_ctx->peer,
2337 /* check query valid */
2338 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID
2339 == GNUNET_BLOCK_evaluate (block_context,
2343 msg_ctx->reply_bf_mutator,
2345 msg_ctx->xquery_size,
2348 GNUNET_break_op (0);
2349 msg_ctx->do_forward = GNUNET_NO;
2353 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2355 #if DEBUG_DHT_ROUTING
2356 if ((debug_routes) && (dhtlog_handle != NULL))
2358 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2359 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2364 if (msg_ctx->do_forward == GNUNET_YES)
2365 route_message (msg, msg_ctx);
2366 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2371 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2373 GNUNET_HashCode *key = cls;
2375 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, NULL));
2380 * Server handler for initiating local dht find peer requests
2382 * @param find_msg the actual find peer message
2383 * @param msg_ctx struct containing pertinent information about the request
2387 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2388 struct DHT_MessageContext *msg_ctx)
2390 struct GNUNET_MessageHeader *find_peer_result;
2391 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2392 struct DHT_MessageContext *new_msg_ctx;
2393 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2396 GNUNET_HashCode *recent_hash;
2397 struct GNUNET_MessageHeader *other_hello;
2398 size_t other_hello_size;
2399 struct GNUNET_PeerIdentity peer_id;
2401 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2402 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2403 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2406 other_hello_size = 0;
2407 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2409 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2410 other_hello = GNUNET_malloc(other_hello_size);
2411 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2412 if ((GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)other_hello) == 0) || (GNUNET_OK != GNUNET_HELLO_get_id((struct GNUNET_HELLO_Message *)other_hello, &peer_id)))
2414 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2415 GNUNET_free(other_hello);
2418 #if FIND_PEER_WITH_HELLO
2419 if (GNUNET_YES == consider_peer(&peer_id))
2421 increment_stats(STAT_HELLOS_PROVIDED);
2422 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2423 GNUNET_CORE_peer_request_connect(cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2424 route_message (find_msg, msg_ctx);
2425 GNUNET_free (other_hello);
2428 else /* We don't want this peer! */
2430 route_message (find_msg, msg_ctx);
2431 GNUNET_free (other_hello);
2438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2439 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2440 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2441 ntohs (find_msg->size),
2442 sizeof (struct GNUNET_MessageHeader));
2444 if (my_hello == NULL)
2447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2448 "`%s': Our HELLO is null, can't return.\n",
2451 GNUNET_free_non_null (other_hello);
2452 route_message (find_msg, msg_ctx);
2456 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2457 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2459 increment_stats(STAT_BLOOM_FIND_PEER);
2460 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2461 GNUNET_free_non_null(other_hello);
2462 route_message (find_msg, msg_ctx);
2463 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2465 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2467 #if RESTRICT_FIND_PEER
2470 * Ignore any find peer requests from a peer we have seen very recently.
2472 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! */
2474 increment_stats("# dht find peer requests ignored (recently seen!)");
2475 GNUNET_free_non_null(other_hello);
2480 * Use this check to only allow the peer to respond to find peer requests if
2481 * it would be beneficial to have the requesting peer in this peers routing
2482 * table. Can be used to thwart peers flooding the network with find peer
2483 * requests that we don't care about. However, if a new peer is joining
2484 * the network and has no other peers this is a problem (assume all buckets
2485 * full, no one will respond!).
2487 memcpy(&peer_id.hashPubKey, &msg_ctx->key, sizeof(GNUNET_HashCode));
2488 if (GNUNET_NO == consider_peer(&peer_id))
2490 increment_stats("# dht find peer requests ignored (do not need!)");
2491 GNUNET_free_non_null(other_hello);
2492 route_message (find_msg, msg_ctx);
2497 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2498 memcpy(recent_hash, &msg_ctx->key, sizeof(GNUNET_HashCode));
2499 if (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2500 &msg_ctx->key, NULL,
2501 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2503 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding recent remove task for key `%s`!\n", GNUNET_h2s(&msg_ctx->key));
2504 /* Only add a task if there wasn't one for this key already! */
2505 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30),
2506 &remove_recent_find_peer, recent_hash);
2510 GNUNET_free(recent_hash);
2511 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received duplicate find peer request too soon!\n");
2514 /* Simplistic find_peer functionality, always return our hello */
2515 hello_size = ntohs(my_hello->size);
2516 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2518 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2520 GNUNET_break_op (0);
2521 GNUNET_free_non_null(other_hello);
2525 find_peer_result = GNUNET_malloc (tsize);
2526 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2527 find_peer_result->size = htons (tsize);
2528 memcpy (&find_peer_result[1], my_hello, hello_size);
2530 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2531 "`%s': Sending hello size %d to requesting peer.\n",
2534 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2535 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2536 new_msg_ctx->peer = &my_identity;
2537 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2538 new_msg_ctx->hop_count = 0;
2539 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make find peer requests a higher priority */
2540 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2541 increment_stats(STAT_FIND_PEER_ANSWER);
2542 route_result_message(find_peer_result, new_msg_ctx);
2543 GNUNET_free(new_msg_ctx);
2544 #if DEBUG_DHT_ROUTING
2545 if ((debug_routes) && (dhtlog_handle != NULL))
2547 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2548 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2552 GNUNET_free_non_null(other_hello);
2553 GNUNET_free(find_peer_result);
2554 route_message (find_msg, msg_ctx);
2558 * Task used to republish data.
2559 * Forward declaration; function call loop.
2561 * @param cls closure (a struct RepublishContext)
2562 * @param tc runtime context for this task
2565 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2568 * Server handler for initiating local dht put requests
2570 * @param msg the actual put message
2571 * @param msg_ctx struct containing pertinent information about the request
2574 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2575 struct DHT_MessageContext *msg_ctx)
2577 const struct GNUNET_DHT_PutMessage *put_msg;
2578 enum GNUNET_BLOCK_Type put_type;
2581 struct RepublishContext *put_context;
2582 GNUNET_HashCode key;
2584 GNUNET_assert (ntohs (msg->size) >=
2585 sizeof (struct GNUNET_DHT_PutMessage));
2588 put_msg = (const struct GNUNET_DHT_PutMessage *)msg;
2589 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2591 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2594 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2595 ret = GNUNET_BLOCK_get_key (block_context,
2600 if (GNUNET_NO == ret)
2603 GNUNET_break_op (0);
2606 if ( (GNUNET_YES == ret) &&
2609 sizeof (GNUNET_HashCode))) )
2611 /* invalid wrapper: key mismatch! */
2612 GNUNET_break_op (0);
2615 /* ret == GNUNET_SYSERR means that there is no known relationship between
2616 data and the key, so we cannot check it */
2618 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2619 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2620 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2622 #if DEBUG_DHT_ROUTING
2623 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2625 if ((debug_routes) && (dhtlog_handle != NULL))
2627 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2628 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2634 if (msg_ctx->closest != GNUNET_YES)
2636 route_message (msg, msg_ctx);
2641 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2642 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2643 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2646 #if DEBUG_DHT_ROUTING
2647 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2649 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2650 msg_ctx->hop_count, GNUNET_YES,
2651 &my_identity, &msg_ctx->key, msg_ctx->peer,
2655 if ((debug_routes) && (dhtlog_handle != NULL))
2657 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2658 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2663 increment_stats(STAT_PUTS_INSERTED);
2664 if (datacache != NULL)
2666 ret = GNUNET_DATACACHE_put (datacache, &msg_ctx->key, data_size,
2667 (char *) &put_msg[1], put_type,
2668 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2670 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2672 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2673 memcpy(&put_context->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
2674 put_context->type = put_type;
2675 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content, put_context);
2679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2680 "`%s:%s': %s request received, but have no datacache!\n",
2681 my_short_id, "DHT", "PUT");
2683 if (stop_on_closest == GNUNET_NO)
2684 route_message (msg, msg_ctx);
2688 * Estimate the diameter of the network based
2689 * on how many buckets are currently in use.
2690 * Concept here is that the diameter of the network
2691 * is roughly the distance a message must travel in
2692 * order to reach its intended destination. Since
2693 * at each hop we expect to get one bit closer, and
2694 * we have one bit per bucket, the number of buckets
2695 * in use should be the largest number of hops for
2696 * a successful message. (of course, this assumes we
2697 * know all peers in the network!)
2699 * @return ballpark diameter figure
2701 static unsigned int estimate_diameter()
2703 return MAX_BUCKETS - lowest_bucket;
2707 * To how many peers should we (on average)
2708 * forward the request to obtain the desired
2709 * target_replication count (on average).
2711 * Always 0, 1 or 2 (don't send, send once, split)
2714 get_forward_count (unsigned int hop_count, size_t target_replication)
2717 double target_count;
2718 double random_probability;
2720 uint32_t random_value;
2722 unsigned int target_value;
2723 unsigned int diameter;
2726 * If we are behaving in strict kademlia mode, send multiple initial requests,
2727 * but then only send to 1 or 0 peers based strictly on the number of hops.
2729 if (strict_kademlia == GNUNET_YES)
2732 return DHT_KADEMLIA_REPLICATION;
2733 else if (hop_count < max_hops)
2739 /* FIXME: the smaller we think the network is the more lenient we should be for
2740 * routing right? The estimation below only works if we think we have reasonably
2741 * full routing tables, which for our RR topologies may not be the case!
2743 diameter = estimate_diameter ();
2744 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size) && (use_max_hops == GNUNET_NO))
2747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2748 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2749 "DHT", estimate_diameter(), lowest_bucket);
2753 else if (hop_count > max_hops)
2756 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2757 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2764 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2765 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2766 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2767 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2768 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2769 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2770 RAND_MAX)) / RAND_MAX;
2771 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2774 //while (target_value < target_count)
2775 if (target_value < target_count)
2776 target_value++; /* target_value is ALWAYS 1 after this "loop", right? Because target_count is always > 0, right? Or does it become 0.00000... at some point because the hop count is so high? */
2779 //if ((target_count + 1 - (double)target_value) > random_probability)
2780 if ((target_count) > random_probability)
2784 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2785 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "replication %u, at hop %d, will split with probability %f\n", target_replication, hop_count, target_replication / (double)((target_replication * (hop_count + 1) + diameter) + 1));
2787 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2788 if (random_value < target_replication)
2790 increment_stats("# DHT Messages split");
2794 return target_value;
2798 * Check whether my identity is closer than any known peers.
2799 * If a non-null bloomfilter is given, check if this is the closest
2800 * peer that hasn't already been routed to.
2802 * @param target hash code to check closeness to
2803 * @param bloom bloomfilter, exclude these entries from the decision
2805 * Return GNUNET_YES if node location is closest, GNUNET_NO
2809 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2815 struct PeerInfo *pos;
2816 unsigned int my_distance;
2818 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2821 bucket_num = find_current_bucket(target);
2823 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2824 my_distance = distance(&my_identity.hashPubKey, target);
2825 pos = k_buckets[bucket_num].head;
2827 while ((pos != NULL) && (count < bucket_size))
2829 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2832 continue; /* Skip already checked entries */
2835 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2836 if (other_bits > bits)
2838 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2840 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2842 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2848 /* No peers closer, we are the closest! */
2854 * Return this peers adjusted value based on the convergence
2855 * function chosen. This is the key function for randomized
2856 * routing decisions.
2858 * @param target the key of the request
2859 * @param peer the peer we would like the value of
2860 * @param hops number of hops this message has already traveled
2862 * @return bit distance from target to peer raised to an exponent
2863 * adjusted based on the current routing convergence algorithm
2866 static unsigned long long
2867 converge_distance (const GNUNET_HashCode *target,
2868 struct PeerInfo *peer,
2871 unsigned long long ret;
2872 unsigned int other_matching_bits;
2873 double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
2874 double temp_modifier;
2880 curr_max_hops = max_hops;
2882 curr_max_hops = (estimate_diameter() + 1) * 2;
2884 if (converge_modifier > 0)
2885 temp_modifier = converge_modifier * base_converge_modifier;
2888 temp_modifier = base_converge_modifier;
2889 base_converge_modifier = 0.0;
2892 GNUNET_assert(temp_modifier > 0);
2894 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2896 switch (converge_option)
2898 case DHT_CONVERGE_RANDOM:
2899 return 1; /* Always return 1, choose equally among all peers */
2900 case DHT_CONVERGE_LINEAR:
2901 calc_value = hops * curr_max_hops * temp_modifier;
2903 case DHT_CONVERGE_SQUARE:
2905 * Simple square based curve.
2907 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * temp_modifier));
2909 case DHT_CONVERGE_EXPONENTIAL:
2911 * Simple exponential curve.
2913 if (base_converge_modifier > 0)
2914 calc_value = (temp_modifier * hops * hops) / curr_max_hops;
2916 calc_value = (hops * hops) / curr_max_hops;
2918 case DHT_CONVERGE_BINARY:
2920 * If below the cutoff, route randomly (return 1),
2921 * If above the cutoff, return the maximum possible
2922 * value first (always route to closest, because
2926 if (hops > converge_modifier) /* Past cutoff */
2935 /* Take the log (base e) of the number of bits matching the other peer */
2936 exponent = log(other_matching_bits);
2938 /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
2939 if (exponent * calc_value >= 44.361419555836498)
2942 /* Clear errno and all math exceptions */
2944 feclearexcept(FE_ALL_EXCEPT);
2945 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2946 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2949 if (0 != fetestexcept(FE_OVERFLOW))
2950 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2951 if (0 != fetestexcept(FE_INVALID))
2952 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2953 if (0 != fetestexcept(FE_UNDERFLOW))
2954 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2962 * Comparison function for two struct PeerInfo's
2963 * which have already had their matching bits to
2964 * some target calculated.
2966 * @param p1 a pointer pointer to a struct PeerInfo
2967 * @param p2 a pointer pointer to a struct PeerInfo
2969 * @return 0 if equidistant to target,
2970 * -1 if p1 is closer,
2974 compare_peers (const void *p1, const void *p2)
2976 struct PeerInfo **first = (struct PeerInfo **)p1;
2977 struct PeerInfo **second = (struct PeerInfo **)p2;
2979 if ((*first)->matching_bits > (*second)->matching_bits)
2981 if ((*first)->matching_bits < (*second)->matching_bits)
2989 * Select a peer from the routing table that would be a good routing
2990 * destination for sending a message for "target". The resulting peer
2991 * must not be in the set of blocked peers.<p>
2993 * Note that we should not ALWAYS select the closest peer to the
2994 * target, peers further away from the target should be chosen with
2995 * exponentially declining probability.
2997 * @param target the key we are selecting a peer to route to
2998 * @param bloom a bloomfilter containing entries this request has seen already
3000 * @return Peer to route to, or NULL on error
3002 static struct PeerInfo *
3003 select_peer (const GNUNET_HashCode * target,
3004 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3009 unsigned int offset;
3010 unsigned int my_matching_bits;
3012 struct PeerInfo *pos;
3013 struct PeerInfo *sorted_closest[bucket_size];
3014 unsigned long long temp_converge_distance;
3015 unsigned long long total_distance;
3016 unsigned long long selected;
3018 unsigned long long stats_total_distance;
3022 unsigned int distance;
3023 unsigned int largest_distance;
3024 struct PeerInfo *chosen;
3026 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
3029 if (strict_kademlia == GNUNET_YES)
3031 largest_distance = 0;
3033 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3035 pos = k_buckets[bc].head;
3037 while ((pos != NULL) && (count < bucket_size))
3039 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3040 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3042 distance = inverse_distance (target, &pos->id.hashPubKey);
3043 if (distance > largest_distance)
3046 largest_distance = distance;
3054 if ((largest_distance > 0) && (chosen != NULL))
3056 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
3067 /* Three steps: order peers in closest bucket (most matching bits).
3068 * Then go over all LOWER buckets (matching same bits we do)
3069 * Then go over all HIGHER buckets (matching less then we do)
3072 closest_bucket = find_current_bucket(target);
3073 GNUNET_assert(closest_bucket >= lowest_bucket);
3074 pos = k_buckets[closest_bucket].head;
3076 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3077 memset(sorted_closest, 0, sizeof(sorted_closest));
3078 /* Put any peers in the closest bucket in the sorting array */
3079 while ((pos != NULL) && (count < bucket_size))
3081 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3085 continue; /* Ignore bloomfiltered peers */
3087 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
3088 sorted_closest[offset] = pos;
3094 /* Sort the peers in descending order */
3095 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
3097 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3098 for (i = 0; i < offset; i++)
3100 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3101 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3102 break; /* Ignore bloomfiltered peers */
3103 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3104 total_distance += temp_converge_distance;
3106 break; /* overflow case */
3109 /* Now handle peers in lower buckets (matches same # of bits as target) */
3110 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3112 pos = k_buckets[bc].head;
3114 while ((pos != NULL) && (count < bucket_size))
3116 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3120 continue; /* Ignore bloomfiltered peers */
3122 temp_converge_distance = converge_distance(target, pos, hops);
3123 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3124 total_distance += temp_converge_distance;
3126 break; /* overflow case */
3132 /* Now handle all the further away peers */
3133 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3135 pos = k_buckets[bc].head;
3137 while ((pos != NULL) && (count < bucket_size))
3139 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3143 continue; /* Ignore bloomfiltered peers */
3145 temp_converge_distance = converge_distance(target, pos, hops);
3146 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3147 total_distance += temp_converge_distance;
3149 break; /* overflow case */
3155 if (total_distance == 0) /* No peers to select from! */
3157 increment_stats("# select_peer, total_distance == 0");
3161 #if DEBUG_DHT_ROUTING > 1
3164 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3165 stats_total_distance = 0;
3166 for (i = 0; i < offset; i++)
3168 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3169 break; /* Ignore bloomfiltered peers */
3170 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3171 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3172 stats_total_distance += temp_converge_distance;
3174 break; /* overflow case */
3175 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n", GNUNET_CRYPTO_hash_matching_bits(&sorted_closest[i]->id.hashPubKey, target), GNUNET_CRYPTO_hash_matching_bits(&sorted_closest[i]->id.hashPubKey, &my_identity.hashPubKey), (temp_converge_distance / (double)total_distance) * 100, temp_converge_distance);
3178 /* Now handle peers in lower buckets (matches same # of bits as target) */
3179 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3181 pos = k_buckets[bc].head;
3183 while ((pos != NULL) && (count < bucket_size))
3185 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3189 continue; /* Ignore bloomfiltered peers */
3191 temp_converge_distance = converge_distance(target, pos, hops);
3192 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3193 stats_total_distance += temp_converge_distance;
3195 break; /* overflow case */
3196 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n", GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target), GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey), (temp_converge_distance / (double)total_distance) * 100, temp_converge_distance);
3202 /* Now handle all the further away peers */
3203 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3205 pos = k_buckets[bc].head;
3207 while ((pos != NULL) && (count < bucket_size))
3209 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3213 continue; /* Ignore bloomfiltered peers */
3215 temp_converge_distance = converge_distance(target, pos, hops);
3216 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3217 stats_total_distance += temp_converge_distance;
3219 break; /* overflow case */
3220 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n", GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target), GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey), (temp_converge_distance / (double)total_distance) * 100, temp_converge_distance);
3225 /* END PRINT STATS */
3228 /* Now actually choose a peer */
3229 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3231 /* Go over closest sorted peers. */
3232 for (i = 0; i < offset; i++)
3234 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3235 break; /* Ignore bloomfiltered peers */
3236 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3237 if (temp_converge_distance >= selected)
3238 return sorted_closest[i];
3240 selected -= temp_converge_distance;
3243 /* Now handle peers in lower buckets (matches same # of bits as target) */
3244 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3246 pos = k_buckets[bc].head;
3248 while ((pos != NULL) && (count < bucket_size))
3250 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3254 continue; /* Ignore bloomfiltered peers */
3256 temp_converge_distance = converge_distance(target, pos, hops);
3257 if (temp_converge_distance >= selected)
3260 selected -= temp_converge_distance;
3266 /* Now handle all the further away peers */
3267 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3269 pos = k_buckets[bc].head;
3271 while ((pos != NULL) && (count < bucket_size))
3273 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3277 continue; /* Ignore bloomfiltered peers */
3279 temp_converge_distance = converge_distance(target, pos, hops);
3280 if (temp_converge_distance >= selected)
3283 selected -= temp_converge_distance;
3289 increment_stats("# failed to select peer");
3295 * Task used to remove recent entries, either
3296 * after timeout, when full, or on shutdown.
3298 * @param cls the entry to remove
3299 * @param tc context, reason, etc.
3302 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3304 struct RecentRequest *req = cls;
3305 static GNUNET_HashCode hash;
3307 GNUNET_assert(req != NULL);
3308 hash_from_uid(req->uid, &hash);
3309 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3310 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3311 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3315 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3317 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3318 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3325 * Task used to remove forwarding entries, either
3326 * after timeout, when full, or on shutdown.
3328 * @param cls the entry to remove
3329 * @param tc context, reason, etc.
3332 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3334 struct DHTRouteSource *source_info = cls;
3335 struct DHTQueryRecord *record;
3336 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3337 record = source_info->record;
3338 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3340 if (record->head == NULL) /* No more entries in DLL */
3342 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3343 GNUNET_free(record);
3345 if (source_info->find_peers_responded != NULL)
3346 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3347 GNUNET_free(source_info);
3351 * Remember this routing request so that if a reply is
3352 * received we can either forward it to the correct peer
3353 * or return the result locally.
3355 * @param msg_ctx Context of the route request
3357 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3359 static int cache_response(struct DHT_MessageContext *msg_ctx)
3361 struct DHTQueryRecord *record;
3362 struct DHTRouteSource *source_info;
3363 struct DHTRouteSource *pos;
3364 struct GNUNET_TIME_Absolute now;
3365 unsigned int current_size;
3367 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3368 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3370 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3371 GNUNET_assert(source_info != NULL);
3372 record = source_info->record;
3373 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3374 if (record->head == NULL) /* No more entries in DLL */
3376 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3377 GNUNET_free(record);
3379 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3380 GNUNET_SCHEDULER_cancel(source_info->delete_task);
3381 if (source_info->find_peers_responded != NULL)
3382 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3383 GNUNET_free(source_info);
3384 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3386 now = GNUNET_TIME_absolute_get();
3387 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3388 if (record != NULL) /* Already know this request! */
3393 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3394 break; /* Already have this peer in reply list! */
3397 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3399 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.abs_value);
3405 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3406 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3407 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3410 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3411 source_info->record = record;
3412 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3413 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3414 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3415 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3416 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3418 source_info->client = msg_ctx->client;
3419 now = GNUNET_TIME_absolute_get_forever();
3421 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.abs_value);
3423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3424 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3425 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3432 * Main function that handles whether or not to route a message to other
3435 * @param msg the message to be routed
3436 * @param msg_ctx the context containing all pertinent information about the message
3439 route_message(const struct GNUNET_MessageHeader *msg,
3440 struct DHT_MessageContext *msg_ctx)
3443 struct PeerInfo *selected;
3444 #if DEBUG_DHT_ROUTING > 1
3445 struct PeerInfo *nearest;
3447 unsigned int forward_count;
3448 struct RecentRequest *recent_req;
3449 GNUNET_HashCode unique_hash;
3450 char *stat_forward_count;
3451 char *temp_stat_str;
3452 #if DEBUG_DHT_ROUTING
3456 if (malicious_dropper == GNUNET_YES)
3458 #if DEBUG_DHT_ROUTING
3459 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3461 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3462 msg_ctx->hop_count, GNUNET_SYSERR,
3463 &my_identity, &msg_ctx->key, msg_ctx->peer,
3467 if (msg_ctx->bloom != NULL)
3468 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3472 increment_stats(STAT_ROUTES);
3473 forward_count = get_forward_count(msg_ctx->hop_count, msg_ctx->replication);
3474 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3475 increment_stats(stat_forward_count);
3476 GNUNET_free(stat_forward_count);
3477 if (msg_ctx->bloom == NULL)
3478 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3480 if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3484 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3485 * any closer peers (which is being checked for below). Since we are doing recursive
3486 * routing we have no choice but to stop forwarding in this case. This means that at
3487 * any given step the request may NOT be forwarded to alpha peers (because routes will
3488 * stop and the parallel route will not be aware of it). Of course, assuming that we
3489 * have fulfilled the Kademlia requirements for routing table fullness this will never
3490 * ever ever be a problem.
3492 * However, is this fair?
3494 * Since we use these requests to build our routing tables (and we build them in the
3495 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3496 * routing tables still get constructed.
3498 if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) && (msg_ctx->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3501 #if DEBUG_DHT_ROUTING
3502 if (forward_count == 0)
3503 ret = GNUNET_SYSERR;
3507 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3509 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3510 msg_ctx->hop_count, ret,
3511 &my_identity, &msg_ctx->key, msg_ctx->peer,
3517 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3518 hash_from_uid (msg_ctx->unique_id, &unique_hash);
3519 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3521 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3522 GNUNET_assert(recent_req != NULL);
3523 if (0 != memcmp(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode)))
3524 increment_stats(STAT_DUPLICATE_UID);
3527 increment_stats(STAT_RECENT_SEEN);
3528 GNUNET_CONTAINER_bloomfilter_or2(msg_ctx->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3533 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3534 recent_req->uid = msg_ctx->unique_id;
3535 memcpy(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3536 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3537 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().abs_value);
3538 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3539 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3542 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3544 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3545 GNUNET_assert(recent_req != NULL);
3546 GNUNET_SCHEDULER_cancel(recent_req->remove_task);
3547 GNUNET_SCHEDULER_add_now(&remove_recent, recent_req);
3550 for (i = 0; i < forward_count; i++)
3552 selected = select_peer(&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3554 if (selected != NULL)
3556 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &msg_ctx->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &msg_ctx->key))
3557 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", msg_ctx->hop_count);
3559 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", msg_ctx->hop_count);
3560 if (temp_stat_str != NULL)
3562 increment_stats(temp_stat_str);
3563 GNUNET_free(temp_stat_str);
3565 GNUNET_CONTAINER_bloomfilter_add(msg_ctx->bloom, &selected->id.hashPubKey);
3566 #if DEBUG_DHT_ROUTING > 1
3567 nearest = find_closest_peer(&msg_ctx->key);
3568 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3569 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3570 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3571 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&selected->id), nearest_buf, GNUNET_CRYPTO_hash_matching_bits(&nearest->id.hashPubKey, msg_ctx->key), distance(&nearest->id.hashPubKey, msg_ctx->key));
3572 GNUNET_free(nearest_buf);
3574 #if DEBUG_DHT_ROUTING
3575 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3577 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3578 msg_ctx->hop_count, GNUNET_NO,
3579 &my_identity, &msg_ctx->key, msg_ctx->peer,
3583 forward_message(msg, selected, msg_ctx);
3587 if (msg_ctx->bloom != NULL)
3589 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, msg_ctx->bloom, DHT_BLOOM_SIZE);
3590 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3597 * Main function that handles whether or not to route a message to other
3600 * @param msg the message to be routed
3601 * @param msg_ctx the context containing all pertinent information about the message
3604 demultiplex_message(const struct GNUNET_MessageHeader *msg,
3605 struct DHT_MessageContext *msg_ctx)
3607 msg_ctx->closest = am_closest_peer(&msg_ctx->key, NULL);
3608 switch (ntohs(msg->type))
3610 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3611 cache_response (msg_ctx);
3612 handle_dht_get (msg, msg_ctx);
3614 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3615 increment_stats(STAT_PUTS);
3616 handle_dht_put (msg, msg_ctx);
3618 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3619 increment_stats(STAT_FIND_PEER);
3620 if (((msg_ctx->hop_count > 0) && (0 != memcmp(msg_ctx->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (msg_ctx->client != NULL))
3622 cache_response (msg_ctx);
3623 if ((msg_ctx->closest == GNUNET_YES) || (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3624 handle_dht_find_peer (msg, msg_ctx);
3627 route_message (msg, msg_ctx);
3628 #if DEBUG_DHT_ROUTING
3629 if (msg_ctx->hop_count == 0) /* Locally initiated request */
3631 if ((debug_routes) && (dhtlog_handle != NULL))
3633 dhtlog_handle->insert_dhtkey(NULL, &msg_ctx->key);
3634 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
3635 msg_ctx->hop_count, GNUNET_NO, &my_identity,
3642 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3643 "`%s': Message type (%d) not handled, forwarding anyway!\n", "DHT", ntohs(msg->type));
3644 route_message (msg, msg_ctx);
3652 * Iterator for local get request results,
3654 * @param cls closure for iterator, NULL
3655 * @param exp when does this value expire?
3656 * @param key the key this data is stored under
3657 * @param size the size of the data identified by key
3658 * @param data the actual data
3659 * @param type the type of the data
3661 * @return GNUNET_OK to continue iteration, anything else
3662 * to stop iteration.
3665 republish_content_iterator (void *cls,
3666 struct GNUNET_TIME_Absolute exp,
3667 const GNUNET_HashCode * key,
3668 size_t size, const char *data, uint32_t type)
3671 struct DHT_MessageContext *new_msg_ctx;
3672 struct GNUNET_DHT_PutMessage *put_msg;
3674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3675 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3677 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3680 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3681 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3682 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3683 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3684 put_msg->type = htons (type);
3685 memcpy (&put_msg[1], data, size);
3686 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3687 new_msg_ctx->replication = ntohl (DEFAULT_PUT_REPLICATION);
3688 new_msg_ctx->msg_options = ntohl (0);
3689 new_msg_ctx->network_size = estimate_diameter();
3690 new_msg_ctx->peer = &my_identity;
3691 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3692 new_msg_ctx->hop_count = 0;
3693 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3694 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3695 increment_stats(STAT_PUT_START);
3696 demultiplex_message(&put_msg->header, new_msg_ctx);
3698 GNUNET_free(new_msg_ctx);
3699 GNUNET_free (put_msg);
3704 * Task used to republish data.
3706 * @param cls closure (a struct RepublishContext)
3707 * @param tc runtime context for this task
3710 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3712 struct RepublishContext *put_context = cls;
3714 unsigned int results;
3716 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3718 GNUNET_free(put_context);
3722 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3723 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3724 if (results == 0) /* Data must have expired */
3725 GNUNET_free(put_context);
3726 else /* Reschedule task for next time period */
3727 GNUNET_SCHEDULER_add_delayed(dht_republish_frequency, &republish_content, put_context);
3733 * Iterator over hash map entries.
3735 * @param cls client to search for in source routes
3736 * @param key current key code (ignored)
3737 * @param value value in the hash map, a DHTQueryRecord
3738 * @return GNUNET_YES if we should continue to
3742 static int find_client_records (void *cls,
3743 const GNUNET_HashCode * key, void *value)
3745 struct ClientList *client = cls;
3746 struct DHTQueryRecord *record = value;
3747 struct DHTRouteSource *pos;
3751 if (pos->client == client)
3757 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3758 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3759 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3760 GNUNET_SCHEDULER_cancel(pos->delete_task);
3762 if (pos->find_peers_responded != NULL)
3763 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3766 if (record->head == NULL) /* No more entries in DLL */
3768 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3769 GNUNET_free(record);
3775 * Functions with this signature are called whenever a client
3776 * is disconnected on the network level.
3778 * @param cls closure (NULL for dht)
3779 * @param client identification of the client; NULL
3780 * for the last call when the server is destroyed
3782 static void handle_client_disconnect (void *cls,
3783 struct GNUNET_SERVER_Client* client)
3785 struct ClientList *pos = client_list;
3786 struct ClientList *prev;
3787 struct ClientList *found;
3788 struct PendingMessage *reply;
3794 if (pos->client_handle == client)
3797 prev->next = pos->next;
3799 client_list = pos->next;
3809 while(NULL != (reply = found->pending_head))
3811 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3814 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3820 * Find a client if it exists, add it otherwise.
3822 * @param client the server handle to the client
3824 * @return the client if found, a new client otherwise
3826 static struct ClientList *
3827 find_active_client (struct GNUNET_SERVER_Client *client)
3829 struct ClientList *pos = client_list;
3830 struct ClientList *ret;
3834 if (pos->client_handle == client)
3839 ret = GNUNET_malloc (sizeof (struct ClientList));
3840 ret->client_handle = client;
3841 ret->next = client_list;
3849 * Task to send a malicious put message across the network.
3851 * @param cls closure for this task
3852 * @param tc the context under which the task is running
3855 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3857 static struct GNUNET_DHT_PutMessage put_message;
3858 static struct DHT_MessageContext msg_ctx;
3859 static GNUNET_HashCode key;
3860 uint32_t random_key;
3862 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3864 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3865 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3866 put_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3867 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3868 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3869 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3870 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3871 memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3872 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3873 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3874 msg_ctx.msg_options = ntohl (0);
3875 msg_ctx.network_size = estimate_diameter();
3876 msg_ctx.peer = &my_identity;
3877 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3878 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3879 #if DEBUG_DHT_ROUTING
3880 if (dhtlog_handle != NULL)
3881 dhtlog_handle->insert_dhtkey(NULL, &key);
3883 increment_stats(STAT_PUT_START);
3884 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3885 demultiplex_message(&put_message.header, &msg_ctx);
3886 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3891 * Task to send a malicious put message across the network.
3893 * @param cls closure for this task
3894 * @param tc the context under which the task is running
3897 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3899 static struct GNUNET_DHT_GetMessage get_message;
3900 struct DHT_MessageContext msg_ctx;
3901 static GNUNET_HashCode key;
3902 uint32_t random_key;
3904 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3907 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3908 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3909 get_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3910 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3911 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3912 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3913 memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3914 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3915 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3916 msg_ctx.msg_options = ntohl (0);
3917 msg_ctx.network_size = estimate_diameter();
3918 msg_ctx.peer = &my_identity;
3919 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3920 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3921 #if DEBUG_DHT_ROUTING
3922 if (dhtlog_handle != NULL)
3923 dhtlog_handle->insert_dhtkey(NULL, &key);
3925 increment_stats(STAT_GET_START);
3926 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3927 demultiplex_message (&get_message.header, &msg_ctx);
3928 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3934 * Iterator over hash map entries.
3936 * @param cls closure
3937 * @param key current key code
3938 * @param value value in the hash map
3939 * @return GNUNET_YES if we should continue to
3944 add_known_to_bloom (void *cls,
3945 const GNUNET_HashCode * key,
3948 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3949 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3954 * Task to send a find peer message for our own peer identifier
3955 * so that we can find the closest peers in the network to ourselves
3956 * and attempt to connect to them.
3958 * @param cls closure for this task
3959 * @param tc the context under which the task is running
3962 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3964 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3965 struct DHT_MessageContext msg_ctx;
3966 struct GNUNET_TIME_Relative next_send_time;
3967 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3969 struct GNUNET_TIME_Relative time_diff;
3970 struct GNUNET_TIME_Absolute end;
3972 double count_per_interval;
3974 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3977 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! */
3979 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3980 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3981 &send_find_peer_message, NULL);
3982 newly_found_peers = 0;
3986 increment_stats(STAT_FIND_PEER_START);
3988 end = GNUNET_TIME_absolute_get();
3989 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3991 if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
3993 multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
3994 count_per_interval = find_peer_context.count / multiplier;
3998 multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
3999 count_per_interval = find_peer_context.count * multiplier;
4003 #if FIND_PEER_WITH_HELLO
4004 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4005 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4006 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4008 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
4009 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
4011 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4012 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4013 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
4014 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
4015 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4016 memcpy(&msg_ctx.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
4017 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
4018 msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4019 msg_ctx.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4020 msg_ctx.network_size = estimate_diameter();
4021 msg_ctx.peer = &my_identity;
4022 msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4023 msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4025 demultiplex_message(&find_peer_msg->header, &msg_ctx);
4026 GNUNET_free(find_peer_msg);
4027 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4028 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
4030 if (newly_found_peers < bucket_size)
4032 next_send_time.rel_value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4033 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4034 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4038 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4039 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4040 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4043 GNUNET_assert (next_send_time.rel_value != 0);
4044 find_peer_context.count = 0;
4045 newly_found_peers = 0;
4046 find_peer_context.start = GNUNET_TIME_absolute_get();
4047 if (GNUNET_YES == do_find_peer)
4049 GNUNET_SCHEDULER_add_delayed (next_send_time,
4050 &send_find_peer_message, NULL);
4055 * Handler for any generic DHT messages, calls the appropriate handler
4056 * depending on message type, sends confirmation if responses aren't otherwise
4059 * @param cls closure for the service
4060 * @param client the client we received this message from
4061 * @param message the actual message received
4064 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4065 const struct GNUNET_MessageHeader *message)
4067 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
4068 const struct GNUNET_MessageHeader *enc_msg;
4069 struct DHT_MessageContext msg_ctx;
4071 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4074 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4078 ntohs (message->type),
4079 GNUNET_h2s (&dht_msg->key),
4080 GNUNET_ntohll (dht_msg->unique_id));
4082 #if DEBUG_DHT_ROUTING
4083 if (dhtlog_handle != NULL)
4084 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4086 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4087 msg_ctx.client = find_active_client (client);
4088 memcpy(&msg_ctx.key, &dht_msg->key, sizeof(GNUNET_HashCode));
4089 msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4090 msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
4091 msg_ctx.msg_options = ntohl (dht_msg->options);
4092 msg_ctx.network_size = estimate_diameter();
4093 msg_ctx.peer = &my_identity;
4094 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
4095 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4096 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4097 increment_stats(STAT_GET_START);
4098 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4099 increment_stats(STAT_PUT_START);
4100 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4101 increment_stats(STAT_FIND_PEER_START);
4103 demultiplex_message(enc_msg, &msg_ctx);
4105 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4110 * Handler for any locally received DHT control messages,
4111 * sets malicious flags mostly for now.
4113 * @param cls closure for the service
4114 * @param client the client we received this message from
4115 * @param message the actual message received
4119 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4120 const struct GNUNET_MessageHeader *message)
4122 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4123 (const struct GNUNET_DHT_ControlMessage *) message;
4125 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4126 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4127 "CONTROL", ntohs(dht_control_msg->command));
4130 switch (ntohs(dht_control_msg->command))
4132 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4133 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4134 GNUNET_SCHEDULER_add_now(&send_find_peer_message, NULL);
4137 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4138 if (ntohs(dht_control_msg->variable) > 0)
4139 malicious_get_frequency = ntohs(dht_control_msg->variable);
4140 if (malicious_get_frequency == 0)
4141 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4142 if (malicious_getter != GNUNET_YES)
4143 GNUNET_SCHEDULER_add_now(&malicious_get_task, NULL);
4144 malicious_getter = GNUNET_YES;
4145 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4146 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4148 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4149 if (ntohs(dht_control_msg->variable) > 0)
4150 malicious_put_frequency = ntohs(dht_control_msg->variable);
4151 if (malicious_put_frequency == 0)
4152 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4153 if (malicious_putter != GNUNET_YES)
4154 GNUNET_SCHEDULER_add_now(&malicious_put_task, NULL);
4155 malicious_putter = GNUNET_YES;
4156 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4157 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4159 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4160 #if DEBUG_DHT_ROUTING
4161 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4162 dhtlog_handle->set_malicious(&my_identity);
4164 malicious_dropper = GNUNET_YES;
4165 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4166 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4170 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4171 "%s:%s Unknown control command type `%d'!\n",
4173 ntohs(dht_control_msg->command));
4177 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4181 * Handler for any generic DHT stop messages, calls the appropriate handler
4182 * depending on message type (if processed locally)
4184 * @param cls closure for the service
4185 * @param client the client we received this message from
4186 * @param message the actual message received
4190 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4191 const struct GNUNET_MessageHeader *message)
4194 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4195 (const struct GNUNET_DHT_StopMessage *) message;
4196 struct DHTQueryRecord *record;
4197 struct DHTRouteSource *pos;
4199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4200 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4201 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4203 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
4210 if ((pos->client != NULL) && (pos->client->client_handle == client))
4212 GNUNET_SCHEDULER_cancel(pos->delete_task);
4213 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4214 GNUNET_SCHEDULER_add_now(&remove_forward_entry, pos);
4220 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4225 * Core handler for p2p route requests.
4228 handle_dht_p2p_route_request (void *cls,
4229 const struct GNUNET_PeerIdentity *peer,
4230 const struct GNUNET_MessageHeader *message,
4231 struct GNUNET_TIME_Relative latency, uint32_t distance)
4234 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4235 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4237 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4238 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4239 struct DHT_MessageContext *msg_ctx;
4241 if (get_max_send_delay().rel_value > MAX_REQUEST_TIME.rel_value)
4243 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending of previous replies took too long, backing off!\n");
4244 increment_stats("# route requests dropped due to high load");
4245 decrease_max_send_delay(get_max_send_delay());
4249 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4252 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4257 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4262 msg_ctx = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4263 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4264 GNUNET_assert(msg_ctx->bloom != NULL);
4265 msg_ctx->hop_count = ntohl(incoming->hop_count);
4266 memcpy(&msg_ctx->key, &incoming->key, sizeof(GNUNET_HashCode));
4267 msg_ctx->replication = ntohl(incoming->desired_replication_level);
4268 msg_ctx->unique_id = GNUNET_ntohll(incoming->unique_id);
4269 msg_ctx->msg_options = ntohl(incoming->options);
4270 msg_ctx->network_size = ntohl(incoming->network_size);
4271 msg_ctx->peer = peer;
4272 msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4273 msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4274 demultiplex_message(enc_msg, msg_ctx);
4275 GNUNET_free(msg_ctx);
4281 * Core handler for p2p route results.
4284 handle_dht_p2p_route_result (void *cls,
4285 const struct GNUNET_PeerIdentity *peer,
4286 const struct GNUNET_MessageHeader *message,
4287 struct GNUNET_TIME_Relative latency, uint32_t distance)
4290 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4291 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4293 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4294 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4295 struct DHT_MessageContext msg_ctx;
4297 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4303 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4304 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4305 msg_ctx.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4306 GNUNET_assert(msg_ctx.bloom != NULL);
4307 memcpy(&msg_ctx.key, &incoming->key, sizeof(GNUNET_HashCode));
4308 msg_ctx.unique_id = GNUNET_ntohll(incoming->unique_id);
4309 msg_ctx.msg_options = ntohl(incoming->options);
4310 msg_ctx.hop_count = ntohl(incoming->hop_count);
4311 msg_ctx.peer = peer;
4312 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4313 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4314 route_result_message(enc_msg, &msg_ctx);
4320 * Receive the HELLO from transport service,
4321 * free current and replace if necessary.
4324 * @param message HELLO message of peer
4327 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4331 "Received our `%s' from transport service\n",
4335 GNUNET_assert (message != NULL);
4336 GNUNET_free_non_null(my_hello);
4337 my_hello = GNUNET_malloc(ntohs(message->size));
4338 memcpy(my_hello, message, ntohs(message->size));
4343 * Task run during shutdown.
4349 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4352 struct PeerInfo *pos;
4354 if (transport_handle != NULL)
4356 GNUNET_free_non_null(my_hello);
4357 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4358 GNUNET_TRANSPORT_disconnect(transport_handle);
4360 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4362 while (k_buckets[bucket_count].head != NULL)
4364 pos = k_buckets[bucket_count].head;
4366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4367 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4369 delete_peer(pos, bucket_count);
4372 if (coreAPI != NULL)
4375 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4376 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4378 GNUNET_CORE_disconnect (coreAPI);
4381 if (datacache != NULL)
4384 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4385 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4387 GNUNET_DATACACHE_destroy (datacache);
4392 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4395 if (dhtlog_handle != NULL)
4397 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4398 dhtlog_handle = NULL;
4400 if (block_context != NULL)
4402 GNUNET_BLOCK_context_destroy (block_context);
4403 block_context = NULL;
4405 GNUNET_free_non_null(my_short_id);
4411 * To be called on core init/fail.
4413 * @param cls service closure
4414 * @param server handle to the server for this service
4415 * @param identity the public identity of this peer
4416 * @param publicKey the public key of this peer
4419 core_init (void *cls,
4420 struct GNUNET_CORE_Handle *server,
4421 const struct GNUNET_PeerIdentity *identity,
4422 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4428 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4429 "%s: Connection to core FAILED!\n", "dht",
4430 GNUNET_i2s (identity));
4432 GNUNET_SCHEDULER_cancel (cleanup_task);
4433 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4438 "%s: Core connection initialized, I am peer: %s\n", "dht",
4439 GNUNET_i2s (identity));
4442 /* Copy our identity so we can use it */
4443 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4444 if (my_short_id != NULL)
4445 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4446 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4447 /* Set the server to local variable */
4450 if (dhtlog_handle != NULL)
4451 dhtlog_handle->insert_node (NULL, &my_identity);
4455 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4456 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4457 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4458 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4463 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4464 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4465 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4471 * Method called whenever a peer connects.
4473 * @param cls closure
4474 * @param peer peer identity this notification is about
4475 * @param latency reported latency of the connection with peer
4476 * @param distance reported distance (DV) to peer
4478 void handle_core_connect (void *cls,
4479 const struct GNUNET_PeerIdentity * peer,
4480 struct GNUNET_TIME_Relative latency,
4483 struct PeerInfo *ret;
4486 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4487 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4490 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received %s message for peer %s, but already have peer in RT!", my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s(peer));
4496 if (datacache != NULL)
4497 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, GNUNET_BLOCK_TYPE_DHT_HELLO, GNUNET_TIME_absolute_get_forever());
4498 ret = try_add_peer(peer,
4499 find_current_bucket(&peer->hashPubKey),
4504 newly_found_peers++;
4505 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4508 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4509 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4515 * Method called whenever a peer disconnects.
4517 * @param cls closure
4518 * @param peer peer identity this notification is about
4520 void handle_core_disconnect (void *cls,
4522 GNUNET_PeerIdentity * peer)
4524 struct PeerInfo *to_remove;
4527 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s: Received peer disconnect message for peer `%s' from %s\n", my_short_id, "DHT", GNUNET_i2s(peer), "CORE");
4529 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4531 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s: do not have peer `%s' in RT, can't disconnect!\n", my_short_id, "DHT", GNUNET_i2s(peer));
4534 increment_stats(STAT_DISCONNECTS);
4535 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4536 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4537 GNUNET_assert (to_remove != NULL);
4538 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4539 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4540 delete_peer(to_remove, current_bucket);
4545 * Process dht requests.
4547 * @param cls closure
4548 * @param server the initialized server
4549 * @param c configuration to use
4553 struct GNUNET_SERVER_Handle *server,
4554 const struct GNUNET_CONFIGURATION_Handle *c)
4556 struct GNUNET_TIME_Relative next_send_time;
4557 unsigned long long temp_config_num;
4558 char *converge_modifier_buf;
4561 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4562 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4563 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4564 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
4566 GNUNET_TIME_UNIT_FOREVER_REL,
4567 NULL, /* Closure passed to DHT functions */
4568 &core_init, /* Call core_init once connected */
4569 &handle_core_connect, /* Handle connects */
4570 &handle_core_disconnect, /* remove peers on disconnects */
4571 NULL, /* Do we care about "status" updates? */
4572 NULL, /* Don't want notified about all incoming messages */
4573 GNUNET_NO, /* For header only inbound notification */
4574 NULL, /* Don't want notified about all outbound messages */
4575 GNUNET_NO, /* For header only outbound notification */
4576 core_handlers); /* Register these handlers */
4578 if (coreAPI == NULL)
4580 transport_handle = GNUNET_TRANSPORT_connect(cfg,
4581 NULL, NULL, NULL, NULL, NULL);
4582 if (transport_handle != NULL)
4583 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4585 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4586 "Failed to connect to transport service!\n");
4587 block_context = GNUNET_BLOCK_context_create (cfg);
4588 lowest_bucket = MAX_BUCKETS - 1;
4589 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4590 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4591 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4592 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4593 GNUNET_assert(all_known_peers != NULL);
4594 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4596 debug_routes = GNUNET_YES;
4600 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4603 strict_kademlia = GNUNET_YES;
4607 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4610 stop_on_closest = GNUNET_YES;
4614 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4617 stop_on_found = GNUNET_YES;
4621 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4622 "malicious_getter"))
4624 malicious_getter = GNUNET_YES;
4625 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4626 "MALICIOUS_GET_FREQUENCY",
4627 &malicious_get_frequency))
4628 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4631 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4635 max_hops = DEFAULT_MAX_HOPS;
4638 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4641 use_max_hops = GNUNET_YES;
4645 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4646 "malicious_putter"))
4648 malicious_putter = GNUNET_YES;
4649 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4650 "MALICIOUS_PUT_FREQUENCY",
4651 &malicious_put_frequency))
4652 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4655 dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
4656 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4658 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4662 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4663 "malicious_dropper"))
4665 malicious_dropper = GNUNET_YES;
4669 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4671 do_republish = GNUNET_NO;
4674 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4677 do_find_peer = GNUNET_NO;
4680 do_find_peer = GNUNET_YES;
4683 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4684 "use_real_distance"))
4685 use_real_distance = GNUNET_YES;
4688 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4689 "mysql_logging_extended"))
4691 debug_routes = GNUNET_YES;
4692 debug_routes_extended = GNUNET_YES;
4695 #if DEBUG_DHT_ROUTING
4696 if (GNUNET_YES == debug_routes)
4698 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4699 if (dhtlog_handle == NULL)
4701 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4702 "Could not connect to mysql logging server, logging will not happen!");
4707 converge_option = DHT_CONVERGE_SQUARE;
4709 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4712 converge_option = DHT_CONVERGE_LINEAR;
4714 else if (GNUNET_YES ==
4715 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4716 "converge_exponential"))
4718 converge_option = DHT_CONVERGE_EXPONENTIAL;
4720 else if (GNUNET_YES ==
4721 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4724 converge_option = DHT_CONVERGE_RANDOM;
4726 else if (GNUNET_YES ==
4727 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4730 converge_option = DHT_CONVERGE_BINARY;
4733 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4735 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4737 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4738 converge_modifier = 0.0;
4740 GNUNET_free(converge_modifier_buf);
4743 stats = GNUNET_STATISTICS_create("dht", cfg);
4747 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4748 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4749 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4750 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4751 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4752 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4753 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4754 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4755 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4756 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4757 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4758 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4759 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4760 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4761 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4762 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4763 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4764 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4765 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4766 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4768 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4769 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4770 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4771 if (GNUNET_YES == do_find_peer)
4773 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4774 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4775 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4776 find_peer_context.start = GNUNET_TIME_absolute_get();
4777 GNUNET_SCHEDULER_add_delayed (next_send_time,
4778 &send_find_peer_message, &find_peer_context);
4781 /* Scheduled the task to clean up when shutdown is called */
4782 cleanup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4783 &shutdown_task, NULL);
4787 * The main function for the dht service.
4789 * @param argc number of arguments from the command line
4790 * @param argv command line arguments
4791 * @return 0 ok, 1 on error
4794 main (int argc, char *const *argv)
4799 GNUNET_SERVICE_run (argc,
4802 GNUNET_SERVICE_OPTION_NONE,
4803 &run, NULL)) ? 0 : 1;
4804 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap));
4805 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap));
4806 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4807 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4808 GNUNET_CONTAINER_heap_destroy (recent.minHeap);