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 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
166 * Real maximum number of hops, at which point we refuse
167 * to forward the message.
169 #define DEFAULT_MAX_HOPS 10
172 * How many time differences between requesting a core send and
173 * the actual callback to remember.
175 #define MAX_REPLY_TIMES 8
177 enum ConvergenceOptions
180 * Use the linear method for convergence.
185 * Converge using a fast converging square
191 * Converge using a slower exponential
194 DHT_CONVERGE_EXPONENTIAL,
197 * Don't do any special convergence, allow
198 * the algorithm to hopefully route to closer
205 * Linked list of messages to send to clients.
207 struct P2PPendingMessage
210 * Pointer to next item in the list
212 struct P2PPendingMessage *next;
215 * Pointer to previous item in the list
217 struct P2PPendingMessage *prev;
220 * Message importance level.
222 unsigned int importance;
225 * Time when this request was scheduled to be sent.
227 struct GNUNET_TIME_Absolute scheduled;
230 * How long to wait before sending message.
232 struct GNUNET_TIME_Relative timeout;
235 * Actual message to be sent; // avoid allocation
237 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
242 * Per-peer information.
247 * Next peer entry (DLL)
249 struct PeerInfo *next;
252 * Prev peer entry (DLL)
254 struct PeerInfo *prev;
257 * Head of pending messages to be sent to this peer.
259 struct P2PPendingMessage *head;
262 * Tail of pending messages to be sent to this peer.
264 struct P2PPendingMessage *tail;
267 * Core handle for sending messages to this peer.
269 struct GNUNET_CORE_TransmitHandle *th;
272 * Task for scheduling message sends.
274 GNUNET_SCHEDULER_TaskIdentifier send_task;
277 * Task for scheduling preference updates
279 GNUNET_SCHEDULER_TaskIdentifier preference_task;
282 * Preference update context
284 struct GNUNET_CORE_InformationRequestContext *info_ctx;
287 * What is the average latency for replies received?
289 struct GNUNET_TIME_Relative latency;
292 * What is the identity of the peer?
294 struct GNUNET_PeerIdentity id;
297 * Transport level distance to peer.
299 unsigned int distance;
302 * Holds matching bits from peer to current target,
303 * used for distance comparisons between peers. May
304 * be considered a really bad idea.
305 * FIXME: remove this value (create struct which holds
306 * a single peerinfo and the matching bits, use
307 * that to pass to comparitor)
309 unsigned int matching_bits;
312 * Task for scheduling periodic ping messages for this peer.
314 GNUNET_SCHEDULER_TaskIdentifier ping_task;
318 * Peers are grouped into buckets.
325 struct PeerInfo *head;
330 struct PeerInfo *tail;
333 * Number of peers in the bucket.
335 unsigned int peers_size;
339 * Linked list of messages to send to clients.
341 struct PendingMessage
344 * Pointer to next item in the list
346 struct PendingMessage *next;
349 * Pointer to previous item in the list
351 struct PendingMessage *prev;
354 * Actual message to be sent; // avoid allocation
356 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
361 * Struct containing information about a client,
362 * handle to connect to it, and any pending messages
363 * that need to be sent to it.
368 * Linked list of active clients
370 struct ClientList *next;
373 * The handle to this client
375 struct GNUNET_SERVER_Client *client_handle;
378 * Handle to the current transmission request, NULL
381 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
384 * Linked list of pending messages for this client
386 struct PendingMessage *pending_head;
389 * Tail of linked list of pending messages for this client
391 struct PendingMessage *pending_tail;
396 * Context containing information about a DHT message received.
398 struct DHT_MessageContext
401 * The client this request was received from.
402 * (NULL if received from another peer)
404 struct ClientList *client;
407 * The peer this request was received from.
408 * (NULL if received from local client)
410 const struct GNUNET_PeerIdentity *peer;
413 * Bloomfilter for this routing request.
415 struct GNUNET_CONTAINER_BloomFilter *bloom;
418 * extended query (see gnunet_block_lib.h).
423 * Bloomfilter to filter out duplicate replies.
425 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
428 * The key this request was about
433 * How long should we wait to transmit this request?
435 struct GNUNET_TIME_Relative timeout;
438 * The unique identifier of this request
443 * Number of bytes in xquery.
448 * Mutator value for the reply_bf, see gnunet_block_lib.h
450 uint32_t reply_bf_mutator;
453 * Desired replication level
455 uint32_t replication;
458 * Network size estimate, either ours or the sum of
459 * those routed to thus far. =~ Log of number of peers
460 * chosen from for this request.
462 uint32_t network_size;
465 * Any message options for this request
467 uint32_t msg_options;
470 * How many hops has the message already traversed?
475 * How important is this message?
477 unsigned int importance;
480 * Should we (still) forward the request on to other peers?
485 * Did we forward this message? (may need to remember it!)
490 * Are we the closest known peer to this key (out of our neighbors?)
496 * Record used for remembering what peers are waiting for what
497 * responses (based on search key).
499 struct DHTRouteSource
504 struct DHTRouteSource *next;
509 struct DHTRouteSource *prev;
512 * Source of the request. Replies should be forwarded to
515 struct GNUNET_PeerIdentity source;
518 * If this was a local request, remember the client; otherwise NULL.
520 struct ClientList *client;
523 * Pointer to this nodes heap location (for removal)
525 struct GNUNET_CONTAINER_HeapNode *hnode;
528 * Back pointer to the record storing this information.
530 struct DHTQueryRecord *record;
533 * Task to remove this entry on timeout.
535 GNUNET_SCHEDULER_TaskIdentifier delete_task;
538 * Bloomfilter of peers we have already sent back as
539 * replies to the initial request. Allows us to not
540 * forward the same peer multiple times for a find peer
543 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
548 * Entry in the DHT routing table.
550 struct DHTQueryRecord
553 * Head of DLL for result forwarding.
555 struct DHTRouteSource *head;
558 * Tail of DLL for result forwarding.
560 struct DHTRouteSource *tail;
563 * Key that the record concerns.
568 * GET message of this record (what we already forwarded?).
570 //DV_DHT_MESSAGE get; Try to get away with not saving this.
573 * Bloomfilter of the peers we've replied to so far
575 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
580 * Context used to calculate the number of find peer messages
581 * per X time units since our last scheduled find peer message
582 * was sent. If we have seen too many messages, delay or don't
585 struct FindPeerMessageContext
589 struct GNUNET_TIME_Absolute start;
591 struct GNUNET_TIME_Absolute end;
595 * DHT Routing results structure
600 * Min heap for removal upon reaching limit
602 struct GNUNET_CONTAINER_Heap *minHeap;
605 * Hashmap for fast key based lookup
607 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
612 * DHT structure for recent requests.
614 struct RecentRequests
617 * Min heap for removal upon reaching limit
619 struct GNUNET_CONTAINER_Heap *minHeap;
622 * Hashmap for key based lookup
624 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
630 * Position of this node in the min heap.
632 struct GNUNET_CONTAINER_HeapNode *heap_node;
635 * Bloomfilter containing entries for peers
636 * we forwarded this request to.
638 struct GNUNET_CONTAINER_BloomFilter *bloom;
641 * Timestamp of this request, for ordering
644 struct GNUNET_TIME_Absolute timestamp;
647 * Key of this request.
652 * Unique identifier for this request.
657 * Task to remove this entry on timeout.
659 GNUNET_SCHEDULER_TaskIdentifier remove_task;
662 struct RepublishContext
677 * Which kind of convergence will we be using?
679 static enum ConvergenceOptions converge_option;
682 * Modifier for the convergence function
684 static float converge_modifier;
687 * Recent requests by hash/uid and by time inserted.
689 static struct RecentRequests recent;
692 * Context to use to calculate find peer rates.
694 static struct FindPeerMessageContext find_peer_context;
697 * Don't use our routing algorithm, always route
698 * to closest peer; initially send requests to 3
701 static unsigned int strict_kademlia;
704 * Routing option to end routing when closest peer found.
706 static unsigned int stop_on_closest;
709 * Routing option to end routing when data is found.
711 static unsigned int stop_on_found;
714 * Whether DHT needs to manage find peer requests, or
715 * an external force will do it on behalf of the DHT.
717 static unsigned int do_find_peer;
720 * Once we have stored an item in the DHT, refresh it
721 * according to our republish interval.
723 static unsigned int do_republish;
726 * Use the "real" distance metric when selecting the
727 * next routing hop. Can be less accurate.
729 static unsigned int use_real_distance;
732 * How many peers have we added since we sent out our last
735 static unsigned int newly_found_peers;
738 * Container of active queries we should remember
740 static struct DHTResults forward_list;
743 * Handle to the datacache service (for inserting/retrieving data)
745 static struct GNUNET_DATACACHE_Handle *datacache;
748 * Handle for the statistics service.
750 struct GNUNET_STATISTICS_Handle *stats;
753 * The main scheduler to use for the DHT service
755 static struct GNUNET_SCHEDULER_Handle *sched;
758 * The configuration the DHT service is running with
760 static const struct GNUNET_CONFIGURATION_Handle *cfg;
763 * Handle to the core service
765 static struct GNUNET_CORE_Handle *coreAPI;
768 * Handle to the transport service, for getting our hello
770 static struct GNUNET_TRANSPORT_Handle *transport_handle;
773 * The identity of our peer.
775 static struct GNUNET_PeerIdentity my_identity;
778 * Short id of the peer, for printing
780 static char *my_short_id;
785 static struct GNUNET_MessageHeader *my_hello;
788 * Task to run when we shut down, cleaning up all our trash
790 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
793 * The lowest currently used bucket.
795 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
798 * The maximum number of hops before we stop routing messages.
800 static unsigned long long max_hops;
803 * How often to republish content we have previously stored.
805 static struct GNUNET_TIME_Relative dht_republish_frequency;
808 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
810 static int use_max_hops;
813 * The buckets (Kademlia routing table, complete with growth).
814 * Array of size MAX_BUCKET_SIZE.
816 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
819 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
821 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
824 * Recently seen find peer requests.
826 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
829 * Maximum size for each bucket.
831 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
834 * List of active clients.
836 static struct ClientList *client_list;
839 * Handle to the DHT logger.
841 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
844 * Whether or not to send routing debugging information
845 * to the dht logging server
847 static unsigned int debug_routes;
850 * Whether or not to send FULL route information to
853 static unsigned int debug_routes_extended;
856 * GNUNET_YES or GNUNET_NO, whether or not to act as
857 * a malicious node which drops all messages
859 static unsigned int malicious_dropper;
862 * GNUNET_YES or GNUNET_NO, whether or not to act as
863 * a malicious node which sends out lots of GETS
865 static unsigned int malicious_getter;
868 * GNUNET_YES or GNUNET_NO, whether or not to act as
869 * a malicious node which sends out lots of PUTS
871 static unsigned int malicious_putter;
874 * Frequency for malicious get requests.
876 static unsigned long long malicious_get_frequency;
879 * Frequency for malicious put requests.
881 static unsigned long long malicious_put_frequency;
884 * Reply times for requests, if we are busy, don't send any
887 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
890 * Current counter for replies.
892 static unsigned int reply_counter;
895 * Our handle to the BLOCK library.
897 static struct GNUNET_BLOCK_Context *block_context;
901 * Forward declaration.
904 send_generic_reply (void *cls, size_t size, void *buf);
907 /** Declare here so retry_core_send is aware of it */
909 core_transmit_notify (void *cls,
910 size_t size, void *buf);
913 * Convert unique ID to hash code.
915 * @param uid unique ID to convert
916 * @param hash set to uid (extended with zeros)
919 hash_from_uid (uint64_t uid,
920 GNUNET_HashCode *hash)
922 memset (hash, 0, sizeof(GNUNET_HashCode));
923 *((uint64_t*)hash) = uid;
928 * Calculate the average send time between messages so that we can
929 * ignore certain requests if we get too busy.
931 * @return the average time between asking core to send a message
932 * and when the buffer for copying it is passed
934 static struct GNUNET_TIME_Relative get_average_send_delay()
937 unsigned int divisor;
938 struct GNUNET_TIME_Relative average_time;
939 average_time = GNUNET_TIME_relative_get_zero();
941 for (i = 0; i < MAX_REPLY_TIMES; i++)
943 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
944 if (reply_times[i].value == (uint64_t)0)
954 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
955 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
961 * Given the largest send delay, artificially decrease it
962 * so the next time around we may have a chance at sending
965 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
968 for (i = 0; i < MAX_REPLY_TIMES; i++)
970 if (reply_times[i].value == max_time.value)
972 reply_times[i].value = reply_times[i].value / 2;
979 * Find the maximum send time of the recently sent values.
981 * @return the average time between asking core to send a message
982 * and when the buffer for copying it is passed
984 static struct GNUNET_TIME_Relative get_max_send_delay()
987 struct GNUNET_TIME_Relative max_time;
988 max_time = GNUNET_TIME_relative_get_zero();
990 for (i = 0; i < MAX_REPLY_TIMES; i++)
992 if (reply_times[i].value > max_time.value)
993 max_time.value = reply_times[i].value;
996 if (max_time.value > MAX_REQUEST_TIME.value)
997 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
1002 increment_stats(const char *value)
1006 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
1011 * Try to send another message from our core send list
1014 try_core_send (void *cls,
1015 const struct GNUNET_SCHEDULER_TaskContext *tc)
1017 struct PeerInfo *peer = cls;
1018 struct P2PPendingMessage *pending;
1021 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
1023 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1026 if (peer->th != NULL)
1027 return; /* Message send already in progress */
1029 pending = peer->head;
1030 if (pending != NULL)
1032 ssize = ntohs(pending->msg->size);
1034 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1035 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
1036 "DHT", ssize, GNUNET_i2s(&peer->id));
1038 pending->scheduled = GNUNET_TIME_absolute_get();
1040 if (reply_counter >= MAX_REPLY_TIMES)
1042 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
1043 pending->timeout, &peer->id,
1044 ssize, &core_transmit_notify, peer);
1049 * Function called to send a request out to another peer.
1050 * Called both for locally initiated requests and those
1051 * received from other peers.
1053 * @param cls DHT service closure argument
1054 * @param msg the encapsulated message
1055 * @param peer the peer to forward the message to
1056 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1059 forward_result_message (void *cls,
1060 const struct GNUNET_MessageHeader *msg,
1061 struct PeerInfo *peer,
1062 struct DHT_MessageContext *msg_ctx)
1064 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1065 struct P2PPendingMessage *pending;
1069 increment_stats(STAT_RESULT_FORWARDS);
1070 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1071 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1072 psize = sizeof(struct P2PPendingMessage) + msize;
1073 pending = GNUNET_malloc(psize);
1074 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1075 pending->importance = DHT_SEND_PRIORITY;
1076 pending->timeout = GNUNET_TIME_relative_get_forever();
1077 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1078 result_message->header.size = htons(msize);
1079 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1080 result_message->put_path_length = htons(0); /* FIXME: implement */
1081 result_message->get_path_length = htons(0); /* FIXME: implement */
1082 result_message->options = htonl(msg_ctx->msg_options);
1083 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1084 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1085 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1086 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1087 memcpy(&result_message[1], msg, ntohs(msg->size));
1089 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));
1091 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1092 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1093 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1098 * Called when core is ready to send a message we asked for
1099 * out to the destination.
1101 * @param cls closure (NULL)
1102 * @param size number of bytes available in buf
1103 * @param buf where the callee should write the message
1104 * @return number of bytes written to buf
1107 core_transmit_notify (void *cls,
1108 size_t size, void *buf)
1110 struct PeerInfo *peer = cls;
1112 struct P2PPendingMessage *pending;
1119 /* client disconnected */
1121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1126 if (peer->head == NULL)
1131 pending = peer->head;
1132 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1133 msize = ntohs(pending->msg->size);
1137 memcpy (cbuf, pending->msg, msize);
1138 GNUNET_CONTAINER_DLL_remove (peer->head,
1142 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));
1144 GNUNET_free (pending);
1147 while (NULL != pending &&
1148 (size - off >= (msize = ntohs (pending->msg->size))))
1150 #if DEBUG_DHT_ROUTING
1151 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);
1153 memcpy (&cbuf[off], pending->msg, msize);
1155 GNUNET_CONTAINER_DLL_remove (peer->head,
1158 GNUNET_free (pending);
1159 pending = peer->head;
1162 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1163 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1165 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);
1172 * Compute the distance between have and target as a 32-bit value.
1173 * Differences in the lower bits must count stronger than differences
1174 * in the higher bits.
1176 * @return 0 if have==target, otherwise a number
1177 * that is larger as the distance between
1178 * the two hash codes increases
1181 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1183 unsigned int bucket;
1188 /* We have to represent the distance between two 2^9 (=512)-bit
1189 numbers as a 2^5 (=32)-bit number with "0" being used for the
1190 two numbers being identical; furthermore, we need to
1191 guarantee that a difference in the number of matching
1192 bits is always represented in the result.
1194 We use 2^32/2^9 numerical values to distinguish between
1195 hash codes that have the same LSB bit distance and
1196 use the highest 2^9 bits of the result to signify the
1197 number of (mis)matching LSB bits; if we have 0 matching
1198 and hence 512 mismatching LSB bits we return -1 (since
1199 512 itself cannot be represented with 9 bits) */
1201 /* first, calculate the most significant 9 bits of our
1202 result, aka the number of LSBs */
1203 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1204 /* bucket is now a value between 0 and 512 */
1206 return 0; /* perfect match */
1208 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1209 below, we'd end up with max+1 (overflow)) */
1211 /* calculate the most significant bits of the final result */
1212 msb = (512 - bucket) << (32 - 9);
1213 /* calculate the 32-9 least significant bits of the final result by
1214 looking at the differences in the 32-9 bits following the
1215 mismatching bit at 'bucket' */
1217 for (i = bucket + 1;
1218 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1220 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1221 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1222 last bit set will be 31 -- if
1223 i does not reach 512 first... */
1229 * Return a number that is larger the closer the
1230 * "have" GNUNET_hash code is to the "target".
1232 * @return inverse distance metric, non-zero.
1233 * Must fudge the value if NO bits match.
1236 inverse_distance (const GNUNET_HashCode * target,
1237 const GNUNET_HashCode * have)
1239 if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1240 return 1; /* Never return 0! */
1241 return ((unsigned int) -1) - distance (target, have);
1245 * Find the optimal bucket for this key, regardless
1246 * of the current number of buckets in use.
1248 * @param hc the hashcode to compare our identity to
1250 * @return the proper bucket index, or GNUNET_SYSERR
1251 * on error (same hashcode)
1253 static int find_bucket(const GNUNET_HashCode *hc)
1257 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1258 if (bits == MAX_BUCKETS)
1259 return GNUNET_SYSERR;
1260 return MAX_BUCKETS - bits - 1;
1264 * Find which k-bucket this peer should go into,
1265 * taking into account the size of the k-bucket
1266 * array. This means that if more bits match than
1267 * there are currently buckets, lowest_bucket will
1270 * @param hc GNUNET_HashCode we are finding the bucket for.
1272 * @return the proper bucket index for this key,
1273 * or GNUNET_SYSERR on error (same hashcode)
1275 static int find_current_bucket(const GNUNET_HashCode *hc)
1278 actual_bucket = find_bucket(hc);
1280 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1281 return lowest_bucket;
1282 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1283 return lowest_bucket;
1285 return actual_bucket;
1290 * Find a routing table entry from a peer identity
1292 * @param peer the peer to look up
1294 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1297 find_bucket_by_peer(const struct PeerInfo *peer)
1300 struct PeerInfo *pos;
1302 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1304 pos = k_buckets[bucket].head;
1313 return GNUNET_SYSERR; /* No such peer. */
1319 * Print the complete routing table for this peer.
1322 print_routing_table ()
1325 struct PeerInfo *pos;
1326 char char_buf[30000];
1328 memset(char_buf, 0, sizeof(char_buf));
1330 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1331 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1332 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1334 pos = k_buckets[bucket].head;
1335 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1336 //fprintf(stderr, "Bucket %d:\n", bucket);
1339 //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));
1340 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));
1344 fprintf(stderr, "%s", char_buf);
1350 * Find a routing table entry from a peer identity
1352 * @param peer the peer identity to look up
1354 * @return the routing table entry, or NULL if not found
1356 static struct PeerInfo *
1357 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1360 struct PeerInfo *pos;
1361 bucket = find_current_bucket(&peer->hashPubKey);
1363 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1366 pos = k_buckets[bucket].head;
1369 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1373 return NULL; /* No such peer. */
1376 /* Forward declaration */
1378 update_core_preference (void *cls,
1379 const struct GNUNET_SCHEDULER_TaskContext *tc);
1381 * Function called with statistics about the given peer.
1383 * @param cls closure
1384 * @param peer identifies the peer
1385 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1386 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1387 * @param amount set to the amount that was actually reserved or unreserved;
1388 * either the full requested amount or zero (no partial reservations)
1389 * @param preference current traffic preference for the given peer
1392 update_core_preference_finish (void *cls,
1393 const struct GNUNET_PeerIdentity * peer,
1394 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1395 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1396 int amount, uint64_t preference)
1398 struct PeerInfo *peer_info = cls;
1399 peer_info->info_ctx = NULL;
1400 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1404 update_core_preference (void *cls,
1405 const struct GNUNET_SCHEDULER_TaskContext *tc)
1407 struct PeerInfo *peer = cls;
1408 uint64_t preference;
1409 unsigned int matching;
1410 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1414 matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1417 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1420 preference = 1LL << matching;
1421 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1423 GNUNET_TIME_relative_get_forever(),
1424 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1427 &update_core_preference_finish,
1432 * Really add a peer to a bucket (only do assertions
1435 * @param peer GNUNET_PeerIdentity of the peer to add
1436 * @param bucket the already figured out bucket to add
1438 * @param latency the core reported latency of this peer
1439 * @param distance the transport level distance to this peer
1441 * @return the newly added PeerInfo
1443 static struct PeerInfo *
1444 add_peer(const struct GNUNET_PeerIdentity *peer,
1445 unsigned int bucket,
1446 struct GNUNET_TIME_Relative latency,
1447 unsigned int distance)
1449 struct PeerInfo *new_peer;
1450 GNUNET_assert(bucket < MAX_BUCKETS);
1451 GNUNET_assert(peer != NULL);
1452 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1453 new_peer->latency = latency;
1454 new_peer->distance = distance;
1456 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1458 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1459 k_buckets[bucket].tail,
1460 k_buckets[bucket].tail,
1462 k_buckets[bucket].peers_size++;
1464 if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1466 #if DO_UPDATE_PREFERENCE
1467 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1475 * Given a peer and its corresponding bucket,
1476 * remove it from that bucket. Does not free
1477 * the PeerInfo struct, nor cancel messages
1478 * or free messages waiting to be sent to this
1481 * @param peer the peer to remove
1482 * @param bucket the bucket the peer belongs to
1484 static void remove_peer (struct PeerInfo *peer,
1485 unsigned int bucket)
1487 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1488 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1489 k_buckets[bucket].tail,
1491 k_buckets[bucket].peers_size--;
1493 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1499 * Removes peer from a bucket, then frees associated
1500 * resources and frees peer.
1502 * @param peer peer to be removed and freed
1503 * @param bucket which bucket this peer belongs to
1505 static void delete_peer (struct PeerInfo *peer,
1506 unsigned int bucket)
1508 struct P2PPendingMessage *pos;
1509 struct P2PPendingMessage *next;
1511 struct PeerInfo *peer_pos;
1513 peer_pos = k_buckets[bucket].head;
1514 while ((peer_pos != NULL) && (peer_pos != peer))
1515 peer_pos = peer_pos->next;
1516 if (peer_pos == NULL)
1518 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1519 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));
1521 GNUNET_assert(peer_pos != NULL);
1523 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1525 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1526 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1527 if (peer->th != NULL)
1528 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1531 while (pos != NULL) /* Remove any pending messages for this peer */
1538 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1539 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1545 * Iterator over hash map entries.
1547 * @param cls closure
1548 * @param key current key code
1549 * @param value PeerInfo of the peer to move to new lowest bucket
1550 * @return GNUNET_YES if we should continue to
1554 static int move_lowest_bucket (void *cls,
1555 const GNUNET_HashCode * key,
1558 struct PeerInfo *peer = value;
1561 GNUNET_assert(lowest_bucket > 0);
1562 new_bucket = lowest_bucket - 1;
1563 remove_peer(peer, lowest_bucket);
1564 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1565 k_buckets[new_bucket].tail,
1566 k_buckets[new_bucket].tail,
1568 k_buckets[new_bucket].peers_size++;
1574 * The current lowest bucket is full, so change the lowest
1575 * bucket to the next lower down, and move any appropriate
1576 * entries in the current lowest bucket to the new bucket.
1578 static void enable_next_bucket()
1580 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1581 struct PeerInfo *pos;
1582 GNUNET_assert(lowest_bucket > 0);
1583 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1584 pos = k_buckets[lowest_bucket].head;
1587 fprintf(stderr, "Printing RT before new bucket\n");
1588 print_routing_table();
1590 /* Populate the array of peers which should be in the next lowest bucket */
1593 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1594 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1598 /* Remove peers from lowest bucket, insert into next lowest bucket */
1599 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1600 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1601 lowest_bucket = lowest_bucket - 1;
1603 fprintf(stderr, "Printing RT after new bucket\n");
1604 print_routing_table();
1609 * Find the closest peer in our routing table to the
1612 * @return The closest peer in our routing table to the
1613 * key, or NULL on error.
1615 static struct PeerInfo *
1616 find_closest_peer (const GNUNET_HashCode *hc)
1618 struct PeerInfo *pos;
1619 struct PeerInfo *current_closest;
1620 unsigned int lowest_distance;
1621 unsigned int temp_distance;
1625 lowest_distance = -1;
1627 if (k_buckets[lowest_bucket].peers_size == 0)
1630 current_closest = NULL;
1631 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1633 pos = k_buckets[bucket].head;
1635 while ((pos != NULL) && (count < bucket_size))
1637 temp_distance = distance(&pos->id.hashPubKey, hc);
1638 if (temp_distance <= lowest_distance)
1640 lowest_distance = temp_distance;
1641 current_closest = pos;
1647 GNUNET_assert(current_closest != NULL);
1648 return current_closest;
1653 * Function called to send a request out to another peer.
1654 * Called both for locally initiated requests and those
1655 * received from other peers.
1657 * @param msg the encapsulated message
1658 * @param peer the peer to forward the message to
1659 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1661 static void forward_message (const struct GNUNET_MessageHeader *msg,
1662 struct PeerInfo *peer,
1663 struct DHT_MessageContext *msg_ctx)
1665 struct GNUNET_DHT_P2PRouteMessage *route_message;
1666 struct P2PPendingMessage *pending;
1670 increment_stats(STAT_ROUTE_FORWARDS);
1672 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1673 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1675 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1676 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1677 psize = sizeof(struct P2PPendingMessage) + msize;
1678 pending = GNUNET_malloc(psize);
1679 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1680 pending->importance = msg_ctx->importance;
1681 pending->timeout = msg_ctx->timeout;
1682 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1683 route_message->header.size = htons(msize);
1684 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1685 route_message->options = htonl(msg_ctx->msg_options);
1686 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1687 route_message->network_size = htonl(msg_ctx->network_size);
1688 route_message->desired_replication_level = htonl(msg_ctx->replication);
1689 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1690 if (msg_ctx->bloom != NULL)
1691 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1692 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1693 memcpy(&route_message[1], msg, ntohs(msg->size));
1695 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));
1697 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1698 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1699 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1704 * Task used to send ping messages to peers so that
1705 * they don't get disconnected.
1707 * @param cls the peer to send a ping message to
1708 * @param tc context, reason, etc.
1711 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1713 struct PeerInfo *peer = cls;
1714 struct GNUNET_MessageHeader ping_message;
1715 struct DHT_MessageContext message_context;
1717 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1720 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1721 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1723 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1725 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1727 forward_message(&ping_message, peer, &message_context);
1728 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1732 * Schedule PING messages for the top X peers in each
1733 * bucket of the routing table (so core won't disconnect them!)
1735 void schedule_ping_messages()
1737 unsigned int bucket;
1739 struct PeerInfo *pos;
1740 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1742 pos = k_buckets[bucket].head;
1746 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1747 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1748 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1750 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1751 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1761 * Attempt to add a peer to our k-buckets.
1763 * @param peer the peer identity of the peer being added
1764 * @param bucket the bucket that we want this peer to go in
1765 * @param latency transport latency of this peer
1766 * @param distance transport distance to this peer
1768 * @return NULL if the peer was not added,
1769 * pointer to PeerInfo for new peer otherwise
1771 static struct PeerInfo *
1772 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1773 unsigned int bucket,
1774 struct GNUNET_TIME_Relative latency,
1775 unsigned int distance)
1778 struct PeerInfo *new_peer;
1780 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1783 peer_bucket = find_current_bucket(&peer->hashPubKey);
1785 GNUNET_assert(peer_bucket >= lowest_bucket);
1786 new_peer = add_peer(peer, peer_bucket, latency, distance);
1788 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1789 enable_next_bucket();
1791 schedule_ping_messages();
1798 * Task run to check for messages that need to be sent to a client.
1800 * @param client a ClientList, containing the client and any messages to be sent to it
1803 process_pending_messages (struct ClientList *client)
1805 if (client->pending_head == NULL)
1807 if (client->transmit_handle != NULL)
1810 client->transmit_handle =
1811 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1812 ntohs (client->pending_head->msg->
1814 GNUNET_TIME_UNIT_FOREVER_REL,
1815 &send_generic_reply, client);
1819 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1820 * request. A ClientList is passed as closure, take the head of the list
1821 * and copy it into buf, which has the result of sending the message to the
1824 * @param cls closure to this call
1825 * @param size maximum number of bytes available to send
1826 * @param buf where to copy the actual message to
1828 * @return the number of bytes actually copied, 0 indicates failure
1831 send_generic_reply (void *cls, size_t size, void *buf)
1833 struct ClientList *client = cls;
1835 struct PendingMessage *reply;
1839 client->transmit_handle = NULL;
1842 /* client disconnected */
1846 while ( (NULL != (reply = client->pending_head)) &&
1847 (size >= off + (msize = ntohs (reply->msg->size))))
1849 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1850 client->pending_tail,
1852 memcpy (&cbuf[off], reply->msg, msize);
1853 GNUNET_free (reply);
1856 process_pending_messages (client);
1858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1859 "Transmitted %u bytes of replies to client\n",
1860 (unsigned int) off);
1867 * Add a PendingMessage to the clients list of messages to be sent
1869 * @param client the active client to send the message to
1870 * @param pending_message the actual message to send
1873 add_pending_message (struct ClientList *client,
1874 struct PendingMessage *pending_message)
1876 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1877 client->pending_tail,
1878 client->pending_tail,
1880 process_pending_messages (client);
1887 * Called when a reply needs to be sent to a client, as
1888 * a result it found to a GET or FIND PEER request.
1890 * @param client the client to send the reply to
1891 * @param message the encapsulated message to send
1892 * @param uid the unique identifier of this request
1895 send_reply_to_client (struct ClientList *client,
1896 const struct GNUNET_MessageHeader *message,
1897 unsigned long long uid,
1898 const GNUNET_HashCode *key)
1900 struct GNUNET_DHT_RouteResultMessage *reply;
1901 struct PendingMessage *pending_message;
1905 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1906 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1908 msize = ntohs (message->size);
1909 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1910 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1912 GNUNET_break_op (0);
1915 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1916 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1917 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1918 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1919 reply->header.size = htons (tsize);
1920 reply->put_path_length = htons(0); /* FIXME: implement */
1921 reply->get_path_length = htons(0); /* FIXME: implement */
1922 reply->unique_id = GNUNET_htonll (uid);
1924 memcpy (&reply[1], message, msize);
1925 add_pending_message (client, pending_message);
1929 * Consider whether or not we would like to have this peer added to
1930 * our routing table. Check whether bucket for this peer is full,
1931 * if so return negative; if not return positive. Since peers are
1932 * only added on CORE level connect, this doesn't actually add the
1933 * peer to the routing table.
1935 * @param peer the peer we are considering adding
1937 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1940 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1944 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1945 return GNUNET_NO; /* We already know this peer (are connected even!) */
1946 bucket = find_current_bucket(&peer->hashPubKey);
1948 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1955 * Main function that handles whether or not to route a result
1956 * message to other peers, or to send to our local client.
1958 * @param cls closure (unused, always should be NULL)
1959 * @param msg the result message to be routed
1960 * @param message_context context of the message we are routing
1962 * @return the number of peers the message was routed to,
1963 * GNUNET_SYSERR on failure
1965 static int route_result_message(void *cls,
1966 struct GNUNET_MessageHeader *msg,
1967 struct DHT_MessageContext *message_context)
1969 struct GNUNET_PeerIdentity new_peer;
1970 struct DHTQueryRecord *record;
1971 struct DHTRouteSource *pos;
1972 struct PeerInfo *peer_info;
1973 const struct GNUNET_MessageHeader *hello_msg;
1975 increment_stats(STAT_RESULTS);
1977 * If a find peer result message is received and contains a valid
1978 * HELLO for another peer, offer it to the transport service.
1980 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1982 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1985 hello_msg = &msg[1];
1986 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1988 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1992 else /* We have a valid hello, and peer id stored in new_peer */
1994 find_peer_context.count++;
1995 increment_stats(STAT_FIND_PEER_REPLY);
1996 if (GNUNET_YES == consider_peer(&new_peer))
1998 increment_stats(STAT_HELLOS_PROVIDED);
1999 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
2000 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
2005 if (malicious_dropper == GNUNET_YES)
2008 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
2010 if (record == NULL) /* No record of this message! */
2013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2014 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
2015 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2017 #if DEBUG_DHT_ROUTING
2018 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2020 dhtlog_handle->insert_route (NULL,
2021 message_context->unique_id,
2023 message_context->hop_count,
2026 &message_context->key,
2027 message_context->peer, NULL);
2030 if (message_context->bloom != NULL)
2032 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2033 message_context->bloom = NULL;
2041 #if STRICT_FORWARDING
2042 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2044 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2046 increment_stats("# find peer responses NOT forwarded (bloom match)");
2051 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2055 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2058 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2059 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2060 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id);
2062 #if DEBUG_DHT_ROUTING
2063 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2065 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2066 message_context->hop_count,
2067 GNUNET_YES, &my_identity, &message_context->key,
2068 message_context->peer, NULL);
2071 increment_stats(STAT_RESULTS_TO_CLIENT);
2072 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2073 increment_stats(STAT_GET_REPLY);
2075 send_reply_to_client(pos->client, msg,
2076 message_context->unique_id,
2077 &message_context->key);
2079 else /* Send to peer */
2081 peer_info = find_peer_by_id(&pos->source);
2082 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2088 if (message_context->bloom == NULL)
2089 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2090 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2091 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2094 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2095 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2096 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2098 #if DEBUG_DHT_ROUTING
2099 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2101 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2103 message_context->hop_count,
2104 GNUNET_NO, &my_identity, &message_context->key,
2105 message_context->peer, &pos->source);
2108 forward_result_message(cls, msg, peer_info, message_context);
2113 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2114 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2115 "DHT", GNUNET_h2s (&message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2121 if (message_context->bloom != NULL)
2122 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2127 * Iterator for local get request results,
2129 * @param cls closure for iterator, a DatacacheGetContext
2130 * @param exp when does this value expire?
2131 * @param key the key this data is stored under
2132 * @param size the size of the data identified by key
2133 * @param data the actual data
2134 * @param type the type of the data
2136 * @return GNUNET_OK to continue iteration, anything else
2137 * to stop iteration.
2140 datacache_get_iterator (void *cls,
2141 struct GNUNET_TIME_Absolute exp,
2142 const GNUNET_HashCode * key,
2143 uint32_t size, const char *data,
2144 enum GNUNET_BLOCK_Type type)
2146 struct DHT_MessageContext *msg_ctx = cls;
2147 struct DHT_MessageContext *new_msg_ctx;
2148 struct GNUNET_DHT_GetResultMessage *get_result;
2149 enum GNUNET_BLOCK_EvaluationResult eval;
2152 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2153 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2155 eval = GNUNET_BLOCK_evaluate (block_context,
2159 msg_ctx->reply_bf_mutator,
2161 msg_ctx->xquery_size,
2166 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2167 msg_ctx->do_forward = GNUNET_NO;
2168 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2169 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2170 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2172 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2173 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2174 get_result->header.size =
2175 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2176 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2177 get_result->type = htons (type);
2178 memcpy (&get_result[1], data, size);
2179 new_msg_ctx->peer = &my_identity;
2180 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2181 new_msg_ctx->hop_count = 0;
2182 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2183 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2184 increment_stats(STAT_GET_RESPONSE_START);
2185 route_result_message(cls, &get_result->header, new_msg_ctx);
2186 GNUNET_free(new_msg_ctx);
2187 GNUNET_free (get_result);
2189 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2192 "`%s:%s': Duplicate block error\n", my_short_id, "DHT");
2195 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2198 "`%s:%s': Invalid request error\n", my_short_id, "DHT");
2201 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2204 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2208 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2209 GNUNET_break_op (0);
2210 msg_ctx->do_forward = GNUNET_NO;
2212 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2215 "`%s:%s': Unsupported block type (%u) in response!\n", my_short_id, "DHT", type);
2217 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2225 * Main function that handles whether or not to route a message to other
2228 * @param msg the message to be routed
2229 * @param message_context the context containing all pertinent information about the message
2232 route_message2(const struct GNUNET_MessageHeader *msg,
2233 struct DHT_MessageContext *message_context);
2237 * Server handler for all dht get requests, look for data,
2238 * if found, send response either to clients or other peers.
2240 * @param cls closure for service
2241 * @param msg the actual get message
2242 * @param message_context struct containing pertinent information about the get request
2244 * @return number of items found for GET request
2247 handle_dht_get (void *cls,
2248 const struct GNUNET_MessageHeader *msg,
2249 struct DHT_MessageContext *message_context)
2251 const struct GNUNET_DHT_GetMessage *get_msg;
2254 unsigned int results;
2256 enum GNUNET_BLOCK_Type type;
2258 msize = ntohs (msg->size);
2259 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2264 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2265 bf_size = ntohs (get_msg->bf_size);
2266 message_context->xquery_size = ntohs (get_msg->xquery_size);
2267 message_context->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2268 if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + message_context->xquery_size)
2273 end = (const char*) &get_msg[1];
2274 if (message_context->xquery_size == 0)
2276 message_context->xquery = NULL;
2280 message_context->xquery = (const void*) end;
2281 end += message_context->xquery_size;
2285 message_context->reply_bf = NULL;
2289 message_context->reply_bf = GNUNET_CONTAINER_bloomfilter_init (end,
2291 GNUNET_DHT_GET_BLOOMFILTER_K);
2293 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2295 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2296 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2300 GNUNET_h2s (&message_context->key),
2301 message_context->unique_id);
2303 increment_stats(STAT_GETS);
2306 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2308 GNUNET_CONTAINER_bloomfilter_free (message_context->reply_bf);
2312 message_context->do_forward = GNUNET_YES;
2313 if (datacache != NULL)
2315 = GNUNET_DATACACHE_get (datacache,
2316 &message_context->key, type,
2317 &datacache_get_iterator,
2322 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2323 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2324 results, "GET", message_context->unique_id);
2326 #if DEBUG_DHT_ROUTING
2327 if ((debug_routes) && (dhtlog_handle != NULL))
2329 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2330 message_context->hop_count, GNUNET_YES, &my_identity,
2331 &message_context->key);
2334 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2336 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2337 message_context->hop_count, GNUNET_YES,
2338 &my_identity, &message_context->key, message_context->peer,
2345 /* check query valid */
2346 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID
2347 == GNUNET_BLOCK_evaluate (block_context,
2349 &message_context->key,
2350 &message_context->reply_bf,
2351 message_context->reply_bf_mutator,
2352 message_context->xquery,
2353 message_context->xquery_size,
2356 GNUNET_break_op (0);
2357 message_context->do_forward = GNUNET_NO;
2361 if (message_context->hop_count == 0) /* Locally initiated request */
2363 #if DEBUG_DHT_ROUTING
2364 if ((debug_routes) && (dhtlog_handle != NULL))
2366 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2367 message_context->hop_count, GNUNET_NO, &my_identity,
2368 &message_context->key);
2372 if (message_context->do_forward == GNUNET_YES)
2373 route_message2 (msg, message_context);
2374 GNUNET_CONTAINER_bloomfilter_free (message_context->reply_bf);
2379 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2381 GNUNET_HashCode *key = cls;
2383 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key));
2388 * Server handler for initiating local dht find peer requests
2390 * @param cls closure for service
2391 * @param find_msg the actual find peer message
2392 * @param message_context struct containing pertinent information about the request
2396 handle_dht_find_peer (void *cls,
2397 const struct GNUNET_MessageHeader *find_msg,
2398 struct DHT_MessageContext *message_context)
2400 struct GNUNET_MessageHeader *find_peer_result;
2401 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2402 struct DHT_MessageContext *new_msg_ctx;
2403 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2406 GNUNET_HashCode *recent_hash;
2407 struct GNUNET_MessageHeader *other_hello;
2408 size_t other_hello_size;
2409 struct GNUNET_PeerIdentity peer_id;
2411 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2412 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2413 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2416 other_hello_size = 0;
2417 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2419 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2420 other_hello = GNUNET_malloc(other_hello_size);
2421 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2422 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)))
2424 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2425 GNUNET_free(other_hello);
2428 #if FIND_PEER_WITH_HELLO
2429 if (GNUNET_YES == consider_peer(&peer_id))
2431 increment_stats(STAT_HELLOS_PROVIDED);
2432 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2433 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2434 route_message2 (find_msg, message_context);
2435 GNUNET_free (other_hello);
2438 else /* We don't want this peer! */
2440 route_message2 (find_msg, message_context);
2447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2448 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2449 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&message_context->key),
2450 ntohs (find_msg->size),
2451 sizeof (struct GNUNET_MessageHeader));
2453 if (my_hello == NULL)
2456 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2457 "`%s': Our HELLO is null, can't return.\n",
2460 GNUNET_free_non_null (other_hello);
2461 route_message2 (find_msg, message_context);
2465 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2466 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2468 increment_stats(STAT_BLOOM_FIND_PEER);
2469 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2470 GNUNET_free_non_null(other_hello);
2471 route_message2 (find_msg, message_context);
2472 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2474 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2476 #if RESTRICT_FIND_PEER
2479 * Ignore any find peer requests from a peer we have seen very recently.
2481 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! */
2483 increment_stats("# dht find peer requests ignored (recently seen!)");
2484 GNUNET_free_non_null(other_hello);
2489 * Use this check to only allow the peer to respond to find peer requests if
2490 * it would be beneficial to have the requesting peer in this peers routing
2491 * table. Can be used to thwart peers flooding the network with find peer
2492 * requests that we don't care about. However, if a new peer is joining
2493 * the network and has no other peers this is a problem (assume all buckets
2494 * full, no one will respond!).
2496 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2497 if (GNUNET_NO == consider_peer(&peer_id))
2499 increment_stats("# dht find peer requests ignored (do not need!)");
2500 GNUNET_free_non_null(other_hello);
2501 route_message2 (find_msg, message_context);
2506 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2507 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2508 if (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2509 &message_context->key, NULL,
2510 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2512 /* Only add a task if there wasn't one for this key already! */
2513 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30),
2514 &remove_recent_find_peer, recent_hash);
2518 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received duplicate find peer request too soon!\n");
2521 /* Simplistic find_peer functionality, always return our hello */
2522 hello_size = ntohs(my_hello->size);
2523 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2525 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2527 GNUNET_break_op (0);
2528 GNUNET_free_non_null(other_hello);
2532 find_peer_result = GNUNET_malloc (tsize);
2533 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2534 find_peer_result->size = htons (tsize);
2535 memcpy (&find_peer_result[1], my_hello, hello_size);
2537 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2538 "`%s': Sending hello size %d to requesting peer.\n",
2541 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2542 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2543 new_msg_ctx->peer = &my_identity;
2544 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2545 new_msg_ctx->hop_count = 0;
2546 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2547 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2548 increment_stats(STAT_FIND_PEER_ANSWER);
2549 route_result_message(cls, find_peer_result, new_msg_ctx);
2550 GNUNET_free(new_msg_ctx);
2551 #if DEBUG_DHT_ROUTING
2552 if ((debug_routes) && (dhtlog_handle != NULL))
2554 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2555 message_context->hop_count, GNUNET_YES, &my_identity,
2556 &message_context->key);
2559 GNUNET_free_non_null(other_hello);
2560 GNUNET_free(find_peer_result);
2561 route_message2 (find_msg, message_context);
2565 * Task used to republish data.
2566 * Forward declaration; function call loop.
2568 * @param cls closure (a struct RepublishContext)
2569 * @param tc runtime context for this task
2572 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2575 * Server handler for initiating local dht put requests
2577 * @param cls closure for service
2578 * @param msg the actual put message
2579 * @param message_context struct containing pertinent information about the request
2582 handle_dht_put (void *cls,
2583 const struct GNUNET_MessageHeader *msg,
2584 struct DHT_MessageContext *message_context)
2586 struct GNUNET_DHT_PutMessage *put_msg;
2587 enum GNUNET_BLOCK_Type put_type;
2590 struct RepublishContext *put_context;
2592 GNUNET_assert (ntohs (msg->size) >=
2593 sizeof (struct GNUNET_DHT_PutMessage));
2596 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2597 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2599 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2602 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2604 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2605 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2606 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&message_context->key), message_context->unique_id);
2608 #if DEBUG_DHT_ROUTING
2609 if (message_context->hop_count == 0) /* Locally initiated request */
2611 if ((debug_routes) && (dhtlog_handle != NULL))
2613 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2614 message_context->hop_count, GNUNET_NO, &my_identity,
2615 &message_context->key);
2620 if (message_context->closest != GNUNET_YES)
2623 #if DEBUG_DHT_ROUTING
2624 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2626 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2627 message_context->hop_count, GNUNET_YES,
2628 &my_identity, &message_context->key, message_context->peer,
2632 if ((debug_routes) && (dhtlog_handle != NULL))
2634 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2635 message_context->hop_count, GNUNET_YES, &my_identity,
2636 &message_context->key);
2640 increment_stats(STAT_PUTS_INSERTED);
2641 if (datacache != NULL)
2643 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2644 (char *) &put_msg[1], put_type,
2645 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2647 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2649 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2650 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2651 put_context->type = put_type;
2652 GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
2656 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2657 "`%s:%s': %s request received, but have no datacache!\n",
2658 my_short_id, "DHT", "PUT");
2659 route_message2 (msg, message_context);
2663 * Estimate the diameter of the network based
2664 * on how many buckets are currently in use.
2665 * Concept here is that the diameter of the network
2666 * is roughly the distance a message must travel in
2667 * order to reach its intended destination. Since
2668 * at each hop we expect to get one bit closer, and
2669 * we have one bit per bucket, the number of buckets
2670 * in use should be the largest number of hops for
2671 * a sucessful message. (of course, this assumes we
2672 * know all peers in the network!)
2674 * @return ballpark diameter figure
2676 static unsigned int estimate_diameter()
2678 return MAX_BUCKETS - lowest_bucket;
2682 * To how many peers should we (on average)
2683 * forward the request to obtain the desired
2684 * target_replication count (on average).
2686 * Always 0, 1 or 2 (don't send, send once, split)
2689 get_forward_count (unsigned int hop_count, size_t target_replication)
2692 double target_count;
2693 double random_probability;
2695 uint32_t random_value;
2697 unsigned int target_value;
2698 unsigned int diameter;
2701 * If we are behaving in strict kademlia mode, send multiple initial requests,
2702 * but then only send to 1 or 0 peers based strictly on the number of hops.
2704 if (strict_kademlia == GNUNET_YES)
2707 return DHT_KADEMLIA_REPLICATION;
2708 else if (hop_count < max_hops)
2714 /* FIXME: the smaller we think the network is the more lenient we should be for
2715 * routing right? The estimation below only works if we think we have reasonably
2716 * full routing tables, which for our RR topologies may not be the case!
2718 diameter = estimate_diameter ();
2719 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2722 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2723 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2724 "DHT", estimate_diameter(), lowest_bucket);
2728 else if (hop_count > max_hops)
2731 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2732 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2739 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2740 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2741 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2742 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2743 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2744 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2745 RAND_MAX)) / RAND_MAX;
2746 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2749 //while (target_value < target_count)
2750 if (target_value < target_count)
2751 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? */
2754 //if ((target_count + 1 - (double)target_value) > random_probability)
2755 if ((target_count) > random_probability)
2759 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2760 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));
2762 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2763 if (random_value < target_replication)
2766 return target_value;
2770 * Check whether my identity is closer than any known peers.
2771 * If a non-null bloomfilter is given, check if this is the closest
2772 * peer that hasn't already been routed to.
2774 * @param target hash code to check closeness to
2775 * @param bloom bloomfilter, exclude these entries from the decision
2777 * Return GNUNET_YES if node location is closest, GNUNET_NO
2781 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2787 struct PeerInfo *pos;
2788 unsigned int my_distance;
2790 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2793 bucket_num = find_current_bucket(target);
2795 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2796 my_distance = distance(&my_identity.hashPubKey, target);
2797 pos = k_buckets[bucket_num].head;
2799 while ((pos != NULL) && (count < bucket_size))
2801 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2804 continue; /* Skip already checked entries */
2807 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2808 if (other_bits > bits)
2810 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2812 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2814 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2821 GNUNET_GE_LOG (coreAPI->ectx,
2822 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2823 GNUNET_GE_BULK, "closest peer\n");
2824 printPeerBits (&closest);
2825 GNUNET_GE_LOG (coreAPI->ectx,
2826 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2827 GNUNET_GE_BULK, "me\n");
2828 printPeerBits (coreAPI->my_identity);
2829 GNUNET_GE_LOG (coreAPI->ectx,
2830 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2831 GNUNET_GE_BULK, "key\n");
2832 printKeyBits (target);
2833 GNUNET_GE_LOG (coreAPI->ectx,
2834 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2836 "closest peer inverse distance is %u, mine is %u\n",
2837 inverse_distance (target, &closest.hashPubKey),
2838 inverse_distance (target,
2839 &coreAPI->my_identity->hashPubKey));
2842 /* No peers closer, we are the closest! */
2848 * Return this peers adjusted value based on the convergence
2849 * function chosen. This is the key function for randomized
2850 * routing decisions.
2852 * @param target the key of the request
2853 * @param peer the peer we would like the value of
2854 * @param hops number of hops this message has already traveled
2856 * @return bit distance from target to peer raised to an exponent
2857 * adjusted based on the current routing convergence algorithm
2861 converge_distance (const GNUNET_HashCode *target,
2862 struct PeerInfo *peer,
2865 unsigned long long ret;
2866 unsigned int other_matching_bits;
2867 double converge_modifier = 0.0;
2868 double base_converge_modifier = .1;
2874 curr_max_hops = max_hops;
2876 curr_max_hops = (estimate_diameter() + 1) * 2;
2878 if (converge_modifier > 0)
2879 converge_modifier = converge_modifier * base_converge_modifier;
2882 converge_modifier = base_converge_modifier;
2883 base_converge_modifier = 0.0;
2886 GNUNET_assert(converge_modifier > 0);
2888 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2890 switch (converge_option)
2892 case DHT_CONVERGE_RANDOM:
2893 return 1; /* Always return 1, choose equally among all peers */
2894 case DHT_CONVERGE_LINEAR:
2895 calc_value = hops * curr_max_hops * converge_modifier;
2897 case DHT_CONVERGE_SQUARE:
2899 * Simple square based curve.
2901 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * converge_modifier));
2903 case DHT_CONVERGE_EXPONENTIAL:
2905 * Simple exponential curve.
2907 if (base_converge_modifier > 0)
2908 calc_value = (converge_modifier * hops * hops) / curr_max_hops;
2910 calc_value = (hops * hops) / curr_max_hops;
2916 /* Take the log (base e) of the number of bits matching the other peer */
2917 exponent = log(other_matching_bits);
2919 /* Check if we would overflow; our largest possible value is 2^64 = e^44.361419555836498 */
2920 if (exponent * calc_value >= 44.361419555836498)
2923 /* Clear errno and all math exceptions */
2925 feclearexcept(FE_ALL_EXCEPT);
2926 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2927 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2930 if (0 != fetestexcept(FE_OVERFLOW))
2931 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2932 if (0 != fetestexcept(FE_INVALID))
2933 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2934 if (0 != fetestexcept(FE_UNDERFLOW))
2935 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2943 * Comparison function for two struct PeerInfo's
2944 * which have already had their matching bits to
2945 * some target calculated.
2947 * @param p1 a pointer pointer to a struct PeerInfo
2948 * @param p2 a pointer pointer to a struct PeerInfo
2950 * @return 0 if equidistant to target,
2951 * -1 if p1 is closer,
2955 compare_peers (const void *p1, const void *p2)
2957 struct PeerInfo **first = (struct PeerInfo **)p1;
2958 struct PeerInfo **second = (struct PeerInfo **)p2;
2960 if ((*first)->matching_bits > (*second)->matching_bits)
2962 if ((*first)->matching_bits < (*second)->matching_bits)
2970 * Select a peer from the routing table that would be a good routing
2971 * destination for sending a message for "target". The resulting peer
2972 * must not be in the set of blocked peers.<p>
2974 * Note that we should not ALWAYS select the closest peer to the
2975 * target, peers further away from the target should be chosen with
2976 * exponentially declining probability.
2978 * @param target the key we are selecting a peer to route to
2979 * @param bloom a bloomfilter containing entries this request has seen already
2981 * @return Peer to route to, or NULL on error
2983 static struct PeerInfo *
2984 select_peer (const GNUNET_HashCode * target,
2985 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2990 unsigned int offset;
2991 unsigned int my_matching_bits;
2993 struct PeerInfo *pos;
2994 struct PeerInfo *sorted_closest[bucket_size];
2995 unsigned long long temp_converge_distance;
2996 unsigned long long total_distance;
2997 unsigned long long selected;
2999 unsigned long long stats_total_distance;
3003 unsigned int distance;
3004 unsigned int largest_distance;
3005 struct PeerInfo *chosen;
3007 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
3010 if (strict_kademlia == GNUNET_YES)
3012 largest_distance = 0;
3014 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3016 pos = k_buckets[bc].head;
3018 while ((pos != NULL) && (count < bucket_size))
3020 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3021 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3023 distance = inverse_distance (target, &pos->id.hashPubKey);
3024 if (distance > largest_distance)
3027 largest_distance = distance;
3035 if ((largest_distance > 0) && (chosen != NULL))
3037 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
3048 /* Three steps: order peers in closest bucket (most matching bits).
3049 * Then go over all LOWER buckets (matching same bits we do)
3050 * Then go over all HIGHER buckets (matching less then we do)
3053 closest_bucket = find_current_bucket(target);
3054 GNUNET_assert(closest_bucket >= lowest_bucket);
3055 pos = k_buckets[closest_bucket].head;
3057 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3058 memset(sorted_closest, 0, sizeof(sorted_closest));
3059 /* Put any peers in the closest bucket in the sorting array */
3060 while ((pos != NULL) && (count < bucket_size))
3062 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3066 continue; /* Ignore bloomfiltered peers */
3068 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
3069 sorted_closest[offset] = pos;
3075 /* Sort the peers in descending order */
3076 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
3078 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3079 for (i = 0; i < offset; i++)
3081 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3082 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3083 break; /* Ignore bloomfiltered peers */
3084 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3085 total_distance += temp_converge_distance;
3087 break; /* overflow case */
3090 /* Now handle peers in lower buckets (matches same # of bits as target) */
3091 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3093 pos = k_buckets[bc].head;
3095 while ((pos != NULL) && (count < bucket_size))
3097 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3101 continue; /* Ignore bloomfiltered peers */
3103 temp_converge_distance = converge_distance(target, pos, hops);
3104 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3105 total_distance += temp_converge_distance;
3107 break; /* overflow case */
3113 /* Now handle all the further away peers */
3114 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3116 pos = k_buckets[bc].head;
3118 while ((pos != NULL) && (count < bucket_size))
3120 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3124 continue; /* Ignore bloomfiltered peers */
3126 temp_converge_distance = converge_distance(target, pos, hops);
3127 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3128 total_distance += temp_converge_distance;
3130 break; /* overflow case */
3136 if (total_distance == 0) /* No peers to select from! */
3138 increment_stats("# select_peer, total_distance == 0");
3142 #if DEBUG_DHT_ROUTING > 1
3145 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3146 stats_total_distance = 0;
3147 for (i = 0; i < offset; i++)
3149 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3150 break; /* Ignore bloomfiltered peers */
3151 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3152 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3153 stats_total_distance += temp_converge_distance;
3155 break; /* overflow case */
3156 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);
3159 /* Now handle peers in lower buckets (matches same # of bits as target) */
3160 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3162 pos = k_buckets[bc].head;
3164 while ((pos != NULL) && (count < bucket_size))
3166 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3170 continue; /* Ignore bloomfiltered peers */
3172 temp_converge_distance = converge_distance(target, pos, hops);
3173 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3174 stats_total_distance += temp_converge_distance;
3176 break; /* overflow case */
3177 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);
3183 /* Now handle all the further away peers */
3184 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3186 pos = k_buckets[bc].head;
3188 while ((pos != NULL) && (count < bucket_size))
3190 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3194 continue; /* Ignore bloomfiltered peers */
3196 temp_converge_distance = converge_distance(target, pos, hops);
3197 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3198 stats_total_distance += temp_converge_distance;
3200 break; /* overflow case */
3201 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);
3206 /* END PRINT STATS */
3209 /* Now actually choose a peer */
3210 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3212 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3213 for (i = 0; i < offset; i++)
3215 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3216 break; /* Ignore bloomfiltered peers */
3217 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3218 if (temp_converge_distance >= selected)
3219 return sorted_closest[i];
3221 selected -= temp_converge_distance;
3224 /* Now handle peers in lower buckets (matches same # of bits as target) */
3225 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3227 pos = k_buckets[bc].head;
3229 while ((pos != NULL) && (count < bucket_size))
3231 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3235 continue; /* Ignore bloomfiltered peers */
3237 temp_converge_distance = converge_distance(target, pos, hops);
3238 if (temp_converge_distance >= selected)
3241 selected -= temp_converge_distance;
3247 /* Now handle all the further away peers */
3248 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3250 pos = k_buckets[bc].head;
3252 while ((pos != NULL) && (count < bucket_size))
3254 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3258 continue; /* Ignore bloomfiltered peers */
3260 temp_converge_distance = converge_distance(target, pos, hops);
3261 if (temp_converge_distance >= selected)
3264 selected -= temp_converge_distance;
3270 increment_stats("# failed to select peer");
3276 * Task used to remove recent entries, either
3277 * after timeout, when full, or on shutdown.
3279 * @param cls the entry to remove
3280 * @param tc context, reason, etc.
3283 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3285 struct RecentRequest *req = cls;
3286 static GNUNET_HashCode hash;
3288 GNUNET_assert(req != NULL);
3289 hash_from_uid(req->uid, &hash);
3290 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3291 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3292 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3295 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3297 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3298 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3304 * Task used to remove forwarding entries, either
3305 * after timeout, when full, or on shutdown.
3307 * @param cls the entry to remove
3308 * @param tc context, reason, etc.
3311 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3313 struct DHTRouteSource *source_info = cls;
3314 struct DHTQueryRecord *record;
3315 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3316 record = source_info->record;
3317 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3319 if (record->head == NULL) /* No more entries in DLL */
3321 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3322 GNUNET_free(record);
3324 if (source_info->find_peers_responded != NULL)
3325 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3326 GNUNET_free(source_info);
3330 * Remember this routing request so that if a reply is
3331 * received we can either forward it to the correct peer
3332 * or return the result locally.
3334 * @param cls DHT service closure
3335 * @param msg_ctx Context of the route request
3337 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3339 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
3341 struct DHTQueryRecord *record;
3342 struct DHTRouteSource *source_info;
3343 struct DHTRouteSource *pos;
3344 struct GNUNET_TIME_Absolute now;
3345 unsigned int current_size;
3347 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3348 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3350 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3351 GNUNET_assert(source_info != NULL);
3352 record = source_info->record;
3353 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3354 if (record->head == NULL) /* No more entries in DLL */
3356 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3357 GNUNET_free(record);
3359 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
3360 if (source_info->find_peers_responded != NULL)
3361 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3362 GNUNET_free(source_info);
3363 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3365 now = GNUNET_TIME_absolute_get();
3366 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3367 if (record != NULL) /* Already know this request! */
3372 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3373 break; /* Already have this peer in reply list! */
3376 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3378 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3384 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3385 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3386 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3389 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3390 source_info->record = record;
3391 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3392 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3393 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3394 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3395 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3397 source_info->client = msg_ctx->client;
3398 now = GNUNET_TIME_absolute_get_forever();
3400 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3402 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3403 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3404 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3411 * Main function that handles whether or not to route a message to other
3414 * @param msg the message to be routed
3415 * @param message_context the context containing all pertinent information about the message
3418 route_message2(const struct GNUNET_MessageHeader *msg,
3419 struct DHT_MessageContext *message_context)
3422 struct PeerInfo *selected;
3423 #if DEBUG_DHT_ROUTING > 1
3424 struct PeerInfo *nearest;
3426 unsigned int forward_count;
3427 struct RecentRequest *recent_req;
3428 GNUNET_HashCode unique_hash;
3429 char *stat_forward_count;
3430 char *temp_stat_str;
3431 #if DEBUG_DHT_ROUTING
3435 if (malicious_dropper == GNUNET_YES)
3437 #if DEBUG_DHT_ROUTING
3438 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3440 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3441 message_context->hop_count, GNUNET_SYSERR,
3442 &my_identity, &message_context->key, message_context->peer,
3446 if (message_context->bloom != NULL)
3447 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3451 increment_stats(STAT_ROUTES);
3452 /* Semantics of this call means we find whether we are the closest peer out of those already
3453 * routed to on this messages path.
3455 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3456 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3457 increment_stats(stat_forward_count);
3458 GNUNET_free(stat_forward_count);
3459 if (message_context->bloom == NULL)
3460 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3462 if ((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3466 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3467 * any closer peers (which is being checked for below). Since we are doing recursive
3468 * routing we have no choice but to stop forwarding in this case. This means that at
3469 * any given step the request may NOT be forwarded to alpha peers (because routes will
3470 * stop and the parallel route will not be aware of it). Of course, assuming that we
3471 * have fulfilled the Kademlia requirements for routing table fullness this will never
3472 * ever ever be a problem.
3474 * However, is this fair?
3476 * Since we use these requests to build our routing tables (and we build them in the
3477 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3478 * routing tables still get constructed.
3480 if ((GNUNET_YES == strict_kademlia) && (message_context->closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3483 #if DEBUG_DHT_ROUTING
3484 if (forward_count == 0)
3485 ret = GNUNET_SYSERR;
3489 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3491 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3492 message_context->hop_count, ret,
3493 &my_identity, &message_context->key, message_context->peer,
3499 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3500 hash_from_uid (message_context->unique_id, &unique_hash);
3501 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3503 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3504 GNUNET_assert(recent_req != NULL);
3505 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3506 increment_stats(STAT_DUPLICATE_UID);
3509 increment_stats(STAT_RECENT_SEEN);
3510 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3515 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3516 recent_req->uid = message_context->unique_id;
3517 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3518 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3519 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3520 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3521 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3524 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3526 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3527 GNUNET_assert(recent_req != NULL);
3528 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3529 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3532 for (i = 0; i < forward_count; i++)
3534 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3536 if (selected != NULL)
3538 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &message_context->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &message_context->key))
3539 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", message_context->hop_count);
3541 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", message_context->hop_count);
3542 if (temp_stat_str != NULL)
3544 increment_stats(temp_stat_str);
3545 GNUNET_free(temp_stat_str);
3547 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3548 #if DEBUG_DHT_ROUTING > 1
3549 nearest = find_closest_peer(&message_context->key);
3550 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3551 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3552 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3553 "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));
3554 GNUNET_free(nearest_buf);
3556 #if DEBUG_DHT_ROUTING
3557 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3559 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3560 message_context->hop_count, GNUNET_NO,
3561 &my_identity, &message_context->key, message_context->peer,
3565 forward_message(msg, selected, message_context);
3569 if (message_context->bloom != NULL)
3571 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3572 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3579 * Main function that handles whether or not to route a message to other
3582 * @param cls closure for dht service (NULL)
3583 * @param msg the message to be routed
3584 * @param message_context the context containing all pertinent information about the message
3587 route_message(void *cls,
3588 const struct GNUNET_MessageHeader *msg,
3589 struct DHT_MessageContext *message_context)
3591 message_context->closest = am_closest_peer(&message_context->key, NULL);
3592 switch (ntohs(msg->type))
3594 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3595 cache_response (cls, message_context);
3596 handle_dht_get (cls, msg, message_context);
3598 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3599 increment_stats(STAT_PUTS);
3600 handle_dht_put (cls, msg, message_context);
3602 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3603 increment_stats(STAT_FIND_PEER);
3604 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3606 cache_response (cls, message_context);
3607 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3608 handle_dht_find_peer (cls, msg, message_context);
3610 #if DEBUG_DHT_ROUTING
3611 if (message_context->hop_count == 0) /* Locally initiated request */
3613 if ((debug_routes) && (dhtlog_handle != NULL))
3615 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3616 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3617 message_context->hop_count, GNUNET_NO, &my_identity,
3618 &message_context->key);
3624 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3625 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3626 route_message (cls, msg, message_context);
3634 * Iterator for local get request results,
3636 * @param cls closure for iterator, NULL
3637 * @param exp when does this value expire?
3638 * @param key the key this data is stored under
3639 * @param size the size of the data identified by key
3640 * @param data the actual data
3641 * @param type the type of the data
3643 * @return GNUNET_OK to continue iteration, anything else
3644 * to stop iteration.
3647 republish_content_iterator (void *cls,
3648 struct GNUNET_TIME_Absolute exp,
3649 const GNUNET_HashCode * key,
3650 uint32_t size, const char *data, uint32_t type)
3653 struct DHT_MessageContext *new_msg_ctx;
3654 struct GNUNET_DHT_PutMessage *put_msg;
3656 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3657 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3659 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3662 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3663 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3664 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3665 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3666 put_msg->type = htons (type);
3667 memcpy (&put_msg[1], data, size);
3668 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3669 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3670 new_msg_ctx->msg_options = ntohl (0);
3671 new_msg_ctx->network_size = estimate_diameter();
3672 new_msg_ctx->peer = &my_identity;
3673 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3674 new_msg_ctx->hop_count = 0;
3675 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3676 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3677 increment_stats(STAT_PUT_START);
3678 route_message(cls, &put_msg->header, new_msg_ctx);
3680 GNUNET_free(new_msg_ctx);
3681 GNUNET_free (put_msg);
3686 * Task used to republish data.
3688 * @param cls closure (a struct RepublishContext)
3689 * @param tc runtime context for this task
3692 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3694 struct RepublishContext *put_context = cls;
3696 unsigned int results;
3698 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3700 GNUNET_free(put_context);
3704 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3705 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3706 if (results == 0) /* Data must have expired */
3707 GNUNET_free(put_context);
3708 else /* Reschedule task for next time period */
3709 GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);
3715 * Iterator over hash map entries.
3717 * @param cls client to search for in source routes
3718 * @param key current key code (ignored)
3719 * @param value value in the hash map, a DHTQueryRecord
3720 * @return GNUNET_YES if we should continue to
3724 static int find_client_records (void *cls,
3725 const GNUNET_HashCode * key, void *value)
3727 struct ClientList *client = cls;
3728 struct DHTQueryRecord *record = value;
3729 struct DHTRouteSource *pos;
3733 if (pos->client == client)
3739 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3740 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3741 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3742 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3744 if (pos->find_peers_responded != NULL)
3745 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3748 if (record->head == NULL) /* No more entries in DLL */
3750 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3751 GNUNET_free(record);
3757 * Functions with this signature are called whenever a client
3758 * is disconnected on the network level.
3760 * @param cls closure (NULL for dht)
3761 * @param client identification of the client; NULL
3762 * for the last call when the server is destroyed
3764 static void handle_client_disconnect (void *cls,
3765 struct GNUNET_SERVER_Client* client)
3767 struct ClientList *pos = client_list;
3768 struct ClientList *prev;
3769 struct ClientList *found;
3770 struct PendingMessage *reply;
3776 if (pos->client_handle == client)
3779 prev->next = pos->next;
3781 client_list = pos->next;
3791 while(NULL != (reply = found->pending_head))
3793 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3796 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3802 * Find a client if it exists, add it otherwise.
3804 * @param client the server handle to the client
3806 * @return the client if found, a new client otherwise
3808 static struct ClientList *
3809 find_active_client (struct GNUNET_SERVER_Client *client)
3811 struct ClientList *pos = client_list;
3812 struct ClientList *ret;
3816 if (pos->client_handle == client)
3821 ret = GNUNET_malloc (sizeof (struct ClientList));
3822 ret->client_handle = client;
3823 ret->next = client_list;
3830 * Task to send a malicious put message across the network.
3832 * @param cls closure for this task
3833 * @param tc the context under which the task is running
3836 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3838 static struct GNUNET_DHT_PutMessage put_message;
3839 static struct DHT_MessageContext message_context;
3840 static GNUNET_HashCode key;
3841 uint32_t random_key;
3843 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3846 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3847 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3848 put_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3849 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3850 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3851 message_context.client = NULL;
3852 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3853 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3854 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3855 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3856 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3857 message_context.msg_options = ntohl (0);
3858 message_context.network_size = estimate_diameter();
3859 message_context.peer = &my_identity;
3860 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3861 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3862 #if DEBUG_DHT_ROUTING
3863 if (dhtlog_handle != NULL)
3864 dhtlog_handle->insert_dhtkey(NULL, &key);
3866 increment_stats(STAT_PUT_START);
3867 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3868 route_message(NULL, &put_message.header, &message_context);
3869 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3874 * Task to send a malicious put message across the network.
3876 * @param cls closure for this task
3877 * @param tc the context under which the task is running
3880 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3882 static struct GNUNET_DHT_GetMessage get_message;
3883 struct DHT_MessageContext message_context;
3884 static GNUNET_HashCode key;
3885 uint32_t random_key;
3887 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3890 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3891 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3892 get_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3893 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3894 message_context.client = NULL;
3895 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3896 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3897 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3898 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3899 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3900 message_context.msg_options = ntohl (0);
3901 message_context.network_size = estimate_diameter();
3902 message_context.peer = &my_identity;
3903 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3904 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3905 #if DEBUG_DHT_ROUTING
3906 if (dhtlog_handle != NULL)
3907 dhtlog_handle->insert_dhtkey(NULL, &key);
3909 increment_stats(STAT_GET_START);
3910 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3911 route_message (NULL, &get_message.header, &message_context);
3912 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3916 * Iterator over hash map entries.
3918 * @param cls closure
3919 * @param key current key code
3920 * @param value value in the hash map
3921 * @return GNUNET_YES if we should continue to
3926 add_known_to_bloom (void *cls,
3927 const GNUNET_HashCode * key,
3930 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3931 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3936 * Task to send a find peer message for our own peer identifier
3937 * so that we can find the closest peers in the network to ourselves
3938 * and attempt to connect to them.
3940 * @param cls closure for this task
3941 * @param tc the context under which the task is running
3944 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3946 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3947 struct DHT_MessageContext message_context;
3948 struct GNUNET_TIME_Relative next_send_time;
3949 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3951 struct GNUNET_TIME_Relative time_diff;
3952 struct GNUNET_TIME_Absolute end;
3954 double count_per_interval;
3956 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3959 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! */
3961 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3962 GNUNET_SCHEDULER_add_delayed (sched,
3963 GNUNET_TIME_UNIT_MINUTES,
3964 &send_find_peer_message, NULL);
3965 newly_found_peers = 0;
3969 increment_stats(STAT_FIND_PEER_START);
3971 end = GNUNET_TIME_absolute_get();
3972 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3974 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3976 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3977 count_per_interval = find_peer_context.count / multiplier;
3981 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3982 count_per_interval = find_peer_context.count * multiplier;
3986 #if FIND_PEER_WITH_HELLO
3987 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3988 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3989 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3991 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3992 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3994 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3995 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3996 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3997 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3998 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3999 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
4000 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
4001 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4002 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4003 message_context.network_size = estimate_diameter();
4004 message_context.peer = &my_identity;
4005 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4006 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4008 route_message(NULL, &find_peer_msg->header, &message_context);
4009 GNUNET_free(find_peer_msg);
4010 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4011 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
4013 if (newly_found_peers < bucket_size)
4015 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
4016 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4017 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
4021 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4022 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4023 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4026 GNUNET_assert (next_send_time.value != 0);
4027 find_peer_context.count = 0;
4028 newly_found_peers = 0;
4029 find_peer_context.start = GNUNET_TIME_absolute_get();
4030 if (GNUNET_YES == do_find_peer)
4032 GNUNET_SCHEDULER_add_delayed (sched,
4034 &send_find_peer_message, NULL);
4039 * Handler for any generic DHT messages, calls the appropriate handler
4040 * depending on message type, sends confirmation if responses aren't otherwise
4043 * @param cls closure for the service
4044 * @param client the client we received this message from
4045 * @param message the actual message received
4048 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4049 const struct GNUNET_MessageHeader *message)
4051 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
4052 const struct GNUNET_MessageHeader *enc_msg;
4053 struct DHT_MessageContext message_context;
4055 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4057 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4058 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4062 ntohs (message->type),
4063 GNUNET_h2s (&dht_msg->key),
4064 GNUNET_ntohll (dht_msg->unique_id));
4066 #if DEBUG_DHT_ROUTING
4067 if (dhtlog_handle != NULL)
4068 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4070 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4071 message_context.client = find_active_client (client);
4072 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
4073 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4074 message_context.replication = ntohl (dht_msg->desired_replication_level);
4075 message_context.msg_options = ntohl (dht_msg->options);
4076 message_context.network_size = estimate_diameter();
4077 message_context.peer = &my_identity;
4078 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
4079 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4080 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4081 increment_stats(STAT_GET_START);
4082 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4083 increment_stats(STAT_PUT_START);
4084 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4085 increment_stats(STAT_FIND_PEER_START);
4087 route_message(cls, enc_msg, &message_context);
4089 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4094 * Handler for any locally received DHT control messages,
4095 * sets malicious flags mostly for now.
4097 * @param cls closure for the service
4098 * @param client the client we received this message from
4099 * @param message the actual message received
4103 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4104 const struct GNUNET_MessageHeader *message)
4106 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4107 (const struct GNUNET_DHT_ControlMessage *) message;
4109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4110 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4111 "CONTROL", ntohs(dht_control_msg->command));
4114 switch (ntohs(dht_control_msg->command))
4116 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4117 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4118 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
4120 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4121 if (ntohs(dht_control_msg->variable) > 0)
4122 malicious_get_frequency = ntohs(dht_control_msg->variable);
4123 if (malicious_get_frequency == 0)
4124 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4125 if (malicious_getter != GNUNET_YES)
4126 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
4127 malicious_getter = GNUNET_YES;
4128 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4129 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4131 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4132 if (ntohs(dht_control_msg->variable) > 0)
4133 malicious_put_frequency = ntohs(dht_control_msg->variable);
4134 if (malicious_put_frequency == 0)
4135 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4136 if (malicious_putter != GNUNET_YES)
4137 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
4138 malicious_putter = GNUNET_YES;
4139 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4140 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4142 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4143 #if DEBUG_DHT_ROUTING
4144 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4145 dhtlog_handle->set_malicious(&my_identity);
4147 malicious_dropper = GNUNET_YES;
4148 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4149 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4152 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4153 "%s:%s Unknown control command type `%d'!\n",
4155 ntohs(dht_control_msg->command));
4159 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4163 * Handler for any generic DHT stop messages, calls the appropriate handler
4164 * depending on message type (if processed locally)
4166 * @param cls closure for the service
4167 * @param client the client we received this message from
4168 * @param message the actual message received
4172 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4173 const struct GNUNET_MessageHeader *message)
4176 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4177 (const struct GNUNET_DHT_StopMessage *) message;
4178 struct DHTQueryRecord *record;
4179 struct DHTRouteSource *pos;
4181 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4182 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4183 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4185 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
4192 if ((pos->client != NULL) && (pos->client->client_handle == client))
4194 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
4195 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
4201 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4206 * Core handler for p2p route requests.
4209 handle_dht_p2p_route_request (void *cls,
4210 const struct GNUNET_PeerIdentity *peer,
4211 const struct GNUNET_MessageHeader *message,
4212 struct GNUNET_TIME_Relative latency, uint32_t distance)
4215 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4216 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4218 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4219 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4220 struct DHT_MessageContext *message_context;
4222 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
4224 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending of previous replies took too long, backing off!\n");
4225 increment_stats("# route requests dropped due to high load");
4226 decrease_max_send_delay(get_max_send_delay());
4230 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4233 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4238 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4243 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4244 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4245 GNUNET_assert(message_context->bloom != NULL);
4246 message_context->hop_count = ntohl(incoming->hop_count);
4247 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
4248 message_context->replication = ntohl(incoming->desired_replication_level);
4249 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
4250 message_context->msg_options = ntohl(incoming->options);
4251 message_context->network_size = ntohl(incoming->network_size);
4252 message_context->peer = peer;
4253 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4254 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4255 route_message(cls, enc_msg, message_context);
4256 GNUNET_free(message_context);
4262 * Core handler for p2p route results.
4265 handle_dht_p2p_route_result (void *cls,
4266 const struct GNUNET_PeerIdentity *peer,
4267 const struct GNUNET_MessageHeader *message,
4268 struct GNUNET_TIME_Relative latency, uint32_t distance)
4271 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4272 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4274 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4275 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4276 struct DHT_MessageContext message_context;
4278 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4284 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
4285 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4286 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4287 GNUNET_assert(message_context.bloom != NULL);
4288 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
4289 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
4290 message_context.msg_options = ntohl(incoming->options);
4291 message_context.hop_count = ntohl(incoming->hop_count);
4292 message_context.peer = peer;
4293 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
4294 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4295 route_result_message(cls, enc_msg, &message_context);
4301 * Receive the HELLO from transport service,
4302 * free current and replace if necessary.
4305 * @param message HELLO message of peer
4308 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4312 "Received our `%s' from transport service\n",
4316 GNUNET_assert (message != NULL);
4317 GNUNET_free_non_null(my_hello);
4318 my_hello = GNUNET_malloc(ntohs(message->size));
4319 memcpy(my_hello, message, ntohs(message->size));
4324 * Task run during shutdown.
4330 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4333 struct PeerInfo *pos;
4335 if (transport_handle != NULL)
4337 GNUNET_free_non_null(my_hello);
4338 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4339 GNUNET_TRANSPORT_disconnect(transport_handle);
4341 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4343 while (k_buckets[bucket_count].head != NULL)
4345 pos = k_buckets[bucket_count].head;
4347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4348 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4350 delete_peer(pos, bucket_count);
4353 if (coreAPI != NULL)
4356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4357 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4359 GNUNET_CORE_disconnect (coreAPI);
4362 if (datacache != NULL)
4365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4366 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4368 GNUNET_DATACACHE_destroy (datacache);
4373 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4376 if (dhtlog_handle != NULL)
4378 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4379 dhtlog_handle = NULL;
4381 if (block_context != NULL)
4383 GNUNET_BLOCK_context_destroy (block_context);
4384 block_context = NULL;
4386 GNUNET_free_non_null(my_short_id);
4392 * To be called on core init/fail.
4394 * @param cls service closure
4395 * @param server handle to the server for this service
4396 * @param identity the public identity of this peer
4397 * @param publicKey the public key of this peer
4400 core_init (void *cls,
4401 struct GNUNET_CORE_Handle *server,
4402 const struct GNUNET_PeerIdentity *identity,
4403 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4410 "%s: Connection to core FAILED!\n", "dht",
4411 GNUNET_i2s (identity));
4413 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
4414 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
4418 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4419 "%s: Core connection initialized, I am peer: %s\n", "dht",
4420 GNUNET_i2s (identity));
4423 /* Copy our identity so we can use it */
4424 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4425 if (my_short_id != NULL)
4426 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4427 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4428 /* Set the server to local variable */
4431 if (dhtlog_handle != NULL)
4432 dhtlog_handle->insert_node (NULL, &my_identity);
4436 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4437 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4438 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4439 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4444 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4445 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4446 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4452 * Method called whenever a peer connects.
4454 * @param cls closure
4455 * @param peer peer identity this notification is about
4456 * @param latency reported latency of the connection with peer
4457 * @param distance reported distance (DV) to peer
4459 void handle_core_connect (void *cls,
4460 const struct GNUNET_PeerIdentity * peer,
4461 struct GNUNET_TIME_Relative latency,
4464 struct PeerInfo *ret;
4467 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4468 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4471 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4473 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));
4477 if (datacache != NULL)
4478 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, GNUNET_BLOCK_TYPE_DHT_HELLO, GNUNET_TIME_absolute_get_forever());
4479 ret = try_add_peer(peer,
4480 find_current_bucket(&peer->hashPubKey),
4485 newly_found_peers++;
4486 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4489 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4490 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4496 * Method called whenever a peer disconnects.
4498 * @param cls closure
4499 * @param peer peer identity this notification is about
4501 void handle_core_disconnect (void *cls,
4503 GNUNET_PeerIdentity * peer)
4505 struct PeerInfo *to_remove;
4508 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");
4510 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4512 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));
4515 increment_stats(STAT_DISCONNECTS);
4516 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4517 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4518 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4519 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4520 delete_peer(to_remove, current_bucket);
4525 * Process dht requests.
4527 * @param cls closure
4528 * @param scheduler scheduler to use
4529 * @param server the initialized server
4530 * @param c configuration to use
4534 struct GNUNET_SCHEDULER_Handle *scheduler,
4535 struct GNUNET_SERVER_Handle *server,
4536 const struct GNUNET_CONFIGURATION_Handle *c)
4538 struct GNUNET_TIME_Relative next_send_time;
4539 unsigned long long temp_config_num;
4540 char *converge_modifier_buf;
4544 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4545 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4546 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4547 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4548 cfg, /* Main configuration */
4549 GNUNET_TIME_UNIT_FOREVER_REL,
4550 NULL, /* Closure passed to DHT functions */
4551 &core_init, /* Call core_init once connected */
4552 &handle_core_connect, /* Handle connects */
4553 &handle_core_disconnect, /* remove peers on disconnects */
4554 NULL, /* Do we care about "status" updates? */
4555 NULL, /* Don't want notified about all incoming messages */
4556 GNUNET_NO, /* For header only inbound notification */
4557 NULL, /* Don't want notified about all outbound messages */
4558 GNUNET_NO, /* For header only outbound notification */
4559 core_handlers); /* Register these handlers */
4561 if (coreAPI == NULL)
4563 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
4564 NULL, NULL, NULL, NULL, NULL);
4565 if (transport_handle != NULL)
4566 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4568 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4569 "Failed to connect to transport service!\n");
4570 block_context = GNUNET_BLOCK_context_create (cfg);
4571 lowest_bucket = MAX_BUCKETS - 1;
4572 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4573 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4574 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4575 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4576 GNUNET_assert(all_known_peers != NULL);
4577 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4579 debug_routes = GNUNET_YES;
4583 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4586 strict_kademlia = GNUNET_YES;
4590 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4593 stop_on_closest = GNUNET_YES;
4597 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4600 stop_on_found = GNUNET_YES;
4604 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4605 "malicious_getter"))
4607 malicious_getter = GNUNET_YES;
4608 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4609 "MALICIOUS_GET_FREQUENCY",
4610 &malicious_get_frequency))
4611 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4614 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4618 max_hops = DEFAULT_MAX_HOPS;
4621 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4624 use_max_hops = GNUNET_YES;
4628 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4629 "malicious_putter"))
4631 malicious_putter = GNUNET_YES;
4632 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4633 "MALICIOUS_PUT_FREQUENCY",
4634 &malicious_put_frequency))
4635 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4638 dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
4639 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4641 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4645 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4646 "malicious_dropper"))
4648 malicious_dropper = GNUNET_YES;
4652 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4654 do_republish = GNUNET_NO;
4657 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4660 do_find_peer = GNUNET_NO;
4663 do_find_peer = GNUNET_YES;
4666 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4667 "use_real_distance"))
4668 use_real_distance = GNUNET_YES;
4671 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4672 "mysql_logging_extended"))
4674 debug_routes = GNUNET_YES;
4675 debug_routes_extended = GNUNET_YES;
4678 #if DEBUG_DHT_ROUTING
4679 if (GNUNET_YES == debug_routes)
4681 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4682 if (dhtlog_handle == NULL)
4684 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4685 "Could not connect to mysql logging server, logging will not happen!");
4690 converge_option = DHT_CONVERGE_SQUARE;
4692 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4695 converge_option = DHT_CONVERGE_LINEAR;
4697 else if (GNUNET_YES ==
4698 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4699 "converge_exponential"))
4701 converge_option = DHT_CONVERGE_EXPONENTIAL;
4703 else if (GNUNET_YES ==
4704 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4707 converge_option = DHT_CONVERGE_RANDOM;
4710 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4712 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4714 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4715 converge_modifier = 0.0;
4717 GNUNET_free(converge_modifier_buf);
4720 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4724 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4725 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4726 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4727 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4728 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4729 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4730 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4731 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4732 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4733 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4734 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4735 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4736 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4737 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4738 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4739 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4740 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4741 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4742 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4743 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4745 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4746 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4747 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4748 if (GNUNET_YES == do_find_peer)
4750 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4751 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4752 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4753 find_peer_context.start = GNUNET_TIME_absolute_get();
4754 GNUNET_SCHEDULER_add_delayed (sched,
4756 &send_find_peer_message, &find_peer_context);
4759 /* Scheduled the task to clean up when shutdown is called */
4760 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4761 GNUNET_TIME_UNIT_FOREVER_REL,
4762 &shutdown_task, NULL);
4766 * The main function for the dht service.
4768 * @param argc number of arguments from the command line
4769 * @param argv command line arguments
4770 * @return 0 ok, 1 on error
4773 main (int argc, char *const *argv)
4778 GNUNET_SERVICE_run (argc,
4781 GNUNET_SERVICE_OPTION_NONE,
4782 &run, NULL)) ? 0 : 1;
4783 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);