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
53 * How many buckets will we allow total.
55 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
58 * Should the DHT issue FIND_PEER requests to get better routing tables?
60 #define DEFAULT_DO_FIND_PEER GNUNET_YES
63 * Defines whether find peer requests send their HELLO's outgoing,
64 * or expect replies to contain hellos.
66 #define FIND_PEER_WITH_HELLO GNUNET_YES
69 * What is the maximum number of peers in a given bucket.
71 #define DEFAULT_BUCKET_SIZE 4
74 * Minimum number of peers we need for "good" routing,
75 * any less than this and we will allow messages to
76 * travel much further through the network!
78 #define MINIMUM_PEER_THRESHOLD 20
80 #define DHT_MAX_RECENT 1000
82 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
85 * Default time to wait to send messages on behalf of other peers.
87 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
90 * Default importance for handling messages on behalf of other peers.
92 #define DHT_DEFAULT_P2P_IMPORTANCE 0
95 * How long to keep recent requests around by default.
97 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
100 * Default time to wait to send find peer messages sent by the dht service.
102 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
105 * Default importance for find peer messages sent by the dht service.
107 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
110 * Default replication parameter for find peer messages sent by the dht service.
112 #define DHT_DEFAULT_PUT_REPLICATION 4
115 * Default replication parameter for find peer messages sent by the dht service.
117 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
120 * Default options for find peer requests sent by the dht service.
122 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
123 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
126 * How long at least to wait before sending another find peer request.
128 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
131 * How long at most to wait before sending another find peer request.
133 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
136 * How often to update our preference levels for peers in our routing tables.
138 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
141 * How long at most on average will we allow a reply forward to take
142 * (before we quit sending out new requests)
144 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
147 * How many initial requests to send out (in true Kademlia fashion)
149 #define DHT_KADEMLIA_REPLICATION 3
152 * Default frequency for sending malicious get messages
154 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
157 * Default frequency for sending malicious put messages
159 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
162 * Type for a malicious request, so we can ignore it during testing
164 #define DHT_MALICIOUS_MESSAGE_TYPE 42
166 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
169 * Real maximum number of hops, at which point we refuse
170 * to forward the message.
172 #define DEFAULT_MAX_HOPS 10
175 * How many time differences between requesting a core send and
176 * the actual callback to remember.
178 #define MAX_REPLY_TIMES 8
180 enum ConvergenceOptions
183 * Use the linear method for convergence.
188 * Converge using a fast converging square
194 * Converge using a slower exponential
197 DHT_CONVERGE_EXPONENTIAL,
200 * Don't do any special convergence, allow
201 * the algorithm to hopefully route to closer
208 * Linked list of messages to send to clients.
210 struct P2PPendingMessage
213 * Pointer to next item in the list
215 struct P2PPendingMessage *next;
218 * Pointer to previous item in the list
220 struct P2PPendingMessage *prev;
223 * Message importance level.
225 unsigned int importance;
228 * Time when this request was scheduled to be sent.
230 struct GNUNET_TIME_Absolute scheduled;
233 * How long to wait before sending message.
235 struct GNUNET_TIME_Relative timeout;
238 * Actual message to be sent; // avoid allocation
240 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
245 * Per-peer information.
250 * Next peer entry (DLL)
252 struct PeerInfo *next;
255 * Prev peer entry (DLL)
257 struct PeerInfo *prev;
260 * Head of pending messages to be sent to this peer.
262 struct P2PPendingMessage *head;
265 * Tail of pending messages to be sent to this peer.
267 struct P2PPendingMessage *tail;
270 * Core handle for sending messages to this peer.
272 struct GNUNET_CORE_TransmitHandle *th;
275 * Task for scheduling message sends.
277 GNUNET_SCHEDULER_TaskIdentifier send_task;
280 * Task for scheduling preference updates
282 GNUNET_SCHEDULER_TaskIdentifier preference_task;
285 * Preference update context
287 struct GNUNET_CORE_InformationRequestContext *info_ctx;
290 * What is the average latency for replies received?
292 struct GNUNET_TIME_Relative latency;
295 * What is the identity of the peer?
297 struct GNUNET_PeerIdentity id;
300 * Transport level distance to peer.
302 unsigned int distance;
305 * Holds matching bits from peer to current target,
306 * used for distance comparisons between peers. May
307 * be considered a really bad idea.
308 * FIXME: remove this value (create struct which holds
309 * a single peerinfo and the matching bits, use
310 * that to pass to comparitor)
312 unsigned int matching_bits;
315 * Task for scheduling periodic ping messages for this peer.
317 GNUNET_SCHEDULER_TaskIdentifier ping_task;
321 * Peers are grouped into buckets.
328 struct PeerInfo *head;
333 struct PeerInfo *tail;
336 * Number of peers in the bucket.
338 unsigned int peers_size;
342 * Linked list of messages to send to clients.
344 struct PendingMessage
347 * Pointer to next item in the list
349 struct PendingMessage *next;
352 * Pointer to previous item in the list
354 struct PendingMessage *prev;
357 * Actual message to be sent; // avoid allocation
359 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
364 * Struct containing information about a client,
365 * handle to connect to it, and any pending messages
366 * that need to be sent to it.
371 * Linked list of active clients
373 struct ClientList *next;
376 * The handle to this client
378 struct GNUNET_SERVER_Client *client_handle;
381 * Handle to the current transmission request, NULL
384 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
387 * Linked list of pending messages for this client
389 struct PendingMessage *pending_head;
392 * Tail of linked list of pending messages for this client
394 struct PendingMessage *pending_tail;
399 * Context containing information about a DHT message received.
401 struct DHT_MessageContext
404 * The client this request was received from.
405 * (NULL if received from another peer)
407 struct ClientList *client;
410 * The peer this request was received from.
411 * (NULL if received from local client)
413 const struct GNUNET_PeerIdentity *peer;
416 * The key this request was about
421 * The unique identifier of this request
426 * Desired replication level
428 uint32_t replication;
431 * Network size estimate, either ours or the sum of
432 * those routed to thus far. =~ Log of number of peers
433 * chosen from for this request.
435 uint32_t network_size;
438 * Any message options for this request
440 uint32_t msg_options;
443 * How many hops has the message already traversed?
448 * How important is this message?
450 unsigned int importance;
453 * How long should we wait to transmit this request?
455 struct GNUNET_TIME_Relative timeout;
458 * Bloomfilter for this routing request.
460 struct GNUNET_CONTAINER_BloomFilter *bloom;
463 * Did we forward this message? (may need to remember it!)
468 * Are we the closest known peer to this key (out of our neighbors?)
474 * Record used for remembering what peers are waiting for what
475 * responses (based on search key).
477 struct DHTRouteSource
482 struct DHTRouteSource *next;
487 struct DHTRouteSource *prev;
490 * Source of the request. Replies should be forwarded to
493 struct GNUNET_PeerIdentity source;
496 * If this was a local request, remember the client; otherwise NULL.
498 struct ClientList *client;
501 * Pointer to this nodes heap location (for removal)
503 struct GNUNET_CONTAINER_HeapNode *hnode;
506 * Back pointer to the record storing this information.
508 struct DHTQueryRecord *record;
511 * Task to remove this entry on timeout.
513 GNUNET_SCHEDULER_TaskIdentifier delete_task;
516 * Bloomfilter of peers we have already sent back as
517 * replies to the initial request. Allows us to not
518 * forward the same peer multiple times for a find peer
521 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
526 * Entry in the DHT routing table.
528 struct DHTQueryRecord
531 * Head of DLL for result forwarding.
533 struct DHTRouteSource *head;
536 * Tail of DLL for result forwarding.
538 struct DHTRouteSource *tail;
541 * Key that the record concerns.
546 * GET message of this record (what we already forwarded?).
548 //DV_DHT_MESSAGE get; Try to get away with not saving this.
551 * Bloomfilter of the peers we've replied to so far
553 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
558 * Context used to calculate the number of find peer messages
559 * per X time units since our last scheduled find peer message
560 * was sent. If we have seen too many messages, delay or don't
563 struct FindPeerMessageContext
567 struct GNUNET_TIME_Absolute start;
569 struct GNUNET_TIME_Absolute end;
573 * DHT Routing results structure
578 * Min heap for removal upon reaching limit
580 struct GNUNET_CONTAINER_Heap *minHeap;
583 * Hashmap for fast key based lookup
585 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
590 * DHT structure for recent requests.
592 struct RecentRequests
595 * Min heap for removal upon reaching limit
597 struct GNUNET_CONTAINER_Heap *minHeap;
600 * Hashmap for key based lookup
602 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
608 * Position of this node in the min heap.
610 struct GNUNET_CONTAINER_HeapNode *heap_node;
613 * Bloomfilter containing entries for peers
614 * we forwarded this request to.
616 struct GNUNET_CONTAINER_BloomFilter *bloom;
619 * Timestamp of this request, for ordering
622 struct GNUNET_TIME_Absolute timestamp;
625 * Key of this request.
630 * Unique identifier for this request.
635 * Task to remove this entry on timeout.
637 GNUNET_SCHEDULER_TaskIdentifier remove_task;
640 struct RepublishContext
655 * Which kind of convergence will we be using?
657 enum ConvergenceOptions converge_option;
660 * Modifier for the convergence function
662 float converge_modifier;
665 * Recent requests by hash/uid and by time inserted.
667 static struct RecentRequests recent;
670 * Context to use to calculate find peer rates.
672 static struct FindPeerMessageContext find_peer_context;
675 * Don't use our routing algorithm, always route
676 * to closest peer; initially send requests to 3
679 static unsigned int strict_kademlia;
682 * Routing option to end routing when closest peer found.
684 static unsigned int stop_on_closest;
687 * Routing option to end routing when data is found.
689 static unsigned int stop_on_found;
692 * Whether DHT needs to manage find peer requests, or
693 * an external force will do it on behalf of the DHT.
695 static unsigned int do_find_peer;
698 * Once we have stored an item in the DHT, refresh it
699 * according to our republish interval.
701 static unsigned int do_republish;
704 * Use the "real" distance metric when selecting the
705 * next routing hop. Can be less accurate.
707 static unsigned int use_real_distance;
710 * How many peers have we added since we sent out our last
713 static unsigned int newly_found_peers;
716 * Container of active queries we should remember
718 static struct DHTResults forward_list;
721 * Handle to the datacache service (for inserting/retrieving data)
723 static struct GNUNET_DATACACHE_Handle *datacache;
726 * Handle for the statistics service.
728 struct GNUNET_STATISTICS_Handle *stats;
731 * The main scheduler to use for the DHT service
733 static struct GNUNET_SCHEDULER_Handle *sched;
736 * The configuration the DHT service is running with
738 static const struct GNUNET_CONFIGURATION_Handle *cfg;
741 * Handle to the core service
743 static struct GNUNET_CORE_Handle *coreAPI;
746 * Handle to the transport service, for getting our hello
748 static struct GNUNET_TRANSPORT_Handle *transport_handle;
751 * The identity of our peer.
753 static struct GNUNET_PeerIdentity my_identity;
756 * Short id of the peer, for printing
758 static char *my_short_id;
763 static struct GNUNET_MessageHeader *my_hello;
766 * Task to run when we shut down, cleaning up all our trash
768 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
771 * The lowest currently used bucket.
773 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
776 * The maximum number of hops before we stop routing messages.
778 static unsigned long long max_hops;
781 * How often to republish content we have previously stored.
783 static struct GNUNET_TIME_Relative dht_republish_frequency;
786 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
788 static int use_max_hops;
791 * The buckets (Kademlia routing table, complete with growth).
792 * Array of size MAX_BUCKET_SIZE.
794 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
797 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
799 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
802 * Recently seen find peer requests.
804 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
807 * Maximum size for each bucket.
809 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
812 * List of active clients.
814 static struct ClientList *client_list;
817 * Handle to the DHT logger.
819 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
822 * Whether or not to send routing debugging information
823 * to the dht logging server
825 static unsigned int debug_routes;
828 * Whether or not to send FULL route information to
831 static unsigned int debug_routes_extended;
834 * GNUNET_YES or GNUNET_NO, whether or not to act as
835 * a malicious node which drops all messages
837 static unsigned int malicious_dropper;
840 * GNUNET_YES or GNUNET_NO, whether or not to act as
841 * a malicious node which sends out lots of GETS
843 static unsigned int malicious_getter;
846 * GNUNET_YES or GNUNET_NO, whether or not to act as
847 * a malicious node which sends out lots of PUTS
849 static unsigned int malicious_putter;
852 * Frequency for malicious get requests.
854 static unsigned long long malicious_get_frequency;
857 * Frequency for malicious put requests.
859 static unsigned long long malicious_put_frequency;
862 * Reply times for requests, if we are busy, don't send any
865 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
868 * Current counter for replies.
870 static unsigned int reply_counter;
873 * Forward declaration.
875 static size_t send_generic_reply (void *cls, size_t size, void *buf);
877 /** Declare here so retry_core_send is aware of it */
878 size_t core_transmit_notify (void *cls,
879 size_t size, void *buf);
882 * Convert unique ID to hash code.
884 * @param uid unique ID to convert
885 * @param hash set to uid (extended with zeros)
888 hash_from_uid (uint64_t uid,
889 GNUNET_HashCode *hash)
891 memset (hash, 0, sizeof(GNUNET_HashCode));
892 *((uint64_t*)hash) = uid;
897 * Calculate the average send time between messages so that we can
898 * ignore certain requests if we get too busy.
900 * @return the average time between asking core to send a message
901 * and when the buffer for copying it is passed
903 static struct GNUNET_TIME_Relative get_average_send_delay()
906 unsigned int divisor;
907 struct GNUNET_TIME_Relative average_time;
908 average_time = GNUNET_TIME_relative_get_zero();
910 for (i = 0; i < MAX_REPLY_TIMES; i++)
912 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
913 if (reply_times[i].value == (uint64_t)0)
923 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
924 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
930 * Given the largest send delay, artificially decrease it
931 * so the next time around we may have a chance at sending
934 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
937 for (i = 0; i < MAX_REPLY_TIMES; i++)
939 if (reply_times[i].value == max_time.value)
941 reply_times[i].value = reply_times[i].value / 2;
948 * Find the maximum send time of the recently sent values.
950 * @return the average time between asking core to send a message
951 * and when the buffer for copying it is passed
953 static struct GNUNET_TIME_Relative get_max_send_delay()
956 struct GNUNET_TIME_Relative max_time;
957 max_time = GNUNET_TIME_relative_get_zero();
959 for (i = 0; i < MAX_REPLY_TIMES; i++)
961 if (reply_times[i].value > max_time.value)
962 max_time.value = reply_times[i].value;
965 if (max_time.value > MAX_REQUEST_TIME.value)
966 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
971 increment_stats(const char *value)
975 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
980 * Try to send another message from our core send list
983 try_core_send (void *cls,
984 const struct GNUNET_SCHEDULER_TaskContext *tc)
986 struct PeerInfo *peer = cls;
987 struct P2PPendingMessage *pending;
990 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
992 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
995 if (peer->th != NULL)
996 return; /* Message send already in progress */
998 pending = peer->head;
1001 ssize = ntohs(pending->msg->size);
1003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1004 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
1005 "DHT", ssize, GNUNET_i2s(&peer->id));
1007 pending->scheduled = GNUNET_TIME_absolute_get();
1009 if (reply_counter >= MAX_REPLY_TIMES)
1011 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
1012 pending->timeout, &peer->id,
1013 ssize, &core_transmit_notify, peer);
1018 * Function called to send a request out to another peer.
1019 * Called both for locally initiated requests and those
1020 * received from other peers.
1022 * @param cls DHT service closure argument
1023 * @param msg the encapsulated message
1024 * @param peer the peer to forward the message to
1025 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1027 static void forward_result_message (void *cls,
1028 const struct GNUNET_MessageHeader *msg,
1029 struct PeerInfo *peer,
1030 struct DHT_MessageContext *msg_ctx)
1032 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1033 struct P2PPendingMessage *pending;
1037 increment_stats(STAT_RESULT_FORWARDS);
1038 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1039 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1040 psize = sizeof(struct P2PPendingMessage) + msize;
1041 pending = GNUNET_malloc(psize);
1042 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1043 pending->importance = DHT_SEND_PRIORITY;
1044 pending->timeout = GNUNET_TIME_relative_get_forever();
1045 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1046 result_message->header.size = htons(msize);
1047 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1048 result_message->options = htonl(msg_ctx->msg_options);
1049 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1050 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1051 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1052 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1053 memcpy(&result_message[1], msg, ntohs(msg->size));
1055 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));
1057 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1058 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1059 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1062 * Called when core is ready to send a message we asked for
1063 * out to the destination.
1065 * @param cls closure (NULL)
1066 * @param size number of bytes available in buf
1067 * @param buf where the callee should write the message
1068 * @return number of bytes written to buf
1070 size_t core_transmit_notify (void *cls,
1071 size_t size, void *buf)
1073 struct PeerInfo *peer = cls;
1075 struct P2PPendingMessage *pending;
1082 /* client disconnected */
1084 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1089 if (peer->head == NULL)
1094 pending = peer->head;
1095 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1096 msize = ntohs(pending->msg->size);
1100 memcpy (cbuf, pending->msg, msize);
1101 GNUNET_CONTAINER_DLL_remove (peer->head,
1105 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));
1107 GNUNET_free (pending);
1110 while (NULL != pending &&
1111 (size - off >= (msize = ntohs (pending->msg->size))))
1113 #if DEBUG_DHT_ROUTING
1114 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);
1116 memcpy (&cbuf[off], pending->msg, msize);
1118 GNUNET_CONTAINER_DLL_remove (peer->head,
1121 GNUNET_free (pending);
1122 pending = peer->head;
1125 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1126 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1128 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);
1135 * Compute the distance between have and target as a 32-bit value.
1136 * Differences in the lower bits must count stronger than differences
1137 * in the higher bits.
1139 * @return 0 if have==target, otherwise a number
1140 * that is larger as the distance between
1141 * the two hash codes increases
1144 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1146 unsigned int bucket;
1151 /* We have to represent the distance between two 2^9 (=512)-bit
1152 numbers as a 2^5 (=32)-bit number with "0" being used for the
1153 two numbers being identical; furthermore, we need to
1154 guarantee that a difference in the number of matching
1155 bits is always represented in the result.
1157 We use 2^32/2^9 numerical values to distinguish between
1158 hash codes that have the same LSB bit distance and
1159 use the highest 2^9 bits of the result to signify the
1160 number of (mis)matching LSB bits; if we have 0 matching
1161 and hence 512 mismatching LSB bits we return -1 (since
1162 512 itself cannot be represented with 9 bits) */
1164 /* first, calculate the most significant 9 bits of our
1165 result, aka the number of LSBs */
1166 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1167 /* bucket is now a value between 0 and 512 */
1169 return 0; /* perfect match */
1171 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1172 below, we'd end up with max+1 (overflow)) */
1174 /* calculate the most significant bits of the final result */
1175 msb = (512 - bucket) << (32 - 9);
1176 /* calculate the 32-9 least significant bits of the final result by
1177 looking at the differences in the 32-9 bits following the
1178 mismatching bit at 'bucket' */
1180 for (i = bucket + 1;
1181 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1183 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1184 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1185 last bit set will be 31 -- if
1186 i does not reach 512 first... */
1192 * Return a number that is larger the closer the
1193 * "have" GNUNET_hash code is to the "target".
1195 * @return inverse distance metric, non-zero.
1196 * Must fudge the value if NO bits match.
1199 inverse_distance (const GNUNET_HashCode * target,
1200 const GNUNET_HashCode * have)
1202 if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1203 return 1; /* Never return 0! */
1204 return ((unsigned int) -1) - distance (target, have);
1208 * Find the optimal bucket for this key, regardless
1209 * of the current number of buckets in use.
1211 * @param hc the hashcode to compare our identity to
1213 * @return the proper bucket index, or GNUNET_SYSERR
1214 * on error (same hashcode)
1216 static int find_bucket(const GNUNET_HashCode *hc)
1220 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1221 if (bits == MAX_BUCKETS)
1222 return GNUNET_SYSERR;
1223 return MAX_BUCKETS - bits - 1;
1227 * Find which k-bucket this peer should go into,
1228 * taking into account the size of the k-bucket
1229 * array. This means that if more bits match than
1230 * there are currently buckets, lowest_bucket will
1233 * @param hc GNUNET_HashCode we are finding the bucket for.
1235 * @return the proper bucket index for this key,
1236 * or GNUNET_SYSERR on error (same hashcode)
1238 static int find_current_bucket(const GNUNET_HashCode *hc)
1241 actual_bucket = find_bucket(hc);
1243 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1244 return lowest_bucket;
1245 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1246 return lowest_bucket;
1248 return actual_bucket;
1253 * Find a routing table entry from a peer identity
1255 * @param peer the peer to look up
1257 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1260 find_bucket_by_peer(const struct PeerInfo *peer)
1263 struct PeerInfo *pos;
1265 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1267 pos = k_buckets[bucket].head;
1276 return GNUNET_SYSERR; /* No such peer. */
1282 * Print the complete routing table for this peer.
1285 print_routing_table ()
1288 struct PeerInfo *pos;
1289 char char_buf[30000];
1291 memset(char_buf, 0, sizeof(char_buf));
1293 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1294 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1295 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1297 pos = k_buckets[bucket].head;
1298 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1299 //fprintf(stderr, "Bucket %d:\n", bucket);
1302 //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));
1303 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));
1307 fprintf(stderr, "%s", char_buf);
1313 * Find a routing table entry from a peer identity
1315 * @param peer the peer identity to look up
1317 * @return the routing table entry, or NULL if not found
1319 static struct PeerInfo *
1320 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1323 struct PeerInfo *pos;
1324 bucket = find_current_bucket(&peer->hashPubKey);
1326 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1329 pos = k_buckets[bucket].head;
1332 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1336 return NULL; /* No such peer. */
1339 /* Forward declaration */
1341 update_core_preference (void *cls,
1342 const struct GNUNET_SCHEDULER_TaskContext *tc);
1344 * Function called with statistics about the given peer.
1346 * @param cls closure
1347 * @param peer identifies the peer
1348 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1349 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1350 * @param amount set to the amount that was actually reserved or unreserved;
1351 * either the full requested amount or zero (no partial reservations)
1352 * @param preference current traffic preference for the given peer
1355 update_core_preference_finish (void *cls,
1356 const struct GNUNET_PeerIdentity * peer,
1357 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1358 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1359 int amount, uint64_t preference)
1361 struct PeerInfo *peer_info = cls;
1362 peer_info->info_ctx = NULL;
1363 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1367 update_core_preference (void *cls,
1368 const struct GNUNET_SCHEDULER_TaskContext *tc)
1370 struct PeerInfo *peer = cls;
1371 uint64_t preference;
1372 unsigned int matching;
1373 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1377 matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1380 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1383 preference = 1LL << matching;
1384 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1386 GNUNET_TIME_relative_get_forever(),
1387 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1390 &update_core_preference_finish,
1395 * Really add a peer to a bucket (only do assertions
1398 * @param peer GNUNET_PeerIdentity of the peer to add
1399 * @param bucket the already figured out bucket to add
1401 * @param latency the core reported latency of this peer
1402 * @param distance the transport level distance to this peer
1404 * @return the newly added PeerInfo
1406 static struct PeerInfo *
1407 add_peer(const struct GNUNET_PeerIdentity *peer,
1408 unsigned int bucket,
1409 struct GNUNET_TIME_Relative latency,
1410 unsigned int distance)
1412 struct PeerInfo *new_peer;
1413 GNUNET_assert(bucket < MAX_BUCKETS);
1414 GNUNET_assert(peer != NULL);
1415 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1416 new_peer->latency = latency;
1417 new_peer->distance = distance;
1419 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1421 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1422 k_buckets[bucket].tail,
1423 k_buckets[bucket].tail,
1425 k_buckets[bucket].peers_size++;
1427 if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1429 #if DO_UPDATE_PREFERENCE
1430 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1438 * Given a peer and its corresponding bucket,
1439 * remove it from that bucket. Does not free
1440 * the PeerInfo struct, nor cancel messages
1441 * or free messages waiting to be sent to this
1444 * @param peer the peer to remove
1445 * @param bucket the bucket the peer belongs to
1447 static void remove_peer (struct PeerInfo *peer,
1448 unsigned int bucket)
1450 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1451 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1452 k_buckets[bucket].tail,
1454 k_buckets[bucket].peers_size--;
1456 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1462 * Removes peer from a bucket, then frees associated
1463 * resources and frees peer.
1465 * @param peer peer to be removed and freed
1466 * @param bucket which bucket this peer belongs to
1468 static void delete_peer (struct PeerInfo *peer,
1469 unsigned int bucket)
1471 struct P2PPendingMessage *pos;
1472 struct P2PPendingMessage *next;
1474 struct PeerInfo *peer_pos;
1476 peer_pos = k_buckets[bucket].head;
1477 while ((peer_pos != NULL) && (peer_pos != peer))
1478 peer_pos = peer_pos->next;
1479 if (peer_pos == NULL)
1481 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1482 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));
1484 GNUNET_assert(peer_pos != NULL);
1486 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1488 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1489 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1490 if (peer->th != NULL)
1491 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1494 while (pos != NULL) /* Remove any pending messages for this peer */
1501 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1502 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1508 * Iterator over hash map entries.
1510 * @param cls closure
1511 * @param key current key code
1512 * @param value PeerInfo of the peer to move to new lowest bucket
1513 * @return GNUNET_YES if we should continue to
1517 static int move_lowest_bucket (void *cls,
1518 const GNUNET_HashCode * key,
1521 struct PeerInfo *peer = value;
1524 GNUNET_assert(lowest_bucket > 0);
1525 new_bucket = lowest_bucket - 1;
1526 remove_peer(peer, lowest_bucket);
1527 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1528 k_buckets[new_bucket].tail,
1529 k_buckets[new_bucket].tail,
1531 k_buckets[new_bucket].peers_size++;
1537 * The current lowest bucket is full, so change the lowest
1538 * bucket to the next lower down, and move any appropriate
1539 * entries in the current lowest bucket to the new bucket.
1541 static void enable_next_bucket()
1543 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1544 struct PeerInfo *pos;
1545 GNUNET_assert(lowest_bucket > 0);
1546 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1547 pos = k_buckets[lowest_bucket].head;
1550 fprintf(stderr, "Printing RT before new bucket\n");
1551 print_routing_table();
1553 /* Populate the array of peers which should be in the next lowest bucket */
1556 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1557 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1561 /* Remove peers from lowest bucket, insert into next lowest bucket */
1562 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1563 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1564 lowest_bucket = lowest_bucket - 1;
1566 fprintf(stderr, "Printing RT after new bucket\n");
1567 print_routing_table();
1572 * Find the closest peer in our routing table to the
1575 * @return The closest peer in our routing table to the
1576 * key, or NULL on error.
1578 static struct PeerInfo *
1579 find_closest_peer (const GNUNET_HashCode *hc)
1581 struct PeerInfo *pos;
1582 struct PeerInfo *current_closest;
1583 unsigned int lowest_distance;
1584 unsigned int temp_distance;
1588 lowest_distance = -1;
1590 if (k_buckets[lowest_bucket].peers_size == 0)
1593 current_closest = NULL;
1594 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1596 pos = k_buckets[bucket].head;
1598 while ((pos != NULL) && (count < bucket_size))
1600 temp_distance = distance(&pos->id.hashPubKey, hc);
1601 if (temp_distance <= lowest_distance)
1603 lowest_distance = temp_distance;
1604 current_closest = pos;
1610 GNUNET_assert(current_closest != NULL);
1611 return current_closest;
1616 * Function called to send a request out to another peer.
1617 * Called both for locally initiated requests and those
1618 * received from other peers.
1620 * @param cls DHT service closure argument (unused)
1621 * @param msg the encapsulated message
1622 * @param peer the peer to forward the message to
1623 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1625 static void forward_message (void *cls,
1626 const struct GNUNET_MessageHeader *msg,
1627 struct PeerInfo *peer,
1628 struct DHT_MessageContext *msg_ctx)
1630 struct GNUNET_DHT_P2PRouteMessage *route_message;
1631 struct P2PPendingMessage *pending;
1635 increment_stats(STAT_ROUTE_FORWARDS);
1637 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1638 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1640 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1641 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1642 psize = sizeof(struct P2PPendingMessage) + msize;
1643 pending = GNUNET_malloc(psize);
1644 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1645 pending->importance = msg_ctx->importance;
1646 pending->timeout = msg_ctx->timeout;
1647 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1648 route_message->header.size = htons(msize);
1649 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1650 route_message->options = htonl(msg_ctx->msg_options);
1651 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1652 route_message->network_size = htonl(msg_ctx->network_size);
1653 route_message->desired_replication_level = htonl(msg_ctx->replication);
1654 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1655 if (msg_ctx->bloom != NULL)
1656 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1657 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1658 memcpy(&route_message[1], msg, ntohs(msg->size));
1660 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));
1662 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1663 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1664 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1669 * Task used to send ping messages to peers so that
1670 * they don't get disconnected.
1672 * @param cls the peer to send a ping message to
1673 * @param tc context, reason, etc.
1676 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1678 struct PeerInfo *peer = cls;
1679 struct GNUNET_MessageHeader ping_message;
1680 struct DHT_MessageContext message_context;
1682 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1685 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1686 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1688 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1690 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1692 forward_message(NULL, &ping_message, peer, &message_context);
1693 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1697 * Schedule PING messages for the top X peers in each
1698 * bucket of the routing table (so core won't disconnect them!)
1700 void schedule_ping_messages()
1702 unsigned int bucket;
1704 struct PeerInfo *pos;
1705 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1707 pos = k_buckets[bucket].head;
1711 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1712 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1713 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1715 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1716 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1726 * Attempt to add a peer to our k-buckets.
1728 * @param peer the peer identity of the peer being added
1729 * @param bucket the bucket that we want this peer to go in
1730 * @param latency transport latency of this peer
1731 * @param distance transport distance to this peer
1733 * @return NULL if the peer was not added,
1734 * pointer to PeerInfo for new peer otherwise
1736 static struct PeerInfo *
1737 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1738 unsigned int bucket,
1739 struct GNUNET_TIME_Relative latency,
1740 unsigned int distance)
1743 struct PeerInfo *new_peer;
1745 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1748 peer_bucket = find_current_bucket(&peer->hashPubKey);
1750 GNUNET_assert(peer_bucket >= lowest_bucket);
1751 new_peer = add_peer(peer, peer_bucket, latency, distance);
1753 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1754 enable_next_bucket();
1756 schedule_ping_messages();
1763 * Task run to check for messages that need to be sent to a client.
1765 * @param client a ClientList, containing the client and any messages to be sent to it
1768 process_pending_messages (struct ClientList *client)
1770 if (client->pending_head == NULL)
1772 if (client->transmit_handle != NULL)
1775 client->transmit_handle =
1776 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1777 ntohs (client->pending_head->msg->
1779 GNUNET_TIME_UNIT_FOREVER_REL,
1780 &send_generic_reply, client);
1784 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1785 * request. A ClientList is passed as closure, take the head of the list
1786 * and copy it into buf, which has the result of sending the message to the
1789 * @param cls closure to this call
1790 * @param size maximum number of bytes available to send
1791 * @param buf where to copy the actual message to
1793 * @return the number of bytes actually copied, 0 indicates failure
1796 send_generic_reply (void *cls, size_t size, void *buf)
1798 struct ClientList *client = cls;
1800 struct PendingMessage *reply;
1804 client->transmit_handle = NULL;
1807 /* client disconnected */
1811 while ( (NULL != (reply = client->pending_head)) &&
1812 (size >= off + (msize = ntohs (reply->msg->size))))
1814 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1815 client->pending_tail,
1817 memcpy (&cbuf[off], reply->msg, msize);
1818 GNUNET_free (reply);
1821 process_pending_messages (client);
1823 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1824 "Transmitted %u bytes of replies to client\n",
1825 (unsigned int) off);
1832 * Add a PendingMessage to the clients list of messages to be sent
1834 * @param client the active client to send the message to
1835 * @param pending_message the actual message to send
1838 add_pending_message (struct ClientList *client,
1839 struct PendingMessage *pending_message)
1841 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1842 client->pending_tail,
1843 client->pending_tail,
1845 process_pending_messages (client);
1852 * Called when a reply needs to be sent to a client, as
1853 * a result it found to a GET or FIND PEER request.
1855 * @param client the client to send the reply to
1856 * @param message the encapsulated message to send
1857 * @param uid the unique identifier of this request
1860 send_reply_to_client (struct ClientList *client,
1861 const struct GNUNET_MessageHeader *message,
1862 unsigned long long uid,
1863 const GNUNET_HashCode *key)
1865 struct GNUNET_DHT_RouteResultMessage *reply;
1866 struct PendingMessage *pending_message;
1870 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1871 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1873 msize = ntohs (message->size);
1874 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1875 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1877 GNUNET_break_op (0);
1881 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1882 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1883 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1884 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1885 reply->header.size = htons (tsize);
1886 reply->unique_id = GNUNET_htonll (uid);
1888 memcpy (&reply[1], message, msize);
1890 add_pending_message (client, pending_message);
1894 * Consider whether or not we would like to have this peer added to
1895 * our routing table. Check whether bucket for this peer is full,
1896 * if so return negative; if not return positive. Since peers are
1897 * only added on CORE level connect, this doesn't actually add the
1898 * peer to the routing table.
1900 * @param peer the peer we are considering adding
1902 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1905 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1909 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1910 return GNUNET_NO; /* We already know this peer (are connected even!) */
1911 bucket = find_current_bucket(&peer->hashPubKey);
1913 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1920 * Main function that handles whether or not to route a result
1921 * message to other peers, or to send to our local client.
1923 * @param cls closure (unused, always should be NULL)
1924 * @param msg the result message to be routed
1925 * @param message_context context of the message we are routing
1927 * @return the number of peers the message was routed to,
1928 * GNUNET_SYSERR on failure
1930 static int route_result_message(void *cls,
1931 struct GNUNET_MessageHeader *msg,
1932 struct DHT_MessageContext *message_context)
1934 struct GNUNET_PeerIdentity new_peer;
1935 struct DHTQueryRecord *record;
1936 struct DHTRouteSource *pos;
1937 struct PeerInfo *peer_info;
1938 const struct GNUNET_MessageHeader *hello_msg;
1940 increment_stats(STAT_RESULTS);
1942 * If a find peer result message is received and contains a valid
1943 * HELLO for another peer, offer it to the transport service.
1945 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1947 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1950 hello_msg = &msg[1];
1951 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1953 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1957 else /* We have a valid hello, and peer id stored in new_peer */
1959 find_peer_context.count++;
1960 increment_stats(STAT_FIND_PEER_REPLY);
1961 if (GNUNET_YES == consider_peer(&new_peer))
1963 increment_stats(STAT_HELLOS_PROVIDED);
1964 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1965 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1970 if (malicious_dropper == GNUNET_YES)
1973 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1975 if (record == NULL) /* No record of this message! */
1978 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1979 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1980 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
1982 #if DEBUG_DHT_ROUTING
1983 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1985 dhtlog_handle->insert_route (NULL,
1986 message_context->unique_id,
1988 message_context->hop_count,
1991 &message_context->key,
1992 message_context->peer, NULL);
1995 if (message_context->bloom != NULL)
1997 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1998 message_context->bloom = NULL;
2006 #if STRICT_FORWARDING
2007 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2009 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2011 increment_stats("# find peer responses NOT forwarded (bloom match)");
2016 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2020 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2023 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2024 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2025 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2027 #if DEBUG_DHT_ROUTING
2028 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2030 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2031 message_context->hop_count,
2032 GNUNET_YES, &my_identity, &message_context->key,
2033 message_context->peer, NULL);
2036 increment_stats(STAT_RESULTS_TO_CLIENT);
2037 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2038 increment_stats(STAT_GET_REPLY);
2040 send_reply_to_client(pos->client, msg,
2041 message_context->unique_id,
2042 &message_context->key);
2044 else /* Send to peer */
2046 peer_info = find_peer_by_id(&pos->source);
2047 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2053 if (message_context->bloom == NULL)
2054 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2055 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2056 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2059 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2060 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2061 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2063 #if DEBUG_DHT_ROUTING
2064 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2066 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2068 message_context->hop_count,
2069 GNUNET_NO, &my_identity, &message_context->key,
2070 message_context->peer, &pos->source);
2073 forward_result_message(cls, msg, peer_info, message_context);
2078 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2079 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2080 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2086 if (message_context->bloom != NULL)
2087 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2092 * Iterator for local get request results,
2094 * @param cls closure for iterator, a DatacacheGetContext
2095 * @param exp when does this value expire?
2096 * @param key the key this data is stored under
2097 * @param size the size of the data identified by key
2098 * @param data the actual data
2099 * @param type the type of the data
2101 * @return GNUNET_OK to continue iteration, anything else
2102 * to stop iteration.
2105 datacache_get_iterator (void *cls,
2106 struct GNUNET_TIME_Absolute exp,
2107 const GNUNET_HashCode * key,
2108 uint32_t size, const char *data, uint32_t type)
2110 struct DHT_MessageContext *msg_ctx = cls;
2111 struct DHT_MessageContext *new_msg_ctx;
2112 struct GNUNET_DHT_GetResultMessage *get_result;
2114 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2115 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2117 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2118 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2120 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2121 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2122 get_result->header.size =
2123 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2124 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2125 get_result->type = htons (type);
2126 memcpy (&get_result[1], data, size);
2127 new_msg_ctx->peer = &my_identity;
2128 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2129 new_msg_ctx->hop_count = 0;
2130 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2131 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2132 increment_stats(STAT_GET_RESPONSE_START);
2133 route_result_message(cls, &get_result->header, new_msg_ctx);
2134 GNUNET_free(new_msg_ctx);
2135 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2136 // datacache_get_ctx->unique_id);
2137 GNUNET_free (get_result);
2143 * Server handler for all dht get requests, look for data,
2144 * if found, send response either to clients or other peers.
2146 * @param cls closure for service
2147 * @param msg the actual get message
2148 * @param message_context struct containing pertinent information about the get request
2150 * @return number of items found for GET request
2153 handle_dht_get (void *cls,
2154 const struct GNUNET_MessageHeader *msg,
2155 struct DHT_MessageContext *message_context)
2157 const struct GNUNET_DHT_GetMessage *get_msg;
2159 unsigned int results;
2161 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2162 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2168 get_type = ntohs (get_msg->type);
2170 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2171 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2172 "DHT", "GET", get_type, GNUNET_h2s (&message_context->key),
2173 message_context->unique_id);
2175 increment_stats(STAT_GETS);
2177 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2180 if (datacache != NULL)
2182 GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2183 &datacache_get_iterator, message_context);
2188 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2189 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2190 results, "GET", message_context->unique_id);
2192 #if DEBUG_DHT_ROUTING
2193 if ((debug_routes) && (dhtlog_handle != NULL))
2195 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2196 message_context->hop_count, GNUNET_YES, &my_identity,
2197 &message_context->key);
2200 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2202 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2203 message_context->hop_count, GNUNET_YES,
2204 &my_identity, &message_context->key, message_context->peer,
2210 if (message_context->hop_count == 0) /* Locally initiated request */
2212 #if DEBUG_DHT_ROUTING
2213 if ((debug_routes) && (dhtlog_handle != NULL))
2215 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2216 message_context->hop_count, GNUNET_NO, &my_identity,
2217 &message_context->key);
2226 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2228 GNUNET_HashCode *key = cls;
2229 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2236 * Server handler for initiating local dht find peer requests
2238 * @param cls closure for service
2239 * @param find_msg the actual find peer message
2240 * @param message_context struct containing pertinent information about the request
2244 handle_dht_find_peer (void *cls,
2245 const struct GNUNET_MessageHeader *find_msg,
2246 struct DHT_MessageContext *message_context)
2248 struct GNUNET_MessageHeader *find_peer_result;
2249 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2250 struct DHT_MessageContext *new_msg_ctx;
2251 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2254 GNUNET_HashCode *recent_hash;
2255 struct GNUNET_MessageHeader *other_hello;
2256 size_t other_hello_size;
2257 struct GNUNET_PeerIdentity peer_id;
2259 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2260 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2261 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2264 other_hello_size = 0;
2265 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2267 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2268 other_hello = GNUNET_malloc(other_hello_size);
2269 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2270 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)))
2272 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2273 GNUNET_free(other_hello);
2276 #if FIND_PEER_WITH_HELLO
2277 if (GNUNET_YES == consider_peer(&peer_id))
2279 increment_stats(STAT_HELLOS_PROVIDED);
2280 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2281 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2284 else /* We don't want this peer! */
2290 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2291 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2292 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&message_context->key),
2293 ntohs (find_msg->size),
2294 sizeof (struct GNUNET_MessageHeader));
2296 if (my_hello == NULL)
2299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2300 "`%s': Our HELLO is null, can't return.\n",
2303 GNUNET_free_non_null(other_hello);
2307 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2308 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2310 increment_stats(STAT_BLOOM_FIND_PEER);
2311 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2312 GNUNET_free_non_null(other_hello);
2313 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2315 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2317 #if RESTRICT_FIND_PEER
2320 * Ignore any find peer requests from a peer we have seen very recently.
2322 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! */
2324 increment_stats("# dht find peer requests ignored (recently seen!)");
2325 GNUNET_free_non_null(other_hello);
2330 * Use this check to only allow the peer to respond to find peer requests if
2331 * it would be beneficial to have the requesting peer in this peers routing
2332 * table. Can be used to thwart peers flooding the network with find peer
2333 * requests that we don't care about. However, if a new peer is joining
2334 * the network and has no other peers this is a problem (assume all buckets
2335 * full, no one will respond!).
2337 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2338 if (GNUNET_NO == consider_peer(&peer_id))
2340 increment_stats("# dht find peer requests ignored (do not need!)");
2341 GNUNET_free_non_null(other_hello);
2346 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2347 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2348 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2349 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2351 /* Simplistic find_peer functionality, always return our hello */
2352 hello_size = ntohs(my_hello->size);
2353 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2355 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2357 GNUNET_break_op (0);
2358 GNUNET_free_non_null(other_hello);
2362 find_peer_result = GNUNET_malloc (tsize);
2363 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2364 find_peer_result->size = htons (tsize);
2365 memcpy (&find_peer_result[1], my_hello, hello_size);
2367 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2368 "`%s': Sending hello size %d to requesting peer.\n",
2371 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2372 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2373 new_msg_ctx->peer = &my_identity;
2374 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2375 new_msg_ctx->hop_count = 0;
2376 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2377 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2378 increment_stats(STAT_FIND_PEER_ANSWER);
2379 route_result_message(cls, find_peer_result, new_msg_ctx);
2380 GNUNET_free(new_msg_ctx);
2381 #if DEBUG_DHT_ROUTING
2382 if ((debug_routes) && (dhtlog_handle != NULL))
2384 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2385 message_context->hop_count, GNUNET_YES, &my_identity,
2386 &message_context->key);
2389 GNUNET_free_non_null(other_hello);
2390 GNUNET_free(find_peer_result);
2394 * Task used to republish data.
2395 * Forward declaration; function call loop.
2397 * @param cls closure (a struct RepublishContext)
2398 * @param tc runtime context for this task
2401 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2404 * Server handler for initiating local dht put requests
2406 * @param cls closure for service
2407 * @param msg the actual put message
2408 * @param message_context struct containing pertinent information about the request
2411 handle_dht_put (void *cls,
2412 const struct GNUNET_MessageHeader *msg,
2413 struct DHT_MessageContext *message_context)
2415 struct GNUNET_DHT_PutMessage *put_msg;
2419 struct RepublishContext *put_context;
2421 GNUNET_assert (ntohs (msg->size) >=
2422 sizeof (struct GNUNET_DHT_PutMessage));
2425 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2426 put_type = ntohs (put_msg->type);
2428 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2431 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2433 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2434 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2435 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
2437 #if DEBUG_DHT_ROUTING
2438 if (message_context->hop_count == 0) /* Locally initiated request */
2440 if ((debug_routes) && (dhtlog_handle != NULL))
2442 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2443 message_context->hop_count, GNUNET_NO, &my_identity,
2444 &message_context->key);
2449 if (message_context->closest != GNUNET_YES)
2452 #if DEBUG_DHT_ROUTING
2453 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2455 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2456 message_context->hop_count, GNUNET_YES,
2457 &my_identity, &message_context->key, message_context->peer,
2461 if ((debug_routes) && (dhtlog_handle != NULL))
2463 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2464 message_context->hop_count, GNUNET_YES, &my_identity,
2465 &message_context->key);
2469 increment_stats(STAT_PUTS_INSERTED);
2470 if (datacache != NULL)
2472 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2473 (char *) &put_msg[1], put_type,
2474 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2476 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2478 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2479 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2480 put_context->type = put_type;
2481 GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
2485 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2486 "`%s:%s': %s request received, but have no datacache!\n",
2487 my_short_id, "DHT", "PUT");
2491 * Estimate the diameter of the network based
2492 * on how many buckets are currently in use.
2493 * Concept here is that the diameter of the network
2494 * is roughly the distance a message must travel in
2495 * order to reach its intended destination. Since
2496 * at each hop we expect to get one bit closer, and
2497 * we have one bit per bucket, the number of buckets
2498 * in use should be the largest number of hops for
2499 * a sucessful message. (of course, this assumes we
2500 * know all peers in the network!)
2502 * @return ballpark diameter figure
2504 static unsigned int estimate_diameter()
2506 return MAX_BUCKETS - lowest_bucket;
2510 * To how many peers should we (on average)
2511 * forward the request to obtain the desired
2512 * target_replication count (on average).
2514 * Always 0, 1 or 2 (don't send, send once, split)
2517 get_forward_count (unsigned int hop_count, size_t target_replication)
2520 double target_count;
2521 double random_probability;
2523 uint32_t random_value;
2525 unsigned int target_value;
2526 unsigned int diameter;
2529 * If we are behaving in strict kademlia mode, send multiple initial requests,
2530 * but then only send to 1 or 0 peers based strictly on the number of hops.
2532 if (strict_kademlia == GNUNET_YES)
2535 return DHT_KADEMLIA_REPLICATION;
2536 else if (hop_count < max_hops)
2542 /* FIXME: the smaller we think the network is the more lenient we should be for
2543 * routing right? The estimation below only works if we think we have reasonably
2544 * full routing tables, which for our RR topologies may not be the case!
2546 diameter = estimate_diameter ();
2547 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2551 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2552 "DHT", estimate_diameter(), lowest_bucket);
2556 else if (hop_count > max_hops)
2559 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2560 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2567 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2568 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2569 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2570 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2571 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2572 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2573 RAND_MAX)) / RAND_MAX;
2574 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2577 //while (target_value < target_count)
2578 if (target_value < target_count)
2579 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? */
2582 //if ((target_count + 1 - (double)target_value) > random_probability)
2583 if ((target_count) > random_probability)
2587 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2588 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));
2590 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2591 if (random_value < target_replication)
2594 return target_value;
2598 * Check whether my identity is closer than any known peers.
2599 * If a non-null bloomfilter is given, check if this is the closest
2600 * peer that hasn't already been routed to.
2602 * @param target hash code to check closeness to
2603 * @param bloom bloomfilter, exclude these entries from the decision
2605 * Return GNUNET_YES if node location is closest, GNUNET_NO
2609 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2615 struct PeerInfo *pos;
2616 unsigned int my_distance;
2618 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2621 bucket_num = find_current_bucket(target);
2623 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2624 my_distance = distance(&my_identity.hashPubKey, target);
2625 pos = k_buckets[bucket_num].head;
2627 while ((pos != NULL) && (count < bucket_size))
2629 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2632 continue; /* Skip already checked entries */
2635 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2636 if (other_bits > bits)
2638 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2640 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2642 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2649 GNUNET_GE_LOG (coreAPI->ectx,
2650 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2651 GNUNET_GE_BULK, "closest peer\n");
2652 printPeerBits (&closest);
2653 GNUNET_GE_LOG (coreAPI->ectx,
2654 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2655 GNUNET_GE_BULK, "me\n");
2656 printPeerBits (coreAPI->my_identity);
2657 GNUNET_GE_LOG (coreAPI->ectx,
2658 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2659 GNUNET_GE_BULK, "key\n");
2660 printKeyBits (target);
2661 GNUNET_GE_LOG (coreAPI->ectx,
2662 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2664 "closest peer inverse distance is %u, mine is %u\n",
2665 inverse_distance (target, &closest.hashPubKey),
2666 inverse_distance (target,
2667 &coreAPI->my_identity->hashPubKey));
2670 /* No peers closer, we are the closest! */
2676 * Return this peers adjusted value based on the convergence
2677 * function chosen. This is the key function for randomized
2678 * routing decisions.
2680 * @param target the key of the request
2681 * @param peer the peer we would like the value of
2682 * @param hops number of hops this message has already traveled
2684 * @return bit distance from target to peer raised to an exponent
2685 * adjusted based on the current routing convergence algorithm
2689 converge_distance (const GNUNET_HashCode *target,
2690 struct PeerInfo *peer,
2693 unsigned long long ret;
2694 unsigned int other_matching_bits;
2695 double converge_modifier = 0.0;
2696 double base_converge_modifier = .1;
2702 curr_max_hops = max_hops;
2704 curr_max_hops = (estimate_diameter() + 1) * 2;
2706 if (converge_modifier > 0)
2707 converge_modifier = converge_modifier * base_converge_modifier;
2710 converge_modifier = base_converge_modifier;
2711 base_converge_modifier = 0.0;
2714 GNUNET_assert(converge_modifier > 0);
2716 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2718 switch (converge_option)
2720 case DHT_CONVERGE_RANDOM:
2721 return 1; /* Always return 1, choose equally among all peers */
2722 case DHT_CONVERGE_LINEAR:
2723 calc_value = hops * curr_max_hops * converge_modifier;
2725 case DHT_CONVERGE_SQUARE:
2727 * Simple square based curve.
2729 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * converge_modifier));
2731 case DHT_CONVERGE_EXPONENTIAL:
2733 * Simple exponential curve.
2735 if (base_converge_modifier > 0)
2736 calc_value = (converge_modifier * hops * hops) / curr_max_hops;
2738 calc_value = (hops * hops) / curr_max_hops;
2744 /* Take the log (base e) of the number of bits matching the other peer */
2745 exponent = log(other_matching_bits);
2747 /* Check if we would overflow; our largest possible value is 2^64 = e^44.361419555836498 */
2748 if (exponent * calc_value >= 44.361419555836498)
2751 /* Clear errno and all math exceptions */
2753 feclearexcept(FE_ALL_EXCEPT);
2754 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2755 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2758 if (0 != fetestexcept(FE_OVERFLOW))
2759 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2760 if (0 != fetestexcept(FE_INVALID))
2761 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2762 if (0 != fetestexcept(FE_UNDERFLOW))
2763 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2771 * Comparison function for two struct PeerInfo's
2772 * which have already had their matching bits to
2773 * some target calculated.
2775 * @param p1 a pointer pointer to a struct PeerInfo
2776 * @param p2 a pointer pointer to a struct PeerInfo
2778 * @return 0 if equidistant to target,
2779 * -1 if p1 is closer,
2783 compare_peers (const void *p1, const void *p2)
2785 struct PeerInfo **first = (struct PeerInfo **)p1;
2786 struct PeerInfo **second = (struct PeerInfo **)p2;
2788 if ((*first)->matching_bits > (*second)->matching_bits)
2790 if ((*first)->matching_bits < (*second)->matching_bits)
2798 * Select a peer from the routing table that would be a good routing
2799 * destination for sending a message for "target". The resulting peer
2800 * must not be in the set of blocked peers.<p>
2802 * Note that we should not ALWAYS select the closest peer to the
2803 * target, peers further away from the target should be chosen with
2804 * exponentially declining probability.
2806 * @param target the key we are selecting a peer to route to
2807 * @param bloom a bloomfilter containing entries this request has seen already
2809 * @return Peer to route to, or NULL on error
2811 static struct PeerInfo *
2812 select_peer (const GNUNET_HashCode * target,
2813 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2818 unsigned int offset;
2819 unsigned int my_matching_bits;
2821 struct PeerInfo *pos;
2822 struct PeerInfo *sorted_closest[bucket_size];
2823 unsigned long long temp_converge_distance;
2824 unsigned long long total_distance;
2825 unsigned long long selected;
2827 unsigned long long stats_total_distance;
2831 unsigned int distance;
2832 unsigned int largest_distance;
2833 struct PeerInfo *chosen;
2835 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
2838 if (strict_kademlia == GNUNET_YES)
2840 largest_distance = 0;
2842 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2844 pos = k_buckets[bc].head;
2846 while ((pos != NULL) && (count < bucket_size))
2848 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2849 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2851 distance = inverse_distance (target, &pos->id.hashPubKey);
2852 if (distance > largest_distance)
2855 largest_distance = distance;
2863 if ((largest_distance > 0) && (chosen != NULL))
2865 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2876 /* Three steps: order peers in closest bucket (most matching bits).
2877 * Then go over all LOWER buckets (matching same bits we do)
2878 * Then go over all HIGHER buckets (matching less then we do)
2881 closest_bucket = find_current_bucket(target);
2882 GNUNET_assert(closest_bucket >= lowest_bucket);
2883 pos = k_buckets[closest_bucket].head;
2885 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
2886 memset(sorted_closest, 0, sizeof(sorted_closest));
2887 /* Put any peers in the closest bucket in the sorting array */
2888 while ((pos != NULL) && (count < bucket_size))
2890 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2894 continue; /* Ignore bloomfiltered peers */
2896 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2897 sorted_closest[offset] = pos;
2903 /* Sort the peers in descending order */
2904 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
2906 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
2907 for (i = 0; i < offset; i++)
2909 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
2910 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
2911 break; /* Ignore bloomfiltered peers */
2912 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2913 total_distance += temp_converge_distance;
2915 break; /* overflow case */
2918 /* Now handle peers in lower buckets (matches same # of bits as target) */
2919 for (bc = lowest_bucket; bc < closest_bucket; bc++)
2921 pos = k_buckets[bc].head;
2923 while ((pos != NULL) && (count < bucket_size))
2925 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2929 continue; /* Ignore bloomfiltered peers */
2931 temp_converge_distance = converge_distance(target, pos, hops);
2932 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2933 total_distance += temp_converge_distance;
2935 break; /* overflow case */
2941 /* Now handle all the further away peers */
2942 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
2944 pos = k_buckets[bc].head;
2946 while ((pos != NULL) && (count < bucket_size))
2948 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2952 continue; /* Ignore bloomfiltered peers */
2954 temp_converge_distance = converge_distance(target, pos, hops);
2955 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2956 total_distance += temp_converge_distance;
2958 break; /* overflow case */
2964 if (total_distance == 0) /* No peers to select from! */
2966 increment_stats("# select_peer, total_distance == 0");
2970 #if DEBUG_DHT_ROUTING > 1
2973 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
2974 stats_total_distance = 0;
2975 for (i = 0; i < offset; i++)
2977 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
2978 break; /* Ignore bloomfiltered peers */
2979 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
2980 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
2981 stats_total_distance += temp_converge_distance;
2983 break; /* overflow case */
2984 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);
2987 /* Now handle peers in lower buckets (matches same # of bits as target) */
2988 for (bc = lowest_bucket; bc < closest_bucket; bc++)
2990 pos = k_buckets[bc].head;
2992 while ((pos != NULL) && (count < bucket_size))
2994 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2998 continue; /* Ignore bloomfiltered peers */
3000 temp_converge_distance = converge_distance(target, pos, hops);
3001 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3002 stats_total_distance += temp_converge_distance;
3004 break; /* overflow case */
3005 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);
3011 /* Now handle all the further away peers */
3012 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3014 pos = k_buckets[bc].head;
3016 while ((pos != NULL) && (count < bucket_size))
3018 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3022 continue; /* Ignore bloomfiltered peers */
3024 temp_converge_distance = converge_distance(target, pos, hops);
3025 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3026 stats_total_distance += temp_converge_distance;
3028 break; /* overflow case */
3029 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);
3034 /* END PRINT STATS */
3037 /* Now actually choose a peer */
3038 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3040 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3041 for (i = 0; i < offset; i++)
3043 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3044 break; /* Ignore bloomfiltered peers */
3045 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3046 if (temp_converge_distance >= selected)
3047 return sorted_closest[i];
3049 selected -= temp_converge_distance;
3052 /* Now handle peers in lower buckets (matches same # of bits as target) */
3053 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3055 pos = k_buckets[bc].head;
3057 while ((pos != NULL) && (count < bucket_size))
3059 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3063 continue; /* Ignore bloomfiltered peers */
3065 temp_converge_distance = converge_distance(target, pos, hops);
3066 if (temp_converge_distance >= selected)
3069 selected -= temp_converge_distance;
3075 /* Now handle all the further away peers */
3076 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3078 pos = k_buckets[bc].head;
3080 while ((pos != NULL) && (count < bucket_size))
3082 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3086 continue; /* Ignore bloomfiltered peers */
3088 temp_converge_distance = converge_distance(target, pos, hops);
3089 if (temp_converge_distance >= selected)
3092 selected -= temp_converge_distance;
3098 increment_stats("# failed to select peer");
3104 * Task used to remove recent entries, either
3105 * after timeout, when full, or on shutdown.
3107 * @param cls the entry to remove
3108 * @param tc context, reason, etc.
3111 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3113 struct RecentRequest *req = cls;
3114 static GNUNET_HashCode hash;
3116 GNUNET_assert(req != NULL);
3117 hash_from_uid(req->uid, &hash);
3118 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3119 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3120 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3123 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3125 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3126 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3132 * Task used to remove forwarding entries, either
3133 * after timeout, when full, or on shutdown.
3135 * @param cls the entry to remove
3136 * @param tc context, reason, etc.
3139 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3141 struct DHTRouteSource *source_info = cls;
3142 struct DHTQueryRecord *record;
3143 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3144 record = source_info->record;
3145 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3147 if (record->head == NULL) /* No more entries in DLL */
3149 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3150 GNUNET_free(record);
3152 if (source_info->find_peers_responded != NULL)
3153 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3154 GNUNET_free(source_info);
3158 * Remember this routing request so that if a reply is
3159 * received we can either forward it to the correct peer
3160 * or return the result locally.
3162 * @param cls DHT service closure
3163 * @param msg_ctx Context of the route request
3165 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3167 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
3169 struct DHTQueryRecord *record;
3170 struct DHTRouteSource *source_info;
3171 struct DHTRouteSource *pos;
3172 struct GNUNET_TIME_Absolute now;
3173 unsigned int current_size;
3175 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3176 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3178 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3179 GNUNET_assert(source_info != NULL);
3180 record = source_info->record;
3181 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3182 if (record->head == NULL) /* No more entries in DLL */
3184 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3185 GNUNET_free(record);
3187 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
3188 if (source_info->find_peers_responded != NULL)
3189 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3190 GNUNET_free(source_info);
3191 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3193 now = GNUNET_TIME_absolute_get();
3194 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3195 if (record != NULL) /* Already know this request! */
3200 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3201 break; /* Already have this peer in reply list! */
3204 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3206 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3212 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3213 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3214 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3217 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3218 source_info->record = record;
3219 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3220 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3221 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3222 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3223 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3225 source_info->client = msg_ctx->client;
3226 now = GNUNET_TIME_absolute_get_forever();
3228 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3230 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3231 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3232 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3239 * Main function that handles whether or not to route a message to other
3242 * @param cls closure for dht service (NULL)
3243 * @param msg the message to be routed
3244 * @param message_context the context containing all pertinent information about the message
3246 * @return the number of peers the message was routed to,
3247 * GNUNET_SYSERR on failure
3249 static int route_message(void *cls,
3250 const struct GNUNET_MessageHeader *msg,
3251 struct DHT_MessageContext *message_context)
3255 struct PeerInfo *selected;
3256 #if DEBUG_DHT_ROUTING > 1
3257 struct PeerInfo *nearest;
3259 unsigned int forward_count;
3260 struct RecentRequest *recent_req;
3261 GNUNET_HashCode unique_hash;
3262 char *stat_forward_count;
3263 char *temp_stat_str;
3264 #if DEBUG_DHT_ROUTING
3268 if (malicious_dropper == GNUNET_YES)
3270 #if DEBUG_DHT_ROUTING
3271 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3273 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3274 message_context->hop_count, GNUNET_SYSERR,
3275 &my_identity, &message_context->key, message_context->peer,
3279 if (message_context->bloom != NULL)
3280 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3284 increment_stats(STAT_ROUTES);
3285 /* Semantics of this call means we find whether we are the closest peer out of those already
3286 * routed to on this messages path.
3288 global_closest = am_closest_peer(&message_context->key, NULL);
3289 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3290 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3291 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3292 increment_stats(stat_forward_count);
3293 GNUNET_free(stat_forward_count);
3294 if (message_context->bloom == NULL)
3295 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3297 if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3301 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3302 * any closer peers (which is being checked for below). Since we are doing recursive
3303 * routing we have no choice but to stop forwarding in this case. This means that at
3304 * any given step the request may NOT be forwarded to alpha peers (because routes will
3305 * stop and the parallel route will not be aware of it). Of course, assuming that we
3306 * have fulfilled the Kademlia requirements for routing table fullness this will never
3307 * ever ever be a problem.
3309 * However, is this fair?
3311 * Since we use these requests to build our routing tables (and we build them in the
3312 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3313 * routing tables still get constructed.
3315 if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3318 #if DEBUG_DHT_ROUTING
3319 if (forward_count == 0)
3320 ret = GNUNET_SYSERR;
3324 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3326 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3327 message_context->hop_count, ret,
3328 &my_identity, &message_context->key, message_context->peer,
3333 switch (ntohs(msg->type))
3335 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3336 cache_response (cls, message_context);
3337 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3340 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3341 increment_stats(STAT_PUTS);
3342 message_context->closest = global_closest;
3343 handle_dht_put (cls, msg, message_context);
3345 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3346 increment_stats(STAT_FIND_PEER);
3347 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3349 cache_response (cls, message_context);
3350 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3351 handle_dht_find_peer (cls, msg, message_context);
3353 #if DEBUG_DHT_ROUTING
3354 if (message_context->hop_count == 0) /* Locally initiated request */
3356 if ((debug_routes) && (dhtlog_handle != NULL))
3358 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3359 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3360 message_context->hop_count, GNUNET_NO, &my_identity,
3361 &message_context->key);
3367 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3368 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3371 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3372 hash_from_uid (message_context->unique_id, &unique_hash);
3373 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3375 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3376 GNUNET_assert(recent_req != NULL);
3377 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3378 increment_stats(STAT_DUPLICATE_UID);
3381 increment_stats(STAT_RECENT_SEEN);
3382 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3387 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3388 recent_req->uid = message_context->unique_id;
3389 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3390 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3391 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3392 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3393 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3396 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3398 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3399 GNUNET_assert(recent_req != NULL);
3400 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3401 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3404 for (i = 0; i < forward_count; i++)
3406 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3408 if (selected != NULL)
3410 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
3411 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
3413 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
3414 if (temp_stat_str != NULL)
3416 increment_stats(temp_stat_str);
3417 GNUNET_free(temp_stat_str);
3419 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3420 #if DEBUG_DHT_ROUTING > 1
3421 nearest = find_closest_peer(&message_context->key);
3422 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3424 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3425 "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));
3426 GNUNET_free(nearest_buf);
3428 #if DEBUG_DHT_ROUTING
3429 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3431 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3432 message_context->hop_count, GNUNET_NO,
3433 &my_identity, &message_context->key, message_context->peer,
3437 forward_message(cls, msg, selected, message_context);
3441 if (message_context->bloom != NULL)
3443 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3444 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3447 return forward_count;
3451 * Iterator for local get request results,
3453 * @param cls closure for iterator, NULL
3454 * @param exp when does this value expire?
3455 * @param key the key this data is stored under
3456 * @param size the size of the data identified by key
3457 * @param data the actual data
3458 * @param type the type of the data
3460 * @return GNUNET_OK to continue iteration, anything else
3461 * to stop iteration.
3464 republish_content_iterator (void *cls,
3465 struct GNUNET_TIME_Absolute exp,
3466 const GNUNET_HashCode * key,
3467 uint32_t size, const char *data, uint32_t type)
3470 struct DHT_MessageContext *new_msg_ctx;
3471 struct GNUNET_DHT_PutMessage *put_msg;
3473 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3474 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3476 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3479 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3480 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3481 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3482 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3483 put_msg->type = htons (type);
3484 memcpy (&put_msg[1], data, size);
3485 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3486 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3487 new_msg_ctx->msg_options = ntohl (0);
3488 new_msg_ctx->network_size = estimate_diameter();
3489 new_msg_ctx->peer = &my_identity;
3490 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3491 new_msg_ctx->hop_count = 0;
3492 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3493 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3494 increment_stats(STAT_PUT_START);
3495 route_message(cls, &put_msg->header, new_msg_ctx);
3497 GNUNET_free(new_msg_ctx);
3498 GNUNET_free (put_msg);
3503 * Task used to republish data.
3505 * @param cls closure (a struct RepublishContext)
3506 * @param tc runtime context for this task
3509 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3511 struct RepublishContext *put_context = cls;
3513 unsigned int results;
3515 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3517 GNUNET_free(put_context);
3521 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3522 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3523 if (results == 0) /* Data must have expired */
3524 GNUNET_free(put_context);
3525 else /* Reschedule task for next time period */
3526 GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);
3532 * Iterator over hash map entries.
3534 * @param cls client to search for in source routes
3535 * @param key current key code (ignored)
3536 * @param value value in the hash map, a DHTQueryRecord
3537 * @return GNUNET_YES if we should continue to
3541 static int find_client_records (void *cls,
3542 const GNUNET_HashCode * key, void *value)
3544 struct ClientList *client = cls;
3545 struct DHTQueryRecord *record = value;
3546 struct DHTRouteSource *pos;
3550 if (pos->client == client)
3556 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3557 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3558 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3559 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3561 if (pos->find_peers_responded != NULL)
3562 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3565 if (record->head == NULL) /* No more entries in DLL */
3567 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3568 GNUNET_free(record);
3574 * Functions with this signature are called whenever a client
3575 * is disconnected on the network level.
3577 * @param cls closure (NULL for dht)
3578 * @param client identification of the client; NULL
3579 * for the last call when the server is destroyed
3581 static void handle_client_disconnect (void *cls,
3582 struct GNUNET_SERVER_Client* client)
3584 struct ClientList *pos = client_list;
3585 struct ClientList *prev;
3586 struct ClientList *found;
3587 struct PendingMessage *reply;
3593 if (pos->client_handle == client)
3596 prev->next = pos->next;
3598 client_list = pos->next;
3608 while(NULL != (reply = found->pending_head))
3610 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3613 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3619 * Find a client if it exists, add it otherwise.
3621 * @param client the server handle to the client
3623 * @return the client if found, a new client otherwise
3625 static struct ClientList *
3626 find_active_client (struct GNUNET_SERVER_Client *client)
3628 struct ClientList *pos = client_list;
3629 struct ClientList *ret;
3633 if (pos->client_handle == client)
3638 ret = GNUNET_malloc (sizeof (struct ClientList));
3639 ret->client_handle = client;
3640 ret->next = client_list;
3647 * Task to send a malicious put message across the network.
3649 * @param cls closure for this task
3650 * @param tc the context under which the task is running
3653 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3655 static struct GNUNET_DHT_PutMessage put_message;
3656 static struct DHT_MessageContext message_context;
3657 static GNUNET_HashCode key;
3658 uint32_t random_key;
3660 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3663 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3664 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3665 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3666 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3667 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3668 message_context.client = NULL;
3669 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3670 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3671 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3672 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3673 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3674 message_context.msg_options = ntohl (0);
3675 message_context.network_size = estimate_diameter();
3676 message_context.peer = &my_identity;
3677 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3678 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3679 #if DEBUG_DHT_ROUTING
3680 if (dhtlog_handle != NULL)
3681 dhtlog_handle->insert_dhtkey(NULL, &key);
3683 increment_stats(STAT_PUT_START);
3684 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3685 route_message(NULL, &put_message.header, &message_context);
3686 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3691 * Task to send a malicious put message across the network.
3693 * @param cls closure for this task
3694 * @param tc the context under which the task is running
3697 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3699 static struct GNUNET_DHT_GetMessage get_message;
3700 struct DHT_MessageContext message_context;
3701 static GNUNET_HashCode key;
3702 uint32_t random_key;
3704 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3707 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3708 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3709 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3710 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3711 message_context.client = NULL;
3712 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3713 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3714 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3715 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3716 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3717 message_context.msg_options = ntohl (0);
3718 message_context.network_size = estimate_diameter();
3719 message_context.peer = &my_identity;
3720 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3721 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3722 #if DEBUG_DHT_ROUTING
3723 if (dhtlog_handle != NULL)
3724 dhtlog_handle->insert_dhtkey(NULL, &key);
3726 increment_stats(STAT_GET_START);
3727 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3728 route_message (NULL, &get_message.header, &message_context);
3729 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3733 * Iterator over hash map entries.
3735 * @param cls closure
3736 * @param key current key code
3737 * @param value value in the hash map
3738 * @return GNUNET_YES if we should continue to
3743 add_known_to_bloom (void *cls,
3744 const GNUNET_HashCode * key,
3747 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3748 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3753 * Task to send a find peer message for our own peer identifier
3754 * so that we can find the closest peers in the network to ourselves
3755 * and attempt to connect to them.
3757 * @param cls closure for this task
3758 * @param tc the context under which the task is running
3761 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3763 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3764 struct DHT_MessageContext message_context;
3766 struct GNUNET_TIME_Relative next_send_time;
3767 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3769 struct GNUNET_TIME_Relative time_diff;
3770 struct GNUNET_TIME_Absolute end;
3772 double count_per_interval;
3774 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3777 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! */
3779 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3780 GNUNET_SCHEDULER_add_delayed (sched,
3781 GNUNET_TIME_UNIT_MINUTES,
3782 &send_find_peer_message, NULL);
3783 newly_found_peers = 0;
3787 increment_stats(STAT_FIND_PEER_START);
3789 end = GNUNET_TIME_absolute_get();
3790 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3792 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3794 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3795 count_per_interval = find_peer_context.count / multiplier;
3799 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3800 count_per_interval = find_peer_context.count * multiplier;
3804 #if FIND_PEER_WITH_HELLO
3805 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3806 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3807 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3809 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3810 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3812 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3813 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3814 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3815 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3816 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3817 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3818 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3819 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3820 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3821 message_context.network_size = estimate_diameter();
3822 message_context.peer = &my_identity;
3823 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3824 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3826 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3827 GNUNET_free(find_peer_msg);
3828 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3829 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3831 if (newly_found_peers < bucket_size)
3833 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3834 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3835 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3839 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3840 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3841 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3844 GNUNET_assert (next_send_time.value != 0);
3845 find_peer_context.count = 0;
3846 newly_found_peers = 0;
3847 find_peer_context.start = GNUNET_TIME_absolute_get();
3848 if (GNUNET_YES == do_find_peer)
3850 GNUNET_SCHEDULER_add_delayed (sched,
3852 &send_find_peer_message, NULL);
3857 * Handler for any generic DHT messages, calls the appropriate handler
3858 * depending on message type, sends confirmation if responses aren't otherwise
3861 * @param cls closure for the service
3862 * @param client the client we received this message from
3863 * @param message the actual message received
3866 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3867 const struct GNUNET_MessageHeader *message)
3869 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3870 const struct GNUNET_MessageHeader *enc_msg;
3871 struct DHT_MessageContext message_context;
3873 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3876 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3880 ntohs (message->type),
3881 GNUNET_h2s (&dht_msg->key),
3882 GNUNET_ntohll (dht_msg->unique_id));
3884 #if DEBUG_DHT_ROUTING
3885 if (dhtlog_handle != NULL)
3886 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3888 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3889 message_context.client = find_active_client (client);
3890 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3891 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3892 message_context.replication = ntohl (dht_msg->desired_replication_level);
3893 message_context.msg_options = ntohl (dht_msg->options);
3894 message_context.network_size = estimate_diameter();
3895 message_context.peer = &my_identity;
3896 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3897 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3898 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3899 increment_stats(STAT_GET_START);
3900 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3901 increment_stats(STAT_PUT_START);
3902 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3903 increment_stats(STAT_FIND_PEER_START);
3905 route_message(cls, enc_msg, &message_context);
3907 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3912 * Handler for any locally received DHT control messages,
3913 * sets malicious flags mostly for now.
3915 * @param cls closure for the service
3916 * @param client the client we received this message from
3917 * @param message the actual message received
3921 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3922 const struct GNUNET_MessageHeader *message)
3924 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3925 (const struct GNUNET_DHT_ControlMessage *) message;
3927 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3928 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3929 "CONTROL", ntohs(dht_control_msg->command));
3932 switch (ntohs(dht_control_msg->command))
3934 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3935 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3936 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3938 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3939 if (ntohs(dht_control_msg->variable) > 0)
3940 malicious_get_frequency = ntohs(dht_control_msg->variable);
3941 if (malicious_get_frequency == 0)
3942 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3943 if (malicious_getter != GNUNET_YES)
3944 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3945 malicious_getter = GNUNET_YES;
3946 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3947 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3949 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3950 if (ntohs(dht_control_msg->variable) > 0)
3951 malicious_put_frequency = ntohs(dht_control_msg->variable);
3952 if (malicious_put_frequency == 0)
3953 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3954 if (malicious_putter != GNUNET_YES)
3955 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3956 malicious_putter = GNUNET_YES;
3957 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3958 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3960 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3961 #if DEBUG_DHT_ROUTING
3962 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3963 dhtlog_handle->set_malicious(&my_identity);
3965 malicious_dropper = GNUNET_YES;
3966 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3967 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3970 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
3971 "%s:%s Unknown control command type `%d'!\n",
3973 ntohs(dht_control_msg->command));
3977 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3981 * Handler for any generic DHT stop messages, calls the appropriate handler
3982 * depending on message type (if processed locally)
3984 * @param cls closure for the service
3985 * @param client the client we received this message from
3986 * @param message the actual message received
3990 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3991 const struct GNUNET_MessageHeader *message)
3994 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3995 (const struct GNUNET_DHT_StopMessage *) message;
3996 struct DHTQueryRecord *record;
3997 struct DHTRouteSource *pos;
3999 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4000 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4001 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4003 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
4010 if ((pos->client != NULL) && (pos->client->client_handle == client))
4012 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
4013 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
4019 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4024 * Core handler for p2p route requests.
4027 handle_dht_p2p_route_request (void *cls,
4028 const struct GNUNET_PeerIdentity *peer,
4029 const struct GNUNET_MessageHeader *message,
4030 struct GNUNET_TIME_Relative latency, uint32_t distance)
4033 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4034 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4036 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4037 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4038 struct DHT_MessageContext *message_context;
4040 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
4042 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
4043 increment_stats("# route requests dropped due to high load");
4044 decrease_max_send_delay(get_max_send_delay());
4048 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4051 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4056 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4061 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4062 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4063 GNUNET_assert(message_context->bloom != NULL);
4064 message_context->hop_count = ntohl(incoming->hop_count);
4065 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
4066 message_context->replication = ntohl(incoming->desired_replication_level);
4067 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
4068 message_context->msg_options = ntohl(incoming->options);
4069 message_context->network_size = ntohl(incoming->network_size);
4070 message_context->peer = peer;
4071 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4072 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4073 route_message(cls, enc_msg, message_context);
4074 GNUNET_free(message_context);
4080 * Core handler for p2p route results.
4083 handle_dht_p2p_route_result (void *cls,
4084 const struct GNUNET_PeerIdentity *peer,
4085 const struct GNUNET_MessageHeader *message,
4086 struct GNUNET_TIME_Relative latency, uint32_t distance)
4089 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4090 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4092 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4093 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4094 struct DHT_MessageContext message_context;
4096 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4102 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4103 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4104 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4105 GNUNET_assert(message_context.bloom != NULL);
4106 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
4107 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
4108 message_context.msg_options = ntohl(incoming->options);
4109 message_context.hop_count = ntohl(incoming->hop_count);
4110 message_context.peer = peer;
4111 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
4112 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4113 route_result_message(cls, enc_msg, &message_context);
4119 * Receive the HELLO from transport service,
4120 * free current and replace if necessary.
4123 * @param message HELLO message of peer
4126 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4130 "Received our `%s' from transport service\n",
4134 GNUNET_assert (message != NULL);
4135 GNUNET_free_non_null(my_hello);
4136 my_hello = GNUNET_malloc(ntohs(message->size));
4137 memcpy(my_hello, message, ntohs(message->size));
4142 * Task run during shutdown.
4148 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4151 struct PeerInfo *pos;
4152 if (transport_handle != NULL)
4154 GNUNET_free_non_null(my_hello);
4155 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4156 GNUNET_TRANSPORT_disconnect(transport_handle);
4159 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4161 while (k_buckets[bucket_count].head != NULL)
4163 pos = k_buckets[bucket_count].head;
4165 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4166 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4168 delete_peer(pos, bucket_count);
4171 if (coreAPI != NULL)
4174 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4175 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4177 GNUNET_CORE_disconnect (coreAPI);
4179 if (datacache != NULL)
4182 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4183 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4185 GNUNET_DATACACHE_destroy (datacache);
4190 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4193 if (dhtlog_handle != NULL)
4194 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4196 GNUNET_free_non_null(my_short_id);
4201 * To be called on core init/fail.
4203 * @param cls service closure
4204 * @param server handle to the server for this service
4205 * @param identity the public identity of this peer
4206 * @param publicKey the public key of this peer
4209 core_init (void *cls,
4210 struct GNUNET_CORE_Handle *server,
4211 const struct GNUNET_PeerIdentity *identity,
4212 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4219 "%s: Connection to core FAILED!\n", "dht",
4220 GNUNET_i2s (identity));
4222 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
4223 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
4227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4228 "%s: Core connection initialized, I am peer: %s\n", "dht",
4229 GNUNET_i2s (identity));
4232 /* Copy our identity so we can use it */
4233 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4234 if (my_short_id != NULL)
4235 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4236 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4237 /* Set the server to local variable */
4240 if (dhtlog_handle != NULL)
4241 dhtlog_handle->insert_node (NULL, &my_identity);
4245 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4246 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4247 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4248 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4253 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4254 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4255 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4260 * Method called whenever a peer connects.
4262 * @param cls closure
4263 * @param peer peer identity this notification is about
4264 * @param latency reported latency of the connection with peer
4265 * @param distance reported distance (DV) to peer
4267 void handle_core_connect (void *cls,
4268 const struct GNUNET_PeerIdentity * peer,
4269 struct GNUNET_TIME_Relative latency,
4272 struct PeerInfo *ret;
4275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4276 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4279 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4281 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));
4285 if (datacache != NULL)
4286 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
4287 ret = try_add_peer(peer,
4288 find_current_bucket(&peer->hashPubKey),
4293 newly_found_peers++;
4294 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4297 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4298 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4303 * Method called whenever a peer disconnects.
4305 * @param cls closure
4306 * @param peer peer identity this notification is about
4308 void handle_core_disconnect (void *cls,
4310 GNUNET_PeerIdentity * peer)
4312 struct PeerInfo *to_remove;
4315 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");
4317 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4319 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));
4322 increment_stats(STAT_DISCONNECTS);
4323 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4324 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4325 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4326 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4327 delete_peer(to_remove, current_bucket);
4331 * Process dht requests.
4333 * @param cls closure
4334 * @param scheduler scheduler to use
4335 * @param server the initialized server
4336 * @param c configuration to use
4340 struct GNUNET_SCHEDULER_Handle *scheduler,
4341 struct GNUNET_SERVER_Handle *server,
4342 const struct GNUNET_CONFIGURATION_Handle *c)
4344 struct GNUNET_TIME_Relative next_send_time;
4345 unsigned long long temp_config_num;
4346 char *converge_modifier_buf;
4349 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4350 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4351 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4352 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4353 cfg, /* Main configuration */
4354 GNUNET_TIME_UNIT_FOREVER_REL,
4355 NULL, /* Closure passed to DHT functions */
4356 &core_init, /* Call core_init once connected */
4357 &handle_core_connect, /* Handle connects */
4358 &handle_core_disconnect, /* remove peers on disconnects */
4359 NULL, /* Do we care about "status" updates? */
4360 NULL, /* Don't want notified about all incoming messages */
4361 GNUNET_NO, /* For header only inbound notification */
4362 NULL, /* Don't want notified about all outbound messages */
4363 GNUNET_NO, /* For header only outbound notification */
4364 core_handlers); /* Register these handlers */
4366 if (coreAPI == NULL)
4368 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
4369 NULL, NULL, NULL, NULL, NULL);
4370 if (transport_handle != NULL)
4371 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4373 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4375 lowest_bucket = MAX_BUCKETS - 1;
4376 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4377 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4378 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4379 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4380 GNUNET_assert(all_known_peers != NULL);
4381 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4383 debug_routes = GNUNET_YES;
4387 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4390 strict_kademlia = GNUNET_YES;
4394 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4397 stop_on_closest = GNUNET_YES;
4401 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4404 stop_on_found = GNUNET_YES;
4408 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4409 "malicious_getter"))
4411 malicious_getter = GNUNET_YES;
4412 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4413 "MALICIOUS_GET_FREQUENCY",
4414 &malicious_get_frequency))
4415 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4418 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4422 max_hops = DEFAULT_MAX_HOPS;
4425 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4428 use_max_hops = GNUNET_YES;
4432 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4433 "malicious_putter"))
4435 malicious_putter = GNUNET_YES;
4436 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4437 "MALICIOUS_PUT_FREQUENCY",
4438 &malicious_put_frequency))
4439 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4442 dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
4443 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4445 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4449 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4450 "malicious_dropper"))
4452 malicious_dropper = GNUNET_YES;
4456 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4458 do_republish = GNUNET_NO;
4461 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4464 do_find_peer = GNUNET_NO;
4467 do_find_peer = GNUNET_YES;
4470 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4471 "use_real_distance"))
4472 use_real_distance = GNUNET_YES;
4475 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4476 "mysql_logging_extended"))
4478 debug_routes = GNUNET_YES;
4479 debug_routes_extended = GNUNET_YES;
4482 #if DEBUG_DHT_ROUTING
4483 if (GNUNET_YES == debug_routes)
4485 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4486 if (dhtlog_handle == NULL)
4488 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4489 "Could not connect to mysql logging server, logging will not happen!");
4494 converge_option = DHT_CONVERGE_SQUARE;
4496 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4499 converge_option = DHT_CONVERGE_LINEAR;
4501 else if (GNUNET_YES ==
4502 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4503 "converge_exponential"))
4505 converge_option = DHT_CONVERGE_EXPONENTIAL;
4507 else if (GNUNET_YES ==
4508 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4511 converge_option = DHT_CONVERGE_RANDOM;
4514 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4516 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4518 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4519 converge_modifier = 0.0;
4521 GNUNET_free(converge_modifier_buf);
4524 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4528 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4529 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4530 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4531 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4532 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4533 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4534 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4535 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4536 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4537 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4538 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4539 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4540 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4541 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4542 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4543 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4544 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4545 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4546 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4547 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4549 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4550 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4551 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4552 if (GNUNET_YES == do_find_peer)
4554 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4555 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4556 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4557 find_peer_context.start = GNUNET_TIME_absolute_get();
4558 GNUNET_SCHEDULER_add_delayed (sched,
4560 &send_find_peer_message, &find_peer_context);
4563 /* Scheduled the task to clean up when shutdown is called */
4564 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4565 GNUNET_TIME_UNIT_FOREVER_REL,
4566 &shutdown_task, NULL);
4570 * The main function for the dht service.
4572 * @param argc number of arguments from the command line
4573 * @param argv command line arguments
4574 * @return 0 ok, 1 on error
4577 main (int argc, char *const *argv)
4579 return (GNUNET_OK ==
4580 GNUNET_SERVICE_run (argc,
4583 GNUNET_SERVICE_OPTION_NONE,
4584 &run, NULL)) ? 0 : 1;