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)
1774 client->transmit_handle =
1775 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1776 ntohs (client->pending_head->msg->
1778 GNUNET_TIME_UNIT_FOREVER_REL,
1779 &send_generic_reply, client);
1783 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1784 * request. A ClientList is passed as closure, take the head of the list
1785 * and copy it into buf, which has the result of sending the message to the
1788 * @param cls closure to this call
1789 * @param size maximum number of bytes available to send
1790 * @param buf where to copy the actual message to
1792 * @return the number of bytes actually copied, 0 indicates failure
1795 send_generic_reply (void *cls, size_t size, void *buf)
1797 struct ClientList *client = cls;
1799 struct PendingMessage *reply;
1803 client->transmit_handle = NULL;
1806 /* client disconnected */
1810 while ( (NULL != (reply = client->pending_head)) &&
1811 (size >= off + (msize = ntohs (reply->msg->size))))
1813 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1814 client->pending_tail,
1816 memcpy (&cbuf[off], reply->msg, msize);
1817 GNUNET_free (reply);
1820 process_pending_messages (client);
1826 * Add a PendingMessage to the clients list of messages to be sent
1828 * @param client the active client to send the message to
1829 * @param pending_message the actual message to send
1832 add_pending_message (struct ClientList *client,
1833 struct PendingMessage *pending_message)
1835 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1836 client->pending_tail,
1837 client->pending_tail,
1839 process_pending_messages (client);
1846 * Called when a reply needs to be sent to a client, as
1847 * a result it found to a GET or FIND PEER request.
1849 * @param client the client to send the reply to
1850 * @param message the encapsulated message to send
1851 * @param uid the unique identifier of this request
1854 send_reply_to_client (struct ClientList *client,
1855 const struct GNUNET_MessageHeader *message,
1856 unsigned long long uid)
1858 struct GNUNET_DHT_RouteResultMessage *reply;
1859 struct PendingMessage *pending_message;
1863 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1864 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1866 msize = ntohs (message->size);
1867 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1868 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1870 GNUNET_break_op (0);
1874 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1875 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1876 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1877 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1878 reply->header.size = htons (tsize);
1879 reply->unique_id = GNUNET_htonll (uid);
1880 memcpy (&reply[1], message, msize);
1882 add_pending_message (client, pending_message);
1886 * Consider whether or not we would like to have this peer added to
1887 * our routing table. Check whether bucket for this peer is full,
1888 * if so return negative; if not return positive. Since peers are
1889 * only added on CORE level connect, this doesn't actually add the
1890 * peer to the routing table.
1892 * @param peer the peer we are considering adding
1894 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1897 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1901 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1902 return GNUNET_NO; /* We already know this peer (are connected even!) */
1903 bucket = find_current_bucket(&peer->hashPubKey);
1905 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1912 * Main function that handles whether or not to route a result
1913 * message to other peers, or to send to our local client.
1915 * @param cls closure (unused, always should be NULL)
1916 * @param msg the result message to be routed
1917 * @param message_context context of the message we are routing
1919 * @return the number of peers the message was routed to,
1920 * GNUNET_SYSERR on failure
1922 static int route_result_message(void *cls,
1923 struct GNUNET_MessageHeader *msg,
1924 struct DHT_MessageContext *message_context)
1926 struct GNUNET_PeerIdentity new_peer;
1927 struct DHTQueryRecord *record;
1928 struct DHTRouteSource *pos;
1929 struct PeerInfo *peer_info;
1930 const struct GNUNET_MessageHeader *hello_msg;
1932 increment_stats(STAT_RESULTS);
1934 * If a find peer result message is received and contains a valid
1935 * HELLO for another peer, offer it to the transport service.
1937 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1939 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1942 hello_msg = &msg[1];
1943 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1945 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1949 else /* We have a valid hello, and peer id stored in new_peer */
1951 find_peer_context.count++;
1952 increment_stats(STAT_FIND_PEER_REPLY);
1953 if (GNUNET_YES == consider_peer(&new_peer))
1955 increment_stats(STAT_HELLOS_PROVIDED);
1956 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1957 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1962 if (malicious_dropper == GNUNET_YES)
1965 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1967 if (record == NULL) /* No record of this message! */
1970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1971 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1972 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1974 #if DEBUG_DHT_ROUTING
1975 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1977 dhtlog_handle->insert_route (NULL,
1978 message_context->unique_id,
1980 message_context->hop_count,
1983 &message_context->key,
1984 message_context->peer, NULL);
1987 if (message_context->bloom != NULL)
1989 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1990 message_context->bloom = NULL;
1998 #if STRICT_FORWARDING
1999 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2001 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2003 increment_stats("# find peer responses NOT forwarded (bloom match)");
2008 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2012 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2015 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2016 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2017 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2019 #if DEBUG_DHT_ROUTING
2020 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2022 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2023 message_context->hop_count,
2024 GNUNET_YES, &my_identity, &message_context->key,
2025 message_context->peer, NULL);
2028 increment_stats(STAT_RESULTS_TO_CLIENT);
2029 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2030 increment_stats(STAT_GET_REPLY);
2032 send_reply_to_client(pos->client, msg, message_context->unique_id);
2034 else /* Send to peer */
2036 peer_info = find_peer_by_id(&pos->source);
2037 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2043 if (message_context->bloom == NULL)
2044 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2045 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2046 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2049 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2050 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2051 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2053 #if DEBUG_DHT_ROUTING
2054 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2056 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2058 message_context->hop_count,
2059 GNUNET_NO, &my_identity, &message_context->key,
2060 message_context->peer, &pos->source);
2063 forward_result_message(cls, msg, peer_info, message_context);
2068 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2069 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2070 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2076 if (message_context->bloom != NULL)
2077 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2082 * Iterator for local get request results,
2084 * @param cls closure for iterator, a DatacacheGetContext
2085 * @param exp when does this value expire?
2086 * @param key the key this data is stored under
2087 * @param size the size of the data identified by key
2088 * @param data the actual data
2089 * @param type the type of the data
2091 * @return GNUNET_OK to continue iteration, anything else
2092 * to stop iteration.
2095 datacache_get_iterator (void *cls,
2096 struct GNUNET_TIME_Absolute exp,
2097 const GNUNET_HashCode * key,
2098 uint32_t size, const char *data, uint32_t type)
2100 struct DHT_MessageContext *msg_ctx = cls;
2101 struct DHT_MessageContext *new_msg_ctx;
2102 struct GNUNET_DHT_GetResultMessage *get_result;
2104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2105 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2107 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2108 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2110 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2111 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2112 get_result->header.size =
2113 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2114 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2115 get_result->type = htons (type);
2116 memcpy (&get_result[1], data, size);
2117 new_msg_ctx->peer = &my_identity;
2118 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2119 new_msg_ctx->hop_count = 0;
2120 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2121 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2122 increment_stats(STAT_GET_RESPONSE_START);
2123 route_result_message(cls, &get_result->header, new_msg_ctx);
2124 GNUNET_free(new_msg_ctx);
2125 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2126 // datacache_get_ctx->unique_id);
2127 GNUNET_free (get_result);
2133 * Server handler for all dht get requests, look for data,
2134 * if found, send response either to clients or other peers.
2136 * @param cls closure for service
2137 * @param msg the actual get message
2138 * @param message_context struct containing pertinent information about the get request
2140 * @return number of items found for GET request
2143 handle_dht_get (void *cls,
2144 const struct GNUNET_MessageHeader *msg,
2145 struct DHT_MessageContext *message_context)
2147 const struct GNUNET_DHT_GetMessage *get_msg;
2149 unsigned int results;
2151 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2152 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2158 get_type = ntohs (get_msg->type);
2160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2161 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2162 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2163 message_context->unique_id);
2165 increment_stats(STAT_GETS);
2167 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2170 if (datacache != NULL)
2172 GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2173 &datacache_get_iterator, message_context);
2178 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2179 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2180 results, "GET", message_context->unique_id);
2182 #if DEBUG_DHT_ROUTING
2183 if ((debug_routes) && (dhtlog_handle != NULL))
2185 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2186 message_context->hop_count, GNUNET_YES, &my_identity,
2187 &message_context->key);
2190 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2192 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2193 message_context->hop_count, GNUNET_YES,
2194 &my_identity, &message_context->key, message_context->peer,
2200 if (message_context->hop_count == 0) /* Locally initiated request */
2202 #if DEBUG_DHT_ROUTING
2203 if ((debug_routes) && (dhtlog_handle != NULL))
2205 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2206 message_context->hop_count, GNUNET_NO, &my_identity,
2207 &message_context->key);
2216 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2218 GNUNET_HashCode *key = cls;
2219 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2226 * Server handler for initiating local dht find peer requests
2228 * @param cls closure for service
2229 * @param find_msg the actual find peer message
2230 * @param message_context struct containing pertinent information about the request
2234 handle_dht_find_peer (void *cls,
2235 const struct GNUNET_MessageHeader *find_msg,
2236 struct DHT_MessageContext *message_context)
2238 struct GNUNET_MessageHeader *find_peer_result;
2239 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2240 struct DHT_MessageContext *new_msg_ctx;
2241 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2244 GNUNET_HashCode *recent_hash;
2245 struct GNUNET_MessageHeader *other_hello;
2246 size_t other_hello_size;
2247 struct GNUNET_PeerIdentity peer_id;
2249 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2250 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2251 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2254 other_hello_size = 0;
2255 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2257 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2258 other_hello = GNUNET_malloc(other_hello_size);
2259 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2260 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)))
2262 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2263 GNUNET_free(other_hello);
2266 #if FIND_PEER_WITH_HELLO
2267 if (GNUNET_YES == consider_peer(&peer_id))
2269 increment_stats(STAT_HELLOS_PROVIDED);
2270 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2271 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2274 else /* We don't want this peer! */
2280 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2281 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2282 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2283 ntohs (find_msg->size),
2284 sizeof (struct GNUNET_MessageHeader));
2286 if (my_hello == NULL)
2289 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2290 "`%s': Our HELLO is null, can't return.\n",
2293 GNUNET_free_non_null(other_hello);
2297 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2298 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2300 increment_stats(STAT_BLOOM_FIND_PEER);
2301 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2302 GNUNET_free_non_null(other_hello);
2303 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2305 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2307 #if RESTRICT_FIND_PEER
2310 * Ignore any find peer requests from a peer we have seen very recently.
2312 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! */
2314 increment_stats("# dht find peer requests ignored (recently seen!)");
2315 GNUNET_free_non_null(other_hello);
2320 * Use this check to only allow the peer to respond to find peer requests if
2321 * it would be beneficial to have the requesting peer in this peers routing
2322 * table. Can be used to thwart peers flooding the network with find peer
2323 * requests that we don't care about. However, if a new peer is joining
2324 * the network and has no other peers this is a problem (assume all buckets
2325 * full, no one will respond!).
2327 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2328 if (GNUNET_NO == consider_peer(&peer_id))
2330 increment_stats("# dht find peer requests ignored (do not need!)");
2331 GNUNET_free_non_null(other_hello);
2336 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2337 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2338 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2339 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2341 /* Simplistic find_peer functionality, always return our hello */
2342 hello_size = ntohs(my_hello->size);
2343 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2345 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2347 GNUNET_break_op (0);
2348 GNUNET_free_non_null(other_hello);
2352 find_peer_result = GNUNET_malloc (tsize);
2353 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2354 find_peer_result->size = htons (tsize);
2355 memcpy (&find_peer_result[1], my_hello, hello_size);
2357 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2358 "`%s': Sending hello size %d to requesting peer.\n",
2361 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2362 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2363 new_msg_ctx->peer = &my_identity;
2364 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2365 new_msg_ctx->hop_count = 0;
2366 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2367 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2368 increment_stats(STAT_FIND_PEER_ANSWER);
2369 route_result_message(cls, find_peer_result, new_msg_ctx);
2370 GNUNET_free(new_msg_ctx);
2371 #if DEBUG_DHT_ROUTING
2372 if ((debug_routes) && (dhtlog_handle != NULL))
2374 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2375 message_context->hop_count, GNUNET_YES, &my_identity,
2376 &message_context->key);
2379 GNUNET_free_non_null(other_hello);
2380 GNUNET_free(find_peer_result);
2384 * Task used to republish data.
2385 * Forward declaration; function call loop.
2387 * @param cls closure (a struct RepublishContext)
2388 * @param tc runtime context for this task
2391 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2394 * Server handler for initiating local dht put requests
2396 * @param cls closure for service
2397 * @param msg the actual put message
2398 * @param message_context struct containing pertinent information about the request
2401 handle_dht_put (void *cls,
2402 const struct GNUNET_MessageHeader *msg,
2403 struct DHT_MessageContext *message_context)
2405 struct GNUNET_DHT_PutMessage *put_msg;
2409 struct RepublishContext *put_context;
2411 GNUNET_assert (ntohs (msg->size) >=
2412 sizeof (struct GNUNET_DHT_PutMessage));
2415 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2416 put_type = ntohs (put_msg->type);
2418 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2421 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2424 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2425 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2427 #if DEBUG_DHT_ROUTING
2428 if (message_context->hop_count == 0) /* Locally initiated request */
2430 if ((debug_routes) && (dhtlog_handle != NULL))
2432 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2433 message_context->hop_count, GNUNET_NO, &my_identity,
2434 &message_context->key);
2439 if (message_context->closest != GNUNET_YES)
2442 #if DEBUG_DHT_ROUTING
2443 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2445 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2446 message_context->hop_count, GNUNET_YES,
2447 &my_identity, &message_context->key, message_context->peer,
2451 if ((debug_routes) && (dhtlog_handle != NULL))
2453 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2454 message_context->hop_count, GNUNET_YES, &my_identity,
2455 &message_context->key);
2459 increment_stats(STAT_PUTS_INSERTED);
2460 if (datacache != NULL)
2462 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2463 (char *) &put_msg[1], put_type,
2464 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2466 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2468 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2469 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2470 put_context->type = put_type;
2471 GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
2475 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2476 "`%s:%s': %s request received, but have no datacache!\n",
2477 my_short_id, "DHT", "PUT");
2481 * Estimate the diameter of the network based
2482 * on how many buckets are currently in use.
2483 * Concept here is that the diameter of the network
2484 * is roughly the distance a message must travel in
2485 * order to reach its intended destination. Since
2486 * at each hop we expect to get one bit closer, and
2487 * we have one bit per bucket, the number of buckets
2488 * in use should be the largest number of hops for
2489 * a sucessful message. (of course, this assumes we
2490 * know all peers in the network!)
2492 * @return ballpark diameter figure
2494 static unsigned int estimate_diameter()
2496 return MAX_BUCKETS - lowest_bucket;
2500 * To how many peers should we (on average)
2501 * forward the request to obtain the desired
2502 * target_replication count (on average).
2504 * Always 0, 1 or 2 (don't send, send once, split)
2507 get_forward_count (unsigned int hop_count, size_t target_replication)
2510 double target_count;
2511 double random_probability;
2513 uint32_t random_value;
2515 unsigned int target_value;
2516 unsigned int diameter;
2519 * If we are behaving in strict kademlia mode, send multiple initial requests,
2520 * but then only send to 1 or 0 peers based strictly on the number of hops.
2522 if (strict_kademlia == GNUNET_YES)
2525 return DHT_KADEMLIA_REPLICATION;
2526 else if (hop_count < max_hops)
2532 /* FIXME: the smaller we think the network is the more lenient we should be for
2533 * routing right? The estimation below only works if we think we have reasonably
2534 * full routing tables, which for our RR topologies may not be the case!
2536 diameter = estimate_diameter ();
2537 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2540 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2541 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2542 "DHT", estimate_diameter(), lowest_bucket);
2546 else if (hop_count > max_hops)
2549 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2550 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2557 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2558 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2559 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2560 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2561 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2562 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2563 RAND_MAX)) / RAND_MAX;
2564 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2567 //while (target_value < target_count)
2568 if (target_value < target_count)
2569 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? */
2572 //if ((target_count + 1 - (double)target_value) > random_probability)
2573 if ((target_count) > random_probability)
2577 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2578 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));
2580 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2581 if (random_value < target_replication)
2584 return target_value;
2588 * Check whether my identity is closer than any known peers.
2589 * If a non-null bloomfilter is given, check if this is the closest
2590 * peer that hasn't already been routed to.
2592 * @param target hash code to check closeness to
2593 * @param bloom bloomfilter, exclude these entries from the decision
2595 * Return GNUNET_YES if node location is closest, GNUNET_NO
2599 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2605 struct PeerInfo *pos;
2606 unsigned int my_distance;
2608 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2611 bucket_num = find_current_bucket(target);
2613 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2614 my_distance = distance(&my_identity.hashPubKey, target);
2615 pos = k_buckets[bucket_num].head;
2617 while ((pos != NULL) && (count < bucket_size))
2619 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2622 continue; /* Skip already checked entries */
2625 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2626 if (other_bits > bits)
2628 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2630 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2632 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2639 GNUNET_GE_LOG (coreAPI->ectx,
2640 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2641 GNUNET_GE_BULK, "closest peer\n");
2642 printPeerBits (&closest);
2643 GNUNET_GE_LOG (coreAPI->ectx,
2644 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2645 GNUNET_GE_BULK, "me\n");
2646 printPeerBits (coreAPI->my_identity);
2647 GNUNET_GE_LOG (coreAPI->ectx,
2648 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2649 GNUNET_GE_BULK, "key\n");
2650 printKeyBits (target);
2651 GNUNET_GE_LOG (coreAPI->ectx,
2652 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2654 "closest peer inverse distance is %u, mine is %u\n",
2655 inverse_distance (target, &closest.hashPubKey),
2656 inverse_distance (target,
2657 &coreAPI->my_identity->hashPubKey));
2660 /* No peers closer, we are the closest! */
2666 * Return this peers adjusted value based on the convergence
2667 * function chosen. This is the key function for randomized
2668 * routing decisions.
2670 * @param target the key of the request
2671 * @param peer the peer we would like the value of
2672 * @param hops number of hops this message has already traveled
2674 * @return bit distance from target to peer raised to an exponent
2675 * adjusted based on the current routing convergence algorithm
2679 converge_distance (const GNUNET_HashCode *target,
2680 struct PeerInfo *peer,
2683 unsigned long long ret;
2684 unsigned int other_matching_bits;
2685 double converge_modifier = 0.0;
2686 double base_converge_modifier = .1;
2692 curr_max_hops = max_hops;
2694 curr_max_hops = (estimate_diameter() + 1) * 2;
2696 if (converge_modifier > 0)
2697 converge_modifier = converge_modifier * base_converge_modifier;
2700 converge_modifier = base_converge_modifier;
2701 base_converge_modifier = 0.0;
2704 GNUNET_assert(converge_modifier > 0);
2706 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2708 switch (converge_option)
2710 case DHT_CONVERGE_RANDOM:
2711 return 1; /* Always return 1, choose equally among all peers */
2712 case DHT_CONVERGE_LINEAR:
2713 calc_value = hops * curr_max_hops * converge_modifier;
2715 case DHT_CONVERGE_SQUARE:
2717 * Simple square based curve.
2719 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * converge_modifier));
2721 case DHT_CONVERGE_EXPONENTIAL:
2723 * Simple exponential curve.
2725 if (base_converge_modifier > 0)
2726 calc_value = (converge_modifier * hops * hops) / curr_max_hops;
2728 calc_value = (hops * hops) / curr_max_hops;
2734 /* Take the log (base 2) of the number of bits matching the other peer */
2735 exponent = log2(other_matching_bits);
2737 /* Check if we would overflow; our largest possible value is 2^64 */
2738 if (exponent * calc_value >= 64)
2741 /* Clear errno and all math exceptions */
2743 feclearexcept(FE_ALL_EXCEPT);
2744 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2745 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2748 if (0 != fetestexcept(FE_OVERFLOW))
2749 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2750 if (0 != fetestexcept(FE_INVALID))
2751 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2752 if (0 != fetestexcept(FE_UNDERFLOW))
2753 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2761 * Comparison function for two struct PeerInfo's
2762 * which have already had their matching bits to
2763 * some target calculated.
2765 * @param p1 a pointer pointer to a struct PeerInfo
2766 * @param p2 a pointer pointer to a struct PeerInfo
2768 * @return 0 if equidistant to target,
2769 * -1 if p1 is closer,
2773 compare_peers (const void *p1, const void *p2)
2775 struct PeerInfo **first = (struct PeerInfo **)p1;
2776 struct PeerInfo **second = (struct PeerInfo **)p2;
2778 if ((*first)->matching_bits > (*second)->matching_bits)
2780 if ((*first)->matching_bits < (*second)->matching_bits)
2788 * Select a peer from the routing table that would be a good routing
2789 * destination for sending a message for "target". The resulting peer
2790 * must not be in the set of blocked peers.<p>
2792 * Note that we should not ALWAYS select the closest peer to the
2793 * target, peers further away from the target should be chosen with
2794 * exponentially declining probability.
2796 * @param target the key we are selecting a peer to route to
2797 * @param bloom a bloomfilter containing entries this request has seen already
2799 * @return Peer to route to, or NULL on error
2801 static struct PeerInfo *
2802 select_peer (const GNUNET_HashCode * target,
2803 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2808 unsigned int offset;
2809 unsigned int my_matching_bits;
2811 struct PeerInfo *pos;
2812 struct PeerInfo *sorted_closest[bucket_size];
2813 unsigned long long temp_converge_distance;
2814 unsigned long long total_distance;
2815 unsigned long long selected;
2817 unsigned long long stats_total_distance;
2821 unsigned int distance;
2822 unsigned int largest_distance;
2823 struct PeerInfo *chosen;
2825 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
2828 if (strict_kademlia == GNUNET_YES)
2830 largest_distance = 0;
2832 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2834 pos = k_buckets[bc].head;
2836 while ((pos != NULL) && (count < bucket_size))
2838 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2839 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2841 distance = inverse_distance (target, &pos->id.hashPubKey);
2842 if (distance > largest_distance)
2845 largest_distance = distance;
2853 if ((largest_distance > 0) && (chosen != NULL))
2855 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2866 /* Three steps: order peers in closest bucket (most matching bits).
2867 * Then go over all LOWER buckets (matching same bits we do)
2868 * Then go over all HIGHER buckets (matching less then we do)
2871 closest_bucket = find_current_bucket(target);
2872 GNUNET_assert(closest_bucket >= lowest_bucket);
2873 pos = k_buckets[closest_bucket].head;
2875 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
2876 memset(sorted_closest, 0, sizeof(sorted_closest));
2877 /* Put any peers in the closest bucket in the sorting array */
2878 while ((pos != NULL) && (count < bucket_size))
2880 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2884 continue; /* Ignore bloomfiltered peers */
2886 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2887 sorted_closest[offset] = pos;
2893 /* Sort the peers in descending order */
2894 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
2896 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
2897 for (i = 0; i < offset; i++)
2899 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
2900 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
2901 break; /* Ignore bloomfiltered peers */
2902 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2903 total_distance += temp_converge_distance;
2905 break; /* overflow case */
2908 /* Now handle peers in lower buckets (matches same # of bits as target) */
2909 for (bc = lowest_bucket; bc < closest_bucket; bc++)
2911 pos = k_buckets[bc].head;
2913 while ((pos != NULL) && (count < bucket_size))
2915 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2919 continue; /* Ignore bloomfiltered peers */
2921 temp_converge_distance = converge_distance(target, pos, hops);
2922 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2923 total_distance += temp_converge_distance;
2925 break; /* overflow case */
2931 /* Now handle all the further away peers */
2932 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
2934 pos = k_buckets[bc].head;
2936 while ((pos != NULL) && (count < bucket_size))
2938 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2942 continue; /* Ignore bloomfiltered peers */
2944 temp_converge_distance = converge_distance(target, pos, hops);
2945 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2946 total_distance += temp_converge_distance;
2948 break; /* overflow case */
2954 if (total_distance == 0) /* No peers to select from! */
2956 increment_stats("# select_peer, total_distance == 0");
2960 #if DEBUG_DHT_ROUTING > 1
2963 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
2964 stats_total_distance = 0;
2965 for (i = 0; i < offset; i++)
2967 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
2968 break; /* Ignore bloomfiltered peers */
2969 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
2970 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
2971 stats_total_distance += temp_converge_distance;
2973 break; /* overflow case */
2974 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);
2977 /* Now handle peers in lower buckets (matches same # of bits as target) */
2978 for (bc = lowest_bucket; bc < closest_bucket; bc++)
2980 pos = k_buckets[bc].head;
2982 while ((pos != NULL) && (count < bucket_size))
2984 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2988 continue; /* Ignore bloomfiltered peers */
2990 temp_converge_distance = converge_distance(target, pos, hops);
2991 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
2992 stats_total_distance += temp_converge_distance;
2994 break; /* overflow case */
2995 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);
3001 /* Now handle all the further away peers */
3002 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3004 pos = k_buckets[bc].head;
3006 while ((pos != NULL) && (count < bucket_size))
3008 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3012 continue; /* Ignore bloomfiltered peers */
3014 temp_converge_distance = converge_distance(target, pos, hops);
3015 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3016 stats_total_distance += temp_converge_distance;
3018 break; /* overflow case */
3019 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);
3024 /* END PRINT STATS */
3027 /* Now actually choose a peer */
3028 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3030 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3031 for (i = 0; i < offset; i++)
3033 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3034 break; /* Ignore bloomfiltered peers */
3035 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3036 if (temp_converge_distance >= selected)
3037 return sorted_closest[i];
3039 selected -= temp_converge_distance;
3042 /* Now handle peers in lower buckets (matches same # of bits as target) */
3043 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3045 pos = k_buckets[bc].head;
3047 while ((pos != NULL) && (count < bucket_size))
3049 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3053 continue; /* Ignore bloomfiltered peers */
3055 temp_converge_distance = converge_distance(target, pos, hops);
3056 if (temp_converge_distance >= selected)
3059 selected -= temp_converge_distance;
3065 /* Now handle all the further away peers */
3066 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3068 pos = k_buckets[bc].head;
3070 while ((pos != NULL) && (count < bucket_size))
3072 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3076 continue; /* Ignore bloomfiltered peers */
3078 temp_converge_distance = converge_distance(target, pos, hops);
3079 if (temp_converge_distance >= selected)
3082 selected -= temp_converge_distance;
3088 increment_stats("# failed to select peer");
3094 * Task used to remove recent entries, either
3095 * after timeout, when full, or on shutdown.
3097 * @param cls the entry to remove
3098 * @param tc context, reason, etc.
3101 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3103 struct RecentRequest *req = cls;
3104 static GNUNET_HashCode hash;
3106 GNUNET_assert(req != NULL);
3107 hash_from_uid(req->uid, &hash);
3108 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3109 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3110 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3113 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3115 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3116 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3122 * Task used to remove forwarding entries, either
3123 * after timeout, when full, or on shutdown.
3125 * @param cls the entry to remove
3126 * @param tc context, reason, etc.
3129 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3131 struct DHTRouteSource *source_info = cls;
3132 struct DHTQueryRecord *record;
3133 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3134 record = source_info->record;
3135 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3137 if (record->head == NULL) /* No more entries in DLL */
3139 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3140 GNUNET_free(record);
3142 if (source_info->find_peers_responded != NULL)
3143 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3144 GNUNET_free(source_info);
3148 * Remember this routing request so that if a reply is
3149 * received we can either forward it to the correct peer
3150 * or return the result locally.
3152 * @param cls DHT service closure
3153 * @param msg_ctx Context of the route request
3155 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3157 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
3159 struct DHTQueryRecord *record;
3160 struct DHTRouteSource *source_info;
3161 struct DHTRouteSource *pos;
3162 struct GNUNET_TIME_Absolute now;
3163 unsigned int current_size;
3165 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3166 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3168 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3169 GNUNET_assert(source_info != NULL);
3170 record = source_info->record;
3171 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3172 if (record->head == NULL) /* No more entries in DLL */
3174 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3175 GNUNET_free(record);
3177 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
3178 if (source_info->find_peers_responded != NULL)
3179 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3180 GNUNET_free(source_info);
3181 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3183 now = GNUNET_TIME_absolute_get();
3184 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3185 if (record != NULL) /* Already know this request! */
3190 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3191 break; /* Already have this peer in reply list! */
3194 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3196 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3202 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3203 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3204 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3207 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3208 source_info->record = record;
3209 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3210 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3211 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3212 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3213 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3215 source_info->client = msg_ctx->client;
3216 now = GNUNET_TIME_absolute_get_forever();
3218 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3220 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3221 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3222 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
3229 * Main function that handles whether or not to route a message to other
3232 * @param cls closure for dht service (NULL)
3233 * @param msg the message to be routed
3234 * @param message_context the context containing all pertinent information about the message
3236 * @return the number of peers the message was routed to,
3237 * GNUNET_SYSERR on failure
3239 static int route_message(void *cls,
3240 const struct GNUNET_MessageHeader *msg,
3241 struct DHT_MessageContext *message_context)
3245 struct PeerInfo *selected;
3246 #if DEBUG_DHT_ROUTING > 1
3247 struct PeerInfo *nearest;
3249 unsigned int forward_count;
3250 struct RecentRequest *recent_req;
3251 GNUNET_HashCode unique_hash;
3252 char *stat_forward_count;
3253 char *temp_stat_str;
3254 #if DEBUG_DHT_ROUTING
3258 if (malicious_dropper == GNUNET_YES)
3260 #if DEBUG_DHT_ROUTING
3261 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3263 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3264 message_context->hop_count, GNUNET_SYSERR,
3265 &my_identity, &message_context->key, message_context->peer,
3269 if (message_context->bloom != NULL)
3270 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3274 increment_stats(STAT_ROUTES);
3275 /* Semantics of this call means we find whether we are the closest peer out of those already
3276 * routed to on this messages path.
3278 global_closest = am_closest_peer(&message_context->key, NULL);
3279 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3280 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3281 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3282 increment_stats(stat_forward_count);
3283 GNUNET_free(stat_forward_count);
3284 if (message_context->bloom == NULL)
3285 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3287 if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3291 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3292 * any closer peers (which is being checked for below). Since we are doing recursive
3293 * routing we have no choice but to stop forwarding in this case. This means that at
3294 * any given step the request may NOT be forwarded to alpha peers (because routes will
3295 * stop and the parallel route will not be aware of it). Of course, assuming that we
3296 * have fulfilled the Kademlia requirements for routing table fullness this will never
3297 * ever ever be a problem.
3299 * However, is this fair?
3301 * Since we use these requests to build our routing tables (and we build them in the
3302 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3303 * routing tables still get constructed.
3305 if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3308 #if DEBUG_DHT_ROUTING
3309 if (forward_count == 0)
3310 ret = GNUNET_SYSERR;
3314 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3316 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3317 message_context->hop_count, ret,
3318 &my_identity, &message_context->key, message_context->peer,
3323 switch (ntohs(msg->type))
3325 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3326 cache_response (cls, message_context);
3327 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3330 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3331 increment_stats(STAT_PUTS);
3332 message_context->closest = global_closest;
3333 handle_dht_put (cls, msg, message_context);
3335 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3336 increment_stats(STAT_FIND_PEER);
3337 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3339 cache_response (cls, message_context);
3340 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3341 handle_dht_find_peer (cls, msg, message_context);
3343 #if DEBUG_DHT_ROUTING
3344 if (message_context->hop_count == 0) /* Locally initiated request */
3346 if ((debug_routes) && (dhtlog_handle != NULL))
3348 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3349 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3350 message_context->hop_count, GNUNET_NO, &my_identity,
3351 &message_context->key);
3357 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3358 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3361 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3362 hash_from_uid (message_context->unique_id, &unique_hash);
3363 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3365 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3366 GNUNET_assert(recent_req != NULL);
3367 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3368 increment_stats(STAT_DUPLICATE_UID);
3371 increment_stats(STAT_RECENT_SEEN);
3372 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3377 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3378 recent_req->uid = message_context->unique_id;
3379 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3380 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3381 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3382 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3383 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3386 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3388 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3389 GNUNET_assert(recent_req != NULL);
3390 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3391 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3394 for (i = 0; i < forward_count; i++)
3396 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3398 if (selected != NULL)
3400 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
3401 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
3403 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
3404 if (temp_stat_str != NULL)
3406 increment_stats(temp_stat_str);
3407 GNUNET_free(temp_stat_str);
3409 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3410 #if DEBUG_DHT_ROUTING > 1
3411 nearest = find_closest_peer(&message_context->key);
3412 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3413 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3414 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3415 "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));
3416 GNUNET_free(nearest_buf);
3418 #if DEBUG_DHT_ROUTING
3419 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3421 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3422 message_context->hop_count, GNUNET_NO,
3423 &my_identity, &message_context->key, message_context->peer,
3427 forward_message(cls, msg, selected, message_context);
3431 if (message_context->bloom != NULL)
3433 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3434 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3437 return forward_count;
3441 * Iterator for local get request results,
3443 * @param cls closure for iterator, NULL
3444 * @param exp when does this value expire?
3445 * @param key the key this data is stored under
3446 * @param size the size of the data identified by key
3447 * @param data the actual data
3448 * @param type the type of the data
3450 * @return GNUNET_OK to continue iteration, anything else
3451 * to stop iteration.
3454 republish_content_iterator (void *cls,
3455 struct GNUNET_TIME_Absolute exp,
3456 const GNUNET_HashCode * key,
3457 uint32_t size, const char *data, uint32_t type)
3460 struct DHT_MessageContext *new_msg_ctx;
3461 struct GNUNET_DHT_PutMessage *put_msg;
3463 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3464 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3466 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3469 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3470 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3471 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3472 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3473 put_msg->type = htons (type);
3474 memcpy (&put_msg[1], data, size);
3475 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3476 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3477 new_msg_ctx->msg_options = ntohl (0);
3478 new_msg_ctx->network_size = estimate_diameter();
3479 new_msg_ctx->peer = &my_identity;
3480 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3481 new_msg_ctx->hop_count = 0;
3482 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3483 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3484 increment_stats(STAT_PUT_START);
3485 route_message(cls, &put_msg->header, new_msg_ctx);
3487 GNUNET_free(new_msg_ctx);
3488 GNUNET_free (put_msg);
3493 * Task used to republish data.
3495 * @param cls closure (a struct RepublishContext)
3496 * @param tc runtime context for this task
3499 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3501 struct RepublishContext *put_context = cls;
3503 unsigned int results;
3505 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3507 GNUNET_free(put_context);
3511 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3512 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3513 if (results == 0) /* Data must have expired */
3514 GNUNET_free(put_context);
3515 else /* Reschedule task for next time period */
3516 GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);
3522 * Iterator over hash map entries.
3524 * @param cls client to search for in source routes
3525 * @param key current key code (ignored)
3526 * @param value value in the hash map, a DHTQueryRecord
3527 * @return GNUNET_YES if we should continue to
3531 static int find_client_records (void *cls,
3532 const GNUNET_HashCode * key, void *value)
3534 struct ClientList *client = cls;
3535 struct DHTQueryRecord *record = value;
3536 struct DHTRouteSource *pos;
3540 if (pos->client == client)
3546 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3547 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3548 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3549 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3551 if (pos->find_peers_responded != NULL)
3552 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3555 if (record->head == NULL) /* No more entries in DLL */
3557 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3558 GNUNET_free(record);
3564 * Functions with this signature are called whenever a client
3565 * is disconnected on the network level.
3567 * @param cls closure (NULL for dht)
3568 * @param client identification of the client; NULL
3569 * for the last call when the server is destroyed
3571 static void handle_client_disconnect (void *cls,
3572 struct GNUNET_SERVER_Client* client)
3574 struct ClientList *pos = client_list;
3575 struct ClientList *prev;
3576 struct ClientList *found;
3577 struct PendingMessage *reply;
3583 if (pos->client_handle == client)
3586 prev->next = pos->next;
3588 client_list = pos->next;
3598 while(NULL != (reply = found->pending_head))
3600 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3603 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3609 * Find a client if it exists, add it otherwise.
3611 * @param client the server handle to the client
3613 * @return the client if found, a new client otherwise
3615 static struct ClientList *
3616 find_active_client (struct GNUNET_SERVER_Client *client)
3618 struct ClientList *pos = client_list;
3619 struct ClientList *ret;
3623 if (pos->client_handle == client)
3628 ret = GNUNET_malloc (sizeof (struct ClientList));
3629 ret->client_handle = client;
3630 ret->next = client_list;
3637 * Task to send a malicious put message across the network.
3639 * @param cls closure for this task
3640 * @param tc the context under which the task is running
3643 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3645 static struct GNUNET_DHT_PutMessage put_message;
3646 static struct DHT_MessageContext message_context;
3647 static GNUNET_HashCode key;
3648 uint32_t random_key;
3650 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3653 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3654 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3655 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3656 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3657 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3658 message_context.client = NULL;
3659 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3660 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3661 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3662 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3663 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3664 message_context.msg_options = ntohl (0);
3665 message_context.network_size = estimate_diameter();
3666 message_context.peer = &my_identity;
3667 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3668 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3669 #if DEBUG_DHT_ROUTING
3670 if (dhtlog_handle != NULL)
3671 dhtlog_handle->insert_dhtkey(NULL, &key);
3673 increment_stats(STAT_PUT_START);
3674 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3675 route_message(NULL, &put_message.header, &message_context);
3676 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3681 * Task to send a malicious put message across the network.
3683 * @param cls closure for this task
3684 * @param tc the context under which the task is running
3687 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3689 static struct GNUNET_DHT_GetMessage get_message;
3690 struct DHT_MessageContext message_context;
3691 static GNUNET_HashCode key;
3692 uint32_t random_key;
3694 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3697 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3698 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3699 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3700 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3701 message_context.client = NULL;
3702 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3703 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3704 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3705 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3706 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3707 message_context.msg_options = ntohl (0);
3708 message_context.network_size = estimate_diameter();
3709 message_context.peer = &my_identity;
3710 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3711 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3712 #if DEBUG_DHT_ROUTING
3713 if (dhtlog_handle != NULL)
3714 dhtlog_handle->insert_dhtkey(NULL, &key);
3716 increment_stats(STAT_GET_START);
3717 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3718 route_message (NULL, &get_message.header, &message_context);
3719 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3723 * Iterator over hash map entries.
3725 * @param cls closure
3726 * @param key current key code
3727 * @param value value in the hash map
3728 * @return GNUNET_YES if we should continue to
3733 add_known_to_bloom (void *cls,
3734 const GNUNET_HashCode * key,
3737 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3738 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3743 * Task to send a find peer message for our own peer identifier
3744 * so that we can find the closest peers in the network to ourselves
3745 * and attempt to connect to them.
3747 * @param cls closure for this task
3748 * @param tc the context under which the task is running
3751 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3753 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3754 struct DHT_MessageContext message_context;
3756 struct GNUNET_TIME_Relative next_send_time;
3757 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3759 struct GNUNET_TIME_Relative time_diff;
3760 struct GNUNET_TIME_Absolute end;
3762 double count_per_interval;
3764 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3767 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! */
3769 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3770 GNUNET_SCHEDULER_add_delayed (sched,
3771 GNUNET_TIME_UNIT_MINUTES,
3772 &send_find_peer_message, NULL);
3773 newly_found_peers = 0;
3777 increment_stats(STAT_FIND_PEER_START);
3779 end = GNUNET_TIME_absolute_get();
3780 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3782 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3784 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3785 count_per_interval = find_peer_context.count / multiplier;
3789 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3790 count_per_interval = find_peer_context.count * multiplier;
3794 #if FIND_PEER_WITH_HELLO
3795 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3796 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3797 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3799 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3800 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3802 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3803 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3804 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3805 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3806 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3807 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3808 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3809 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3810 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3811 message_context.network_size = estimate_diameter();
3812 message_context.peer = &my_identity;
3813 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3814 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3816 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3817 GNUNET_free(find_peer_msg);
3818 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3819 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3821 if (newly_found_peers < bucket_size)
3823 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3824 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3825 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3829 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3830 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3831 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3834 GNUNET_assert (next_send_time.value != 0);
3835 find_peer_context.count = 0;
3836 newly_found_peers = 0;
3837 find_peer_context.start = GNUNET_TIME_absolute_get();
3838 if (GNUNET_YES == do_find_peer)
3840 GNUNET_SCHEDULER_add_delayed (sched,
3842 &send_find_peer_message, NULL);
3847 * Handler for any generic DHT messages, calls the appropriate handler
3848 * depending on message type, sends confirmation if responses aren't otherwise
3851 * @param cls closure for the service
3852 * @param client the client we received this message from
3853 * @param message the actual message received
3856 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3857 const struct GNUNET_MessageHeader *message)
3859 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3860 const struct GNUNET_MessageHeader *enc_msg;
3861 struct DHT_MessageContext message_context;
3862 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3864 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3865 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3866 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3867 GNUNET_ntohll (dht_msg->unique_id));
3869 #if DEBUG_DHT_ROUTING
3870 if (dhtlog_handle != NULL)
3871 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3873 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3874 message_context.client = find_active_client (client);
3875 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3876 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3877 message_context.replication = ntohl (dht_msg->desired_replication_level);
3878 message_context.msg_options = ntohl (dht_msg->options);
3879 message_context.network_size = estimate_diameter();
3880 message_context.peer = &my_identity;
3881 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3882 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3883 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3884 increment_stats(STAT_GET_START);
3885 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3886 increment_stats(STAT_PUT_START);
3887 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3888 increment_stats(STAT_FIND_PEER_START);
3890 route_message(cls, enc_msg, &message_context);
3892 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3897 * Handler for any locally received DHT control messages,
3898 * sets malicious flags mostly for now.
3900 * @param cls closure for the service
3901 * @param client the client we received this message from
3902 * @param message the actual message received
3906 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3907 const struct GNUNET_MessageHeader *message)
3909 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3910 (const struct GNUNET_DHT_ControlMessage *) message;
3912 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3913 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3914 "CONTROL", ntohs(dht_control_msg->command));
3917 switch (ntohs(dht_control_msg->command))
3919 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3920 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3921 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3923 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3924 if (ntohs(dht_control_msg->variable) > 0)
3925 malicious_get_frequency = ntohs(dht_control_msg->variable);
3926 if (malicious_get_frequency == 0)
3927 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3928 if (malicious_getter != GNUNET_YES)
3929 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3930 malicious_getter = GNUNET_YES;
3931 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3933 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3934 if (ntohs(dht_control_msg->variable) > 0)
3935 malicious_put_frequency = ntohs(dht_control_msg->variable);
3936 if (malicious_put_frequency == 0)
3937 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3938 if (malicious_putter != GNUNET_YES)
3939 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3940 malicious_putter = GNUNET_YES;
3941 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3943 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3944 #if DEBUG_DHT_ROUTING
3945 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3946 dhtlog_handle->set_malicious(&my_identity);
3948 malicious_dropper = GNUNET_YES;
3949 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3952 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3955 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3959 * Handler for any generic DHT stop messages, calls the appropriate handler
3960 * depending on message type (if processed locally)
3962 * @param cls closure for the service
3963 * @param client the client we received this message from
3964 * @param message the actual message received
3968 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3969 const struct GNUNET_MessageHeader *message)
3972 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3973 (const struct GNUNET_DHT_StopMessage *) message;
3974 struct DHTQueryRecord *record;
3975 struct DHTRouteSource *pos;
3977 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3978 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3979 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3981 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3988 if ((pos->client != NULL) && (pos->client->client_handle == client))
3990 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3991 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3997 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4002 * Core handler for p2p route requests.
4005 handle_dht_p2p_route_request (void *cls,
4006 const struct GNUNET_PeerIdentity *peer,
4007 const struct GNUNET_MessageHeader *message,
4008 struct GNUNET_TIME_Relative latency, uint32_t distance)
4011 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4012 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4014 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4015 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4016 struct DHT_MessageContext *message_context;
4018 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
4020 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
4021 increment_stats("# route requests dropped due to high load");
4022 decrease_max_send_delay(get_max_send_delay());
4026 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4029 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4034 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4039 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4040 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4041 GNUNET_assert(message_context->bloom != NULL);
4042 message_context->hop_count = ntohl(incoming->hop_count);
4043 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
4044 message_context->replication = ntohl(incoming->desired_replication_level);
4045 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
4046 message_context->msg_options = ntohl(incoming->options);
4047 message_context->network_size = ntohl(incoming->network_size);
4048 message_context->peer = peer;
4049 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4050 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4051 route_message(cls, enc_msg, message_context);
4052 GNUNET_free(message_context);
4058 * Core handler for p2p route results.
4061 handle_dht_p2p_route_result (void *cls,
4062 const struct GNUNET_PeerIdentity *peer,
4063 const struct GNUNET_MessageHeader *message,
4064 struct GNUNET_TIME_Relative latency, uint32_t distance)
4067 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4068 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4070 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4071 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4072 struct DHT_MessageContext message_context;
4074 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4080 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4081 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4082 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4083 GNUNET_assert(message_context.bloom != NULL);
4084 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
4085 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
4086 message_context.msg_options = ntohl(incoming->options);
4087 message_context.hop_count = ntohl(incoming->hop_count);
4088 message_context.peer = peer;
4089 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
4090 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4091 route_result_message(cls, enc_msg, &message_context);
4097 * Receive the HELLO from transport service,
4098 * free current and replace if necessary.
4101 * @param message HELLO message of peer
4104 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4107 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4108 "Received our `%s' from transport service\n",
4112 GNUNET_assert (message != NULL);
4113 GNUNET_free_non_null(my_hello);
4114 my_hello = GNUNET_malloc(ntohs(message->size));
4115 memcpy(my_hello, message, ntohs(message->size));
4120 * Task run during shutdown.
4126 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4129 struct PeerInfo *pos;
4130 if (transport_handle != NULL)
4132 GNUNET_free_non_null(my_hello);
4133 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4134 GNUNET_TRANSPORT_disconnect(transport_handle);
4137 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4139 while (k_buckets[bucket_count].head != NULL)
4141 pos = k_buckets[bucket_count].head;
4143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4144 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4146 delete_peer(pos, bucket_count);
4149 if (coreAPI != NULL)
4152 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4153 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4155 GNUNET_CORE_disconnect (coreAPI);
4157 if (datacache != NULL)
4160 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4161 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4163 GNUNET_DATACACHE_destroy (datacache);
4168 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4171 if (dhtlog_handle != NULL)
4172 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4174 GNUNET_free_non_null(my_short_id);
4179 * To be called on core init/fail.
4181 * @param cls service closure
4182 * @param server handle to the server for this service
4183 * @param identity the public identity of this peer
4184 * @param publicKey the public key of this peer
4187 core_init (void *cls,
4188 struct GNUNET_CORE_Handle *server,
4189 const struct GNUNET_PeerIdentity *identity,
4190 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4196 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4197 "%s: Connection to core FAILED!\n", "dht",
4198 GNUNET_i2s (identity));
4200 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
4201 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
4205 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4206 "%s: Core connection initialized, I am peer: %s\n", "dht",
4207 GNUNET_i2s (identity));
4210 /* Copy our identity so we can use it */
4211 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4212 if (my_short_id != NULL)
4213 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4214 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4215 /* Set the server to local variable */
4218 if (dhtlog_handle != NULL)
4219 dhtlog_handle->insert_node (NULL, &my_identity);
4223 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4224 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4225 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4226 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4231 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4232 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4233 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4238 * Method called whenever a peer connects.
4240 * @param cls closure
4241 * @param peer peer identity this notification is about
4242 * @param latency reported latency of the connection with peer
4243 * @param distance reported distance (DV) to peer
4245 void handle_core_connect (void *cls,
4246 const struct GNUNET_PeerIdentity * peer,
4247 struct GNUNET_TIME_Relative latency,
4250 struct PeerInfo *ret;
4253 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4254 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4257 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4259 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));
4263 if (datacache != NULL)
4264 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
4265 ret = try_add_peer(peer,
4266 find_current_bucket(&peer->hashPubKey),
4271 newly_found_peers++;
4272 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4276 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4281 * Method called whenever a peer disconnects.
4283 * @param cls closure
4284 * @param peer peer identity this notification is about
4286 void handle_core_disconnect (void *cls,
4288 GNUNET_PeerIdentity * peer)
4290 struct PeerInfo *to_remove;
4293 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");
4295 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4297 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));
4300 increment_stats(STAT_DISCONNECTS);
4301 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4302 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4303 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4304 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4305 delete_peer(to_remove, current_bucket);
4309 * Process dht requests.
4311 * @param cls closure
4312 * @param scheduler scheduler to use
4313 * @param server the initialized server
4314 * @param c configuration to use
4318 struct GNUNET_SCHEDULER_Handle *scheduler,
4319 struct GNUNET_SERVER_Handle *server,
4320 const struct GNUNET_CONFIGURATION_Handle *c)
4322 struct GNUNET_TIME_Relative next_send_time;
4323 unsigned long long temp_config_num;
4324 char *converge_modifier_buf;
4327 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4328 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4329 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4330 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4331 cfg, /* Main configuration */
4332 GNUNET_TIME_UNIT_FOREVER_REL,
4333 NULL, /* Closure passed to DHT functions */
4334 &core_init, /* Call core_init once connected */
4335 &handle_core_connect, /* Handle connects */
4336 &handle_core_disconnect, /* remove peers on disconnects */
4337 NULL, /* Do we care about "status" updates? */
4338 NULL, /* Don't want notified about all incoming messages */
4339 GNUNET_NO, /* For header only inbound notification */
4340 NULL, /* Don't want notified about all outbound messages */
4341 GNUNET_NO, /* For header only outbound notification */
4342 core_handlers); /* Register these handlers */
4344 if (coreAPI == NULL)
4346 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
4347 NULL, NULL, NULL, NULL, NULL);
4348 if (transport_handle != NULL)
4349 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4351 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4353 lowest_bucket = MAX_BUCKETS - 1;
4354 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4355 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4356 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4357 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4358 GNUNET_assert(all_known_peers != NULL);
4359 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4361 debug_routes = GNUNET_YES;
4365 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4368 strict_kademlia = GNUNET_YES;
4372 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4375 stop_on_closest = GNUNET_YES;
4379 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4382 stop_on_found = GNUNET_YES;
4386 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4387 "malicious_getter"))
4389 malicious_getter = GNUNET_YES;
4390 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4391 "MALICIOUS_GET_FREQUENCY",
4392 &malicious_get_frequency))
4393 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4396 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4400 max_hops = DEFAULT_MAX_HOPS;
4403 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4406 use_max_hops = GNUNET_YES;
4410 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4411 "malicious_putter"))
4413 malicious_putter = GNUNET_YES;
4414 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4415 "MALICIOUS_PUT_FREQUENCY",
4416 &malicious_put_frequency))
4417 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4420 dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
4421 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4423 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4427 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4428 "malicious_dropper"))
4430 malicious_dropper = GNUNET_YES;
4434 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4436 do_republish = GNUNET_NO;
4439 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4442 do_find_peer = GNUNET_NO;
4445 do_find_peer = GNUNET_YES;
4448 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4449 "use_real_distance"))
4450 use_real_distance = GNUNET_YES;
4453 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4454 "mysql_logging_extended"))
4456 debug_routes = GNUNET_YES;
4457 debug_routes_extended = GNUNET_YES;
4460 #if DEBUG_DHT_ROUTING
4461 if (GNUNET_YES == debug_routes)
4463 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4464 if (dhtlog_handle == NULL)
4466 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4467 "Could not connect to mysql logging server, logging will not happen!");
4472 converge_option = DHT_CONVERGE_SQUARE;
4474 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4477 converge_option = DHT_CONVERGE_LINEAR;
4479 else if (GNUNET_YES ==
4480 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4481 "converge_exponential"))
4483 converge_option = DHT_CONVERGE_EXPONENTIAL;
4485 else if (GNUNET_YES ==
4486 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4489 converge_option = DHT_CONVERGE_RANDOM;
4492 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4494 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4496 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4497 converge_modifier = 0.0;
4499 GNUNET_free(converge_modifier_buf);
4502 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4506 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4507 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4508 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4509 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4510 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4511 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4512 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4513 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4514 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4515 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4516 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4517 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4518 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4519 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4520 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4521 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4522 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4523 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4524 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4525 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4527 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4528 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4529 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4530 if (GNUNET_YES == do_find_peer)
4532 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4533 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4534 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4535 find_peer_context.start = GNUNET_TIME_absolute_get();
4536 GNUNET_SCHEDULER_add_delayed (sched,
4538 &send_find_peer_message, &find_peer_context);
4541 /* Scheduled the task to clean up when shutdown is called */
4542 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4543 GNUNET_TIME_UNIT_FOREVER_REL,
4544 &shutdown_task, NULL);
4548 * The main function for the dht service.
4550 * @param argc number of arguments from the command line
4551 * @param argv command line arguments
4552 * @return 0 ok, 1 on error
4555 main (int argc, char *const *argv)
4557 return (GNUNET_OK ==
4558 GNUNET_SERVICE_run (argc,
4561 GNUNET_SERVICE_OPTION_NONE,
4562 &run, NULL)) ? 0 : 1;