2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file dht/gnunet-service-dht.c
23 * @brief main DHT service shell, building block for DHT implementations
24 * @author Christian Grothoff
25 * @author Nathan Evans
29 #include "gnunet_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_PUT_REPLICATION 4
116 * Default replication parameter for find peer messages sent by the dht service.
118 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
121 * Default options for find peer requests sent by the dht service.
123 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
124 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
127 * How long at least to wait before sending another find peer request.
129 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
132 * How long at most to wait before sending another find peer request.
134 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
137 * How often to update our preference levels for peers in our routing tables.
139 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
142 * How long at most on average will we allow a reply forward to take
143 * (before we quit sending out new requests)
145 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
148 * How many initial requests to send out (in true Kademlia fashion)
150 #define DHT_KADEMLIA_REPLICATION 3
153 * Default frequency for sending malicious get messages
155 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
158 * Default frequency for sending malicious put messages
160 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
163 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
166 * Real maximum number of hops, at which point we refuse
167 * to forward the message.
169 #define DEFAULT_MAX_HOPS 10
172 * How many time differences between requesting a core send and
173 * the actual callback to remember.
175 #define MAX_REPLY_TIMES 8
177 enum ConvergenceOptions
180 * Use the linear method for convergence.
185 * Converge using a fast converging square
191 * Converge using a slower exponential
194 DHT_CONVERGE_EXPONENTIAL,
197 * Don't do any special convergence, allow
198 * the algorithm to hopefully route to closer
204 * Binary convergence, start routing to closest
205 * only after set number of hops.
211 * Linked list of messages to send to clients.
213 struct P2PPendingMessage
216 * Pointer to next item in the list
218 struct P2PPendingMessage *next;
221 * Pointer to previous item in the list
223 struct P2PPendingMessage *prev;
226 * Message importance level.
228 unsigned int importance;
231 * Time when this request was scheduled to be sent.
233 struct GNUNET_TIME_Absolute scheduled;
236 * How long to wait before sending message.
238 struct GNUNET_TIME_Relative timeout;
241 * Actual message to be sent; // avoid allocation
243 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
248 * Per-peer information.
253 * Next peer entry (DLL)
255 struct PeerInfo *next;
258 * Prev peer entry (DLL)
260 struct PeerInfo *prev;
263 * Head of pending messages to be sent to this peer.
265 struct P2PPendingMessage *head;
268 * Tail of pending messages to be sent to this peer.
270 struct P2PPendingMessage *tail;
273 * Core handle for sending messages to this peer.
275 struct GNUNET_CORE_TransmitHandle *th;
278 * Task for scheduling message sends.
280 GNUNET_SCHEDULER_TaskIdentifier send_task;
283 * Task for scheduling preference updates
285 GNUNET_SCHEDULER_TaskIdentifier preference_task;
288 * Preference update context
290 struct GNUNET_CORE_InformationRequestContext *info_ctx;
293 * What is the average latency for replies received?
295 struct GNUNET_TIME_Relative latency;
298 * What is the identity of the peer?
300 struct GNUNET_PeerIdentity id;
303 * Transport level distance to peer.
305 unsigned int distance;
308 * Holds matching bits from peer to current target,
309 * used for distance comparisons between peers. May
310 * be considered a really bad idea.
311 * FIXME: remove this value (create struct which holds
312 * a single peerinfo and the matching bits, use
313 * that to pass to comparitor)
315 unsigned int matching_bits;
318 * Task for scheduling periodic ping messages for this peer.
320 GNUNET_SCHEDULER_TaskIdentifier ping_task;
324 * Peers are grouped into buckets.
331 struct PeerInfo *head;
336 struct PeerInfo *tail;
339 * Number of peers in the bucket.
341 unsigned int peers_size;
345 * Linked list of messages to send to clients.
347 struct PendingMessage
350 * Pointer to next item in the list
352 struct PendingMessage *next;
355 * Pointer to previous item in the list
357 struct PendingMessage *prev;
360 * Actual message to be sent; // avoid allocation
362 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
367 * Struct containing information about a client,
368 * handle to connect to it, and any pending messages
369 * that need to be sent to it.
374 * Linked list of active clients
376 struct ClientList *next;
379 * The handle to this client
381 struct GNUNET_SERVER_Client *client_handle;
384 * Handle to the current transmission request, NULL
387 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
390 * Linked list of pending messages for this client
392 struct PendingMessage *pending_head;
395 * Tail of linked list of pending messages for this client
397 struct PendingMessage *pending_tail;
402 * Context containing information about a DHT message received.
404 struct DHT_MessageContext
407 * The client this request was received from.
408 * (NULL if received from another peer)
410 struct ClientList *client;
413 * The peer this request was received from.
414 * (NULL if received from local client)
416 const struct GNUNET_PeerIdentity *peer;
419 * Bloomfilter for this routing request.
421 struct GNUNET_CONTAINER_BloomFilter *bloom;
424 * extended query (see gnunet_block_lib.h).
429 * Bloomfilter to filter out duplicate replies.
431 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
434 * The key this request was about
439 * How long should we wait to transmit this request?
441 struct GNUNET_TIME_Relative timeout;
444 * The unique identifier of this request
449 * Number of bytes in xquery.
454 * Mutator value for the reply_bf, see gnunet_block_lib.h
456 uint32_t reply_bf_mutator;
459 * Desired replication level
461 uint32_t replication;
464 * Network size estimate, either ours or the sum of
465 * those routed to thus far. =~ Log of number of peers
466 * chosen from for this request.
468 uint32_t network_size;
471 * Any message options for this request
473 uint32_t msg_options;
476 * How many hops has the message already traversed?
481 * How important is this message?
483 unsigned int importance;
486 * Should we (still) forward the request on to other peers?
491 * Did we forward this message? (may need to remember it!)
496 * Are we the closest known peer to this key (out of our neighbors?)
502 * Record used for remembering what peers are waiting for what
503 * responses (based on search key).
505 struct DHTRouteSource
510 struct DHTRouteSource *next;
515 struct DHTRouteSource *prev;
518 * Source of the request. Replies should be forwarded to
521 struct GNUNET_PeerIdentity source;
524 * If this was a local request, remember the client; otherwise NULL.
526 struct ClientList *client;
529 * Pointer to this nodes heap location (for removal)
531 struct GNUNET_CONTAINER_HeapNode *hnode;
534 * Back pointer to the record storing this information.
536 struct DHTQueryRecord *record;
539 * Task to remove this entry on timeout.
541 GNUNET_SCHEDULER_TaskIdentifier delete_task;
544 * Bloomfilter of peers we have already sent back as
545 * replies to the initial request. Allows us to not
546 * forward the same peer multiple times for a find peer
549 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
554 * Entry in the DHT routing table.
556 struct DHTQueryRecord
559 * Head of DLL for result forwarding.
561 struct DHTRouteSource *head;
564 * Tail of DLL for result forwarding.
566 struct DHTRouteSource *tail;
569 * Key that the record concerns.
574 * GET message of this record (what we already forwarded?).
576 //DV_DHT_MESSAGE get; Try to get away with not saving this.
579 * Bloomfilter of the peers we've replied to so far
581 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
586 * Context used to calculate the number of find peer messages
587 * per X time units since our last scheduled find peer message
588 * was sent. If we have seen too many messages, delay or don't
591 struct FindPeerMessageContext
595 struct GNUNET_TIME_Absolute start;
597 struct GNUNET_TIME_Absolute end;
601 * DHT Routing results structure
606 * Min heap for removal upon reaching limit
608 struct GNUNET_CONTAINER_Heap *minHeap;
611 * Hashmap for fast key based lookup
613 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
618 * DHT structure for recent requests.
620 struct RecentRequests
623 * Min heap for removal upon reaching limit
625 struct GNUNET_CONTAINER_Heap *minHeap;
628 * Hashmap for key based lookup
630 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
636 * Position of this node in the min heap.
638 struct GNUNET_CONTAINER_HeapNode *heap_node;
641 * Bloomfilter containing entries for peers
642 * we forwarded this request to.
644 struct GNUNET_CONTAINER_BloomFilter *bloom;
647 * Timestamp of this request, for ordering
650 struct GNUNET_TIME_Absolute timestamp;
653 * Key of this request.
658 * Unique identifier for this request.
663 * Task to remove this entry on timeout.
665 GNUNET_SCHEDULER_TaskIdentifier remove_task;
668 struct RepublishContext
683 * Which kind of convergence will we be using?
685 static enum ConvergenceOptions converge_option;
688 * Modifier for the convergence function
690 static float converge_modifier;
693 * Recent requests by hash/uid and by time inserted.
695 static struct RecentRequests recent;
698 * Context to use to calculate find peer rates.
700 static struct FindPeerMessageContext find_peer_context;
703 * Don't use our routing algorithm, always route
704 * to closest peer; initially send requests to 3
707 static unsigned int strict_kademlia;
710 * Routing option to end routing when closest peer found.
712 static unsigned int stop_on_closest;
715 * Routing option to end routing when data is found.
717 static unsigned int stop_on_found;
720 * Whether DHT needs to manage find peer requests, or
721 * an external force will do it on behalf of the DHT.
723 static unsigned int do_find_peer;
726 * Once we have stored an item in the DHT, refresh it
727 * according to our republish interval.
729 static unsigned int do_republish;
732 * Use the "real" distance metric when selecting the
733 * next routing hop. Can be less accurate.
735 static unsigned int use_real_distance;
738 * How many peers have we added since we sent out our last
741 static unsigned int newly_found_peers;
744 * Container of active queries we should remember
746 static struct DHTResults forward_list;
749 * Handle to the datacache service (for inserting/retrieving data)
751 static struct GNUNET_DATACACHE_Handle *datacache;
754 * Handle for the statistics service.
756 struct GNUNET_STATISTICS_Handle *stats;
760 * The configuration the DHT service is running with
762 static const struct GNUNET_CONFIGURATION_Handle *cfg;
765 * Handle to the core service
767 static struct GNUNET_CORE_Handle *coreAPI;
770 * Handle to the transport service, for getting our hello
772 static struct GNUNET_TRANSPORT_Handle *transport_handle;
775 * The identity of our peer.
777 static struct GNUNET_PeerIdentity my_identity;
780 * Short id of the peer, for printing
782 static char *my_short_id;
787 static struct GNUNET_MessageHeader *my_hello;
790 * Task to run when we shut down, cleaning up all our trash
792 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
795 * The lowest currently used bucket.
797 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
800 * The maximum number of hops before we stop routing messages.
802 static unsigned long long max_hops;
805 * How often to republish content we have previously stored.
807 static struct GNUNET_TIME_Relative dht_republish_frequency;
810 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
812 static int use_max_hops;
815 * The buckets (Kademlia routing table, complete with growth).
816 * Array of size MAX_BUCKET_SIZE.
818 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
821 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
823 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
826 * Recently seen find peer requests.
828 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
831 * Maximum size for each bucket.
833 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
836 * List of active clients.
838 static struct ClientList *client_list;
841 * Handle to the DHT logger.
843 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
846 * Whether or not to send routing debugging information
847 * to the dht logging server
849 static unsigned int debug_routes;
852 * Whether or not to send FULL route information to
855 static unsigned int debug_routes_extended;
858 * GNUNET_YES or GNUNET_NO, whether or not to act as
859 * a malicious node which drops all messages
861 static unsigned int malicious_dropper;
864 * GNUNET_YES or GNUNET_NO, whether or not to act as
865 * a malicious node which sends out lots of GETS
867 static unsigned int malicious_getter;
870 * GNUNET_YES or GNUNET_NO, whether or not to act as
871 * a malicious node which sends out lots of PUTS
873 static unsigned int malicious_putter;
876 * Frequency for malicious get requests.
878 static unsigned long long malicious_get_frequency;
881 * Frequency for malicious put requests.
883 static unsigned long long malicious_put_frequency;
886 * Reply times for requests, if we are busy, don't send any
889 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
892 * Current counter for replies.
894 static unsigned int reply_counter;
897 * Our handle to the BLOCK library.
899 static struct GNUNET_BLOCK_Context *block_context;
903 * Forward declaration.
906 send_generic_reply (void *cls, size_t size, void *buf);
909 /** Declare here so retry_core_send is aware of it */
911 core_transmit_notify (void *cls,
912 size_t size, void *buf);
915 * Convert unique ID to hash code.
917 * @param uid unique ID to convert
918 * @param hash set to uid (extended with zeros)
921 hash_from_uid (uint64_t uid,
922 GNUNET_HashCode *hash)
924 memset (hash, 0, sizeof(GNUNET_HashCode));
925 *((uint64_t*)hash) = uid;
930 * Calculate the average send time between messages so that we can
931 * ignore certain requests if we get too busy.
933 * @return the average time between asking core to send a message
934 * and when the buffer for copying it is passed
936 static struct GNUNET_TIME_Relative get_average_send_delay()
939 unsigned int divisor;
940 struct GNUNET_TIME_Relative average_time;
941 average_time = GNUNET_TIME_relative_get_zero();
943 for (i = 0; i < MAX_REPLY_TIMES; i++)
945 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
946 if (reply_times[i].abs_value == (uint64_t)0)
956 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
958 "Avg send delay: %u sends is %llu\n",
960 (unsigned long long) average_time.abs_value);
966 * Given the largest send delay, artificially decrease it
967 * so the next time around we may have a chance at sending
970 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
973 for (i = 0; i < MAX_REPLY_TIMES; i++)
975 if (reply_times[i].rel_value == max_time.rel_value)
977 reply_times[i].rel_value = reply_times[i].rel_value / 2;
984 * Find the maximum send time of the recently sent values.
986 * @return the average time between asking core to send a message
987 * and when the buffer for copying it is passed
989 static struct GNUNET_TIME_Relative get_max_send_delay()
992 struct GNUNET_TIME_Relative max_time;
993 max_time = GNUNET_TIME_relative_get_zero();
995 for (i = 0; i < MAX_REPLY_TIMES; i++)
997 if (reply_times[i].rel_value > max_time.rel_value)
998 max_time.rel_value = reply_times[i].rel_value;
1001 if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
1002 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n",
1003 (unsigned long long) max_time.rel_value);
1008 increment_stats(const char *value)
1012 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
1017 * Try to send another message from our core send list
1020 try_core_send (void *cls,
1021 const struct GNUNET_SCHEDULER_TaskContext *tc)
1023 struct PeerInfo *peer = cls;
1024 struct P2PPendingMessage *pending;
1027 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
1029 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1032 if (peer->th != NULL)
1033 return; /* Message send already in progress */
1035 pending = peer->head;
1036 if (pending != NULL)
1038 ssize = ntohs(pending->msg->size);
1040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1041 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
1042 "DHT", ssize, GNUNET_i2s(&peer->id));
1044 pending->scheduled = GNUNET_TIME_absolute_get();
1046 if (reply_counter >= MAX_REPLY_TIMES)
1048 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
1049 pending->timeout, &peer->id,
1050 ssize, &core_transmit_notify, peer);
1055 * Function called to send a request out to another peer.
1056 * Called both for locally initiated requests and those
1057 * received from other peers.
1059 * @param msg the encapsulated message
1060 * @param peer the peer to forward the message to
1061 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1064 forward_result_message (const struct GNUNET_MessageHeader *msg,
1065 struct PeerInfo *peer,
1066 struct DHT_MessageContext *msg_ctx)
1068 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1069 struct P2PPendingMessage *pending;
1073 increment_stats(STAT_RESULT_FORWARDS);
1074 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1075 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1076 psize = sizeof(struct P2PPendingMessage) + msize;
1077 pending = GNUNET_malloc(psize);
1078 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1079 pending->importance = DHT_SEND_PRIORITY;
1080 pending->timeout = GNUNET_TIME_relative_get_forever();
1081 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1082 result_message->header.size = htons(msize);
1083 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1084 result_message->put_path_length = htons(0); /* FIXME: implement */
1085 result_message->get_path_length = htons(0); /* FIXME: implement */
1086 result_message->options = htonl(msg_ctx->msg_options);
1087 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1088 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1089 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1090 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1091 memcpy(&result_message[1], msg, ntohs(msg->size));
1093 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));
1095 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1096 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1097 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1102 * Called when core is ready to send a message we asked for
1103 * out to the destination.
1105 * @param cls closure (NULL)
1106 * @param size number of bytes available in buf
1107 * @param buf where the callee should write the message
1108 * @return number of bytes written to buf
1111 core_transmit_notify (void *cls,
1112 size_t size, void *buf)
1114 struct PeerInfo *peer = cls;
1116 struct P2PPendingMessage *pending;
1123 /* client disconnected */
1125 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1130 if (peer->head == NULL)
1135 pending = peer->head;
1136 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1137 msize = ntohs(pending->msg->size);
1141 memcpy (cbuf, pending->msg, msize);
1142 GNUNET_CONTAINER_DLL_remove (peer->head,
1146 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));
1148 GNUNET_free (pending);
1151 while (NULL != pending &&
1152 (size - off >= (msize = ntohs (pending->msg->size))))
1154 #if DEBUG_DHT_ROUTING
1155 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);
1157 memcpy (&cbuf[off], pending->msg, msize);
1159 GNUNET_CONTAINER_DLL_remove (peer->head,
1162 GNUNET_free (pending);
1163 pending = peer->head;
1166 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1167 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1169 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);
1176 * Compute the distance between have and target as a 32-bit value.
1177 * Differences in the lower bits must count stronger than differences
1178 * in the higher bits.
1180 * @return 0 if have==target, otherwise a number
1181 * that is larger as the distance between
1182 * the two hash codes increases
1185 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1187 unsigned int bucket;
1192 /* We have to represent the distance between two 2^9 (=512)-bit
1193 numbers as a 2^5 (=32)-bit number with "0" being used for the
1194 two numbers being identical; furthermore, we need to
1195 guarantee that a difference in the number of matching
1196 bits is always represented in the result.
1198 We use 2^32/2^9 numerical values to distinguish between
1199 hash codes that have the same LSB bit distance and
1200 use the highest 2^9 bits of the result to signify the
1201 number of (mis)matching LSB bits; if we have 0 matching
1202 and hence 512 mismatching LSB bits we return -1 (since
1203 512 itself cannot be represented with 9 bits) */
1205 /* first, calculate the most significant 9 bits of our
1206 result, aka the number of LSBs */
1207 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1208 /* bucket is now a value between 0 and 512 */
1210 return 0; /* perfect match */
1212 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1213 below, we'd end up with max+1 (overflow)) */
1215 /* calculate the most significant bits of the final result */
1216 msb = (512 - bucket) << (32 - 9);
1217 /* calculate the 32-9 least significant bits of the final result by
1218 looking at the differences in the 32-9 bits following the
1219 mismatching bit at 'bucket' */
1221 for (i = bucket + 1;
1222 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1224 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1225 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1226 last bit set will be 31 -- if
1227 i does not reach 512 first... */
1233 * Return a number that is larger the closer the
1234 * "have" GNUNET_hash code is to the "target".
1236 * @return inverse distance metric, non-zero.
1237 * Must fudge the value if NO bits match.
1240 inverse_distance (const GNUNET_HashCode * target,
1241 const GNUNET_HashCode * have)
1243 if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1244 return 1; /* Never return 0! */
1245 return ((unsigned int) -1) - distance (target, have);
1249 * Find the optimal bucket for this key, regardless
1250 * of the current number of buckets in use.
1252 * @param hc the hashcode to compare our identity to
1254 * @return the proper bucket index, or GNUNET_SYSERR
1255 * on error (same hashcode)
1257 static int find_bucket(const GNUNET_HashCode *hc)
1261 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1262 if (bits == MAX_BUCKETS)
1263 return GNUNET_SYSERR;
1264 return MAX_BUCKETS - bits - 1;
1268 * Find which k-bucket this peer should go into,
1269 * taking into account the size of the k-bucket
1270 * array. This means that if more bits match than
1271 * there are currently buckets, lowest_bucket will
1274 * @param hc GNUNET_HashCode we are finding the bucket for.
1276 * @return the proper bucket index for this key,
1277 * or GNUNET_SYSERR on error (same hashcode)
1279 static int find_current_bucket(const GNUNET_HashCode *hc)
1282 actual_bucket = find_bucket(hc);
1284 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1285 return lowest_bucket;
1286 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1287 return lowest_bucket;
1289 return actual_bucket;
1294 * Find a routing table entry from a peer identity
1296 * @param peer the peer to look up
1298 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1301 find_bucket_by_peer(const struct PeerInfo *peer)
1304 struct PeerInfo *pos;
1306 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1308 pos = k_buckets[bucket].head;
1317 return GNUNET_SYSERR; /* No such peer. */
1323 * Print the complete routing table for this peer.
1326 print_routing_table ()
1329 struct PeerInfo *pos;
1330 char char_buf[30000];
1332 memset(char_buf, 0, sizeof(char_buf));
1334 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1335 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1336 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1338 pos = k_buckets[bucket].head;
1339 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1340 //fprintf(stderr, "Bucket %d:\n", bucket);
1343 //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));
1344 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));
1348 fprintf(stderr, "%s", char_buf);
1354 * Find a routing table entry from a peer identity
1356 * @param peer the peer identity to look up
1358 * @return the routing table entry, or NULL if not found
1360 static struct PeerInfo *
1361 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1364 struct PeerInfo *pos;
1365 bucket = find_current_bucket(&peer->hashPubKey);
1367 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1370 pos = k_buckets[bucket].head;
1373 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1377 return NULL; /* No such peer. */
1380 /* Forward declaration */
1382 update_core_preference (void *cls,
1383 const struct GNUNET_SCHEDULER_TaskContext *tc);
1385 * Function called with statistics about the given peer.
1387 * @param cls closure
1388 * @param peer identifies the peer
1389 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1390 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1391 * @param amount set to the amount that was actually reserved or unreserved;
1392 * either the full requested amount or zero (no partial reservations)
1393 * @param preference current traffic preference for the given peer
1396 update_core_preference_finish (void *cls,
1397 const struct GNUNET_PeerIdentity * peer,
1398 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1399 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1400 int amount, uint64_t preference)
1402 struct PeerInfo *peer_info = cls;
1403 peer_info->info_ctx = NULL;
1404 GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1408 update_core_preference (void *cls,
1409 const struct GNUNET_SCHEDULER_TaskContext *tc)
1411 struct PeerInfo *peer = cls;
1412 uint64_t preference;
1413 unsigned int matching;
1414 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1418 matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1421 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1424 preference = 1LL << matching;
1425 peer->info_ctx = GNUNET_CORE_peer_change_preference (cfg,
1427 GNUNET_TIME_relative_get_forever(),
1428 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1431 &update_core_preference_finish,
1436 * Really add a peer to a bucket (only do assertions
1439 * @param peer GNUNET_PeerIdentity of the peer to add
1440 * @param bucket the already figured out bucket to add
1442 * @param latency the core reported latency of this peer
1443 * @param distance the transport level distance to this peer
1445 * @return the newly added PeerInfo
1447 static struct PeerInfo *
1448 add_peer(const struct GNUNET_PeerIdentity *peer,
1449 unsigned int bucket,
1450 struct GNUNET_TIME_Relative latency,
1451 unsigned int distance)
1453 struct PeerInfo *new_peer;
1454 GNUNET_assert(bucket < MAX_BUCKETS);
1455 GNUNET_assert(peer != NULL);
1456 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1457 new_peer->latency = latency;
1458 new_peer->distance = distance;
1460 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1462 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1463 k_buckets[bucket].tail,
1464 k_buckets[bucket].tail,
1466 k_buckets[bucket].peers_size++;
1468 if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1470 #if DO_UPDATE_PREFERENCE
1471 new_peer->preference_task = GNUNET_SCHEDULER_add_now(&update_core_preference, new_peer);
1479 * Given a peer and its corresponding bucket,
1480 * remove it from that bucket. Does not free
1481 * the PeerInfo struct, nor cancel messages
1482 * or free messages waiting to be sent to this
1485 * @param peer the peer to remove
1486 * @param bucket the bucket the peer belongs to
1488 static void remove_peer (struct PeerInfo *peer,
1489 unsigned int bucket)
1491 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1492 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1493 k_buckets[bucket].tail,
1495 k_buckets[bucket].peers_size--;
1497 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1503 * Removes peer from a bucket, then frees associated
1504 * resources and frees peer.
1506 * @param peer peer to be removed and freed
1507 * @param bucket which bucket this peer belongs to
1509 static void delete_peer (struct PeerInfo *peer,
1510 unsigned int bucket)
1512 struct P2PPendingMessage *pos;
1513 struct P2PPendingMessage *next;
1515 struct PeerInfo *peer_pos;
1517 peer_pos = k_buckets[bucket].head;
1518 while ((peer_pos != NULL) && (peer_pos != peer))
1519 peer_pos = peer_pos->next;
1520 if (peer_pos == NULL)
1522 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1523 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));
1525 GNUNET_assert(peer_pos != NULL);
1527 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1529 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1530 GNUNET_SCHEDULER_cancel(peer->send_task);
1531 if (peer->th != NULL)
1532 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1535 while (pos != NULL) /* Remove any pending messages for this peer */
1542 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1543 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1549 * Iterator over hash map entries.
1551 * @param cls closure
1552 * @param key current key code
1553 * @param value PeerInfo of the peer to move to new lowest bucket
1554 * @return GNUNET_YES if we should continue to
1558 static int move_lowest_bucket (void *cls,
1559 const GNUNET_HashCode * key,
1562 struct PeerInfo *peer = value;
1565 GNUNET_assert(lowest_bucket > 0);
1566 new_bucket = lowest_bucket - 1;
1567 remove_peer(peer, lowest_bucket);
1568 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1569 k_buckets[new_bucket].tail,
1570 k_buckets[new_bucket].tail,
1572 k_buckets[new_bucket].peers_size++;
1578 * The current lowest bucket is full, so change the lowest
1579 * bucket to the next lower down, and move any appropriate
1580 * entries in the current lowest bucket to the new bucket.
1582 static void enable_next_bucket()
1584 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1585 struct PeerInfo *pos;
1586 GNUNET_assert(lowest_bucket > 0);
1587 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1588 pos = k_buckets[lowest_bucket].head;
1591 fprintf(stderr, "Printing RT before new bucket\n");
1592 print_routing_table();
1594 /* Populate the array of peers which should be in the next lowest bucket */
1597 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1598 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1602 /* Remove peers from lowest bucket, insert into next lowest bucket */
1603 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1604 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1605 lowest_bucket = lowest_bucket - 1;
1607 fprintf(stderr, "Printing RT after new bucket\n");
1608 print_routing_table();
1613 * Find the closest peer in our routing table to the
1616 * @return The closest peer in our routing table to the
1617 * key, or NULL on error.
1619 static struct PeerInfo *
1620 find_closest_peer (const GNUNET_HashCode *hc)
1622 struct PeerInfo *pos;
1623 struct PeerInfo *current_closest;
1624 unsigned int lowest_distance;
1625 unsigned int temp_distance;
1629 lowest_distance = -1;
1631 if (k_buckets[lowest_bucket].peers_size == 0)
1634 current_closest = NULL;
1635 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1637 pos = k_buckets[bucket].head;
1639 while ((pos != NULL) && (count < bucket_size))
1641 temp_distance = distance(&pos->id.hashPubKey, hc);
1642 if (temp_distance <= lowest_distance)
1644 lowest_distance = temp_distance;
1645 current_closest = pos;
1651 GNUNET_assert(current_closest != NULL);
1652 return current_closest;
1657 * Function called to send a request out to another peer.
1658 * Called both for locally initiated requests and those
1659 * received from other peers.
1661 * @param msg the encapsulated message
1662 * @param peer the peer to forward the message to
1663 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1665 static void forward_message (const struct GNUNET_MessageHeader *msg,
1666 struct PeerInfo *peer,
1667 struct DHT_MessageContext *msg_ctx)
1669 struct GNUNET_DHT_P2PRouteMessage *route_message;
1670 struct P2PPendingMessage *pending;
1674 increment_stats(STAT_ROUTE_FORWARDS);
1675 GNUNET_assert(peer != NULL);
1676 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1677 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1679 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1680 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1681 psize = sizeof(struct P2PPendingMessage) + msize;
1682 pending = GNUNET_malloc(psize);
1683 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1684 pending->importance = msg_ctx->importance;
1685 pending->timeout = msg_ctx->timeout;
1686 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1687 route_message->header.size = htons(msize);
1688 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1689 route_message->options = htonl(msg_ctx->msg_options);
1690 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1691 route_message->network_size = htonl(msg_ctx->network_size);
1692 route_message->desired_replication_level = htonl(msg_ctx->replication);
1693 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1694 if (msg_ctx->bloom != NULL)
1695 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1696 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1697 memcpy(&route_message[1], msg, ntohs(msg->size));
1699 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));
1701 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1702 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1703 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1708 * Task used to send ping messages to peers so that
1709 * they don't get disconnected.
1711 * @param cls the peer to send a ping message to
1712 * @param tc context, reason, etc.
1715 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1717 struct PeerInfo *peer = cls;
1718 struct GNUNET_MessageHeader ping_message;
1719 struct DHT_MessageContext message_context;
1721 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1724 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1725 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1727 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1729 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1731 forward_message(&ping_message, peer, &message_context);
1732 peer->ping_task = GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1736 * Schedule PING messages for the top X peers in each
1737 * bucket of the routing table (so core won't disconnect them!)
1739 void schedule_ping_messages()
1741 unsigned int bucket;
1743 struct PeerInfo *pos;
1744 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1746 pos = k_buckets[bucket].head;
1750 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1751 GNUNET_SCHEDULER_add_now(&periodic_ping_task, pos);
1752 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1754 GNUNET_SCHEDULER_cancel(pos->ping_task);
1755 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1765 * Attempt to add a peer to our k-buckets.
1767 * @param peer the peer identity of the peer being added
1768 * @param bucket the bucket that we want this peer to go in
1769 * @param latency transport latency of this peer
1770 * @param distance transport distance to this peer
1772 * @return NULL if the peer was not added,
1773 * pointer to PeerInfo for new peer otherwise
1775 static struct PeerInfo *
1776 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1777 unsigned int bucket,
1778 struct GNUNET_TIME_Relative latency,
1779 unsigned int distance)
1782 struct PeerInfo *new_peer;
1784 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1787 peer_bucket = find_current_bucket(&peer->hashPubKey);
1789 GNUNET_assert(peer_bucket >= lowest_bucket);
1790 new_peer = add_peer(peer, peer_bucket, latency, distance);
1792 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1793 enable_next_bucket();
1795 schedule_ping_messages();
1802 * Task run to check for messages that need to be sent to a client.
1804 * @param client a ClientList, containing the client and any messages to be sent to it
1807 process_pending_messages (struct ClientList *client)
1809 if (client->pending_head == NULL)
1811 if (client->transmit_handle != NULL)
1814 client->transmit_handle =
1815 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1816 ntohs (client->pending_head->msg->
1818 GNUNET_TIME_UNIT_FOREVER_REL,
1819 &send_generic_reply, client);
1823 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1824 * request. A ClientList is passed as closure, take the head of the list
1825 * and copy it into buf, which has the result of sending the message to the
1828 * @param cls closure to this call
1829 * @param size maximum number of bytes available to send
1830 * @param buf where to copy the actual message to
1832 * @return the number of bytes actually copied, 0 indicates failure
1835 send_generic_reply (void *cls, size_t size, void *buf)
1837 struct ClientList *client = cls;
1839 struct PendingMessage *reply;
1843 client->transmit_handle = NULL;
1846 /* client disconnected */
1850 while ( (NULL != (reply = client->pending_head)) &&
1851 (size >= off + (msize = ntohs (reply->msg->size))))
1853 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1854 client->pending_tail,
1856 memcpy (&cbuf[off], reply->msg, msize);
1857 GNUNET_free (reply);
1860 process_pending_messages (client);
1862 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1863 "Transmitted %u bytes of replies to client\n",
1864 (unsigned int) off);
1871 * Add a PendingMessage to the clients list of messages to be sent
1873 * @param client the active client to send the message to
1874 * @param pending_message the actual message to send
1877 add_pending_message (struct ClientList *client,
1878 struct PendingMessage *pending_message)
1880 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1881 client->pending_tail,
1882 client->pending_tail,
1884 process_pending_messages (client);
1889 * Called when a reply needs to be sent to a client, as
1890 * a result it found to a GET or FIND PEER request.
1892 * @param client the client to send the reply to
1893 * @param message the encapsulated message to send
1894 * @param uid the unique identifier of this request
1897 send_reply_to_client (struct ClientList *client,
1898 const struct GNUNET_MessageHeader *message,
1899 unsigned long long uid,
1900 const GNUNET_HashCode *key)
1902 struct GNUNET_DHT_RouteResultMessage *reply;
1903 struct PendingMessage *pending_message;
1907 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1908 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1910 msize = ntohs (message->size);
1911 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1912 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1914 GNUNET_break_op (0);
1917 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1918 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1919 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1920 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1921 reply->header.size = htons (tsize);
1922 reply->put_path_length = htons(0); /* FIXME: implement */
1923 reply->get_path_length = htons(0); /* FIXME: implement */
1924 reply->unique_id = GNUNET_htonll (uid);
1926 memcpy (&reply[1], message, msize);
1927 add_pending_message (client, pending_message);
1931 * Consider whether or not we would like to have this peer added to
1932 * our routing table. Check whether bucket for this peer is full,
1933 * if so return negative; if not return positive. Since peers are
1934 * only added on CORE level connect, this doesn't actually add the
1935 * peer to the routing table.
1937 * @param peer the peer we are considering adding
1939 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1942 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1946 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1947 return GNUNET_NO; /* We already know this peer (are connected even!) */
1948 bucket = find_current_bucket(&peer->hashPubKey);
1950 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1957 * Main function that handles whether or not to route a result
1958 * message to other peers, or to send to our local client.
1960 * @param msg the result message to be routed
1961 * @param message_context context of the message we are routing
1963 * @return the number of peers the message was routed to,
1964 * GNUNET_SYSERR on failure
1966 static int route_result_message(struct GNUNET_MessageHeader *msg,
1967 struct DHT_MessageContext *message_context)
1969 struct GNUNET_PeerIdentity new_peer;
1970 struct DHTQueryRecord *record;
1971 struct DHTRouteSource *pos;
1972 struct PeerInfo *peer_info;
1973 const struct GNUNET_MessageHeader *hello_msg;
1975 increment_stats(STAT_RESULTS);
1977 * If a find peer result message is received and contains a valid
1978 * HELLO for another peer, offer it to the transport service.
1980 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1982 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1985 hello_msg = &msg[1];
1986 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1988 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1992 else /* We have a valid hello, and peer id stored in new_peer */
1994 find_peer_context.count++;
1995 increment_stats(STAT_FIND_PEER_REPLY);
1996 if (GNUNET_YES == consider_peer(&new_peer))
1998 increment_stats(STAT_HELLOS_PROVIDED);
1999 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
2000 GNUNET_CORE_peer_request_connect(cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
2005 if (malicious_dropper == GNUNET_YES)
2008 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
2010 if (record == NULL) /* No record of this message! */
2013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2014 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
2015 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2017 #if DEBUG_DHT_ROUTING
2018 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2020 dhtlog_handle->insert_route (NULL,
2021 message_context->unique_id,
2023 message_context->hop_count,
2026 &message_context->key,
2027 message_context->peer, NULL);
2030 if (message_context->bloom != NULL)
2032 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2033 message_context->bloom = NULL;
2041 #if STRICT_FORWARDING
2042 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2044 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2046 increment_stats("# find peer responses NOT forwarded (bloom match)");
2051 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2055 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2058 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2059 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2060 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2062 #if DEBUG_DHT_ROUTING
2063 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2065 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2066 message_context->hop_count,
2067 GNUNET_YES, &my_identity, &message_context->key,
2068 message_context->peer, NULL);
2071 increment_stats(STAT_RESULTS_TO_CLIENT);
2072 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2073 increment_stats(STAT_GET_REPLY);
2075 send_reply_to_client(pos->client, msg,
2076 message_context->unique_id,
2077 &message_context->key);
2079 else /* Send to peer */
2081 peer_info = find_peer_by_id(&pos->source);
2082 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2088 if (message_context->bloom == NULL)
2089 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2090 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2091 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2094 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2095 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2096 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2098 #if DEBUG_DHT_ROUTING
2099 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2101 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2103 message_context->hop_count,
2104 GNUNET_NO, &my_identity, &message_context->key,
2105 message_context->peer, &pos->source);
2108 forward_result_message(msg, peer_info, message_context);
2113 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2114 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2115 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2121 if (message_context->bloom != NULL)
2122 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2127 * Iterator for local get request results,
2129 * @param cls closure for iterator, a DatacacheGetContext
2130 * @param exp when does this value expire?
2131 * @param key the key this data is stored under
2132 * @param size the size of the data identified by key
2133 * @param data the actual data
2134 * @param type the type of the data
2136 * @return GNUNET_OK to continue iteration, anything else
2137 * to stop iteration.
2140 datacache_get_iterator (void *cls,
2141 struct GNUNET_TIME_Absolute exp,
2142 const GNUNET_HashCode * key,
2143 size_t size, const char *data,
2144 enum GNUNET_BLOCK_Type type)
2146 struct DHT_MessageContext *msg_ctx = cls;
2147 struct DHT_MessageContext *new_msg_ctx;
2148 struct GNUNET_DHT_GetResultMessage *get_result;
2149 enum GNUNET_BLOCK_EvaluationResult eval;
2152 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2153 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2155 eval = GNUNET_BLOCK_evaluate (block_context,
2159 msg_ctx->reply_bf_mutator,
2161 msg_ctx->xquery_size,
2166 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2167 msg_ctx->do_forward = GNUNET_NO;
2168 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2169 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2170 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2172 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2173 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2174 get_result->header.size =
2175 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2176 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2177 get_result->type = htons (type);
2178 memcpy (&get_result[1], data, size);
2179 new_msg_ctx->peer = &my_identity;
2180 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2181 new_msg_ctx->hop_count = 0;
2182 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2183 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2184 increment_stats(STAT_GET_RESPONSE_START);
2185 route_result_message(&get_result->header, new_msg_ctx);
2186 GNUNET_free(new_msg_ctx);
2187 GNUNET_free (get_result);
2189 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2192 "`%s:%s': Duplicate block error\n", my_short_id, "DHT");
2195 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2198 "`%s:%s': Invalid request error\n", my_short_id, "DHT");
2201 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2204 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2208 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2209 GNUNET_break_op (0);
2210 msg_ctx->do_forward = GNUNET_NO;
2212 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2215 "`%s:%s': Unsupported block type (%u) in response!\n", my_short_id, "DHT", type);
2217 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2225 * Main function that handles whether or not to route a message to other
2228 * @param msg the message to be routed
2229 * @param message_context the context containing all pertinent information about the message
2232 route_message(const struct GNUNET_MessageHeader *msg,
2233 struct DHT_MessageContext *message_context);
2237 * Server handler for all dht get requests, look for data,
2238 * if found, send response either to clients or other peers.
2240 * @param msg the actual get message
2241 * @param message_context struct containing pertinent information about the get request
2243 * @return number of items found for GET request
2246 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2247 struct DHT_MessageContext *message_context)
2249 const struct GNUNET_DHT_GetMessage *get_msg;
2252 unsigned int results;
2254 enum GNUNET_BLOCK_Type type;
2256 msize = ntohs (msg->size);
2257 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2262 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2263 bf_size = ntohs (get_msg->bf_size);
2264 message_context->xquery_size = ntohs (get_msg->xquery_size);
2265 message_context->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2266 if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + message_context->xquery_size)
2271 end = (const char*) &get_msg[1];
2272 if (message_context->xquery_size == 0)
2274 message_context->xquery = NULL;
2278 message_context->xquery = (const void*) end;
2279 end += message_context->xquery_size;
2283 message_context->reply_bf = NULL;
2287 message_context->reply_bf = GNUNET_CONTAINER_bloomfilter_init (end,
2289 GNUNET_DHT_GET_BLOOMFILTER_K);
2291 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2293 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2294 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2298 GNUNET_h2s (&message_context->key),
2299 message_context->unique_id);
2301 increment_stats(STAT_GETS);
2304 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2306 GNUNET_CONTAINER_bloomfilter_free (message_context->reply_bf);
2310 message_context->do_forward = GNUNET_YES;
2311 if (datacache != NULL)
2313 = GNUNET_DATACACHE_get (datacache,
2314 &message_context->key, type,
2315 &datacache_get_iterator,
2318 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2319 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2320 results, "GET", message_context->unique_id);
2324 #if DEBUG_DHT_ROUTING
2325 if ((debug_routes) && (dhtlog_handle != NULL))
2327 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2328 message_context->hop_count, GNUNET_YES, &my_identity,
2329 &message_context->key);
2332 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2334 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2335 message_context->hop_count, GNUNET_YES,
2336 &my_identity, &message_context->key, message_context->peer,
2343 /* check query valid */
2344 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID
2345 == GNUNET_BLOCK_evaluate (block_context,
2347 &message_context->key,
2348 &message_context->reply_bf,
2349 message_context->reply_bf_mutator,
2350 message_context->xquery,
2351 message_context->xquery_size,
2354 GNUNET_break_op (0);
2355 message_context->do_forward = GNUNET_NO;
2359 if (message_context->hop_count == 0) /* Locally initiated request */
2361 #if DEBUG_DHT_ROUTING
2362 if ((debug_routes) && (dhtlog_handle != NULL))
2364 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2365 message_context->hop_count, GNUNET_NO, &my_identity,
2366 &message_context->key);
2370 if (message_context->do_forward == GNUNET_YES)
2371 route_message (msg, message_context);
2372 GNUNET_CONTAINER_bloomfilter_free (message_context->reply_bf);
2377 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2379 GNUNET_HashCode *key = cls;
2381 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, NULL));
2386 * Server handler for initiating local dht find peer requests
2388 * @param find_msg the actual find peer message
2389 * @param message_context struct containing pertinent information about the request
2393 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2394 struct DHT_MessageContext *message_context)
2396 struct GNUNET_MessageHeader *find_peer_result;
2397 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2398 struct DHT_MessageContext *new_msg_ctx;
2399 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2402 GNUNET_HashCode *recent_hash;
2403 struct GNUNET_MessageHeader *other_hello;
2404 size_t other_hello_size;
2405 struct GNUNET_PeerIdentity peer_id;
2407 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2408 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2409 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2412 other_hello_size = 0;
2413 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2415 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2416 other_hello = GNUNET_malloc(other_hello_size);
2417 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2418 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)))
2420 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2421 GNUNET_free(other_hello);
2424 #if FIND_PEER_WITH_HELLO
2425 if (GNUNET_YES == consider_peer(&peer_id))
2427 increment_stats(STAT_HELLOS_PROVIDED);
2428 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2429 GNUNET_CORE_peer_request_connect(cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2430 route_message (find_msg, message_context);
2431 GNUNET_free (other_hello);
2434 else /* We don't want this peer! */
2436 route_message (find_msg, message_context);
2437 GNUNET_free (other_hello);
2444 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2445 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2446 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&message_context->key),
2447 ntohs (find_msg->size),
2448 sizeof (struct GNUNET_MessageHeader));
2450 if (my_hello == NULL)
2453 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2454 "`%s': Our HELLO is null, can't return.\n",
2457 GNUNET_free_non_null (other_hello);
2458 route_message (find_msg, message_context);
2462 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2463 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2465 increment_stats(STAT_BLOOM_FIND_PEER);
2466 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2467 GNUNET_free_non_null(other_hello);
2468 route_message (find_msg, message_context);
2469 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2471 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2473 #if RESTRICT_FIND_PEER
2476 * Ignore any find peer requests from a peer we have seen very recently.
2478 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent_find_peer_requests, &message_context->key)) /* We have recently responded to a find peer request for this peer! */
2480 increment_stats("# dht find peer requests ignored (recently seen!)");
2481 GNUNET_free_non_null(other_hello);
2486 * Use this check to only allow the peer to respond to find peer requests if
2487 * it would be beneficial to have the requesting peer in this peers routing
2488 * table. Can be used to thwart peers flooding the network with find peer
2489 * requests that we don't care about. However, if a new peer is joining
2490 * the network and has no other peers this is a problem (assume all buckets
2491 * full, no one will respond!).
2493 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2494 if (GNUNET_NO == consider_peer(&peer_id))
2496 increment_stats("# dht find peer requests ignored (do not need!)");
2497 GNUNET_free_non_null(other_hello);
2498 route_message (find_msg, message_context);
2503 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2504 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2505 if (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2506 &message_context->key, NULL,
2507 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2509 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding recent remove task for key `%s`!\n", GNUNET_h2s(&message_context->key));
2510 /* Only add a task if there wasn't one for this key already! */
2511 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30),
2512 &remove_recent_find_peer, recent_hash);
2516 GNUNET_free(recent_hash);
2517 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received duplicate find peer request too soon!\n");
2520 /* Simplistic find_peer functionality, always return our hello */
2521 hello_size = ntohs(my_hello->size);
2522 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2524 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2526 GNUNET_break_op (0);
2527 GNUNET_free_non_null(other_hello);
2531 find_peer_result = GNUNET_malloc (tsize);
2532 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2533 find_peer_result->size = htons (tsize);
2534 memcpy (&find_peer_result[1], my_hello, hello_size);
2536 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2537 "`%s': Sending hello size %d to requesting peer.\n",
2540 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2541 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2542 new_msg_ctx->peer = &my_identity;
2543 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2544 new_msg_ctx->hop_count = 0;
2545 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2546 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2547 increment_stats(STAT_FIND_PEER_ANSWER);
2548 route_result_message(find_peer_result, new_msg_ctx);
2549 GNUNET_free(new_msg_ctx);
2550 #if DEBUG_DHT_ROUTING
2551 if ((debug_routes) && (dhtlog_handle != NULL))
2553 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2554 message_context->hop_count, GNUNET_YES, &my_identity,
2555 &message_context->key);
2558 GNUNET_free_non_null(other_hello);
2559 GNUNET_free(find_peer_result);
2560 route_message (find_msg, message_context);
2564 * Task used to republish data.
2565 * Forward declaration; function call loop.
2567 * @param cls closure (a struct RepublishContext)
2568 * @param tc runtime context for this task
2571 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2574 * Server handler for initiating local dht put requests
2576 * @param msg the actual put message
2577 * @param message_context struct containing pertinent information about the request
2580 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2581 struct DHT_MessageContext *message_context)
2583 const struct GNUNET_DHT_PutMessage *put_msg;
2584 enum GNUNET_BLOCK_Type put_type;
2587 struct RepublishContext *put_context;
2588 GNUNET_HashCode key;
2590 GNUNET_assert (ntohs (msg->size) >=
2591 sizeof (struct GNUNET_DHT_PutMessage));
2594 put_msg = (const struct GNUNET_DHT_PutMessage *)msg;
2595 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2597 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2600 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2601 ret = GNUNET_BLOCK_get_key (block_context,
2606 if (GNUNET_NO == ret)
2609 GNUNET_break_op (0);
2612 if ( (GNUNET_YES == ret) &&
2614 &message_context->key,
2615 sizeof (GNUNET_HashCode))) )
2617 /* invalid wrapper: key mismatch! */
2618 GNUNET_break_op (0);
2621 /* ret == GNUNET_SYSERR means that there is no known relationship between
2622 data and the key, so we cannot check it */
2624 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2625 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2626 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
2628 #if DEBUG_DHT_ROUTING
2629 if (message_context->hop_count == 0) /* Locally initiated request */
2631 if ((debug_routes) && (dhtlog_handle != NULL))
2633 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2634 message_context->hop_count, GNUNET_NO, &my_identity,
2635 &message_context->key);
2640 if (message_context->closest != GNUNET_YES)
2642 route_message (msg, message_context);
2647 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2648 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2649 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
2652 #if DEBUG_DHT_ROUTING
2653 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2655 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2656 message_context->hop_count, GNUNET_YES,
2657 &my_identity, &message_context->key, message_context->peer,
2661 if ((debug_routes) && (dhtlog_handle != NULL))
2663 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2664 message_context->hop_count, GNUNET_YES, &my_identity,
2665 &message_context->key);
2669 increment_stats(STAT_PUTS_INSERTED);
2670 if (datacache != NULL)
2672 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2673 (char *) &put_msg[1], put_type,
2674 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2676 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2678 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2679 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2680 put_context->type = put_type;
2681 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content, put_context);
2685 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2686 "`%s:%s': %s request received, but have no datacache!\n",
2687 my_short_id, "DHT", "PUT");
2689 if (stop_on_closest == GNUNET_NO)
2690 route_message (msg, message_context);
2694 * Estimate the diameter of the network based
2695 * on how many buckets are currently in use.
2696 * Concept here is that the diameter of the network
2697 * is roughly the distance a message must travel in
2698 * order to reach its intended destination. Since
2699 * at each hop we expect to get one bit closer, and
2700 * we have one bit per bucket, the number of buckets
2701 * in use should be the largest number of hops for
2702 * a successful message. (of course, this assumes we
2703 * know all peers in the network!)
2705 * @return ballpark diameter figure
2707 static unsigned int estimate_diameter()
2709 return MAX_BUCKETS - lowest_bucket;
2713 * To how many peers should we (on average)
2714 * forward the request to obtain the desired
2715 * target_replication count (on average).
2717 * Always 0, 1 or 2 (don't send, send once, split)
2720 get_forward_count (unsigned int hop_count, size_t target_replication)
2723 double target_count;
2724 double random_probability;
2726 uint32_t random_value;
2728 unsigned int target_value;
2729 unsigned int diameter;
2732 * If we are behaving in strict kademlia mode, send multiple initial requests,
2733 * but then only send to 1 or 0 peers based strictly on the number of hops.
2735 if (strict_kademlia == GNUNET_YES)
2738 return DHT_KADEMLIA_REPLICATION;
2739 else if (hop_count < max_hops)
2745 /* FIXME: the smaller we think the network is the more lenient we should be for
2746 * routing right? The estimation below only works if we think we have reasonably
2747 * full routing tables, which for our RR topologies may not be the case!
2749 diameter = estimate_diameter ();
2750 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size) && (use_max_hops == GNUNET_NO))
2753 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2754 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2755 "DHT", estimate_diameter(), lowest_bucket);
2759 else if (hop_count > max_hops)
2762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2763 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2770 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2771 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2772 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2773 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2774 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2775 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2776 RAND_MAX)) / RAND_MAX;
2777 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2780 //while (target_value < target_count)
2781 if (target_value < target_count)
2782 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? */
2785 //if ((target_count + 1 - (double)target_value) > random_probability)
2786 if ((target_count) > random_probability)
2790 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2791 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));
2793 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2794 if (random_value < target_replication)
2797 return target_value;
2801 * Check whether my identity is closer than any known peers.
2802 * If a non-null bloomfilter is given, check if this is the closest
2803 * peer that hasn't already been routed to.
2805 * @param target hash code to check closeness to
2806 * @param bloom bloomfilter, exclude these entries from the decision
2808 * Return GNUNET_YES if node location is closest, GNUNET_NO
2812 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2818 struct PeerInfo *pos;
2819 unsigned int my_distance;
2821 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2824 bucket_num = find_current_bucket(target);
2826 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2827 my_distance = distance(&my_identity.hashPubKey, target);
2828 pos = k_buckets[bucket_num].head;
2830 while ((pos != NULL) && (count < bucket_size))
2832 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2835 continue; /* Skip already checked entries */
2838 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2839 if (other_bits > bits)
2841 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2843 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2845 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2851 /* No peers closer, we are the closest! */
2857 * Return this peers adjusted value based on the convergence
2858 * function chosen. This is the key function for randomized
2859 * routing decisions.
2861 * @param target the key of the request
2862 * @param peer the peer we would like the value of
2863 * @param hops number of hops this message has already traveled
2865 * @return bit distance from target to peer raised to an exponent
2866 * adjusted based on the current routing convergence algorithm
2869 static unsigned long long
2870 converge_distance (const GNUNET_HashCode *target,
2871 struct PeerInfo *peer,
2874 unsigned long long ret;
2875 unsigned int other_matching_bits;
2876 double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
2877 double temp_modifier;
2883 curr_max_hops = max_hops;
2885 curr_max_hops = (estimate_diameter() + 1) * 2;
2887 if (converge_modifier > 0)
2888 temp_modifier = converge_modifier * base_converge_modifier;
2891 temp_modifier = base_converge_modifier;
2892 base_converge_modifier = 0.0;
2895 GNUNET_assert(temp_modifier > 0);
2897 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2899 switch (converge_option)
2901 case DHT_CONVERGE_RANDOM:
2902 return 1; /* Always return 1, choose equally among all peers */
2903 case DHT_CONVERGE_LINEAR:
2904 calc_value = hops * curr_max_hops * temp_modifier;
2906 case DHT_CONVERGE_SQUARE:
2908 * Simple square based curve.
2910 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * temp_modifier));
2912 case DHT_CONVERGE_EXPONENTIAL:
2914 * Simple exponential curve.
2916 if (base_converge_modifier > 0)
2917 calc_value = (temp_modifier * hops * hops) / curr_max_hops;
2919 calc_value = (hops * hops) / curr_max_hops;
2921 case DHT_CONVERGE_BINARY:
2923 * If below the cutoff, route randomly (return 1),
2924 * If above the cutoff, return the maximum possible
2925 * value first (always route to closest, because
2929 if (hops > converge_modifier) /* Past cutoff */
2938 /* Take the log (base e) of the number of bits matching the other peer */
2939 exponent = log(other_matching_bits);
2941 /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
2942 if (exponent * calc_value >= 44.361419555836498)
2945 /* Clear errno and all math exceptions */
2947 feclearexcept(FE_ALL_EXCEPT);
2948 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2949 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2952 if (0 != fetestexcept(FE_OVERFLOW))
2953 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2954 if (0 != fetestexcept(FE_INVALID))
2955 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2956 if (0 != fetestexcept(FE_UNDERFLOW))
2957 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2965 * Comparison function for two struct PeerInfo's
2966 * which have already had their matching bits to
2967 * some target calculated.
2969 * @param p1 a pointer pointer to a struct PeerInfo
2970 * @param p2 a pointer pointer to a struct PeerInfo
2972 * @return 0 if equidistant to target,
2973 * -1 if p1 is closer,
2977 compare_peers (const void *p1, const void *p2)
2979 struct PeerInfo **first = (struct PeerInfo **)p1;
2980 struct PeerInfo **second = (struct PeerInfo **)p2;
2982 if ((*first)->matching_bits > (*second)->matching_bits)
2984 if ((*first)->matching_bits < (*second)->matching_bits)
2992 * Select a peer from the routing table that would be a good routing
2993 * destination for sending a message for "target". The resulting peer
2994 * must not be in the set of blocked peers.<p>
2996 * Note that we should not ALWAYS select the closest peer to the
2997 * target, peers further away from the target should be chosen with
2998 * exponentially declining probability.
3000 * @param target the key we are selecting a peer to route to
3001 * @param bloom a bloomfilter containing entries this request has seen already
3003 * @return Peer to route to, or NULL on error
3005 static struct PeerInfo *
3006 select_peer (const GNUNET_HashCode * target,
3007 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3012 unsigned int offset;
3013 unsigned int my_matching_bits;
3015 struct PeerInfo *pos;
3016 struct PeerInfo *sorted_closest[bucket_size];
3017 unsigned long long temp_converge_distance;
3018 unsigned long long total_distance;
3019 unsigned long long selected;
3021 unsigned long long stats_total_distance;
3025 unsigned int distance;
3026 unsigned int largest_distance;
3027 struct PeerInfo *chosen;
3029 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
3032 if (strict_kademlia == GNUNET_YES)
3034 largest_distance = 0;
3036 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3038 pos = k_buckets[bc].head;
3040 while ((pos != NULL) && (count < bucket_size))
3042 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3043 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3045 distance = inverse_distance (target, &pos->id.hashPubKey);
3046 if (distance > largest_distance)
3049 largest_distance = distance;
3057 if ((largest_distance > 0) && (chosen != NULL))
3059 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
3070 /* Three steps: order peers in closest bucket (most matching bits).
3071 * Then go over all LOWER buckets (matching same bits we do)
3072 * Then go over all HIGHER buckets (matching less then we do)
3075 closest_bucket = find_current_bucket(target);
3076 GNUNET_assert(closest_bucket >= lowest_bucket);
3077 pos = k_buckets[closest_bucket].head;
3079 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3080 memset(sorted_closest, 0, sizeof(sorted_closest));
3081 /* Put any peers in the closest bucket in the sorting array */
3082 while ((pos != NULL) && (count < bucket_size))
3084 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3088 continue; /* Ignore bloomfiltered peers */
3090 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
3091 sorted_closest[offset] = pos;
3097 /* Sort the peers in descending order */
3098 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
3100 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3101 for (i = 0; i < offset; i++)
3103 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3104 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3105 break; /* Ignore bloomfiltered peers */
3106 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3107 total_distance += temp_converge_distance;
3109 break; /* overflow case */
3112 /* Now handle peers in lower buckets (matches same # of bits as target) */
3113 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3115 pos = k_buckets[bc].head;
3117 while ((pos != NULL) && (count < bucket_size))
3119 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3123 continue; /* Ignore bloomfiltered peers */
3125 temp_converge_distance = converge_distance(target, pos, hops);
3126 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3127 total_distance += temp_converge_distance;
3129 break; /* overflow case */
3135 /* Now handle all the further away peers */
3136 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3138 pos = k_buckets[bc].head;
3140 while ((pos != NULL) && (count < bucket_size))
3142 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3146 continue; /* Ignore bloomfiltered peers */
3148 temp_converge_distance = converge_distance(target, pos, hops);
3149 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3150 total_distance += temp_converge_distance;
3152 break; /* overflow case */
3158 if (total_distance == 0) /* No peers to select from! */
3160 increment_stats("# select_peer, total_distance == 0");
3164 #if DEBUG_DHT_ROUTING > 1
3167 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3168 stats_total_distance = 0;
3169 for (i = 0; i < offset; i++)
3171 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3172 break; /* Ignore bloomfiltered peers */
3173 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3174 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3175 stats_total_distance += temp_converge_distance;
3177 break; /* overflow case */
3178 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);
3181 /* Now handle peers in lower buckets (matches same # of bits as target) */
3182 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3184 pos = k_buckets[bc].head;
3186 while ((pos != NULL) && (count < bucket_size))
3188 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3192 continue; /* Ignore bloomfiltered peers */
3194 temp_converge_distance = converge_distance(target, pos, hops);
3195 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3196 stats_total_distance += temp_converge_distance;
3198 break; /* overflow case */
3199 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);
3205 /* Now handle all the further away peers */
3206 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3208 pos = k_buckets[bc].head;
3210 while ((pos != NULL) && (count < bucket_size))
3212 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3216 continue; /* Ignore bloomfiltered peers */
3218 temp_converge_distance = converge_distance(target, pos, hops);
3219 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3220 stats_total_distance += temp_converge_distance;
3222 break; /* overflow case */
3223 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);
3228 /* END PRINT STATS */
3231 /* Now actually choose a peer */
3232 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3234 /* Go over closest sorted peers. */
3235 for (i = 0; i < offset; i++)
3237 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3238 break; /* Ignore bloomfiltered peers */
3239 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3240 if (temp_converge_distance >= selected)
3241 return sorted_closest[i];
3243 selected -= temp_converge_distance;
3246 /* Now handle peers in lower buckets (matches same # of bits as target) */
3247 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3249 pos = k_buckets[bc].head;
3251 while ((pos != NULL) && (count < bucket_size))
3253 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3257 continue; /* Ignore bloomfiltered peers */
3259 temp_converge_distance = converge_distance(target, pos, hops);
3260 if (temp_converge_distance >= selected)
3263 selected -= temp_converge_distance;
3269 /* Now handle all the further away peers */
3270 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3272 pos = k_buckets[bc].head;
3274 while ((pos != NULL) && (count < bucket_size))
3276 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3280 continue; /* Ignore bloomfiltered peers */
3282 temp_converge_distance = converge_distance(target, pos, hops);
3283 if (temp_converge_distance >= selected)
3286 selected -= temp_converge_distance;
3292 increment_stats("# failed to select peer");
3298 * Task used to remove recent entries, either
3299 * after timeout, when full, or on shutdown.
3301 * @param cls the entry to remove
3302 * @param tc context, reason, etc.
3305 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3307 struct RecentRequest *req = cls;
3308 static GNUNET_HashCode hash;
3310 GNUNET_assert(req != NULL);
3311 hash_from_uid(req->uid, &hash);
3312 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3313 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3314 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3318 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3320 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3321 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3328 * Task used to remove forwarding entries, either
3329 * after timeout, when full, or on shutdown.
3331 * @param cls the entry to remove
3332 * @param tc context, reason, etc.
3335 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3337 struct DHTRouteSource *source_info = cls;
3338 struct DHTQueryRecord *record;
3339 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3340 record = source_info->record;
3341 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3343 if (record->head == NULL) /* No more entries in DLL */
3345 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3346 GNUNET_free(record);
3348 if (source_info->find_peers_responded != NULL)
3349 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3350 GNUNET_free(source_info);
3354 * Remember this routing request so that if a reply is
3355 * received we can either forward it to the correct peer
3356 * or return the result locally.
3358 * @param msg_ctx Context of the route request
3360 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3362 static int cache_response(struct DHT_MessageContext *msg_ctx)
3364 struct DHTQueryRecord *record;
3365 struct DHTRouteSource *source_info;
3366 struct DHTRouteSource *pos;
3367 struct GNUNET_TIME_Absolute now;
3368 unsigned int current_size;
3370 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3371 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3373 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3374 GNUNET_assert(source_info != NULL);
3375 record = source_info->record;
3376 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3377 if (record->head == NULL) /* No more entries in DLL */
3379 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3380 GNUNET_free(record);
3382 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3383 GNUNET_SCHEDULER_cancel(source_info->delete_task);
3384 if (source_info->find_peers_responded != NULL)
3385 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3386 GNUNET_free(source_info);
3387 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3389 now = GNUNET_TIME_absolute_get();
3390 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3391 if (record != NULL) /* Already know this request! */
3396 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3397 break; /* Already have this peer in reply list! */
3400 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3402 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.abs_value);
3408 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3409 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3410 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3413 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3414 source_info->record = record;
3415 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3416 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3417 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3418 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3419 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3421 source_info->client = msg_ctx->client;
3422 now = GNUNET_TIME_absolute_get_forever();
3424 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.abs_value);
3426 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3427 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3428 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3435 * Main function that handles whether or not to route a message to other
3438 * @param msg the message to be routed
3439 * @param message_context the context containing all pertinent information about the message
3442 route_message(const struct GNUNET_MessageHeader *msg,
3443 struct DHT_MessageContext *message_context)
3446 struct PeerInfo *selected;
3447 #if DEBUG_DHT_ROUTING > 1
3448 struct PeerInfo *nearest;
3450 unsigned int forward_count;
3451 struct RecentRequest *recent_req;
3452 GNUNET_HashCode unique_hash;
3453 char *stat_forward_count;
3454 char *temp_stat_str;
3455 #if DEBUG_DHT_ROUTING
3459 if (malicious_dropper == GNUNET_YES)
3461 #if DEBUG_DHT_ROUTING
3462 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3464 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3465 message_context->hop_count, GNUNET_SYSERR,
3466 &my_identity, &message_context->key, message_context->peer,
3470 if (message_context->bloom != NULL)
3471 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3475 increment_stats(STAT_ROUTES);
3476 /* Semantics of this call means we find whether we are the closest peer out of those already
3477 * routed to on this messages path.
3479 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3480 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3481 increment_stats(stat_forward_count);
3482 GNUNET_free(stat_forward_count);
3483 if (message_context->bloom == NULL)
3484 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3486 if ((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3490 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3491 * any closer peers (which is being checked for below). Since we are doing recursive
3492 * routing we have no choice but to stop forwarding in this case. This means that at
3493 * any given step the request may NOT be forwarded to alpha peers (because routes will
3494 * stop and the parallel route will not be aware of it). Of course, assuming that we
3495 * have fulfilled the Kademlia requirements for routing table fullness this will never
3496 * ever ever be a problem.
3498 * However, is this fair?
3500 * Since we use these requests to build our routing tables (and we build them in the
3501 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3502 * routing tables still get constructed.
3504 if ((GNUNET_YES == strict_kademlia) && (message_context->closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3507 #if DEBUG_DHT_ROUTING
3508 if (forward_count == 0)
3509 ret = GNUNET_SYSERR;
3513 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3515 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3516 message_context->hop_count, ret,
3517 &my_identity, &message_context->key, message_context->peer,
3523 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3524 hash_from_uid (message_context->unique_id, &unique_hash);
3525 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3527 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3528 GNUNET_assert(recent_req != NULL);
3529 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3530 increment_stats(STAT_DUPLICATE_UID);
3533 increment_stats(STAT_RECENT_SEEN);
3534 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3539 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3540 recent_req->uid = message_context->unique_id;
3541 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3542 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3543 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().abs_value);
3544 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3545 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3548 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3550 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3551 GNUNET_assert(recent_req != NULL);
3552 GNUNET_SCHEDULER_cancel(recent_req->remove_task);
3553 GNUNET_SCHEDULER_add_now(&remove_recent, recent_req);
3556 for (i = 0; i < forward_count; i++)
3558 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3560 if (selected != NULL)
3562 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
3563 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
3565 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
3566 if (temp_stat_str != NULL)
3568 increment_stats(temp_stat_str);
3569 GNUNET_free(temp_stat_str);
3571 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3572 #if DEBUG_DHT_ROUTING > 1
3573 nearest = find_closest_peer(&message_context->key);
3574 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3575 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3576 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3577 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&selected->id), nearest_buf, GNUNET_CRYPTO_hash_matching_bits(&nearest->id.hashPubKey, message_context->key), distance(&nearest->id.hashPubKey, message_context->key));
3578 GNUNET_free(nearest_buf);
3580 #if DEBUG_DHT_ROUTING
3581 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3583 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3584 message_context->hop_count, GNUNET_NO,
3585 &my_identity, &message_context->key, message_context->peer,
3589 forward_message(msg, selected, message_context);
3593 if (message_context->bloom != NULL)
3595 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3596 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3603 * Main function that handles whether or not to route a message to other
3606 * @param msg the message to be routed
3607 * @param message_context the context containing all pertinent information about the message
3610 demultiplex_message(const struct GNUNET_MessageHeader *msg,
3611 struct DHT_MessageContext *message_context)
3613 message_context->closest = am_closest_peer(&message_context->key, NULL);
3614 switch (ntohs(msg->type))
3616 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3617 cache_response (message_context);
3618 handle_dht_get (msg, message_context);
3620 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3621 increment_stats(STAT_PUTS);
3622 handle_dht_put (msg, message_context);
3624 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3625 increment_stats(STAT_FIND_PEER);
3626 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3628 cache_response (message_context);
3629 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3630 handle_dht_find_peer (msg, message_context);
3633 route_message (msg, message_context);
3634 #if DEBUG_DHT_ROUTING
3635 if (message_context->hop_count == 0) /* Locally initiated request */
3637 if ((debug_routes) && (dhtlog_handle != NULL))
3639 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3640 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3641 message_context->hop_count, GNUNET_NO, &my_identity,
3642 &message_context->key);
3648 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3649 "`%s': Message type (%d) not handled, forwarding anyway!\n", "DHT", ntohs(msg->type));
3650 route_message (msg, message_context);
3658 * Iterator for local get request results,
3660 * @param cls closure for iterator, NULL
3661 * @param exp when does this value expire?
3662 * @param key the key this data is stored under
3663 * @param size the size of the data identified by key
3664 * @param data the actual data
3665 * @param type the type of the data
3667 * @return GNUNET_OK to continue iteration, anything else
3668 * to stop iteration.
3671 republish_content_iterator (void *cls,
3672 struct GNUNET_TIME_Absolute exp,
3673 const GNUNET_HashCode * key,
3674 size_t size, const char *data, uint32_t type)
3677 struct DHT_MessageContext *new_msg_ctx;
3678 struct GNUNET_DHT_PutMessage *put_msg;
3680 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3681 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3683 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3686 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3687 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3688 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3689 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3690 put_msg->type = htons (type);
3691 memcpy (&put_msg[1], data, size);
3692 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3693 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3694 new_msg_ctx->msg_options = ntohl (0);
3695 new_msg_ctx->network_size = estimate_diameter();
3696 new_msg_ctx->peer = &my_identity;
3697 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3698 new_msg_ctx->hop_count = 0;
3699 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3700 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3701 increment_stats(STAT_PUT_START);
3702 demultiplex_message(&put_msg->header, new_msg_ctx);
3704 GNUNET_free(new_msg_ctx);
3705 GNUNET_free (put_msg);
3710 * Task used to republish data.
3712 * @param cls closure (a struct RepublishContext)
3713 * @param tc runtime context for this task
3716 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3718 struct RepublishContext *put_context = cls;
3720 unsigned int results;
3722 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3724 GNUNET_free(put_context);
3728 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3729 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3730 if (results == 0) /* Data must have expired */
3731 GNUNET_free(put_context);
3732 else /* Reschedule task for next time period */
3733 GNUNET_SCHEDULER_add_delayed(dht_republish_frequency, &republish_content, put_context);
3739 * Iterator over hash map entries.
3741 * @param cls client to search for in source routes
3742 * @param key current key code (ignored)
3743 * @param value value in the hash map, a DHTQueryRecord
3744 * @return GNUNET_YES if we should continue to
3748 static int find_client_records (void *cls,
3749 const GNUNET_HashCode * key, void *value)
3751 struct ClientList *client = cls;
3752 struct DHTQueryRecord *record = value;
3753 struct DHTRouteSource *pos;
3757 if (pos->client == client)
3763 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3764 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3765 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3766 GNUNET_SCHEDULER_cancel(pos->delete_task);
3768 if (pos->find_peers_responded != NULL)
3769 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3772 if (record->head == NULL) /* No more entries in DLL */
3774 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3775 GNUNET_free(record);
3781 * Functions with this signature are called whenever a client
3782 * is disconnected on the network level.
3784 * @param cls closure (NULL for dht)
3785 * @param client identification of the client; NULL
3786 * for the last call when the server is destroyed
3788 static void handle_client_disconnect (void *cls,
3789 struct GNUNET_SERVER_Client* client)
3791 struct ClientList *pos = client_list;
3792 struct ClientList *prev;
3793 struct ClientList *found;
3794 struct PendingMessage *reply;
3800 if (pos->client_handle == client)
3803 prev->next = pos->next;
3805 client_list = pos->next;
3815 while(NULL != (reply = found->pending_head))
3817 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3820 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3826 * Find a client if it exists, add it otherwise.
3828 * @param client the server handle to the client
3830 * @return the client if found, a new client otherwise
3832 static struct ClientList *
3833 find_active_client (struct GNUNET_SERVER_Client *client)
3835 struct ClientList *pos = client_list;
3836 struct ClientList *ret;
3840 if (pos->client_handle == client)
3845 ret = GNUNET_malloc (sizeof (struct ClientList));
3846 ret->client_handle = client;
3847 ret->next = client_list;
3855 * Task to send a malicious put message across the network.
3857 * @param cls closure for this task
3858 * @param tc the context under which the task is running
3861 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3863 static struct GNUNET_DHT_PutMessage put_message;
3864 static struct DHT_MessageContext message_context;
3865 static GNUNET_HashCode key;
3866 uint32_t random_key;
3868 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3870 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3871 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3872 put_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3873 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3874 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3875 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3876 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3877 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3878 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3879 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3880 message_context.msg_options = ntohl (0);
3881 message_context.network_size = estimate_diameter();
3882 message_context.peer = &my_identity;
3883 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3884 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3885 #if DEBUG_DHT_ROUTING
3886 if (dhtlog_handle != NULL)
3887 dhtlog_handle->insert_dhtkey(NULL, &key);
3889 increment_stats(STAT_PUT_START);
3890 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3891 demultiplex_message(&put_message.header, &message_context);
3892 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3897 * Task to send a malicious put message across the network.
3899 * @param cls closure for this task
3900 * @param tc the context under which the task is running
3903 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3905 static struct GNUNET_DHT_GetMessage get_message;
3906 struct DHT_MessageContext message_context;
3907 static GNUNET_HashCode key;
3908 uint32_t random_key;
3910 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3913 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3914 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3915 get_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3916 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3917 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3918 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3919 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3920 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3921 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3922 message_context.msg_options = ntohl (0);
3923 message_context.network_size = estimate_diameter();
3924 message_context.peer = &my_identity;
3925 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3926 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3927 #if DEBUG_DHT_ROUTING
3928 if (dhtlog_handle != NULL)
3929 dhtlog_handle->insert_dhtkey(NULL, &key);
3931 increment_stats(STAT_GET_START);
3932 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3933 demultiplex_message (&get_message.header, &message_context);
3934 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3940 * Iterator over hash map entries.
3942 * @param cls closure
3943 * @param key current key code
3944 * @param value value in the hash map
3945 * @return GNUNET_YES if we should continue to
3950 add_known_to_bloom (void *cls,
3951 const GNUNET_HashCode * key,
3954 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3955 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3960 * Task to send a find peer message for our own peer identifier
3961 * so that we can find the closest peers in the network to ourselves
3962 * and attempt to connect to them.
3964 * @param cls closure for this task
3965 * @param tc the context under which the task is running
3968 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3970 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3971 struct DHT_MessageContext message_context;
3972 struct GNUNET_TIME_Relative next_send_time;
3973 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3975 struct GNUNET_TIME_Relative time_diff;
3976 struct GNUNET_TIME_Absolute end;
3978 double count_per_interval;
3980 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3983 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! */
3985 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3986 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3987 &send_find_peer_message, NULL);
3988 newly_found_peers = 0;
3992 increment_stats(STAT_FIND_PEER_START);
3994 end = GNUNET_TIME_absolute_get();
3995 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3997 if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
3999 multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
4000 count_per_interval = find_peer_context.count / multiplier;
4004 multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
4005 count_per_interval = find_peer_context.count * multiplier;
4009 #if FIND_PEER_WITH_HELLO
4010 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4011 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4012 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4014 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
4015 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
4017 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4018 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4019 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
4020 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
4021 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4022 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
4023 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
4024 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4025 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4026 message_context.network_size = estimate_diameter();
4027 message_context.peer = &my_identity;
4028 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4029 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4031 demultiplex_message(&find_peer_msg->header, &message_context);
4032 GNUNET_free(find_peer_msg);
4033 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4034 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
4036 if (newly_found_peers < bucket_size)
4038 next_send_time.rel_value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4039 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4040 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4044 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4045 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4046 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4049 GNUNET_assert (next_send_time.rel_value != 0);
4050 find_peer_context.count = 0;
4051 newly_found_peers = 0;
4052 find_peer_context.start = GNUNET_TIME_absolute_get();
4053 if (GNUNET_YES == do_find_peer)
4055 GNUNET_SCHEDULER_add_delayed (next_send_time,
4056 &send_find_peer_message, NULL);
4061 * Handler for any generic DHT messages, calls the appropriate handler
4062 * depending on message type, sends confirmation if responses aren't otherwise
4065 * @param cls closure for the service
4066 * @param client the client we received this message from
4067 * @param message the actual message received
4070 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4071 const struct GNUNET_MessageHeader *message)
4073 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
4074 const struct GNUNET_MessageHeader *enc_msg;
4075 struct DHT_MessageContext message_context;
4077 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4079 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4080 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4084 ntohs (message->type),
4085 GNUNET_h2s (&dht_msg->key),
4086 GNUNET_ntohll (dht_msg->unique_id));
4088 #if DEBUG_DHT_ROUTING
4089 if (dhtlog_handle != NULL)
4090 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4092 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4093 message_context.client = find_active_client (client);
4094 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
4095 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4096 message_context.replication = ntohl (dht_msg->desired_replication_level);
4097 message_context.msg_options = ntohl (dht_msg->options);
4098 message_context.network_size = estimate_diameter();
4099 message_context.peer = &my_identity;
4100 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
4101 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4102 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4103 increment_stats(STAT_GET_START);
4104 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4105 increment_stats(STAT_PUT_START);
4106 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4107 increment_stats(STAT_FIND_PEER_START);
4109 demultiplex_message(enc_msg, &message_context);
4111 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4116 * Handler for any locally received DHT control messages,
4117 * sets malicious flags mostly for now.
4119 * @param cls closure for the service
4120 * @param client the client we received this message from
4121 * @param message the actual message received
4125 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4126 const struct GNUNET_MessageHeader *message)
4128 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4129 (const struct GNUNET_DHT_ControlMessage *) message;
4131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4132 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4133 "CONTROL", ntohs(dht_control_msg->command));
4136 switch (ntohs(dht_control_msg->command))
4138 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4139 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4140 GNUNET_SCHEDULER_add_now(&send_find_peer_message, NULL);
4143 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4144 if (ntohs(dht_control_msg->variable) > 0)
4145 malicious_get_frequency = ntohs(dht_control_msg->variable);
4146 if (malicious_get_frequency == 0)
4147 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4148 if (malicious_getter != GNUNET_YES)
4149 GNUNET_SCHEDULER_add_now(&malicious_get_task, NULL);
4150 malicious_getter = GNUNET_YES;
4151 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4152 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4154 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4155 if (ntohs(dht_control_msg->variable) > 0)
4156 malicious_put_frequency = ntohs(dht_control_msg->variable);
4157 if (malicious_put_frequency == 0)
4158 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4159 if (malicious_putter != GNUNET_YES)
4160 GNUNET_SCHEDULER_add_now(&malicious_put_task, NULL);
4161 malicious_putter = GNUNET_YES;
4162 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4163 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4165 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4166 #if DEBUG_DHT_ROUTING
4167 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4168 dhtlog_handle->set_malicious(&my_identity);
4170 malicious_dropper = GNUNET_YES;
4171 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4172 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4176 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4177 "%s:%s Unknown control command type `%d'!\n",
4179 ntohs(dht_control_msg->command));
4183 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4187 * Handler for any generic DHT stop messages, calls the appropriate handler
4188 * depending on message type (if processed locally)
4190 * @param cls closure for the service
4191 * @param client the client we received this message from
4192 * @param message the actual message received
4196 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4197 const struct GNUNET_MessageHeader *message)
4200 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4201 (const struct GNUNET_DHT_StopMessage *) message;
4202 struct DHTQueryRecord *record;
4203 struct DHTRouteSource *pos;
4205 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4206 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4207 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4209 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
4216 if ((pos->client != NULL) && (pos->client->client_handle == client))
4218 GNUNET_SCHEDULER_cancel(pos->delete_task);
4219 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4220 GNUNET_SCHEDULER_add_now(&remove_forward_entry, pos);
4226 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4231 * Core handler for p2p route requests.
4234 handle_dht_p2p_route_request (void *cls,
4235 const struct GNUNET_PeerIdentity *peer,
4236 const struct GNUNET_MessageHeader *message,
4237 struct GNUNET_TIME_Relative latency, uint32_t distance)
4240 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4241 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4243 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4244 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4245 struct DHT_MessageContext *message_context;
4247 if (get_max_send_delay().rel_value > MAX_REQUEST_TIME.rel_value)
4249 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
4250 increment_stats("# route requests dropped due to high load");
4251 decrease_max_send_delay(get_max_send_delay());
4255 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4258 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4263 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4268 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4269 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4270 GNUNET_assert(message_context->bloom != NULL);
4271 message_context->hop_count = ntohl(incoming->hop_count);
4272 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
4273 message_context->replication = ntohl(incoming->desired_replication_level);
4274 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
4275 message_context->msg_options = ntohl(incoming->options);
4276 message_context->network_size = ntohl(incoming->network_size);
4277 message_context->peer = peer;
4278 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4279 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4280 demultiplex_message(enc_msg, message_context);
4281 GNUNET_free(message_context);
4287 * Core handler for p2p route results.
4290 handle_dht_p2p_route_result (void *cls,
4291 const struct GNUNET_PeerIdentity *peer,
4292 const struct GNUNET_MessageHeader *message,
4293 struct GNUNET_TIME_Relative latency, uint32_t distance)
4296 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4297 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4299 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4300 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4301 struct DHT_MessageContext message_context;
4303 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4309 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4310 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4311 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4312 GNUNET_assert(message_context.bloom != NULL);
4313 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
4314 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
4315 message_context.msg_options = ntohl(incoming->options);
4316 message_context.hop_count = ntohl(incoming->hop_count);
4317 message_context.peer = peer;
4318 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
4319 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4320 route_result_message(enc_msg, &message_context);
4326 * Receive the HELLO from transport service,
4327 * free current and replace if necessary.
4330 * @param message HELLO message of peer
4333 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4336 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4337 "Received our `%s' from transport service\n",
4341 GNUNET_assert (message != NULL);
4342 GNUNET_free_non_null(my_hello);
4343 my_hello = GNUNET_malloc(ntohs(message->size));
4344 memcpy(my_hello, message, ntohs(message->size));
4349 * Task run during shutdown.
4355 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4358 struct PeerInfo *pos;
4360 if (transport_handle != NULL)
4362 GNUNET_free_non_null(my_hello);
4363 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4364 GNUNET_TRANSPORT_disconnect(transport_handle);
4366 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4368 while (k_buckets[bucket_count].head != NULL)
4370 pos = k_buckets[bucket_count].head;
4372 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4373 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4375 delete_peer(pos, bucket_count);
4378 if (coreAPI != NULL)
4381 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4382 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4384 GNUNET_CORE_disconnect (coreAPI);
4387 if (datacache != NULL)
4390 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4391 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4393 GNUNET_DATACACHE_destroy (datacache);
4398 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4401 if (dhtlog_handle != NULL)
4403 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4404 dhtlog_handle = NULL;
4406 if (block_context != NULL)
4408 GNUNET_BLOCK_context_destroy (block_context);
4409 block_context = NULL;
4411 GNUNET_free_non_null(my_short_id);
4417 * To be called on core init/fail.
4419 * @param cls service closure
4420 * @param server handle to the server for this service
4421 * @param identity the public identity of this peer
4422 * @param publicKey the public key of this peer
4425 core_init (void *cls,
4426 struct GNUNET_CORE_Handle *server,
4427 const struct GNUNET_PeerIdentity *identity,
4428 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4434 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4435 "%s: Connection to core FAILED!\n", "dht",
4436 GNUNET_i2s (identity));
4438 GNUNET_SCHEDULER_cancel (cleanup_task);
4439 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4443 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4444 "%s: Core connection initialized, I am peer: %s\n", "dht",
4445 GNUNET_i2s (identity));
4448 /* Copy our identity so we can use it */
4449 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4450 if (my_short_id != NULL)
4451 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4452 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4453 /* Set the server to local variable */
4456 if (dhtlog_handle != NULL)
4457 dhtlog_handle->insert_node (NULL, &my_identity);
4461 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4462 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4463 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4464 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4469 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4470 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4471 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4477 * Method called whenever a peer connects.
4479 * @param cls closure
4480 * @param peer peer identity this notification is about
4481 * @param latency reported latency of the connection with peer
4482 * @param distance reported distance (DV) to peer
4484 void handle_core_connect (void *cls,
4485 const struct GNUNET_PeerIdentity * peer,
4486 struct GNUNET_TIME_Relative latency,
4489 struct PeerInfo *ret;
4492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4493 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4496 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4498 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));
4502 if (datacache != NULL)
4503 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, GNUNET_BLOCK_TYPE_DHT_HELLO, GNUNET_TIME_absolute_get_forever());
4504 ret = try_add_peer(peer,
4505 find_current_bucket(&peer->hashPubKey),
4510 newly_found_peers++;
4511 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4514 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4515 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4521 * Method called whenever a peer disconnects.
4523 * @param cls closure
4524 * @param peer peer identity this notification is about
4526 void handle_core_disconnect (void *cls,
4528 GNUNET_PeerIdentity * peer)
4530 struct PeerInfo *to_remove;
4533 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");
4535 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4537 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));
4540 increment_stats(STAT_DISCONNECTS);
4541 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4542 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4543 GNUNET_assert (to_remove != NULL);
4544 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4545 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4546 delete_peer(to_remove, current_bucket);
4551 * Process dht requests.
4553 * @param cls closure
4554 * @param server the initialized server
4555 * @param c configuration to use
4559 struct GNUNET_SERVER_Handle *server,
4560 const struct GNUNET_CONFIGURATION_Handle *c)
4562 struct GNUNET_TIME_Relative next_send_time;
4563 unsigned long long temp_config_num;
4564 char *converge_modifier_buf;
4567 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4568 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4569 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4570 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
4572 GNUNET_TIME_UNIT_FOREVER_REL,
4573 NULL, /* Closure passed to DHT functions */
4574 &core_init, /* Call core_init once connected */
4575 &handle_core_connect, /* Handle connects */
4576 &handle_core_disconnect, /* remove peers on disconnects */
4577 NULL, /* Do we care about "status" updates? */
4578 NULL, /* Don't want notified about all incoming messages */
4579 GNUNET_NO, /* For header only inbound notification */
4580 NULL, /* Don't want notified about all outbound messages */
4581 GNUNET_NO, /* For header only outbound notification */
4582 core_handlers); /* Register these handlers */
4584 if (coreAPI == NULL)
4586 transport_handle = GNUNET_TRANSPORT_connect(cfg,
4587 NULL, NULL, NULL, NULL, NULL);
4588 if (transport_handle != NULL)
4589 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4591 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4592 "Failed to connect to transport service!\n");
4593 block_context = GNUNET_BLOCK_context_create (cfg);
4594 lowest_bucket = MAX_BUCKETS - 1;
4595 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4596 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4597 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4598 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4599 GNUNET_assert(all_known_peers != NULL);
4600 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4602 debug_routes = GNUNET_YES;
4606 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4609 strict_kademlia = GNUNET_YES;
4613 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4616 stop_on_closest = GNUNET_YES;
4620 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4623 stop_on_found = GNUNET_YES;
4627 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4628 "malicious_getter"))
4630 malicious_getter = GNUNET_YES;
4631 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4632 "MALICIOUS_GET_FREQUENCY",
4633 &malicious_get_frequency))
4634 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4637 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4641 max_hops = DEFAULT_MAX_HOPS;
4644 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4647 use_max_hops = GNUNET_YES;
4651 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4652 "malicious_putter"))
4654 malicious_putter = GNUNET_YES;
4655 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4656 "MALICIOUS_PUT_FREQUENCY",
4657 &malicious_put_frequency))
4658 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4661 dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
4662 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4664 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4668 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4669 "malicious_dropper"))
4671 malicious_dropper = GNUNET_YES;
4675 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4677 do_republish = GNUNET_NO;
4680 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4683 do_find_peer = GNUNET_NO;
4686 do_find_peer = GNUNET_YES;
4689 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4690 "use_real_distance"))
4691 use_real_distance = GNUNET_YES;
4694 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4695 "mysql_logging_extended"))
4697 debug_routes = GNUNET_YES;
4698 debug_routes_extended = GNUNET_YES;
4701 #if DEBUG_DHT_ROUTING
4702 if (GNUNET_YES == debug_routes)
4704 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4705 if (dhtlog_handle == NULL)
4707 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4708 "Could not connect to mysql logging server, logging will not happen!");
4713 converge_option = DHT_CONVERGE_SQUARE;
4715 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4718 converge_option = DHT_CONVERGE_LINEAR;
4720 else if (GNUNET_YES ==
4721 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4722 "converge_exponential"))
4724 converge_option = DHT_CONVERGE_EXPONENTIAL;
4726 else if (GNUNET_YES ==
4727 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4730 converge_option = DHT_CONVERGE_RANDOM;
4732 else if (GNUNET_YES ==
4733 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4736 converge_option = DHT_CONVERGE_BINARY;
4739 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4741 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4743 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4744 converge_modifier = 0.0;
4746 GNUNET_free(converge_modifier_buf);
4749 stats = GNUNET_STATISTICS_create("dht", cfg);
4753 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4754 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4755 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4756 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4757 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4758 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4759 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4760 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4761 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4762 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4763 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4764 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4765 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4766 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4767 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4768 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4769 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4770 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4771 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4772 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4774 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4775 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4776 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4777 if (GNUNET_YES == do_find_peer)
4779 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4780 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4781 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4782 find_peer_context.start = GNUNET_TIME_absolute_get();
4783 GNUNET_SCHEDULER_add_delayed (next_send_time,
4784 &send_find_peer_message, &find_peer_context);
4787 /* Scheduled the task to clean up when shutdown is called */
4788 cleanup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4789 &shutdown_task, NULL);
4793 * The main function for the dht service.
4795 * @param argc number of arguments from the command line
4796 * @param argv command line arguments
4797 * @return 0 ok, 1 on error
4800 main (int argc, char *const *argv)
4805 GNUNET_SERVICE_run (argc,
4808 GNUNET_SERVICE_OPTION_NONE,
4809 &run, NULL)) ? 0 : 1;
4810 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap));
4811 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap));
4812 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4813 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4814 GNUNET_CONTAINER_heap_destroy (recent.minHeap);