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_client_lib.h"
30 #include "gnunet_getopt_lib.h"
31 #include "gnunet_os_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_core_service.h"
35 #include "gnunet_signal_lib.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_datacache_lib.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_hello_lib.h"
40 #include "gnunet_dht_service.h"
41 #include "gnunet_statistics_service.h"
46 #define PRINT_TABLES GNUNET_NO
48 #define REAL_DISTANCE GNUNET_NO
50 #define EXTRA_CHECKS GNUNET_NO
52 * How many buckets will we allow total.
54 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
57 * Should the DHT issue FIND_PEER requests to get better routing tables?
59 #define DEFAULT_DO_FIND_PEER GNUNET_YES
62 * Defines whether find peer requests send their HELLO's outgoing,
63 * or expect replies to contain hellos.
65 #define FIND_PEER_WITH_HELLO GNUNET_YES
68 * What is the maximum number of peers in a given bucket.
70 #define DEFAULT_BUCKET_SIZE 4
73 * Minimum number of peers we need for "good" routing,
74 * any less than this and we will allow messages to
75 * travel much further through the network!
77 #define MINIMUM_PEER_THRESHOLD 20
79 #define DHT_MAX_RECENT 1000
81 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
84 * Default time to wait to send messages on behalf of other peers.
86 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
89 * Default importance for handling messages on behalf of other peers.
91 #define DHT_DEFAULT_P2P_IMPORTANCE 0
94 * How long to keep recent requests around by default.
96 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
99 * Default time to wait to send find peer messages sent by the dht service.
101 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
104 * Default importance for find peer messages sent by the dht service.
106 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
109 * Default replication parameter for find peer messages sent by the dht service.
111 #define DHT_DEFAULT_PUT_REPLICATION 4
114 * Default replication parameter for find peer messages sent by the dht service.
116 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
119 * Default options for find peer requests sent by the dht service.
121 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
122 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
125 * How long at least to wait before sending another find peer request.
127 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
130 * How long at most to wait before sending another find peer request.
132 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
135 * How often to update our preference levels for peers in our routing tables.
137 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
140 * How long at most on average will we allow a reply forward to take
141 * (before we quit sending out new requests)
143 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
146 * How many initial requests to send out (in true Kademlia fashion)
148 #define DHT_KADEMLIA_REPLICATION 3
151 * Default frequency for sending malicious get messages
153 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
156 * Default frequency for sending malicious put messages
158 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
161 * Type for a malicious request, so we can ignore it during testing
163 #define DHT_MALICIOUS_MESSAGE_TYPE 42
165 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
168 * Real maximum number of hops, at which point we refuse
169 * to forward the message.
171 #define DEFAULT_MAX_HOPS 10
174 * How many time differences between requesting a core send and
175 * the actual callback to remember.
177 #define MAX_REPLY_TIMES 8
179 enum ConvergenceOptions
182 * Use the linear method for convergence.
187 * Converge using a fast converging square
193 * Converge using a slower exponential
196 DHT_CONVERGE_EXPONENTIAL,
199 * Don't do any special convergence, allow
200 * the algorithm to hopefully route to closer
207 * Linked list of messages to send to clients.
209 struct P2PPendingMessage
212 * Pointer to next item in the list
214 struct P2PPendingMessage *next;
217 * Pointer to previous item in the list
219 struct P2PPendingMessage *prev;
222 * Message importance level.
224 unsigned int importance;
227 * Time when this request was scheduled to be sent.
229 struct GNUNET_TIME_Absolute scheduled;
232 * How long to wait before sending message.
234 struct GNUNET_TIME_Relative timeout;
237 * Actual message to be sent; // avoid allocation
239 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
244 * Per-peer information.
249 * Next peer entry (DLL)
251 struct PeerInfo *next;
254 * Prev peer entry (DLL)
256 struct PeerInfo *prev;
259 * Head of pending messages to be sent to this peer.
261 struct P2PPendingMessage *head;
264 * Tail of pending messages to be sent to this peer.
266 struct P2PPendingMessage *tail;
269 * Core handle for sending messages to this peer.
271 struct GNUNET_CORE_TransmitHandle *th;
274 * Task for scheduling message sends.
276 GNUNET_SCHEDULER_TaskIdentifier send_task;
279 * Task for scheduling preference updates
281 GNUNET_SCHEDULER_TaskIdentifier preference_task;
284 * Preference update context
286 struct GNUNET_CORE_InformationRequestContext *info_ctx;
289 * What is the average latency for replies received?
291 struct GNUNET_TIME_Relative latency;
294 * What is the identity of the peer?
296 struct GNUNET_PeerIdentity id;
299 * Transport level distance to peer.
301 unsigned int distance;
304 * Holds matching bits from peer to current target,
305 * used for distance comparisons between peers. May
306 * be considered a really bad idea.
307 * FIXME: remove this value (create struct which holds
308 * a single peerinfo and the matching bits, use
309 * that to pass to comparitor)
311 unsigned int matching_bits;
314 * Task for scheduling periodic ping messages for this peer.
316 GNUNET_SCHEDULER_TaskIdentifier ping_task;
320 * Peers are grouped into buckets.
327 struct PeerInfo *head;
332 struct PeerInfo *tail;
335 * Number of peers in the bucket.
337 unsigned int peers_size;
341 * Linked list of messages to send to clients.
343 struct PendingMessage
346 * Pointer to next item in the list
348 struct PendingMessage *next;
351 * Pointer to previous item in the list
353 struct PendingMessage *prev;
356 * Actual message to be sent; // avoid allocation
358 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
363 * Struct containing information about a client,
364 * handle to connect to it, and any pending messages
365 * that need to be sent to it.
370 * Linked list of active clients
372 struct ClientList *next;
375 * The handle to this client
377 struct GNUNET_SERVER_Client *client_handle;
380 * Handle to the current transmission request, NULL
383 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
386 * Linked list of pending messages for this client
388 struct PendingMessage *pending_head;
391 * Tail of linked list of pending messages for this client
393 struct PendingMessage *pending_tail;
398 * Context containing information about a DHT message received.
400 struct DHT_MessageContext
403 * The client this request was received from.
404 * (NULL if received from another peer)
406 struct ClientList *client;
409 * The peer this request was received from.
410 * (NULL if received from local client)
412 const struct GNUNET_PeerIdentity *peer;
415 * The key this request was about
420 * The unique identifier of this request
425 * Desired replication level
427 uint32_t replication;
430 * Network size estimate, either ours or the sum of
431 * those routed to thus far. =~ Log of number of peers
432 * chosen from for this request.
434 uint32_t network_size;
437 * Any message options for this request
439 uint32_t msg_options;
442 * How many hops has the message already traversed?
447 * How important is this message?
449 unsigned int importance;
452 * How long should we wait to transmit this request?
454 struct GNUNET_TIME_Relative timeout;
457 * Bloomfilter for this routing request.
459 struct GNUNET_CONTAINER_BloomFilter *bloom;
462 * Did we forward this message? (may need to remember it!)
467 * Are we the closest known peer to this key (out of our neighbors?)
473 * Record used for remembering what peers are waiting for what
474 * responses (based on search key).
476 struct DHTRouteSource
481 struct DHTRouteSource *next;
486 struct DHTRouteSource *prev;
489 * Source of the request. Replies should be forwarded to
492 struct GNUNET_PeerIdentity source;
495 * If this was a local request, remember the client; otherwise NULL.
497 struct ClientList *client;
500 * Pointer to this nodes heap location (for removal)
502 struct GNUNET_CONTAINER_HeapNode *hnode;
505 * Back pointer to the record storing this information.
507 struct DHTQueryRecord *record;
510 * Task to remove this entry on timeout.
512 GNUNET_SCHEDULER_TaskIdentifier delete_task;
515 * Bloomfilter of peers we have already sent back as
516 * replies to the initial request. Allows us to not
517 * forward the same peer multiple times for a find peer
520 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
525 * Entry in the DHT routing table.
527 struct DHTQueryRecord
530 * Head of DLL for result forwarding.
532 struct DHTRouteSource *head;
535 * Tail of DLL for result forwarding.
537 struct DHTRouteSource *tail;
540 * Key that the record concerns.
545 * GET message of this record (what we already forwarded?).
547 //DV_DHT_MESSAGE get; Try to get away with not saving this.
550 * Bloomfilter of the peers we've replied to so far
552 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
557 * Context used to calculate the number of find peer messages
558 * per X time units since our last scheduled find peer message
559 * was sent. If we have seen too many messages, delay or don't
562 struct FindPeerMessageContext
566 struct GNUNET_TIME_Absolute start;
568 struct GNUNET_TIME_Absolute end;
572 * DHT Routing results structure
577 * Min heap for removal upon reaching limit
579 struct GNUNET_CONTAINER_Heap *minHeap;
582 * Hashmap for fast key based lookup
584 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
589 * DHT structure for recent requests.
591 struct RecentRequests
594 * Min heap for removal upon reaching limit
596 struct GNUNET_CONTAINER_Heap *minHeap;
599 * Hashmap for key based lookup
601 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
607 * Position of this node in the min heap.
609 struct GNUNET_CONTAINER_HeapNode *heap_node;
612 * Bloomfilter containing entries for peers
613 * we forwarded this request to.
615 struct GNUNET_CONTAINER_BloomFilter *bloom;
618 * Timestamp of this request, for ordering
621 struct GNUNET_TIME_Absolute timestamp;
624 * Key of this request.
629 * Unique identifier for this request.
634 * Task to remove this entry on timeout.
636 GNUNET_SCHEDULER_TaskIdentifier remove_task;
639 struct RepublishContext
654 * Which kind of convergence will we be using?
656 enum ConvergenceOptions converge_option;
659 * Modifier for the convergence function
661 float converge_modifier;
664 * Recent requests by hash/uid and by time inserted.
666 static struct RecentRequests recent;
669 * Context to use to calculate find peer rates.
671 static struct FindPeerMessageContext find_peer_context;
674 * Don't use our routing algorithm, always route
675 * to closest peer; initially send requests to 3
678 static unsigned int strict_kademlia;
681 * Routing option to end routing when closest peer found.
683 static unsigned int stop_on_closest;
686 * Routing option to end routing when data is found.
688 static unsigned int stop_on_found;
691 * Whether DHT needs to manage find peer requests, or
692 * an external force will do it on behalf of the DHT.
694 static unsigned int do_find_peer;
697 * Once we have stored an item in the DHT, refresh it
698 * according to our republish interval.
700 static unsigned int do_republish;
703 * Use the "real" distance metric when selecting the
704 * next routing hop. Can be less accurate.
706 static unsigned int use_real_distance;
709 * How many peers have we added since we sent out our last
712 static unsigned int newly_found_peers;
715 * Container of active queries we should remember
717 static struct DHTResults forward_list;
720 * Handle to the datacache service (for inserting/retrieving data)
722 static struct GNUNET_DATACACHE_Handle *datacache;
725 * Handle for the statistics service.
727 struct GNUNET_STATISTICS_Handle *stats;
730 * The main scheduler to use for the DHT service
732 static struct GNUNET_SCHEDULER_Handle *sched;
735 * The configuration the DHT service is running with
737 static const struct GNUNET_CONFIGURATION_Handle *cfg;
740 * Handle to the core service
742 static struct GNUNET_CORE_Handle *coreAPI;
745 * Handle to the transport service, for getting our hello
747 static struct GNUNET_TRANSPORT_Handle *transport_handle;
750 * The identity of our peer.
752 static struct GNUNET_PeerIdentity my_identity;
755 * Short id of the peer, for printing
757 static char *my_short_id;
762 static struct GNUNET_MessageHeader *my_hello;
765 * Task to run when we shut down, cleaning up all our trash
767 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
770 * The lowest currently used bucket.
772 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
775 * The maximum number of hops before we stop routing messages.
777 static unsigned long long max_hops;
780 * How often to republish content we have previously stored.
782 static struct GNUNET_TIME_Relative dht_republish_frequency;
785 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
787 static int use_max_hops;
790 * The buckets (Kademlia routing table, complete with growth).
791 * Array of size MAX_BUCKET_SIZE.
793 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
796 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
798 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
801 * Recently seen find peer requests.
803 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
806 * Maximum size for each bucket.
808 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
811 * List of active clients.
813 static struct ClientList *client_list;
816 * Handle to the DHT logger.
818 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
821 * Whether or not to send routing debugging information
822 * to the dht logging server
824 static unsigned int debug_routes;
827 * Whether or not to send FULL route information to
830 static unsigned int debug_routes_extended;
833 * GNUNET_YES or GNUNET_NO, whether or not to act as
834 * a malicious node which drops all messages
836 static unsigned int malicious_dropper;
839 * GNUNET_YES or GNUNET_NO, whether or not to act as
840 * a malicious node which sends out lots of GETS
842 static unsigned int malicious_getter;
845 * GNUNET_YES or GNUNET_NO, whether or not to act as
846 * a malicious node which sends out lots of PUTS
848 static unsigned int malicious_putter;
851 * Frequency for malicious get requests.
853 static unsigned long long malicious_get_frequency;
856 * Frequency for malicious put requests.
858 static unsigned long long malicious_put_frequency;
861 * Reply times for requests, if we are busy, don't send any
864 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
867 * Current counter for replies.
869 static unsigned int reply_counter;
872 * Forward declaration.
874 static size_t send_generic_reply (void *cls, size_t size, void *buf);
876 /** Declare here so retry_core_send is aware of it */
877 size_t core_transmit_notify (void *cls,
878 size_t size, void *buf);
881 * Convert unique ID to hash code.
883 * @param uid unique ID to convert
884 * @param hash set to uid (extended with zeros)
887 hash_from_uid (uint64_t uid,
888 GNUNET_HashCode *hash)
890 memset (hash, 0, sizeof(GNUNET_HashCode));
891 *((uint64_t*)hash) = uid;
896 * Calculate the average send time between messages so that we can
897 * ignore certain requests if we get too busy.
899 * @return the average time between asking core to send a message
900 * and when the buffer for copying it is passed
902 static struct GNUNET_TIME_Relative get_average_send_delay()
905 unsigned int divisor;
906 struct GNUNET_TIME_Relative average_time;
907 average_time = GNUNET_TIME_relative_get_zero();
909 for (i = 0; i < MAX_REPLY_TIMES; i++)
911 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
912 if (reply_times[i].value == (uint64_t)0)
922 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
923 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
929 * Given the largest send delay, artificially decrease it
930 * so the next time around we may have a chance at sending
933 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
936 for (i = 0; i < MAX_REPLY_TIMES; i++)
938 if (reply_times[i].value == max_time.value)
940 reply_times[i].value = reply_times[i].value / 2;
947 * Find the maximum send time of the recently sent values.
949 * @return the average time between asking core to send a message
950 * and when the buffer for copying it is passed
952 static struct GNUNET_TIME_Relative get_max_send_delay()
955 struct GNUNET_TIME_Relative max_time;
956 max_time = GNUNET_TIME_relative_get_zero();
958 for (i = 0; i < MAX_REPLY_TIMES; i++)
960 if (reply_times[i].value > max_time.value)
961 max_time.value = reply_times[i].value;
964 if (max_time.value > MAX_REQUEST_TIME.value)
965 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
970 increment_stats(const char *value)
974 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
979 * Try to send another message from our core send list
982 try_core_send (void *cls,
983 const struct GNUNET_SCHEDULER_TaskContext *tc)
985 struct PeerInfo *peer = cls;
986 struct P2PPendingMessage *pending;
989 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
991 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
994 if (peer->th != NULL)
995 return; /* Message send already in progress */
997 pending = peer->head;
1000 ssize = ntohs(pending->msg->size);
1002 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1003 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
1004 "DHT", ssize, GNUNET_i2s(&peer->id));
1006 pending->scheduled = GNUNET_TIME_absolute_get();
1008 if (reply_counter >= MAX_REPLY_TIMES)
1010 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
1011 pending->timeout, &peer->id,
1012 ssize, &core_transmit_notify, peer);
1017 * Function called to send a request out to another peer.
1018 * Called both for locally initiated requests and those
1019 * received from other peers.
1021 * @param cls DHT service closure argument
1022 * @param msg the encapsulated message
1023 * @param peer the peer to forward the message to
1024 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1026 static void forward_result_message (void *cls,
1027 const struct GNUNET_MessageHeader *msg,
1028 struct PeerInfo *peer,
1029 struct DHT_MessageContext *msg_ctx)
1031 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1032 struct P2PPendingMessage *pending;
1036 increment_stats(STAT_RESULT_FORWARDS);
1037 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1038 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1039 psize = sizeof(struct P2PPendingMessage) + msize;
1040 pending = GNUNET_malloc(psize);
1041 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1042 pending->importance = DHT_SEND_PRIORITY;
1043 pending->timeout = GNUNET_TIME_relative_get_forever();
1044 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1045 result_message->header.size = htons(msize);
1046 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1047 result_message->options = htonl(msg_ctx->msg_options);
1048 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1049 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1050 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1051 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1052 memcpy(&result_message[1], msg, ntohs(msg->size));
1054 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));
1056 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1057 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1058 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1061 * Called when core is ready to send a message we asked for
1062 * out to the destination.
1064 * @param cls closure (NULL)
1065 * @param size number of bytes available in buf
1066 * @param buf where the callee should write the message
1067 * @return number of bytes written to buf
1069 size_t core_transmit_notify (void *cls,
1070 size_t size, void *buf)
1072 struct PeerInfo *peer = cls;
1074 struct P2PPendingMessage *pending;
1081 /* client disconnected */
1083 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1088 if (peer->head == NULL)
1093 pending = peer->head;
1094 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1095 msize = ntohs(pending->msg->size);
1099 memcpy (cbuf, pending->msg, msize);
1100 GNUNET_CONTAINER_DLL_remove (peer->head,
1104 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));
1106 GNUNET_free (pending);
1109 while (NULL != pending &&
1110 (size - off >= (msize = ntohs (pending->msg->size))))
1112 #if DEBUG_DHT_ROUTING
1113 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);
1115 memcpy (&cbuf[off], pending->msg, msize);
1117 GNUNET_CONTAINER_DLL_remove (peer->head,
1120 GNUNET_free (pending);
1121 pending = peer->head;
1124 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1125 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1127 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);
1134 * Compute the distance between have and target as a 32-bit value.
1135 * Differences in the lower bits must count stronger than differences
1136 * in the higher bits.
1138 * @return 0 if have==target, otherwise a number
1139 * that is larger as the distance between
1140 * the two hash codes increases
1143 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1145 unsigned int bucket;
1150 /* We have to represent the distance between two 2^9 (=512)-bit
1151 numbers as a 2^5 (=32)-bit number with "0" being used for the
1152 two numbers being identical; furthermore, we need to
1153 guarantee that a difference in the number of matching
1154 bits is always represented in the result.
1156 We use 2^32/2^9 numerical values to distinguish between
1157 hash codes that have the same LSB bit distance and
1158 use the highest 2^9 bits of the result to signify the
1159 number of (mis)matching LSB bits; if we have 0 matching
1160 and hence 512 mismatching LSB bits we return -1 (since
1161 512 itself cannot be represented with 9 bits) */
1163 /* first, calculate the most significant 9 bits of our
1164 result, aka the number of LSBs */
1165 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1166 /* bucket is now a value between 0 and 512 */
1168 return 0; /* perfect match */
1170 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1171 below, we'd end up with max+1 (overflow)) */
1173 /* calculate the most significant bits of the final result */
1174 msb = (512 - bucket) << (32 - 9);
1175 /* calculate the 32-9 least significant bits of the final result by
1176 looking at the differences in the 32-9 bits following the
1177 mismatching bit at 'bucket' */
1179 for (i = bucket + 1;
1180 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1182 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1183 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1184 last bit set will be 31 -- if
1185 i does not reach 512 first... */
1191 * Return a number that is larger the closer the
1192 * "have" GNUNET_hash code is to the "target".
1194 * @return inverse distance metric, non-zero.
1195 * Must fudge the value if NO bits match.
1198 inverse_distance (const GNUNET_HashCode * target,
1199 const GNUNET_HashCode * have)
1201 if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1202 return 1; /* Never return 0! */
1203 return ((unsigned int) -1) - distance (target, have);
1207 * Find the optimal bucket for this key, regardless
1208 * of the current number of buckets in use.
1210 * @param hc the hashcode to compare our identity to
1212 * @return the proper bucket index, or GNUNET_SYSERR
1213 * on error (same hashcode)
1215 static int find_bucket(const GNUNET_HashCode *hc)
1219 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1220 if (bits == MAX_BUCKETS)
1221 return GNUNET_SYSERR;
1222 return MAX_BUCKETS - bits - 1;
1226 * Find which k-bucket this peer should go into,
1227 * taking into account the size of the k-bucket
1228 * array. This means that if more bits match than
1229 * there are currently buckets, lowest_bucket will
1232 * @param hc GNUNET_HashCode we are finding the bucket for.
1234 * @return the proper bucket index for this key,
1235 * or GNUNET_SYSERR on error (same hashcode)
1237 static int find_current_bucket(const GNUNET_HashCode *hc)
1240 actual_bucket = find_bucket(hc);
1242 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1243 return lowest_bucket;
1244 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1245 return lowest_bucket;
1247 return actual_bucket;
1252 * Find a routing table entry from a peer identity
1254 * @param peer the peer to look up
1256 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1259 find_bucket_by_peer(const struct PeerInfo *peer)
1262 struct PeerInfo *pos;
1264 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1266 pos = k_buckets[bucket].head;
1275 return GNUNET_SYSERR; /* No such peer. */
1281 * Print the complete routing table for this peer.
1284 print_routing_table ()
1287 struct PeerInfo *pos;
1288 char char_buf[30000];
1290 memset(char_buf, 0, sizeof(char_buf));
1292 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1293 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1294 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1296 pos = k_buckets[bucket].head;
1297 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1298 //fprintf(stderr, "Bucket %d:\n", bucket);
1301 //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));
1302 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));
1306 fprintf(stderr, "%s", char_buf);
1312 * Find a routing table entry from a peer identity
1314 * @param peer the peer identity to look up
1316 * @return the routing table entry, or NULL if not found
1318 static struct PeerInfo *
1319 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1322 struct PeerInfo *pos;
1323 bucket = find_current_bucket(&peer->hashPubKey);
1325 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1328 pos = k_buckets[bucket].head;
1331 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1335 return NULL; /* No such peer. */
1338 /* Forward declaration */
1340 update_core_preference (void *cls,
1341 const struct GNUNET_SCHEDULER_TaskContext *tc);
1343 * Function called with statistics about the given peer.
1345 * @param cls closure
1346 * @param peer identifies the peer
1347 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1348 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1349 * @param amount set to the amount that was actually reserved or unreserved;
1350 * either the full requested amount or zero (no partial reservations)
1351 * @param preference current traffic preference for the given peer
1354 update_core_preference_finish (void *cls,
1355 const struct GNUNET_PeerIdentity * peer,
1356 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1357 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1358 int amount, uint64_t preference)
1360 struct PeerInfo *peer_info = cls;
1361 peer_info->info_ctx = NULL;
1362 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1366 update_core_preference (void *cls,
1367 const struct GNUNET_SCHEDULER_TaskContext *tc)
1369 struct PeerInfo *peer = cls;
1370 uint64_t preference;
1371 unsigned int matching;
1372 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1376 matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1379 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1382 preference = 1LL << matching;
1383 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1385 GNUNET_TIME_relative_get_forever(),
1386 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1389 &update_core_preference_finish,
1394 * Really add a peer to a bucket (only do assertions
1397 * @param peer GNUNET_PeerIdentity of the peer to add
1398 * @param bucket the already figured out bucket to add
1400 * @param latency the core reported latency of this peer
1401 * @param distance the transport level distance to this peer
1403 * @return the newly added PeerInfo
1405 static struct PeerInfo *
1406 add_peer(const struct GNUNET_PeerIdentity *peer,
1407 unsigned int bucket,
1408 struct GNUNET_TIME_Relative latency,
1409 unsigned int distance)
1411 struct PeerInfo *new_peer;
1412 GNUNET_assert(bucket < MAX_BUCKETS);
1413 GNUNET_assert(peer != NULL);
1414 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1415 new_peer->latency = latency;
1416 new_peer->distance = distance;
1418 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1420 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1421 k_buckets[bucket].tail,
1422 k_buckets[bucket].tail,
1424 k_buckets[bucket].peers_size++;
1426 if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1428 #if DO_UPDATE_PREFERENCE
1429 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1437 * Given a peer and its corresponding bucket,
1438 * remove it from that bucket. Does not free
1439 * the PeerInfo struct, nor cancel messages
1440 * or free messages waiting to be sent to this
1443 * @param peer the peer to remove
1444 * @param bucket the bucket the peer belongs to
1446 static void remove_peer (struct PeerInfo *peer,
1447 unsigned int bucket)
1449 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1450 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1451 k_buckets[bucket].tail,
1453 k_buckets[bucket].peers_size--;
1455 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1461 * Removes peer from a bucket, then frees associated
1462 * resources and frees peer.
1464 * @param peer peer to be removed and freed
1465 * @param bucket which bucket this peer belongs to
1467 static void delete_peer (struct PeerInfo *peer,
1468 unsigned int bucket)
1470 struct P2PPendingMessage *pos;
1471 struct P2PPendingMessage *next;
1473 struct PeerInfo *peer_pos;
1475 peer_pos = k_buckets[bucket].head;
1476 while ((peer_pos != NULL) && (peer_pos != peer))
1477 peer_pos = peer_pos->next;
1478 if (peer_pos == NULL)
1480 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1481 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));
1483 GNUNET_assert(peer_pos != NULL);
1485 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1487 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1488 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1489 if (peer->th != NULL)
1490 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1493 while (pos != NULL) /* Remove any pending messages for this peer */
1500 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1501 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1507 * Iterator over hash map entries.
1509 * @param cls closure
1510 * @param key current key code
1511 * @param value PeerInfo of the peer to move to new lowest bucket
1512 * @return GNUNET_YES if we should continue to
1516 static int move_lowest_bucket (void *cls,
1517 const GNUNET_HashCode * key,
1520 struct PeerInfo *peer = value;
1523 GNUNET_assert(lowest_bucket > 0);
1524 new_bucket = lowest_bucket - 1;
1525 remove_peer(peer, lowest_bucket);
1526 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1527 k_buckets[new_bucket].tail,
1528 k_buckets[new_bucket].tail,
1530 k_buckets[new_bucket].peers_size++;
1536 * The current lowest bucket is full, so change the lowest
1537 * bucket to the next lower down, and move any appropriate
1538 * entries in the current lowest bucket to the new bucket.
1540 static void enable_next_bucket()
1542 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1543 struct PeerInfo *pos;
1544 GNUNET_assert(lowest_bucket > 0);
1545 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1546 pos = k_buckets[lowest_bucket].head;
1549 fprintf(stderr, "Printing RT before new bucket\n");
1550 print_routing_table();
1552 /* Populate the array of peers which should be in the next lowest bucket */
1555 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1556 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1560 /* Remove peers from lowest bucket, insert into next lowest bucket */
1561 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1562 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1563 lowest_bucket = lowest_bucket - 1;
1565 fprintf(stderr, "Printing RT after new bucket\n");
1566 print_routing_table();
1571 * Find the closest peer in our routing table to the
1574 * @return The closest peer in our routing table to the
1575 * key, or NULL on error.
1577 static struct PeerInfo *
1578 find_closest_peer (const GNUNET_HashCode *hc)
1580 struct PeerInfo *pos;
1581 struct PeerInfo *current_closest;
1582 unsigned int lowest_distance;
1583 unsigned int temp_distance;
1587 lowest_distance = -1;
1589 if (k_buckets[lowest_bucket].peers_size == 0)
1592 current_closest = NULL;
1593 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1595 pos = k_buckets[bucket].head;
1597 while ((pos != NULL) && (count < bucket_size))
1599 temp_distance = distance(&pos->id.hashPubKey, hc);
1600 if (temp_distance <= lowest_distance)
1602 lowest_distance = temp_distance;
1603 current_closest = pos;
1609 GNUNET_assert(current_closest != NULL);
1610 return current_closest;
1615 * Function called to send a request out to another peer.
1616 * Called both for locally initiated requests and those
1617 * received from other peers.
1619 * @param cls DHT service closure argument (unused)
1620 * @param msg the encapsulated message
1621 * @param peer the peer to forward the message to
1622 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1624 static void forward_message (void *cls,
1625 const struct GNUNET_MessageHeader *msg,
1626 struct PeerInfo *peer,
1627 struct DHT_MessageContext *msg_ctx)
1629 struct GNUNET_DHT_P2PRouteMessage *route_message;
1630 struct P2PPendingMessage *pending;
1634 increment_stats(STAT_ROUTE_FORWARDS);
1636 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1637 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1639 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1640 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1641 psize = sizeof(struct P2PPendingMessage) + msize;
1642 pending = GNUNET_malloc(psize);
1643 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1644 pending->importance = msg_ctx->importance;
1645 pending->timeout = msg_ctx->timeout;
1646 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1647 route_message->header.size = htons(msize);
1648 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1649 route_message->options = htonl(msg_ctx->msg_options);
1650 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1651 route_message->network_size = htonl(msg_ctx->network_size);
1652 route_message->desired_replication_level = htonl(msg_ctx->replication);
1653 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1654 if (msg_ctx->bloom != NULL)
1655 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1656 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1657 memcpy(&route_message[1], msg, ntohs(msg->size));
1659 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));
1661 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1662 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1663 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1668 * Task used to send ping messages to peers so that
1669 * they don't get disconnected.
1671 * @param cls the peer to send a ping message to
1672 * @param tc context, reason, etc.
1675 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1677 struct PeerInfo *peer = cls;
1678 struct GNUNET_MessageHeader ping_message;
1679 struct DHT_MessageContext message_context;
1681 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1684 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1685 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1687 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1689 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1691 forward_message(NULL, &ping_message, peer, &message_context);
1692 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1696 * Schedule PING messages for the top X peers in each
1697 * bucket of the routing table (so core won't disconnect them!)
1699 void schedule_ping_messages()
1701 unsigned int bucket;
1703 struct PeerInfo *pos;
1704 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1706 pos = k_buckets[bucket].head;
1710 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1711 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1712 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1714 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1715 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1725 * Attempt to add a peer to our k-buckets.
1727 * @param peer the peer identity of the peer being added
1728 * @param bucket the bucket that we want this peer to go in
1729 * @param latency transport latency of this peer
1730 * @param distance transport distance to this peer
1732 * @return NULL if the peer was not added,
1733 * pointer to PeerInfo for new peer otherwise
1735 static struct PeerInfo *
1736 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1737 unsigned int bucket,
1738 struct GNUNET_TIME_Relative latency,
1739 unsigned int distance)
1742 struct PeerInfo *new_peer;
1744 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1747 peer_bucket = find_current_bucket(&peer->hashPubKey);
1749 GNUNET_assert(peer_bucket >= lowest_bucket);
1750 new_peer = add_peer(peer, peer_bucket, latency, distance);
1752 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1753 enable_next_bucket();
1755 schedule_ping_messages();
1762 * Task run to check for messages that need to be sent to a client.
1764 * @param client a ClientList, containing the client and any messages to be sent to it
1767 process_pending_messages (struct ClientList *client)
1769 if (client->pending_head == NULL)
1771 if (client->transmit_handle != NULL)
1773 client->transmit_handle =
1774 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1775 ntohs (client->pending_head->msg->
1777 GNUNET_TIME_UNIT_FOREVER_REL,
1778 &send_generic_reply, client);
1782 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1783 * request. A ClientList is passed as closure, take the head of the list
1784 * and copy it into buf, which has the result of sending the message to the
1787 * @param cls closure to this call
1788 * @param size maximum number of bytes available to send
1789 * @param buf where to copy the actual message to
1791 * @return the number of bytes actually copied, 0 indicates failure
1794 send_generic_reply (void *cls, size_t size, void *buf)
1796 struct ClientList *client = cls;
1798 struct PendingMessage *reply;
1802 client->transmit_handle = NULL;
1805 /* client disconnected */
1809 while ( (NULL != (reply = client->pending_head)) &&
1810 (size >= off + (msize = ntohs (reply->msg->size))))
1812 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1813 client->pending_tail,
1815 memcpy (&cbuf[off], reply->msg, msize);
1816 GNUNET_free (reply);
1819 process_pending_messages (client);
1825 * Add a PendingMessage to the clients list of messages to be sent
1827 * @param client the active client to send the message to
1828 * @param pending_message the actual message to send
1831 add_pending_message (struct ClientList *client,
1832 struct PendingMessage *pending_message)
1834 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1835 client->pending_tail,
1836 client->pending_tail,
1838 process_pending_messages (client);
1845 * Called when a reply needs to be sent to a client, as
1846 * a result it found to a GET or FIND PEER request.
1848 * @param client the client to send the reply to
1849 * @param message the encapsulated message to send
1850 * @param uid the unique identifier of this request
1853 send_reply_to_client (struct ClientList *client,
1854 const struct GNUNET_MessageHeader *message,
1855 unsigned long long uid)
1857 struct GNUNET_DHT_RouteResultMessage *reply;
1858 struct PendingMessage *pending_message;
1862 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1863 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1865 msize = ntohs (message->size);
1866 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1867 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1869 GNUNET_break_op (0);
1873 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1874 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1875 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1876 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1877 reply->header.size = htons (tsize);
1878 reply->unique_id = GNUNET_htonll (uid);
1879 memcpy (&reply[1], message, msize);
1881 add_pending_message (client, pending_message);
1885 * Consider whether or not we would like to have this peer added to
1886 * our routing table. Check whether bucket for this peer is full,
1887 * if so return negative; if not return positive. Since peers are
1888 * only added on CORE level connect, this doesn't actually add the
1889 * peer to the routing table.
1891 * @param peer the peer we are considering adding
1893 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1896 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1900 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1901 return GNUNET_NO; /* We already know this peer (are connected even!) */
1902 bucket = find_current_bucket(&peer->hashPubKey);
1904 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1911 * Main function that handles whether or not to route a result
1912 * message to other peers, or to send to our local client.
1914 * @param cls closure (unused, always should be NULL)
1915 * @param msg the result message to be routed
1916 * @param message_context context of the message we are routing
1918 * @return the number of peers the message was routed to,
1919 * GNUNET_SYSERR on failure
1921 static int route_result_message(void *cls,
1922 struct GNUNET_MessageHeader *msg,
1923 struct DHT_MessageContext *message_context)
1925 struct GNUNET_PeerIdentity new_peer;
1926 struct DHTQueryRecord *record;
1927 struct DHTRouteSource *pos;
1928 struct PeerInfo *peer_info;
1929 const struct GNUNET_MessageHeader *hello_msg;
1931 increment_stats(STAT_RESULTS);
1933 * If a find peer result message is received and contains a valid
1934 * HELLO for another peer, offer it to the transport service.
1936 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1938 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1941 hello_msg = &msg[1];
1942 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1944 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1948 else /* We have a valid hello, and peer id stored in new_peer */
1950 find_peer_context.count++;
1951 increment_stats(STAT_FIND_PEER_REPLY);
1952 if (GNUNET_YES == consider_peer(&new_peer))
1954 increment_stats(STAT_HELLOS_PROVIDED);
1955 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1956 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1961 if (malicious_dropper == GNUNET_YES)
1964 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1966 if (record == NULL) /* No record of this message! */
1969 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1970 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1971 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1973 #if DEBUG_DHT_ROUTING
1974 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1976 dhtlog_handle->insert_route (NULL,
1977 message_context->unique_id,
1979 message_context->hop_count,
1982 &message_context->key,
1983 message_context->peer, NULL);
1986 if (message_context->bloom != NULL)
1988 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1989 message_context->bloom = NULL;
1997 #if STRICT_FORWARDING
1998 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2000 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2002 increment_stats("# find peer responses NOT forwarded (bloom match)");
2007 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2011 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2015 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2016 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2018 #if DEBUG_DHT_ROUTING
2019 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2021 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2022 message_context->hop_count,
2023 GNUNET_YES, &my_identity, &message_context->key,
2024 message_context->peer, NULL);
2027 increment_stats(STAT_RESULTS_TO_CLIENT);
2028 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2029 increment_stats(STAT_GET_REPLY);
2031 send_reply_to_client(pos->client, msg, message_context->unique_id);
2033 else /* Send to peer */
2035 peer_info = find_peer_by_id(&pos->source);
2036 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2042 if (message_context->bloom == NULL)
2043 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2044 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2045 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2048 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2049 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2050 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2052 #if DEBUG_DHT_ROUTING
2053 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2055 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2057 message_context->hop_count,
2058 GNUNET_NO, &my_identity, &message_context->key,
2059 message_context->peer, &pos->source);
2062 forward_result_message(cls, msg, peer_info, message_context);
2067 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2068 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2069 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2075 if (message_context->bloom != NULL)
2076 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2081 * Iterator for local get request results,
2083 * @param cls closure for iterator, a DatacacheGetContext
2084 * @param exp when does this value expire?
2085 * @param key the key this data is stored under
2086 * @param size the size of the data identified by key
2087 * @param data the actual data
2088 * @param type the type of the data
2090 * @return GNUNET_OK to continue iteration, anything else
2091 * to stop iteration.
2094 datacache_get_iterator (void *cls,
2095 struct GNUNET_TIME_Absolute exp,
2096 const GNUNET_HashCode * key,
2097 uint32_t size, const char *data, uint32_t type)
2099 struct DHT_MessageContext *msg_ctx = cls;
2100 struct DHT_MessageContext *new_msg_ctx;
2101 struct GNUNET_DHT_GetResultMessage *get_result;
2103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2106 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2107 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2109 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2110 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2111 get_result->header.size =
2112 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2113 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2114 get_result->type = htons (type);
2115 memcpy (&get_result[1], data, size);
2116 new_msg_ctx->peer = &my_identity;
2117 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2118 new_msg_ctx->hop_count = 0;
2119 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2120 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2121 increment_stats(STAT_GET_RESPONSE_START);
2122 route_result_message(cls, &get_result->header, new_msg_ctx);
2123 GNUNET_free(new_msg_ctx);
2124 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2125 // datacache_get_ctx->unique_id);
2126 GNUNET_free (get_result);
2132 * Server handler for all dht get requests, look for data,
2133 * if found, send response either to clients or other peers.
2135 * @param cls closure for service
2136 * @param msg the actual get message
2137 * @param message_context struct containing pertinent information about the get request
2139 * @return number of items found for GET request
2142 handle_dht_get (void *cls,
2143 const struct GNUNET_MessageHeader *msg,
2144 struct DHT_MessageContext *message_context)
2146 const struct GNUNET_DHT_GetMessage *get_msg;
2148 unsigned int results;
2150 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2151 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2157 get_type = ntohs (get_msg->type);
2159 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2160 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2161 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2162 message_context->unique_id);
2164 increment_stats(STAT_GETS);
2166 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2169 if (datacache != NULL)
2171 GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2172 &datacache_get_iterator, message_context);
2177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2178 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2179 results, "GET", message_context->unique_id);
2181 #if DEBUG_DHT_ROUTING
2182 if ((debug_routes) && (dhtlog_handle != NULL))
2184 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2185 message_context->hop_count, GNUNET_YES, &my_identity,
2186 &message_context->key);
2189 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2191 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2192 message_context->hop_count, GNUNET_YES,
2193 &my_identity, &message_context->key, message_context->peer,
2199 if (message_context->hop_count == 0) /* Locally initiated request */
2201 #if DEBUG_DHT_ROUTING
2202 if ((debug_routes) && (dhtlog_handle != NULL))
2204 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2205 message_context->hop_count, GNUNET_NO, &my_identity,
2206 &message_context->key);
2215 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2217 GNUNET_HashCode *key = cls;
2218 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2225 * Server handler for initiating local dht find peer requests
2227 * @param cls closure for service
2228 * @param find_msg the actual find peer message
2229 * @param message_context struct containing pertinent information about the request
2233 handle_dht_find_peer (void *cls,
2234 const struct GNUNET_MessageHeader *find_msg,
2235 struct DHT_MessageContext *message_context)
2237 struct GNUNET_MessageHeader *find_peer_result;
2238 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2239 struct DHT_MessageContext *new_msg_ctx;
2240 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2243 GNUNET_HashCode *recent_hash;
2244 struct GNUNET_MessageHeader *other_hello;
2245 size_t other_hello_size;
2246 struct GNUNET_PeerIdentity peer_id;
2248 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2249 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2250 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2253 other_hello_size = 0;
2254 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2256 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2257 other_hello = GNUNET_malloc(other_hello_size);
2258 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2259 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)))
2261 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2262 GNUNET_free(other_hello);
2265 #if FIND_PEER_WITH_HELLO
2266 if (GNUNET_YES == consider_peer(&peer_id))
2268 increment_stats(STAT_HELLOS_PROVIDED);
2269 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2270 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2273 else /* We don't want this peer! */
2279 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2280 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2281 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2282 ntohs (find_msg->size),
2283 sizeof (struct GNUNET_MessageHeader));
2285 if (my_hello == NULL)
2288 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2289 "`%s': Our HELLO is null, can't return.\n",
2292 GNUNET_free_non_null(other_hello);
2296 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2297 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2299 increment_stats(STAT_BLOOM_FIND_PEER);
2300 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2301 GNUNET_free_non_null(other_hello);
2302 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2304 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2306 #if RESTRICT_FIND_PEER
2309 * Ignore any find peer requests from a peer we have seen very recently.
2311 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! */
2313 increment_stats("# dht find peer requests ignored (recently seen!)");
2314 GNUNET_free_non_null(other_hello);
2319 * Use this check to only allow the peer to respond to find peer requests if
2320 * it would be beneficial to have the requesting peer in this peers routing
2321 * table. Can be used to thwart peers flooding the network with find peer
2322 * requests that we don't care about. However, if a new peer is joining
2323 * the network and has no other peers this is a problem (assume all buckets
2324 * full, no one will respond!).
2326 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2327 if (GNUNET_NO == consider_peer(&peer_id))
2329 increment_stats("# dht find peer requests ignored (do not need!)");
2330 GNUNET_free_non_null(other_hello);
2335 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2336 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2337 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2338 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2340 /* Simplistic find_peer functionality, always return our hello */
2341 hello_size = ntohs(my_hello->size);
2342 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2344 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2346 GNUNET_break_op (0);
2347 GNUNET_free_non_null(other_hello);
2351 find_peer_result = GNUNET_malloc (tsize);
2352 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2353 find_peer_result->size = htons (tsize);
2354 memcpy (&find_peer_result[1], my_hello, hello_size);
2356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2357 "`%s': Sending hello size %d to requesting peer.\n",
2360 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2361 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2362 new_msg_ctx->peer = &my_identity;
2363 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2364 new_msg_ctx->hop_count = 0;
2365 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2366 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2367 increment_stats(STAT_FIND_PEER_ANSWER);
2368 route_result_message(cls, find_peer_result, new_msg_ctx);
2369 GNUNET_free(new_msg_ctx);
2370 #if DEBUG_DHT_ROUTING
2371 if ((debug_routes) && (dhtlog_handle != NULL))
2373 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2374 message_context->hop_count, GNUNET_YES, &my_identity,
2375 &message_context->key);
2378 GNUNET_free_non_null(other_hello);
2379 GNUNET_free(find_peer_result);
2383 * Task used to republish data.
2384 * Forward declaration; function call loop.
2386 * @param cls closure (a struct RepublishContext)
2387 * @param tc runtime context for this task
2390 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2393 * Server handler for initiating local dht put requests
2395 * @param cls closure for service
2396 * @param msg the actual put message
2397 * @param message_context struct containing pertinent information about the request
2400 handle_dht_put (void *cls,
2401 const struct GNUNET_MessageHeader *msg,
2402 struct DHT_MessageContext *message_context)
2404 struct GNUNET_DHT_PutMessage *put_msg;
2408 struct RepublishContext *put_context;
2410 GNUNET_assert (ntohs (msg->size) >=
2411 sizeof (struct GNUNET_DHT_PutMessage));
2414 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2415 put_type = ntohs (put_msg->type);
2417 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2420 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2423 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2424 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2426 #if DEBUG_DHT_ROUTING
2427 if (message_context->hop_count == 0) /* Locally initiated request */
2429 if ((debug_routes) && (dhtlog_handle != NULL))
2431 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2432 message_context->hop_count, GNUNET_NO, &my_identity,
2433 &message_context->key);
2438 if (message_context->closest != GNUNET_YES)
2441 #if DEBUG_DHT_ROUTING
2442 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2444 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2445 message_context->hop_count, GNUNET_YES,
2446 &my_identity, &message_context->key, message_context->peer,
2450 if ((debug_routes) && (dhtlog_handle != NULL))
2452 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2453 message_context->hop_count, GNUNET_YES, &my_identity,
2454 &message_context->key);
2458 increment_stats(STAT_PUTS_INSERTED);
2459 if (datacache != NULL)
2461 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2462 (char *) &put_msg[1], put_type,
2463 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2465 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2467 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2468 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2469 put_context->type = put_type;
2470 GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
2474 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2475 "`%s:%s': %s request received, but have no datacache!\n",
2476 my_short_id, "DHT", "PUT");
2480 * Estimate the diameter of the network based
2481 * on how many buckets are currently in use.
2482 * Concept here is that the diameter of the network
2483 * is roughly the distance a message must travel in
2484 * order to reach its intended destination. Since
2485 * at each hop we expect to get one bit closer, and
2486 * we have one bit per bucket, the number of buckets
2487 * in use should be the largest number of hops for
2488 * a sucessful message. (of course, this assumes we
2489 * know all peers in the network!)
2491 * @return ballpark diameter figure
2493 static unsigned int estimate_diameter()
2495 return MAX_BUCKETS - lowest_bucket;
2499 * To how many peers should we (on average)
2500 * forward the request to obtain the desired
2501 * target_replication count (on average).
2503 * Always 0, 1 or 2 (don't send, send once, split)
2506 get_forward_count (unsigned int hop_count, size_t target_replication)
2509 double target_count;
2510 double random_probability;
2512 uint32_t random_value;
2514 unsigned int target_value;
2515 unsigned int diameter;
2518 * If we are behaving in strict kademlia mode, send multiple initial requests,
2519 * but then only send to 1 or 0 peers based strictly on the number of hops.
2521 if (strict_kademlia == GNUNET_YES)
2524 return DHT_KADEMLIA_REPLICATION;
2525 else if (hop_count < max_hops)
2531 /* FIXME: the smaller we think the network is the more lenient we should be for
2532 * routing right? The estimation below only works if we think we have reasonably
2533 * full routing tables, which for our RR topologies may not be the case!
2535 diameter = estimate_diameter ();
2536 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2539 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2540 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2541 "DHT", estimate_diameter(), lowest_bucket);
2545 else if (hop_count > max_hops)
2548 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2549 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2556 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2557 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2558 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2559 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2560 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2561 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2562 RAND_MAX)) / RAND_MAX;
2563 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2566 //while (target_value < target_count)
2567 if (target_value < target_count)
2568 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? */
2571 //if ((target_count + 1 - (double)target_value) > random_probability)
2572 if ((target_count) > random_probability)
2576 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2577 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));
2579 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2580 if (random_value < target_replication)
2583 return target_value;
2587 * Check whether my identity is closer than any known peers.
2588 * If a non-null bloomfilter is given, check if this is the closest
2589 * peer that hasn't already been routed to.
2591 * @param target hash code to check closeness to
2592 * @param bloom bloomfilter, exclude these entries from the decision
2594 * Return GNUNET_YES if node location is closest, GNUNET_NO
2598 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2604 struct PeerInfo *pos;
2605 unsigned int my_distance;
2607 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2610 bucket_num = find_current_bucket(target);
2612 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2613 my_distance = distance(&my_identity.hashPubKey, target);
2614 pos = k_buckets[bucket_num].head;
2616 while ((pos != NULL) && (count < bucket_size))
2618 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2621 continue; /* Skip already checked entries */
2624 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2625 if (other_bits > bits)
2627 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2629 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2631 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2638 GNUNET_GE_LOG (coreAPI->ectx,
2639 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2640 GNUNET_GE_BULK, "closest peer\n");
2641 printPeerBits (&closest);
2642 GNUNET_GE_LOG (coreAPI->ectx,
2643 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2644 GNUNET_GE_BULK, "me\n");
2645 printPeerBits (coreAPI->my_identity);
2646 GNUNET_GE_LOG (coreAPI->ectx,
2647 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2648 GNUNET_GE_BULK, "key\n");
2649 printKeyBits (target);
2650 GNUNET_GE_LOG (coreAPI->ectx,
2651 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2653 "closest peer inverse distance is %u, mine is %u\n",
2654 inverse_distance (target, &closest.hashPubKey),
2655 inverse_distance (target,
2656 &coreAPI->my_identity->hashPubKey));
2659 /* No peers closer, we are the closest! */
2665 * Return this peers adjusted value based on the convergence
2666 * function chosen. This is the key function for randomized
2667 * routing decisions.
2669 * @param target the key of the request
2670 * @param peer the peer we would like the value of
2671 * @param hops number of hops this message has already traveled
2673 * @return bit distance from target to peer raised to an exponent
2674 * adjusted based on the current routing convergence algorithm
2678 converge_distance (const GNUNET_HashCode *target,
2679 struct PeerInfo *peer,
2682 unsigned long long ret;
2683 unsigned int other_matching_bits;
2684 double converge_modifier = 0.0;
2685 double base_converge_modifier = .1;
2691 curr_max_hops = max_hops;
2693 curr_max_hops = (estimate_diameter() + 1) * 2;
2695 if (converge_modifier > 0)
2696 converge_modifier = converge_modifier * base_converge_modifier;
2699 converge_modifier = base_converge_modifier;
2700 base_converge_modifier = 0.0;
2703 GNUNET_assert(converge_modifier > 0);
2705 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2707 switch (converge_option)
2709 case DHT_CONVERGE_RANDOM:
2710 return 1; /* Always return 1, choose equally among all peers */
2711 case DHT_CONVERGE_LINEAR:
2712 calc_value = hops * curr_max_hops * converge_modifier;
2714 case DHT_CONVERGE_SQUARE:
2716 * Simple square based curve.
2718 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * converge_modifier));
2720 case DHT_CONVERGE_EXPONENTIAL:
2722 * Simple exponential curve.
2724 if (base_converge_modifier > 0)
2725 calc_value = (converge_modifier * hops * hops) / curr_max_hops;
2727 calc_value = (hops * hops) / curr_max_hops;
2733 /* Take the log (base 2) of the number of bits matching the other peer */
2734 exponent = log2(other_matching_bits);
2736 /* Check if we would overflow; our largest possible value is 2^64 */
2737 if (exponent * calc_value >= 64)
2740 /* Clear errno and all math exceptions */
2742 feclearexcept(FE_ALL_EXCEPT);
2743 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2744 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2747 if (0 != fetestexcept(FE_OVERFLOW))
2748 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2749 if (0 != fetestexcept(FE_INVALID))
2750 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2751 if (0 != fetestexcept(FE_UNDERFLOW))
2752 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2760 * Comparison function for two struct PeerInfo's
2761 * which have already had their matching bits to
2762 * some target calculated.
2764 * @param p1 a pointer pointer to a struct PeerInfo
2765 * @param p2 a pointer pointer to a struct PeerInfo
2767 * @return 0 if equidistant to target,
2768 * -1 if p1 is closer,
2772 compare_peers (const void *p1, const void *p2)
2774 struct PeerInfo **first = (struct PeerInfo **)p1;
2775 struct PeerInfo **second = (struct PeerInfo **)p2;
2777 if ((*first)->matching_bits > (*second)->matching_bits)
2779 if ((*first)->matching_bits < (*second)->matching_bits)
2787 * Select a peer from the routing table that would be a good routing
2788 * destination for sending a message for "target". The resulting peer
2789 * must not be in the set of blocked peers.<p>
2791 * Note that we should not ALWAYS select the closest peer to the
2792 * target, peers further away from the target should be chosen with
2793 * exponentially declining probability.
2795 * @param target the key we are selecting a peer to route to
2796 * @param bloom a bloomfilter containing entries this request has seen already
2798 * @return Peer to route to, or NULL on error
2800 static struct PeerInfo *
2801 select_peer (const GNUNET_HashCode * target,
2802 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2807 unsigned int offset;
2808 unsigned int my_matching_bits;
2810 struct PeerInfo *pos;
2811 struct PeerInfo *sorted_closest[bucket_size];
2812 unsigned long long temp_converge_distance;
2813 unsigned long long total_distance;
2814 unsigned long long selected;
2816 unsigned long long stats_total_distance;
2820 unsigned int distance;
2821 unsigned int largest_distance;
2822 struct PeerInfo *chosen;
2824 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
2827 if (strict_kademlia == GNUNET_YES)
2829 largest_distance = 0;
2831 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2833 pos = k_buckets[bc].head;
2835 while ((pos != NULL) && (count < bucket_size))
2837 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2838 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2840 distance = inverse_distance (target, &pos->id.hashPubKey);
2841 if (distance > largest_distance)
2844 largest_distance = distance;
2852 if ((largest_distance > 0) && (chosen != NULL))
2854 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2865 /* Three steps: order peers in closest bucket (most matching bits).
2866 * Then go over all LOWER buckets (matching same bits we do)
2867 * Then go over all HIGHER buckets (matching less then we do)
2870 closest_bucket = find_current_bucket(target);
2871 GNUNET_assert(closest_bucket >= lowest_bucket);
2872 pos = k_buckets[closest_bucket].head;
2874 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
2875 memset(sorted_closest, 0, sizeof(sorted_closest));
2876 /* Put any peers in the closest bucket in the sorting array */
2877 while ((pos != NULL) && (count < bucket_size))
2879 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2883 continue; /* Ignore bloomfiltered peers */
2885 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2886 sorted_closest[offset] = pos;
2892 /* Sort the peers in descending order */
2893 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
2895 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
2896 for (i = 0; i < offset; i++)
2898 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
2899 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
2900 break; /* Ignore bloomfiltered peers */
2901 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2902 total_distance += temp_converge_distance;
2904 break; /* overflow case */
2907 /* Now handle peers in lower buckets (matches same # of bits as target) */
2908 for (bc = lowest_bucket; bc < closest_bucket; bc++)
2910 pos = k_buckets[bc].head;
2912 while ((pos != NULL) && (count < bucket_size))
2914 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2918 continue; /* Ignore bloomfiltered peers */
2920 temp_converge_distance = converge_distance(target, pos, hops);
2921 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2922 total_distance += temp_converge_distance;
2924 break; /* overflow case */
2930 /* Now handle all the further away peers */
2931 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
2933 pos = k_buckets[bc].head;
2935 while ((pos != NULL) && (count < bucket_size))
2937 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2941 continue; /* Ignore bloomfiltered peers */
2943 temp_converge_distance = converge_distance(target, pos, hops);
2944 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2945 total_distance += temp_converge_distance;
2947 break; /* overflow case */
2953 if (total_distance == 0) /* No peers to select from! */
2955 increment_stats("# select_peer, total_distance == 0");
2959 #if DEBUG_DHT_ROUTING > 1
2962 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
2963 stats_total_distance = 0;
2964 for (i = 0; i < offset; i++)
2966 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
2967 break; /* Ignore bloomfiltered peers */
2968 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
2969 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
2970 stats_total_distance += temp_converge_distance;
2972 break; /* overflow case */
2973 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);
2976 /* Now handle peers in lower buckets (matches same # of bits as target) */
2977 for (bc = lowest_bucket; bc < closest_bucket; bc++)
2979 pos = k_buckets[bc].head;
2981 while ((pos != NULL) && (count < bucket_size))
2983 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2987 continue; /* Ignore bloomfiltered peers */
2989 temp_converge_distance = converge_distance(target, pos, hops);
2990 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
2991 stats_total_distance += temp_converge_distance;
2993 break; /* overflow case */
2994 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);
3000 /* Now handle all the further away peers */
3001 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3003 pos = k_buckets[bc].head;
3005 while ((pos != NULL) && (count < bucket_size))
3007 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3011 continue; /* Ignore bloomfiltered peers */
3013 temp_converge_distance = converge_distance(target, pos, hops);
3014 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3015 stats_total_distance += temp_converge_distance;
3017 break; /* overflow case */
3018 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);
3023 /* END PRINT STATS */
3026 /* Now actually choose a peer */
3027 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3029 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3030 for (i = 0; i < offset; i++)
3032 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3033 break; /* Ignore bloomfiltered peers */
3034 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3035 if (temp_converge_distance >= selected)
3036 return sorted_closest[i];
3038 selected -= temp_converge_distance;
3041 /* Now handle peers in lower buckets (matches same # of bits as target) */
3042 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3044 pos = k_buckets[bc].head;
3046 while ((pos != NULL) && (count < bucket_size))
3048 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3052 continue; /* Ignore bloomfiltered peers */
3054 temp_converge_distance = converge_distance(target, pos, hops);
3055 if (temp_converge_distance >= selected)
3058 selected -= temp_converge_distance;
3064 /* Now handle all the further away peers */
3065 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3067 pos = k_buckets[bc].head;
3069 while ((pos != NULL) && (count < bucket_size))
3071 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3075 continue; /* Ignore bloomfiltered peers */
3077 temp_converge_distance = converge_distance(target, pos, hops);
3078 if (temp_converge_distance >= selected)
3081 selected -= temp_converge_distance;
3087 increment_stats("# failed to select peer");
3093 * Task used to remove recent entries, either
3094 * after timeout, when full, or on shutdown.
3096 * @param cls the entry to remove
3097 * @param tc context, reason, etc.
3100 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3102 struct RecentRequest *req = cls;
3103 static GNUNET_HashCode hash;
3105 GNUNET_assert(req != NULL);
3106 hash_from_uid(req->uid, &hash);
3107 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3108 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3109 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3112 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3114 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3115 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3121 * Task used to remove forwarding entries, either
3122 * after timeout, when full, or on shutdown.
3124 * @param cls the entry to remove
3125 * @param tc context, reason, etc.
3128 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3130 struct DHTRouteSource *source_info = cls;
3131 struct DHTQueryRecord *record;
3132 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3133 record = source_info->record;
3134 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3136 if (record->head == NULL) /* No more entries in DLL */
3138 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3139 GNUNET_free(record);
3141 if (source_info->find_peers_responded != NULL)
3142 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3143 GNUNET_free(source_info);
3147 * Remember this routing request so that if a reply is
3148 * received we can either forward it to the correct peer
3149 * or return the result locally.
3151 * @param cls DHT service closure
3152 * @param msg_ctx Context of the route request
3154 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3156 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
3158 struct DHTQueryRecord *record;
3159 struct DHTRouteSource *source_info;
3160 struct DHTRouteSource *pos;
3161 struct GNUNET_TIME_Absolute now;
3162 unsigned int current_size;
3164 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3165 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3167 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3168 GNUNET_assert(source_info != NULL);
3169 record = source_info->record;
3170 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3171 if (record->head == NULL) /* No more entries in DLL */
3173 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3174 GNUNET_free(record);
3176 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
3177 if (source_info->find_peers_responded != NULL)
3178 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3179 GNUNET_free(source_info);
3180 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3182 now = GNUNET_TIME_absolute_get();
3183 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3184 if (record != NULL) /* Already know this request! */
3189 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3190 break; /* Already have this peer in reply list! */
3193 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3195 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3201 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3202 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3203 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3206 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3207 source_info->record = record;
3208 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3209 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3210 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3211 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3212 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3214 source_info->client = msg_ctx->client;
3215 now = GNUNET_TIME_absolute_get_forever();
3217 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3219 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3220 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3221 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
3228 * Main function that handles whether or not to route a message to other
3231 * @param cls closure for dht service (NULL)
3232 * @param msg the message to be routed
3233 * @param message_context the context containing all pertinent information about the message
3235 * @return the number of peers the message was routed to,
3236 * GNUNET_SYSERR on failure
3238 static int route_message(void *cls,
3239 const struct GNUNET_MessageHeader *msg,
3240 struct DHT_MessageContext *message_context)
3244 struct PeerInfo *selected;
3245 #if DEBUG_DHT_ROUTING > 1
3246 struct PeerInfo *nearest;
3248 unsigned int forward_count;
3249 struct RecentRequest *recent_req;
3250 GNUNET_HashCode unique_hash;
3251 char *stat_forward_count;
3252 char *temp_stat_str;
3253 #if DEBUG_DHT_ROUTING
3257 if (malicious_dropper == GNUNET_YES)
3259 #if DEBUG_DHT_ROUTING
3260 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3262 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3263 message_context->hop_count, GNUNET_SYSERR,
3264 &my_identity, &message_context->key, message_context->peer,
3268 if (message_context->bloom != NULL)
3269 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3273 increment_stats(STAT_ROUTES);
3274 /* Semantics of this call means we find whether we are the closest peer out of those already
3275 * routed to on this messages path.
3277 global_closest = am_closest_peer(&message_context->key, NULL);
3278 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3279 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3280 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3281 increment_stats(stat_forward_count);
3282 GNUNET_free(stat_forward_count);
3283 if (message_context->bloom == NULL)
3284 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3286 if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3290 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3291 * any closer peers (which is being checked for below). Since we are doing recursive
3292 * routing we have no choice but to stop forwarding in this case. This means that at
3293 * any given step the request may NOT be forwarded to alpha peers (because routes will
3294 * stop and the parallel route will not be aware of it). Of course, assuming that we
3295 * have fulfilled the Kademlia requirements for routing table fullness this will never
3296 * ever ever be a problem.
3298 * However, is this fair?
3300 * Since we use these requests to build our routing tables (and we build them in the
3301 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3302 * routing tables still get constructed.
3304 if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3307 #if DEBUG_DHT_ROUTING
3308 if (forward_count == 0)
3309 ret = GNUNET_SYSERR;
3313 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3315 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3316 message_context->hop_count, ret,
3317 &my_identity, &message_context->key, message_context->peer,
3322 switch (ntohs(msg->type))
3324 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3325 cache_response (cls, message_context);
3326 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3329 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3330 increment_stats(STAT_PUTS);
3331 message_context->closest = global_closest;
3332 handle_dht_put (cls, msg, message_context);
3334 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3335 increment_stats(STAT_FIND_PEER);
3336 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3338 cache_response (cls, message_context);
3339 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3340 handle_dht_find_peer (cls, msg, message_context);
3342 #if DEBUG_DHT_ROUTING
3343 if (message_context->hop_count == 0) /* Locally initiated request */
3345 if ((debug_routes) && (dhtlog_handle != NULL))
3347 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3348 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3349 message_context->hop_count, GNUNET_NO, &my_identity,
3350 &message_context->key);
3356 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3357 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3360 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3361 hash_from_uid (message_context->unique_id, &unique_hash);
3362 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3364 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3365 GNUNET_assert(recent_req != NULL);
3366 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3367 increment_stats(STAT_DUPLICATE_UID);
3370 increment_stats(STAT_RECENT_SEEN);
3371 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3376 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3377 recent_req->uid = message_context->unique_id;
3378 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3379 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3380 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3381 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3382 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3385 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3387 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3388 GNUNET_assert(recent_req != NULL);
3389 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3390 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3393 for (i = 0; i < forward_count; i++)
3395 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3397 if (selected != NULL)
3399 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
3400 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
3402 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
3403 if (temp_stat_str != NULL)
3405 increment_stats(temp_stat_str);
3406 GNUNET_free(temp_stat_str);
3408 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3409 #if DEBUG_DHT_ROUTING > 1
3410 nearest = find_closest_peer(&message_context->key);
3411 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3412 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3413 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3414 "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));
3415 GNUNET_free(nearest_buf);
3417 #if DEBUG_DHT_ROUTING
3418 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3420 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3421 message_context->hop_count, GNUNET_NO,
3422 &my_identity, &message_context->key, message_context->peer,
3426 forward_message(cls, msg, selected, message_context);
3430 if (message_context->bloom != NULL)
3432 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3433 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3436 return forward_count;
3440 * Iterator for local get request results,
3442 * @param cls closure for iterator, NULL
3443 * @param exp when does this value expire?
3444 * @param key the key this data is stored under
3445 * @param size the size of the data identified by key
3446 * @param data the actual data
3447 * @param type the type of the data
3449 * @return GNUNET_OK to continue iteration, anything else
3450 * to stop iteration.
3453 republish_content_iterator (void *cls,
3454 struct GNUNET_TIME_Absolute exp,
3455 const GNUNET_HashCode * key,
3456 uint32_t size, const char *data, uint32_t type)
3459 struct DHT_MessageContext *new_msg_ctx;
3460 struct GNUNET_DHT_PutMessage *put_msg;
3462 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3463 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3465 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3468 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3469 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3470 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3471 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3472 put_msg->type = htons (type);
3473 memcpy (&put_msg[1], data, size);
3474 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3475 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3476 new_msg_ctx->msg_options = ntohl (0);
3477 new_msg_ctx->network_size = estimate_diameter();
3478 new_msg_ctx->peer = &my_identity;
3479 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3480 new_msg_ctx->hop_count = 0;
3481 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3482 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3483 increment_stats(STAT_PUT_START);
3484 route_message(cls, &put_msg->header, new_msg_ctx);
3486 GNUNET_free(new_msg_ctx);
3487 GNUNET_free (put_msg);
3492 * Task used to republish data.
3494 * @param cls closure (a struct RepublishContext)
3495 * @param tc runtime context for this task
3498 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3500 struct RepublishContext *put_context = cls;
3502 unsigned int results;
3504 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3506 GNUNET_free(put_context);
3510 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3511 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3512 if (results == 0) /* Data must have expired */
3513 GNUNET_free(put_context);
3514 else /* Reschedule task for next time period */
3515 GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);
3520 * Find a client if it exists, add it otherwise.
3522 * @param client the server handle to the client
3524 * @return the client if found, a new client otherwise
3526 static struct ClientList *
3527 find_active_client (struct GNUNET_SERVER_Client *client)
3529 struct ClientList *pos = client_list;
3530 struct ClientList *ret;
3534 if (pos->client_handle == client)
3539 ret = GNUNET_malloc (sizeof (struct ClientList));
3540 ret->client_handle = client;
3541 ret->next = client_list;
3547 * Task to send a malicious put message across the network.
3549 * @param cls closure for this task
3550 * @param tc the context under which the task is running
3553 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3555 static struct GNUNET_DHT_PutMessage put_message;
3556 static struct DHT_MessageContext message_context;
3557 static GNUNET_HashCode key;
3558 uint32_t random_key;
3560 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3563 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3564 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3565 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3566 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3567 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3568 message_context.client = NULL;
3569 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3570 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3571 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3572 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3573 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3574 message_context.msg_options = ntohl (0);
3575 message_context.network_size = estimate_diameter();
3576 message_context.peer = &my_identity;
3577 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3578 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3579 #if DEBUG_DHT_ROUTING
3580 if (dhtlog_handle != NULL)
3581 dhtlog_handle->insert_dhtkey(NULL, &key);
3583 increment_stats(STAT_PUT_START);
3584 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3585 route_message(NULL, &put_message.header, &message_context);
3586 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3591 * Task to send a malicious put message across the network.
3593 * @param cls closure for this task
3594 * @param tc the context under which the task is running
3597 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3599 static struct GNUNET_DHT_GetMessage get_message;
3600 struct DHT_MessageContext message_context;
3601 static GNUNET_HashCode key;
3602 uint32_t random_key;
3604 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3607 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3608 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3609 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3610 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3611 message_context.client = NULL;
3612 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3613 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3614 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3615 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3616 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3617 message_context.msg_options = ntohl (0);
3618 message_context.network_size = estimate_diameter();
3619 message_context.peer = &my_identity;
3620 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3621 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3622 #if DEBUG_DHT_ROUTING
3623 if (dhtlog_handle != NULL)
3624 dhtlog_handle->insert_dhtkey(NULL, &key);
3626 increment_stats(STAT_GET_START);
3627 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3628 route_message (NULL, &get_message.header, &message_context);
3629 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3633 * Iterator over hash map entries.
3635 * @param cls closure
3636 * @param key current key code
3637 * @param value value in the hash map
3638 * @return GNUNET_YES if we should continue to
3643 add_known_to_bloom (void *cls,
3644 const GNUNET_HashCode * key,
3647 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3648 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3653 * Task to send a find peer message for our own peer identifier
3654 * so that we can find the closest peers in the network to ourselves
3655 * and attempt to connect to them.
3657 * @param cls closure for this task
3658 * @param tc the context under which the task is running
3661 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3663 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3664 struct DHT_MessageContext message_context;
3666 struct GNUNET_TIME_Relative next_send_time;
3667 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3669 struct GNUNET_TIME_Relative time_diff;
3670 struct GNUNET_TIME_Absolute end;
3672 double count_per_interval;
3674 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3677 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! */
3679 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3680 GNUNET_SCHEDULER_add_delayed (sched,
3681 GNUNET_TIME_UNIT_MINUTES,
3682 &send_find_peer_message, NULL);
3683 newly_found_peers = 0;
3687 increment_stats(STAT_FIND_PEER_START);
3689 end = GNUNET_TIME_absolute_get();
3690 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3692 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3694 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3695 count_per_interval = find_peer_context.count / multiplier;
3699 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3700 count_per_interval = find_peer_context.count * multiplier;
3704 #if FIND_PEER_WITH_HELLO
3705 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3706 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3707 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3709 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3710 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3712 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3713 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3714 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3715 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3716 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3717 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3718 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3719 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3720 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3721 message_context.network_size = estimate_diameter();
3722 message_context.peer = &my_identity;
3723 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3724 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3726 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3727 GNUNET_free(find_peer_msg);
3728 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3729 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3731 if (newly_found_peers < bucket_size)
3733 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3734 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3735 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3739 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3740 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3741 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3744 GNUNET_assert (next_send_time.value != 0);
3745 find_peer_context.count = 0;
3746 newly_found_peers = 0;
3747 find_peer_context.start = GNUNET_TIME_absolute_get();
3748 if (GNUNET_YES == do_find_peer)
3750 GNUNET_SCHEDULER_add_delayed (sched,
3752 &send_find_peer_message, NULL);
3757 * Handler for any generic DHT messages, calls the appropriate handler
3758 * depending on message type, sends confirmation if responses aren't otherwise
3761 * @param cls closure for the service
3762 * @param client the client we received this message from
3763 * @param message the actual message received
3766 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3767 const struct GNUNET_MessageHeader *message)
3769 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3770 const struct GNUNET_MessageHeader *enc_msg;
3771 struct DHT_MessageContext message_context;
3772 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3774 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3775 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3776 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3777 GNUNET_ntohll (dht_msg->unique_id));
3779 #if DEBUG_DHT_ROUTING
3780 if (dhtlog_handle != NULL)
3781 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3783 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3784 message_context.client = find_active_client (client);
3785 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3786 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3787 message_context.replication = ntohl (dht_msg->desired_replication_level);
3788 message_context.msg_options = ntohl (dht_msg->options);
3789 message_context.network_size = estimate_diameter();
3790 message_context.peer = &my_identity;
3791 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3792 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3793 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3794 increment_stats(STAT_GET_START);
3795 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3796 increment_stats(STAT_PUT_START);
3797 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3798 increment_stats(STAT_FIND_PEER_START);
3800 route_message(cls, enc_msg, &message_context);
3802 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3807 * Handler for any locally received DHT control messages,
3808 * sets malicious flags mostly for now.
3810 * @param cls closure for the service
3811 * @param client the client we received this message from
3812 * @param message the actual message received
3816 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3817 const struct GNUNET_MessageHeader *message)
3819 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3820 (const struct GNUNET_DHT_ControlMessage *) message;
3822 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3823 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3824 "CONTROL", ntohs(dht_control_msg->command));
3827 switch (ntohs(dht_control_msg->command))
3829 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3830 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3831 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3833 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3834 if (ntohs(dht_control_msg->variable) > 0)
3835 malicious_get_frequency = ntohs(dht_control_msg->variable);
3836 if (malicious_get_frequency == 0)
3837 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3838 if (malicious_getter != GNUNET_YES)
3839 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3840 malicious_getter = GNUNET_YES;
3841 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3843 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3844 if (ntohs(dht_control_msg->variable) > 0)
3845 malicious_put_frequency = ntohs(dht_control_msg->variable);
3846 if (malicious_put_frequency == 0)
3847 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3848 if (malicious_putter != GNUNET_YES)
3849 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3850 malicious_putter = GNUNET_YES;
3851 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3853 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3854 #if DEBUG_DHT_ROUTING
3855 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3856 dhtlog_handle->set_malicious(&my_identity);
3858 malicious_dropper = GNUNET_YES;
3859 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3862 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3865 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3869 * Handler for any generic DHT stop messages, calls the appropriate handler
3870 * depending on message type (if processed locally)
3872 * @param cls closure for the service
3873 * @param client the client we received this message from
3874 * @param message the actual message received
3878 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3879 const struct GNUNET_MessageHeader *message)
3882 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3883 (const struct GNUNET_DHT_StopMessage *) message;
3884 struct DHTQueryRecord *record;
3885 struct DHTRouteSource *pos;
3887 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3888 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3889 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3891 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3898 if ((pos->client != NULL) && (pos->client->client_handle == client))
3900 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3901 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3907 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3912 * Core handler for p2p route requests.
3915 handle_dht_p2p_route_request (void *cls,
3916 const struct GNUNET_PeerIdentity *peer,
3917 const struct GNUNET_MessageHeader *message,
3918 struct GNUNET_TIME_Relative latency, uint32_t distance)
3921 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3922 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3924 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3925 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3926 struct DHT_MessageContext *message_context;
3928 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
3930 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
3931 increment_stats("# route requests dropped due to high load");
3932 decrease_max_send_delay(get_max_send_delay());
3936 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3939 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3944 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
3949 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3950 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3951 GNUNET_assert(message_context->bloom != NULL);
3952 message_context->hop_count = ntohl(incoming->hop_count);
3953 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
3954 message_context->replication = ntohl(incoming->desired_replication_level);
3955 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3956 message_context->msg_options = ntohl(incoming->options);
3957 message_context->network_size = ntohl(incoming->network_size);
3958 message_context->peer = peer;
3959 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3960 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3961 route_message(cls, enc_msg, message_context);
3962 GNUNET_free(message_context);
3968 * Core handler for p2p route results.
3971 handle_dht_p2p_route_result (void *cls,
3972 const struct GNUNET_PeerIdentity *peer,
3973 const struct GNUNET_MessageHeader *message,
3974 struct GNUNET_TIME_Relative latency, uint32_t distance)
3977 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3978 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3980 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3981 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3982 struct DHT_MessageContext message_context;
3984 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
3990 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3991 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
3992 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3993 GNUNET_assert(message_context.bloom != NULL);
3994 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
3995 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3996 message_context.msg_options = ntohl(incoming->options);
3997 message_context.hop_count = ntohl(incoming->hop_count);
3998 message_context.peer = peer;
3999 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
4000 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4001 route_result_message(cls, enc_msg, &message_context);
4007 * Receive the HELLO from transport service,
4008 * free current and replace if necessary.
4011 * @param message HELLO message of peer
4014 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4017 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4018 "Received our `%s' from transport service\n",
4022 GNUNET_assert (message != NULL);
4023 GNUNET_free_non_null(my_hello);
4024 my_hello = GNUNET_malloc(ntohs(message->size));
4025 memcpy(my_hello, message, ntohs(message->size));
4030 * Task run during shutdown.
4036 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4039 struct PeerInfo *pos;
4040 if (transport_handle != NULL)
4042 GNUNET_free_non_null(my_hello);
4043 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4044 GNUNET_TRANSPORT_disconnect(transport_handle);
4047 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4049 while (k_buckets[bucket_count].head != NULL)
4051 pos = k_buckets[bucket_count].head;
4053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4054 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4056 delete_peer(pos, bucket_count);
4059 if (coreAPI != NULL)
4062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4063 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4065 GNUNET_CORE_disconnect (coreAPI);
4067 if (datacache != NULL)
4070 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4071 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4073 GNUNET_DATACACHE_destroy (datacache);
4078 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4081 if (dhtlog_handle != NULL)
4082 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4084 GNUNET_free_non_null(my_short_id);
4089 * To be called on core init/fail.
4091 * @param cls service closure
4092 * @param server handle to the server for this service
4093 * @param identity the public identity of this peer
4094 * @param publicKey the public key of this peer
4097 core_init (void *cls,
4098 struct GNUNET_CORE_Handle *server,
4099 const struct GNUNET_PeerIdentity *identity,
4100 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4106 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4107 "%s: Connection to core FAILED!\n", "dht",
4108 GNUNET_i2s (identity));
4110 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
4111 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
4115 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4116 "%s: Core connection initialized, I am peer: %s\n", "dht",
4117 GNUNET_i2s (identity));
4120 /* Copy our identity so we can use it */
4121 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4122 if (my_short_id != NULL)
4123 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4124 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4125 /* Set the server to local variable */
4128 if (dhtlog_handle != NULL)
4129 dhtlog_handle->insert_node (NULL, &my_identity);
4133 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4134 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4135 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4136 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4141 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4142 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4143 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4148 * Method called whenever a peer connects.
4150 * @param cls closure
4151 * @param peer peer identity this notification is about
4152 * @param latency reported latency of the connection with peer
4153 * @param distance reported distance (DV) to peer
4155 void handle_core_connect (void *cls,
4156 const struct GNUNET_PeerIdentity * peer,
4157 struct GNUNET_TIME_Relative latency,
4160 struct PeerInfo *ret;
4163 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4164 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4167 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4169 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));
4173 if (datacache != NULL)
4174 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
4175 ret = try_add_peer(peer,
4176 find_current_bucket(&peer->hashPubKey),
4181 newly_found_peers++;
4182 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4185 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4186 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4191 * Method called whenever a peer disconnects.
4193 * @param cls closure
4194 * @param peer peer identity this notification is about
4196 void handle_core_disconnect (void *cls,
4198 GNUNET_PeerIdentity * peer)
4200 struct PeerInfo *to_remove;
4203 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");
4205 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4207 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));
4210 increment_stats(STAT_DISCONNECTS);
4211 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4212 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4213 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4214 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4215 delete_peer(to_remove, current_bucket);
4219 * Process dht requests.
4221 * @param cls closure
4222 * @param scheduler scheduler to use
4223 * @param server the initialized server
4224 * @param c configuration to use
4228 struct GNUNET_SCHEDULER_Handle *scheduler,
4229 struct GNUNET_SERVER_Handle *server,
4230 const struct GNUNET_CONFIGURATION_Handle *c)
4232 struct GNUNET_TIME_Relative next_send_time;
4233 unsigned long long temp_config_num;
4234 char *converge_modifier_buf;
4237 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4238 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4239 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4240 cfg, /* Main configuration */
4241 GNUNET_TIME_UNIT_FOREVER_REL,
4242 NULL, /* Closure passed to DHT functions */
4243 &core_init, /* Call core_init once connected */
4244 &handle_core_connect, /* Handle connects */
4245 &handle_core_disconnect, /* remove peers on disconnects */
4246 NULL, /* Do we care about "status" updates? */
4247 NULL, /* Don't want notified about all incoming messages */
4248 GNUNET_NO, /* For header only inbound notification */
4249 NULL, /* Don't want notified about all outbound messages */
4250 GNUNET_NO, /* For header only outbound notification */
4251 core_handlers); /* Register these handlers */
4253 if (coreAPI == NULL)
4255 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
4256 NULL, NULL, NULL, NULL, NULL);
4257 if (transport_handle != NULL)
4258 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4260 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4262 lowest_bucket = MAX_BUCKETS - 1;
4263 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4264 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4265 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4266 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4267 GNUNET_assert(all_known_peers != NULL);
4268 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4270 debug_routes = GNUNET_YES;
4274 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4277 strict_kademlia = GNUNET_YES;
4281 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4284 stop_on_closest = GNUNET_YES;
4288 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4291 stop_on_found = GNUNET_YES;
4295 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4296 "malicious_getter"))
4298 malicious_getter = GNUNET_YES;
4299 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4300 "MALICIOUS_GET_FREQUENCY",
4301 &malicious_get_frequency))
4302 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4305 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4309 max_hops = DEFAULT_MAX_HOPS;
4312 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4315 use_max_hops = GNUNET_YES;
4319 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4320 "malicious_putter"))
4322 malicious_putter = GNUNET_YES;
4323 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4324 "MALICIOUS_PUT_FREQUENCY",
4325 &malicious_put_frequency))
4326 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4329 dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
4330 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4332 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4336 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4337 "malicious_dropper"))
4339 malicious_dropper = GNUNET_YES;
4343 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4345 do_republish = GNUNET_NO;
4348 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4351 do_find_peer = GNUNET_NO;
4354 do_find_peer = GNUNET_YES;
4357 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4358 "use_real_distance"))
4359 use_real_distance = GNUNET_YES;
4362 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4363 "mysql_logging_extended"))
4365 debug_routes = GNUNET_YES;
4366 debug_routes_extended = GNUNET_YES;
4369 #if DEBUG_DHT_ROUTING
4370 if (GNUNET_YES == debug_routes)
4372 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4373 if (dhtlog_handle == NULL)
4375 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4376 "Could not connect to mysql logging server, logging will not happen!");
4381 converge_option = DHT_CONVERGE_SQUARE;
4383 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4386 converge_option = DHT_CONVERGE_LINEAR;
4388 else if (GNUNET_YES ==
4389 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4390 "converge_exponential"))
4392 converge_option = DHT_CONVERGE_EXPONENTIAL;
4394 else if (GNUNET_YES ==
4395 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4398 converge_option = DHT_CONVERGE_RANDOM;
4401 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4403 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4405 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4406 converge_modifier = 0.0;
4408 GNUNET_free(converge_modifier_buf);
4411 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4415 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4416 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4417 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4418 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4419 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4420 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4421 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4422 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4423 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4424 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4425 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4426 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4427 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4428 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4429 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4430 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4431 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4432 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4433 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4434 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4436 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4437 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4438 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4439 if (GNUNET_YES == do_find_peer)
4441 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4442 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4443 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4444 find_peer_context.start = GNUNET_TIME_absolute_get();
4445 GNUNET_SCHEDULER_add_delayed (sched,
4447 &send_find_peer_message, &find_peer_context);
4450 /* Scheduled the task to clean up when shutdown is called */
4451 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4452 GNUNET_TIME_UNIT_FOREVER_REL,
4453 &shutdown_task, NULL);
4457 * The main function for the dht service.
4459 * @param argc number of arguments from the command line
4460 * @param argv command line arguments
4461 * @return 0 ok, 1 on error
4464 main (int argc, char *const *argv)
4466 return (GNUNET_OK ==
4467 GNUNET_SERVICE_run (argc,
4470 GNUNET_SERVICE_OPTION_NONE,
4471 &run, NULL)) ? 0 : 1;