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_block_lib.h"
30 #include "gnunet_client_lib.h"
31 #include "gnunet_getopt_lib.h"
32 #include "gnunet_os_lib.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_service_lib.h"
35 #include "gnunet_core_service.h"
36 #include "gnunet_signal_lib.h"
37 #include "gnunet_util_lib.h"
38 #include "gnunet_datacache_lib.h"
39 #include "gnunet_transport_service.h"
40 #include "gnunet_hello_lib.h"
41 #include "gnunet_dht_service.h"
42 #include "gnunet_statistics_service.h"
47 #define PRINT_TABLES GNUNET_NO
49 #define REAL_DISTANCE GNUNET_NO
51 #define EXTRA_CHECKS GNUNET_NO
54 * How many buckets will we allow total.
56 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
59 * Should the DHT issue FIND_PEER requests to get better routing tables?
61 #define DEFAULT_DO_FIND_PEER GNUNET_YES
64 * Defines whether find peer requests send their HELLO's outgoing,
65 * or expect replies to contain hellos.
67 #define FIND_PEER_WITH_HELLO GNUNET_YES
70 * What is the maximum number of peers in a given bucket.
72 #define DEFAULT_BUCKET_SIZE 4
75 * Minimum number of peers we need for "good" routing,
76 * any less than this and we will allow messages to
77 * travel much further through the network!
79 #define MINIMUM_PEER_THRESHOLD 20
81 #define DHT_MAX_RECENT 1000
83 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
86 * Default time to wait to send messages on behalf of other peers.
88 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
91 * Default importance for handling messages on behalf of other peers.
93 #define DHT_DEFAULT_P2P_IMPORTANCE 0
96 * How long to keep recent requests around by default.
98 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
101 * Default time to wait to send find peer messages sent by the dht service.
103 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
106 * Default importance for find peer messages sent by the dht service.
108 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
111 * Default replication parameter for find peer messages sent by the dht service.
113 #define DHT_DEFAULT_PUT_REPLICATION 4
116 * Default replication parameter for find peer messages sent by the dht service.
118 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
121 * Default options for find peer requests sent by the dht service.
123 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
124 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
127 * How long at least to wait before sending another find peer request.
129 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
132 * How long at most to wait before sending another find peer request.
134 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
137 * How often to update our preference levels for peers in our routing tables.
139 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
142 * How long at most on average will we allow a reply forward to take
143 * (before we quit sending out new requests)
145 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
148 * How many initial requests to send out (in true Kademlia fashion)
150 #define DHT_KADEMLIA_REPLICATION 3
153 * Default frequency for sending malicious get messages
155 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
158 * Default frequency for sending malicious put messages
160 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
163 * Type for a malicious request, so we can ignore it during testing
165 #define DHT_MALICIOUS_MESSAGE_TYPE 42
167 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
170 * Real maximum number of hops, at which point we refuse
171 * to forward the message.
173 #define DEFAULT_MAX_HOPS 10
176 * How many time differences between requesting a core send and
177 * the actual callback to remember.
179 #define MAX_REPLY_TIMES 8
181 enum ConvergenceOptions
184 * Use the linear method for convergence.
189 * Converge using a fast converging square
195 * Converge using a slower exponential
198 DHT_CONVERGE_EXPONENTIAL,
201 * Don't do any special convergence, allow
202 * the algorithm to hopefully route to closer
209 * Linked list of messages to send to clients.
211 struct P2PPendingMessage
214 * Pointer to next item in the list
216 struct P2PPendingMessage *next;
219 * Pointer to previous item in the list
221 struct P2PPendingMessage *prev;
224 * Message importance level.
226 unsigned int importance;
229 * Time when this request was scheduled to be sent.
231 struct GNUNET_TIME_Absolute scheduled;
234 * How long to wait before sending message.
236 struct GNUNET_TIME_Relative timeout;
239 * Actual message to be sent; // avoid allocation
241 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
246 * Per-peer information.
251 * Next peer entry (DLL)
253 struct PeerInfo *next;
256 * Prev peer entry (DLL)
258 struct PeerInfo *prev;
261 * Head of pending messages to be sent to this peer.
263 struct P2PPendingMessage *head;
266 * Tail of pending messages to be sent to this peer.
268 struct P2PPendingMessage *tail;
271 * Core handle for sending messages to this peer.
273 struct GNUNET_CORE_TransmitHandle *th;
276 * Task for scheduling message sends.
278 GNUNET_SCHEDULER_TaskIdentifier send_task;
281 * Task for scheduling preference updates
283 GNUNET_SCHEDULER_TaskIdentifier preference_task;
286 * Preference update context
288 struct GNUNET_CORE_InformationRequestContext *info_ctx;
291 * What is the average latency for replies received?
293 struct GNUNET_TIME_Relative latency;
296 * What is the identity of the peer?
298 struct GNUNET_PeerIdentity id;
301 * Transport level distance to peer.
303 unsigned int distance;
306 * Holds matching bits from peer to current target,
307 * used for distance comparisons between peers. May
308 * be considered a really bad idea.
309 * FIXME: remove this value (create struct which holds
310 * a single peerinfo and the matching bits, use
311 * that to pass to comparitor)
313 unsigned int matching_bits;
316 * Task for scheduling periodic ping messages for this peer.
318 GNUNET_SCHEDULER_TaskIdentifier ping_task;
322 * Peers are grouped into buckets.
329 struct PeerInfo *head;
334 struct PeerInfo *tail;
337 * Number of peers in the bucket.
339 unsigned int peers_size;
343 * Linked list of messages to send to clients.
345 struct PendingMessage
348 * Pointer to next item in the list
350 struct PendingMessage *next;
353 * Pointer to previous item in the list
355 struct PendingMessage *prev;
358 * Actual message to be sent; // avoid allocation
360 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
365 * Struct containing information about a client,
366 * handle to connect to it, and any pending messages
367 * that need to be sent to it.
372 * Linked list of active clients
374 struct ClientList *next;
377 * The handle to this client
379 struct GNUNET_SERVER_Client *client_handle;
382 * Handle to the current transmission request, NULL
385 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
388 * Linked list of pending messages for this client
390 struct PendingMessage *pending_head;
393 * Tail of linked list of pending messages for this client
395 struct PendingMessage *pending_tail;
400 * Context containing information about a DHT message received.
402 struct DHT_MessageContext
405 * The client this request was received from.
406 * (NULL if received from another peer)
408 struct ClientList *client;
411 * The peer this request was received from.
412 * (NULL if received from local client)
414 const struct GNUNET_PeerIdentity *peer;
417 * Bloomfilter for this routing request.
419 struct GNUNET_CONTAINER_BloomFilter *bloom;
422 * The key this request was about
427 * How long should we wait to transmit this request?
429 struct GNUNET_TIME_Relative timeout;
432 * The unique identifier of this request
437 * Desired replication level
439 uint32_t replication;
442 * Network size estimate, either ours or the sum of
443 * those routed to thus far. =~ Log of number of peers
444 * chosen from for this request.
446 uint32_t network_size;
449 * Any message options for this request
451 uint32_t msg_options;
454 * How many hops has the message already traversed?
459 * How important is this message?
461 unsigned int importance;
464 * Did we forward this message? (may need to remember it!)
469 * Are we the closest known peer to this key (out of our neighbors?)
475 * Record used for remembering what peers are waiting for what
476 * responses (based on search key).
478 struct DHTRouteSource
483 struct DHTRouteSource *next;
488 struct DHTRouteSource *prev;
491 * Source of the request. Replies should be forwarded to
494 struct GNUNET_PeerIdentity source;
497 * If this was a local request, remember the client; otherwise NULL.
499 struct ClientList *client;
502 * Pointer to this nodes heap location (for removal)
504 struct GNUNET_CONTAINER_HeapNode *hnode;
507 * Back pointer to the record storing this information.
509 struct DHTQueryRecord *record;
512 * Task to remove this entry on timeout.
514 GNUNET_SCHEDULER_TaskIdentifier delete_task;
517 * Bloomfilter of peers we have already sent back as
518 * replies to the initial request. Allows us to not
519 * forward the same peer multiple times for a find peer
522 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
527 * Entry in the DHT routing table.
529 struct DHTQueryRecord
532 * Head of DLL for result forwarding.
534 struct DHTRouteSource *head;
537 * Tail of DLL for result forwarding.
539 struct DHTRouteSource *tail;
542 * Key that the record concerns.
547 * GET message of this record (what we already forwarded?).
549 //DV_DHT_MESSAGE get; Try to get away with not saving this.
552 * Bloomfilter of the peers we've replied to so far
554 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
559 * Context used to calculate the number of find peer messages
560 * per X time units since our last scheduled find peer message
561 * was sent. If we have seen too many messages, delay or don't
564 struct FindPeerMessageContext
568 struct GNUNET_TIME_Absolute start;
570 struct GNUNET_TIME_Absolute end;
574 * DHT Routing results structure
579 * Min heap for removal upon reaching limit
581 struct GNUNET_CONTAINER_Heap *minHeap;
584 * Hashmap for fast key based lookup
586 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
591 * DHT structure for recent requests.
593 struct RecentRequests
596 * Min heap for removal upon reaching limit
598 struct GNUNET_CONTAINER_Heap *minHeap;
601 * Hashmap for key based lookup
603 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
609 * Position of this node in the min heap.
611 struct GNUNET_CONTAINER_HeapNode *heap_node;
614 * Bloomfilter containing entries for peers
615 * we forwarded this request to.
617 struct GNUNET_CONTAINER_BloomFilter *bloom;
620 * Timestamp of this request, for ordering
623 struct GNUNET_TIME_Absolute timestamp;
626 * Key of this request.
631 * Unique identifier for this request.
636 * Task to remove this entry on timeout.
638 GNUNET_SCHEDULER_TaskIdentifier remove_task;
641 struct RepublishContext
656 * Which kind of convergence will we be using?
658 static enum ConvergenceOptions converge_option;
661 * Modifier for the convergence function
663 static float converge_modifier;
666 * Recent requests by hash/uid and by time inserted.
668 static struct RecentRequests recent;
671 * Context to use to calculate find peer rates.
673 static struct FindPeerMessageContext find_peer_context;
676 * Don't use our routing algorithm, always route
677 * to closest peer; initially send requests to 3
680 static unsigned int strict_kademlia;
683 * Routing option to end routing when closest peer found.
685 static unsigned int stop_on_closest;
688 * Routing option to end routing when data is found.
690 static unsigned int stop_on_found;
693 * Whether DHT needs to manage find peer requests, or
694 * an external force will do it on behalf of the DHT.
696 static unsigned int do_find_peer;
699 * Once we have stored an item in the DHT, refresh it
700 * according to our republish interval.
702 static unsigned int do_republish;
705 * Use the "real" distance metric when selecting the
706 * next routing hop. Can be less accurate.
708 static unsigned int use_real_distance;
711 * How many peers have we added since we sent out our last
714 static unsigned int newly_found_peers;
717 * Container of active queries we should remember
719 static struct DHTResults forward_list;
722 * Handle to the datacache service (for inserting/retrieving data)
724 static struct GNUNET_DATACACHE_Handle *datacache;
727 * Handle for the statistics service.
729 struct GNUNET_STATISTICS_Handle *stats;
732 * The main scheduler to use for the DHT service
734 static struct GNUNET_SCHEDULER_Handle *sched;
737 * The configuration the DHT service is running with
739 static const struct GNUNET_CONFIGURATION_Handle *cfg;
742 * Handle to the core service
744 static struct GNUNET_CORE_Handle *coreAPI;
747 * Handle to the transport service, for getting our hello
749 static struct GNUNET_TRANSPORT_Handle *transport_handle;
752 * The identity of our peer.
754 static struct GNUNET_PeerIdentity my_identity;
757 * Short id of the peer, for printing
759 static char *my_short_id;
764 static struct GNUNET_MessageHeader *my_hello;
767 * Task to run when we shut down, cleaning up all our trash
769 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
772 * The lowest currently used bucket.
774 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
777 * The maximum number of hops before we stop routing messages.
779 static unsigned long long max_hops;
782 * How often to republish content we have previously stored.
784 static struct GNUNET_TIME_Relative dht_republish_frequency;
787 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
789 static int use_max_hops;
792 * The buckets (Kademlia routing table, complete with growth).
793 * Array of size MAX_BUCKET_SIZE.
795 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
798 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
800 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
803 * Recently seen find peer requests.
805 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
808 * Maximum size for each bucket.
810 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
813 * List of active clients.
815 static struct ClientList *client_list;
818 * Handle to the DHT logger.
820 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
823 * Whether or not to send routing debugging information
824 * to the dht logging server
826 static unsigned int debug_routes;
829 * Whether or not to send FULL route information to
832 static unsigned int debug_routes_extended;
835 * GNUNET_YES or GNUNET_NO, whether or not to act as
836 * a malicious node which drops all messages
838 static unsigned int malicious_dropper;
841 * GNUNET_YES or GNUNET_NO, whether or not to act as
842 * a malicious node which sends out lots of GETS
844 static unsigned int malicious_getter;
847 * GNUNET_YES or GNUNET_NO, whether or not to act as
848 * a malicious node which sends out lots of PUTS
850 static unsigned int malicious_putter;
853 * Frequency for malicious get requests.
855 static unsigned long long malicious_get_frequency;
858 * Frequency for malicious put requests.
860 static unsigned long long malicious_put_frequency;
863 * Reply times for requests, if we are busy, don't send any
866 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
869 * Current counter for replies.
871 static unsigned int reply_counter;
874 * Our handle to the BLOCK library.
876 static struct GNUNET_BLOCK_Context *block_context;
880 * Forward declaration.
883 send_generic_reply (void *cls, size_t size, void *buf);
886 /** Declare here so retry_core_send is aware of it */
888 core_transmit_notify (void *cls,
889 size_t size, void *buf);
892 * Convert unique ID to hash code.
894 * @param uid unique ID to convert
895 * @param hash set to uid (extended with zeros)
898 hash_from_uid (uint64_t uid,
899 GNUNET_HashCode *hash)
901 memset (hash, 0, sizeof(GNUNET_HashCode));
902 *((uint64_t*)hash) = uid;
907 * Calculate the average send time between messages so that we can
908 * ignore certain requests if we get too busy.
910 * @return the average time between asking core to send a message
911 * and when the buffer for copying it is passed
913 static struct GNUNET_TIME_Relative get_average_send_delay()
916 unsigned int divisor;
917 struct GNUNET_TIME_Relative average_time;
918 average_time = GNUNET_TIME_relative_get_zero();
920 for (i = 0; i < MAX_REPLY_TIMES; i++)
922 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
923 if (reply_times[i].value == (uint64_t)0)
933 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
934 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
940 * Given the largest send delay, artificially decrease it
941 * so the next time around we may have a chance at sending
944 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
947 for (i = 0; i < MAX_REPLY_TIMES; i++)
949 if (reply_times[i].value == max_time.value)
951 reply_times[i].value = reply_times[i].value / 2;
958 * Find the maximum send time of the recently sent values.
960 * @return the average time between asking core to send a message
961 * and when the buffer for copying it is passed
963 static struct GNUNET_TIME_Relative get_max_send_delay()
966 struct GNUNET_TIME_Relative max_time;
967 max_time = GNUNET_TIME_relative_get_zero();
969 for (i = 0; i < MAX_REPLY_TIMES; i++)
971 if (reply_times[i].value > max_time.value)
972 max_time.value = reply_times[i].value;
975 if (max_time.value > MAX_REQUEST_TIME.value)
976 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
981 increment_stats(const char *value)
985 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
990 * Try to send another message from our core send list
993 try_core_send (void *cls,
994 const struct GNUNET_SCHEDULER_TaskContext *tc)
996 struct PeerInfo *peer = cls;
997 struct P2PPendingMessage *pending;
1000 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
1002 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1005 if (peer->th != NULL)
1006 return; /* Message send already in progress */
1008 pending = peer->head;
1009 if (pending != NULL)
1011 ssize = ntohs(pending->msg->size);
1013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1014 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
1015 "DHT", ssize, GNUNET_i2s(&peer->id));
1017 pending->scheduled = GNUNET_TIME_absolute_get();
1019 if (reply_counter >= MAX_REPLY_TIMES)
1021 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
1022 pending->timeout, &peer->id,
1023 ssize, &core_transmit_notify, peer);
1028 * Function called to send a request out to another peer.
1029 * Called both for locally initiated requests and those
1030 * received from other peers.
1032 * @param cls DHT service closure argument
1033 * @param msg the encapsulated message
1034 * @param peer the peer to forward the message to
1035 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1038 forward_result_message (void *cls,
1039 const struct GNUNET_MessageHeader *msg,
1040 struct PeerInfo *peer,
1041 struct DHT_MessageContext *msg_ctx)
1043 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1044 struct P2PPendingMessage *pending;
1048 increment_stats(STAT_RESULT_FORWARDS);
1049 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1050 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1051 psize = sizeof(struct P2PPendingMessage) + msize;
1052 pending = GNUNET_malloc(psize);
1053 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1054 pending->importance = DHT_SEND_PRIORITY;
1055 pending->timeout = GNUNET_TIME_relative_get_forever();
1056 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1057 result_message->header.size = htons(msize);
1058 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1059 result_message->put_path_length = htons(0); /* FIXME: implement */
1060 result_message->get_path_length = htons(0); /* FIXME: implement */
1061 result_message->options = htonl(msg_ctx->msg_options);
1062 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1063 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1064 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1065 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1066 memcpy(&result_message[1], msg, ntohs(msg->size));
1068 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));
1070 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1071 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1072 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1077 * Called when core is ready to send a message we asked for
1078 * out to the destination.
1080 * @param cls closure (NULL)
1081 * @param size number of bytes available in buf
1082 * @param buf where the callee should write the message
1083 * @return number of bytes written to buf
1086 core_transmit_notify (void *cls,
1087 size_t size, void *buf)
1089 struct PeerInfo *peer = cls;
1091 struct P2PPendingMessage *pending;
1098 /* client disconnected */
1100 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1105 if (peer->head == NULL)
1110 pending = peer->head;
1111 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1112 msize = ntohs(pending->msg->size);
1116 memcpy (cbuf, pending->msg, msize);
1117 GNUNET_CONTAINER_DLL_remove (peer->head,
1121 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));
1123 GNUNET_free (pending);
1126 while (NULL != pending &&
1127 (size - off >= (msize = ntohs (pending->msg->size))))
1129 #if DEBUG_DHT_ROUTING
1130 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);
1132 memcpy (&cbuf[off], pending->msg, msize);
1134 GNUNET_CONTAINER_DLL_remove (peer->head,
1137 GNUNET_free (pending);
1138 pending = peer->head;
1141 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1142 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1144 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);
1151 * Compute the distance between have and target as a 32-bit value.
1152 * Differences in the lower bits must count stronger than differences
1153 * in the higher bits.
1155 * @return 0 if have==target, otherwise a number
1156 * that is larger as the distance between
1157 * the two hash codes increases
1160 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1162 unsigned int bucket;
1167 /* We have to represent the distance between two 2^9 (=512)-bit
1168 numbers as a 2^5 (=32)-bit number with "0" being used for the
1169 two numbers being identical; furthermore, we need to
1170 guarantee that a difference in the number of matching
1171 bits is always represented in the result.
1173 We use 2^32/2^9 numerical values to distinguish between
1174 hash codes that have the same LSB bit distance and
1175 use the highest 2^9 bits of the result to signify the
1176 number of (mis)matching LSB bits; if we have 0 matching
1177 and hence 512 mismatching LSB bits we return -1 (since
1178 512 itself cannot be represented with 9 bits) */
1180 /* first, calculate the most significant 9 bits of our
1181 result, aka the number of LSBs */
1182 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1183 /* bucket is now a value between 0 and 512 */
1185 return 0; /* perfect match */
1187 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1188 below, we'd end up with max+1 (overflow)) */
1190 /* calculate the most significant bits of the final result */
1191 msb = (512 - bucket) << (32 - 9);
1192 /* calculate the 32-9 least significant bits of the final result by
1193 looking at the differences in the 32-9 bits following the
1194 mismatching bit at 'bucket' */
1196 for (i = bucket + 1;
1197 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1199 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1200 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1201 last bit set will be 31 -- if
1202 i does not reach 512 first... */
1208 * Return a number that is larger the closer the
1209 * "have" GNUNET_hash code is to the "target".
1211 * @return inverse distance metric, non-zero.
1212 * Must fudge the value if NO bits match.
1215 inverse_distance (const GNUNET_HashCode * target,
1216 const GNUNET_HashCode * have)
1218 if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1219 return 1; /* Never return 0! */
1220 return ((unsigned int) -1) - distance (target, have);
1224 * Find the optimal bucket for this key, regardless
1225 * of the current number of buckets in use.
1227 * @param hc the hashcode to compare our identity to
1229 * @return the proper bucket index, or GNUNET_SYSERR
1230 * on error (same hashcode)
1232 static int find_bucket(const GNUNET_HashCode *hc)
1236 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1237 if (bits == MAX_BUCKETS)
1238 return GNUNET_SYSERR;
1239 return MAX_BUCKETS - bits - 1;
1243 * Find which k-bucket this peer should go into,
1244 * taking into account the size of the k-bucket
1245 * array. This means that if more bits match than
1246 * there are currently buckets, lowest_bucket will
1249 * @param hc GNUNET_HashCode we are finding the bucket for.
1251 * @return the proper bucket index for this key,
1252 * or GNUNET_SYSERR on error (same hashcode)
1254 static int find_current_bucket(const GNUNET_HashCode *hc)
1257 actual_bucket = find_bucket(hc);
1259 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1260 return lowest_bucket;
1261 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1262 return lowest_bucket;
1264 return actual_bucket;
1269 * Find a routing table entry from a peer identity
1271 * @param peer the peer to look up
1273 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1276 find_bucket_by_peer(const struct PeerInfo *peer)
1279 struct PeerInfo *pos;
1281 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1283 pos = k_buckets[bucket].head;
1292 return GNUNET_SYSERR; /* No such peer. */
1298 * Print the complete routing table for this peer.
1301 print_routing_table ()
1304 struct PeerInfo *pos;
1305 char char_buf[30000];
1307 memset(char_buf, 0, sizeof(char_buf));
1309 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1310 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1311 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1313 pos = k_buckets[bucket].head;
1314 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1315 //fprintf(stderr, "Bucket %d:\n", bucket);
1318 //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));
1319 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));
1323 fprintf(stderr, "%s", char_buf);
1329 * Find a routing table entry from a peer identity
1331 * @param peer the peer identity to look up
1333 * @return the routing table entry, or NULL if not found
1335 static struct PeerInfo *
1336 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1339 struct PeerInfo *pos;
1340 bucket = find_current_bucket(&peer->hashPubKey);
1342 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1345 pos = k_buckets[bucket].head;
1348 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1352 return NULL; /* No such peer. */
1355 /* Forward declaration */
1357 update_core_preference (void *cls,
1358 const struct GNUNET_SCHEDULER_TaskContext *tc);
1360 * Function called with statistics about the given peer.
1362 * @param cls closure
1363 * @param peer identifies the peer
1364 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1365 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1366 * @param amount set to the amount that was actually reserved or unreserved;
1367 * either the full requested amount or zero (no partial reservations)
1368 * @param preference current traffic preference for the given peer
1371 update_core_preference_finish (void *cls,
1372 const struct GNUNET_PeerIdentity * peer,
1373 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1374 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1375 int amount, uint64_t preference)
1377 struct PeerInfo *peer_info = cls;
1378 peer_info->info_ctx = NULL;
1379 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1383 update_core_preference (void *cls,
1384 const struct GNUNET_SCHEDULER_TaskContext *tc)
1386 struct PeerInfo *peer = cls;
1387 uint64_t preference;
1388 unsigned int matching;
1389 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1393 matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1396 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1399 preference = 1LL << matching;
1400 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1402 GNUNET_TIME_relative_get_forever(),
1403 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1406 &update_core_preference_finish,
1411 * Really add a peer to a bucket (only do assertions
1414 * @param peer GNUNET_PeerIdentity of the peer to add
1415 * @param bucket the already figured out bucket to add
1417 * @param latency the core reported latency of this peer
1418 * @param distance the transport level distance to this peer
1420 * @return the newly added PeerInfo
1422 static struct PeerInfo *
1423 add_peer(const struct GNUNET_PeerIdentity *peer,
1424 unsigned int bucket,
1425 struct GNUNET_TIME_Relative latency,
1426 unsigned int distance)
1428 struct PeerInfo *new_peer;
1429 GNUNET_assert(bucket < MAX_BUCKETS);
1430 GNUNET_assert(peer != NULL);
1431 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1432 new_peer->latency = latency;
1433 new_peer->distance = distance;
1435 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1437 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1438 k_buckets[bucket].tail,
1439 k_buckets[bucket].tail,
1441 k_buckets[bucket].peers_size++;
1443 if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1445 #if DO_UPDATE_PREFERENCE
1446 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1454 * Given a peer and its corresponding bucket,
1455 * remove it from that bucket. Does not free
1456 * the PeerInfo struct, nor cancel messages
1457 * or free messages waiting to be sent to this
1460 * @param peer the peer to remove
1461 * @param bucket the bucket the peer belongs to
1463 static void remove_peer (struct PeerInfo *peer,
1464 unsigned int bucket)
1466 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1467 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1468 k_buckets[bucket].tail,
1470 k_buckets[bucket].peers_size--;
1472 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1478 * Removes peer from a bucket, then frees associated
1479 * resources and frees peer.
1481 * @param peer peer to be removed and freed
1482 * @param bucket which bucket this peer belongs to
1484 static void delete_peer (struct PeerInfo *peer,
1485 unsigned int bucket)
1487 struct P2PPendingMessage *pos;
1488 struct P2PPendingMessage *next;
1490 struct PeerInfo *peer_pos;
1492 peer_pos = k_buckets[bucket].head;
1493 while ((peer_pos != NULL) && (peer_pos != peer))
1494 peer_pos = peer_pos->next;
1495 if (peer_pos == NULL)
1497 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1498 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));
1500 GNUNET_assert(peer_pos != NULL);
1502 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1504 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1505 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1506 if (peer->th != NULL)
1507 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1510 while (pos != NULL) /* Remove any pending messages for this peer */
1517 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1518 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1524 * Iterator over hash map entries.
1526 * @param cls closure
1527 * @param key current key code
1528 * @param value PeerInfo of the peer to move to new lowest bucket
1529 * @return GNUNET_YES if we should continue to
1533 static int move_lowest_bucket (void *cls,
1534 const GNUNET_HashCode * key,
1537 struct PeerInfo *peer = value;
1540 GNUNET_assert(lowest_bucket > 0);
1541 new_bucket = lowest_bucket - 1;
1542 remove_peer(peer, lowest_bucket);
1543 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1544 k_buckets[new_bucket].tail,
1545 k_buckets[new_bucket].tail,
1547 k_buckets[new_bucket].peers_size++;
1553 * The current lowest bucket is full, so change the lowest
1554 * bucket to the next lower down, and move any appropriate
1555 * entries in the current lowest bucket to the new bucket.
1557 static void enable_next_bucket()
1559 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1560 struct PeerInfo *pos;
1561 GNUNET_assert(lowest_bucket > 0);
1562 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1563 pos = k_buckets[lowest_bucket].head;
1566 fprintf(stderr, "Printing RT before new bucket\n");
1567 print_routing_table();
1569 /* Populate the array of peers which should be in the next lowest bucket */
1572 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1573 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1577 /* Remove peers from lowest bucket, insert into next lowest bucket */
1578 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1579 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1580 lowest_bucket = lowest_bucket - 1;
1582 fprintf(stderr, "Printing RT after new bucket\n");
1583 print_routing_table();
1588 * Find the closest peer in our routing table to the
1591 * @return The closest peer in our routing table to the
1592 * key, or NULL on error.
1594 static struct PeerInfo *
1595 find_closest_peer (const GNUNET_HashCode *hc)
1597 struct PeerInfo *pos;
1598 struct PeerInfo *current_closest;
1599 unsigned int lowest_distance;
1600 unsigned int temp_distance;
1604 lowest_distance = -1;
1606 if (k_buckets[lowest_bucket].peers_size == 0)
1609 current_closest = NULL;
1610 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1612 pos = k_buckets[bucket].head;
1614 while ((pos != NULL) && (count < bucket_size))
1616 temp_distance = distance(&pos->id.hashPubKey, hc);
1617 if (temp_distance <= lowest_distance)
1619 lowest_distance = temp_distance;
1620 current_closest = pos;
1626 GNUNET_assert(current_closest != NULL);
1627 return current_closest;
1632 * Function called to send a request out to another peer.
1633 * Called both for locally initiated requests and those
1634 * received from other peers.
1636 * @param msg the encapsulated message
1637 * @param peer the peer to forward the message to
1638 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1640 static void forward_message (const struct GNUNET_MessageHeader *msg,
1641 struct PeerInfo *peer,
1642 struct DHT_MessageContext *msg_ctx)
1644 struct GNUNET_DHT_P2PRouteMessage *route_message;
1645 struct P2PPendingMessage *pending;
1649 increment_stats(STAT_ROUTE_FORWARDS);
1651 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1652 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1654 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1655 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1656 psize = sizeof(struct P2PPendingMessage) + msize;
1657 pending = GNUNET_malloc(psize);
1658 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1659 pending->importance = msg_ctx->importance;
1660 pending->timeout = msg_ctx->timeout;
1661 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1662 route_message->header.size = htons(msize);
1663 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1664 route_message->options = htonl(msg_ctx->msg_options);
1665 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1666 route_message->network_size = htonl(msg_ctx->network_size);
1667 route_message->desired_replication_level = htonl(msg_ctx->replication);
1668 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1669 if (msg_ctx->bloom != NULL)
1670 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1671 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1672 memcpy(&route_message[1], msg, ntohs(msg->size));
1674 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));
1676 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1677 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1678 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1683 * Task used to send ping messages to peers so that
1684 * they don't get disconnected.
1686 * @param cls the peer to send a ping message to
1687 * @param tc context, reason, etc.
1690 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1692 struct PeerInfo *peer = cls;
1693 struct GNUNET_MessageHeader ping_message;
1694 struct DHT_MessageContext message_context;
1696 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1699 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1700 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1702 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1704 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1706 forward_message(&ping_message, peer, &message_context);
1707 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1711 * Schedule PING messages for the top X peers in each
1712 * bucket of the routing table (so core won't disconnect them!)
1714 void schedule_ping_messages()
1716 unsigned int bucket;
1718 struct PeerInfo *pos;
1719 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1721 pos = k_buckets[bucket].head;
1725 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1726 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1727 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1729 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1730 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1740 * Attempt to add a peer to our k-buckets.
1742 * @param peer the peer identity of the peer being added
1743 * @param bucket the bucket that we want this peer to go in
1744 * @param latency transport latency of this peer
1745 * @param distance transport distance to this peer
1747 * @return NULL if the peer was not added,
1748 * pointer to PeerInfo for new peer otherwise
1750 static struct PeerInfo *
1751 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1752 unsigned int bucket,
1753 struct GNUNET_TIME_Relative latency,
1754 unsigned int distance)
1757 struct PeerInfo *new_peer;
1759 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1762 peer_bucket = find_current_bucket(&peer->hashPubKey);
1764 GNUNET_assert(peer_bucket >= lowest_bucket);
1765 new_peer = add_peer(peer, peer_bucket, latency, distance);
1767 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1768 enable_next_bucket();
1770 schedule_ping_messages();
1777 * Task run to check for messages that need to be sent to a client.
1779 * @param client a ClientList, containing the client and any messages to be sent to it
1782 process_pending_messages (struct ClientList *client)
1784 if (client->pending_head == NULL)
1786 if (client->transmit_handle != NULL)
1789 client->transmit_handle =
1790 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1791 ntohs (client->pending_head->msg->
1793 GNUNET_TIME_UNIT_FOREVER_REL,
1794 &send_generic_reply, client);
1798 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1799 * request. A ClientList is passed as closure, take the head of the list
1800 * and copy it into buf, which has the result of sending the message to the
1803 * @param cls closure to this call
1804 * @param size maximum number of bytes available to send
1805 * @param buf where to copy the actual message to
1807 * @return the number of bytes actually copied, 0 indicates failure
1810 send_generic_reply (void *cls, size_t size, void *buf)
1812 struct ClientList *client = cls;
1814 struct PendingMessage *reply;
1818 client->transmit_handle = NULL;
1821 /* client disconnected */
1825 while ( (NULL != (reply = client->pending_head)) &&
1826 (size >= off + (msize = ntohs (reply->msg->size))))
1828 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1829 client->pending_tail,
1831 memcpy (&cbuf[off], reply->msg, msize);
1832 GNUNET_free (reply);
1835 process_pending_messages (client);
1837 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1838 "Transmitted %u bytes of replies to client\n",
1839 (unsigned int) off);
1846 * Add a PendingMessage to the clients list of messages to be sent
1848 * @param client the active client to send the message to
1849 * @param pending_message the actual message to send
1852 add_pending_message (struct ClientList *client,
1853 struct PendingMessage *pending_message)
1855 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1856 client->pending_tail,
1857 client->pending_tail,
1859 process_pending_messages (client);
1866 * Called when a reply needs to be sent to a client, as
1867 * a result it found to a GET or FIND PEER request.
1869 * @param client the client to send the reply to
1870 * @param message the encapsulated message to send
1871 * @param uid the unique identifier of this request
1874 send_reply_to_client (struct ClientList *client,
1875 const struct GNUNET_MessageHeader *message,
1876 unsigned long long uid,
1877 const GNUNET_HashCode *key)
1879 struct GNUNET_DHT_RouteResultMessage *reply;
1880 struct PendingMessage *pending_message;
1884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1885 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1887 msize = ntohs (message->size);
1888 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1889 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1891 GNUNET_break_op (0);
1894 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1895 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1896 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1897 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1898 reply->header.size = htons (tsize);
1899 reply->put_path_length = htons(0); /* FIXME: implement */
1900 reply->get_path_length = htons(0); /* FIXME: implement */
1901 reply->unique_id = GNUNET_htonll (uid);
1903 memcpy (&reply[1], message, msize);
1904 add_pending_message (client, pending_message);
1908 * Consider whether or not we would like to have this peer added to
1909 * our routing table. Check whether bucket for this peer is full,
1910 * if so return negative; if not return positive. Since peers are
1911 * only added on CORE level connect, this doesn't actually add the
1912 * peer to the routing table.
1914 * @param peer the peer we are considering adding
1916 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1919 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1923 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1924 return GNUNET_NO; /* We already know this peer (are connected even!) */
1925 bucket = find_current_bucket(&peer->hashPubKey);
1927 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1934 * Main function that handles whether or not to route a result
1935 * message to other peers, or to send to our local client.
1937 * @param cls closure (unused, always should be NULL)
1938 * @param msg the result message to be routed
1939 * @param message_context context of the message we are routing
1941 * @return the number of peers the message was routed to,
1942 * GNUNET_SYSERR on failure
1944 static int route_result_message(void *cls,
1945 struct GNUNET_MessageHeader *msg,
1946 struct DHT_MessageContext *message_context)
1948 struct GNUNET_PeerIdentity new_peer;
1949 struct DHTQueryRecord *record;
1950 struct DHTRouteSource *pos;
1951 struct PeerInfo *peer_info;
1952 const struct GNUNET_MessageHeader *hello_msg;
1954 increment_stats(STAT_RESULTS);
1956 * If a find peer result message is received and contains a valid
1957 * HELLO for another peer, offer it to the transport service.
1959 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1961 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1964 hello_msg = &msg[1];
1965 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1967 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1971 else /* We have a valid hello, and peer id stored in new_peer */
1973 find_peer_context.count++;
1974 increment_stats(STAT_FIND_PEER_REPLY);
1975 if (GNUNET_YES == consider_peer(&new_peer))
1977 increment_stats(STAT_HELLOS_PROVIDED);
1978 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1979 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1984 if (malicious_dropper == GNUNET_YES)
1987 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1989 if (record == NULL) /* No record of this message! */
1992 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1993 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1994 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
1996 #if DEBUG_DHT_ROUTING
1997 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1999 dhtlog_handle->insert_route (NULL,
2000 message_context->unique_id,
2002 message_context->hop_count,
2005 &message_context->key,
2006 message_context->peer, NULL);
2009 if (message_context->bloom != NULL)
2011 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2012 message_context->bloom = NULL;
2020 #if STRICT_FORWARDING
2021 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2023 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2025 increment_stats("# find peer responses NOT forwarded (bloom match)");
2030 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2034 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2037 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2038 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2039 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2041 #if DEBUG_DHT_ROUTING
2042 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2044 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2045 message_context->hop_count,
2046 GNUNET_YES, &my_identity, &message_context->key,
2047 message_context->peer, NULL);
2050 increment_stats(STAT_RESULTS_TO_CLIENT);
2051 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2052 increment_stats(STAT_GET_REPLY);
2054 send_reply_to_client(pos->client, msg,
2055 message_context->unique_id,
2056 &message_context->key);
2058 else /* Send to peer */
2060 peer_info = find_peer_by_id(&pos->source);
2061 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2067 if (message_context->bloom == NULL)
2068 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2069 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2070 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2074 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2075 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2077 #if DEBUG_DHT_ROUTING
2078 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2080 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2082 message_context->hop_count,
2083 GNUNET_NO, &my_identity, &message_context->key,
2084 message_context->peer, &pos->source);
2087 forward_result_message(cls, msg, peer_info, message_context);
2092 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2093 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2094 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2100 if (message_context->bloom != NULL)
2101 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2106 * Iterator for local get request results,
2108 * @param cls closure for iterator, a DatacacheGetContext
2109 * @param exp when does this value expire?
2110 * @param key the key this data is stored under
2111 * @param size the size of the data identified by key
2112 * @param data the actual data
2113 * @param type the type of the data
2115 * @return GNUNET_OK to continue iteration, anything else
2116 * to stop iteration.
2119 datacache_get_iterator (void *cls,
2120 struct GNUNET_TIME_Absolute exp,
2121 const GNUNET_HashCode * key,
2122 uint32_t size, const char *data, uint32_t type)
2124 struct DHT_MessageContext *msg_ctx = cls;
2125 struct DHT_MessageContext *new_msg_ctx;
2126 struct GNUNET_DHT_GetResultMessage *get_result;
2128 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2129 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2131 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2132 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2134 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2135 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2136 get_result->header.size =
2137 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2138 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2139 get_result->type = htons (type);
2140 memcpy (&get_result[1], data, size);
2141 new_msg_ctx->peer = &my_identity;
2142 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2143 new_msg_ctx->hop_count = 0;
2144 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2145 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2146 increment_stats(STAT_GET_RESPONSE_START);
2147 route_result_message(cls, &get_result->header, new_msg_ctx);
2148 GNUNET_free(new_msg_ctx);
2149 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2150 // datacache_get_ctx->unique_id);
2151 GNUNET_free (get_result);
2157 * Main function that handles whether or not to route a message to other
2160 * @param msg the message to be routed
2161 * @param message_context the context containing all pertinent information about the message
2164 route_message2(const struct GNUNET_MessageHeader *msg,
2165 struct DHT_MessageContext *message_context);
2169 * Server handler for all dht get requests, look for data,
2170 * if found, send response either to clients or other peers.
2172 * @param cls closure for service
2173 * @param msg the actual get message
2174 * @param message_context struct containing pertinent information about the get request
2176 * @return number of items found for GET request
2179 handle_dht_get (void *cls,
2180 const struct GNUNET_MessageHeader *msg,
2181 struct DHT_MessageContext *message_context)
2183 const struct GNUNET_DHT_GetMessage *get_msg;
2187 uint16_t xquery_size;
2188 unsigned int results;
2189 struct GNUNET_CONTAINER_BloomFilter *bf;
2193 msize = ntohs (msg->size);
2194 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2199 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2200 bf_size = ntohs (get_msg->bf_size);
2201 xquery_size = ntohs (get_msg->xquery_size);
2202 if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + xquery_size)
2207 end = (const char*) &get_msg[1];
2208 if (xquery_size == 0)
2214 xquery = (const void*) end;
2223 bf = GNUNET_CONTAINER_bloomfilter_init (end,
2225 GNUNET_DHT_GET_BLOOMFILTER_K);
2228 get_type = ntohs (get_msg->type);
2230 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2231 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2235 GNUNET_h2s (&message_context->key),
2236 message_context->unique_id);
2238 increment_stats(STAT_GETS);
2241 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2243 GNUNET_CONTAINER_bloomfilter_free (bf);
2247 /* FIXME: put xquery / bf into message_context and use
2248 them for processing! */
2249 if (datacache != NULL)
2251 = GNUNET_DATACACHE_get (datacache,
2252 &message_context->key, get_type,
2253 &datacache_get_iterator,
2259 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2260 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2261 results, "GET", message_context->unique_id);
2263 #if DEBUG_DHT_ROUTING
2264 if ((debug_routes) && (dhtlog_handle != NULL))
2266 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2267 message_context->hop_count, GNUNET_YES, &my_identity,
2268 &message_context->key);
2271 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2273 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2274 message_context->hop_count, GNUNET_YES,
2275 &my_identity, &message_context->key, message_context->peer,
2281 if (message_context->hop_count == 0) /* Locally initiated request */
2283 #if DEBUG_DHT_ROUTING
2284 if ((debug_routes) && (dhtlog_handle != NULL))
2286 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2287 message_context->hop_count, GNUNET_NO, &my_identity,
2288 &message_context->key);
2292 route_message2 (msg, message_context);
2293 GNUNET_CONTAINER_bloomfilter_free (bf);
2298 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2300 GNUNET_HashCode *key = cls;
2302 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key));
2307 * Server handler for initiating local dht find peer requests
2309 * @param cls closure for service
2310 * @param find_msg the actual find peer message
2311 * @param message_context struct containing pertinent information about the request
2315 handle_dht_find_peer (void *cls,
2316 const struct GNUNET_MessageHeader *find_msg,
2317 struct DHT_MessageContext *message_context)
2319 struct GNUNET_MessageHeader *find_peer_result;
2320 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2321 struct DHT_MessageContext *new_msg_ctx;
2322 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2325 GNUNET_HashCode *recent_hash;
2326 struct GNUNET_MessageHeader *other_hello;
2327 size_t other_hello_size;
2328 struct GNUNET_PeerIdentity peer_id;
2330 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2331 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2332 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2335 other_hello_size = 0;
2336 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2338 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2339 other_hello = GNUNET_malloc(other_hello_size);
2340 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2341 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)))
2343 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2344 GNUNET_free(other_hello);
2347 #if FIND_PEER_WITH_HELLO
2348 if (GNUNET_YES == consider_peer(&peer_id))
2350 increment_stats(STAT_HELLOS_PROVIDED);
2351 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2352 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2353 route_message2 (find_msg, message_context);
2356 else /* We don't want this peer! */
2358 route_message2 (find_msg, message_context);
2365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2366 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2367 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&message_context->key),
2368 ntohs (find_msg->size),
2369 sizeof (struct GNUNET_MessageHeader));
2371 if (my_hello == NULL)
2374 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2375 "`%s': Our HELLO is null, can't return.\n",
2378 GNUNET_free_non_null (other_hello);
2379 route_message2 (find_msg, message_context);
2383 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2384 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2386 increment_stats(STAT_BLOOM_FIND_PEER);
2387 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2388 GNUNET_free_non_null(other_hello);
2389 route_message2 (find_msg, message_context);
2390 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2392 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2394 #if RESTRICT_FIND_PEER
2397 * Ignore any find peer requests from a peer we have seen very recently.
2399 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! */
2401 increment_stats("# dht find peer requests ignored (recently seen!)");
2402 GNUNET_free_non_null(other_hello);
2407 * Use this check to only allow the peer to respond to find peer requests if
2408 * it would be beneficial to have the requesting peer in this peers routing
2409 * table. Can be used to thwart peers flooding the network with find peer
2410 * requests that we don't care about. However, if a new peer is joining
2411 * the network and has no other peers this is a problem (assume all buckets
2412 * full, no one will respond!).
2414 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2415 if (GNUNET_NO == consider_peer(&peer_id))
2417 increment_stats("# dht find peer requests ignored (do not need!)");
2418 GNUNET_free_non_null(other_hello);
2419 route_message2 (find_msg, message_context);
2424 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2425 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2426 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2427 &message_context->key, NULL,
2428 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2429 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30),
2430 &remove_recent_find_peer, recent_hash);
2432 /* Simplistic find_peer functionality, always return our hello */
2433 hello_size = ntohs(my_hello->size);
2434 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2436 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2438 GNUNET_break_op (0);
2439 GNUNET_free_non_null(other_hello);
2443 find_peer_result = GNUNET_malloc (tsize);
2444 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2445 find_peer_result->size = htons (tsize);
2446 memcpy (&find_peer_result[1], my_hello, hello_size);
2448 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2449 "`%s': Sending hello size %d to requesting peer.\n",
2452 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2453 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2454 new_msg_ctx->peer = &my_identity;
2455 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2456 new_msg_ctx->hop_count = 0;
2457 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2458 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2459 increment_stats(STAT_FIND_PEER_ANSWER);
2460 route_result_message(cls, find_peer_result, new_msg_ctx);
2461 GNUNET_free(new_msg_ctx);
2462 #if DEBUG_DHT_ROUTING
2463 if ((debug_routes) && (dhtlog_handle != NULL))
2465 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2466 message_context->hop_count, GNUNET_YES, &my_identity,
2467 &message_context->key);
2470 GNUNET_free_non_null(other_hello);
2471 GNUNET_free(find_peer_result);
2472 route_message2 (find_msg, message_context);
2476 * Task used to republish data.
2477 * Forward declaration; function call loop.
2479 * @param cls closure (a struct RepublishContext)
2480 * @param tc runtime context for this task
2483 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2486 * Server handler for initiating local dht put requests
2488 * @param cls closure for service
2489 * @param msg the actual put message
2490 * @param message_context struct containing pertinent information about the request
2493 handle_dht_put (void *cls,
2494 const struct GNUNET_MessageHeader *msg,
2495 struct DHT_MessageContext *message_context)
2497 struct GNUNET_DHT_PutMessage *put_msg;
2501 struct RepublishContext *put_context;
2503 GNUNET_assert (ntohs (msg->size) >=
2504 sizeof (struct GNUNET_DHT_PutMessage));
2507 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2508 put_type = ntohs (put_msg->type);
2510 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2513 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2515 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2516 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2517 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
2519 #if DEBUG_DHT_ROUTING
2520 if (message_context->hop_count == 0) /* Locally initiated request */
2522 if ((debug_routes) && (dhtlog_handle != NULL))
2524 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2525 message_context->hop_count, GNUNET_NO, &my_identity,
2526 &message_context->key);
2531 if (message_context->closest != GNUNET_YES)
2534 #if DEBUG_DHT_ROUTING
2535 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2537 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2538 message_context->hop_count, GNUNET_YES,
2539 &my_identity, &message_context->key, message_context->peer,
2543 if ((debug_routes) && (dhtlog_handle != NULL))
2545 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2546 message_context->hop_count, GNUNET_YES, &my_identity,
2547 &message_context->key);
2551 increment_stats(STAT_PUTS_INSERTED);
2552 if (datacache != NULL)
2554 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2555 (char *) &put_msg[1], put_type,
2556 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2558 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2560 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2561 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2562 put_context->type = put_type;
2563 GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
2567 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2568 "`%s:%s': %s request received, but have no datacache!\n",
2569 my_short_id, "DHT", "PUT");
2570 route_message2 (msg, message_context);
2574 * Estimate the diameter of the network based
2575 * on how many buckets are currently in use.
2576 * Concept here is that the diameter of the network
2577 * is roughly the distance a message must travel in
2578 * order to reach its intended destination. Since
2579 * at each hop we expect to get one bit closer, and
2580 * we have one bit per bucket, the number of buckets
2581 * in use should be the largest number of hops for
2582 * a sucessful message. (of course, this assumes we
2583 * know all peers in the network!)
2585 * @return ballpark diameter figure
2587 static unsigned int estimate_diameter()
2589 return MAX_BUCKETS - lowest_bucket;
2593 * To how many peers should we (on average)
2594 * forward the request to obtain the desired
2595 * target_replication count (on average).
2597 * Always 0, 1 or 2 (don't send, send once, split)
2600 get_forward_count (unsigned int hop_count, size_t target_replication)
2603 double target_count;
2604 double random_probability;
2606 uint32_t random_value;
2608 unsigned int target_value;
2609 unsigned int diameter;
2612 * If we are behaving in strict kademlia mode, send multiple initial requests,
2613 * but then only send to 1 or 0 peers based strictly on the number of hops.
2615 if (strict_kademlia == GNUNET_YES)
2618 return DHT_KADEMLIA_REPLICATION;
2619 else if (hop_count < max_hops)
2625 /* FIXME: the smaller we think the network is the more lenient we should be for
2626 * routing right? The estimation below only works if we think we have reasonably
2627 * full routing tables, which for our RR topologies may not be the case!
2629 diameter = estimate_diameter ();
2630 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2633 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2634 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2635 "DHT", estimate_diameter(), lowest_bucket);
2639 else if (hop_count > max_hops)
2642 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2643 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2650 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2651 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2652 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2653 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2654 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2655 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2656 RAND_MAX)) / RAND_MAX;
2657 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2660 //while (target_value < target_count)
2661 if (target_value < target_count)
2662 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? */
2665 //if ((target_count + 1 - (double)target_value) > random_probability)
2666 if ((target_count) > random_probability)
2670 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2671 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));
2673 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2674 if (random_value < target_replication)
2677 return target_value;
2681 * Check whether my identity is closer than any known peers.
2682 * If a non-null bloomfilter is given, check if this is the closest
2683 * peer that hasn't already been routed to.
2685 * @param target hash code to check closeness to
2686 * @param bloom bloomfilter, exclude these entries from the decision
2688 * Return GNUNET_YES if node location is closest, GNUNET_NO
2692 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2698 struct PeerInfo *pos;
2699 unsigned int my_distance;
2701 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2704 bucket_num = find_current_bucket(target);
2706 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2707 my_distance = distance(&my_identity.hashPubKey, target);
2708 pos = k_buckets[bucket_num].head;
2710 while ((pos != NULL) && (count < bucket_size))
2712 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2715 continue; /* Skip already checked entries */
2718 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2719 if (other_bits > bits)
2721 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2723 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2725 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2732 GNUNET_GE_LOG (coreAPI->ectx,
2733 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2734 GNUNET_GE_BULK, "closest peer\n");
2735 printPeerBits (&closest);
2736 GNUNET_GE_LOG (coreAPI->ectx,
2737 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2738 GNUNET_GE_BULK, "me\n");
2739 printPeerBits (coreAPI->my_identity);
2740 GNUNET_GE_LOG (coreAPI->ectx,
2741 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2742 GNUNET_GE_BULK, "key\n");
2743 printKeyBits (target);
2744 GNUNET_GE_LOG (coreAPI->ectx,
2745 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2747 "closest peer inverse distance is %u, mine is %u\n",
2748 inverse_distance (target, &closest.hashPubKey),
2749 inverse_distance (target,
2750 &coreAPI->my_identity->hashPubKey));
2753 /* No peers closer, we are the closest! */
2759 * Return this peers adjusted value based on the convergence
2760 * function chosen. This is the key function for randomized
2761 * routing decisions.
2763 * @param target the key of the request
2764 * @param peer the peer we would like the value of
2765 * @param hops number of hops this message has already traveled
2767 * @return bit distance from target to peer raised to an exponent
2768 * adjusted based on the current routing convergence algorithm
2772 converge_distance (const GNUNET_HashCode *target,
2773 struct PeerInfo *peer,
2776 unsigned long long ret;
2777 unsigned int other_matching_bits;
2778 double converge_modifier = 0.0;
2779 double base_converge_modifier = .1;
2785 curr_max_hops = max_hops;
2787 curr_max_hops = (estimate_diameter() + 1) * 2;
2789 if (converge_modifier > 0)
2790 converge_modifier = converge_modifier * base_converge_modifier;
2793 converge_modifier = base_converge_modifier;
2794 base_converge_modifier = 0.0;
2797 GNUNET_assert(converge_modifier > 0);
2799 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2801 switch (converge_option)
2803 case DHT_CONVERGE_RANDOM:
2804 return 1; /* Always return 1, choose equally among all peers */
2805 case DHT_CONVERGE_LINEAR:
2806 calc_value = hops * curr_max_hops * converge_modifier;
2808 case DHT_CONVERGE_SQUARE:
2810 * Simple square based curve.
2812 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * converge_modifier));
2814 case DHT_CONVERGE_EXPONENTIAL:
2816 * Simple exponential curve.
2818 if (base_converge_modifier > 0)
2819 calc_value = (converge_modifier * hops * hops) / curr_max_hops;
2821 calc_value = (hops * hops) / curr_max_hops;
2827 /* Take the log (base e) of the number of bits matching the other peer */
2828 exponent = log(other_matching_bits);
2830 /* Check if we would overflow; our largest possible value is 2^64 = e^44.361419555836498 */
2831 if (exponent * calc_value >= 44.361419555836498)
2834 /* Clear errno and all math exceptions */
2836 feclearexcept(FE_ALL_EXCEPT);
2837 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2838 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2841 if (0 != fetestexcept(FE_OVERFLOW))
2842 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2843 if (0 != fetestexcept(FE_INVALID))
2844 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2845 if (0 != fetestexcept(FE_UNDERFLOW))
2846 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2854 * Comparison function for two struct PeerInfo's
2855 * which have already had their matching bits to
2856 * some target calculated.
2858 * @param p1 a pointer pointer to a struct PeerInfo
2859 * @param p2 a pointer pointer to a struct PeerInfo
2861 * @return 0 if equidistant to target,
2862 * -1 if p1 is closer,
2866 compare_peers (const void *p1, const void *p2)
2868 struct PeerInfo **first = (struct PeerInfo **)p1;
2869 struct PeerInfo **second = (struct PeerInfo **)p2;
2871 if ((*first)->matching_bits > (*second)->matching_bits)
2873 if ((*first)->matching_bits < (*second)->matching_bits)
2881 * Select a peer from the routing table that would be a good routing
2882 * destination for sending a message for "target". The resulting peer
2883 * must not be in the set of blocked peers.<p>
2885 * Note that we should not ALWAYS select the closest peer to the
2886 * target, peers further away from the target should be chosen with
2887 * exponentially declining probability.
2889 * @param target the key we are selecting a peer to route to
2890 * @param bloom a bloomfilter containing entries this request has seen already
2892 * @return Peer to route to, or NULL on error
2894 static struct PeerInfo *
2895 select_peer (const GNUNET_HashCode * target,
2896 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2901 unsigned int offset;
2902 unsigned int my_matching_bits;
2904 struct PeerInfo *pos;
2905 struct PeerInfo *sorted_closest[bucket_size];
2906 unsigned long long temp_converge_distance;
2907 unsigned long long total_distance;
2908 unsigned long long selected;
2910 unsigned long long stats_total_distance;
2914 unsigned int distance;
2915 unsigned int largest_distance;
2916 struct PeerInfo *chosen;
2918 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
2921 if (strict_kademlia == GNUNET_YES)
2923 largest_distance = 0;
2925 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2927 pos = k_buckets[bc].head;
2929 while ((pos != NULL) && (count < bucket_size))
2931 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2932 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2934 distance = inverse_distance (target, &pos->id.hashPubKey);
2935 if (distance > largest_distance)
2938 largest_distance = distance;
2946 if ((largest_distance > 0) && (chosen != NULL))
2948 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2959 /* Three steps: order peers in closest bucket (most matching bits).
2960 * Then go over all LOWER buckets (matching same bits we do)
2961 * Then go over all HIGHER buckets (matching less then we do)
2964 closest_bucket = find_current_bucket(target);
2965 GNUNET_assert(closest_bucket >= lowest_bucket);
2966 pos = k_buckets[closest_bucket].head;
2968 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
2969 memset(sorted_closest, 0, sizeof(sorted_closest));
2970 /* Put any peers in the closest bucket in the sorting array */
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 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2980 sorted_closest[offset] = pos;
2986 /* Sort the peers in descending order */
2987 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
2989 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
2990 for (i = 0; i < offset; i++)
2992 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
2993 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
2994 break; /* Ignore bloomfiltered peers */
2995 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
2996 total_distance += temp_converge_distance;
2998 break; /* overflow case */
3001 /* Now handle peers in lower buckets (matches same # of bits as target) */
3002 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3004 pos = k_buckets[bc].head;
3006 while ((pos != NULL) && (count < bucket_size))
3008 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3012 continue; /* Ignore bloomfiltered peers */
3014 temp_converge_distance = converge_distance(target, pos, hops);
3015 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3016 total_distance += temp_converge_distance;
3018 break; /* overflow case */
3024 /* Now handle all the further away peers */
3025 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3027 pos = k_buckets[bc].head;
3029 while ((pos != NULL) && (count < bucket_size))
3031 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3035 continue; /* Ignore bloomfiltered peers */
3037 temp_converge_distance = converge_distance(target, pos, hops);
3038 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3039 total_distance += temp_converge_distance;
3041 break; /* overflow case */
3047 if (total_distance == 0) /* No peers to select from! */
3049 increment_stats("# select_peer, total_distance == 0");
3053 #if DEBUG_DHT_ROUTING > 1
3056 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3057 stats_total_distance = 0;
3058 for (i = 0; i < offset; i++)
3060 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3061 break; /* Ignore bloomfiltered peers */
3062 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3063 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3064 stats_total_distance += temp_converge_distance;
3066 break; /* overflow case */
3067 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);
3070 /* Now handle peers in lower buckets (matches same # of bits as target) */
3071 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3073 pos = k_buckets[bc].head;
3075 while ((pos != NULL) && (count < bucket_size))
3077 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3081 continue; /* Ignore bloomfiltered peers */
3083 temp_converge_distance = converge_distance(target, pos, hops);
3084 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3085 stats_total_distance += temp_converge_distance;
3087 break; /* overflow case */
3088 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);
3094 /* Now handle all the further away peers */
3095 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3097 pos = k_buckets[bc].head;
3099 while ((pos != NULL) && (count < bucket_size))
3101 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3105 continue; /* Ignore bloomfiltered peers */
3107 temp_converge_distance = converge_distance(target, pos, hops);
3108 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3109 stats_total_distance += temp_converge_distance;
3111 break; /* overflow case */
3112 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);
3117 /* END PRINT STATS */
3120 /* Now actually choose a peer */
3121 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3123 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3124 for (i = 0; i < offset; i++)
3126 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3127 break; /* Ignore bloomfiltered peers */
3128 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3129 if (temp_converge_distance >= selected)
3130 return sorted_closest[i];
3132 selected -= temp_converge_distance;
3135 /* Now handle peers in lower buckets (matches same # of bits as target) */
3136 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3138 pos = k_buckets[bc].head;
3140 while ((pos != NULL) && (count < bucket_size))
3142 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3146 continue; /* Ignore bloomfiltered peers */
3148 temp_converge_distance = converge_distance(target, pos, hops);
3149 if (temp_converge_distance >= selected)
3152 selected -= temp_converge_distance;
3158 /* Now handle all the further away peers */
3159 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3161 pos = k_buckets[bc].head;
3163 while ((pos != NULL) && (count < bucket_size))
3165 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3169 continue; /* Ignore bloomfiltered peers */
3171 temp_converge_distance = converge_distance(target, pos, hops);
3172 if (temp_converge_distance >= selected)
3175 selected -= temp_converge_distance;
3181 increment_stats("# failed to select peer");
3187 * Task used to remove recent entries, either
3188 * after timeout, when full, or on shutdown.
3190 * @param cls the entry to remove
3191 * @param tc context, reason, etc.
3194 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3196 struct RecentRequest *req = cls;
3197 static GNUNET_HashCode hash;
3199 GNUNET_assert(req != NULL);
3200 hash_from_uid(req->uid, &hash);
3201 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3202 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3203 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3206 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3208 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3209 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3215 * Task used to remove forwarding entries, either
3216 * after timeout, when full, or on shutdown.
3218 * @param cls the entry to remove
3219 * @param tc context, reason, etc.
3222 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3224 struct DHTRouteSource *source_info = cls;
3225 struct DHTQueryRecord *record;
3226 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3227 record = source_info->record;
3228 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 if (source_info->find_peers_responded != NULL)
3236 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3237 GNUNET_free(source_info);
3241 * Remember this routing request so that if a reply is
3242 * received we can either forward it to the correct peer
3243 * or return the result locally.
3245 * @param cls DHT service closure
3246 * @param msg_ctx Context of the route request
3248 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3250 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
3252 struct DHTQueryRecord *record;
3253 struct DHTRouteSource *source_info;
3254 struct DHTRouteSource *pos;
3255 struct GNUNET_TIME_Absolute now;
3256 unsigned int current_size;
3258 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3259 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3261 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3262 GNUNET_assert(source_info != NULL);
3263 record = source_info->record;
3264 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3265 if (record->head == NULL) /* No more entries in DLL */
3267 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3268 GNUNET_free(record);
3270 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
3271 if (source_info->find_peers_responded != NULL)
3272 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3273 GNUNET_free(source_info);
3274 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3276 now = GNUNET_TIME_absolute_get();
3277 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3278 if (record != NULL) /* Already know this request! */
3283 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3284 break; /* Already have this peer in reply list! */
3287 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3289 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3295 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3296 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3297 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3300 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3301 source_info->record = record;
3302 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3303 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3304 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3305 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3306 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3308 source_info->client = msg_ctx->client;
3309 now = GNUNET_TIME_absolute_get_forever();
3311 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3313 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3314 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3315 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3322 * Main function that handles whether or not to route a message to other
3325 * @param msg the message to be routed
3326 * @param message_context the context containing all pertinent information about the message
3329 route_message2(const struct GNUNET_MessageHeader *msg,
3330 struct DHT_MessageContext *message_context)
3333 struct PeerInfo *selected;
3334 #if DEBUG_DHT_ROUTING > 1
3335 struct PeerInfo *nearest;
3337 unsigned int forward_count;
3338 struct RecentRequest *recent_req;
3339 GNUNET_HashCode unique_hash;
3340 char *stat_forward_count;
3341 char *temp_stat_str;
3342 #if DEBUG_DHT_ROUTING
3346 if (malicious_dropper == GNUNET_YES)
3348 #if DEBUG_DHT_ROUTING
3349 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3351 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3352 message_context->hop_count, GNUNET_SYSERR,
3353 &my_identity, &message_context->key, message_context->peer,
3357 if (message_context->bloom != NULL)
3358 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3362 increment_stats(STAT_ROUTES);
3363 /* Semantics of this call means we find whether we are the closest peer out of those already
3364 * routed to on this messages path.
3366 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3367 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3368 increment_stats(stat_forward_count);
3369 GNUNET_free(stat_forward_count);
3370 if (message_context->bloom == NULL)
3371 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3373 if ((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3377 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3378 * any closer peers (which is being checked for below). Since we are doing recursive
3379 * routing we have no choice but to stop forwarding in this case. This means that at
3380 * any given step the request may NOT be forwarded to alpha peers (because routes will
3381 * stop and the parallel route will not be aware of it). Of course, assuming that we
3382 * have fulfilled the Kademlia requirements for routing table fullness this will never
3383 * ever ever be a problem.
3385 * However, is this fair?
3387 * Since we use these requests to build our routing tables (and we build them in the
3388 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3389 * routing tables still get constructed.
3391 if ((GNUNET_YES == strict_kademlia) && (message_context->closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3394 #if DEBUG_DHT_ROUTING
3395 if (forward_count == 0)
3396 ret = GNUNET_SYSERR;
3400 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3402 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3403 message_context->hop_count, ret,
3404 &my_identity, &message_context->key, message_context->peer,
3410 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3411 hash_from_uid (message_context->unique_id, &unique_hash);
3412 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3414 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3415 GNUNET_assert(recent_req != NULL);
3416 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3417 increment_stats(STAT_DUPLICATE_UID);
3420 increment_stats(STAT_RECENT_SEEN);
3421 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3426 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3427 recent_req->uid = message_context->unique_id;
3428 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3429 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3430 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3431 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3432 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3435 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3437 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3438 GNUNET_assert(recent_req != NULL);
3439 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3440 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3443 for (i = 0; i < forward_count; i++)
3445 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3447 if (selected != NULL)
3449 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
3450 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
3452 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
3453 if (temp_stat_str != NULL)
3455 increment_stats(temp_stat_str);
3456 GNUNET_free(temp_stat_str);
3458 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3459 #if DEBUG_DHT_ROUTING > 1
3460 nearest = find_closest_peer(&message_context->key);
3461 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3462 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3463 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3464 "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));
3465 GNUNET_free(nearest_buf);
3467 #if DEBUG_DHT_ROUTING
3468 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3470 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3471 message_context->hop_count, GNUNET_NO,
3472 &my_identity, &message_context->key, message_context->peer,
3476 forward_message(msg, selected, message_context);
3480 if (message_context->bloom != NULL)
3482 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3483 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3490 * Main function that handles whether or not to route a message to other
3493 * @param cls closure for dht service (NULL)
3494 * @param msg the message to be routed
3495 * @param message_context the context containing all pertinent information about the message
3498 route_message(void *cls,
3499 const struct GNUNET_MessageHeader *msg,
3500 struct DHT_MessageContext *message_context)
3502 message_context->closest = am_closest_peer(&message_context->key, NULL);
3503 switch (ntohs(msg->type))
3505 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3506 cache_response (cls, message_context);
3507 handle_dht_get (cls, msg, message_context);
3509 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3510 increment_stats(STAT_PUTS);
3511 handle_dht_put (cls, msg, message_context);
3513 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3514 increment_stats(STAT_FIND_PEER);
3515 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3517 cache_response (cls, message_context);
3518 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3519 handle_dht_find_peer (cls, msg, message_context);
3521 #if DEBUG_DHT_ROUTING
3522 if (message_context->hop_count == 0) /* Locally initiated request */
3524 if ((debug_routes) && (dhtlog_handle != NULL))
3526 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3527 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3528 message_context->hop_count, GNUNET_NO, &my_identity,
3529 &message_context->key);
3535 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3536 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3537 route_message (cls, msg, message_context);
3545 * Iterator for local get request results,
3547 * @param cls closure for iterator, NULL
3548 * @param exp when does this value expire?
3549 * @param key the key this data is stored under
3550 * @param size the size of the data identified by key
3551 * @param data the actual data
3552 * @param type the type of the data
3554 * @return GNUNET_OK to continue iteration, anything else
3555 * to stop iteration.
3558 republish_content_iterator (void *cls,
3559 struct GNUNET_TIME_Absolute exp,
3560 const GNUNET_HashCode * key,
3561 uint32_t size, const char *data, uint32_t type)
3564 struct DHT_MessageContext *new_msg_ctx;
3565 struct GNUNET_DHT_PutMessage *put_msg;
3567 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3568 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3570 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3573 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3574 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3575 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3576 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3577 put_msg->type = htons (type);
3578 memcpy (&put_msg[1], data, size);
3579 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3580 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3581 new_msg_ctx->msg_options = ntohl (0);
3582 new_msg_ctx->network_size = estimate_diameter();
3583 new_msg_ctx->peer = &my_identity;
3584 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3585 new_msg_ctx->hop_count = 0;
3586 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3587 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3588 increment_stats(STAT_PUT_START);
3589 route_message(cls, &put_msg->header, new_msg_ctx);
3591 GNUNET_free(new_msg_ctx);
3592 GNUNET_free (put_msg);
3597 * Task used to republish data.
3599 * @param cls closure (a struct RepublishContext)
3600 * @param tc runtime context for this task
3603 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3605 struct RepublishContext *put_context = cls;
3607 unsigned int results;
3609 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3611 GNUNET_free(put_context);
3615 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3616 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3617 if (results == 0) /* Data must have expired */
3618 GNUNET_free(put_context);
3619 else /* Reschedule task for next time period */
3620 GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);
3626 * Iterator over hash map entries.
3628 * @param cls client to search for in source routes
3629 * @param key current key code (ignored)
3630 * @param value value in the hash map, a DHTQueryRecord
3631 * @return GNUNET_YES if we should continue to
3635 static int find_client_records (void *cls,
3636 const GNUNET_HashCode * key, void *value)
3638 struct ClientList *client = cls;
3639 struct DHTQueryRecord *record = value;
3640 struct DHTRouteSource *pos;
3644 if (pos->client == client)
3650 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3651 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3652 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3653 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3655 if (pos->find_peers_responded != NULL)
3656 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3659 if (record->head == NULL) /* No more entries in DLL */
3661 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3662 GNUNET_free(record);
3668 * Functions with this signature are called whenever a client
3669 * is disconnected on the network level.
3671 * @param cls closure (NULL for dht)
3672 * @param client identification of the client; NULL
3673 * for the last call when the server is destroyed
3675 static void handle_client_disconnect (void *cls,
3676 struct GNUNET_SERVER_Client* client)
3678 struct ClientList *pos = client_list;
3679 struct ClientList *prev;
3680 struct ClientList *found;
3681 struct PendingMessage *reply;
3687 if (pos->client_handle == client)
3690 prev->next = pos->next;
3692 client_list = pos->next;
3702 while(NULL != (reply = found->pending_head))
3704 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3707 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3713 * Find a client if it exists, add it otherwise.
3715 * @param client the server handle to the client
3717 * @return the client if found, a new client otherwise
3719 static struct ClientList *
3720 find_active_client (struct GNUNET_SERVER_Client *client)
3722 struct ClientList *pos = client_list;
3723 struct ClientList *ret;
3727 if (pos->client_handle == client)
3732 ret = GNUNET_malloc (sizeof (struct ClientList));
3733 ret->client_handle = client;
3734 ret->next = client_list;
3741 * Task to send a malicious put message across the network.
3743 * @param cls closure for this task
3744 * @param tc the context under which the task is running
3747 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3749 static struct GNUNET_DHT_PutMessage put_message;
3750 static struct DHT_MessageContext message_context;
3751 static GNUNET_HashCode key;
3752 uint32_t random_key;
3754 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3757 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3758 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3759 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3760 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3761 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3762 message_context.client = NULL;
3763 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3764 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3765 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3766 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3767 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3768 message_context.msg_options = ntohl (0);
3769 message_context.network_size = estimate_diameter();
3770 message_context.peer = &my_identity;
3771 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3772 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3773 #if DEBUG_DHT_ROUTING
3774 if (dhtlog_handle != NULL)
3775 dhtlog_handle->insert_dhtkey(NULL, &key);
3777 increment_stats(STAT_PUT_START);
3778 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3779 route_message(NULL, &put_message.header, &message_context);
3780 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3785 * Task to send a malicious put message across the network.
3787 * @param cls closure for this task
3788 * @param tc the context under which the task is running
3791 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3793 static struct GNUNET_DHT_GetMessage get_message;
3794 struct DHT_MessageContext message_context;
3795 static GNUNET_HashCode key;
3796 uint32_t random_key;
3798 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3801 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3802 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3803 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3804 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3805 message_context.client = NULL;
3806 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3807 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3808 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3809 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3810 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3811 message_context.msg_options = ntohl (0);
3812 message_context.network_size = estimate_diameter();
3813 message_context.peer = &my_identity;
3814 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3815 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3816 #if DEBUG_DHT_ROUTING
3817 if (dhtlog_handle != NULL)
3818 dhtlog_handle->insert_dhtkey(NULL, &key);
3820 increment_stats(STAT_GET_START);
3821 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3822 route_message (NULL, &get_message.header, &message_context);
3823 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3827 * Iterator over hash map entries.
3829 * @param cls closure
3830 * @param key current key code
3831 * @param value value in the hash map
3832 * @return GNUNET_YES if we should continue to
3837 add_known_to_bloom (void *cls,
3838 const GNUNET_HashCode * key,
3841 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3842 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3847 * Task to send a find peer message for our own peer identifier
3848 * so that we can find the closest peers in the network to ourselves
3849 * and attempt to connect to them.
3851 * @param cls closure for this task
3852 * @param tc the context under which the task is running
3855 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3857 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3858 struct DHT_MessageContext message_context;
3859 struct GNUNET_TIME_Relative next_send_time;
3860 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3862 struct GNUNET_TIME_Relative time_diff;
3863 struct GNUNET_TIME_Absolute end;
3865 double count_per_interval;
3867 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3870 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! */
3872 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3873 GNUNET_SCHEDULER_add_delayed (sched,
3874 GNUNET_TIME_UNIT_MINUTES,
3875 &send_find_peer_message, NULL);
3876 newly_found_peers = 0;
3880 increment_stats(STAT_FIND_PEER_START);
3882 end = GNUNET_TIME_absolute_get();
3883 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3885 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3887 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3888 count_per_interval = find_peer_context.count / multiplier;
3892 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3893 count_per_interval = find_peer_context.count * multiplier;
3897 #if FIND_PEER_WITH_HELLO
3898 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3899 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3900 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3902 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3903 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3905 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3906 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3907 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3908 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3909 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3910 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3911 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3912 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3913 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3914 message_context.network_size = estimate_diameter();
3915 message_context.peer = &my_identity;
3916 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3917 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3919 route_message(NULL, &find_peer_msg->header, &message_context);
3920 GNUNET_free(find_peer_msg);
3921 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3922 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
3924 if (newly_found_peers < bucket_size)
3926 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3927 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3928 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3932 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3933 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3934 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3937 GNUNET_assert (next_send_time.value != 0);
3938 find_peer_context.count = 0;
3939 newly_found_peers = 0;
3940 find_peer_context.start = GNUNET_TIME_absolute_get();
3941 if (GNUNET_YES == do_find_peer)
3943 GNUNET_SCHEDULER_add_delayed (sched,
3945 &send_find_peer_message, NULL);
3950 * Handler for any generic DHT messages, calls the appropriate handler
3951 * depending on message type, sends confirmation if responses aren't otherwise
3954 * @param cls closure for the service
3955 * @param client the client we received this message from
3956 * @param message the actual message received
3959 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3960 const struct GNUNET_MessageHeader *message)
3962 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3963 const struct GNUNET_MessageHeader *enc_msg;
3964 struct DHT_MessageContext message_context;
3966 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3969 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3973 ntohs (message->type),
3974 GNUNET_h2s (&dht_msg->key),
3975 GNUNET_ntohll (dht_msg->unique_id));
3977 #if DEBUG_DHT_ROUTING
3978 if (dhtlog_handle != NULL)
3979 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3981 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3982 message_context.client = find_active_client (client);
3983 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3984 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3985 message_context.replication = ntohl (dht_msg->desired_replication_level);
3986 message_context.msg_options = ntohl (dht_msg->options);
3987 message_context.network_size = estimate_diameter();
3988 message_context.peer = &my_identity;
3989 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3990 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3991 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3992 increment_stats(STAT_GET_START);
3993 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3994 increment_stats(STAT_PUT_START);
3995 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3996 increment_stats(STAT_FIND_PEER_START);
3998 route_message(cls, enc_msg, &message_context);
4000 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4005 * Handler for any locally received DHT control messages,
4006 * sets malicious flags mostly for now.
4008 * @param cls closure for the service
4009 * @param client the client we received this message from
4010 * @param message the actual message received
4014 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4015 const struct GNUNET_MessageHeader *message)
4017 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4018 (const struct GNUNET_DHT_ControlMessage *) message;
4020 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4021 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4022 "CONTROL", ntohs(dht_control_msg->command));
4025 switch (ntohs(dht_control_msg->command))
4027 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4028 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4029 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
4031 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4032 if (ntohs(dht_control_msg->variable) > 0)
4033 malicious_get_frequency = ntohs(dht_control_msg->variable);
4034 if (malicious_get_frequency == 0)
4035 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4036 if (malicious_getter != GNUNET_YES)
4037 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
4038 malicious_getter = GNUNET_YES;
4039 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4040 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4042 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4043 if (ntohs(dht_control_msg->variable) > 0)
4044 malicious_put_frequency = ntohs(dht_control_msg->variable);
4045 if (malicious_put_frequency == 0)
4046 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4047 if (malicious_putter != GNUNET_YES)
4048 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
4049 malicious_putter = GNUNET_YES;
4050 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4051 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4053 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4054 #if DEBUG_DHT_ROUTING
4055 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4056 dhtlog_handle->set_malicious(&my_identity);
4058 malicious_dropper = GNUNET_YES;
4059 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4060 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4063 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4064 "%s:%s Unknown control command type `%d'!\n",
4066 ntohs(dht_control_msg->command));
4070 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4074 * Handler for any generic DHT stop messages, calls the appropriate handler
4075 * depending on message type (if processed locally)
4077 * @param cls closure for the service
4078 * @param client the client we received this message from
4079 * @param message the actual message received
4083 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4084 const struct GNUNET_MessageHeader *message)
4087 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4088 (const struct GNUNET_DHT_StopMessage *) message;
4089 struct DHTQueryRecord *record;
4090 struct DHTRouteSource *pos;
4092 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4093 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4094 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4096 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
4103 if ((pos->client != NULL) && (pos->client->client_handle == client))
4105 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
4106 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
4112 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4117 * Core handler for p2p route requests.
4120 handle_dht_p2p_route_request (void *cls,
4121 const struct GNUNET_PeerIdentity *peer,
4122 const struct GNUNET_MessageHeader *message,
4123 struct GNUNET_TIME_Relative latency, uint32_t distance)
4126 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4127 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4129 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4130 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4131 struct DHT_MessageContext *message_context;
4133 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
4135 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
4136 increment_stats("# route requests dropped due to high load");
4137 decrease_max_send_delay(get_max_send_delay());
4141 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4144 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4149 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4154 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4155 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4156 GNUNET_assert(message_context->bloom != NULL);
4157 message_context->hop_count = ntohl(incoming->hop_count);
4158 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
4159 message_context->replication = ntohl(incoming->desired_replication_level);
4160 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
4161 message_context->msg_options = ntohl(incoming->options);
4162 message_context->network_size = ntohl(incoming->network_size);
4163 message_context->peer = peer;
4164 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4165 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4166 route_message(cls, enc_msg, message_context);
4167 GNUNET_free(message_context);
4173 * Core handler for p2p route results.
4176 handle_dht_p2p_route_result (void *cls,
4177 const struct GNUNET_PeerIdentity *peer,
4178 const struct GNUNET_MessageHeader *message,
4179 struct GNUNET_TIME_Relative latency, uint32_t distance)
4182 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4183 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4185 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4186 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4187 struct DHT_MessageContext message_context;
4189 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4195 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4196 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4197 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4198 GNUNET_assert(message_context.bloom != NULL);
4199 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
4200 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
4201 message_context.msg_options = ntohl(incoming->options);
4202 message_context.hop_count = ntohl(incoming->hop_count);
4203 message_context.peer = peer;
4204 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
4205 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4206 route_result_message(cls, enc_msg, &message_context);
4212 * Receive the HELLO from transport service,
4213 * free current and replace if necessary.
4216 * @param message HELLO message of peer
4219 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4222 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4223 "Received our `%s' from transport service\n",
4227 GNUNET_assert (message != NULL);
4228 GNUNET_free_non_null(my_hello);
4229 my_hello = GNUNET_malloc(ntohs(message->size));
4230 memcpy(my_hello, message, ntohs(message->size));
4235 * Task run during shutdown.
4241 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4244 struct PeerInfo *pos;
4246 if (transport_handle != NULL)
4248 GNUNET_free_non_null(my_hello);
4249 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4250 GNUNET_TRANSPORT_disconnect(transport_handle);
4252 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4254 while (k_buckets[bucket_count].head != NULL)
4256 pos = k_buckets[bucket_count].head;
4258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4259 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4261 delete_peer(pos, bucket_count);
4264 if (coreAPI != NULL)
4267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4268 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4270 GNUNET_CORE_disconnect (coreAPI);
4273 if (datacache != NULL)
4276 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4277 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4279 GNUNET_DATACACHE_destroy (datacache);
4284 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4287 if (dhtlog_handle != NULL)
4289 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4290 dhtlog_handle = NULL;
4292 if (block_context != NULL)
4294 GNUNET_BLOCK_context_destroy (block_context);
4295 block_context = NULL;
4297 GNUNET_free_non_null(my_short_id);
4303 * To be called on core init/fail.
4305 * @param cls service closure
4306 * @param server handle to the server for this service
4307 * @param identity the public identity of this peer
4308 * @param publicKey the public key of this peer
4311 core_init (void *cls,
4312 struct GNUNET_CORE_Handle *server,
4313 const struct GNUNET_PeerIdentity *identity,
4314 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4320 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4321 "%s: Connection to core FAILED!\n", "dht",
4322 GNUNET_i2s (identity));
4324 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
4325 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
4329 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4330 "%s: Core connection initialized, I am peer: %s\n", "dht",
4331 GNUNET_i2s (identity));
4334 /* Copy our identity so we can use it */
4335 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4336 if (my_short_id != NULL)
4337 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4338 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4339 /* Set the server to local variable */
4342 if (dhtlog_handle != NULL)
4343 dhtlog_handle->insert_node (NULL, &my_identity);
4347 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4348 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4349 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4350 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4355 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4356 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4357 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4363 * Method called whenever a peer connects.
4365 * @param cls closure
4366 * @param peer peer identity this notification is about
4367 * @param latency reported latency of the connection with peer
4368 * @param distance reported distance (DV) to peer
4370 void handle_core_connect (void *cls,
4371 const struct GNUNET_PeerIdentity * peer,
4372 struct GNUNET_TIME_Relative latency,
4375 struct PeerInfo *ret;
4378 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4379 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4382 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4384 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));
4388 if (datacache != NULL)
4389 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
4390 ret = try_add_peer(peer,
4391 find_current_bucket(&peer->hashPubKey),
4396 newly_found_peers++;
4397 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4400 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4401 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4407 * Method called whenever a peer disconnects.
4409 * @param cls closure
4410 * @param peer peer identity this notification is about
4412 void handle_core_disconnect (void *cls,
4414 GNUNET_PeerIdentity * peer)
4416 struct PeerInfo *to_remove;
4419 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");
4421 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4423 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));
4426 increment_stats(STAT_DISCONNECTS);
4427 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4428 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4429 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4430 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4431 delete_peer(to_remove, current_bucket);
4436 * Process dht requests.
4438 * @param cls closure
4439 * @param scheduler scheduler to use
4440 * @param server the initialized server
4441 * @param c configuration to use
4445 struct GNUNET_SCHEDULER_Handle *scheduler,
4446 struct GNUNET_SERVER_Handle *server,
4447 const struct GNUNET_CONFIGURATION_Handle *c)
4449 struct GNUNET_TIME_Relative next_send_time;
4450 unsigned long long temp_config_num;
4451 char *converge_modifier_buf;
4455 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4456 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4457 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4458 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4459 cfg, /* Main configuration */
4460 GNUNET_TIME_UNIT_FOREVER_REL,
4461 NULL, /* Closure passed to DHT functions */
4462 &core_init, /* Call core_init once connected */
4463 &handle_core_connect, /* Handle connects */
4464 &handle_core_disconnect, /* remove peers on disconnects */
4465 NULL, /* Do we care about "status" updates? */
4466 NULL, /* Don't want notified about all incoming messages */
4467 GNUNET_NO, /* For header only inbound notification */
4468 NULL, /* Don't want notified about all outbound messages */
4469 GNUNET_NO, /* For header only outbound notification */
4470 core_handlers); /* Register these handlers */
4472 if (coreAPI == NULL)
4474 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
4475 NULL, NULL, NULL, NULL, NULL);
4476 if (transport_handle != NULL)
4477 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4479 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4480 "Failed to connect to transport service!\n");
4481 block_context = GNUNET_BLOCK_context_create (cfg);
4482 lowest_bucket = MAX_BUCKETS - 1;
4483 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4484 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4485 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4486 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4487 GNUNET_assert(all_known_peers != NULL);
4488 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4490 debug_routes = GNUNET_YES;
4494 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4497 strict_kademlia = GNUNET_YES;
4501 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4504 stop_on_closest = GNUNET_YES;
4508 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4511 stop_on_found = GNUNET_YES;
4515 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4516 "malicious_getter"))
4518 malicious_getter = GNUNET_YES;
4519 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4520 "MALICIOUS_GET_FREQUENCY",
4521 &malicious_get_frequency))
4522 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4525 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4529 max_hops = DEFAULT_MAX_HOPS;
4532 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4535 use_max_hops = GNUNET_YES;
4539 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4540 "malicious_putter"))
4542 malicious_putter = GNUNET_YES;
4543 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4544 "MALICIOUS_PUT_FREQUENCY",
4545 &malicious_put_frequency))
4546 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4549 dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
4550 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4552 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4556 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4557 "malicious_dropper"))
4559 malicious_dropper = GNUNET_YES;
4563 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4565 do_republish = GNUNET_NO;
4568 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4571 do_find_peer = GNUNET_NO;
4574 do_find_peer = GNUNET_YES;
4577 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4578 "use_real_distance"))
4579 use_real_distance = GNUNET_YES;
4582 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4583 "mysql_logging_extended"))
4585 debug_routes = GNUNET_YES;
4586 debug_routes_extended = GNUNET_YES;
4589 #if DEBUG_DHT_ROUTING
4590 if (GNUNET_YES == debug_routes)
4592 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4593 if (dhtlog_handle == NULL)
4595 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4596 "Could not connect to mysql logging server, logging will not happen!");
4601 converge_option = DHT_CONVERGE_SQUARE;
4603 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4606 converge_option = DHT_CONVERGE_LINEAR;
4608 else if (GNUNET_YES ==
4609 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4610 "converge_exponential"))
4612 converge_option = DHT_CONVERGE_EXPONENTIAL;
4614 else if (GNUNET_YES ==
4615 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4618 converge_option = DHT_CONVERGE_RANDOM;
4621 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4623 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4625 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4626 converge_modifier = 0.0;
4628 GNUNET_free(converge_modifier_buf);
4631 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4635 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4636 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4637 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4638 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4639 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4640 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4641 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4642 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4643 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4644 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4645 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4646 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4647 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4648 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4649 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4650 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4651 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4652 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4653 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4654 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4656 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4657 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4658 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4659 if (GNUNET_YES == do_find_peer)
4661 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4662 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4663 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4664 find_peer_context.start = GNUNET_TIME_absolute_get();
4665 GNUNET_SCHEDULER_add_delayed (sched,
4667 &send_find_peer_message, &find_peer_context);
4670 /* Scheduled the task to clean up when shutdown is called */
4671 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4672 GNUNET_TIME_UNIT_FOREVER_REL,
4673 &shutdown_task, NULL);
4677 * The main function for the dht service.
4679 * @param argc number of arguments from the command line
4680 * @param argv command line arguments
4681 * @return 0 ok, 1 on error
4684 main (int argc, char *const *argv)
4689 GNUNET_SERVICE_run (argc,
4692 GNUNET_SERVICE_OPTION_NONE,
4693 &run, NULL)) ? 0 : 1;
4694 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);