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);
957 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.abs_value);
963 * Given the largest send delay, artificially decrease it
964 * so the next time around we may have a chance at sending
967 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
970 for (i = 0; i < MAX_REPLY_TIMES; i++)
972 if (reply_times[i].rel_value == max_time.rel_value)
974 reply_times[i].rel_value = reply_times[i].rel_value / 2;
981 * Find the maximum send time of the recently sent values.
983 * @return the average time between asking core to send a message
984 * and when the buffer for copying it is passed
986 static struct GNUNET_TIME_Relative get_max_send_delay()
989 struct GNUNET_TIME_Relative max_time;
990 max_time = GNUNET_TIME_relative_get_zero();
992 for (i = 0; i < MAX_REPLY_TIMES; i++)
994 if (reply_times[i].rel_value > max_time.rel_value)
995 max_time.rel_value = reply_times[i].rel_value;
998 if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
999 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.rel_value);
1004 increment_stats(const char *value)
1008 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
1013 * Try to send another message from our core send list
1016 try_core_send (void *cls,
1017 const struct GNUNET_SCHEDULER_TaskContext *tc)
1019 struct PeerInfo *peer = cls;
1020 struct P2PPendingMessage *pending;
1023 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
1025 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1028 if (peer->th != NULL)
1029 return; /* Message send already in progress */
1031 pending = peer->head;
1032 if (pending != NULL)
1034 ssize = ntohs(pending->msg->size);
1036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1037 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
1038 "DHT", ssize, GNUNET_i2s(&peer->id));
1040 pending->scheduled = GNUNET_TIME_absolute_get();
1042 if (reply_counter >= MAX_REPLY_TIMES)
1044 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
1045 pending->timeout, &peer->id,
1046 ssize, &core_transmit_notify, peer);
1051 * Function called to send a request out to another peer.
1052 * Called both for locally initiated requests and those
1053 * received from other peers.
1055 * @param msg the encapsulated message
1056 * @param peer the peer to forward the message to
1057 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1060 forward_result_message (const struct GNUNET_MessageHeader *msg,
1061 struct PeerInfo *peer,
1062 struct DHT_MessageContext *msg_ctx)
1064 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1065 struct P2PPendingMessage *pending;
1069 increment_stats(STAT_RESULT_FORWARDS);
1070 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1071 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1072 psize = sizeof(struct P2PPendingMessage) + msize;
1073 pending = GNUNET_malloc(psize);
1074 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1075 pending->importance = DHT_SEND_PRIORITY;
1076 pending->timeout = GNUNET_TIME_relative_get_forever();
1077 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1078 result_message->header.size = htons(msize);
1079 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1080 result_message->put_path_length = htons(0); /* FIXME: implement */
1081 result_message->get_path_length = htons(0); /* FIXME: implement */
1082 result_message->options = htonl(msg_ctx->msg_options);
1083 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1084 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1085 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1086 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1087 memcpy(&result_message[1], msg, ntohs(msg->size));
1089 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));
1091 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1092 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1093 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1098 * Called when core is ready to send a message we asked for
1099 * out to the destination.
1101 * @param cls closure (NULL)
1102 * @param size number of bytes available in buf
1103 * @param buf where the callee should write the message
1104 * @return number of bytes written to buf
1107 core_transmit_notify (void *cls,
1108 size_t size, void *buf)
1110 struct PeerInfo *peer = cls;
1112 struct P2PPendingMessage *pending;
1119 /* client disconnected */
1121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1126 if (peer->head == NULL)
1131 pending = peer->head;
1132 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1133 msize = ntohs(pending->msg->size);
1137 memcpy (cbuf, pending->msg, msize);
1138 GNUNET_CONTAINER_DLL_remove (peer->head,
1142 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));
1144 GNUNET_free (pending);
1147 while (NULL != pending &&
1148 (size - off >= (msize = ntohs (pending->msg->size))))
1150 #if DEBUG_DHT_ROUTING
1151 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);
1153 memcpy (&cbuf[off], pending->msg, msize);
1155 GNUNET_CONTAINER_DLL_remove (peer->head,
1158 GNUNET_free (pending);
1159 pending = peer->head;
1162 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1163 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1165 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);
1172 * Compute the distance between have and target as a 32-bit value.
1173 * Differences in the lower bits must count stronger than differences
1174 * in the higher bits.
1176 * @return 0 if have==target, otherwise a number
1177 * that is larger as the distance between
1178 * the two hash codes increases
1181 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1183 unsigned int bucket;
1188 /* We have to represent the distance between two 2^9 (=512)-bit
1189 numbers as a 2^5 (=32)-bit number with "0" being used for the
1190 two numbers being identical; furthermore, we need to
1191 guarantee that a difference in the number of matching
1192 bits is always represented in the result.
1194 We use 2^32/2^9 numerical values to distinguish between
1195 hash codes that have the same LSB bit distance and
1196 use the highest 2^9 bits of the result to signify the
1197 number of (mis)matching LSB bits; if we have 0 matching
1198 and hence 512 mismatching LSB bits we return -1 (since
1199 512 itself cannot be represented with 9 bits) */
1201 /* first, calculate the most significant 9 bits of our
1202 result, aka the number of LSBs */
1203 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1204 /* bucket is now a value between 0 and 512 */
1206 return 0; /* perfect match */
1208 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1209 below, we'd end up with max+1 (overflow)) */
1211 /* calculate the most significant bits of the final result */
1212 msb = (512 - bucket) << (32 - 9);
1213 /* calculate the 32-9 least significant bits of the final result by
1214 looking at the differences in the 32-9 bits following the
1215 mismatching bit at 'bucket' */
1217 for (i = bucket + 1;
1218 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1220 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1221 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1222 last bit set will be 31 -- if
1223 i does not reach 512 first... */
1229 * Return a number that is larger the closer the
1230 * "have" GNUNET_hash code is to the "target".
1232 * @return inverse distance metric, non-zero.
1233 * Must fudge the value if NO bits match.
1236 inverse_distance (const GNUNET_HashCode * target,
1237 const GNUNET_HashCode * have)
1239 if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1240 return 1; /* Never return 0! */
1241 return ((unsigned int) -1) - distance (target, have);
1245 * Find the optimal bucket for this key, regardless
1246 * of the current number of buckets in use.
1248 * @param hc the hashcode to compare our identity to
1250 * @return the proper bucket index, or GNUNET_SYSERR
1251 * on error (same hashcode)
1253 static int find_bucket(const GNUNET_HashCode *hc)
1257 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1258 if (bits == MAX_BUCKETS)
1259 return GNUNET_SYSERR;
1260 return MAX_BUCKETS - bits - 1;
1264 * Find which k-bucket this peer should go into,
1265 * taking into account the size of the k-bucket
1266 * array. This means that if more bits match than
1267 * there are currently buckets, lowest_bucket will
1270 * @param hc GNUNET_HashCode we are finding the bucket for.
1272 * @return the proper bucket index for this key,
1273 * or GNUNET_SYSERR on error (same hashcode)
1275 static int find_current_bucket(const GNUNET_HashCode *hc)
1278 actual_bucket = find_bucket(hc);
1280 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1281 return lowest_bucket;
1282 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1283 return lowest_bucket;
1285 return actual_bucket;
1290 * Find a routing table entry from a peer identity
1292 * @param peer the peer to look up
1294 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1297 find_bucket_by_peer(const struct PeerInfo *peer)
1300 struct PeerInfo *pos;
1302 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1304 pos = k_buckets[bucket].head;
1313 return GNUNET_SYSERR; /* No such peer. */
1319 * Print the complete routing table for this peer.
1322 print_routing_table ()
1325 struct PeerInfo *pos;
1326 char char_buf[30000];
1328 memset(char_buf, 0, sizeof(char_buf));
1330 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1331 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1332 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1334 pos = k_buckets[bucket].head;
1335 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1336 //fprintf(stderr, "Bucket %d:\n", bucket);
1339 //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));
1340 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));
1344 fprintf(stderr, "%s", char_buf);
1350 * Find a routing table entry from a peer identity
1352 * @param peer the peer identity to look up
1354 * @return the routing table entry, or NULL if not found
1356 static struct PeerInfo *
1357 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1360 struct PeerInfo *pos;
1361 bucket = find_current_bucket(&peer->hashPubKey);
1363 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1366 pos = k_buckets[bucket].head;
1369 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1373 return NULL; /* No such peer. */
1376 /* Forward declaration */
1378 update_core_preference (void *cls,
1379 const struct GNUNET_SCHEDULER_TaskContext *tc);
1381 * Function called with statistics about the given peer.
1383 * @param cls closure
1384 * @param peer identifies the peer
1385 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1386 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1387 * @param amount set to the amount that was actually reserved or unreserved;
1388 * either the full requested amount or zero (no partial reservations)
1389 * @param preference current traffic preference for the given peer
1392 update_core_preference_finish (void *cls,
1393 const struct GNUNET_PeerIdentity * peer,
1394 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1395 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1396 int amount, uint64_t preference)
1398 struct PeerInfo *peer_info = cls;
1399 peer_info->info_ctx = NULL;
1400 GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1404 update_core_preference (void *cls,
1405 const struct GNUNET_SCHEDULER_TaskContext *tc)
1407 struct PeerInfo *peer = cls;
1408 uint64_t preference;
1409 unsigned int matching;
1410 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1414 matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1417 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1420 preference = 1LL << matching;
1421 peer->info_ctx = GNUNET_CORE_peer_change_preference (cfg,
1423 GNUNET_TIME_relative_get_forever(),
1424 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1427 &update_core_preference_finish,
1432 * Really add a peer to a bucket (only do assertions
1435 * @param peer GNUNET_PeerIdentity of the peer to add
1436 * @param bucket the already figured out bucket to add
1438 * @param latency the core reported latency of this peer
1439 * @param distance the transport level distance to this peer
1441 * @return the newly added PeerInfo
1443 static struct PeerInfo *
1444 add_peer(const struct GNUNET_PeerIdentity *peer,
1445 unsigned int bucket,
1446 struct GNUNET_TIME_Relative latency,
1447 unsigned int distance)
1449 struct PeerInfo *new_peer;
1450 GNUNET_assert(bucket < MAX_BUCKETS);
1451 GNUNET_assert(peer != NULL);
1452 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1453 new_peer->latency = latency;
1454 new_peer->distance = distance;
1456 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1458 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1459 k_buckets[bucket].tail,
1460 k_buckets[bucket].tail,
1462 k_buckets[bucket].peers_size++;
1464 if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1466 #if DO_UPDATE_PREFERENCE
1467 new_peer->preference_task = GNUNET_SCHEDULER_add_now(&update_core_preference, new_peer);
1475 * Given a peer and its corresponding bucket,
1476 * remove it from that bucket. Does not free
1477 * the PeerInfo struct, nor cancel messages
1478 * or free messages waiting to be sent to this
1481 * @param peer the peer to remove
1482 * @param bucket the bucket the peer belongs to
1484 static void remove_peer (struct PeerInfo *peer,
1485 unsigned int bucket)
1487 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1488 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1489 k_buckets[bucket].tail,
1491 k_buckets[bucket].peers_size--;
1493 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1499 * Removes peer from a bucket, then frees associated
1500 * resources and frees peer.
1502 * @param peer peer to be removed and freed
1503 * @param bucket which bucket this peer belongs to
1505 static void delete_peer (struct PeerInfo *peer,
1506 unsigned int bucket)
1508 struct P2PPendingMessage *pos;
1509 struct P2PPendingMessage *next;
1511 struct PeerInfo *peer_pos;
1513 peer_pos = k_buckets[bucket].head;
1514 while ((peer_pos != NULL) && (peer_pos != peer))
1515 peer_pos = peer_pos->next;
1516 if (peer_pos == NULL)
1518 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1519 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));
1521 GNUNET_assert(peer_pos != NULL);
1523 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1525 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1526 GNUNET_SCHEDULER_cancel(peer->send_task);
1527 if (peer->th != NULL)
1528 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1531 while (pos != NULL) /* Remove any pending messages for this peer */
1538 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1539 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1545 * Iterator over hash map entries.
1547 * @param cls closure
1548 * @param key current key code
1549 * @param value PeerInfo of the peer to move to new lowest bucket
1550 * @return GNUNET_YES if we should continue to
1554 static int move_lowest_bucket (void *cls,
1555 const GNUNET_HashCode * key,
1558 struct PeerInfo *peer = value;
1561 GNUNET_assert(lowest_bucket > 0);
1562 new_bucket = lowest_bucket - 1;
1563 remove_peer(peer, lowest_bucket);
1564 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1565 k_buckets[new_bucket].tail,
1566 k_buckets[new_bucket].tail,
1568 k_buckets[new_bucket].peers_size++;
1574 * The current lowest bucket is full, so change the lowest
1575 * bucket to the next lower down, and move any appropriate
1576 * entries in the current lowest bucket to the new bucket.
1578 static void enable_next_bucket()
1580 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1581 struct PeerInfo *pos;
1582 GNUNET_assert(lowest_bucket > 0);
1583 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1584 pos = k_buckets[lowest_bucket].head;
1587 fprintf(stderr, "Printing RT before new bucket\n");
1588 print_routing_table();
1590 /* Populate the array of peers which should be in the next lowest bucket */
1593 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1594 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1598 /* Remove peers from lowest bucket, insert into next lowest bucket */
1599 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1600 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1601 lowest_bucket = lowest_bucket - 1;
1603 fprintf(stderr, "Printing RT after new bucket\n");
1604 print_routing_table();
1609 * Find the closest peer in our routing table to the
1612 * @return The closest peer in our routing table to the
1613 * key, or NULL on error.
1615 static struct PeerInfo *
1616 find_closest_peer (const GNUNET_HashCode *hc)
1618 struct PeerInfo *pos;
1619 struct PeerInfo *current_closest;
1620 unsigned int lowest_distance;
1621 unsigned int temp_distance;
1625 lowest_distance = -1;
1627 if (k_buckets[lowest_bucket].peers_size == 0)
1630 current_closest = NULL;
1631 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1633 pos = k_buckets[bucket].head;
1635 while ((pos != NULL) && (count < bucket_size))
1637 temp_distance = distance(&pos->id.hashPubKey, hc);
1638 if (temp_distance <= lowest_distance)
1640 lowest_distance = temp_distance;
1641 current_closest = pos;
1647 GNUNET_assert(current_closest != NULL);
1648 return current_closest;
1653 * Function called to send a request out to another peer.
1654 * Called both for locally initiated requests and those
1655 * received from other peers.
1657 * @param msg the encapsulated message
1658 * @param peer the peer to forward the message to
1659 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1661 static void forward_message (const struct GNUNET_MessageHeader *msg,
1662 struct PeerInfo *peer,
1663 struct DHT_MessageContext *msg_ctx)
1665 struct GNUNET_DHT_P2PRouteMessage *route_message;
1666 struct P2PPendingMessage *pending;
1670 increment_stats(STAT_ROUTE_FORWARDS);
1672 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1673 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1675 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1676 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1677 psize = sizeof(struct P2PPendingMessage) + msize;
1678 pending = GNUNET_malloc(psize);
1679 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1680 pending->importance = msg_ctx->importance;
1681 pending->timeout = msg_ctx->timeout;
1682 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1683 route_message->header.size = htons(msize);
1684 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1685 route_message->options = htonl(msg_ctx->msg_options);
1686 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1687 route_message->network_size = htonl(msg_ctx->network_size);
1688 route_message->desired_replication_level = htonl(msg_ctx->replication);
1689 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1690 if (msg_ctx->bloom != NULL)
1691 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1692 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1693 memcpy(&route_message[1], msg, ntohs(msg->size));
1695 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));
1697 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1698 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1699 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1704 * Task used to send ping messages to peers so that
1705 * they don't get disconnected.
1707 * @param cls the peer to send a ping message to
1708 * @param tc context, reason, etc.
1711 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1713 struct PeerInfo *peer = cls;
1714 struct GNUNET_MessageHeader ping_message;
1715 struct DHT_MessageContext message_context;
1717 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1720 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1721 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1723 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1725 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1727 forward_message(&ping_message, peer, &message_context);
1728 peer->ping_task = GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1732 * Schedule PING messages for the top X peers in each
1733 * bucket of the routing table (so core won't disconnect them!)
1735 void schedule_ping_messages()
1737 unsigned int bucket;
1739 struct PeerInfo *pos;
1740 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1742 pos = k_buckets[bucket].head;
1746 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1747 GNUNET_SCHEDULER_add_now(&periodic_ping_task, pos);
1748 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1750 GNUNET_SCHEDULER_cancel(pos->ping_task);
1751 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1761 * Attempt to add a peer to our k-buckets.
1763 * @param peer the peer identity of the peer being added
1764 * @param bucket the bucket that we want this peer to go in
1765 * @param latency transport latency of this peer
1766 * @param distance transport distance to this peer
1768 * @return NULL if the peer was not added,
1769 * pointer to PeerInfo for new peer otherwise
1771 static struct PeerInfo *
1772 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1773 unsigned int bucket,
1774 struct GNUNET_TIME_Relative latency,
1775 unsigned int distance)
1778 struct PeerInfo *new_peer;
1780 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1783 peer_bucket = find_current_bucket(&peer->hashPubKey);
1785 GNUNET_assert(peer_bucket >= lowest_bucket);
1786 new_peer = add_peer(peer, peer_bucket, latency, distance);
1788 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1789 enable_next_bucket();
1791 schedule_ping_messages();
1798 * Task run to check for messages that need to be sent to a client.
1800 * @param client a ClientList, containing the client and any messages to be sent to it
1803 process_pending_messages (struct ClientList *client)
1805 if (client->pending_head == NULL)
1807 if (client->transmit_handle != NULL)
1810 client->transmit_handle =
1811 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1812 ntohs (client->pending_head->msg->
1814 GNUNET_TIME_UNIT_FOREVER_REL,
1815 &send_generic_reply, client);
1819 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1820 * request. A ClientList is passed as closure, take the head of the list
1821 * and copy it into buf, which has the result of sending the message to the
1824 * @param cls closure to this call
1825 * @param size maximum number of bytes available to send
1826 * @param buf where to copy the actual message to
1828 * @return the number of bytes actually copied, 0 indicates failure
1831 send_generic_reply (void *cls, size_t size, void *buf)
1833 struct ClientList *client = cls;
1835 struct PendingMessage *reply;
1839 client->transmit_handle = NULL;
1842 /* client disconnected */
1846 while ( (NULL != (reply = client->pending_head)) &&
1847 (size >= off + (msize = ntohs (reply->msg->size))))
1849 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1850 client->pending_tail,
1852 memcpy (&cbuf[off], reply->msg, msize);
1853 GNUNET_free (reply);
1856 process_pending_messages (client);
1858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1859 "Transmitted %u bytes of replies to client\n",
1860 (unsigned int) off);
1867 * Add a PendingMessage to the clients list of messages to be sent
1869 * @param client the active client to send the message to
1870 * @param pending_message the actual message to send
1873 add_pending_message (struct ClientList *client,
1874 struct PendingMessage *pending_message)
1876 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1877 client->pending_tail,
1878 client->pending_tail,
1880 process_pending_messages (client);
1885 * Called when a reply needs to be sent to a client, as
1886 * a result it found to a GET or FIND PEER request.
1888 * @param client the client to send the reply to
1889 * @param message the encapsulated message to send
1890 * @param uid the unique identifier of this request
1893 send_reply_to_client (struct ClientList *client,
1894 const struct GNUNET_MessageHeader *message,
1895 unsigned long long uid,
1896 const GNUNET_HashCode *key)
1898 struct GNUNET_DHT_RouteResultMessage *reply;
1899 struct PendingMessage *pending_message;
1903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1904 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1906 msize = ntohs (message->size);
1907 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1908 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1910 GNUNET_break_op (0);
1913 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1914 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1915 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1916 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1917 reply->header.size = htons (tsize);
1918 reply->put_path_length = htons(0); /* FIXME: implement */
1919 reply->get_path_length = htons(0); /* FIXME: implement */
1920 reply->unique_id = GNUNET_htonll (uid);
1922 memcpy (&reply[1], message, msize);
1923 add_pending_message (client, pending_message);
1927 * Consider whether or not we would like to have this peer added to
1928 * our routing table. Check whether bucket for this peer is full,
1929 * if so return negative; if not return positive. Since peers are
1930 * only added on CORE level connect, this doesn't actually add the
1931 * peer to the routing table.
1933 * @param peer the peer we are considering adding
1935 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1938 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1942 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1943 return GNUNET_NO; /* We already know this peer (are connected even!) */
1944 bucket = find_current_bucket(&peer->hashPubKey);
1946 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1953 * Main function that handles whether or not to route a result
1954 * message to other peers, or to send to our local client.
1956 * @param msg the result message to be routed
1957 * @param message_context context of the message we are routing
1959 * @return the number of peers the message was routed to,
1960 * GNUNET_SYSERR on failure
1962 static int route_result_message(struct GNUNET_MessageHeader *msg,
1963 struct DHT_MessageContext *message_context)
1965 struct GNUNET_PeerIdentity new_peer;
1966 struct DHTQueryRecord *record;
1967 struct DHTRouteSource *pos;
1968 struct PeerInfo *peer_info;
1969 const struct GNUNET_MessageHeader *hello_msg;
1971 increment_stats(STAT_RESULTS);
1973 * If a find peer result message is received and contains a valid
1974 * HELLO for another peer, offer it to the transport service.
1976 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1978 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1981 hello_msg = &msg[1];
1982 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1984 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1988 else /* We have a valid hello, and peer id stored in new_peer */
1990 find_peer_context.count++;
1991 increment_stats(STAT_FIND_PEER_REPLY);
1992 if (GNUNET_YES == consider_peer(&new_peer))
1994 increment_stats(STAT_HELLOS_PROVIDED);
1995 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1996 GNUNET_CORE_peer_request_connect(cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
2001 if (malicious_dropper == GNUNET_YES)
2004 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
2006 if (record == NULL) /* No record of this message! */
2009 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2010 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
2011 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2013 #if DEBUG_DHT_ROUTING
2014 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2016 dhtlog_handle->insert_route (NULL,
2017 message_context->unique_id,
2019 message_context->hop_count,
2022 &message_context->key,
2023 message_context->peer, NULL);
2026 if (message_context->bloom != NULL)
2028 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2029 message_context->bloom = NULL;
2037 #if STRICT_FORWARDING
2038 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2040 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2042 increment_stats("# find peer responses NOT forwarded (bloom match)");
2047 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2051 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2054 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2055 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2056 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2058 #if DEBUG_DHT_ROUTING
2059 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2061 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2062 message_context->hop_count,
2063 GNUNET_YES, &my_identity, &message_context->key,
2064 message_context->peer, NULL);
2067 increment_stats(STAT_RESULTS_TO_CLIENT);
2068 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2069 increment_stats(STAT_GET_REPLY);
2071 send_reply_to_client(pos->client, msg,
2072 message_context->unique_id,
2073 &message_context->key);
2075 else /* Send to peer */
2077 peer_info = find_peer_by_id(&pos->source);
2078 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2084 if (message_context->bloom == NULL)
2085 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2086 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2087 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2090 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2091 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2092 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2094 #if DEBUG_DHT_ROUTING
2095 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2097 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2099 message_context->hop_count,
2100 GNUNET_NO, &my_identity, &message_context->key,
2101 message_context->peer, &pos->source);
2104 forward_result_message(msg, peer_info, message_context);
2109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2110 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2111 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2117 if (message_context->bloom != NULL)
2118 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2123 * Iterator for local get request results,
2125 * @param cls closure for iterator, a DatacacheGetContext
2126 * @param exp when does this value expire?
2127 * @param key the key this data is stored under
2128 * @param size the size of the data identified by key
2129 * @param data the actual data
2130 * @param type the type of the data
2132 * @return GNUNET_OK to continue iteration, anything else
2133 * to stop iteration.
2136 datacache_get_iterator (void *cls,
2137 struct GNUNET_TIME_Absolute exp,
2138 const GNUNET_HashCode * key,
2139 size_t size, const char *data,
2140 enum GNUNET_BLOCK_Type type)
2142 struct DHT_MessageContext *msg_ctx = cls;
2143 struct DHT_MessageContext *new_msg_ctx;
2144 struct GNUNET_DHT_GetResultMessage *get_result;
2145 enum GNUNET_BLOCK_EvaluationResult eval;
2148 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2149 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2151 eval = GNUNET_BLOCK_evaluate (block_context,
2155 msg_ctx->reply_bf_mutator,
2157 msg_ctx->xquery_size,
2162 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2163 msg_ctx->do_forward = GNUNET_NO;
2164 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2165 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2166 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2168 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2169 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2170 get_result->header.size =
2171 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2172 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2173 get_result->type = htons (type);
2174 memcpy (&get_result[1], data, size);
2175 new_msg_ctx->peer = &my_identity;
2176 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2177 new_msg_ctx->hop_count = 0;
2178 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2179 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2180 increment_stats(STAT_GET_RESPONSE_START);
2181 route_result_message(&get_result->header, new_msg_ctx);
2182 GNUNET_free(new_msg_ctx);
2183 GNUNET_free (get_result);
2185 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2187 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2188 "`%s:%s': Duplicate block error\n", my_short_id, "DHT");
2191 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2194 "`%s:%s': Invalid request error\n", my_short_id, "DHT");
2197 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2200 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2204 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2205 GNUNET_break_op (0);
2206 msg_ctx->do_forward = GNUNET_NO;
2208 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2211 "`%s:%s': Unsupported block type (%u) in response!\n", my_short_id, "DHT", type);
2213 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2221 * Main function that handles whether or not to route a message to other
2224 * @param msg the message to be routed
2225 * @param message_context the context containing all pertinent information about the message
2228 route_message(const struct GNUNET_MessageHeader *msg,
2229 struct DHT_MessageContext *message_context);
2233 * Server handler for all dht get requests, look for data,
2234 * if found, send response either to clients or other peers.
2236 * @param msg the actual get message
2237 * @param message_context struct containing pertinent information about the get request
2239 * @return number of items found for GET request
2242 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2243 struct DHT_MessageContext *message_context)
2245 const struct GNUNET_DHT_GetMessage *get_msg;
2248 unsigned int results;
2250 enum GNUNET_BLOCK_Type type;
2252 msize = ntohs (msg->size);
2253 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2258 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2259 bf_size = ntohs (get_msg->bf_size);
2260 message_context->xquery_size = ntohs (get_msg->xquery_size);
2261 message_context->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2262 if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + message_context->xquery_size)
2267 end = (const char*) &get_msg[1];
2268 if (message_context->xquery_size == 0)
2270 message_context->xquery = NULL;
2274 message_context->xquery = (const void*) end;
2275 end += message_context->xquery_size;
2279 message_context->reply_bf = NULL;
2283 message_context->reply_bf = GNUNET_CONTAINER_bloomfilter_init (end,
2285 GNUNET_DHT_GET_BLOOMFILTER_K);
2287 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2289 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2290 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2294 GNUNET_h2s (&message_context->key),
2295 message_context->unique_id);
2297 increment_stats(STAT_GETS);
2300 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2302 GNUNET_CONTAINER_bloomfilter_free (message_context->reply_bf);
2306 message_context->do_forward = GNUNET_YES;
2307 if (datacache != NULL)
2309 = GNUNET_DATACACHE_get (datacache,
2310 &message_context->key, type,
2311 &datacache_get_iterator,
2314 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2315 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2316 results, "GET", message_context->unique_id);
2320 #if DEBUG_DHT_ROUTING
2321 if ((debug_routes) && (dhtlog_handle != NULL))
2323 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2324 message_context->hop_count, GNUNET_YES, &my_identity,
2325 &message_context->key);
2328 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2330 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2331 message_context->hop_count, GNUNET_YES,
2332 &my_identity, &message_context->key, message_context->peer,
2339 /* check query valid */
2340 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID
2341 == GNUNET_BLOCK_evaluate (block_context,
2343 &message_context->key,
2344 &message_context->reply_bf,
2345 message_context->reply_bf_mutator,
2346 message_context->xquery,
2347 message_context->xquery_size,
2350 GNUNET_break_op (0);
2351 message_context->do_forward = GNUNET_NO;
2355 if (message_context->hop_count == 0) /* Locally initiated request */
2357 #if DEBUG_DHT_ROUTING
2358 if ((debug_routes) && (dhtlog_handle != NULL))
2360 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2361 message_context->hop_count, GNUNET_NO, &my_identity,
2362 &message_context->key);
2366 if (message_context->do_forward == GNUNET_YES)
2367 route_message (msg, message_context);
2368 GNUNET_CONTAINER_bloomfilter_free (message_context->reply_bf);
2373 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2375 GNUNET_HashCode *key = cls;
2377 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, NULL));
2382 * Server handler for initiating local dht find peer requests
2384 * @param find_msg the actual find peer message
2385 * @param message_context struct containing pertinent information about the request
2389 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2390 struct DHT_MessageContext *message_context)
2392 struct GNUNET_MessageHeader *find_peer_result;
2393 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2394 struct DHT_MessageContext *new_msg_ctx;
2395 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2398 GNUNET_HashCode *recent_hash;
2399 struct GNUNET_MessageHeader *other_hello;
2400 size_t other_hello_size;
2401 struct GNUNET_PeerIdentity peer_id;
2403 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2404 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2405 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2408 other_hello_size = 0;
2409 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2411 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2412 other_hello = GNUNET_malloc(other_hello_size);
2413 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2414 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)))
2416 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2417 GNUNET_free(other_hello);
2420 #if FIND_PEER_WITH_HELLO
2421 if (GNUNET_YES == consider_peer(&peer_id))
2423 increment_stats(STAT_HELLOS_PROVIDED);
2424 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2425 GNUNET_CORE_peer_request_connect(cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2426 route_message (find_msg, message_context);
2427 GNUNET_free (other_hello);
2430 else /* We don't want this peer! */
2432 route_message (find_msg, message_context);
2439 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2440 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2441 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&message_context->key),
2442 ntohs (find_msg->size),
2443 sizeof (struct GNUNET_MessageHeader));
2445 if (my_hello == NULL)
2448 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2449 "`%s': Our HELLO is null, can't return.\n",
2452 GNUNET_free_non_null (other_hello);
2453 route_message (find_msg, message_context);
2457 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2458 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2460 increment_stats(STAT_BLOOM_FIND_PEER);
2461 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2462 GNUNET_free_non_null(other_hello);
2463 route_message (find_msg, message_context);
2464 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2466 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2468 #if RESTRICT_FIND_PEER
2471 * Ignore any find peer requests from a peer we have seen very recently.
2473 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! */
2475 increment_stats("# dht find peer requests ignored (recently seen!)");
2476 GNUNET_free_non_null(other_hello);
2481 * Use this check to only allow the peer to respond to find peer requests if
2482 * it would be beneficial to have the requesting peer in this peers routing
2483 * table. Can be used to thwart peers flooding the network with find peer
2484 * requests that we don't care about. However, if a new peer is joining
2485 * the network and has no other peers this is a problem (assume all buckets
2486 * full, no one will respond!).
2488 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2489 if (GNUNET_NO == consider_peer(&peer_id))
2491 increment_stats("# dht find peer requests ignored (do not need!)");
2492 GNUNET_free_non_null(other_hello);
2493 route_message (find_msg, message_context);
2498 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2499 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2500 if (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2501 &message_context->key, NULL,
2502 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2504 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding recent remove task for key `%s`!\n", GNUNET_h2s(&message_context->key));
2505 /* Only add a task if there wasn't one for this key already! */
2506 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30),
2507 &remove_recent_find_peer, recent_hash);
2511 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received duplicate find peer request too soon!\n");
2514 /* Simplistic find_peer functionality, always return our hello */
2515 hello_size = ntohs(my_hello->size);
2516 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2518 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2520 GNUNET_break_op (0);
2521 GNUNET_free_non_null(other_hello);
2525 find_peer_result = GNUNET_malloc (tsize);
2526 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2527 find_peer_result->size = htons (tsize);
2528 memcpy (&find_peer_result[1], my_hello, hello_size);
2530 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2531 "`%s': Sending hello size %d to requesting peer.\n",
2534 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2535 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2536 new_msg_ctx->peer = &my_identity;
2537 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2538 new_msg_ctx->hop_count = 0;
2539 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2540 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2541 increment_stats(STAT_FIND_PEER_ANSWER);
2542 route_result_message(find_peer_result, new_msg_ctx);
2543 GNUNET_free(new_msg_ctx);
2544 #if DEBUG_DHT_ROUTING
2545 if ((debug_routes) && (dhtlog_handle != NULL))
2547 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2548 message_context->hop_count, GNUNET_YES, &my_identity,
2549 &message_context->key);
2552 GNUNET_free_non_null(other_hello);
2553 GNUNET_free(find_peer_result);
2554 route_message (find_msg, message_context);
2558 * Task used to republish data.
2559 * Forward declaration; function call loop.
2561 * @param cls closure (a struct RepublishContext)
2562 * @param tc runtime context for this task
2565 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2568 * Server handler for initiating local dht put requests
2570 * @param msg the actual put message
2571 * @param message_context struct containing pertinent information about the request
2574 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2575 struct DHT_MessageContext *message_context)
2577 const struct GNUNET_DHT_PutMessage *put_msg;
2578 enum GNUNET_BLOCK_Type put_type;
2581 struct RepublishContext *put_context;
2582 GNUNET_HashCode key;
2584 GNUNET_assert (ntohs (msg->size) >=
2585 sizeof (struct GNUNET_DHT_PutMessage));
2588 put_msg = (const struct GNUNET_DHT_PutMessage *)msg;
2589 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2591 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2594 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2595 ret = GNUNET_BLOCK_get_key (block_context,
2600 if (GNUNET_NO == ret)
2603 GNUNET_break_op (0);
2606 if ( (GNUNET_YES == ret) &&
2608 &message_context->key,
2609 sizeof (GNUNET_HashCode))) )
2611 /* invalid wrapper: key mismatch! */
2612 GNUNET_break_op (0);
2615 /* ret == GNUNET_SYSERR means that there is no known relationship between
2616 data and the key, so we cannot check it */
2618 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2619 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2620 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
2622 #if DEBUG_DHT_ROUTING
2623 if (message_context->hop_count == 0) /* Locally initiated request */
2625 if ((debug_routes) && (dhtlog_handle != NULL))
2627 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2628 message_context->hop_count, GNUNET_NO, &my_identity,
2629 &message_context->key);
2634 if (message_context->closest != GNUNET_YES)
2636 route_message (msg, message_context);
2641 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2642 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2643 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
2646 #if DEBUG_DHT_ROUTING
2647 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2649 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2650 message_context->hop_count, GNUNET_YES,
2651 &my_identity, &message_context->key, message_context->peer,
2655 if ((debug_routes) && (dhtlog_handle != NULL))
2657 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2658 message_context->hop_count, GNUNET_YES, &my_identity,
2659 &message_context->key);
2663 increment_stats(STAT_PUTS_INSERTED);
2664 if (datacache != NULL)
2666 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2667 (char *) &put_msg[1], put_type,
2668 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2670 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2672 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2673 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2674 put_context->type = put_type;
2675 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content, put_context);
2679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2680 "`%s:%s': %s request received, but have no datacache!\n",
2681 my_short_id, "DHT", "PUT");
2683 if (stop_on_closest == GNUNET_NO)
2684 route_message (msg, message_context);
2688 * Estimate the diameter of the network based
2689 * on how many buckets are currently in use.
2690 * Concept here is that the diameter of the network
2691 * is roughly the distance a message must travel in
2692 * order to reach its intended destination. Since
2693 * at each hop we expect to get one bit closer, and
2694 * we have one bit per bucket, the number of buckets
2695 * in use should be the largest number of hops for
2696 * a successful message. (of course, this assumes we
2697 * know all peers in the network!)
2699 * @return ballpark diameter figure
2701 static unsigned int estimate_diameter()
2703 return MAX_BUCKETS - lowest_bucket;
2707 * To how many peers should we (on average)
2708 * forward the request to obtain the desired
2709 * target_replication count (on average).
2711 * Always 0, 1 or 2 (don't send, send once, split)
2714 get_forward_count (unsigned int hop_count, size_t target_replication)
2717 double target_count;
2718 double random_probability;
2720 uint32_t random_value;
2722 unsigned int target_value;
2723 unsigned int diameter;
2726 * If we are behaving in strict kademlia mode, send multiple initial requests,
2727 * but then only send to 1 or 0 peers based strictly on the number of hops.
2729 if (strict_kademlia == GNUNET_YES)
2732 return DHT_KADEMLIA_REPLICATION;
2733 else if (hop_count < max_hops)
2739 /* FIXME: the smaller we think the network is the more lenient we should be for
2740 * routing right? The estimation below only works if we think we have reasonably
2741 * full routing tables, which for our RR topologies may not be the case!
2743 diameter = estimate_diameter ();
2744 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size) && (use_max_hops == GNUNET_NO))
2747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2748 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2749 "DHT", estimate_diameter(), lowest_bucket);
2753 else if (hop_count > max_hops)
2756 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2757 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2764 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2765 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2766 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2767 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2768 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2769 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2770 RAND_MAX)) / RAND_MAX;
2771 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2774 //while (target_value < target_count)
2775 if (target_value < target_count)
2776 target_value++; /* target_value is ALWAYS 1 after this "loop", right? Because target_count is always > 0, right? Or does it become 0.00000... at some point because the hop count is so high? */
2779 //if ((target_count + 1 - (double)target_value) > random_probability)
2780 if ((target_count) > random_probability)
2784 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2785 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "replication %u, at hop %d, will split with probability %f\n", target_replication, hop_count, target_replication / (double)((target_replication * (hop_count + 1) + diameter) + 1));
2787 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2788 if (random_value < target_replication)
2791 return target_value;
2795 * Check whether my identity is closer than any known peers.
2796 * If a non-null bloomfilter is given, check if this is the closest
2797 * peer that hasn't already been routed to.
2799 * @param target hash code to check closeness to
2800 * @param bloom bloomfilter, exclude these entries from the decision
2802 * Return GNUNET_YES if node location is closest, GNUNET_NO
2806 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2812 struct PeerInfo *pos;
2813 unsigned int my_distance;
2815 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2818 bucket_num = find_current_bucket(target);
2820 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2821 my_distance = distance(&my_identity.hashPubKey, target);
2822 pos = k_buckets[bucket_num].head;
2824 while ((pos != NULL) && (count < bucket_size))
2826 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2829 continue; /* Skip already checked entries */
2832 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2833 if (other_bits > bits)
2835 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2837 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2839 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2845 /* No peers closer, we are the closest! */
2851 * Return this peers adjusted value based on the convergence
2852 * function chosen. This is the key function for randomized
2853 * routing decisions.
2855 * @param target the key of the request
2856 * @param peer the peer we would like the value of
2857 * @param hops number of hops this message has already traveled
2859 * @return bit distance from target to peer raised to an exponent
2860 * adjusted based on the current routing convergence algorithm
2863 static unsigned long long
2864 converge_distance (const GNUNET_HashCode *target,
2865 struct PeerInfo *peer,
2868 unsigned long long ret;
2869 unsigned int other_matching_bits;
2870 double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
2871 double temp_modifier;
2877 curr_max_hops = max_hops;
2879 curr_max_hops = (estimate_diameter() + 1) * 2;
2881 if (converge_modifier > 0)
2882 temp_modifier = converge_modifier * base_converge_modifier;
2885 temp_modifier = base_converge_modifier;
2886 base_converge_modifier = 0.0;
2889 GNUNET_assert(temp_modifier > 0);
2891 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2893 switch (converge_option)
2895 case DHT_CONVERGE_RANDOM:
2896 return 1; /* Always return 1, choose equally among all peers */
2897 case DHT_CONVERGE_LINEAR:
2898 calc_value = hops * curr_max_hops * temp_modifier;
2900 case DHT_CONVERGE_SQUARE:
2902 * Simple square based curve.
2904 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * temp_modifier));
2906 case DHT_CONVERGE_EXPONENTIAL:
2908 * Simple exponential curve.
2910 if (base_converge_modifier > 0)
2911 calc_value = (temp_modifier * hops * hops) / curr_max_hops;
2913 calc_value = (hops * hops) / curr_max_hops;
2915 case DHT_CONVERGE_BINARY:
2917 * If below the cutoff, route randomly (return 1),
2918 * If above the cutoff, return the maximum possible
2919 * value first (always route to closest, because
2923 if (hops > converge_modifier) /* Past cutoff */
2932 /* Take the log (base e) of the number of bits matching the other peer */
2933 exponent = log(other_matching_bits);
2935 /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
2936 if (exponent * calc_value >= 44.361419555836498)
2939 /* Clear errno and all math exceptions */
2941 feclearexcept(FE_ALL_EXCEPT);
2942 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2943 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2946 if (0 != fetestexcept(FE_OVERFLOW))
2947 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2948 if (0 != fetestexcept(FE_INVALID))
2949 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2950 if (0 != fetestexcept(FE_UNDERFLOW))
2951 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2959 * Comparison function for two struct PeerInfo's
2960 * which have already had their matching bits to
2961 * some target calculated.
2963 * @param p1 a pointer pointer to a struct PeerInfo
2964 * @param p2 a pointer pointer to a struct PeerInfo
2966 * @return 0 if equidistant to target,
2967 * -1 if p1 is closer,
2971 compare_peers (const void *p1, const void *p2)
2973 struct PeerInfo **first = (struct PeerInfo **)p1;
2974 struct PeerInfo **second = (struct PeerInfo **)p2;
2976 if ((*first)->matching_bits > (*second)->matching_bits)
2978 if ((*first)->matching_bits < (*second)->matching_bits)
2986 * Select a peer from the routing table that would be a good routing
2987 * destination for sending a message for "target". The resulting peer
2988 * must not be in the set of blocked peers.<p>
2990 * Note that we should not ALWAYS select the closest peer to the
2991 * target, peers further away from the target should be chosen with
2992 * exponentially declining probability.
2994 * @param target the key we are selecting a peer to route to
2995 * @param bloom a bloomfilter containing entries this request has seen already
2997 * @return Peer to route to, or NULL on error
2999 static struct PeerInfo *
3000 select_peer (const GNUNET_HashCode * target,
3001 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3006 unsigned int offset;
3007 unsigned int my_matching_bits;
3009 struct PeerInfo *pos;
3010 struct PeerInfo *sorted_closest[bucket_size];
3011 unsigned long long temp_converge_distance;
3012 unsigned long long total_distance;
3013 unsigned long long selected;
3015 unsigned long long stats_total_distance;
3019 unsigned int distance;
3020 unsigned int largest_distance;
3021 struct PeerInfo *chosen;
3023 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
3026 if (strict_kademlia == GNUNET_YES)
3028 largest_distance = 0;
3030 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3032 pos = k_buckets[bc].head;
3034 while ((pos != NULL) && (count < bucket_size))
3036 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3037 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3039 distance = inverse_distance (target, &pos->id.hashPubKey);
3040 if (distance > largest_distance)
3043 largest_distance = distance;
3051 if ((largest_distance > 0) && (chosen != NULL))
3053 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
3064 /* Three steps: order peers in closest bucket (most matching bits).
3065 * Then go over all LOWER buckets (matching same bits we do)
3066 * Then go over all HIGHER buckets (matching less then we do)
3069 closest_bucket = find_current_bucket(target);
3070 GNUNET_assert(closest_bucket >= lowest_bucket);
3071 pos = k_buckets[closest_bucket].head;
3073 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3074 memset(sorted_closest, 0, sizeof(sorted_closest));
3075 /* Put any peers in the closest bucket in the sorting array */
3076 while ((pos != NULL) && (count < bucket_size))
3078 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3082 continue; /* Ignore bloomfiltered peers */
3084 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
3085 sorted_closest[offset] = pos;
3091 /* Sort the peers in descending order */
3092 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
3094 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3095 for (i = 0; i < offset; i++)
3097 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3098 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3099 break; /* Ignore bloomfiltered peers */
3100 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3101 total_distance += temp_converge_distance;
3103 break; /* overflow case */
3106 /* Now handle peers in lower buckets (matches same # of bits as target) */
3107 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3109 pos = k_buckets[bc].head;
3111 while ((pos != NULL) && (count < bucket_size))
3113 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3117 continue; /* Ignore bloomfiltered peers */
3119 temp_converge_distance = converge_distance(target, pos, hops);
3120 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3121 total_distance += temp_converge_distance;
3123 break; /* overflow case */
3129 /* Now handle all the further away peers */
3130 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3132 pos = k_buckets[bc].head;
3134 while ((pos != NULL) && (count < bucket_size))
3136 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3140 continue; /* Ignore bloomfiltered peers */
3142 temp_converge_distance = converge_distance(target, pos, hops);
3143 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3144 total_distance += temp_converge_distance;
3146 break; /* overflow case */
3152 if (total_distance == 0) /* No peers to select from! */
3154 increment_stats("# select_peer, total_distance == 0");
3158 #if DEBUG_DHT_ROUTING > 1
3161 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3162 stats_total_distance = 0;
3163 for (i = 0; i < offset; i++)
3165 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3166 break; /* Ignore bloomfiltered peers */
3167 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3168 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3169 stats_total_distance += temp_converge_distance;
3171 break; /* overflow case */
3172 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);
3175 /* Now handle peers in lower buckets (matches same # of bits as target) */
3176 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3178 pos = k_buckets[bc].head;
3180 while ((pos != NULL) && (count < bucket_size))
3182 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3186 continue; /* Ignore bloomfiltered peers */
3188 temp_converge_distance = converge_distance(target, pos, hops);
3189 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3190 stats_total_distance += temp_converge_distance;
3192 break; /* overflow case */
3193 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);
3199 /* Now handle all the further away peers */
3200 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3202 pos = k_buckets[bc].head;
3204 while ((pos != NULL) && (count < bucket_size))
3206 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3210 continue; /* Ignore bloomfiltered peers */
3212 temp_converge_distance = converge_distance(target, pos, hops);
3213 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3214 stats_total_distance += temp_converge_distance;
3216 break; /* overflow case */
3217 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);
3222 /* END PRINT STATS */
3225 /* Now actually choose a peer */
3226 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3228 /* Go over closest sorted peers. */
3229 for (i = 0; i < offset; i++)
3231 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3232 break; /* Ignore bloomfiltered peers */
3233 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3234 if (temp_converge_distance >= selected)
3235 return sorted_closest[i];
3237 selected -= temp_converge_distance;
3240 /* Now handle peers in lower buckets (matches same # of bits as target) */
3241 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3243 pos = k_buckets[bc].head;
3245 while ((pos != NULL) && (count < bucket_size))
3247 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3251 continue; /* Ignore bloomfiltered peers */
3253 temp_converge_distance = converge_distance(target, pos, hops);
3254 if (temp_converge_distance >= selected)
3257 selected -= temp_converge_distance;
3263 /* Now handle all the further away peers */
3264 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3266 pos = k_buckets[bc].head;
3268 while ((pos != NULL) && (count < bucket_size))
3270 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3274 continue; /* Ignore bloomfiltered peers */
3276 temp_converge_distance = converge_distance(target, pos, hops);
3277 if (temp_converge_distance >= selected)
3280 selected -= temp_converge_distance;
3286 increment_stats("# failed to select peer");
3292 * Task used to remove recent entries, either
3293 * after timeout, when full, or on shutdown.
3295 * @param cls the entry to remove
3296 * @param tc context, reason, etc.
3299 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3301 struct RecentRequest *req = cls;
3302 static GNUNET_HashCode hash;
3304 GNUNET_assert(req != NULL);
3305 hash_from_uid(req->uid, &hash);
3306 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3307 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3308 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3312 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3314 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3315 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3322 * Task used to remove forwarding entries, either
3323 * after timeout, when full, or on shutdown.
3325 * @param cls the entry to remove
3326 * @param tc context, reason, etc.
3329 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3331 struct DHTRouteSource *source_info = cls;
3332 struct DHTQueryRecord *record;
3333 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3334 record = source_info->record;
3335 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3337 if (record->head == NULL) /* No more entries in DLL */
3339 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3340 GNUNET_free(record);
3342 if (source_info->find_peers_responded != NULL)
3343 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3344 GNUNET_free(source_info);
3348 * Remember this routing request so that if a reply is
3349 * received we can either forward it to the correct peer
3350 * or return the result locally.
3352 * @param msg_ctx Context of the route request
3354 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3356 static int cache_response(struct DHT_MessageContext *msg_ctx)
3358 struct DHTQueryRecord *record;
3359 struct DHTRouteSource *source_info;
3360 struct DHTRouteSource *pos;
3361 struct GNUNET_TIME_Absolute now;
3362 unsigned int current_size;
3364 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3365 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3367 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3368 GNUNET_assert(source_info != NULL);
3369 record = source_info->record;
3370 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3371 if (record->head == NULL) /* No more entries in DLL */
3373 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3374 GNUNET_free(record);
3376 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3377 GNUNET_SCHEDULER_cancel(source_info->delete_task);
3378 if (source_info->find_peers_responded != NULL)
3379 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3380 GNUNET_free(source_info);
3381 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3383 now = GNUNET_TIME_absolute_get();
3384 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3385 if (record != NULL) /* Already know this request! */
3390 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3391 break; /* Already have this peer in reply list! */
3394 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3396 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.abs_value);
3402 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3403 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3404 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3407 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3408 source_info->record = record;
3409 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3410 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3411 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3412 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3413 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3415 source_info->client = msg_ctx->client;
3416 now = GNUNET_TIME_absolute_get_forever();
3418 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.abs_value);
3420 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3421 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3422 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3429 * Main function that handles whether or not to route a message to other
3432 * @param msg the message to be routed
3433 * @param message_context the context containing all pertinent information about the message
3436 route_message(const struct GNUNET_MessageHeader *msg,
3437 struct DHT_MessageContext *message_context)
3440 struct PeerInfo *selected;
3441 #if DEBUG_DHT_ROUTING > 1
3442 struct PeerInfo *nearest;
3444 unsigned int forward_count;
3445 struct RecentRequest *recent_req;
3446 GNUNET_HashCode unique_hash;
3447 char *stat_forward_count;
3448 char *temp_stat_str;
3449 #if DEBUG_DHT_ROUTING
3453 if (malicious_dropper == GNUNET_YES)
3455 #if DEBUG_DHT_ROUTING
3456 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3458 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3459 message_context->hop_count, GNUNET_SYSERR,
3460 &my_identity, &message_context->key, message_context->peer,
3464 if (message_context->bloom != NULL)
3465 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3469 increment_stats(STAT_ROUTES);
3470 /* Semantics of this call means we find whether we are the closest peer out of those already
3471 * routed to on this messages path.
3473 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3474 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3475 increment_stats(stat_forward_count);
3476 GNUNET_free(stat_forward_count);
3477 if (message_context->bloom == NULL)
3478 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3480 if ((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3484 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3485 * any closer peers (which is being checked for below). Since we are doing recursive
3486 * routing we have no choice but to stop forwarding in this case. This means that at
3487 * any given step the request may NOT be forwarded to alpha peers (because routes will
3488 * stop and the parallel route will not be aware of it). Of course, assuming that we
3489 * have fulfilled the Kademlia requirements for routing table fullness this will never
3490 * ever ever be a problem.
3492 * However, is this fair?
3494 * Since we use these requests to build our routing tables (and we build them in the
3495 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3496 * routing tables still get constructed.
3498 if ((GNUNET_YES == strict_kademlia) && (message_context->closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3501 #if DEBUG_DHT_ROUTING
3502 if (forward_count == 0)
3503 ret = GNUNET_SYSERR;
3507 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3509 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3510 message_context->hop_count, ret,
3511 &my_identity, &message_context->key, message_context->peer,
3517 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3518 hash_from_uid (message_context->unique_id, &unique_hash);
3519 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3521 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3522 GNUNET_assert(recent_req != NULL);
3523 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3524 increment_stats(STAT_DUPLICATE_UID);
3527 increment_stats(STAT_RECENT_SEEN);
3528 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3533 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3534 recent_req->uid = message_context->unique_id;
3535 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3536 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3537 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().abs_value);
3538 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3539 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3542 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3544 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3545 GNUNET_assert(recent_req != NULL);
3546 GNUNET_SCHEDULER_cancel(recent_req->remove_task);
3547 GNUNET_SCHEDULER_add_now(&remove_recent, recent_req);
3550 for (i = 0; i < forward_count; i++)
3552 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3554 if (selected != NULL)
3556 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
3557 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
3559 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
3560 if (temp_stat_str != NULL)
3562 increment_stats(temp_stat_str);
3563 GNUNET_free(temp_stat_str);
3565 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3566 #if DEBUG_DHT_ROUTING > 1
3567 nearest = find_closest_peer(&message_context->key);
3568 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3569 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3570 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3571 "DHT", GNUNET_h2s (&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));
3572 GNUNET_free(nearest_buf);
3574 #if DEBUG_DHT_ROUTING
3575 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3577 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3578 message_context->hop_count, GNUNET_NO,
3579 &my_identity, &message_context->key, message_context->peer,
3583 forward_message(msg, selected, message_context);
3587 if (message_context->bloom != NULL)
3589 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3590 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3597 * Main function that handles whether or not to route a message to other
3600 * @param msg the message to be routed
3601 * @param message_context the context containing all pertinent information about the message
3604 demultiplex_message(const struct GNUNET_MessageHeader *msg,
3605 struct DHT_MessageContext *message_context)
3607 message_context->closest = am_closest_peer(&message_context->key, NULL);
3608 switch (ntohs(msg->type))
3610 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3611 cache_response (message_context);
3612 handle_dht_get (msg, message_context);
3614 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3615 increment_stats(STAT_PUTS);
3616 handle_dht_put (msg, message_context);
3618 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3619 increment_stats(STAT_FIND_PEER);
3620 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3622 cache_response (message_context);
3623 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3624 handle_dht_find_peer (msg, message_context);
3627 route_message (msg, message_context);
3628 #if DEBUG_DHT_ROUTING
3629 if (message_context->hop_count == 0) /* Locally initiated request */
3631 if ((debug_routes) && (dhtlog_handle != NULL))
3633 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3634 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3635 message_context->hop_count, GNUNET_NO, &my_identity,
3636 &message_context->key);
3642 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3643 "`%s': Message type (%d) not handled, forwarding anyway!\n", "DHT", ntohs(msg->type));
3644 route_message (msg, message_context);
3652 * Iterator for local get request results,
3654 * @param cls closure for iterator, NULL
3655 * @param exp when does this value expire?
3656 * @param key the key this data is stored under
3657 * @param size the size of the data identified by key
3658 * @param data the actual data
3659 * @param type the type of the data
3661 * @return GNUNET_OK to continue iteration, anything else
3662 * to stop iteration.
3665 republish_content_iterator (void *cls,
3666 struct GNUNET_TIME_Absolute exp,
3667 const GNUNET_HashCode * key,
3668 size_t size, const char *data, uint32_t type)
3671 struct DHT_MessageContext *new_msg_ctx;
3672 struct GNUNET_DHT_PutMessage *put_msg;
3674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3675 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3677 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3680 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3681 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3682 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3683 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3684 put_msg->type = htons (type);
3685 memcpy (&put_msg[1], data, size);
3686 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3687 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3688 new_msg_ctx->msg_options = ntohl (0);
3689 new_msg_ctx->network_size = estimate_diameter();
3690 new_msg_ctx->peer = &my_identity;
3691 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3692 new_msg_ctx->hop_count = 0;
3693 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3694 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3695 increment_stats(STAT_PUT_START);
3696 demultiplex_message(&put_msg->header, new_msg_ctx);
3698 GNUNET_free(new_msg_ctx);
3699 GNUNET_free (put_msg);
3704 * Task used to republish data.
3706 * @param cls closure (a struct RepublishContext)
3707 * @param tc runtime context for this task
3710 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3712 struct RepublishContext *put_context = cls;
3714 unsigned int results;
3716 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3718 GNUNET_free(put_context);
3722 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3723 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3724 if (results == 0) /* Data must have expired */
3725 GNUNET_free(put_context);
3726 else /* Reschedule task for next time period */
3727 GNUNET_SCHEDULER_add_delayed(dht_republish_frequency, &republish_content, put_context);
3733 * Iterator over hash map entries.
3735 * @param cls client to search for in source routes
3736 * @param key current key code (ignored)
3737 * @param value value in the hash map, a DHTQueryRecord
3738 * @return GNUNET_YES if we should continue to
3742 static int find_client_records (void *cls,
3743 const GNUNET_HashCode * key, void *value)
3745 struct ClientList *client = cls;
3746 struct DHTQueryRecord *record = value;
3747 struct DHTRouteSource *pos;
3751 if (pos->client == client)
3757 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3758 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3759 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3760 GNUNET_SCHEDULER_cancel(pos->delete_task);
3762 if (pos->find_peers_responded != NULL)
3763 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3766 if (record->head == NULL) /* No more entries in DLL */
3768 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3769 GNUNET_free(record);
3775 * Functions with this signature are called whenever a client
3776 * is disconnected on the network level.
3778 * @param cls closure (NULL for dht)
3779 * @param client identification of the client; NULL
3780 * for the last call when the server is destroyed
3782 static void handle_client_disconnect (void *cls,
3783 struct GNUNET_SERVER_Client* client)
3785 struct ClientList *pos = client_list;
3786 struct ClientList *prev;
3787 struct ClientList *found;
3788 struct PendingMessage *reply;
3794 if (pos->client_handle == client)
3797 prev->next = pos->next;
3799 client_list = pos->next;
3809 while(NULL != (reply = found->pending_head))
3811 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3814 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3820 * Find a client if it exists, add it otherwise.
3822 * @param client the server handle to the client
3824 * @return the client if found, a new client otherwise
3826 static struct ClientList *
3827 find_active_client (struct GNUNET_SERVER_Client *client)
3829 struct ClientList *pos = client_list;
3830 struct ClientList *ret;
3834 if (pos->client_handle == client)
3839 ret = GNUNET_malloc (sizeof (struct ClientList));
3840 ret->client_handle = client;
3841 ret->next = client_list;
3849 * Task to send a malicious put message across the network.
3851 * @param cls closure for this task
3852 * @param tc the context under which the task is running
3855 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3857 static struct GNUNET_DHT_PutMessage put_message;
3858 static struct DHT_MessageContext message_context;
3859 static GNUNET_HashCode key;
3860 uint32_t random_key;
3862 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3864 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3865 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3866 put_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3867 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3868 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3869 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3870 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3871 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3872 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3873 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3874 message_context.msg_options = ntohl (0);
3875 message_context.network_size = estimate_diameter();
3876 message_context.peer = &my_identity;
3877 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3878 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3879 #if DEBUG_DHT_ROUTING
3880 if (dhtlog_handle != NULL)
3881 dhtlog_handle->insert_dhtkey(NULL, &key);
3883 increment_stats(STAT_PUT_START);
3884 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3885 demultiplex_message(&put_message.header, &message_context);
3886 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3891 * Task to send a malicious put message across the network.
3893 * @param cls closure for this task
3894 * @param tc the context under which the task is running
3897 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3899 static struct GNUNET_DHT_GetMessage get_message;
3900 struct DHT_MessageContext message_context;
3901 static GNUNET_HashCode key;
3902 uint32_t random_key;
3904 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3907 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3908 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3909 get_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3910 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3911 message_context.client = NULL;
3912 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3913 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3914 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3915 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3916 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3917 message_context.msg_options = ntohl (0);
3918 message_context.network_size = estimate_diameter();
3919 message_context.peer = &my_identity;
3920 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3921 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3922 #if DEBUG_DHT_ROUTING
3923 if (dhtlog_handle != NULL)
3924 dhtlog_handle->insert_dhtkey(NULL, &key);
3926 increment_stats(STAT_GET_START);
3927 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3928 demultiplex_message (&get_message.header, &message_context);
3929 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3935 * Iterator over hash map entries.
3937 * @param cls closure
3938 * @param key current key code
3939 * @param value value in the hash map
3940 * @return GNUNET_YES if we should continue to
3945 add_known_to_bloom (void *cls,
3946 const GNUNET_HashCode * key,
3949 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3950 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3955 * Task to send a find peer message for our own peer identifier
3956 * so that we can find the closest peers in the network to ourselves
3957 * and attempt to connect to them.
3959 * @param cls closure for this task
3960 * @param tc the context under which the task is running
3963 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3965 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3966 struct DHT_MessageContext message_context;
3967 struct GNUNET_TIME_Relative next_send_time;
3968 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3970 struct GNUNET_TIME_Relative time_diff;
3971 struct GNUNET_TIME_Absolute end;
3973 double count_per_interval;
3975 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3978 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! */
3980 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3981 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3982 &send_find_peer_message, NULL);
3983 newly_found_peers = 0;
3987 increment_stats(STAT_FIND_PEER_START);
3989 end = GNUNET_TIME_absolute_get();
3990 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3992 if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
3994 multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
3995 count_per_interval = find_peer_context.count / multiplier;
3999 multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
4000 count_per_interval = find_peer_context.count * multiplier;
4004 #if FIND_PEER_WITH_HELLO
4005 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4006 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4007 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4009 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
4010 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
4012 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4013 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4014 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
4015 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
4016 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4017 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
4018 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
4019 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4020 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4021 message_context.network_size = estimate_diameter();
4022 message_context.peer = &my_identity;
4023 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4024 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4026 demultiplex_message(&find_peer_msg->header, &message_context);
4027 GNUNET_free(find_peer_msg);
4028 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4029 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
4031 if (newly_found_peers < bucket_size)
4033 next_send_time.rel_value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4034 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4035 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4039 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4040 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4041 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4044 GNUNET_assert (next_send_time.rel_value != 0);
4045 find_peer_context.count = 0;
4046 newly_found_peers = 0;
4047 find_peer_context.start = GNUNET_TIME_absolute_get();
4048 if (GNUNET_YES == do_find_peer)
4050 GNUNET_SCHEDULER_add_delayed (next_send_time,
4051 &send_find_peer_message, NULL);
4056 * Handler for any generic DHT messages, calls the appropriate handler
4057 * depending on message type, sends confirmation if responses aren't otherwise
4060 * @param cls closure for the service
4061 * @param client the client we received this message from
4062 * @param message the actual message received
4065 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4066 const struct GNUNET_MessageHeader *message)
4068 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
4069 const struct GNUNET_MessageHeader *enc_msg;
4070 struct DHT_MessageContext message_context;
4072 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4074 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4075 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4079 ntohs (message->type),
4080 GNUNET_h2s (&dht_msg->key),
4081 GNUNET_ntohll (dht_msg->unique_id));
4083 #if DEBUG_DHT_ROUTING
4084 if (dhtlog_handle != NULL)
4085 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4087 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4088 message_context.client = find_active_client (client);
4089 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
4090 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4091 message_context.replication = ntohl (dht_msg->desired_replication_level);
4092 message_context.msg_options = ntohl (dht_msg->options);
4093 message_context.network_size = estimate_diameter();
4094 message_context.peer = &my_identity;
4095 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
4096 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4097 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4098 increment_stats(STAT_GET_START);
4099 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4100 increment_stats(STAT_PUT_START);
4101 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4102 increment_stats(STAT_FIND_PEER_START);
4104 demultiplex_message(enc_msg, &message_context);
4106 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4111 * Handler for any locally received DHT control messages,
4112 * sets malicious flags mostly for now.
4114 * @param cls closure for the service
4115 * @param client the client we received this message from
4116 * @param message the actual message received
4120 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4121 const struct GNUNET_MessageHeader *message)
4123 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4124 (const struct GNUNET_DHT_ControlMessage *) message;
4126 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4127 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4128 "CONTROL", ntohs(dht_control_msg->command));
4131 switch (ntohs(dht_control_msg->command))
4133 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4134 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4135 GNUNET_SCHEDULER_add_now(&send_find_peer_message, NULL);
4138 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4139 if (ntohs(dht_control_msg->variable) > 0)
4140 malicious_get_frequency = ntohs(dht_control_msg->variable);
4141 if (malicious_get_frequency == 0)
4142 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4143 if (malicious_getter != GNUNET_YES)
4144 GNUNET_SCHEDULER_add_now(&malicious_get_task, NULL);
4145 malicious_getter = GNUNET_YES;
4146 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4147 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4149 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4150 if (ntohs(dht_control_msg->variable) > 0)
4151 malicious_put_frequency = ntohs(dht_control_msg->variable);
4152 if (malicious_put_frequency == 0)
4153 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4154 if (malicious_putter != GNUNET_YES)
4155 GNUNET_SCHEDULER_add_now(&malicious_put_task, NULL);
4156 malicious_putter = GNUNET_YES;
4157 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4158 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4160 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4161 #if DEBUG_DHT_ROUTING
4162 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4163 dhtlog_handle->set_malicious(&my_identity);
4165 malicious_dropper = GNUNET_YES;
4166 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4167 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4171 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4172 "%s:%s Unknown control command type `%d'!\n",
4174 ntohs(dht_control_msg->command));
4178 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4182 * Handler for any generic DHT stop messages, calls the appropriate handler
4183 * depending on message type (if processed locally)
4185 * @param cls closure for the service
4186 * @param client the client we received this message from
4187 * @param message the actual message received
4191 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4192 const struct GNUNET_MessageHeader *message)
4195 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4196 (const struct GNUNET_DHT_StopMessage *) message;
4197 struct DHTQueryRecord *record;
4198 struct DHTRouteSource *pos;
4200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4201 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4202 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4204 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
4211 if ((pos->client != NULL) && (pos->client->client_handle == client))
4213 GNUNET_SCHEDULER_cancel(pos->delete_task);
4214 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4215 GNUNET_SCHEDULER_add_now(&remove_forward_entry, pos);
4221 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4226 * Core handler for p2p route requests.
4229 handle_dht_p2p_route_request (void *cls,
4230 const struct GNUNET_PeerIdentity *peer,
4231 const struct GNUNET_MessageHeader *message,
4232 struct GNUNET_TIME_Relative latency, uint32_t distance)
4235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4236 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4238 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4239 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4240 struct DHT_MessageContext *message_context;
4242 if (get_max_send_delay().rel_value > MAX_REQUEST_TIME.rel_value)
4244 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
4245 increment_stats("# route requests dropped due to high load");
4246 decrease_max_send_delay(get_max_send_delay());
4250 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4253 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4258 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4263 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4264 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4265 GNUNET_assert(message_context->bloom != NULL);
4266 message_context->hop_count = ntohl(incoming->hop_count);
4267 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
4268 message_context->replication = ntohl(incoming->desired_replication_level);
4269 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
4270 message_context->msg_options = ntohl(incoming->options);
4271 message_context->network_size = ntohl(incoming->network_size);
4272 message_context->peer = peer;
4273 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4274 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4275 demultiplex_message(enc_msg, message_context);
4276 GNUNET_free(message_context);
4282 * Core handler for p2p route results.
4285 handle_dht_p2p_route_result (void *cls,
4286 const struct GNUNET_PeerIdentity *peer,
4287 const struct GNUNET_MessageHeader *message,
4288 struct GNUNET_TIME_Relative latency, uint32_t distance)
4291 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4292 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4294 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4295 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4296 struct DHT_MessageContext message_context;
4298 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4304 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4305 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4306 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4307 GNUNET_assert(message_context.bloom != NULL);
4308 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
4309 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
4310 message_context.msg_options = ntohl(incoming->options);
4311 message_context.hop_count = ntohl(incoming->hop_count);
4312 message_context.peer = peer;
4313 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
4314 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4315 route_result_message(enc_msg, &message_context);
4321 * Receive the HELLO from transport service,
4322 * free current and replace if necessary.
4325 * @param message HELLO message of peer
4328 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4332 "Received our `%s' from transport service\n",
4336 GNUNET_assert (message != NULL);
4337 GNUNET_free_non_null(my_hello);
4338 my_hello = GNUNET_malloc(ntohs(message->size));
4339 memcpy(my_hello, message, ntohs(message->size));
4344 * Task run during shutdown.
4350 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4353 struct PeerInfo *pos;
4355 if (transport_handle != NULL)
4357 GNUNET_free_non_null(my_hello);
4358 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4359 GNUNET_TRANSPORT_disconnect(transport_handle);
4361 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4363 while (k_buckets[bucket_count].head != NULL)
4365 pos = k_buckets[bucket_count].head;
4367 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4368 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4370 delete_peer(pos, bucket_count);
4373 if (coreAPI != NULL)
4376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4377 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4379 GNUNET_CORE_disconnect (coreAPI);
4382 if (datacache != NULL)
4385 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4386 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4388 GNUNET_DATACACHE_destroy (datacache);
4393 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4396 if (dhtlog_handle != NULL)
4398 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4399 dhtlog_handle = NULL;
4401 if (block_context != NULL)
4403 GNUNET_BLOCK_context_destroy (block_context);
4404 block_context = NULL;
4406 GNUNET_free_non_null(my_short_id);
4412 * To be called on core init/fail.
4414 * @param cls service closure
4415 * @param server handle to the server for this service
4416 * @param identity the public identity of this peer
4417 * @param publicKey the public key of this peer
4420 core_init (void *cls,
4421 struct GNUNET_CORE_Handle *server,
4422 const struct GNUNET_PeerIdentity *identity,
4423 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4429 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4430 "%s: Connection to core FAILED!\n", "dht",
4431 GNUNET_i2s (identity));
4433 GNUNET_SCHEDULER_cancel (cleanup_task);
4434 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4438 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4439 "%s: Core connection initialized, I am peer: %s\n", "dht",
4440 GNUNET_i2s (identity));
4443 /* Copy our identity so we can use it */
4444 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4445 if (my_short_id != NULL)
4446 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4447 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4448 /* Set the server to local variable */
4451 if (dhtlog_handle != NULL)
4452 dhtlog_handle->insert_node (NULL, &my_identity);
4456 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4457 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4458 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4459 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4464 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4465 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4466 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4472 * Method called whenever a peer connects.
4474 * @param cls closure
4475 * @param peer peer identity this notification is about
4476 * @param latency reported latency of the connection with peer
4477 * @param distance reported distance (DV) to peer
4479 void handle_core_connect (void *cls,
4480 const struct GNUNET_PeerIdentity * peer,
4481 struct GNUNET_TIME_Relative latency,
4484 struct PeerInfo *ret;
4487 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4488 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4491 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4493 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));
4497 if (datacache != NULL)
4498 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, GNUNET_BLOCK_TYPE_DHT_HELLO, GNUNET_TIME_absolute_get_forever());
4499 ret = try_add_peer(peer,
4500 find_current_bucket(&peer->hashPubKey),
4505 newly_found_peers++;
4506 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4509 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4510 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4516 * Method called whenever a peer disconnects.
4518 * @param cls closure
4519 * @param peer peer identity this notification is about
4521 void handle_core_disconnect (void *cls,
4523 GNUNET_PeerIdentity * peer)
4525 struct PeerInfo *to_remove;
4528 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");
4530 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4532 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));
4535 increment_stats(STAT_DISCONNECTS);
4536 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4537 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4538 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4539 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4540 delete_peer(to_remove, current_bucket);
4545 * Process dht requests.
4547 * @param cls closure
4548 * @param server the initialized server
4549 * @param c configuration to use
4553 struct GNUNET_SERVER_Handle *server,
4554 const struct GNUNET_CONFIGURATION_Handle *c)
4556 struct GNUNET_TIME_Relative next_send_time;
4557 unsigned long long temp_config_num;
4558 char *converge_modifier_buf;
4561 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4562 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4563 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4564 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
4565 GNUNET_TIME_UNIT_FOREVER_REL,
4566 NULL, /* Closure passed to DHT functions */
4567 &core_init, /* Call core_init once connected */
4568 &handle_core_connect, /* Handle connects */
4569 &handle_core_disconnect, /* remove peers on disconnects */
4570 NULL, /* Do we care about "status" updates? */
4571 NULL, /* Don't want notified about all incoming messages */
4572 GNUNET_NO, /* For header only inbound notification */
4573 NULL, /* Don't want notified about all outbound messages */
4574 GNUNET_NO, /* For header only outbound notification */
4575 core_handlers); /* Register these handlers */
4577 if (coreAPI == NULL)
4579 transport_handle = GNUNET_TRANSPORT_connect(cfg,
4580 NULL, NULL, NULL, NULL, NULL);
4581 if (transport_handle != NULL)
4582 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4584 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4585 "Failed to connect to transport service!\n");
4586 block_context = GNUNET_BLOCK_context_create (cfg);
4587 lowest_bucket = MAX_BUCKETS - 1;
4588 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4589 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4590 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4591 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4592 GNUNET_assert(all_known_peers != NULL);
4593 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4595 debug_routes = GNUNET_YES;
4599 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4602 strict_kademlia = GNUNET_YES;
4606 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4609 stop_on_closest = GNUNET_YES;
4613 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4616 stop_on_found = GNUNET_YES;
4620 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4621 "malicious_getter"))
4623 malicious_getter = GNUNET_YES;
4624 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4625 "MALICIOUS_GET_FREQUENCY",
4626 &malicious_get_frequency))
4627 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4630 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4634 max_hops = DEFAULT_MAX_HOPS;
4637 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4640 use_max_hops = GNUNET_YES;
4644 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4645 "malicious_putter"))
4647 malicious_putter = GNUNET_YES;
4648 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4649 "MALICIOUS_PUT_FREQUENCY",
4650 &malicious_put_frequency))
4651 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4654 dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
4655 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4657 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4661 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4662 "malicious_dropper"))
4664 malicious_dropper = GNUNET_YES;
4668 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4670 do_republish = GNUNET_NO;
4673 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4676 do_find_peer = GNUNET_NO;
4679 do_find_peer = GNUNET_YES;
4682 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4683 "use_real_distance"))
4684 use_real_distance = GNUNET_YES;
4687 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4688 "mysql_logging_extended"))
4690 debug_routes = GNUNET_YES;
4691 debug_routes_extended = GNUNET_YES;
4694 #if DEBUG_DHT_ROUTING
4695 if (GNUNET_YES == debug_routes)
4697 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4698 if (dhtlog_handle == NULL)
4700 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4701 "Could not connect to mysql logging server, logging will not happen!");
4706 converge_option = DHT_CONVERGE_SQUARE;
4708 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4711 converge_option = DHT_CONVERGE_LINEAR;
4713 else if (GNUNET_YES ==
4714 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4715 "converge_exponential"))
4717 converge_option = DHT_CONVERGE_EXPONENTIAL;
4719 else if (GNUNET_YES ==
4720 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4723 converge_option = DHT_CONVERGE_RANDOM;
4725 else if (GNUNET_YES ==
4726 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4729 converge_option = DHT_CONVERGE_BINARY;
4732 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4734 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4736 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4737 converge_modifier = 0.0;
4739 GNUNET_free(converge_modifier_buf);
4742 stats = GNUNET_STATISTICS_create("dht", cfg);
4746 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4747 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4748 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4749 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4750 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4751 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4752 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4753 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4754 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4755 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4756 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4757 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4758 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4759 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4760 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4761 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4762 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4763 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4764 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4765 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4767 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4768 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4769 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4770 if (GNUNET_YES == do_find_peer)
4772 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4773 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4774 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4775 find_peer_context.start = GNUNET_TIME_absolute_get();
4776 GNUNET_SCHEDULER_add_delayed (next_send_time,
4777 &send_find_peer_message, &find_peer_context);
4780 /* Scheduled the task to clean up when shutdown is called */
4781 cleanup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4782 &shutdown_task, NULL);
4786 * The main function for the dht service.
4788 * @param argc number of arguments from the command line
4789 * @param argv command line arguments
4790 * @return 0 ok, 1 on error
4793 main (int argc, char *const *argv)
4798 GNUNET_SERVICE_run (argc,
4801 GNUNET_SERVICE_OPTION_NONE,
4802 &run, NULL)) ? 0 : 1;
4803 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap));
4804 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap));
4805 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4806 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4807 GNUNET_CONTAINER_heap_destroy (recent.minHeap);