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.)
1028 forward_result_message (void *cls,
1029 const struct GNUNET_MessageHeader *msg,
1030 struct PeerInfo *peer,
1031 struct DHT_MessageContext *msg_ctx)
1033 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1034 struct P2PPendingMessage *pending;
1038 increment_stats(STAT_RESULT_FORWARDS);
1039 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1040 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1041 psize = sizeof(struct P2PPendingMessage) + msize;
1042 pending = GNUNET_malloc(psize);
1043 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1044 pending->importance = DHT_SEND_PRIORITY;
1045 pending->timeout = GNUNET_TIME_relative_get_forever();
1046 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1047 result_message->header.size = htons(msize);
1048 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1049 result_message->put_path_length = htons(0); /* FIXME: implement */
1050 result_message->get_path_length = htons(0); /* FIXME: implement */
1051 result_message->options = htonl(msg_ctx->msg_options);
1052 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1053 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1054 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1055 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1056 memcpy(&result_message[1], msg, ntohs(msg->size));
1058 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));
1060 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1061 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1062 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1065 * Called when core is ready to send a message we asked for
1066 * out to the destination.
1068 * @param cls closure (NULL)
1069 * @param size number of bytes available in buf
1070 * @param buf where the callee should write the message
1071 * @return number of bytes written to buf
1073 size_t core_transmit_notify (void *cls,
1074 size_t size, void *buf)
1076 struct PeerInfo *peer = cls;
1078 struct P2PPendingMessage *pending;
1085 /* client disconnected */
1087 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1092 if (peer->head == NULL)
1097 pending = peer->head;
1098 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1099 msize = ntohs(pending->msg->size);
1103 memcpy (cbuf, pending->msg, msize);
1104 GNUNET_CONTAINER_DLL_remove (peer->head,
1108 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));
1110 GNUNET_free (pending);
1113 while (NULL != pending &&
1114 (size - off >= (msize = ntohs (pending->msg->size))))
1116 #if DEBUG_DHT_ROUTING
1117 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);
1119 memcpy (&cbuf[off], pending->msg, msize);
1121 GNUNET_CONTAINER_DLL_remove (peer->head,
1124 GNUNET_free (pending);
1125 pending = peer->head;
1128 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1129 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1131 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);
1138 * Compute the distance between have and target as a 32-bit value.
1139 * Differences in the lower bits must count stronger than differences
1140 * in the higher bits.
1142 * @return 0 if have==target, otherwise a number
1143 * that is larger as the distance between
1144 * the two hash codes increases
1147 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1149 unsigned int bucket;
1154 /* We have to represent the distance between two 2^9 (=512)-bit
1155 numbers as a 2^5 (=32)-bit number with "0" being used for the
1156 two numbers being identical; furthermore, we need to
1157 guarantee that a difference in the number of matching
1158 bits is always represented in the result.
1160 We use 2^32/2^9 numerical values to distinguish between
1161 hash codes that have the same LSB bit distance and
1162 use the highest 2^9 bits of the result to signify the
1163 number of (mis)matching LSB bits; if we have 0 matching
1164 and hence 512 mismatching LSB bits we return -1 (since
1165 512 itself cannot be represented with 9 bits) */
1167 /* first, calculate the most significant 9 bits of our
1168 result, aka the number of LSBs */
1169 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1170 /* bucket is now a value between 0 and 512 */
1172 return 0; /* perfect match */
1174 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1175 below, we'd end up with max+1 (overflow)) */
1177 /* calculate the most significant bits of the final result */
1178 msb = (512 - bucket) << (32 - 9);
1179 /* calculate the 32-9 least significant bits of the final result by
1180 looking at the differences in the 32-9 bits following the
1181 mismatching bit at 'bucket' */
1183 for (i = bucket + 1;
1184 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1186 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1187 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1188 last bit set will be 31 -- if
1189 i does not reach 512 first... */
1195 * Return a number that is larger the closer the
1196 * "have" GNUNET_hash code is to the "target".
1198 * @return inverse distance metric, non-zero.
1199 * Must fudge the value if NO bits match.
1202 inverse_distance (const GNUNET_HashCode * target,
1203 const GNUNET_HashCode * have)
1205 if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1206 return 1; /* Never return 0! */
1207 return ((unsigned int) -1) - distance (target, have);
1211 * Find the optimal bucket for this key, regardless
1212 * of the current number of buckets in use.
1214 * @param hc the hashcode to compare our identity to
1216 * @return the proper bucket index, or GNUNET_SYSERR
1217 * on error (same hashcode)
1219 static int find_bucket(const GNUNET_HashCode *hc)
1223 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1224 if (bits == MAX_BUCKETS)
1225 return GNUNET_SYSERR;
1226 return MAX_BUCKETS - bits - 1;
1230 * Find which k-bucket this peer should go into,
1231 * taking into account the size of the k-bucket
1232 * array. This means that if more bits match than
1233 * there are currently buckets, lowest_bucket will
1236 * @param hc GNUNET_HashCode we are finding the bucket for.
1238 * @return the proper bucket index for this key,
1239 * or GNUNET_SYSERR on error (same hashcode)
1241 static int find_current_bucket(const GNUNET_HashCode *hc)
1244 actual_bucket = find_bucket(hc);
1246 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1247 return lowest_bucket;
1248 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1249 return lowest_bucket;
1251 return actual_bucket;
1256 * Find a routing table entry from a peer identity
1258 * @param peer the peer to look up
1260 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1263 find_bucket_by_peer(const struct PeerInfo *peer)
1266 struct PeerInfo *pos;
1268 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1270 pos = k_buckets[bucket].head;
1279 return GNUNET_SYSERR; /* No such peer. */
1285 * Print the complete routing table for this peer.
1288 print_routing_table ()
1291 struct PeerInfo *pos;
1292 char char_buf[30000];
1294 memset(char_buf, 0, sizeof(char_buf));
1296 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1297 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1298 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1300 pos = k_buckets[bucket].head;
1301 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1302 //fprintf(stderr, "Bucket %d:\n", bucket);
1305 //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));
1306 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));
1310 fprintf(stderr, "%s", char_buf);
1316 * Find a routing table entry from a peer identity
1318 * @param peer the peer identity to look up
1320 * @return the routing table entry, or NULL if not found
1322 static struct PeerInfo *
1323 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1326 struct PeerInfo *pos;
1327 bucket = find_current_bucket(&peer->hashPubKey);
1329 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1332 pos = k_buckets[bucket].head;
1335 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1339 return NULL; /* No such peer. */
1342 /* Forward declaration */
1344 update_core_preference (void *cls,
1345 const struct GNUNET_SCHEDULER_TaskContext *tc);
1347 * Function called with statistics about the given peer.
1349 * @param cls closure
1350 * @param peer identifies the peer
1351 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1352 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1353 * @param amount set to the amount that was actually reserved or unreserved;
1354 * either the full requested amount or zero (no partial reservations)
1355 * @param preference current traffic preference for the given peer
1358 update_core_preference_finish (void *cls,
1359 const struct GNUNET_PeerIdentity * peer,
1360 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1361 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1362 int amount, uint64_t preference)
1364 struct PeerInfo *peer_info = cls;
1365 peer_info->info_ctx = NULL;
1366 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1370 update_core_preference (void *cls,
1371 const struct GNUNET_SCHEDULER_TaskContext *tc)
1373 struct PeerInfo *peer = cls;
1374 uint64_t preference;
1375 unsigned int matching;
1376 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1380 matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1383 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1386 preference = 1LL << matching;
1387 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1389 GNUNET_TIME_relative_get_forever(),
1390 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1393 &update_core_preference_finish,
1398 * Really add a peer to a bucket (only do assertions
1401 * @param peer GNUNET_PeerIdentity of the peer to add
1402 * @param bucket the already figured out bucket to add
1404 * @param latency the core reported latency of this peer
1405 * @param distance the transport level distance to this peer
1407 * @return the newly added PeerInfo
1409 static struct PeerInfo *
1410 add_peer(const struct GNUNET_PeerIdentity *peer,
1411 unsigned int bucket,
1412 struct GNUNET_TIME_Relative latency,
1413 unsigned int distance)
1415 struct PeerInfo *new_peer;
1416 GNUNET_assert(bucket < MAX_BUCKETS);
1417 GNUNET_assert(peer != NULL);
1418 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1419 new_peer->latency = latency;
1420 new_peer->distance = distance;
1422 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1424 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1425 k_buckets[bucket].tail,
1426 k_buckets[bucket].tail,
1428 k_buckets[bucket].peers_size++;
1430 if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1432 #if DO_UPDATE_PREFERENCE
1433 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1441 * Given a peer and its corresponding bucket,
1442 * remove it from that bucket. Does not free
1443 * the PeerInfo struct, nor cancel messages
1444 * or free messages waiting to be sent to this
1447 * @param peer the peer to remove
1448 * @param bucket the bucket the peer belongs to
1450 static void remove_peer (struct PeerInfo *peer,
1451 unsigned int bucket)
1453 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1454 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1455 k_buckets[bucket].tail,
1457 k_buckets[bucket].peers_size--;
1459 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1465 * Removes peer from a bucket, then frees associated
1466 * resources and frees peer.
1468 * @param peer peer to be removed and freed
1469 * @param bucket which bucket this peer belongs to
1471 static void delete_peer (struct PeerInfo *peer,
1472 unsigned int bucket)
1474 struct P2PPendingMessage *pos;
1475 struct P2PPendingMessage *next;
1477 struct PeerInfo *peer_pos;
1479 peer_pos = k_buckets[bucket].head;
1480 while ((peer_pos != NULL) && (peer_pos != peer))
1481 peer_pos = peer_pos->next;
1482 if (peer_pos == NULL)
1484 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1485 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));
1487 GNUNET_assert(peer_pos != NULL);
1489 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1491 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1492 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1493 if (peer->th != NULL)
1494 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1497 while (pos != NULL) /* Remove any pending messages for this peer */
1504 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1505 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1511 * Iterator over hash map entries.
1513 * @param cls closure
1514 * @param key current key code
1515 * @param value PeerInfo of the peer to move to new lowest bucket
1516 * @return GNUNET_YES if we should continue to
1520 static int move_lowest_bucket (void *cls,
1521 const GNUNET_HashCode * key,
1524 struct PeerInfo *peer = value;
1527 GNUNET_assert(lowest_bucket > 0);
1528 new_bucket = lowest_bucket - 1;
1529 remove_peer(peer, lowest_bucket);
1530 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1531 k_buckets[new_bucket].tail,
1532 k_buckets[new_bucket].tail,
1534 k_buckets[new_bucket].peers_size++;
1540 * The current lowest bucket is full, so change the lowest
1541 * bucket to the next lower down, and move any appropriate
1542 * entries in the current lowest bucket to the new bucket.
1544 static void enable_next_bucket()
1546 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1547 struct PeerInfo *pos;
1548 GNUNET_assert(lowest_bucket > 0);
1549 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1550 pos = k_buckets[lowest_bucket].head;
1553 fprintf(stderr, "Printing RT before new bucket\n");
1554 print_routing_table();
1556 /* Populate the array of peers which should be in the next lowest bucket */
1559 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1560 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1564 /* Remove peers from lowest bucket, insert into next lowest bucket */
1565 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1566 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1567 lowest_bucket = lowest_bucket - 1;
1569 fprintf(stderr, "Printing RT after new bucket\n");
1570 print_routing_table();
1575 * Find the closest peer in our routing table to the
1578 * @return The closest peer in our routing table to the
1579 * key, or NULL on error.
1581 static struct PeerInfo *
1582 find_closest_peer (const GNUNET_HashCode *hc)
1584 struct PeerInfo *pos;
1585 struct PeerInfo *current_closest;
1586 unsigned int lowest_distance;
1587 unsigned int temp_distance;
1591 lowest_distance = -1;
1593 if (k_buckets[lowest_bucket].peers_size == 0)
1596 current_closest = NULL;
1597 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1599 pos = k_buckets[bucket].head;
1601 while ((pos != NULL) && (count < bucket_size))
1603 temp_distance = distance(&pos->id.hashPubKey, hc);
1604 if (temp_distance <= lowest_distance)
1606 lowest_distance = temp_distance;
1607 current_closest = pos;
1613 GNUNET_assert(current_closest != NULL);
1614 return current_closest;
1619 * Function called to send a request out to another peer.
1620 * Called both for locally initiated requests and those
1621 * received from other peers.
1623 * @param cls DHT service closure argument (unused)
1624 * @param msg the encapsulated message
1625 * @param peer the peer to forward the message to
1626 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1628 static void forward_message (void *cls,
1629 const struct GNUNET_MessageHeader *msg,
1630 struct PeerInfo *peer,
1631 struct DHT_MessageContext *msg_ctx)
1633 struct GNUNET_DHT_P2PRouteMessage *route_message;
1634 struct P2PPendingMessage *pending;
1638 increment_stats(STAT_ROUTE_FORWARDS);
1640 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1641 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1643 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1644 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1645 psize = sizeof(struct P2PPendingMessage) + msize;
1646 pending = GNUNET_malloc(psize);
1647 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1648 pending->importance = msg_ctx->importance;
1649 pending->timeout = msg_ctx->timeout;
1650 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1651 route_message->header.size = htons(msize);
1652 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1653 route_message->options = htonl(msg_ctx->msg_options);
1654 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1655 route_message->network_size = htonl(msg_ctx->network_size);
1656 route_message->desired_replication_level = htonl(msg_ctx->replication);
1657 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1658 if (msg_ctx->bloom != NULL)
1659 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1660 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1661 memcpy(&route_message[1], msg, ntohs(msg->size));
1663 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));
1665 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1666 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1667 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1672 * Task used to send ping messages to peers so that
1673 * they don't get disconnected.
1675 * @param cls the peer to send a ping message to
1676 * @param tc context, reason, etc.
1679 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1681 struct PeerInfo *peer = cls;
1682 struct GNUNET_MessageHeader ping_message;
1683 struct DHT_MessageContext message_context;
1685 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1688 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1689 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1691 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1693 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1695 forward_message(NULL, &ping_message, peer, &message_context);
1696 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1700 * Schedule PING messages for the top X peers in each
1701 * bucket of the routing table (so core won't disconnect them!)
1703 void schedule_ping_messages()
1705 unsigned int bucket;
1707 struct PeerInfo *pos;
1708 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1710 pos = k_buckets[bucket].head;
1714 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1715 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1716 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1718 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1719 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1729 * Attempt to add a peer to our k-buckets.
1731 * @param peer the peer identity of the peer being added
1732 * @param bucket the bucket that we want this peer to go in
1733 * @param latency transport latency of this peer
1734 * @param distance transport distance to this peer
1736 * @return NULL if the peer was not added,
1737 * pointer to PeerInfo for new peer otherwise
1739 static struct PeerInfo *
1740 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1741 unsigned int bucket,
1742 struct GNUNET_TIME_Relative latency,
1743 unsigned int distance)
1746 struct PeerInfo *new_peer;
1748 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1751 peer_bucket = find_current_bucket(&peer->hashPubKey);
1753 GNUNET_assert(peer_bucket >= lowest_bucket);
1754 new_peer = add_peer(peer, peer_bucket, latency, distance);
1756 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1757 enable_next_bucket();
1759 schedule_ping_messages();
1766 * Task run to check for messages that need to be sent to a client.
1768 * @param client a ClientList, containing the client and any messages to be sent to it
1771 process_pending_messages (struct ClientList *client)
1773 if (client->pending_head == NULL)
1775 if (client->transmit_handle != NULL)
1778 client->transmit_handle =
1779 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1780 ntohs (client->pending_head->msg->
1782 GNUNET_TIME_UNIT_FOREVER_REL,
1783 &send_generic_reply, client);
1787 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1788 * request. A ClientList is passed as closure, take the head of the list
1789 * and copy it into buf, which has the result of sending the message to the
1792 * @param cls closure to this call
1793 * @param size maximum number of bytes available to send
1794 * @param buf where to copy the actual message to
1796 * @return the number of bytes actually copied, 0 indicates failure
1799 send_generic_reply (void *cls, size_t size, void *buf)
1801 struct ClientList *client = cls;
1803 struct PendingMessage *reply;
1807 client->transmit_handle = NULL;
1810 /* client disconnected */
1814 while ( (NULL != (reply = client->pending_head)) &&
1815 (size >= off + (msize = ntohs (reply->msg->size))))
1817 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1818 client->pending_tail,
1820 memcpy (&cbuf[off], reply->msg, msize);
1821 GNUNET_free (reply);
1824 process_pending_messages (client);
1826 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1827 "Transmitted %u bytes of replies to client\n",
1828 (unsigned int) off);
1835 * Add a PendingMessage to the clients list of messages to be sent
1837 * @param client the active client to send the message to
1838 * @param pending_message the actual message to send
1841 add_pending_message (struct ClientList *client,
1842 struct PendingMessage *pending_message)
1844 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1845 client->pending_tail,
1846 client->pending_tail,
1848 process_pending_messages (client);
1855 * Called when a reply needs to be sent to a client, as
1856 * a result it found to a GET or FIND PEER request.
1858 * @param client the client to send the reply to
1859 * @param message the encapsulated message to send
1860 * @param uid the unique identifier of this request
1863 send_reply_to_client (struct ClientList *client,
1864 const struct GNUNET_MessageHeader *message,
1865 unsigned long long uid,
1866 const GNUNET_HashCode *key)
1868 struct GNUNET_DHT_RouteResultMessage *reply;
1869 struct PendingMessage *pending_message;
1873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1874 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1876 msize = ntohs (message->size);
1877 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1878 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1880 GNUNET_break_op (0);
1883 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1884 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1885 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1886 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1887 reply->header.size = htons (tsize);
1888 reply->put_path_length = htons(0); /* FIXME: implement */
1889 reply->get_path_length = htons(0); /* FIXME: implement */
1890 reply->unique_id = GNUNET_htonll (uid);
1892 memcpy (&reply[1], message, msize);
1893 add_pending_message (client, pending_message);
1897 * Consider whether or not we would like to have this peer added to
1898 * our routing table. Check whether bucket for this peer is full,
1899 * if so return negative; if not return positive. Since peers are
1900 * only added on CORE level connect, this doesn't actually add the
1901 * peer to the routing table.
1903 * @param peer the peer we are considering adding
1905 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1908 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1912 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1913 return GNUNET_NO; /* We already know this peer (are connected even!) */
1914 bucket = find_current_bucket(&peer->hashPubKey);
1916 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1923 * Main function that handles whether or not to route a result
1924 * message to other peers, or to send to our local client.
1926 * @param cls closure (unused, always should be NULL)
1927 * @param msg the result message to be routed
1928 * @param message_context context of the message we are routing
1930 * @return the number of peers the message was routed to,
1931 * GNUNET_SYSERR on failure
1933 static int route_result_message(void *cls,
1934 struct GNUNET_MessageHeader *msg,
1935 struct DHT_MessageContext *message_context)
1937 struct GNUNET_PeerIdentity new_peer;
1938 struct DHTQueryRecord *record;
1939 struct DHTRouteSource *pos;
1940 struct PeerInfo *peer_info;
1941 const struct GNUNET_MessageHeader *hello_msg;
1943 increment_stats(STAT_RESULTS);
1945 * If a find peer result message is received and contains a valid
1946 * HELLO for another peer, offer it to the transport service.
1948 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1950 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1953 hello_msg = &msg[1];
1954 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1956 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1960 else /* We have a valid hello, and peer id stored in new_peer */
1962 find_peer_context.count++;
1963 increment_stats(STAT_FIND_PEER_REPLY);
1964 if (GNUNET_YES == consider_peer(&new_peer))
1966 increment_stats(STAT_HELLOS_PROVIDED);
1967 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1968 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1973 if (malicious_dropper == GNUNET_YES)
1976 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1978 if (record == NULL) /* No record of this message! */
1981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1982 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1983 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
1985 #if DEBUG_DHT_ROUTING
1986 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1988 dhtlog_handle->insert_route (NULL,
1989 message_context->unique_id,
1991 message_context->hop_count,
1994 &message_context->key,
1995 message_context->peer, NULL);
1998 if (message_context->bloom != NULL)
2000 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2001 message_context->bloom = NULL;
2009 #if STRICT_FORWARDING
2010 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2012 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2014 increment_stats("# find peer responses NOT forwarded (bloom match)");
2019 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2023 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2026 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2027 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2028 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2030 #if DEBUG_DHT_ROUTING
2031 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2033 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2034 message_context->hop_count,
2035 GNUNET_YES, &my_identity, &message_context->key,
2036 message_context->peer, NULL);
2039 increment_stats(STAT_RESULTS_TO_CLIENT);
2040 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2041 increment_stats(STAT_GET_REPLY);
2043 send_reply_to_client(pos->client, msg,
2044 message_context->unique_id,
2045 &message_context->key);
2047 else /* Send to peer */
2049 peer_info = find_peer_by_id(&pos->source);
2050 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2056 if (message_context->bloom == NULL)
2057 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2058 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2059 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2063 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2064 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2066 #if DEBUG_DHT_ROUTING
2067 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2069 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2071 message_context->hop_count,
2072 GNUNET_NO, &my_identity, &message_context->key,
2073 message_context->peer, &pos->source);
2076 forward_result_message(cls, msg, peer_info, message_context);
2081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2082 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2083 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2089 if (message_context->bloom != NULL)
2090 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2095 * Iterator for local get request results,
2097 * @param cls closure for iterator, a DatacacheGetContext
2098 * @param exp when does this value expire?
2099 * @param key the key this data is stored under
2100 * @param size the size of the data identified by key
2101 * @param data the actual data
2102 * @param type the type of the data
2104 * @return GNUNET_OK to continue iteration, anything else
2105 * to stop iteration.
2108 datacache_get_iterator (void *cls,
2109 struct GNUNET_TIME_Absolute exp,
2110 const GNUNET_HashCode * key,
2111 uint32_t size, const char *data, uint32_t type)
2113 struct DHT_MessageContext *msg_ctx = cls;
2114 struct DHT_MessageContext *new_msg_ctx;
2115 struct GNUNET_DHT_GetResultMessage *get_result;
2117 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2118 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2120 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2121 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2123 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2124 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2125 get_result->header.size =
2126 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2127 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2128 get_result->type = htons (type);
2129 memcpy (&get_result[1], data, size);
2130 new_msg_ctx->peer = &my_identity;
2131 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2132 new_msg_ctx->hop_count = 0;
2133 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2134 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2135 increment_stats(STAT_GET_RESPONSE_START);
2136 route_result_message(cls, &get_result->header, new_msg_ctx);
2137 GNUNET_free(new_msg_ctx);
2138 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2139 // datacache_get_ctx->unique_id);
2140 GNUNET_free (get_result);
2146 * Server handler for all dht get requests, look for data,
2147 * if found, send response either to clients or other peers.
2149 * @param cls closure for service
2150 * @param msg the actual get message
2151 * @param message_context struct containing pertinent information about the get request
2153 * @return number of items found for GET request
2156 handle_dht_get (void *cls,
2157 const struct GNUNET_MessageHeader *msg,
2158 struct DHT_MessageContext *message_context)
2160 const struct GNUNET_DHT_GetMessage *get_msg;
2164 uint16_t xquery_size;
2165 unsigned int results;
2166 struct GNUNET_CONTAINER_BloomFilter *bf;
2170 msize = ntohs (msg->size);
2171 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2176 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2177 bf_size = ntohs (get_msg->bf_size);
2178 xquery_size = ntohs (get_msg->xquery_size);
2179 if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + xquery_size)
2184 end = (const char*) &get_msg[1];
2185 if (xquery_size == 0)
2191 xquery = (const void*) end;
2200 bf = GNUNET_CONTAINER_bloomfilter_init (end,
2202 GNUNET_DHT_GET_BLOOMFILTER_K);
2205 get_type = ntohs (get_msg->type);
2207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2208 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2212 GNUNET_h2s (&message_context->key),
2213 message_context->unique_id);
2215 increment_stats(STAT_GETS);
2218 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2220 GNUNET_CONTAINER_bloomfilter_free (bf);
2224 /* FIXME: put xquery / bf into message_context and use
2225 them for processing! */
2226 if (datacache != NULL)
2228 = GNUNET_DATACACHE_get (datacache,
2229 &message_context->key, get_type,
2230 &datacache_get_iterator,
2236 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2237 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2238 results, "GET", message_context->unique_id);
2240 #if DEBUG_DHT_ROUTING
2241 if ((debug_routes) && (dhtlog_handle != NULL))
2243 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2244 message_context->hop_count, GNUNET_YES, &my_identity,
2245 &message_context->key);
2248 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2250 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2251 message_context->hop_count, GNUNET_YES,
2252 &my_identity, &message_context->key, message_context->peer,
2258 if (message_context->hop_count == 0) /* Locally initiated request */
2260 #if DEBUG_DHT_ROUTING
2261 if ((debug_routes) && (dhtlog_handle != NULL))
2263 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2264 message_context->hop_count, GNUNET_NO, &my_identity,
2265 &message_context->key);
2269 GNUNET_CONTAINER_bloomfilter_free (bf);
2274 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2276 GNUNET_HashCode *key = cls;
2277 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2284 * Server handler for initiating local dht find peer requests
2286 * @param cls closure for service
2287 * @param find_msg the actual find peer message
2288 * @param message_context struct containing pertinent information about the request
2292 handle_dht_find_peer (void *cls,
2293 const struct GNUNET_MessageHeader *find_msg,
2294 struct DHT_MessageContext *message_context)
2296 struct GNUNET_MessageHeader *find_peer_result;
2297 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2298 struct DHT_MessageContext *new_msg_ctx;
2299 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2302 GNUNET_HashCode *recent_hash;
2303 struct GNUNET_MessageHeader *other_hello;
2304 size_t other_hello_size;
2305 struct GNUNET_PeerIdentity peer_id;
2307 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2308 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2309 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2312 other_hello_size = 0;
2313 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2315 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2316 other_hello = GNUNET_malloc(other_hello_size);
2317 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2318 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)))
2320 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2321 GNUNET_free(other_hello);
2324 #if FIND_PEER_WITH_HELLO
2325 if (GNUNET_YES == consider_peer(&peer_id))
2327 increment_stats(STAT_HELLOS_PROVIDED);
2328 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2329 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2332 else /* We don't want this peer! */
2338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2339 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2340 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&message_context->key),
2341 ntohs (find_msg->size),
2342 sizeof (struct GNUNET_MessageHeader));
2344 if (my_hello == NULL)
2347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2348 "`%s': Our HELLO is null, can't return.\n",
2351 GNUNET_free_non_null(other_hello);
2355 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2356 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2358 increment_stats(STAT_BLOOM_FIND_PEER);
2359 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2360 GNUNET_free_non_null(other_hello);
2361 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2363 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2365 #if RESTRICT_FIND_PEER
2368 * Ignore any find peer requests from a peer we have seen very recently.
2370 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! */
2372 increment_stats("# dht find peer requests ignored (recently seen!)");
2373 GNUNET_free_non_null(other_hello);
2378 * Use this check to only allow the peer to respond to find peer requests if
2379 * it would be beneficial to have the requesting peer in this peers routing
2380 * table. Can be used to thwart peers flooding the network with find peer
2381 * requests that we don't care about. However, if a new peer is joining
2382 * the network and has no other peers this is a problem (assume all buckets
2383 * full, no one will respond!).
2385 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2386 if (GNUNET_NO == consider_peer(&peer_id))
2388 increment_stats("# dht find peer requests ignored (do not need!)");
2389 GNUNET_free_non_null(other_hello);
2394 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2395 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2396 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2397 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2399 /* Simplistic find_peer functionality, always return our hello */
2400 hello_size = ntohs(my_hello->size);
2401 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2403 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2405 GNUNET_break_op (0);
2406 GNUNET_free_non_null(other_hello);
2410 find_peer_result = GNUNET_malloc (tsize);
2411 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2412 find_peer_result->size = htons (tsize);
2413 memcpy (&find_peer_result[1], my_hello, hello_size);
2415 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2416 "`%s': Sending hello size %d to requesting peer.\n",
2419 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2420 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2421 new_msg_ctx->peer = &my_identity;
2422 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2423 new_msg_ctx->hop_count = 0;
2424 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2425 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2426 increment_stats(STAT_FIND_PEER_ANSWER);
2427 route_result_message(cls, find_peer_result, new_msg_ctx);
2428 GNUNET_free(new_msg_ctx);
2429 #if DEBUG_DHT_ROUTING
2430 if ((debug_routes) && (dhtlog_handle != NULL))
2432 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2433 message_context->hop_count, GNUNET_YES, &my_identity,
2434 &message_context->key);
2437 GNUNET_free_non_null(other_hello);
2438 GNUNET_free(find_peer_result);
2442 * Task used to republish data.
2443 * Forward declaration; function call loop.
2445 * @param cls closure (a struct RepublishContext)
2446 * @param tc runtime context for this task
2449 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2452 * Server handler for initiating local dht put requests
2454 * @param cls closure for service
2455 * @param msg the actual put message
2456 * @param message_context struct containing pertinent information about the request
2459 handle_dht_put (void *cls,
2460 const struct GNUNET_MessageHeader *msg,
2461 struct DHT_MessageContext *message_context)
2463 struct GNUNET_DHT_PutMessage *put_msg;
2467 struct RepublishContext *put_context;
2469 GNUNET_assert (ntohs (msg->size) >=
2470 sizeof (struct GNUNET_DHT_PutMessage));
2473 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2474 put_type = ntohs (put_msg->type);
2476 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2479 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2482 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2483 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
2485 #if DEBUG_DHT_ROUTING
2486 if (message_context->hop_count == 0) /* Locally initiated request */
2488 if ((debug_routes) && (dhtlog_handle != NULL))
2490 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2491 message_context->hop_count, GNUNET_NO, &my_identity,
2492 &message_context->key);
2497 if (message_context->closest != GNUNET_YES)
2500 #if DEBUG_DHT_ROUTING
2501 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2503 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2504 message_context->hop_count, GNUNET_YES,
2505 &my_identity, &message_context->key, message_context->peer,
2509 if ((debug_routes) && (dhtlog_handle != NULL))
2511 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2512 message_context->hop_count, GNUNET_YES, &my_identity,
2513 &message_context->key);
2517 increment_stats(STAT_PUTS_INSERTED);
2518 if (datacache != NULL)
2520 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2521 (char *) &put_msg[1], put_type,
2522 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2524 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2526 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2527 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2528 put_context->type = put_type;
2529 GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
2533 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2534 "`%s:%s': %s request received, but have no datacache!\n",
2535 my_short_id, "DHT", "PUT");
2539 * Estimate the diameter of the network based
2540 * on how many buckets are currently in use.
2541 * Concept here is that the diameter of the network
2542 * is roughly the distance a message must travel in
2543 * order to reach its intended destination. Since
2544 * at each hop we expect to get one bit closer, and
2545 * we have one bit per bucket, the number of buckets
2546 * in use should be the largest number of hops for
2547 * a sucessful message. (of course, this assumes we
2548 * know all peers in the network!)
2550 * @return ballpark diameter figure
2552 static unsigned int estimate_diameter()
2554 return MAX_BUCKETS - lowest_bucket;
2558 * To how many peers should we (on average)
2559 * forward the request to obtain the desired
2560 * target_replication count (on average).
2562 * Always 0, 1 or 2 (don't send, send once, split)
2565 get_forward_count (unsigned int hop_count, size_t target_replication)
2568 double target_count;
2569 double random_probability;
2571 uint32_t random_value;
2573 unsigned int target_value;
2574 unsigned int diameter;
2577 * If we are behaving in strict kademlia mode, send multiple initial requests,
2578 * but then only send to 1 or 0 peers based strictly on the number of hops.
2580 if (strict_kademlia == GNUNET_YES)
2583 return DHT_KADEMLIA_REPLICATION;
2584 else if (hop_count < max_hops)
2590 /* FIXME: the smaller we think the network is the more lenient we should be for
2591 * routing right? The estimation below only works if we think we have reasonably
2592 * full routing tables, which for our RR topologies may not be the case!
2594 diameter = estimate_diameter ();
2595 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2598 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2599 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2600 "DHT", estimate_diameter(), lowest_bucket);
2604 else if (hop_count > max_hops)
2607 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2608 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2615 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2616 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2617 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2618 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2619 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2620 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2621 RAND_MAX)) / RAND_MAX;
2622 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2625 //while (target_value < target_count)
2626 if (target_value < target_count)
2627 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? */
2630 //if ((target_count + 1 - (double)target_value) > random_probability)
2631 if ((target_count) > random_probability)
2635 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2636 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));
2638 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2639 if (random_value < target_replication)
2642 return target_value;
2646 * Check whether my identity is closer than any known peers.
2647 * If a non-null bloomfilter is given, check if this is the closest
2648 * peer that hasn't already been routed to.
2650 * @param target hash code to check closeness to
2651 * @param bloom bloomfilter, exclude these entries from the decision
2653 * Return GNUNET_YES if node location is closest, GNUNET_NO
2657 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2663 struct PeerInfo *pos;
2664 unsigned int my_distance;
2666 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2669 bucket_num = find_current_bucket(target);
2671 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2672 my_distance = distance(&my_identity.hashPubKey, target);
2673 pos = k_buckets[bucket_num].head;
2675 while ((pos != NULL) && (count < bucket_size))
2677 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2680 continue; /* Skip already checked entries */
2683 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2684 if (other_bits > bits)
2686 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2688 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2690 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2697 GNUNET_GE_LOG (coreAPI->ectx,
2698 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2699 GNUNET_GE_BULK, "closest peer\n");
2700 printPeerBits (&closest);
2701 GNUNET_GE_LOG (coreAPI->ectx,
2702 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2703 GNUNET_GE_BULK, "me\n");
2704 printPeerBits (coreAPI->my_identity);
2705 GNUNET_GE_LOG (coreAPI->ectx,
2706 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2707 GNUNET_GE_BULK, "key\n");
2708 printKeyBits (target);
2709 GNUNET_GE_LOG (coreAPI->ectx,
2710 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2712 "closest peer inverse distance is %u, mine is %u\n",
2713 inverse_distance (target, &closest.hashPubKey),
2714 inverse_distance (target,
2715 &coreAPI->my_identity->hashPubKey));
2718 /* No peers closer, we are the closest! */
2724 * Return this peers adjusted value based on the convergence
2725 * function chosen. This is the key function for randomized
2726 * routing decisions.
2728 * @param target the key of the request
2729 * @param peer the peer we would like the value of
2730 * @param hops number of hops this message has already traveled
2732 * @return bit distance from target to peer raised to an exponent
2733 * adjusted based on the current routing convergence algorithm
2737 converge_distance (const GNUNET_HashCode *target,
2738 struct PeerInfo *peer,
2741 unsigned long long ret;
2742 unsigned int other_matching_bits;
2743 double converge_modifier = 0.0;
2744 double base_converge_modifier = .1;
2750 curr_max_hops = max_hops;
2752 curr_max_hops = (estimate_diameter() + 1) * 2;
2754 if (converge_modifier > 0)
2755 converge_modifier = converge_modifier * base_converge_modifier;
2758 converge_modifier = base_converge_modifier;
2759 base_converge_modifier = 0.0;
2762 GNUNET_assert(converge_modifier > 0);
2764 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2766 switch (converge_option)
2768 case DHT_CONVERGE_RANDOM:
2769 return 1; /* Always return 1, choose equally among all peers */
2770 case DHT_CONVERGE_LINEAR:
2771 calc_value = hops * curr_max_hops * converge_modifier;
2773 case DHT_CONVERGE_SQUARE:
2775 * Simple square based curve.
2777 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * converge_modifier));
2779 case DHT_CONVERGE_EXPONENTIAL:
2781 * Simple exponential curve.
2783 if (base_converge_modifier > 0)
2784 calc_value = (converge_modifier * hops * hops) / curr_max_hops;
2786 calc_value = (hops * hops) / curr_max_hops;
2792 /* Take the log (base e) of the number of bits matching the other peer */
2793 exponent = log(other_matching_bits);
2795 /* Check if we would overflow; our largest possible value is 2^64 = e^44.361419555836498 */
2796 if (exponent * calc_value >= 44.361419555836498)
2799 /* Clear errno and all math exceptions */
2801 feclearexcept(FE_ALL_EXCEPT);
2802 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2803 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2806 if (0 != fetestexcept(FE_OVERFLOW))
2807 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2808 if (0 != fetestexcept(FE_INVALID))
2809 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2810 if (0 != fetestexcept(FE_UNDERFLOW))
2811 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2819 * Comparison function for two struct PeerInfo's
2820 * which have already had their matching bits to
2821 * some target calculated.
2823 * @param p1 a pointer pointer to a struct PeerInfo
2824 * @param p2 a pointer pointer to a struct PeerInfo
2826 * @return 0 if equidistant to target,
2827 * -1 if p1 is closer,
2831 compare_peers (const void *p1, const void *p2)
2833 struct PeerInfo **first = (struct PeerInfo **)p1;
2834 struct PeerInfo **second = (struct PeerInfo **)p2;
2836 if ((*first)->matching_bits > (*second)->matching_bits)
2838 if ((*first)->matching_bits < (*second)->matching_bits)
2846 * Select a peer from the routing table that would be a good routing
2847 * destination for sending a message for "target". The resulting peer
2848 * must not be in the set of blocked peers.<p>
2850 * Note that we should not ALWAYS select the closest peer to the
2851 * target, peers further away from the target should be chosen with
2852 * exponentially declining probability.
2854 * @param target the key we are selecting a peer to route to
2855 * @param bloom a bloomfilter containing entries this request has seen already
2857 * @return Peer to route to, or NULL on error
2859 static struct PeerInfo *
2860 select_peer (const GNUNET_HashCode * target,
2861 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2866 unsigned int offset;
2867 unsigned int my_matching_bits;
2869 struct PeerInfo *pos;
2870 struct PeerInfo *sorted_closest[bucket_size];
2871 unsigned long long temp_converge_distance;
2872 unsigned long long total_distance;
2873 unsigned long long selected;
2875 unsigned long long stats_total_distance;
2879 unsigned int distance;
2880 unsigned int largest_distance;
2881 struct PeerInfo *chosen;
2883 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
2886 if (strict_kademlia == GNUNET_YES)
2888 largest_distance = 0;
2890 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2892 pos = k_buckets[bc].head;
2894 while ((pos != NULL) && (count < bucket_size))
2896 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2897 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2899 distance = inverse_distance (target, &pos->id.hashPubKey);
2900 if (distance > largest_distance)
2903 largest_distance = distance;
2911 if ((largest_distance > 0) && (chosen != NULL))
2913 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2924 /* Three steps: order peers in closest bucket (most matching bits).
2925 * Then go over all LOWER buckets (matching same bits we do)
2926 * Then go over all HIGHER buckets (matching less then we do)
2929 closest_bucket = find_current_bucket(target);
2930 GNUNET_assert(closest_bucket >= lowest_bucket);
2931 pos = k_buckets[closest_bucket].head;
2933 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
2934 memset(sorted_closest, 0, sizeof(sorted_closest));
2935 /* Put any peers in the closest bucket in the sorting array */
2936 while ((pos != NULL) && (count < bucket_size))
2938 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2942 continue; /* Ignore bloomfiltered peers */
2944 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2945 sorted_closest[offset] = pos;
2951 /* Sort the peers in descending order */
2952 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
2954 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
2955 for (i = 0; i < offset; i++)
2957 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
2958 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
2959 break; /* Ignore bloomfiltered peers */
2960 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2961 total_distance += temp_converge_distance;
2963 break; /* overflow case */
2966 /* Now handle peers in lower buckets (matches same # of bits as target) */
2967 for (bc = lowest_bucket; bc < closest_bucket; bc++)
2969 pos = k_buckets[bc].head;
2971 while ((pos != NULL) && (count < bucket_size))
2973 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2977 continue; /* Ignore bloomfiltered peers */
2979 temp_converge_distance = converge_distance(target, pos, hops);
2980 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2981 total_distance += temp_converge_distance;
2983 break; /* overflow case */
2989 /* Now handle all the further away peers */
2990 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
2992 pos = k_buckets[bc].head;
2994 while ((pos != NULL) && (count < bucket_size))
2996 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3000 continue; /* Ignore bloomfiltered peers */
3002 temp_converge_distance = converge_distance(target, pos, hops);
3003 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3004 total_distance += temp_converge_distance;
3006 break; /* overflow case */
3012 if (total_distance == 0) /* No peers to select from! */
3014 increment_stats("# select_peer, total_distance == 0");
3018 #if DEBUG_DHT_ROUTING > 1
3021 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3022 stats_total_distance = 0;
3023 for (i = 0; i < offset; i++)
3025 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3026 break; /* Ignore bloomfiltered peers */
3027 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3028 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3029 stats_total_distance += temp_converge_distance;
3031 break; /* overflow case */
3032 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);
3035 /* Now handle peers in lower buckets (matches same # of bits as target) */
3036 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3038 pos = k_buckets[bc].head;
3040 while ((pos != NULL) && (count < bucket_size))
3042 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3046 continue; /* Ignore bloomfiltered peers */
3048 temp_converge_distance = converge_distance(target, pos, hops);
3049 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3050 stats_total_distance += temp_converge_distance;
3052 break; /* overflow case */
3053 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);
3059 /* Now handle all the further away peers */
3060 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3062 pos = k_buckets[bc].head;
3064 while ((pos != NULL) && (count < bucket_size))
3066 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3070 continue; /* Ignore bloomfiltered peers */
3072 temp_converge_distance = converge_distance(target, pos, hops);
3073 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3074 stats_total_distance += temp_converge_distance;
3076 break; /* overflow case */
3077 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);
3082 /* END PRINT STATS */
3085 /* Now actually choose a peer */
3086 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3088 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3089 for (i = 0; i < offset; i++)
3091 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3092 break; /* Ignore bloomfiltered peers */
3093 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3094 if (temp_converge_distance >= selected)
3095 return sorted_closest[i];
3097 selected -= temp_converge_distance;
3100 /* Now handle peers in lower buckets (matches same # of bits as target) */
3101 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3103 pos = k_buckets[bc].head;
3105 while ((pos != NULL) && (count < bucket_size))
3107 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3111 continue; /* Ignore bloomfiltered peers */
3113 temp_converge_distance = converge_distance(target, pos, hops);
3114 if (temp_converge_distance >= selected)
3117 selected -= temp_converge_distance;
3123 /* Now handle all the further away peers */
3124 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3126 pos = k_buckets[bc].head;
3128 while ((pos != NULL) && (count < bucket_size))
3130 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3134 continue; /* Ignore bloomfiltered peers */
3136 temp_converge_distance = converge_distance(target, pos, hops);
3137 if (temp_converge_distance >= selected)
3140 selected -= temp_converge_distance;
3146 increment_stats("# failed to select peer");
3152 * Task used to remove recent entries, either
3153 * after timeout, when full, or on shutdown.
3155 * @param cls the entry to remove
3156 * @param tc context, reason, etc.
3159 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3161 struct RecentRequest *req = cls;
3162 static GNUNET_HashCode hash;
3164 GNUNET_assert(req != NULL);
3165 hash_from_uid(req->uid, &hash);
3166 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3167 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3168 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3171 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3173 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3174 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3180 * Task used to remove forwarding entries, either
3181 * after timeout, when full, or on shutdown.
3183 * @param cls the entry to remove
3184 * @param tc context, reason, etc.
3187 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3189 struct DHTRouteSource *source_info = cls;
3190 struct DHTQueryRecord *record;
3191 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3192 record = source_info->record;
3193 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3195 if (record->head == NULL) /* No more entries in DLL */
3197 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3198 GNUNET_free(record);
3200 if (source_info->find_peers_responded != NULL)
3201 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3202 GNUNET_free(source_info);
3206 * Remember this routing request so that if a reply is
3207 * received we can either forward it to the correct peer
3208 * or return the result locally.
3210 * @param cls DHT service closure
3211 * @param msg_ctx Context of the route request
3213 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3215 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
3217 struct DHTQueryRecord *record;
3218 struct DHTRouteSource *source_info;
3219 struct DHTRouteSource *pos;
3220 struct GNUNET_TIME_Absolute now;
3221 unsigned int current_size;
3223 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3224 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3226 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3227 GNUNET_assert(source_info != NULL);
3228 record = source_info->record;
3229 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3230 if (record->head == NULL) /* No more entries in DLL */
3232 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3233 GNUNET_free(record);
3235 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
3236 if (source_info->find_peers_responded != NULL)
3237 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3238 GNUNET_free(source_info);
3239 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3241 now = GNUNET_TIME_absolute_get();
3242 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3243 if (record != NULL) /* Already know this request! */
3248 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3249 break; /* Already have this peer in reply list! */
3252 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3254 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3260 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3261 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3262 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3265 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3266 source_info->record = record;
3267 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3268 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3269 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3270 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3271 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3273 source_info->client = msg_ctx->client;
3274 now = GNUNET_TIME_absolute_get_forever();
3276 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3278 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3279 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3280 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3287 * Main function that handles whether or not to route a message to other
3290 * @param cls closure for dht service (NULL)
3291 * @param msg the message to be routed
3292 * @param message_context the context containing all pertinent information about the message
3294 * @return the number of peers the message was routed to,
3295 * GNUNET_SYSERR on failure
3297 static int route_message(void *cls,
3298 const struct GNUNET_MessageHeader *msg,
3299 struct DHT_MessageContext *message_context)
3303 struct PeerInfo *selected;
3304 #if DEBUG_DHT_ROUTING > 1
3305 struct PeerInfo *nearest;
3307 unsigned int forward_count;
3308 struct RecentRequest *recent_req;
3309 GNUNET_HashCode unique_hash;
3310 char *stat_forward_count;
3311 char *temp_stat_str;
3312 #if DEBUG_DHT_ROUTING
3316 if (malicious_dropper == GNUNET_YES)
3318 #if DEBUG_DHT_ROUTING
3319 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3321 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3322 message_context->hop_count, GNUNET_SYSERR,
3323 &my_identity, &message_context->key, message_context->peer,
3327 if (message_context->bloom != NULL)
3328 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3332 increment_stats(STAT_ROUTES);
3333 /* Semantics of this call means we find whether we are the closest peer out of those already
3334 * routed to on this messages path.
3336 global_closest = am_closest_peer(&message_context->key, NULL);
3337 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3338 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3339 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3340 increment_stats(stat_forward_count);
3341 GNUNET_free(stat_forward_count);
3342 if (message_context->bloom == NULL)
3343 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3345 if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3349 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3350 * any closer peers (which is being checked for below). Since we are doing recursive
3351 * routing we have no choice but to stop forwarding in this case. This means that at
3352 * any given step the request may NOT be forwarded to alpha peers (because routes will
3353 * stop and the parallel route will not be aware of it). Of course, assuming that we
3354 * have fulfilled the Kademlia requirements for routing table fullness this will never
3355 * ever ever be a problem.
3357 * However, is this fair?
3359 * Since we use these requests to build our routing tables (and we build them in the
3360 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3361 * routing tables still get constructed.
3363 if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3366 #if DEBUG_DHT_ROUTING
3367 if (forward_count == 0)
3368 ret = GNUNET_SYSERR;
3372 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3374 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3375 message_context->hop_count, ret,
3376 &my_identity, &message_context->key, message_context->peer,
3381 switch (ntohs(msg->type))
3383 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3384 cache_response (cls, message_context);
3385 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3388 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3389 increment_stats(STAT_PUTS);
3390 message_context->closest = global_closest;
3391 handle_dht_put (cls, msg, message_context);
3393 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3394 increment_stats(STAT_FIND_PEER);
3395 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3397 cache_response (cls, message_context);
3398 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3399 handle_dht_find_peer (cls, msg, message_context);
3401 #if DEBUG_DHT_ROUTING
3402 if (message_context->hop_count == 0) /* Locally initiated request */
3404 if ((debug_routes) && (dhtlog_handle != NULL))
3406 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3407 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3408 message_context->hop_count, GNUNET_NO, &my_identity,
3409 &message_context->key);
3415 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3416 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3419 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3420 hash_from_uid (message_context->unique_id, &unique_hash);
3421 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3423 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3424 GNUNET_assert(recent_req != NULL);
3425 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3426 increment_stats(STAT_DUPLICATE_UID);
3429 increment_stats(STAT_RECENT_SEEN);
3430 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3435 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3436 recent_req->uid = message_context->unique_id;
3437 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3438 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3439 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3440 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3441 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3444 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3446 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3447 GNUNET_assert(recent_req != NULL);
3448 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3449 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3452 for (i = 0; i < forward_count; i++)
3454 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3456 if (selected != NULL)
3458 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
3459 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
3461 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
3462 if (temp_stat_str != NULL)
3464 increment_stats(temp_stat_str);
3465 GNUNET_free(temp_stat_str);
3467 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3468 #if DEBUG_DHT_ROUTING > 1
3469 nearest = find_closest_peer(&message_context->key);
3470 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3471 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3472 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3473 "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));
3474 GNUNET_free(nearest_buf);
3476 #if DEBUG_DHT_ROUTING
3477 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3479 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3480 message_context->hop_count, GNUNET_NO,
3481 &my_identity, &message_context->key, message_context->peer,
3485 forward_message(cls, msg, selected, message_context);
3489 if (message_context->bloom != NULL)
3491 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3492 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3495 return forward_count;
3499 * Iterator for local get request results,
3501 * @param cls closure for iterator, NULL
3502 * @param exp when does this value expire?
3503 * @param key the key this data is stored under
3504 * @param size the size of the data identified by key
3505 * @param data the actual data
3506 * @param type the type of the data
3508 * @return GNUNET_OK to continue iteration, anything else
3509 * to stop iteration.
3512 republish_content_iterator (void *cls,
3513 struct GNUNET_TIME_Absolute exp,
3514 const GNUNET_HashCode * key,
3515 uint32_t size, const char *data, uint32_t type)
3518 struct DHT_MessageContext *new_msg_ctx;
3519 struct GNUNET_DHT_PutMessage *put_msg;
3521 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3522 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3524 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3527 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3528 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3529 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3530 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3531 put_msg->type = htons (type);
3532 memcpy (&put_msg[1], data, size);
3533 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3534 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3535 new_msg_ctx->msg_options = ntohl (0);
3536 new_msg_ctx->network_size = estimate_diameter();
3537 new_msg_ctx->peer = &my_identity;
3538 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3539 new_msg_ctx->hop_count = 0;
3540 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3541 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3542 increment_stats(STAT_PUT_START);
3543 route_message(cls, &put_msg->header, new_msg_ctx);
3545 GNUNET_free(new_msg_ctx);
3546 GNUNET_free (put_msg);
3551 * Task used to republish data.
3553 * @param cls closure (a struct RepublishContext)
3554 * @param tc runtime context for this task
3557 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3559 struct RepublishContext *put_context = cls;
3561 unsigned int results;
3563 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3565 GNUNET_free(put_context);
3569 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3570 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3571 if (results == 0) /* Data must have expired */
3572 GNUNET_free(put_context);
3573 else /* Reschedule task for next time period */
3574 GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);
3580 * Iterator over hash map entries.
3582 * @param cls client to search for in source routes
3583 * @param key current key code (ignored)
3584 * @param value value in the hash map, a DHTQueryRecord
3585 * @return GNUNET_YES if we should continue to
3589 static int find_client_records (void *cls,
3590 const GNUNET_HashCode * key, void *value)
3592 struct ClientList *client = cls;
3593 struct DHTQueryRecord *record = value;
3594 struct DHTRouteSource *pos;
3598 if (pos->client == client)
3604 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3605 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3606 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3607 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3609 if (pos->find_peers_responded != NULL)
3610 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3613 if (record->head == NULL) /* No more entries in DLL */
3615 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3616 GNUNET_free(record);
3622 * Functions with this signature are called whenever a client
3623 * is disconnected on the network level.
3625 * @param cls closure (NULL for dht)
3626 * @param client identification of the client; NULL
3627 * for the last call when the server is destroyed
3629 static void handle_client_disconnect (void *cls,
3630 struct GNUNET_SERVER_Client* client)
3632 struct ClientList *pos = client_list;
3633 struct ClientList *prev;
3634 struct ClientList *found;
3635 struct PendingMessage *reply;
3641 if (pos->client_handle == client)
3644 prev->next = pos->next;
3646 client_list = pos->next;
3656 while(NULL != (reply = found->pending_head))
3658 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3661 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3667 * Find a client if it exists, add it otherwise.
3669 * @param client the server handle to the client
3671 * @return the client if found, a new client otherwise
3673 static struct ClientList *
3674 find_active_client (struct GNUNET_SERVER_Client *client)
3676 struct ClientList *pos = client_list;
3677 struct ClientList *ret;
3681 if (pos->client_handle == client)
3686 ret = GNUNET_malloc (sizeof (struct ClientList));
3687 ret->client_handle = client;
3688 ret->next = client_list;
3695 * Task to send a malicious put message across the network.
3697 * @param cls closure for this task
3698 * @param tc the context under which the task is running
3701 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3703 static struct GNUNET_DHT_PutMessage put_message;
3704 static struct DHT_MessageContext message_context;
3705 static GNUNET_HashCode key;
3706 uint32_t random_key;
3708 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3711 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3712 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3713 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3714 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3715 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3716 message_context.client = NULL;
3717 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3718 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3719 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3720 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3721 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3722 message_context.msg_options = ntohl (0);
3723 message_context.network_size = estimate_diameter();
3724 message_context.peer = &my_identity;
3725 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3726 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3727 #if DEBUG_DHT_ROUTING
3728 if (dhtlog_handle != NULL)
3729 dhtlog_handle->insert_dhtkey(NULL, &key);
3731 increment_stats(STAT_PUT_START);
3732 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3733 route_message(NULL, &put_message.header, &message_context);
3734 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3739 * Task to send a malicious put message across the network.
3741 * @param cls closure for this task
3742 * @param tc the context under which the task is running
3745 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3747 static struct GNUNET_DHT_GetMessage get_message;
3748 struct DHT_MessageContext message_context;
3749 static GNUNET_HashCode key;
3750 uint32_t random_key;
3752 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3755 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3756 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3757 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3758 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3759 message_context.client = NULL;
3760 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3761 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3762 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3763 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3764 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3765 message_context.msg_options = ntohl (0);
3766 message_context.network_size = estimate_diameter();
3767 message_context.peer = &my_identity;
3768 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3769 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3770 #if DEBUG_DHT_ROUTING
3771 if (dhtlog_handle != NULL)
3772 dhtlog_handle->insert_dhtkey(NULL, &key);
3774 increment_stats(STAT_GET_START);
3775 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3776 route_message (NULL, &get_message.header, &message_context);
3777 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3781 * Iterator over hash map entries.
3783 * @param cls closure
3784 * @param key current key code
3785 * @param value value in the hash map
3786 * @return GNUNET_YES if we should continue to
3791 add_known_to_bloom (void *cls,
3792 const GNUNET_HashCode * key,
3795 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3796 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3801 * Task to send a find peer message for our own peer identifier
3802 * so that we can find the closest peers in the network to ourselves
3803 * and attempt to connect to them.
3805 * @param cls closure for this task
3806 * @param tc the context under which the task is running
3809 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3811 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3812 struct DHT_MessageContext message_context;
3814 struct GNUNET_TIME_Relative next_send_time;
3815 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3817 struct GNUNET_TIME_Relative time_diff;
3818 struct GNUNET_TIME_Absolute end;
3820 double count_per_interval;
3822 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3825 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! */
3827 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3828 GNUNET_SCHEDULER_add_delayed (sched,
3829 GNUNET_TIME_UNIT_MINUTES,
3830 &send_find_peer_message, NULL);
3831 newly_found_peers = 0;
3835 increment_stats(STAT_FIND_PEER_START);
3837 end = GNUNET_TIME_absolute_get();
3838 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3840 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3842 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3843 count_per_interval = find_peer_context.count / multiplier;
3847 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3848 count_per_interval = find_peer_context.count * multiplier;
3852 #if FIND_PEER_WITH_HELLO
3853 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3854 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3855 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3857 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3858 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3860 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3861 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3862 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3863 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3864 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3865 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3866 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3867 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3868 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3869 message_context.network_size = estimate_diameter();
3870 message_context.peer = &my_identity;
3871 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3872 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3874 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3875 GNUNET_free(find_peer_msg);
3876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3877 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3879 if (newly_found_peers < bucket_size)
3881 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3882 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3883 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3887 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3888 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3889 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3892 GNUNET_assert (next_send_time.value != 0);
3893 find_peer_context.count = 0;
3894 newly_found_peers = 0;
3895 find_peer_context.start = GNUNET_TIME_absolute_get();
3896 if (GNUNET_YES == do_find_peer)
3898 GNUNET_SCHEDULER_add_delayed (sched,
3900 &send_find_peer_message, NULL);
3905 * Handler for any generic DHT messages, calls the appropriate handler
3906 * depending on message type, sends confirmation if responses aren't otherwise
3909 * @param cls closure for the service
3910 * @param client the client we received this message from
3911 * @param message the actual message received
3914 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3915 const struct GNUNET_MessageHeader *message)
3917 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3918 const struct GNUNET_MessageHeader *enc_msg;
3919 struct DHT_MessageContext message_context;
3921 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3923 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3924 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3928 ntohs (message->type),
3929 GNUNET_h2s (&dht_msg->key),
3930 GNUNET_ntohll (dht_msg->unique_id));
3932 #if DEBUG_DHT_ROUTING
3933 if (dhtlog_handle != NULL)
3934 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3936 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3937 message_context.client = find_active_client (client);
3938 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3939 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3940 message_context.replication = ntohl (dht_msg->desired_replication_level);
3941 message_context.msg_options = ntohl (dht_msg->options);
3942 message_context.network_size = estimate_diameter();
3943 message_context.peer = &my_identity;
3944 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3945 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3946 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3947 increment_stats(STAT_GET_START);
3948 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3949 increment_stats(STAT_PUT_START);
3950 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3951 increment_stats(STAT_FIND_PEER_START);
3953 route_message(cls, enc_msg, &message_context);
3955 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3960 * Handler for any locally received DHT control messages,
3961 * sets malicious flags mostly for now.
3963 * @param cls closure for the service
3964 * @param client the client we received this message from
3965 * @param message the actual message received
3969 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3970 const struct GNUNET_MessageHeader *message)
3972 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3973 (const struct GNUNET_DHT_ControlMessage *) message;
3975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3976 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3977 "CONTROL", ntohs(dht_control_msg->command));
3980 switch (ntohs(dht_control_msg->command))
3982 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3983 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3984 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3986 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3987 if (ntohs(dht_control_msg->variable) > 0)
3988 malicious_get_frequency = ntohs(dht_control_msg->variable);
3989 if (malicious_get_frequency == 0)
3990 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3991 if (malicious_getter != GNUNET_YES)
3992 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3993 malicious_getter = GNUNET_YES;
3994 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
3995 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3997 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3998 if (ntohs(dht_control_msg->variable) > 0)
3999 malicious_put_frequency = ntohs(dht_control_msg->variable);
4000 if (malicious_put_frequency == 0)
4001 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4002 if (malicious_putter != GNUNET_YES)
4003 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
4004 malicious_putter = GNUNET_YES;
4005 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4006 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4008 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4009 #if DEBUG_DHT_ROUTING
4010 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4011 dhtlog_handle->set_malicious(&my_identity);
4013 malicious_dropper = GNUNET_YES;
4014 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4015 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4018 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4019 "%s:%s Unknown control command type `%d'!\n",
4021 ntohs(dht_control_msg->command));
4025 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4029 * Handler for any generic DHT stop messages, calls the appropriate handler
4030 * depending on message type (if processed locally)
4032 * @param cls closure for the service
4033 * @param client the client we received this message from
4034 * @param message the actual message received
4038 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4039 const struct GNUNET_MessageHeader *message)
4042 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4043 (const struct GNUNET_DHT_StopMessage *) message;
4044 struct DHTQueryRecord *record;
4045 struct DHTRouteSource *pos;
4047 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4048 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4049 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4051 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
4058 if ((pos->client != NULL) && (pos->client->client_handle == client))
4060 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
4061 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
4067 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4072 * Core handler for p2p route requests.
4075 handle_dht_p2p_route_request (void *cls,
4076 const struct GNUNET_PeerIdentity *peer,
4077 const struct GNUNET_MessageHeader *message,
4078 struct GNUNET_TIME_Relative latency, uint32_t distance)
4081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4082 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4084 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4085 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4086 struct DHT_MessageContext *message_context;
4088 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
4090 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
4091 increment_stats("# route requests dropped due to high load");
4092 decrease_max_send_delay(get_max_send_delay());
4096 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4099 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4104 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4109 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4110 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4111 GNUNET_assert(message_context->bloom != NULL);
4112 message_context->hop_count = ntohl(incoming->hop_count);
4113 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
4114 message_context->replication = ntohl(incoming->desired_replication_level);
4115 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
4116 message_context->msg_options = ntohl(incoming->options);
4117 message_context->network_size = ntohl(incoming->network_size);
4118 message_context->peer = peer;
4119 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4120 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4121 route_message(cls, enc_msg, message_context);
4122 GNUNET_free(message_context);
4128 * Core handler for p2p route results.
4131 handle_dht_p2p_route_result (void *cls,
4132 const struct GNUNET_PeerIdentity *peer,
4133 const struct GNUNET_MessageHeader *message,
4134 struct GNUNET_TIME_Relative latency, uint32_t distance)
4137 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4138 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4140 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4141 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4142 struct DHT_MessageContext message_context;
4144 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4150 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4151 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4152 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4153 GNUNET_assert(message_context.bloom != NULL);
4154 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
4155 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
4156 message_context.msg_options = ntohl(incoming->options);
4157 message_context.hop_count = ntohl(incoming->hop_count);
4158 message_context.peer = peer;
4159 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
4160 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4161 route_result_message(cls, enc_msg, &message_context);
4167 * Receive the HELLO from transport service,
4168 * free current and replace if necessary.
4171 * @param message HELLO message of peer
4174 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4178 "Received our `%s' from transport service\n",
4182 GNUNET_assert (message != NULL);
4183 GNUNET_free_non_null(my_hello);
4184 my_hello = GNUNET_malloc(ntohs(message->size));
4185 memcpy(my_hello, message, ntohs(message->size));
4190 * Task run during shutdown.
4196 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4199 struct PeerInfo *pos;
4200 if (transport_handle != NULL)
4202 GNUNET_free_non_null(my_hello);
4203 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4204 GNUNET_TRANSPORT_disconnect(transport_handle);
4207 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4209 while (k_buckets[bucket_count].head != NULL)
4211 pos = k_buckets[bucket_count].head;
4213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4214 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4216 delete_peer(pos, bucket_count);
4219 if (coreAPI != NULL)
4222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4223 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4225 GNUNET_CORE_disconnect (coreAPI);
4227 if (datacache != NULL)
4230 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4231 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4233 GNUNET_DATACACHE_destroy (datacache);
4238 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4241 if (dhtlog_handle != NULL)
4242 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4244 GNUNET_free_non_null(my_short_id);
4249 * To be called on core init/fail.
4251 * @param cls service closure
4252 * @param server handle to the server for this service
4253 * @param identity the public identity of this peer
4254 * @param publicKey the public key of this peer
4257 core_init (void *cls,
4258 struct GNUNET_CORE_Handle *server,
4259 const struct GNUNET_PeerIdentity *identity,
4260 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4266 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4267 "%s: Connection to core FAILED!\n", "dht",
4268 GNUNET_i2s (identity));
4270 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
4271 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
4275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4276 "%s: Core connection initialized, I am peer: %s\n", "dht",
4277 GNUNET_i2s (identity));
4280 /* Copy our identity so we can use it */
4281 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4282 if (my_short_id != NULL)
4283 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4284 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4285 /* Set the server to local variable */
4288 if (dhtlog_handle != NULL)
4289 dhtlog_handle->insert_node (NULL, &my_identity);
4293 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4294 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4295 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4296 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4301 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4302 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4303 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4308 * Method called whenever a peer connects.
4310 * @param cls closure
4311 * @param peer peer identity this notification is about
4312 * @param latency reported latency of the connection with peer
4313 * @param distance reported distance (DV) to peer
4315 void handle_core_connect (void *cls,
4316 const struct GNUNET_PeerIdentity * peer,
4317 struct GNUNET_TIME_Relative latency,
4320 struct PeerInfo *ret;
4323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4324 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4327 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4329 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));
4333 if (datacache != NULL)
4334 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
4335 ret = try_add_peer(peer,
4336 find_current_bucket(&peer->hashPubKey),
4341 newly_found_peers++;
4342 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4345 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4346 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4351 * Method called whenever a peer disconnects.
4353 * @param cls closure
4354 * @param peer peer identity this notification is about
4356 void handle_core_disconnect (void *cls,
4358 GNUNET_PeerIdentity * peer)
4360 struct PeerInfo *to_remove;
4363 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");
4365 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4367 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));
4370 increment_stats(STAT_DISCONNECTS);
4371 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4372 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4373 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4374 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4375 delete_peer(to_remove, current_bucket);
4379 * Process dht requests.
4381 * @param cls closure
4382 * @param scheduler scheduler to use
4383 * @param server the initialized server
4384 * @param c configuration to use
4388 struct GNUNET_SCHEDULER_Handle *scheduler,
4389 struct GNUNET_SERVER_Handle *server,
4390 const struct GNUNET_CONFIGURATION_Handle *c)
4392 struct GNUNET_TIME_Relative next_send_time;
4393 unsigned long long temp_config_num;
4394 char *converge_modifier_buf;
4397 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4398 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4399 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4400 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4401 cfg, /* Main configuration */
4402 GNUNET_TIME_UNIT_FOREVER_REL,
4403 NULL, /* Closure passed to DHT functions */
4404 &core_init, /* Call core_init once connected */
4405 &handle_core_connect, /* Handle connects */
4406 &handle_core_disconnect, /* remove peers on disconnects */
4407 NULL, /* Do we care about "status" updates? */
4408 NULL, /* Don't want notified about all incoming messages */
4409 GNUNET_NO, /* For header only inbound notification */
4410 NULL, /* Don't want notified about all outbound messages */
4411 GNUNET_NO, /* For header only outbound notification */
4412 core_handlers); /* Register these handlers */
4414 if (coreAPI == NULL)
4416 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
4417 NULL, NULL, NULL, NULL, NULL);
4418 if (transport_handle != NULL)
4419 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4421 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4423 lowest_bucket = MAX_BUCKETS - 1;
4424 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4425 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4426 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4427 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4428 GNUNET_assert(all_known_peers != NULL);
4429 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4431 debug_routes = GNUNET_YES;
4435 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4438 strict_kademlia = GNUNET_YES;
4442 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4445 stop_on_closest = GNUNET_YES;
4449 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4452 stop_on_found = GNUNET_YES;
4456 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4457 "malicious_getter"))
4459 malicious_getter = GNUNET_YES;
4460 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4461 "MALICIOUS_GET_FREQUENCY",
4462 &malicious_get_frequency))
4463 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4466 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4470 max_hops = DEFAULT_MAX_HOPS;
4473 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4476 use_max_hops = GNUNET_YES;
4480 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4481 "malicious_putter"))
4483 malicious_putter = GNUNET_YES;
4484 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4485 "MALICIOUS_PUT_FREQUENCY",
4486 &malicious_put_frequency))
4487 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4490 dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
4491 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4493 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4497 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4498 "malicious_dropper"))
4500 malicious_dropper = GNUNET_YES;
4504 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4506 do_republish = GNUNET_NO;
4509 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4512 do_find_peer = GNUNET_NO;
4515 do_find_peer = GNUNET_YES;
4518 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4519 "use_real_distance"))
4520 use_real_distance = GNUNET_YES;
4523 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4524 "mysql_logging_extended"))
4526 debug_routes = GNUNET_YES;
4527 debug_routes_extended = GNUNET_YES;
4530 #if DEBUG_DHT_ROUTING
4531 if (GNUNET_YES == debug_routes)
4533 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4534 if (dhtlog_handle == NULL)
4536 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4537 "Could not connect to mysql logging server, logging will not happen!");
4542 converge_option = DHT_CONVERGE_SQUARE;
4544 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4547 converge_option = DHT_CONVERGE_LINEAR;
4549 else if (GNUNET_YES ==
4550 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4551 "converge_exponential"))
4553 converge_option = DHT_CONVERGE_EXPONENTIAL;
4555 else if (GNUNET_YES ==
4556 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4559 converge_option = DHT_CONVERGE_RANDOM;
4562 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4564 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4566 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4567 converge_modifier = 0.0;
4569 GNUNET_free(converge_modifier_buf);
4572 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4576 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4577 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4578 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4579 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4580 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4581 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4582 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4583 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4584 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4585 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4586 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4587 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4588 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4589 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4590 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4591 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4592 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4593 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4594 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4595 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4597 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4598 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4599 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4600 if (GNUNET_YES == do_find_peer)
4602 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4603 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4604 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4605 find_peer_context.start = GNUNET_TIME_absolute_get();
4606 GNUNET_SCHEDULER_add_delayed (sched,
4608 &send_find_peer_message, &find_peer_context);
4611 /* Scheduled the task to clean up when shutdown is called */
4612 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4613 GNUNET_TIME_UNIT_FOREVER_REL,
4614 &shutdown_task, NULL);
4618 * The main function for the dht service.
4620 * @param argc number of arguments from the command line
4621 * @param argv command line arguments
4622 * @return 0 ok, 1 on error
4625 main (int argc, char *const *argv)
4627 return (GNUNET_OK ==
4628 GNUNET_SERVICE_run (argc,
4631 GNUNET_SERVICE_OPTION_NONE,
4632 &run, NULL)) ? 0 : 1;