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);
1880 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1881 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1882 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1883 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1884 reply->header.size = htons (tsize);
1885 reply->reserved = 0;
1886 reply->unique_id = GNUNET_htonll (uid);
1888 memcpy (&reply[1], message, msize);
1889 add_pending_message (client, pending_message);
1893 * Consider whether or not we would like to have this peer added to
1894 * our routing table. Check whether bucket for this peer is full,
1895 * if so return negative; if not return positive. Since peers are
1896 * only added on CORE level connect, this doesn't actually add the
1897 * peer to the routing table.
1899 * @param peer the peer we are considering adding
1901 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1904 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1908 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1909 return GNUNET_NO; /* We already know this peer (are connected even!) */
1910 bucket = find_current_bucket(&peer->hashPubKey);
1912 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1919 * Main function that handles whether or not to route a result
1920 * message to other peers, or to send to our local client.
1922 * @param cls closure (unused, always should be NULL)
1923 * @param msg the result message to be routed
1924 * @param message_context context of the message we are routing
1926 * @return the number of peers the message was routed to,
1927 * GNUNET_SYSERR on failure
1929 static int route_result_message(void *cls,
1930 struct GNUNET_MessageHeader *msg,
1931 struct DHT_MessageContext *message_context)
1933 struct GNUNET_PeerIdentity new_peer;
1934 struct DHTQueryRecord *record;
1935 struct DHTRouteSource *pos;
1936 struct PeerInfo *peer_info;
1937 const struct GNUNET_MessageHeader *hello_msg;
1939 increment_stats(STAT_RESULTS);
1941 * If a find peer result message is received and contains a valid
1942 * HELLO for another peer, offer it to the transport service.
1944 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1946 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1949 hello_msg = &msg[1];
1950 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1952 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1956 else /* We have a valid hello, and peer id stored in new_peer */
1958 find_peer_context.count++;
1959 increment_stats(STAT_FIND_PEER_REPLY);
1960 if (GNUNET_YES == consider_peer(&new_peer))
1962 increment_stats(STAT_HELLOS_PROVIDED);
1963 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1964 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1969 if (malicious_dropper == GNUNET_YES)
1972 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1974 if (record == NULL) /* No record of this message! */
1977 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1978 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1979 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
1981 #if DEBUG_DHT_ROUTING
1982 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1984 dhtlog_handle->insert_route (NULL,
1985 message_context->unique_id,
1987 message_context->hop_count,
1990 &message_context->key,
1991 message_context->peer, NULL);
1994 if (message_context->bloom != NULL)
1996 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1997 message_context->bloom = NULL;
2005 #if STRICT_FORWARDING
2006 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2008 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2010 increment_stats("# find peer responses NOT forwarded (bloom match)");
2015 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2019 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2023 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2024 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2026 #if DEBUG_DHT_ROUTING
2027 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2029 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2030 message_context->hop_count,
2031 GNUNET_YES, &my_identity, &message_context->key,
2032 message_context->peer, NULL);
2035 increment_stats(STAT_RESULTS_TO_CLIENT);
2036 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2037 increment_stats(STAT_GET_REPLY);
2039 send_reply_to_client(pos->client, msg,
2040 message_context->unique_id,
2041 &message_context->key);
2043 else /* Send to peer */
2045 peer_info = find_peer_by_id(&pos->source);
2046 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2052 if (message_context->bloom == NULL)
2053 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2054 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2055 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2058 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2059 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2060 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2062 #if DEBUG_DHT_ROUTING
2063 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2065 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2067 message_context->hop_count,
2068 GNUNET_NO, &my_identity, &message_context->key,
2069 message_context->peer, &pos->source);
2072 forward_result_message(cls, msg, peer_info, message_context);
2077 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2078 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2079 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2085 if (message_context->bloom != NULL)
2086 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2091 * Iterator for local get request results,
2093 * @param cls closure for iterator, a DatacacheGetContext
2094 * @param exp when does this value expire?
2095 * @param key the key this data is stored under
2096 * @param size the size of the data identified by key
2097 * @param data the actual data
2098 * @param type the type of the data
2100 * @return GNUNET_OK to continue iteration, anything else
2101 * to stop iteration.
2104 datacache_get_iterator (void *cls,
2105 struct GNUNET_TIME_Absolute exp,
2106 const GNUNET_HashCode * key,
2107 uint32_t size, const char *data, uint32_t type)
2109 struct DHT_MessageContext *msg_ctx = cls;
2110 struct DHT_MessageContext *new_msg_ctx;
2111 struct GNUNET_DHT_GetResultMessage *get_result;
2113 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2114 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2116 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2117 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2119 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2120 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2121 get_result->header.size =
2122 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2123 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2124 get_result->type = htons (type);
2125 memcpy (&get_result[1], data, size);
2126 new_msg_ctx->peer = &my_identity;
2127 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2128 new_msg_ctx->hop_count = 0;
2129 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2130 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2131 increment_stats(STAT_GET_RESPONSE_START);
2132 route_result_message(cls, &get_result->header, new_msg_ctx);
2133 GNUNET_free(new_msg_ctx);
2134 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2135 // datacache_get_ctx->unique_id);
2136 GNUNET_free (get_result);
2142 * Server handler for all dht get requests, look for data,
2143 * if found, send response either to clients or other peers.
2145 * @param cls closure for service
2146 * @param msg the actual get message
2147 * @param message_context struct containing pertinent information about the get request
2149 * @return number of items found for GET request
2152 handle_dht_get (void *cls,
2153 const struct GNUNET_MessageHeader *msg,
2154 struct DHT_MessageContext *message_context)
2156 const struct GNUNET_DHT_GetMessage *get_msg;
2160 uint16_t xquery_size;
2161 unsigned int results;
2162 struct GNUNET_CONTAINER_BloomFilter *bf;
2166 msize = ntohs (msg->size);
2167 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2172 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2173 bf_size = ntohs (get_msg->bf_size);
2174 xquery_size = ntohs (get_msg->xquery_size);
2175 if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + xquery_size)
2180 end = (const char*) &get_msg[1];
2181 if (xquery_size == 0)
2187 xquery = (const void*) end;
2196 bf = GNUNET_CONTAINER_bloomfilter_init (end,
2198 GNUNET_DHT_GET_BLOOMFILTER_K);
2201 get_type = ntohs (get_msg->type);
2203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2204 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2208 GNUNET_h2s (&message_context->key),
2209 message_context->unique_id);
2211 increment_stats(STAT_GETS);
2214 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2216 GNUNET_CONTAINER_bloomfilter_free (bf);
2220 /* FIXME: put xquery / bf into message_context and use
2221 them for processing! */
2222 if (datacache != NULL)
2224 = GNUNET_DATACACHE_get (datacache,
2225 &message_context->key, get_type,
2226 &datacache_get_iterator,
2232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2233 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2234 results, "GET", message_context->unique_id);
2236 #if DEBUG_DHT_ROUTING
2237 if ((debug_routes) && (dhtlog_handle != NULL))
2239 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2240 message_context->hop_count, GNUNET_YES, &my_identity,
2241 &message_context->key);
2244 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2246 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2247 message_context->hop_count, GNUNET_YES,
2248 &my_identity, &message_context->key, message_context->peer,
2254 if (message_context->hop_count == 0) /* Locally initiated request */
2256 #if DEBUG_DHT_ROUTING
2257 if ((debug_routes) && (dhtlog_handle != NULL))
2259 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2260 message_context->hop_count, GNUNET_NO, &my_identity,
2261 &message_context->key);
2265 GNUNET_CONTAINER_bloomfilter_free (bf);
2270 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2272 GNUNET_HashCode *key = cls;
2273 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2280 * Server handler for initiating local dht find peer requests
2282 * @param cls closure for service
2283 * @param find_msg the actual find peer message
2284 * @param message_context struct containing pertinent information about the request
2288 handle_dht_find_peer (void *cls,
2289 const struct GNUNET_MessageHeader *find_msg,
2290 struct DHT_MessageContext *message_context)
2292 struct GNUNET_MessageHeader *find_peer_result;
2293 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2294 struct DHT_MessageContext *new_msg_ctx;
2295 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2298 GNUNET_HashCode *recent_hash;
2299 struct GNUNET_MessageHeader *other_hello;
2300 size_t other_hello_size;
2301 struct GNUNET_PeerIdentity peer_id;
2303 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2304 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2305 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2308 other_hello_size = 0;
2309 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2311 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2312 other_hello = GNUNET_malloc(other_hello_size);
2313 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2314 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)))
2316 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2317 GNUNET_free(other_hello);
2320 #if FIND_PEER_WITH_HELLO
2321 if (GNUNET_YES == consider_peer(&peer_id))
2323 increment_stats(STAT_HELLOS_PROVIDED);
2324 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2325 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2328 else /* We don't want this peer! */
2334 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2335 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2336 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&message_context->key),
2337 ntohs (find_msg->size),
2338 sizeof (struct GNUNET_MessageHeader));
2340 if (my_hello == NULL)
2343 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2344 "`%s': Our HELLO is null, can't return.\n",
2347 GNUNET_free_non_null(other_hello);
2351 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2352 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2354 increment_stats(STAT_BLOOM_FIND_PEER);
2355 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2356 GNUNET_free_non_null(other_hello);
2357 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2359 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2361 #if RESTRICT_FIND_PEER
2364 * Ignore any find peer requests from a peer we have seen very recently.
2366 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! */
2368 increment_stats("# dht find peer requests ignored (recently seen!)");
2369 GNUNET_free_non_null(other_hello);
2374 * Use this check to only allow the peer to respond to find peer requests if
2375 * it would be beneficial to have the requesting peer in this peers routing
2376 * table. Can be used to thwart peers flooding the network with find peer
2377 * requests that we don't care about. However, if a new peer is joining
2378 * the network and has no other peers this is a problem (assume all buckets
2379 * full, no one will respond!).
2381 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2382 if (GNUNET_NO == consider_peer(&peer_id))
2384 increment_stats("# dht find peer requests ignored (do not need!)");
2385 GNUNET_free_non_null(other_hello);
2390 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2391 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2392 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2393 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2395 /* Simplistic find_peer functionality, always return our hello */
2396 hello_size = ntohs(my_hello->size);
2397 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2399 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2401 GNUNET_break_op (0);
2402 GNUNET_free_non_null(other_hello);
2406 find_peer_result = GNUNET_malloc (tsize);
2407 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2408 find_peer_result->size = htons (tsize);
2409 memcpy (&find_peer_result[1], my_hello, hello_size);
2411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2412 "`%s': Sending hello size %d to requesting peer.\n",
2415 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2416 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2417 new_msg_ctx->peer = &my_identity;
2418 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2419 new_msg_ctx->hop_count = 0;
2420 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2421 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2422 increment_stats(STAT_FIND_PEER_ANSWER);
2423 route_result_message(cls, find_peer_result, new_msg_ctx);
2424 GNUNET_free(new_msg_ctx);
2425 #if DEBUG_DHT_ROUTING
2426 if ((debug_routes) && (dhtlog_handle != NULL))
2428 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2429 message_context->hop_count, GNUNET_YES, &my_identity,
2430 &message_context->key);
2433 GNUNET_free_non_null(other_hello);
2434 GNUNET_free(find_peer_result);
2438 * Task used to republish data.
2439 * Forward declaration; function call loop.
2441 * @param cls closure (a struct RepublishContext)
2442 * @param tc runtime context for this task
2445 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2448 * Server handler for initiating local dht put requests
2450 * @param cls closure for service
2451 * @param msg the actual put message
2452 * @param message_context struct containing pertinent information about the request
2455 handle_dht_put (void *cls,
2456 const struct GNUNET_MessageHeader *msg,
2457 struct DHT_MessageContext *message_context)
2459 struct GNUNET_DHT_PutMessage *put_msg;
2463 struct RepublishContext *put_context;
2465 GNUNET_assert (ntohs (msg->size) >=
2466 sizeof (struct GNUNET_DHT_PutMessage));
2469 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2470 put_type = ntohs (put_msg->type);
2472 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2475 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2477 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2478 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2479 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
2481 #if DEBUG_DHT_ROUTING
2482 if (message_context->hop_count == 0) /* Locally initiated request */
2484 if ((debug_routes) && (dhtlog_handle != NULL))
2486 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2487 message_context->hop_count, GNUNET_NO, &my_identity,
2488 &message_context->key);
2493 if (message_context->closest != GNUNET_YES)
2496 #if DEBUG_DHT_ROUTING
2497 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2499 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2500 message_context->hop_count, GNUNET_YES,
2501 &my_identity, &message_context->key, message_context->peer,
2505 if ((debug_routes) && (dhtlog_handle != NULL))
2507 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2508 message_context->hop_count, GNUNET_YES, &my_identity,
2509 &message_context->key);
2513 increment_stats(STAT_PUTS_INSERTED);
2514 if (datacache != NULL)
2516 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2517 (char *) &put_msg[1], put_type,
2518 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2520 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2522 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2523 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2524 put_context->type = put_type;
2525 GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
2529 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2530 "`%s:%s': %s request received, but have no datacache!\n",
2531 my_short_id, "DHT", "PUT");
2535 * Estimate the diameter of the network based
2536 * on how many buckets are currently in use.
2537 * Concept here is that the diameter of the network
2538 * is roughly the distance a message must travel in
2539 * order to reach its intended destination. Since
2540 * at each hop we expect to get one bit closer, and
2541 * we have one bit per bucket, the number of buckets
2542 * in use should be the largest number of hops for
2543 * a sucessful message. (of course, this assumes we
2544 * know all peers in the network!)
2546 * @return ballpark diameter figure
2548 static unsigned int estimate_diameter()
2550 return MAX_BUCKETS - lowest_bucket;
2554 * To how many peers should we (on average)
2555 * forward the request to obtain the desired
2556 * target_replication count (on average).
2558 * Always 0, 1 or 2 (don't send, send once, split)
2561 get_forward_count (unsigned int hop_count, size_t target_replication)
2564 double target_count;
2565 double random_probability;
2567 uint32_t random_value;
2569 unsigned int target_value;
2570 unsigned int diameter;
2573 * If we are behaving in strict kademlia mode, send multiple initial requests,
2574 * but then only send to 1 or 0 peers based strictly on the number of hops.
2576 if (strict_kademlia == GNUNET_YES)
2579 return DHT_KADEMLIA_REPLICATION;
2580 else if (hop_count < max_hops)
2586 /* FIXME: the smaller we think the network is the more lenient we should be for
2587 * routing right? The estimation below only works if we think we have reasonably
2588 * full routing tables, which for our RR topologies may not be the case!
2590 diameter = estimate_diameter ();
2591 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2595 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2596 "DHT", estimate_diameter(), lowest_bucket);
2600 else if (hop_count > max_hops)
2603 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2604 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2611 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2612 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2613 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2614 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2615 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2616 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2617 RAND_MAX)) / RAND_MAX;
2618 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2621 //while (target_value < target_count)
2622 if (target_value < target_count)
2623 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? */
2626 //if ((target_count + 1 - (double)target_value) > random_probability)
2627 if ((target_count) > random_probability)
2631 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2632 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));
2634 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2635 if (random_value < target_replication)
2638 return target_value;
2642 * Check whether my identity is closer than any known peers.
2643 * If a non-null bloomfilter is given, check if this is the closest
2644 * peer that hasn't already been routed to.
2646 * @param target hash code to check closeness to
2647 * @param bloom bloomfilter, exclude these entries from the decision
2649 * Return GNUNET_YES if node location is closest, GNUNET_NO
2653 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2659 struct PeerInfo *pos;
2660 unsigned int my_distance;
2662 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2665 bucket_num = find_current_bucket(target);
2667 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2668 my_distance = distance(&my_identity.hashPubKey, target);
2669 pos = k_buckets[bucket_num].head;
2671 while ((pos != NULL) && (count < bucket_size))
2673 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2676 continue; /* Skip already checked entries */
2679 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2680 if (other_bits > bits)
2682 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2684 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2686 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2693 GNUNET_GE_LOG (coreAPI->ectx,
2694 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2695 GNUNET_GE_BULK, "closest peer\n");
2696 printPeerBits (&closest);
2697 GNUNET_GE_LOG (coreAPI->ectx,
2698 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2699 GNUNET_GE_BULK, "me\n");
2700 printPeerBits (coreAPI->my_identity);
2701 GNUNET_GE_LOG (coreAPI->ectx,
2702 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2703 GNUNET_GE_BULK, "key\n");
2704 printKeyBits (target);
2705 GNUNET_GE_LOG (coreAPI->ectx,
2706 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2708 "closest peer inverse distance is %u, mine is %u\n",
2709 inverse_distance (target, &closest.hashPubKey),
2710 inverse_distance (target,
2711 &coreAPI->my_identity->hashPubKey));
2714 /* No peers closer, we are the closest! */
2720 * Return this peers adjusted value based on the convergence
2721 * function chosen. This is the key function for randomized
2722 * routing decisions.
2724 * @param target the key of the request
2725 * @param peer the peer we would like the value of
2726 * @param hops number of hops this message has already traveled
2728 * @return bit distance from target to peer raised to an exponent
2729 * adjusted based on the current routing convergence algorithm
2733 converge_distance (const GNUNET_HashCode *target,
2734 struct PeerInfo *peer,
2737 unsigned long long ret;
2738 unsigned int other_matching_bits;
2739 double converge_modifier = 0.0;
2740 double base_converge_modifier = .1;
2746 curr_max_hops = max_hops;
2748 curr_max_hops = (estimate_diameter() + 1) * 2;
2750 if (converge_modifier > 0)
2751 converge_modifier = converge_modifier * base_converge_modifier;
2754 converge_modifier = base_converge_modifier;
2755 base_converge_modifier = 0.0;
2758 GNUNET_assert(converge_modifier > 0);
2760 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2762 switch (converge_option)
2764 case DHT_CONVERGE_RANDOM:
2765 return 1; /* Always return 1, choose equally among all peers */
2766 case DHT_CONVERGE_LINEAR:
2767 calc_value = hops * curr_max_hops * converge_modifier;
2769 case DHT_CONVERGE_SQUARE:
2771 * Simple square based curve.
2773 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * converge_modifier));
2775 case DHT_CONVERGE_EXPONENTIAL:
2777 * Simple exponential curve.
2779 if (base_converge_modifier > 0)
2780 calc_value = (converge_modifier * hops * hops) / curr_max_hops;
2782 calc_value = (hops * hops) / curr_max_hops;
2788 /* Take the log (base e) of the number of bits matching the other peer */
2789 exponent = log(other_matching_bits);
2791 /* Check if we would overflow; our largest possible value is 2^64 = e^44.361419555836498 */
2792 if (exponent * calc_value >= 44.361419555836498)
2795 /* Clear errno and all math exceptions */
2797 feclearexcept(FE_ALL_EXCEPT);
2798 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2799 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2802 if (0 != fetestexcept(FE_OVERFLOW))
2803 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2804 if (0 != fetestexcept(FE_INVALID))
2805 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2806 if (0 != fetestexcept(FE_UNDERFLOW))
2807 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2815 * Comparison function for two struct PeerInfo's
2816 * which have already had their matching bits to
2817 * some target calculated.
2819 * @param p1 a pointer pointer to a struct PeerInfo
2820 * @param p2 a pointer pointer to a struct PeerInfo
2822 * @return 0 if equidistant to target,
2823 * -1 if p1 is closer,
2827 compare_peers (const void *p1, const void *p2)
2829 struct PeerInfo **first = (struct PeerInfo **)p1;
2830 struct PeerInfo **second = (struct PeerInfo **)p2;
2832 if ((*first)->matching_bits > (*second)->matching_bits)
2834 if ((*first)->matching_bits < (*second)->matching_bits)
2842 * Select a peer from the routing table that would be a good routing
2843 * destination for sending a message for "target". The resulting peer
2844 * must not be in the set of blocked peers.<p>
2846 * Note that we should not ALWAYS select the closest peer to the
2847 * target, peers further away from the target should be chosen with
2848 * exponentially declining probability.
2850 * @param target the key we are selecting a peer to route to
2851 * @param bloom a bloomfilter containing entries this request has seen already
2853 * @return Peer to route to, or NULL on error
2855 static struct PeerInfo *
2856 select_peer (const GNUNET_HashCode * target,
2857 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2862 unsigned int offset;
2863 unsigned int my_matching_bits;
2865 struct PeerInfo *pos;
2866 struct PeerInfo *sorted_closest[bucket_size];
2867 unsigned long long temp_converge_distance;
2868 unsigned long long total_distance;
2869 unsigned long long selected;
2871 unsigned long long stats_total_distance;
2875 unsigned int distance;
2876 unsigned int largest_distance;
2877 struct PeerInfo *chosen;
2879 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
2882 if (strict_kademlia == GNUNET_YES)
2884 largest_distance = 0;
2886 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2888 pos = k_buckets[bc].head;
2890 while ((pos != NULL) && (count < bucket_size))
2892 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2893 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2895 distance = inverse_distance (target, &pos->id.hashPubKey);
2896 if (distance > largest_distance)
2899 largest_distance = distance;
2907 if ((largest_distance > 0) && (chosen != NULL))
2909 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2920 /* Three steps: order peers in closest bucket (most matching bits).
2921 * Then go over all LOWER buckets (matching same bits we do)
2922 * Then go over all HIGHER buckets (matching less then we do)
2925 closest_bucket = find_current_bucket(target);
2926 GNUNET_assert(closest_bucket >= lowest_bucket);
2927 pos = k_buckets[closest_bucket].head;
2929 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
2930 memset(sorted_closest, 0, sizeof(sorted_closest));
2931 /* Put any peers in the closest bucket in the sorting array */
2932 while ((pos != NULL) && (count < bucket_size))
2934 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2938 continue; /* Ignore bloomfiltered peers */
2940 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2941 sorted_closest[offset] = pos;
2947 /* Sort the peers in descending order */
2948 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
2950 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
2951 for (i = 0; i < offset; i++)
2953 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
2954 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
2955 break; /* Ignore bloomfiltered peers */
2956 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2957 total_distance += temp_converge_distance;
2959 break; /* overflow case */
2962 /* Now handle peers in lower buckets (matches same # of bits as target) */
2963 for (bc = lowest_bucket; bc < closest_bucket; bc++)
2965 pos = k_buckets[bc].head;
2967 while ((pos != NULL) && (count < bucket_size))
2969 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2973 continue; /* Ignore bloomfiltered peers */
2975 temp_converge_distance = converge_distance(target, pos, hops);
2976 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2977 total_distance += temp_converge_distance;
2979 break; /* overflow case */
2985 /* Now handle all the further away peers */
2986 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
2988 pos = k_buckets[bc].head;
2990 while ((pos != NULL) && (count < bucket_size))
2992 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2996 continue; /* Ignore bloomfiltered peers */
2998 temp_converge_distance = converge_distance(target, pos, hops);
2999 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3000 total_distance += temp_converge_distance;
3002 break; /* overflow case */
3008 if (total_distance == 0) /* No peers to select from! */
3010 increment_stats("# select_peer, total_distance == 0");
3014 #if DEBUG_DHT_ROUTING > 1
3017 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3018 stats_total_distance = 0;
3019 for (i = 0; i < offset; i++)
3021 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3022 break; /* Ignore bloomfiltered peers */
3023 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3024 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3025 stats_total_distance += temp_converge_distance;
3027 break; /* overflow case */
3028 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);
3031 /* Now handle peers in lower buckets (matches same # of bits as target) */
3032 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3034 pos = k_buckets[bc].head;
3036 while ((pos != NULL) && (count < bucket_size))
3038 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3042 continue; /* Ignore bloomfiltered peers */
3044 temp_converge_distance = converge_distance(target, pos, hops);
3045 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3046 stats_total_distance += temp_converge_distance;
3048 break; /* overflow case */
3049 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);
3055 /* Now handle all the further away peers */
3056 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3058 pos = k_buckets[bc].head;
3060 while ((pos != NULL) && (count < bucket_size))
3062 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3066 continue; /* Ignore bloomfiltered peers */
3068 temp_converge_distance = converge_distance(target, pos, hops);
3069 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3070 stats_total_distance += temp_converge_distance;
3072 break; /* overflow case */
3073 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);
3078 /* END PRINT STATS */
3081 /* Now actually choose a peer */
3082 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3084 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3085 for (i = 0; i < offset; i++)
3087 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3088 break; /* Ignore bloomfiltered peers */
3089 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3090 if (temp_converge_distance >= selected)
3091 return sorted_closest[i];
3093 selected -= temp_converge_distance;
3096 /* Now handle peers in lower buckets (matches same # of bits as target) */
3097 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3099 pos = k_buckets[bc].head;
3101 while ((pos != NULL) && (count < bucket_size))
3103 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3107 continue; /* Ignore bloomfiltered peers */
3109 temp_converge_distance = converge_distance(target, pos, hops);
3110 if (temp_converge_distance >= selected)
3113 selected -= temp_converge_distance;
3119 /* Now handle all the further away peers */
3120 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3122 pos = k_buckets[bc].head;
3124 while ((pos != NULL) && (count < bucket_size))
3126 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3130 continue; /* Ignore bloomfiltered peers */
3132 temp_converge_distance = converge_distance(target, pos, hops);
3133 if (temp_converge_distance >= selected)
3136 selected -= temp_converge_distance;
3142 increment_stats("# failed to select peer");
3148 * Task used to remove recent entries, either
3149 * after timeout, when full, or on shutdown.
3151 * @param cls the entry to remove
3152 * @param tc context, reason, etc.
3155 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3157 struct RecentRequest *req = cls;
3158 static GNUNET_HashCode hash;
3160 GNUNET_assert(req != NULL);
3161 hash_from_uid(req->uid, &hash);
3162 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3163 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3164 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3167 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3169 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3170 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3176 * Task used to remove forwarding entries, either
3177 * after timeout, when full, or on shutdown.
3179 * @param cls the entry to remove
3180 * @param tc context, reason, etc.
3183 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3185 struct DHTRouteSource *source_info = cls;
3186 struct DHTQueryRecord *record;
3187 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3188 record = source_info->record;
3189 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3191 if (record->head == NULL) /* No more entries in DLL */
3193 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3194 GNUNET_free(record);
3196 if (source_info->find_peers_responded != NULL)
3197 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3198 GNUNET_free(source_info);
3202 * Remember this routing request so that if a reply is
3203 * received we can either forward it to the correct peer
3204 * or return the result locally.
3206 * @param cls DHT service closure
3207 * @param msg_ctx Context of the route request
3209 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3211 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
3213 struct DHTQueryRecord *record;
3214 struct DHTRouteSource *source_info;
3215 struct DHTRouteSource *pos;
3216 struct GNUNET_TIME_Absolute now;
3217 unsigned int current_size;
3219 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3220 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3222 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3223 GNUNET_assert(source_info != NULL);
3224 record = source_info->record;
3225 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3226 if (record->head == NULL) /* No more entries in DLL */
3228 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3229 GNUNET_free(record);
3231 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
3232 if (source_info->find_peers_responded != NULL)
3233 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3234 GNUNET_free(source_info);
3235 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3237 now = GNUNET_TIME_absolute_get();
3238 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3239 if (record != NULL) /* Already know this request! */
3244 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3245 break; /* Already have this peer in reply list! */
3248 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3250 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3256 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3257 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3258 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3261 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3262 source_info->record = record;
3263 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3264 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3265 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3266 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3267 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3269 source_info->client = msg_ctx->client;
3270 now = GNUNET_TIME_absolute_get_forever();
3272 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3274 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3275 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3276 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3283 * Main function that handles whether or not to route a message to other
3286 * @param cls closure for dht service (NULL)
3287 * @param msg the message to be routed
3288 * @param message_context the context containing all pertinent information about the message
3290 * @return the number of peers the message was routed to,
3291 * GNUNET_SYSERR on failure
3293 static int route_message(void *cls,
3294 const struct GNUNET_MessageHeader *msg,
3295 struct DHT_MessageContext *message_context)
3299 struct PeerInfo *selected;
3300 #if DEBUG_DHT_ROUTING > 1
3301 struct PeerInfo *nearest;
3303 unsigned int forward_count;
3304 struct RecentRequest *recent_req;
3305 GNUNET_HashCode unique_hash;
3306 char *stat_forward_count;
3307 char *temp_stat_str;
3308 #if DEBUG_DHT_ROUTING
3312 if (malicious_dropper == GNUNET_YES)
3314 #if DEBUG_DHT_ROUTING
3315 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3317 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3318 message_context->hop_count, GNUNET_SYSERR,
3319 &my_identity, &message_context->key, message_context->peer,
3323 if (message_context->bloom != NULL)
3324 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3328 increment_stats(STAT_ROUTES);
3329 /* Semantics of this call means we find whether we are the closest peer out of those already
3330 * routed to on this messages path.
3332 global_closest = am_closest_peer(&message_context->key, NULL);
3333 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3334 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3335 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3336 increment_stats(stat_forward_count);
3337 GNUNET_free(stat_forward_count);
3338 if (message_context->bloom == NULL)
3339 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3341 if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3345 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3346 * any closer peers (which is being checked for below). Since we are doing recursive
3347 * routing we have no choice but to stop forwarding in this case. This means that at
3348 * any given step the request may NOT be forwarded to alpha peers (because routes will
3349 * stop and the parallel route will not be aware of it). Of course, assuming that we
3350 * have fulfilled the Kademlia requirements for routing table fullness this will never
3351 * ever ever be a problem.
3353 * However, is this fair?
3355 * Since we use these requests to build our routing tables (and we build them in the
3356 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3357 * routing tables still get constructed.
3359 if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3362 #if DEBUG_DHT_ROUTING
3363 if (forward_count == 0)
3364 ret = GNUNET_SYSERR;
3368 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3370 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3371 message_context->hop_count, ret,
3372 &my_identity, &message_context->key, message_context->peer,
3377 switch (ntohs(msg->type))
3379 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3380 cache_response (cls, message_context);
3381 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3384 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3385 increment_stats(STAT_PUTS);
3386 message_context->closest = global_closest;
3387 handle_dht_put (cls, msg, message_context);
3389 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3390 increment_stats(STAT_FIND_PEER);
3391 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3393 cache_response (cls, message_context);
3394 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3395 handle_dht_find_peer (cls, msg, message_context);
3397 #if DEBUG_DHT_ROUTING
3398 if (message_context->hop_count == 0) /* Locally initiated request */
3400 if ((debug_routes) && (dhtlog_handle != NULL))
3402 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3403 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3404 message_context->hop_count, GNUNET_NO, &my_identity,
3405 &message_context->key);
3411 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3412 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3415 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3416 hash_from_uid (message_context->unique_id, &unique_hash);
3417 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3419 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3420 GNUNET_assert(recent_req != NULL);
3421 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3422 increment_stats(STAT_DUPLICATE_UID);
3425 increment_stats(STAT_RECENT_SEEN);
3426 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3431 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3432 recent_req->uid = message_context->unique_id;
3433 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3434 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3435 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3436 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3437 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3440 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3442 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3443 GNUNET_assert(recent_req != NULL);
3444 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3445 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3448 for (i = 0; i < forward_count; i++)
3450 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3452 if (selected != NULL)
3454 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
3455 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
3457 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
3458 if (temp_stat_str != NULL)
3460 increment_stats(temp_stat_str);
3461 GNUNET_free(temp_stat_str);
3463 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3464 #if DEBUG_DHT_ROUTING > 1
3465 nearest = find_closest_peer(&message_context->key);
3466 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3467 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3468 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3469 "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));
3470 GNUNET_free(nearest_buf);
3472 #if DEBUG_DHT_ROUTING
3473 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3475 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3476 message_context->hop_count, GNUNET_NO,
3477 &my_identity, &message_context->key, message_context->peer,
3481 forward_message(cls, msg, selected, message_context);
3485 if (message_context->bloom != NULL)
3487 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3488 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3491 return forward_count;
3495 * Iterator for local get request results,
3497 * @param cls closure for iterator, NULL
3498 * @param exp when does this value expire?
3499 * @param key the key this data is stored under
3500 * @param size the size of the data identified by key
3501 * @param data the actual data
3502 * @param type the type of the data
3504 * @return GNUNET_OK to continue iteration, anything else
3505 * to stop iteration.
3508 republish_content_iterator (void *cls,
3509 struct GNUNET_TIME_Absolute exp,
3510 const GNUNET_HashCode * key,
3511 uint32_t size, const char *data, uint32_t type)
3514 struct DHT_MessageContext *new_msg_ctx;
3515 struct GNUNET_DHT_PutMessage *put_msg;
3517 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3518 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3520 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3523 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3524 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3525 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3526 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3527 put_msg->type = htons (type);
3528 memcpy (&put_msg[1], data, size);
3529 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3530 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3531 new_msg_ctx->msg_options = ntohl (0);
3532 new_msg_ctx->network_size = estimate_diameter();
3533 new_msg_ctx->peer = &my_identity;
3534 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3535 new_msg_ctx->hop_count = 0;
3536 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3537 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3538 increment_stats(STAT_PUT_START);
3539 route_message(cls, &put_msg->header, new_msg_ctx);
3541 GNUNET_free(new_msg_ctx);
3542 GNUNET_free (put_msg);
3547 * Task used to republish data.
3549 * @param cls closure (a struct RepublishContext)
3550 * @param tc runtime context for this task
3553 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3555 struct RepublishContext *put_context = cls;
3557 unsigned int results;
3559 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3561 GNUNET_free(put_context);
3565 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3566 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3567 if (results == 0) /* Data must have expired */
3568 GNUNET_free(put_context);
3569 else /* Reschedule task for next time period */
3570 GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);
3576 * Iterator over hash map entries.
3578 * @param cls client to search for in source routes
3579 * @param key current key code (ignored)
3580 * @param value value in the hash map, a DHTQueryRecord
3581 * @return GNUNET_YES if we should continue to
3585 static int find_client_records (void *cls,
3586 const GNUNET_HashCode * key, void *value)
3588 struct ClientList *client = cls;
3589 struct DHTQueryRecord *record = value;
3590 struct DHTRouteSource *pos;
3594 if (pos->client == client)
3600 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3601 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3602 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3603 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3605 if (pos->find_peers_responded != NULL)
3606 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3609 if (record->head == NULL) /* No more entries in DLL */
3611 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3612 GNUNET_free(record);
3618 * Functions with this signature are called whenever a client
3619 * is disconnected on the network level.
3621 * @param cls closure (NULL for dht)
3622 * @param client identification of the client; NULL
3623 * for the last call when the server is destroyed
3625 static void handle_client_disconnect (void *cls,
3626 struct GNUNET_SERVER_Client* client)
3628 struct ClientList *pos = client_list;
3629 struct ClientList *prev;
3630 struct ClientList *found;
3631 struct PendingMessage *reply;
3637 if (pos->client_handle == client)
3640 prev->next = pos->next;
3642 client_list = pos->next;
3652 while(NULL != (reply = found->pending_head))
3654 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3657 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3663 * Find a client if it exists, add it otherwise.
3665 * @param client the server handle to the client
3667 * @return the client if found, a new client otherwise
3669 static struct ClientList *
3670 find_active_client (struct GNUNET_SERVER_Client *client)
3672 struct ClientList *pos = client_list;
3673 struct ClientList *ret;
3677 if (pos->client_handle == client)
3682 ret = GNUNET_malloc (sizeof (struct ClientList));
3683 ret->client_handle = client;
3684 ret->next = client_list;
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_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3699 static struct GNUNET_DHT_PutMessage put_message;
3700 static struct DHT_MessageContext message_context;
3701 static GNUNET_HashCode key;
3702 uint32_t random_key;
3704 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3707 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3708 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3709 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3710 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3711 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3712 message_context.client = NULL;
3713 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3714 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3715 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3716 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3717 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3718 message_context.msg_options = ntohl (0);
3719 message_context.network_size = estimate_diameter();
3720 message_context.peer = &my_identity;
3721 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3722 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3723 #if DEBUG_DHT_ROUTING
3724 if (dhtlog_handle != NULL)
3725 dhtlog_handle->insert_dhtkey(NULL, &key);
3727 increment_stats(STAT_PUT_START);
3728 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3729 route_message(NULL, &put_message.header, &message_context);
3730 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3735 * Task to send a malicious put message across the network.
3737 * @param cls closure for this task
3738 * @param tc the context under which the task is running
3741 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3743 static struct GNUNET_DHT_GetMessage get_message;
3744 struct DHT_MessageContext message_context;
3745 static GNUNET_HashCode key;
3746 uint32_t random_key;
3748 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3751 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3752 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3753 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3754 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3755 message_context.client = NULL;
3756 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3757 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3758 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3759 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3760 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3761 message_context.msg_options = ntohl (0);
3762 message_context.network_size = estimate_diameter();
3763 message_context.peer = &my_identity;
3764 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3765 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3766 #if DEBUG_DHT_ROUTING
3767 if (dhtlog_handle != NULL)
3768 dhtlog_handle->insert_dhtkey(NULL, &key);
3770 increment_stats(STAT_GET_START);
3771 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3772 route_message (NULL, &get_message.header, &message_context);
3773 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3777 * Iterator over hash map entries.
3779 * @param cls closure
3780 * @param key current key code
3781 * @param value value in the hash map
3782 * @return GNUNET_YES if we should continue to
3787 add_known_to_bloom (void *cls,
3788 const GNUNET_HashCode * key,
3791 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3792 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3797 * Task to send a find peer message for our own peer identifier
3798 * so that we can find the closest peers in the network to ourselves
3799 * and attempt to connect to them.
3801 * @param cls closure for this task
3802 * @param tc the context under which the task is running
3805 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3807 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3808 struct DHT_MessageContext message_context;
3810 struct GNUNET_TIME_Relative next_send_time;
3811 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3813 struct GNUNET_TIME_Relative time_diff;
3814 struct GNUNET_TIME_Absolute end;
3816 double count_per_interval;
3818 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3821 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! */
3823 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3824 GNUNET_SCHEDULER_add_delayed (sched,
3825 GNUNET_TIME_UNIT_MINUTES,
3826 &send_find_peer_message, NULL);
3827 newly_found_peers = 0;
3831 increment_stats(STAT_FIND_PEER_START);
3833 end = GNUNET_TIME_absolute_get();
3834 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3836 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3838 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3839 count_per_interval = find_peer_context.count / multiplier;
3843 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3844 count_per_interval = find_peer_context.count * multiplier;
3848 #if FIND_PEER_WITH_HELLO
3849 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3850 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3851 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3853 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3854 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3856 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3857 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3858 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3859 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3860 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3861 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3862 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3863 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3864 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3865 message_context.network_size = estimate_diameter();
3866 message_context.peer = &my_identity;
3867 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3868 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3870 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3871 GNUNET_free(find_peer_msg);
3872 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3873 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3875 if (newly_found_peers < bucket_size)
3877 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3878 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3879 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3883 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3884 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3885 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3888 GNUNET_assert (next_send_time.value != 0);
3889 find_peer_context.count = 0;
3890 newly_found_peers = 0;
3891 find_peer_context.start = GNUNET_TIME_absolute_get();
3892 if (GNUNET_YES == do_find_peer)
3894 GNUNET_SCHEDULER_add_delayed (sched,
3896 &send_find_peer_message, NULL);
3901 * Handler for any generic DHT messages, calls the appropriate handler
3902 * depending on message type, sends confirmation if responses aren't otherwise
3905 * @param cls closure for the service
3906 * @param client the client we received this message from
3907 * @param message the actual message received
3910 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3911 const struct GNUNET_MessageHeader *message)
3913 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3914 const struct GNUNET_MessageHeader *enc_msg;
3915 struct DHT_MessageContext message_context;
3917 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3919 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3920 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3924 ntohs (message->type),
3925 GNUNET_h2s (&dht_msg->key),
3926 GNUNET_ntohll (dht_msg->unique_id));
3928 #if DEBUG_DHT_ROUTING
3929 if (dhtlog_handle != NULL)
3930 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3932 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3933 message_context.client = find_active_client (client);
3934 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3935 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3936 message_context.replication = ntohl (dht_msg->desired_replication_level);
3937 message_context.msg_options = ntohl (dht_msg->options);
3938 message_context.network_size = estimate_diameter();
3939 message_context.peer = &my_identity;
3940 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3941 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3942 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3943 increment_stats(STAT_GET_START);
3944 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3945 increment_stats(STAT_PUT_START);
3946 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3947 increment_stats(STAT_FIND_PEER_START);
3949 route_message(cls, enc_msg, &message_context);
3951 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3956 * Handler for any locally received DHT control messages,
3957 * sets malicious flags mostly for now.
3959 * @param cls closure for the service
3960 * @param client the client we received this message from
3961 * @param message the actual message received
3965 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3966 const struct GNUNET_MessageHeader *message)
3968 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3969 (const struct GNUNET_DHT_ControlMessage *) message;
3971 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3972 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3973 "CONTROL", ntohs(dht_control_msg->command));
3976 switch (ntohs(dht_control_msg->command))
3978 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3979 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3980 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3982 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3983 if (ntohs(dht_control_msg->variable) > 0)
3984 malicious_get_frequency = ntohs(dht_control_msg->variable);
3985 if (malicious_get_frequency == 0)
3986 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3987 if (malicious_getter != GNUNET_YES)
3988 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3989 malicious_getter = GNUNET_YES;
3990 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3991 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3993 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3994 if (ntohs(dht_control_msg->variable) > 0)
3995 malicious_put_frequency = ntohs(dht_control_msg->variable);
3996 if (malicious_put_frequency == 0)
3997 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3998 if (malicious_putter != GNUNET_YES)
3999 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
4000 malicious_putter = GNUNET_YES;
4001 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4002 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4004 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4005 #if DEBUG_DHT_ROUTING
4006 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4007 dhtlog_handle->set_malicious(&my_identity);
4009 malicious_dropper = GNUNET_YES;
4010 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4011 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4014 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4015 "%s:%s Unknown control command type `%d'!\n",
4017 ntohs(dht_control_msg->command));
4021 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4025 * Handler for any generic DHT stop messages, calls the appropriate handler
4026 * depending on message type (if processed locally)
4028 * @param cls closure for the service
4029 * @param client the client we received this message from
4030 * @param message the actual message received
4034 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4035 const struct GNUNET_MessageHeader *message)
4038 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4039 (const struct GNUNET_DHT_StopMessage *) message;
4040 struct DHTQueryRecord *record;
4041 struct DHTRouteSource *pos;
4043 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4044 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4045 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4047 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
4054 if ((pos->client != NULL) && (pos->client->client_handle == client))
4056 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
4057 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
4063 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4068 * Core handler for p2p route requests.
4071 handle_dht_p2p_route_request (void *cls,
4072 const struct GNUNET_PeerIdentity *peer,
4073 const struct GNUNET_MessageHeader *message,
4074 struct GNUNET_TIME_Relative latency, uint32_t distance)
4077 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4078 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4080 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4081 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4082 struct DHT_MessageContext *message_context;
4084 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
4086 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
4087 increment_stats("# route requests dropped due to high load");
4088 decrease_max_send_delay(get_max_send_delay());
4092 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4095 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4100 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4105 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4106 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4107 GNUNET_assert(message_context->bloom != NULL);
4108 message_context->hop_count = ntohl(incoming->hop_count);
4109 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
4110 message_context->replication = ntohl(incoming->desired_replication_level);
4111 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
4112 message_context->msg_options = ntohl(incoming->options);
4113 message_context->network_size = ntohl(incoming->network_size);
4114 message_context->peer = peer;
4115 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4116 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4117 route_message(cls, enc_msg, message_context);
4118 GNUNET_free(message_context);
4124 * Core handler for p2p route results.
4127 handle_dht_p2p_route_result (void *cls,
4128 const struct GNUNET_PeerIdentity *peer,
4129 const struct GNUNET_MessageHeader *message,
4130 struct GNUNET_TIME_Relative latency, uint32_t distance)
4133 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4134 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4136 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4137 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4138 struct DHT_MessageContext message_context;
4140 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4146 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4147 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4148 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4149 GNUNET_assert(message_context.bloom != NULL);
4150 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
4151 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
4152 message_context.msg_options = ntohl(incoming->options);
4153 message_context.hop_count = ntohl(incoming->hop_count);
4154 message_context.peer = peer;
4155 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
4156 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4157 route_result_message(cls, enc_msg, &message_context);
4163 * Receive the HELLO from transport service,
4164 * free current and replace if necessary.
4167 * @param message HELLO message of peer
4170 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4173 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4174 "Received our `%s' from transport service\n",
4178 GNUNET_assert (message != NULL);
4179 GNUNET_free_non_null(my_hello);
4180 my_hello = GNUNET_malloc(ntohs(message->size));
4181 memcpy(my_hello, message, ntohs(message->size));
4186 * Task run during shutdown.
4192 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4195 struct PeerInfo *pos;
4196 if (transport_handle != NULL)
4198 GNUNET_free_non_null(my_hello);
4199 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4200 GNUNET_TRANSPORT_disconnect(transport_handle);
4203 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4205 while (k_buckets[bucket_count].head != NULL)
4207 pos = k_buckets[bucket_count].head;
4209 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4210 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4212 delete_peer(pos, bucket_count);
4215 if (coreAPI != NULL)
4218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4219 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4221 GNUNET_CORE_disconnect (coreAPI);
4223 if (datacache != NULL)
4226 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4227 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4229 GNUNET_DATACACHE_destroy (datacache);
4234 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4237 if (dhtlog_handle != NULL)
4238 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4240 GNUNET_free_non_null(my_short_id);
4245 * To be called on core init/fail.
4247 * @param cls service closure
4248 * @param server handle to the server for this service
4249 * @param identity the public identity of this peer
4250 * @param publicKey the public key of this peer
4253 core_init (void *cls,
4254 struct GNUNET_CORE_Handle *server,
4255 const struct GNUNET_PeerIdentity *identity,
4256 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4262 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4263 "%s: Connection to core FAILED!\n", "dht",
4264 GNUNET_i2s (identity));
4266 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
4267 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
4271 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4272 "%s: Core connection initialized, I am peer: %s\n", "dht",
4273 GNUNET_i2s (identity));
4276 /* Copy our identity so we can use it */
4277 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4278 if (my_short_id != NULL)
4279 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4280 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4281 /* Set the server to local variable */
4284 if (dhtlog_handle != NULL)
4285 dhtlog_handle->insert_node (NULL, &my_identity);
4289 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4290 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4291 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4292 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4297 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4298 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4299 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4304 * Method called whenever a peer connects.
4306 * @param cls closure
4307 * @param peer peer identity this notification is about
4308 * @param latency reported latency of the connection with peer
4309 * @param distance reported distance (DV) to peer
4311 void handle_core_connect (void *cls,
4312 const struct GNUNET_PeerIdentity * peer,
4313 struct GNUNET_TIME_Relative latency,
4316 struct PeerInfo *ret;
4319 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4320 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4323 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4325 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));
4329 if (datacache != NULL)
4330 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
4331 ret = try_add_peer(peer,
4332 find_current_bucket(&peer->hashPubKey),
4337 newly_found_peers++;
4338 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4341 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4342 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4347 * Method called whenever a peer disconnects.
4349 * @param cls closure
4350 * @param peer peer identity this notification is about
4352 void handle_core_disconnect (void *cls,
4354 GNUNET_PeerIdentity * peer)
4356 struct PeerInfo *to_remove;
4359 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");
4361 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4363 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));
4366 increment_stats(STAT_DISCONNECTS);
4367 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4368 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4369 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4370 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4371 delete_peer(to_remove, current_bucket);
4375 * Process dht requests.
4377 * @param cls closure
4378 * @param scheduler scheduler to use
4379 * @param server the initialized server
4380 * @param c configuration to use
4384 struct GNUNET_SCHEDULER_Handle *scheduler,
4385 struct GNUNET_SERVER_Handle *server,
4386 const struct GNUNET_CONFIGURATION_Handle *c)
4388 struct GNUNET_TIME_Relative next_send_time;
4389 unsigned long long temp_config_num;
4390 char *converge_modifier_buf;
4393 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4394 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4395 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4396 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4397 cfg, /* Main configuration */
4398 GNUNET_TIME_UNIT_FOREVER_REL,
4399 NULL, /* Closure passed to DHT functions */
4400 &core_init, /* Call core_init once connected */
4401 &handle_core_connect, /* Handle connects */
4402 &handle_core_disconnect, /* remove peers on disconnects */
4403 NULL, /* Do we care about "status" updates? */
4404 NULL, /* Don't want notified about all incoming messages */
4405 GNUNET_NO, /* For header only inbound notification */
4406 NULL, /* Don't want notified about all outbound messages */
4407 GNUNET_NO, /* For header only outbound notification */
4408 core_handlers); /* Register these handlers */
4410 if (coreAPI == NULL)
4412 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
4413 NULL, NULL, NULL, NULL, NULL);
4414 if (transport_handle != NULL)
4415 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4417 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4419 lowest_bucket = MAX_BUCKETS - 1;
4420 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4421 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4422 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4423 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4424 GNUNET_assert(all_known_peers != NULL);
4425 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4427 debug_routes = GNUNET_YES;
4431 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4434 strict_kademlia = GNUNET_YES;
4438 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4441 stop_on_closest = GNUNET_YES;
4445 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4448 stop_on_found = GNUNET_YES;
4452 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4453 "malicious_getter"))
4455 malicious_getter = GNUNET_YES;
4456 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4457 "MALICIOUS_GET_FREQUENCY",
4458 &malicious_get_frequency))
4459 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4462 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4466 max_hops = DEFAULT_MAX_HOPS;
4469 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4472 use_max_hops = GNUNET_YES;
4476 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4477 "malicious_putter"))
4479 malicious_putter = GNUNET_YES;
4480 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4481 "MALICIOUS_PUT_FREQUENCY",
4482 &malicious_put_frequency))
4483 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4486 dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
4487 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4489 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4493 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4494 "malicious_dropper"))
4496 malicious_dropper = GNUNET_YES;
4500 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4502 do_republish = GNUNET_NO;
4505 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4508 do_find_peer = GNUNET_NO;
4511 do_find_peer = GNUNET_YES;
4514 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4515 "use_real_distance"))
4516 use_real_distance = GNUNET_YES;
4519 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4520 "mysql_logging_extended"))
4522 debug_routes = GNUNET_YES;
4523 debug_routes_extended = GNUNET_YES;
4526 #if DEBUG_DHT_ROUTING
4527 if (GNUNET_YES == debug_routes)
4529 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4530 if (dhtlog_handle == NULL)
4532 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4533 "Could not connect to mysql logging server, logging will not happen!");
4538 converge_option = DHT_CONVERGE_SQUARE;
4540 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4543 converge_option = DHT_CONVERGE_LINEAR;
4545 else if (GNUNET_YES ==
4546 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4547 "converge_exponential"))
4549 converge_option = DHT_CONVERGE_EXPONENTIAL;
4551 else if (GNUNET_YES ==
4552 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4555 converge_option = DHT_CONVERGE_RANDOM;
4558 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4560 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4562 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4563 converge_modifier = 0.0;
4565 GNUNET_free(converge_modifier_buf);
4568 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4572 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4573 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4574 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4575 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4576 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4577 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4578 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4579 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4580 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4581 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4582 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4583 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4584 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4585 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4586 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4587 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4588 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4589 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4590 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4591 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4593 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4594 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4595 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4596 if (GNUNET_YES == do_find_peer)
4598 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4599 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4600 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4601 find_peer_context.start = GNUNET_TIME_absolute_get();
4602 GNUNET_SCHEDULER_add_delayed (sched,
4604 &send_find_peer_message, &find_peer_context);
4607 /* Scheduled the task to clean up when shutdown is called */
4608 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4609 GNUNET_TIME_UNIT_FOREVER_REL,
4610 &shutdown_task, NULL);
4614 * The main function for the dht service.
4616 * @param argc number of arguments from the command line
4617 * @param argv command line arguments
4618 * @return 0 ok, 1 on error
4621 main (int argc, char *const *argv)
4623 return (GNUNET_OK ==
4624 GNUNET_SERVICE_run (argc,
4627 GNUNET_SERVICE_OPTION_NONE,
4628 &run, NULL)) ? 0 : 1;