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 GNUnet DHT service
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
74 #define DEFAULT_CORE_QUEUE_SIZE 32
77 * Minimum number of peers we need for "good" routing,
78 * any less than this and we will allow messages to
79 * travel much further through the network!
81 #define MINIMUM_PEER_THRESHOLD 20
83 #define DHT_MAX_RECENT 1000
85 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
88 * Default time to wait to send messages on behalf of other peers.
90 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
93 * Default importance for handling messages on behalf of other peers.
95 #define DHT_DEFAULT_P2P_IMPORTANCE 0
98 * How long to keep recent requests around by default.
100 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
103 * Default time to wait to send find peer messages sent by the dht service.
105 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
108 * Default importance for find peer messages sent by the dht service.
110 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
113 * Default replication parameter for find peer messages sent by the dht service.
115 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
118 * Default options for find peer requests sent by the dht service.
120 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
121 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
124 * How long at least to wait before sending another find peer request.
126 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
129 * How long at most to wait before sending another find peer request.
131 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
134 * How often to update our preference levels for peers in our routing tables.
136 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
139 * How long at most on average will we allow a reply forward to take
140 * (before we quit sending out new requests)
142 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
145 * How many initial requests to send out (in true Kademlia fashion)
147 #define DEFAULT_KADEMLIA_REPLICATION 3
150 * Default frequency for sending malicious get messages
152 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
155 * Default frequency for sending malicious put messages
157 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
160 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
163 * Real maximum number of hops, at which point we refuse
164 * to forward the message.
166 #define DEFAULT_MAX_HOPS 10
169 * How many time differences between requesting a core send and
170 * the actual callback to remember.
172 #define MAX_REPLY_TIMES 8
174 enum ConvergenceOptions
177 * Use the linear method for convergence.
182 * Converge using a fast converging square
188 * Converge using a slower exponential
191 DHT_CONVERGE_EXPONENTIAL,
194 * Don't do any special convergence, allow
195 * the algorithm to hopefully route to closer
201 * Binary convergence, start routing to closest
202 * only after set number of hops.
208 * Linked list of messages to send to clients.
210 struct P2PPendingMessage
213 * Pointer to next item in the list
215 struct P2PPendingMessage *next;
218 * Pointer to previous item in the list
220 struct P2PPendingMessage *prev;
223 * Message importance level.
225 unsigned int importance;
228 * Time when this request was scheduled to be sent.
230 struct GNUNET_TIME_Absolute scheduled;
233 * How long to wait before sending message.
235 struct GNUNET_TIME_Relative timeout;
238 * Actual message to be sent; // avoid allocation
240 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
245 * Per-peer information.
250 * Next peer entry (DLL)
252 struct PeerInfo *next;
255 * Prev peer entry (DLL)
257 struct PeerInfo *prev;
260 * Count of outstanding messages for peer.
262 unsigned int pending_count;
265 * Head of pending messages to be sent to this peer.
267 struct P2PPendingMessage *head;
270 * Tail of pending messages to be sent to this peer.
272 struct P2PPendingMessage *tail;
275 * Core handle for sending messages to this peer.
277 struct GNUNET_CORE_TransmitHandle *th;
280 * Task for scheduling message sends.
282 GNUNET_SCHEDULER_TaskIdentifier send_task;
285 * Task for scheduling preference updates
287 GNUNET_SCHEDULER_TaskIdentifier preference_task;
290 * Preference update context
292 struct GNUNET_CORE_InformationRequestContext *info_ctx;
295 * What is the identity of the peer?
297 struct GNUNET_PeerIdentity id;
301 * What is the average latency for replies received?
303 struct GNUNET_TIME_Relative latency;
306 * Transport level distance to peer.
308 unsigned int distance;
312 * Holds matching bits from peer to current target,
313 * used for distance comparisons between peers. May
314 * be considered a really bad idea.
315 * FIXME: remove this value (create struct which holds
316 * a single peerinfo and the matching bits, use
317 * that to pass to comparator)
319 unsigned int matching_bits;
322 * Task for scheduling periodic ping messages for this peer.
324 GNUNET_SCHEDULER_TaskIdentifier ping_task;
328 * Peers are grouped into buckets.
335 struct PeerInfo *head;
340 struct PeerInfo *tail;
343 * Number of peers in the bucket.
345 unsigned int peers_size;
349 * Linked list of messages to send to clients.
351 struct PendingMessage
354 * Pointer to next item in the list
356 struct PendingMessage *next;
359 * Pointer to previous item in the list
361 struct PendingMessage *prev;
364 * Actual message to be sent; // avoid allocation
366 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
371 * Struct containing information about a client,
372 * handle to connect to it, and any pending messages
373 * that need to be sent to it.
378 * Linked list of active clients
380 struct ClientList *next;
383 * The handle to this client
385 struct GNUNET_SERVER_Client *client_handle;
388 * Handle to the current transmission request, NULL
391 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
394 * Linked list of pending messages for this client
396 struct PendingMessage *pending_head;
399 * Tail of linked list of pending messages for this client
401 struct PendingMessage *pending_tail;
406 * Context containing information about a DHT message received.
408 struct DHT_MessageContext
411 * The client this request was received from.
412 * (NULL if received from another peer)
414 struct ClientList *client;
417 * The peer this request was received from.
418 * (NULL if received from local client)
420 const struct GNUNET_PeerIdentity *peer;
423 * Bloomfilter for this routing request.
425 struct GNUNET_CONTAINER_BloomFilter *bloom;
428 * extended query (see gnunet_block_lib.h).
433 * Bloomfilter to filter out duplicate replies.
435 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
438 * The key this request was about
443 * How long should we wait to transmit this request?
445 struct GNUNET_TIME_Relative timeout;
448 * The unique identifier of this request
453 * Number of bytes in xquery.
458 * Mutator value for the reply_bf, see gnunet_block_lib.h
460 uint32_t reply_bf_mutator;
463 * Desired replication level
465 uint32_t replication;
468 * Network size estimate, either ours or the sum of
469 * those routed to thus far. =~ Log of number of peers
470 * chosen from for this request.
472 uint32_t network_size;
475 * Any message options for this request
477 uint32_t msg_options;
480 * How many hops has the message already traversed?
485 * How important is this message?
487 unsigned int importance;
490 * Should we (still) forward the request on to other peers?
495 * Did we forward this message? (may need to remember it!)
500 * Are we the closest known peer to this key (out of our neighbors?)
506 * Record used for remembering what peers are waiting for what
507 * responses (based on search key).
509 struct DHTRouteSource
514 struct DHTRouteSource *next;
519 struct DHTRouteSource *prev;
522 * Source of the request. Replies should be forwarded to
525 struct GNUNET_PeerIdentity source;
528 * If this was a local request, remember the client; otherwise NULL.
530 struct ClientList *client;
533 * Pointer to this nodes heap location (for removal)
535 struct GNUNET_CONTAINER_HeapNode *hnode;
538 * Back pointer to the record storing this information.
540 struct DHTQueryRecord *record;
543 * Task to remove this entry on timeout.
545 GNUNET_SCHEDULER_TaskIdentifier delete_task;
548 * Bloomfilter of peers we have already sent back as
549 * replies to the initial request. Allows us to not
550 * forward the same peer multiple times for a find peer
553 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
558 * Entry in the DHT routing table.
560 struct DHTQueryRecord
563 * Head of DLL for result forwarding.
565 struct DHTRouteSource *head;
568 * Tail of DLL for result forwarding.
570 struct DHTRouteSource *tail;
573 * Key that the record concerns.
578 * GET message of this record (what we already forwarded?).
580 //DV_DHT_MESSAGE get; Try to get away with not saving this.
583 * Bloomfilter of the peers we've replied to so far
585 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
590 * Context used to calculate the number of find peer messages
591 * per X time units since our last scheduled find peer message
592 * was sent. If we have seen too many messages, delay or don't
595 struct FindPeerMessageContext
599 struct GNUNET_TIME_Absolute start;
601 struct GNUNET_TIME_Absolute end;
605 * DHT Routing results structure
610 * Min heap for removal upon reaching limit
612 struct GNUNET_CONTAINER_Heap *minHeap;
615 * Hashmap for fast key based lookup
617 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
622 * DHT structure for recent requests.
624 struct RecentRequests
627 * Min heap for removal upon reaching limit
629 struct GNUNET_CONTAINER_Heap *minHeap;
632 * Hashmap for key based lookup
634 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
640 * Position of this node in the min heap.
642 struct GNUNET_CONTAINER_HeapNode *heap_node;
645 * Bloomfilter containing entries for peers
646 * we forwarded this request to.
648 struct GNUNET_CONTAINER_BloomFilter *bloom;
651 * Timestamp of this request, for ordering
654 struct GNUNET_TIME_Absolute timestamp;
657 * Key of this request.
662 * Unique identifier for this request.
667 * Task to remove this entry on timeout.
669 GNUNET_SCHEDULER_TaskIdentifier remove_task;
672 struct RepublishContext
687 * Which kind of convergence will we be using?
689 static enum ConvergenceOptions converge_option;
692 * Modifier for the convergence function
694 static float converge_modifier;
697 * Recent requests by hash/uid and by time inserted.
699 static struct RecentRequests recent;
702 * Context to use to calculate find peer rates.
704 static struct FindPeerMessageContext find_peer_context;
707 * Don't use our routing algorithm, always route
708 * to closest peer; initially send requests to 3
711 static unsigned int strict_kademlia;
714 * Routing option to end routing when closest peer found.
716 static unsigned int stop_on_closest;
719 * Routing option to end routing when data is found.
721 static unsigned int stop_on_found;
724 * Whether DHT needs to manage find peer requests, or
725 * an external force will do it on behalf of the DHT.
727 static unsigned int do_find_peer;
730 * Once we have stored an item in the DHT, refresh it
731 * according to our republish interval.
733 static unsigned int do_republish;
736 * Use the "real" distance metric when selecting the
737 * next routing hop. Can be less accurate.
739 static unsigned int use_real_distance;
742 * How many peers have we added since we sent out our last
745 static unsigned int newly_found_peers;
748 * Container of active queries we should remember
750 static struct DHTResults forward_list;
753 * Handle to the datacache service (for inserting/retrieving data)
755 static struct GNUNET_DATACACHE_Handle *datacache;
758 * Handle for the statistics service.
760 struct GNUNET_STATISTICS_Handle *stats;
764 * The configuration the DHT service is running with
766 static const struct GNUNET_CONFIGURATION_Handle *cfg;
769 * Handle to the core service
771 static struct GNUNET_CORE_Handle *coreAPI;
774 * Handle to the transport service, for getting our hello
776 static struct GNUNET_TRANSPORT_Handle *transport_handle;
779 * The identity of our peer.
781 static struct GNUNET_PeerIdentity my_identity;
784 * Short id of the peer, for printing
786 static char *my_short_id;
791 static struct GNUNET_MessageHeader *my_hello;
794 * Task to run when we shut down, cleaning up all our trash
796 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
799 * The lowest currently used bucket.
801 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
804 * The maximum number of hops before we stop routing messages.
806 static unsigned long long max_hops;
809 * How often to republish content we have previously stored.
811 static struct GNUNET_TIME_Relative dht_republish_frequency;
814 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
816 static int use_max_hops;
819 * The buckets (Kademlia routing table, complete with growth).
820 * Array of size MAX_BUCKET_SIZE.
822 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
825 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
827 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
830 * Recently seen find peer requests.
832 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
835 * Maximum size for each bucket.
837 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
840 * List of active clients.
842 static struct ClientList *client_list;
845 * Handle to the DHT logger.
847 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
850 * Whether or not to send routing debugging information
851 * to the dht logging server
853 static unsigned int debug_routes;
856 * Whether or not to send FULL route information to
859 static unsigned int debug_routes_extended;
862 * GNUNET_YES or GNUNET_NO, whether or not to act as
863 * a malicious node which drops all messages
865 static unsigned int malicious_dropper;
868 * GNUNET_YES or GNUNET_NO, whether or not to act as
869 * a malicious node which sends out lots of GETS
871 static unsigned int malicious_getter;
874 * GNUNET_YES or GNUNET_NO, whether or not to act as
875 * a malicious node which sends out lots of PUTS
877 static unsigned int malicious_putter;
880 * Frequency for malicious get requests.
882 static unsigned long long malicious_get_frequency;
885 * Frequency for malicious put requests.
887 static unsigned long long malicious_put_frequency;
890 * Kademlia replication
892 static unsigned long long kademlia_replication;
895 * Reply times for requests, if we are busy, don't send any
898 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
901 * Current counter for replies.
903 static unsigned int reply_counter;
906 * Our handle to the BLOCK library.
908 static struct GNUNET_BLOCK_Context *block_context;
912 * Forward declaration.
915 send_generic_reply (void *cls, size_t size, void *buf);
918 /** Declare here so retry_core_send is aware of it */
920 core_transmit_notify (void *cls,
921 size_t size, void *buf);
924 * Convert unique ID to hash code.
926 * @param uid unique ID to convert
927 * @param hash set to uid (extended with zeros)
930 hash_from_uid (uint64_t uid,
931 GNUNET_HashCode *hash)
933 memset (hash, 0, sizeof(GNUNET_HashCode));
934 *((uint64_t*)hash) = uid;
939 * Calculate the average send time between messages so that we can
940 * ignore certain requests if we get too busy.
942 * @return the average time between asking core to send a message
943 * and when the buffer for copying it is passed
945 static struct GNUNET_TIME_Relative get_average_send_delay()
948 unsigned int divisor;
949 struct GNUNET_TIME_Relative average_time;
950 average_time = GNUNET_TIME_relative_get_zero();
952 for (i = 0; i < MAX_REPLY_TIMES; i++)
954 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
955 if (reply_times[i].abs_value == (uint64_t)0)
965 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
967 "Avg send delay: %u sends is %llu\n",
969 (unsigned long long) average_time.abs_value);
975 * Given the largest send delay, artificially decrease it
976 * so the next time around we may have a chance at sending
979 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
982 for (i = 0; i < MAX_REPLY_TIMES; i++)
984 if (reply_times[i].rel_value == max_time.rel_value)
986 reply_times[i].rel_value = reply_times[i].rel_value / 2;
993 * Find the maximum send time of the recently sent values.
995 * @return the average time between asking core to send a message
996 * and when the buffer for copying it is passed
998 static struct GNUNET_TIME_Relative get_max_send_delay()
1001 struct GNUNET_TIME_Relative max_time;
1002 max_time = GNUNET_TIME_relative_get_zero();
1004 for (i = 0; i < MAX_REPLY_TIMES; i++)
1006 if (reply_times[i].rel_value > max_time.rel_value)
1007 max_time.rel_value = reply_times[i].rel_value;
1010 if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
1011 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n",
1012 (unsigned long long) max_time.rel_value);
1017 increment_stats(const char *value)
1021 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
1026 * Try to send another message from our core send list
1029 try_core_send (void *cls,
1030 const struct GNUNET_SCHEDULER_TaskContext *tc)
1032 struct PeerInfo *peer = cls;
1033 struct P2PPendingMessage *pending;
1036 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
1038 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1041 if (peer->th != NULL)
1042 return; /* Message send already in progress */
1044 pending = peer->head;
1045 if (pending != NULL)
1047 ssize = ntohs(pending->msg->size);
1049 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1050 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
1051 "DHT", ssize, GNUNET_i2s(&peer->id));
1053 pending->scheduled = GNUNET_TIME_absolute_get();
1055 if (reply_counter >= MAX_REPLY_TIMES)
1057 peer->th = GNUNET_CORE_notify_transmit_ready (coreAPI, pending->importance,
1058 pending->timeout, &peer->id,
1059 ssize, &core_transmit_notify, peer);
1060 if (peer->th == NULL)
1061 increment_stats("# notify transmit ready failed");
1066 * Function called to send a request out to another peer.
1067 * Called both for locally initiated requests and those
1068 * received from other peers.
1070 * @param msg the encapsulated message
1071 * @param peer the peer to forward the message to
1072 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1075 forward_result_message (const struct GNUNET_MessageHeader *msg,
1076 struct PeerInfo *peer,
1077 struct DHT_MessageContext *msg_ctx)
1079 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1080 struct P2PPendingMessage *pending;
1084 increment_stats(STAT_RESULT_FORWARDS);
1085 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1086 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1087 psize = sizeof(struct P2PPendingMessage) + msize;
1088 pending = GNUNET_malloc(psize);
1089 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1090 pending->importance = DHT_SEND_PRIORITY;
1091 pending->timeout = GNUNET_TIME_relative_get_forever();
1092 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1093 result_message->header.size = htons(msize);
1094 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1095 result_message->put_path_length = htons(0); /* FIXME: implement */
1096 result_message->get_path_length = htons(0); /* FIXME: implement */
1097 result_message->options = htonl(msg_ctx->msg_options);
1098 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1099 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1100 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1101 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1102 memcpy(&result_message[1], msg, ntohs(msg->size));
1104 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));
1106 peer->pending_count++;
1107 increment_stats("# pending messages scheduled");
1108 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1109 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1110 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1115 * Called when core is ready to send a message we asked for
1116 * out to the destination.
1118 * @param cls closure (NULL)
1119 * @param size number of bytes available in buf
1120 * @param buf where the callee should write the message
1121 * @return number of bytes written to buf
1124 core_transmit_notify (void *cls,
1125 size_t size, void *buf)
1127 struct PeerInfo *peer = cls;
1129 struct P2PPendingMessage *pending;
1136 /* client disconnected */
1138 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1143 if (peer->head == NULL)
1147 pending = peer->head;
1148 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1149 msize = ntohs(pending->msg->size);
1153 memcpy (cbuf, pending->msg, msize);
1154 peer->pending_count--;
1155 increment_stats("# pending messages sent");
1156 GNUNET_assert(peer->pending_count >= 0);
1157 GNUNET_CONTAINER_DLL_remove (peer->head,
1160 GNUNET_free (pending);
1163 while (NULL != pending &&
1164 (size - off >= (msize = ntohs (pending->msg->size))))
1166 memcpy (&cbuf[off], pending->msg, msize);
1168 peer->pending_count--;
1169 GNUNET_assert(peer->pending_count >= 0);
1170 GNUNET_CONTAINER_DLL_remove (peer->head,
1173 GNUNET_free (pending);
1174 pending = peer->head;
1177 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1178 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1185 * Compute the distance between have and target as a 32-bit value.
1186 * Differences in the lower bits must count stronger than differences
1187 * in the higher bits.
1189 * @return 0 if have==target, otherwise a number
1190 * that is larger as the distance between
1191 * the two hash codes increases
1194 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1196 unsigned int bucket;
1201 /* We have to represent the distance between two 2^9 (=512)-bit
1202 numbers as a 2^5 (=32)-bit number with "0" being used for the
1203 two numbers being identical; furthermore, we need to
1204 guarantee that a difference in the number of matching
1205 bits is always represented in the result.
1207 We use 2^32/2^9 numerical values to distinguish between
1208 hash codes that have the same LSB bit distance and
1209 use the highest 2^9 bits of the result to signify the
1210 number of (mis)matching LSB bits; if we have 0 matching
1211 and hence 512 mismatching LSB bits we return -1 (since
1212 512 itself cannot be represented with 9 bits) */
1214 /* first, calculate the most significant 9 bits of our
1215 result, aka the number of LSBs */
1216 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1217 /* bucket is now a value between 0 and 512 */
1219 return 0; /* perfect match */
1221 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1222 below, we'd end up with max+1 (overflow)) */
1224 /* calculate the most significant bits of the final result */
1225 msb = (512 - bucket) << (32 - 9);
1226 /* calculate the 32-9 least significant bits of the final result by
1227 looking at the differences in the 32-9 bits following the
1228 mismatching bit at 'bucket' */
1230 for (i = bucket + 1;
1231 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1233 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1234 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1235 last bit set will be 31 -- if
1236 i does not reach 512 first... */
1242 * Return a number that is larger the closer the
1243 * "have" GNUNET_hash code is to the "target".
1245 * @return inverse distance metric, non-zero.
1246 * Must fudge the value if NO bits match.
1249 inverse_distance (const GNUNET_HashCode * target,
1250 const GNUNET_HashCode * have)
1252 if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1253 return 1; /* Never return 0! */
1254 return ((unsigned int) -1) - distance (target, have);
1258 * Find the optimal bucket for this key, regardless
1259 * of the current number of buckets in use.
1261 * @param hc the hashcode to compare our identity to
1263 * @return the proper bucket index, or GNUNET_SYSERR
1264 * on error (same hashcode)
1266 static int find_bucket(const GNUNET_HashCode *hc)
1270 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1271 if (bits == MAX_BUCKETS)
1272 return GNUNET_SYSERR;
1273 return MAX_BUCKETS - bits - 1;
1277 * Find which k-bucket this peer should go into,
1278 * taking into account the size of the k-bucket
1279 * array. This means that if more bits match than
1280 * there are currently buckets, lowest_bucket will
1283 * @param hc GNUNET_HashCode we are finding the bucket for.
1285 * @return the proper bucket index for this key,
1286 * or GNUNET_SYSERR on error (same hashcode)
1288 static int find_current_bucket(const GNUNET_HashCode *hc)
1291 actual_bucket = find_bucket(hc);
1293 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1294 return lowest_bucket;
1295 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1296 return lowest_bucket;
1298 return actual_bucket;
1303 * Find a routing table entry from a peer identity
1305 * @param peer the peer to look up
1307 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1310 find_bucket_by_peer(const struct PeerInfo *peer)
1313 struct PeerInfo *pos;
1315 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1317 pos = k_buckets[bucket].head;
1326 return GNUNET_SYSERR; /* No such peer. */
1332 * Print the complete routing table for this peer.
1335 print_routing_table ()
1338 struct PeerInfo *pos;
1339 char char_buf[30000];
1341 memset(char_buf, 0, sizeof(char_buf));
1343 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1344 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1345 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1347 pos = k_buckets[bucket].head;
1348 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1349 //fprintf(stderr, "Bucket %d:\n", bucket);
1352 //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));
1353 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));
1357 fprintf(stderr, "%s", char_buf);
1363 * Find a routing table entry from a peer identity
1365 * @param peer the peer identity to look up
1367 * @return the routing table entry, or NULL if not found
1369 static struct PeerInfo *
1370 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1373 struct PeerInfo *pos;
1374 bucket = find_current_bucket(&peer->hashPubKey);
1376 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1379 pos = k_buckets[bucket].head;
1382 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1386 return NULL; /* No such peer. */
1389 /* Forward declaration */
1391 update_core_preference (void *cls,
1392 const struct GNUNET_SCHEDULER_TaskContext *tc);
1394 * Function called with statistics about the given peer.
1396 * @param cls closure
1397 * @param peer identifies the peer
1398 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1399 * @param amount set to the amount that was actually reserved or unreserved;
1400 * either the full requested amount or zero (no partial reservations)
1401 * @param preference current traffic preference for the given peer
1404 update_core_preference_finish (void *cls,
1405 const struct GNUNET_PeerIdentity * peer,
1406 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1407 int amount, uint64_t preference)
1409 struct PeerInfo *peer_info = cls;
1410 peer_info->info_ctx = NULL;
1411 GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1415 update_core_preference (void *cls,
1416 const struct GNUNET_SCHEDULER_TaskContext *tc)
1418 struct PeerInfo *peer = cls;
1419 uint64_t preference;
1420 unsigned int matching;
1421 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1425 matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1428 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1431 preference = 1LL << matching;
1432 peer->info_ctx = GNUNET_CORE_peer_change_preference (coreAPI,
1434 GNUNET_TIME_relative_get_forever(),
1435 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1438 &update_core_preference_finish,
1443 * Really add a peer to a bucket (only do assertions
1446 * @param peer GNUNET_PeerIdentity of the peer to add
1447 * @param bucket the already figured out bucket to add
1449 * @param atsi performance information
1451 * @return the newly added PeerInfo
1453 static struct PeerInfo *
1454 add_peer(const struct GNUNET_PeerIdentity *peer,
1455 unsigned int bucket,
1456 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1458 struct PeerInfo *new_peer;
1459 GNUNET_assert(bucket < MAX_BUCKETS);
1460 GNUNET_assert(peer != NULL);
1461 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1463 new_peer->latency = latency;
1464 new_peer->distance = distance;
1467 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1469 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1470 k_buckets[bucket].tail,
1471 k_buckets[bucket].tail,
1473 k_buckets[bucket].peers_size++;
1475 if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1477 #if DO_UPDATE_PREFERENCE
1478 new_peer->preference_task = GNUNET_SCHEDULER_add_now(&update_core_preference, new_peer);
1486 * Given a peer and its corresponding bucket,
1487 * remove it from that bucket. Does not free
1488 * the PeerInfo struct, nor cancel messages
1489 * or free messages waiting to be sent to this
1492 * @param peer the peer to remove
1493 * @param bucket the bucket the peer belongs to
1495 static void remove_peer (struct PeerInfo *peer,
1496 unsigned int bucket)
1498 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1499 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1500 k_buckets[bucket].tail,
1502 k_buckets[bucket].peers_size--;
1504 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1510 * Removes peer from a bucket, then frees associated
1511 * resources and frees peer.
1513 * @param peer peer to be removed and freed
1514 * @param bucket which bucket this peer belongs to
1516 static void delete_peer (struct PeerInfo *peer,
1517 unsigned int bucket)
1519 struct P2PPendingMessage *pos;
1520 struct P2PPendingMessage *next;
1522 struct PeerInfo *peer_pos;
1524 peer_pos = k_buckets[bucket].head;
1525 while ((peer_pos != NULL) && (peer_pos != peer))
1526 peer_pos = peer_pos->next;
1527 if (peer_pos == NULL)
1529 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1530 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));
1532 GNUNET_assert(peer_pos != NULL);
1534 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1536 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1537 GNUNET_SCHEDULER_cancel(peer->send_task);
1538 if ((peer->th != NULL) && (coreAPI != NULL))
1539 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1542 while (pos != NULL) /* Remove any pending messages for this peer */
1549 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1550 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer));
1556 * Iterator over hash map entries.
1558 * @param cls closure
1559 * @param key current key code
1560 * @param value PeerInfo of the peer to move to new lowest bucket
1561 * @return GNUNET_YES if we should continue to
1565 static int move_lowest_bucket (void *cls,
1566 const GNUNET_HashCode * key,
1569 struct PeerInfo *peer = value;
1572 GNUNET_assert(lowest_bucket > 0);
1573 new_bucket = lowest_bucket - 1;
1574 remove_peer(peer, lowest_bucket);
1575 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1576 k_buckets[new_bucket].tail,
1577 k_buckets[new_bucket].tail,
1579 k_buckets[new_bucket].peers_size++;
1585 * The current lowest bucket is full, so change the lowest
1586 * bucket to the next lower down, and move any appropriate
1587 * entries in the current lowest bucket to the new bucket.
1589 static void enable_next_bucket()
1591 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1592 struct PeerInfo *pos;
1593 GNUNET_assert(lowest_bucket > 0);
1594 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1595 pos = k_buckets[lowest_bucket].head;
1598 fprintf(stderr, "Printing RT before new bucket\n");
1599 print_routing_table();
1601 /* Populate the array of peers which should be in the next lowest bucket */
1604 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1605 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1609 /* Remove peers from lowest bucket, insert into next lowest bucket */
1610 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1611 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1612 lowest_bucket = lowest_bucket - 1;
1614 fprintf(stderr, "Printing RT after new bucket\n");
1615 print_routing_table();
1620 * Find the closest peer in our routing table to the
1623 * @return The closest peer in our routing table to the
1624 * key, or NULL on error.
1626 static struct PeerInfo *
1627 find_closest_peer (const GNUNET_HashCode *hc)
1629 struct PeerInfo *pos;
1630 struct PeerInfo *current_closest;
1631 unsigned int lowest_distance;
1632 unsigned int temp_distance;
1636 lowest_distance = -1;
1638 if (k_buckets[lowest_bucket].peers_size == 0)
1641 current_closest = NULL;
1642 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1644 pos = k_buckets[bucket].head;
1646 while ((pos != NULL) && (count < bucket_size))
1648 temp_distance = distance(&pos->id.hashPubKey, hc);
1649 if (temp_distance <= lowest_distance)
1651 lowest_distance = temp_distance;
1652 current_closest = pos;
1658 GNUNET_assert(current_closest != NULL);
1659 return current_closest;
1664 * Function called to send a request out to another peer.
1665 * Called both for locally initiated requests and those
1666 * received from other peers.
1668 * @param msg the encapsulated message
1669 * @param peer the peer to forward the message to
1670 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1672 static void forward_message (const struct GNUNET_MessageHeader *msg,
1673 struct PeerInfo *peer,
1674 struct DHT_MessageContext *msg_ctx)
1676 struct GNUNET_DHT_P2PRouteMessage *route_message;
1677 struct P2PPendingMessage *pending;
1681 increment_stats(STAT_ROUTE_FORWARDS);
1682 GNUNET_assert(peer != NULL);
1683 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1684 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1686 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1687 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1688 psize = sizeof(struct P2PPendingMessage) + msize;
1689 pending = GNUNET_malloc(psize);
1690 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1691 pending->importance = msg_ctx->importance;
1692 pending->timeout = msg_ctx->timeout;
1693 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1694 route_message->header.size = htons(msize);
1695 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1696 route_message->options = htonl(msg_ctx->msg_options);
1697 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1698 route_message->network_size = htonl(msg_ctx->network_size);
1699 route_message->desired_replication_level = htonl(msg_ctx->replication);
1700 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1701 if (msg_ctx->bloom != NULL)
1702 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1703 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1704 memcpy(&route_message[1], msg, ntohs(msg->size));
1706 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));
1708 peer->pending_count++;
1709 increment_stats("# pending messages scheduled");
1710 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1711 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1712 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1717 * Task used to send ping messages to peers so that
1718 * they don't get disconnected.
1720 * @param cls the peer to send a ping message to
1721 * @param tc context, reason, etc.
1724 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1726 struct PeerInfo *peer = cls;
1727 struct GNUNET_MessageHeader ping_message;
1728 struct DHT_MessageContext msg_ctx;
1730 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1733 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1734 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1736 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
1738 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1740 forward_message(&ping_message, peer, &msg_ctx);
1741 peer->ping_task = GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1745 * Schedule PING messages for the top X peers in each
1746 * bucket of the routing table (so core won't disconnect them!)
1748 void schedule_ping_messages()
1750 unsigned int bucket;
1752 struct PeerInfo *pos;
1753 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1755 pos = k_buckets[bucket].head;
1759 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1760 GNUNET_SCHEDULER_add_now(&periodic_ping_task, pos);
1761 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1763 GNUNET_SCHEDULER_cancel(pos->ping_task);
1764 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1774 * Attempt to add a peer to our k-buckets.
1776 * @param peer the peer identity of the peer being added
1777 * @param bucket the bucket that we want this peer to go in
1778 * @param latency transport latency of this peer
1779 * @param distance transport distance to this peer
1781 * @return NULL if the peer was not added,
1782 * pointer to PeerInfo for new peer otherwise
1784 static struct PeerInfo *
1785 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1786 unsigned int bucket,
1787 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1790 struct PeerInfo *new_peer;
1792 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1795 peer_bucket = find_current_bucket(&peer->hashPubKey);
1797 GNUNET_assert(peer_bucket >= lowest_bucket);
1798 new_peer = add_peer(peer, peer_bucket, atsi);
1800 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1801 enable_next_bucket();
1803 schedule_ping_messages();
1810 * Task run to check for messages that need to be sent to a client.
1812 * @param client a ClientList, containing the client and any messages to be sent to it
1815 process_pending_messages (struct ClientList *client)
1817 if (client->pending_head == NULL)
1819 if (client->transmit_handle != NULL)
1822 client->transmit_handle =
1823 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1824 ntohs (client->pending_head->msg->
1826 GNUNET_TIME_UNIT_FOREVER_REL,
1827 &send_generic_reply, client);
1831 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1832 * request. A ClientList is passed as closure, take the head of the list
1833 * and copy it into buf, which has the result of sending the message to the
1836 * @param cls closure to this call
1837 * @param size maximum number of bytes available to send
1838 * @param buf where to copy the actual message to
1840 * @return the number of bytes actually copied, 0 indicates failure
1843 send_generic_reply (void *cls, size_t size, void *buf)
1845 struct ClientList *client = cls;
1847 struct PendingMessage *reply;
1851 client->transmit_handle = NULL;
1854 /* client disconnected */
1858 while ( (NULL != (reply = client->pending_head)) &&
1859 (size >= off + (msize = ntohs (reply->msg->size))))
1861 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1862 client->pending_tail,
1864 memcpy (&cbuf[off], reply->msg, msize);
1865 GNUNET_free (reply);
1868 process_pending_messages (client);
1870 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1871 "Transmitted %u bytes of replies to client\n",
1872 (unsigned int) off);
1879 * Add a PendingMessage to the clients list of messages to be sent
1881 * @param client the active client to send the message to
1882 * @param pending_message the actual message to send
1885 add_pending_message (struct ClientList *client,
1886 struct PendingMessage *pending_message)
1888 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1889 client->pending_tail,
1890 client->pending_tail,
1892 process_pending_messages (client);
1897 * Called when a reply needs to be sent to a client, as
1898 * a result it found to a GET or FIND PEER request.
1900 * @param client the client to send the reply to
1901 * @param message the encapsulated message to send
1902 * @param uid the unique identifier of this request
1905 send_reply_to_client (struct ClientList *client,
1906 const struct GNUNET_MessageHeader *message,
1907 unsigned long long uid,
1908 const GNUNET_HashCode *key)
1910 struct GNUNET_DHT_RouteResultMessage *reply;
1911 struct PendingMessage *pending_message;
1915 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1916 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1918 msize = ntohs (message->size);
1919 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1920 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1922 GNUNET_break_op (0);
1925 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1926 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1927 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1928 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1929 reply->header.size = htons (tsize);
1930 reply->put_path_length = htons(0); /* FIXME: implement */
1931 reply->get_path_length = htons(0); /* FIXME: implement */
1932 reply->unique_id = GNUNET_htonll (uid);
1934 memcpy (&reply[1], message, msize);
1935 add_pending_message (client, pending_message);
1939 * Consider whether or not we would like to have this peer added to
1940 * our routing table. Check whether bucket for this peer is full,
1941 * if so return negative; if not return positive. Since peers are
1942 * only added on CORE level connect, this doesn't actually add the
1943 * peer to the routing table.
1945 * @param peer the peer we are considering adding
1947 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1950 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1954 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1955 return GNUNET_NO; /* We already know this peer (are connected even!) */
1956 bucket = find_current_bucket(&peer->hashPubKey);
1958 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1965 * Main function that handles whether or not to route a result
1966 * message to other peers, or to send to our local client.
1968 * @param msg the result message to be routed
1969 * @param msg_ctx context of the message we are routing
1971 * @return the number of peers the message was routed to,
1972 * GNUNET_SYSERR on failure
1974 static int route_result_message(struct GNUNET_MessageHeader *msg,
1975 struct DHT_MessageContext *msg_ctx)
1977 struct GNUNET_PeerIdentity new_peer;
1978 struct DHTQueryRecord *record;
1979 struct DHTRouteSource *pos;
1980 struct PeerInfo *peer_info;
1981 const struct GNUNET_MessageHeader *hello_msg;
1983 increment_stats(STAT_RESULTS);
1985 * If a find peer result message is received and contains a valid
1986 * HELLO for another peer, offer it to the transport service.
1988 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1990 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1993 hello_msg = &msg[1];
1994 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1996 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
2000 else /* We have a valid hello, and peer id stored in new_peer */
2002 find_peer_context.count++;
2003 increment_stats(STAT_FIND_PEER_REPLY);
2004 if (GNUNET_YES == consider_peer(&new_peer))
2006 increment_stats(STAT_HELLOS_PROVIDED);
2007 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
2008 GNUNET_CORE_peer_request_connect(coreAPI,
2009 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
2014 if (malicious_dropper == GNUNET_YES)
2017 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2019 if (record == NULL) /* No record of this message! */
2022 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2023 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
2024 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2026 #if DEBUG_DHT_ROUTING
2027 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2029 dhtlog_handle->insert_route (NULL,
2036 msg_ctx->peer, NULL);
2039 if (msg_ctx->bloom != NULL)
2041 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
2042 msg_ctx->bloom = NULL;
2050 #if STRICT_FORWARDING
2051 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2053 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2055 increment_stats("# find peer responses NOT forwarded (bloom match)");
2060 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2064 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2067 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2068 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2069 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2071 #if DEBUG_DHT_ROUTING
2072 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2074 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2076 GNUNET_YES, &my_identity, &msg_ctx->key,
2077 msg_ctx->peer, NULL);
2080 increment_stats(STAT_RESULTS_TO_CLIENT);
2081 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2082 increment_stats(STAT_GET_REPLY);
2084 send_reply_to_client(pos->client, msg,
2088 else /* Send to peer */
2090 peer_info = find_peer_by_id(&pos->source);
2091 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2097 if (msg_ctx->bloom == NULL)
2098 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2099 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
2100 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom, &peer_info->id.hashPubKey)))
2103 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2105 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&peer_info->id));
2107 #if DEBUG_DHT_ROUTING
2108 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2110 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id,
2113 GNUNET_NO, &my_identity, &msg_ctx->key,
2114 msg_ctx->peer, &pos->source);
2117 forward_result_message(msg, peer_info, msg_ctx);
2122 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2123 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2124 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&peer_info->id));
2130 if (msg_ctx->bloom != NULL)
2132 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
2133 msg_ctx->bloom = NULL;
2139 * Iterator for local get request results,
2141 * @param cls closure for iterator, a DatacacheGetContext
2142 * @param exp when does this value expire?
2143 * @param key the key this data is stored under
2144 * @param size the size of the data identified by key
2145 * @param data the actual data
2146 * @param type the type of the data
2148 * @return GNUNET_OK to continue iteration, anything else
2149 * to stop iteration.
2152 datacache_get_iterator (void *cls,
2153 struct GNUNET_TIME_Absolute exp,
2154 const GNUNET_HashCode * key,
2155 size_t size, const char *data,
2156 enum GNUNET_BLOCK_Type type)
2158 struct DHT_MessageContext *msg_ctx = cls;
2159 struct DHT_MessageContext *new_msg_ctx;
2160 struct GNUNET_DHT_GetResultMessage *get_result;
2161 enum GNUNET_BLOCK_EvaluationResult eval;
2164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2165 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2167 eval = GNUNET_BLOCK_evaluate (block_context,
2171 msg_ctx->reply_bf_mutator,
2173 msg_ctx->xquery_size,
2178 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2179 msg_ctx->do_forward = GNUNET_NO;
2180 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2181 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2182 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2184 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2185 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2186 get_result->header.size =
2187 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2188 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2189 get_result->type = htons (type);
2190 memcpy (&get_result[1], data, size);
2191 new_msg_ctx->peer = &my_identity;
2192 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2193 new_msg_ctx->hop_count = 0;
2194 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
2195 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2196 increment_stats(STAT_GET_RESPONSE_START);
2197 route_result_message(&get_result->header, new_msg_ctx);
2198 GNUNET_free(new_msg_ctx);
2199 GNUNET_free (get_result);
2201 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2204 "`%s:%s': Duplicate block error\n", my_short_id, "DHT");
2207 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2209 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2210 "`%s:%s': Invalid request error\n", my_short_id, "DHT");
2213 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2215 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2216 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2220 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2221 GNUNET_break_op (0);
2222 msg_ctx->do_forward = GNUNET_NO;
2224 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2226 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2227 "`%s:%s': Unsupported block type (%u) in response!\n", my_short_id, "DHT", type);
2229 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2237 * Main function that handles whether or not to route a message to other
2240 * @param msg the message to be routed
2241 * @param msg_ctx the context containing all pertinent information about the message
2244 route_message(const struct GNUNET_MessageHeader *msg,
2245 struct DHT_MessageContext *msg_ctx);
2249 * Server handler for all dht get requests, look for data,
2250 * if found, send response either to clients or other peers.
2252 * @param msg the actual get message
2253 * @param msg_ctx struct containing pertinent information about the get request
2255 * @return number of items found for GET request
2258 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2259 struct DHT_MessageContext *msg_ctx)
2261 const struct GNUNET_DHT_GetMessage *get_msg;
2264 unsigned int results;
2266 enum GNUNET_BLOCK_Type type;
2268 msize = ntohs (msg->size);
2269 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2274 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2275 bf_size = ntohs (get_msg->bf_size);
2276 msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2277 msg_ctx->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2278 if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2283 end = (const char*) &get_msg[1];
2284 if (msg_ctx->xquery_size == 0)
2286 msg_ctx->xquery = NULL;
2290 msg_ctx->xquery = (const void*) end;
2291 end += msg_ctx->xquery_size;
2295 msg_ctx->reply_bf = NULL;
2299 msg_ctx->reply_bf = GNUNET_CONTAINER_bloomfilter_init (end,
2301 GNUNET_DHT_GET_BLOOMFILTER_K);
2303 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2305 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2306 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2310 GNUNET_h2s (&msg_ctx->key),
2311 msg_ctx->unique_id);
2313 increment_stats(STAT_GETS);
2316 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2318 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2322 msg_ctx->do_forward = GNUNET_YES;
2323 if (datacache != NULL)
2325 = GNUNET_DATACACHE_get (datacache,
2326 &msg_ctx->key, type,
2327 &datacache_get_iterator,
2330 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2331 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2332 results, "GET", msg_ctx->unique_id);
2336 #if DEBUG_DHT_ROUTING
2337 if ((debug_routes) && (dhtlog_handle != NULL))
2339 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2340 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2344 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2346 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2347 msg_ctx->hop_count, GNUNET_YES,
2348 &my_identity, &msg_ctx->key, msg_ctx->peer,
2355 /* check query valid */
2356 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID
2357 == GNUNET_BLOCK_evaluate (block_context,
2361 msg_ctx->reply_bf_mutator,
2363 msg_ctx->xquery_size,
2366 GNUNET_break_op (0);
2367 msg_ctx->do_forward = GNUNET_NO;
2371 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2373 #if DEBUG_DHT_ROUTING
2374 if ((debug_routes) && (dhtlog_handle != NULL))
2376 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2377 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2382 if (msg_ctx->do_forward == GNUNET_YES)
2383 route_message (msg, msg_ctx);
2384 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2389 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2391 GNUNET_HashCode *key = cls;
2393 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, NULL));
2398 * Server handler for initiating local dht find peer requests
2400 * @param find_msg the actual find peer message
2401 * @param msg_ctx struct containing pertinent information about the request
2405 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2406 struct DHT_MessageContext *msg_ctx)
2408 struct GNUNET_MessageHeader *find_peer_result;
2409 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2410 struct DHT_MessageContext *new_msg_ctx;
2411 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2414 GNUNET_HashCode *recent_hash;
2415 struct GNUNET_MessageHeader *other_hello;
2416 size_t other_hello_size;
2417 struct GNUNET_PeerIdentity peer_id;
2419 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2420 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2421 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2424 other_hello_size = 0;
2425 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2427 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2428 other_hello = GNUNET_malloc(other_hello_size);
2429 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2430 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)))
2432 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2433 GNUNET_free(other_hello);
2436 #if FIND_PEER_WITH_HELLO
2437 if (GNUNET_YES == consider_peer(&peer_id))
2439 increment_stats(STAT_HELLOS_PROVIDED);
2440 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2441 GNUNET_CORE_peer_request_connect(coreAPI,
2442 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2443 route_message (find_msg, msg_ctx);
2444 GNUNET_free (other_hello);
2447 else /* We don't want this peer! */
2449 route_message (find_msg, msg_ctx);
2450 GNUNET_free (other_hello);
2457 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2458 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2459 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2460 ntohs (find_msg->size),
2461 sizeof (struct GNUNET_MessageHeader));
2463 if (my_hello == NULL)
2466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2467 "`%s': Our HELLO is null, can't return.\n",
2470 GNUNET_free_non_null (other_hello);
2471 route_message (find_msg, msg_ctx);
2475 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2476 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2478 increment_stats(STAT_BLOOM_FIND_PEER);
2479 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2480 GNUNET_free_non_null(other_hello);
2481 route_message (find_msg, msg_ctx);
2482 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2484 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2486 #if RESTRICT_FIND_PEER
2489 * Ignore any find peer requests from a peer we have seen very recently.
2491 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent_find_peer_requests, &msg_ctx->key)) /* We have recently responded to a find peer request for this peer! */
2493 increment_stats("# dht find peer requests ignored (recently seen!)");
2494 GNUNET_free_non_null(other_hello);
2499 * Use this check to only allow the peer to respond to find peer requests if
2500 * it would be beneficial to have the requesting peer in this peers routing
2501 * table. Can be used to thwart peers flooding the network with find peer
2502 * requests that we don't care about. However, if a new peer is joining
2503 * the network and has no other peers this is a problem (assume all buckets
2504 * full, no one will respond!).
2506 memcpy(&peer_id.hashPubKey, &msg_ctx->key, sizeof(GNUNET_HashCode));
2507 if (GNUNET_NO == consider_peer(&peer_id))
2509 increment_stats("# dht find peer requests ignored (do not need!)");
2510 GNUNET_free_non_null(other_hello);
2511 route_message (find_msg, msg_ctx);
2516 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2517 memcpy(recent_hash, &msg_ctx->key, sizeof(GNUNET_HashCode));
2518 if (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2519 &msg_ctx->key, NULL,
2520 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2522 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding recent remove task for key `%s`!\n", GNUNET_h2s(&msg_ctx->key));
2523 /* Only add a task if there wasn't one for this key already! */
2524 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30),
2525 &remove_recent_find_peer, recent_hash);
2529 GNUNET_free(recent_hash);
2530 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received duplicate find peer request too soon!\n");
2533 /* Simplistic find_peer functionality, always return our hello */
2534 hello_size = ntohs(my_hello->size);
2535 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2537 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2539 GNUNET_break_op (0);
2540 GNUNET_free_non_null(other_hello);
2544 find_peer_result = GNUNET_malloc (tsize);
2545 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2546 find_peer_result->size = htons (tsize);
2547 memcpy (&find_peer_result[1], my_hello, hello_size);
2549 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2550 "`%s': Sending hello size %d to requesting peer.\n",
2553 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2554 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2555 new_msg_ctx->peer = &my_identity;
2556 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2557 new_msg_ctx->hop_count = 0;
2558 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make find peer requests a higher priority */
2559 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2560 increment_stats(STAT_FIND_PEER_ANSWER);
2561 route_result_message(find_peer_result, new_msg_ctx);
2562 GNUNET_free(new_msg_ctx);
2563 #if DEBUG_DHT_ROUTING
2564 if ((debug_routes) && (dhtlog_handle != NULL))
2566 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2567 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2571 GNUNET_free_non_null(other_hello);
2572 GNUNET_free(find_peer_result);
2573 route_message (find_msg, msg_ctx);
2577 * Task used to republish data.
2578 * Forward declaration; function call loop.
2580 * @param cls closure (a struct RepublishContext)
2581 * @param tc runtime context for this task
2584 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2587 * Server handler for initiating local dht put requests
2589 * @param msg the actual put message
2590 * @param msg_ctx struct containing pertinent information about the request
2593 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2594 struct DHT_MessageContext *msg_ctx)
2596 const struct GNUNET_DHT_PutMessage *put_msg;
2597 enum GNUNET_BLOCK_Type put_type;
2600 struct RepublishContext *put_context;
2601 GNUNET_HashCode key;
2603 GNUNET_assert (ntohs (msg->size) >=
2604 sizeof (struct GNUNET_DHT_PutMessage));
2607 put_msg = (const struct GNUNET_DHT_PutMessage *)msg;
2608 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2610 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2612 #if DEBUG_DHT_ROUTING
2613 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2615 /** Log routes that die due to high load! */
2616 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2617 msg_ctx->hop_count, GNUNET_SYSERR,
2618 &my_identity, &msg_ctx->key, msg_ctx->peer,
2625 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2626 ret = GNUNET_BLOCK_get_key (block_context,
2631 if (GNUNET_NO == ret)
2633 #if DEBUG_DHT_ROUTING
2634 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2636 /** Log routes that die due to high load! */
2637 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2638 msg_ctx->hop_count, GNUNET_SYSERR,
2639 &my_identity, &msg_ctx->key, msg_ctx->peer,
2644 GNUNET_break_op (0);
2647 if ( (GNUNET_YES == ret) &&
2650 sizeof (GNUNET_HashCode))) )
2652 #if DEBUG_DHT_ROUTING
2653 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2655 /** Log routes that die due to high load! */
2656 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2657 msg_ctx->hop_count, GNUNET_SYSERR,
2658 &my_identity, &msg_ctx->key, msg_ctx->peer,
2662 /* invalid wrapper: key mismatch! */
2663 GNUNET_break_op (0);
2666 /* ret == GNUNET_SYSERR means that there is no known relationship between
2667 data and the key, so we cannot check it */
2669 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2670 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2671 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2673 #if DEBUG_DHT_ROUTING
2674 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2676 if ((debug_routes) && (dhtlog_handle != NULL))
2678 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2679 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2685 if (msg_ctx->closest != GNUNET_YES)
2687 route_message (msg, msg_ctx);
2692 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2693 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2694 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2697 #if DEBUG_DHT_ROUTING
2698 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2700 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2701 msg_ctx->hop_count, GNUNET_YES,
2702 &my_identity, &msg_ctx->key, msg_ctx->peer,
2706 if ((debug_routes) && (dhtlog_handle != NULL))
2708 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2709 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2714 increment_stats(STAT_PUTS_INSERTED);
2715 if (datacache != NULL)
2717 ret = GNUNET_DATACACHE_put (datacache, &msg_ctx->key, data_size,
2718 (char *) &put_msg[1], put_type,
2719 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2721 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2723 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2724 memcpy(&put_context->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
2725 put_context->type = put_type;
2726 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content, put_context);
2730 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2731 "`%s:%s': %s request received, but have no datacache!\n",
2732 my_short_id, "DHT", "PUT");
2734 if (stop_on_closest == GNUNET_NO)
2735 route_message (msg, msg_ctx);
2739 * Estimate the diameter of the network based
2740 * on how many buckets are currently in use.
2741 * Concept here is that the diameter of the network
2742 * is roughly the distance a message must travel in
2743 * order to reach its intended destination. Since
2744 * at each hop we expect to get one bit closer, and
2745 * we have one bit per bucket, the number of buckets
2746 * in use should be the largest number of hops for
2747 * a successful message. (of course, this assumes we
2748 * know all peers in the network!)
2750 * @return ballpark diameter figure
2752 static unsigned int estimate_diameter()
2754 return MAX_BUCKETS - lowest_bucket;
2758 * To how many peers should we (on average)
2759 * forward the request to obtain the desired
2760 * target_replication count (on average).
2762 * returns: target_replication / (est. hops) + (target_replication * hop_count)
2763 * where est. hops is typically 2 * the routing table depth
2765 * @param hop_count number of hops the message has traversed
2766 * @param target_replication the number of total paths desired
2768 * @return Some number of peers to forward the message to
2771 get_forward_count (unsigned int hop_count, size_t target_replication)
2773 uint32_t random_value;
2774 unsigned int forward_count;
2776 unsigned int diameter;
2778 diameter = estimate_diameter ();
2780 if (GNUNET_NO == use_max_hops)
2781 max_hops = (diameter + 1) * 2;
2784 * If we are behaving in strict kademlia mode, send multiple initial requests,
2785 * but then only send to 1 or 0 peers based strictly on the number of hops.
2787 if (strict_kademlia == GNUNET_YES)
2790 return kademlia_replication;
2791 else if (hop_count < max_hops)
2797 /* FIXME: the smaller we think the network is the more lenient we should be for
2798 * routing right? The estimation below only works if we think we have reasonably
2799 * full routing tables, which for our RR topologies may not be the case!
2801 if (hop_count > max_hops)
2804 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2805 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2806 "DHT", estimate_diameter(), lowest_bucket);
2812 /* FIXME: we use diameter as the expected number of hops, but with randomized routing we will likely route to more! */
2813 target_value = target_replication / (diameter + ((float)target_replication * hop_count));
2814 if (target_value > 1)
2815 return (unsigned int)target_value;
2817 random_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int)-1);
2819 if (random_value < (target_value * (unsigned int)-1))
2824 return forward_count;
2828 * Check whether my identity is closer than any known peers.
2829 * If a non-null bloomfilter is given, check if this is the closest
2830 * peer that hasn't already been routed to.
2832 * @param target hash code to check closeness to
2833 * @param bloom bloomfilter, exclude these entries from the decision
2835 * Return GNUNET_YES if node location is closest, GNUNET_NO
2839 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2845 struct PeerInfo *pos;
2846 unsigned int my_distance;
2848 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2851 bucket_num = find_current_bucket(target);
2853 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2854 my_distance = distance(&my_identity.hashPubKey, target);
2855 pos = k_buckets[bucket_num].head;
2857 while ((pos != NULL) && (count < bucket_size))
2859 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2862 continue; /* Skip already checked entries */
2865 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2866 if (other_bits > bits)
2868 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2870 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2872 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2878 /* No peers closer, we are the closest! */
2884 * Return this peers adjusted value based on the convergence
2885 * function chosen. This is the key function for randomized
2886 * routing decisions.
2888 * @param target the key of the request
2889 * @param peer the peer we would like the value of
2890 * @param hops number of hops this message has already traveled
2892 * @return bit distance from target to peer raised to an exponent
2893 * adjusted based on the current routing convergence algorithm
2896 static unsigned long long
2897 converge_distance (const GNUNET_HashCode *target,
2898 struct PeerInfo *peer,
2901 unsigned long long ret;
2902 unsigned int other_matching_bits;
2903 double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
2904 double temp_modifier;
2910 curr_max_hops = max_hops;
2912 curr_max_hops = (estimate_diameter() + 1) * 2;
2914 if (converge_modifier > 0)
2915 temp_modifier = converge_modifier * base_converge_modifier;
2918 temp_modifier = base_converge_modifier;
2919 base_converge_modifier = 0.0;
2922 GNUNET_assert(temp_modifier > 0);
2924 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2926 switch (converge_option)
2928 case DHT_CONVERGE_RANDOM:
2929 return 1; /* Always return 1, choose equally among all peers */
2930 case DHT_CONVERGE_LINEAR:
2931 calc_value = hops * curr_max_hops * temp_modifier;
2933 case DHT_CONVERGE_SQUARE:
2935 * Simple square based curve.
2937 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * temp_modifier));
2939 case DHT_CONVERGE_EXPONENTIAL:
2941 * Simple exponential curve.
2943 if (base_converge_modifier > 0)
2944 calc_value = (temp_modifier * hops * hops) / curr_max_hops;
2946 calc_value = (hops * hops) / curr_max_hops;
2948 case DHT_CONVERGE_BINARY:
2950 * If below the cutoff, route randomly (return 1),
2951 * If above the cutoff, return the maximum possible
2952 * value first (always route to closest, because
2956 if (hops > converge_modifier) /* Past cutoff */
2965 /* Take the log (base e) of the number of bits matching the other peer */
2966 exponent = log(other_matching_bits);
2968 /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
2969 if (exponent * calc_value >= 44.361419555836498)
2972 /* Clear errno and all math exceptions */
2974 feclearexcept(FE_ALL_EXCEPT);
2975 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2976 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2979 if (0 != fetestexcept(FE_OVERFLOW))
2980 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2981 if (0 != fetestexcept(FE_INVALID))
2982 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2983 if (0 != fetestexcept(FE_UNDERFLOW))
2984 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2992 * Comparison function for two struct PeerInfo's
2993 * which have already had their matching bits to
2994 * some target calculated.
2996 * @param p1 a pointer pointer to a struct PeerInfo
2997 * @param p2 a pointer pointer to a struct PeerInfo
2999 * @return 0 if equidistant to target,
3000 * -1 if p1 is closer,
3004 compare_peers (const void *p1, const void *p2)
3006 struct PeerInfo **first = (struct PeerInfo **)p1;
3007 struct PeerInfo **second = (struct PeerInfo **)p2;
3009 if ((*first)->matching_bits > (*second)->matching_bits)
3011 if ((*first)->matching_bits < (*second)->matching_bits)
3019 * Select a peer from the routing table that would be a good routing
3020 * destination for sending a message for "target". The resulting peer
3021 * must not be in the set of blocked peers.<p>
3023 * Note that we should not ALWAYS select the closest peer to the
3024 * target, peers further away from the target should be chosen with
3025 * exponentially declining probability.
3027 * @param target the key we are selecting a peer to route to
3028 * @param bloom a bloomfilter containing entries this request has seen already
3030 * @return Peer to route to, or NULL on error
3032 static struct PeerInfo *
3033 select_peer (const GNUNET_HashCode * target,
3034 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3039 unsigned int offset;
3040 unsigned int my_matching_bits;
3042 struct PeerInfo *pos;
3043 struct PeerInfo *sorted_closest[bucket_size];
3044 unsigned long long temp_converge_distance;
3045 unsigned long long total_distance;
3046 unsigned long long selected;
3048 unsigned long long stats_total_distance;
3052 unsigned int distance;
3053 unsigned int largest_distance;
3054 struct PeerInfo *chosen;
3056 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
3059 if (strict_kademlia == GNUNET_YES)
3061 largest_distance = 0;
3063 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3065 pos = k_buckets[bc].head;
3067 while ((pos != NULL) && (count < bucket_size))
3069 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3070 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3072 distance = inverse_distance (target, &pos->id.hashPubKey);
3073 if (distance > largest_distance)
3076 largest_distance = distance;
3084 if ((largest_distance > 0) && (chosen != NULL))
3086 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
3097 /* Three steps: order peers in closest bucket (most matching bits).
3098 * Then go over all LOWER buckets (matching same bits we do)
3099 * Then go over all HIGHER buckets (matching less then we do)
3102 closest_bucket = find_current_bucket(target);
3103 GNUNET_assert(closest_bucket >= lowest_bucket);
3104 pos = k_buckets[closest_bucket].head;
3106 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3107 memset(sorted_closest, 0, sizeof(sorted_closest));
3108 /* Put any peers in the closest bucket in the sorting array */
3109 while ((pos != NULL) && (count < bucket_size))
3111 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3115 continue; /* Ignore bloomfiltered peers */
3117 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
3118 sorted_closest[offset] = pos;
3124 /* Sort the peers in descending order */
3125 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
3127 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3128 for (i = 0; i < offset; i++)
3130 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3131 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3132 break; /* Ignore bloomfiltered peers */
3133 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3134 total_distance += temp_converge_distance;
3136 break; /* overflow case */
3139 /* Now handle peers in lower buckets (matches same # of bits as target) */
3140 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3142 pos = k_buckets[bc].head;
3144 while ((pos != NULL) && (count < bucket_size))
3146 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3150 continue; /* Ignore bloomfiltered peers */
3152 temp_converge_distance = converge_distance(target, pos, hops);
3153 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3154 total_distance += temp_converge_distance;
3156 break; /* overflow case */
3162 /* Now handle all the further away peers */
3163 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3165 pos = k_buckets[bc].head;
3167 while ((pos != NULL) && (count < bucket_size))
3169 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3173 continue; /* Ignore bloomfiltered peers */
3175 temp_converge_distance = converge_distance(target, pos, hops);
3176 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3177 total_distance += temp_converge_distance;
3179 break; /* overflow case */
3185 if (total_distance == 0) /* No peers to select from! */
3187 increment_stats("# select_peer, total_distance == 0");
3191 #if DEBUG_DHT_ROUTING > 1
3194 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3195 stats_total_distance = 0;
3196 for (i = 0; i < offset; i++)
3198 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3199 break; /* Ignore bloomfiltered peers */
3200 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3201 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3202 stats_total_distance += temp_converge_distance;
3204 break; /* overflow case */
3205 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);
3208 /* Now handle peers in lower buckets (matches same # of bits as target) */
3209 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3211 pos = k_buckets[bc].head;
3213 while ((pos != NULL) && (count < bucket_size))
3215 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3219 continue; /* Ignore bloomfiltered peers */
3221 temp_converge_distance = converge_distance(target, pos, hops);
3222 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3223 stats_total_distance += temp_converge_distance;
3225 break; /* overflow case */
3226 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);
3232 /* Now handle all the further away peers */
3233 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3235 pos = k_buckets[bc].head;
3237 while ((pos != NULL) && (count < bucket_size))
3239 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3243 continue; /* Ignore bloomfiltered peers */
3245 temp_converge_distance = converge_distance(target, pos, hops);
3246 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3247 stats_total_distance += temp_converge_distance;
3249 break; /* overflow case */
3250 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);
3255 /* END PRINT STATS */
3258 /* Now actually choose a peer */
3259 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3261 /* Go over closest sorted peers. */
3262 for (i = 0; i < offset; i++)
3264 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3265 break; /* Ignore bloomfiltered peers */
3266 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3267 if (temp_converge_distance >= selected)
3268 return sorted_closest[i];
3270 selected -= temp_converge_distance;
3273 /* Now handle peers in lower buckets (matches same # of bits as target) */
3274 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3276 pos = k_buckets[bc].head;
3278 while ((pos != NULL) && (count < bucket_size))
3280 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3284 continue; /* Ignore bloomfiltered peers */
3286 temp_converge_distance = converge_distance(target, pos, hops);
3287 if (temp_converge_distance >= selected)
3290 selected -= temp_converge_distance;
3296 /* Now handle all the further away peers */
3297 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3299 pos = k_buckets[bc].head;
3301 while ((pos != NULL) && (count < bucket_size))
3303 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3307 continue; /* Ignore bloomfiltered peers */
3309 temp_converge_distance = converge_distance(target, pos, hops);
3310 if (temp_converge_distance >= selected)
3313 selected -= temp_converge_distance;
3319 increment_stats("# failed to select peer");
3325 * Task used to remove recent entries, either
3326 * after timeout, when full, or on shutdown.
3328 * @param cls the entry to remove
3329 * @param tc context, reason, etc.
3332 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3334 struct RecentRequest *req = cls;
3335 static GNUNET_HashCode hash;
3337 GNUNET_assert(req != NULL);
3338 hash_from_uid(req->uid, &hash);
3339 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3340 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3341 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3345 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3347 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3348 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3355 * Task used to remove forwarding entries, either
3356 * after timeout, when full, or on shutdown.
3358 * @param cls the entry to remove
3359 * @param tc context, reason, etc.
3362 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3364 struct DHTRouteSource *source_info = cls;
3365 struct DHTQueryRecord *record;
3366 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3367 record = source_info->record;
3368 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3370 if (record->head == NULL) /* No more entries in DLL */
3372 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap, &record->key, record));
3373 GNUNET_free(record);
3375 if (source_info->find_peers_responded != NULL)
3376 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3377 GNUNET_free(source_info);
3381 * Remember this routing request so that if a reply is
3382 * received we can either forward it to the correct peer
3383 * or return the result locally.
3385 * @param msg_ctx Context of the route request
3387 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3389 static int cache_response(struct DHT_MessageContext *msg_ctx)
3391 struct DHTQueryRecord *record;
3392 struct DHTRouteSource *source_info;
3393 struct DHTRouteSource *pos;
3394 struct GNUNET_TIME_Absolute now;
3395 unsigned int current_size;
3397 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3399 #if DELETE_WHEN_FULL
3400 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3402 source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3403 GNUNET_assert(source_info != NULL);
3404 record = source_info->record;
3405 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3406 if (record->head == NULL) /* No more entries in DLL */
3408 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3409 GNUNET_free(record);
3411 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3412 GNUNET_SCHEDULER_cancel(source_info->delete_task);
3413 if (source_info->find_peers_responded != NULL)
3414 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3415 GNUNET_free(source_info);
3416 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3419 /** Non-local request and have too many outstanding forwards, discard! */
3420 if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3423 now = GNUNET_TIME_absolute_get();
3424 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3425 if (record != NULL) /* Already know this request! */
3430 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3431 break; /* Already have this peer in reply list! */
3434 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3436 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.abs_value);
3442 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3443 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3444 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3447 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3448 source_info->record = record;
3449 source_info->delete_task = GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3450 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3451 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3452 GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail, source_info);
3453 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3455 source_info->client = msg_ctx->client;
3456 now = GNUNET_TIME_absolute_get_forever();
3458 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.abs_value);
3460 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3461 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3462 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3469 * Main function that handles whether or not to route a message to other
3472 * @param msg the message to be routed
3473 * @param msg_ctx the context containing all pertinent information about the message
3476 route_message(const struct GNUNET_MessageHeader *msg,
3477 struct DHT_MessageContext *msg_ctx)
3480 struct PeerInfo *selected;
3481 #if DEBUG_DHT_ROUTING > 1
3482 struct PeerInfo *nearest;
3484 unsigned int target_forward_count;
3485 unsigned int forward_count;
3486 struct RecentRequest *recent_req;
3487 GNUNET_HashCode unique_hash;
3488 char *stat_forward_count;
3489 char *temp_stat_str;
3490 #if DEBUG_DHT_ROUTING
3494 if (malicious_dropper == GNUNET_YES)
3496 #if DEBUG_DHT_ROUTING
3497 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3499 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3500 msg_ctx->hop_count, GNUNET_SYSERR,
3501 &my_identity, &msg_ctx->key, msg_ctx->peer,
3505 if (msg_ctx->bloom != NULL)
3507 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3508 msg_ctx->bloom = NULL;
3513 increment_stats(STAT_ROUTES);
3514 target_forward_count = get_forward_count(msg_ctx->hop_count, msg_ctx->replication);
3515 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", target_forward_count);
3516 increment_stats(stat_forward_count);
3517 GNUNET_free(stat_forward_count);
3518 if (msg_ctx->bloom == NULL)
3519 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3521 if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3522 target_forward_count = 0;
3525 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3526 * any closer peers (which is being checked for below). Since we are doing recursive
3527 * routing we have no choice but to stop forwarding in this case. This means that at
3528 * any given step the request may NOT be forwarded to alpha peers (because routes will
3529 * stop and the parallel route will not be aware of it). Of course, assuming that we
3530 * have fulfilled the Kademlia requirements for routing table fullness this will never
3531 * ever ever be a problem.
3533 * However, is this fair?
3535 * Since we use these requests to build our routing tables (and we build them in the
3536 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3537 * routing tables still get constructed.
3539 if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) && (msg_ctx->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3540 target_forward_count = 0;
3543 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3544 hash_from_uid (msg_ctx->unique_id, &unique_hash);
3545 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3547 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3548 GNUNET_assert(recent_req != NULL);
3549 if (0 != memcmp(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode)))
3550 increment_stats(STAT_DUPLICATE_UID);
3553 increment_stats(STAT_RECENT_SEEN);
3554 GNUNET_CONTAINER_bloomfilter_or2(msg_ctx->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3559 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3560 recent_req->uid = msg_ctx->unique_id;
3561 memcpy(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3562 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3563 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().abs_value);
3564 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3565 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3568 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3570 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3571 GNUNET_assert(recent_req != NULL);
3572 GNUNET_SCHEDULER_cancel(recent_req->remove_task);
3573 GNUNET_SCHEDULER_add_now(&remove_recent, recent_req);
3577 for (i = 0; i < target_forward_count; i++)
3579 selected = select_peer(&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3581 if (selected != NULL)
3584 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &msg_ctx->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &msg_ctx->key))
3585 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", msg_ctx->hop_count);
3587 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", msg_ctx->hop_count);
3588 if (temp_stat_str != NULL)
3590 increment_stats(temp_stat_str);
3591 GNUNET_free(temp_stat_str);
3593 GNUNET_CONTAINER_bloomfilter_add(msg_ctx->bloom, &selected->id.hashPubKey);
3594 #if DEBUG_DHT_ROUTING > 1
3595 nearest = find_closest_peer(&msg_ctx->key);
3596 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3597 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3598 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3599 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&selected->id), nearest_buf, GNUNET_CRYPTO_hash_matching_bits(&nearest->id.hashPubKey, msg_ctx->key), distance(&nearest->id.hashPubKey, msg_ctx->key));
3600 GNUNET_free(nearest_buf);
3602 #if DEBUG_DHT_ROUTING
3603 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3605 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3606 msg_ctx->hop_count, GNUNET_NO,
3607 &my_identity, &msg_ctx->key, msg_ctx->peer,
3611 forward_message (msg, selected, msg_ctx);
3615 if (msg_ctx->bloom != NULL)
3617 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, msg_ctx->bloom, DHT_BLOOM_SIZE);
3618 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3619 msg_ctx->bloom = NULL;
3622 #if DEBUG_DHT_ROUTING
3623 if (forward_count == 0)
3624 ret = GNUNET_SYSERR;
3628 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3630 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3631 msg_ctx->hop_count, ret,
3632 &my_identity, &msg_ctx->key, msg_ctx->peer,
3641 * Main function that handles whether or not to route a message to other
3644 * @param msg the message to be routed
3645 * @param msg_ctx the context containing all pertinent information about the message
3648 demultiplex_message(const struct GNUNET_MessageHeader *msg,
3649 struct DHT_MessageContext *msg_ctx)
3651 msg_ctx->closest = am_closest_peer(&msg_ctx->key, NULL);
3652 switch (ntohs(msg->type))
3654 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3655 cache_response (msg_ctx);
3656 handle_dht_get (msg, msg_ctx);
3658 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3659 increment_stats(STAT_PUTS);
3660 handle_dht_put (msg, msg_ctx);
3662 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3663 increment_stats(STAT_FIND_PEER);
3664 if (((msg_ctx->hop_count > 0) && (0 != memcmp(msg_ctx->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (msg_ctx->client != NULL))
3666 cache_response (msg_ctx);
3667 if ((msg_ctx->closest == GNUNET_YES) || (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3668 handle_dht_find_peer (msg, msg_ctx);
3671 route_message (msg, msg_ctx);
3672 #if DEBUG_DHT_ROUTING
3673 if (msg_ctx->hop_count == 0) /* Locally initiated request */
3675 if ((debug_routes) && (dhtlog_handle != NULL))
3677 dhtlog_handle->insert_dhtkey(NULL, &msg_ctx->key);
3678 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
3679 msg_ctx->hop_count, GNUNET_NO, &my_identity,
3686 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3687 "`%s': Message type (%d) not handled, forwarding anyway!\n", "DHT", ntohs(msg->type));
3688 route_message (msg, msg_ctx);
3696 * Iterator for local get request results,
3698 * @param cls closure for iterator, NULL
3699 * @param exp when does this value expire?
3700 * @param key the key this data is stored under
3701 * @param size the size of the data identified by key
3702 * @param data the actual data
3703 * @param type the type of the data
3705 * @return GNUNET_OK to continue iteration, anything else
3706 * to stop iteration.
3709 republish_content_iterator (void *cls,
3710 struct GNUNET_TIME_Absolute exp,
3711 const GNUNET_HashCode * key,
3712 size_t size, const char *data, uint32_t type)
3715 struct DHT_MessageContext *new_msg_ctx;
3716 struct GNUNET_DHT_PutMessage *put_msg;
3718 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3719 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3721 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3724 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3725 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3726 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3727 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3728 put_msg->type = htons (type);
3729 memcpy (&put_msg[1], data, size);
3730 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3731 new_msg_ctx->replication = ntohl (DEFAULT_PUT_REPLICATION);
3732 new_msg_ctx->msg_options = ntohl (0);
3733 new_msg_ctx->network_size = estimate_diameter();
3734 new_msg_ctx->peer = &my_identity;
3735 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3736 new_msg_ctx->hop_count = 0;
3737 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3738 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3739 increment_stats(STAT_PUT_START);
3740 demultiplex_message(&put_msg->header, new_msg_ctx);
3742 GNUNET_free(new_msg_ctx);
3743 GNUNET_free (put_msg);
3748 * Task used to republish data.
3750 * @param cls closure (a struct RepublishContext)
3751 * @param tc runtime context for this task
3754 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3756 struct RepublishContext *put_context = cls;
3758 unsigned int results;
3760 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3762 GNUNET_free(put_context);
3766 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3767 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3768 if (results == 0) /* Data must have expired */
3769 GNUNET_free(put_context);
3770 else /* Reschedule task for next time period */
3771 GNUNET_SCHEDULER_add_delayed(dht_republish_frequency, &republish_content, put_context);
3777 * Iterator over hash map entries.
3779 * @param cls client to search for in source routes
3780 * @param key current key code (ignored)
3781 * @param value value in the hash map, a DHTQueryRecord
3782 * @return GNUNET_YES if we should continue to
3786 static int find_client_records (void *cls,
3787 const GNUNET_HashCode * key, void *value)
3789 struct ClientList *client = cls;
3790 struct DHTQueryRecord *record = value;
3791 struct DHTRouteSource *pos;
3795 if (pos->client == client)
3801 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3802 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3803 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3804 GNUNET_SCHEDULER_cancel(pos->delete_task);
3806 if (pos->find_peers_responded != NULL)
3807 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3810 if (record->head == NULL) /* No more entries in DLL */
3812 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3813 GNUNET_free(record);
3819 * Functions with this signature are called whenever a client
3820 * is disconnected on the network level.
3822 * @param cls closure (NULL for dht)
3823 * @param client identification of the client; NULL
3824 * for the last call when the server is destroyed
3826 static void handle_client_disconnect (void *cls,
3827 struct GNUNET_SERVER_Client* client)
3829 struct ClientList *pos = client_list;
3830 struct ClientList *prev;
3831 struct ClientList *found;
3832 struct PendingMessage *reply;
3838 if (pos->client_handle == client)
3841 prev->next = pos->next;
3843 client_list = pos->next;
3853 if (found->transmit_handle != NULL)
3854 GNUNET_CONNECTION_notify_transmit_ready_cancel(found->transmit_handle);
3856 while(NULL != (reply = found->pending_head))
3858 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3861 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3867 * Find a client if it exists, add it otherwise.
3869 * @param client the server handle to the client
3871 * @return the client if found, a new client otherwise
3873 static struct ClientList *
3874 find_active_client (struct GNUNET_SERVER_Client *client)
3876 struct ClientList *pos = client_list;
3877 struct ClientList *ret;
3881 if (pos->client_handle == client)
3886 ret = GNUNET_malloc (sizeof (struct ClientList));
3887 ret->client_handle = client;
3888 ret->next = client_list;
3896 * Task to send a malicious put message across the network.
3898 * @param cls closure for this task
3899 * @param tc the context under which the task is running
3902 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3904 static struct GNUNET_DHT_PutMessage put_message;
3905 static struct DHT_MessageContext msg_ctx;
3906 static GNUNET_HashCode key;
3907 uint32_t random_key;
3909 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3911 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3912 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3913 put_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3914 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3915 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3916 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3917 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3918 memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3919 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3920 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3921 msg_ctx.msg_options = ntohl (0);
3922 msg_ctx.network_size = estimate_diameter();
3923 msg_ctx.peer = &my_identity;
3924 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3925 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3926 #if DEBUG_DHT_ROUTING
3927 if (dhtlog_handle != NULL)
3928 dhtlog_handle->insert_dhtkey(NULL, &key);
3930 increment_stats(STAT_PUT_START);
3931 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3932 demultiplex_message(&put_message.header, &msg_ctx);
3933 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3938 * Task to send a malicious put message across the network.
3940 * @param cls closure for this task
3941 * @param tc the context under which the task is running
3944 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3946 static struct GNUNET_DHT_GetMessage get_message;
3947 struct DHT_MessageContext msg_ctx;
3948 static GNUNET_HashCode key;
3949 uint32_t random_key;
3951 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3954 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3955 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3956 get_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3957 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3958 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3959 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3960 memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3961 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3962 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3963 msg_ctx.msg_options = ntohl (0);
3964 msg_ctx.network_size = estimate_diameter();
3965 msg_ctx.peer = &my_identity;
3966 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3967 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3968 #if DEBUG_DHT_ROUTING
3969 if (dhtlog_handle != NULL)
3970 dhtlog_handle->insert_dhtkey(NULL, &key);
3972 increment_stats(STAT_GET_START);
3973 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3974 demultiplex_message (&get_message.header, &msg_ctx);
3975 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3981 * Iterator over hash map entries.
3983 * @param cls closure
3984 * @param key current key code
3985 * @param value value in the hash map
3986 * @return GNUNET_YES if we should continue to
3991 add_known_to_bloom (void *cls,
3992 const GNUNET_HashCode * key,
3995 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3996 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
4001 * Task to send a find peer message for our own peer identifier
4002 * so that we can find the closest peers in the network to ourselves
4003 * and attempt to connect to them.
4005 * @param cls closure for this task
4006 * @param tc the context under which the task is running
4009 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4011 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
4012 struct DHT_MessageContext msg_ctx;
4013 struct GNUNET_TIME_Relative next_send_time;
4014 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
4016 struct GNUNET_TIME_Relative time_diff;
4017 struct GNUNET_TIME_Absolute end;
4019 double count_per_interval;
4021 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
4024 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! */
4026 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
4027 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
4028 &send_find_peer_message, NULL);
4029 newly_found_peers = 0;
4033 increment_stats(STAT_FIND_PEER_START);
4035 end = GNUNET_TIME_absolute_get();
4036 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
4038 if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
4040 multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
4041 count_per_interval = find_peer_context.count / multiplier;
4045 multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
4046 count_per_interval = find_peer_context.count * multiplier;
4050 #if FIND_PEER_WITH_HELLO
4051 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4052 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4053 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4055 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
4056 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
4058 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4059 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4060 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
4061 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
4062 GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
4063 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4064 memcpy(&msg_ctx.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
4065 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
4066 msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4067 msg_ctx.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4068 msg_ctx.network_size = estimate_diameter();
4069 msg_ctx.peer = &my_identity;
4070 msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4071 msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4073 demultiplex_message(&find_peer_msg->header, &msg_ctx);
4074 GNUNET_free(find_peer_msg);
4075 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4076 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
4078 if (newly_found_peers < bucket_size)
4080 next_send_time.rel_value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4081 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4082 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4086 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4087 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4088 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4091 GNUNET_assert (next_send_time.rel_value != 0);
4092 find_peer_context.count = 0;
4093 newly_found_peers = 0;
4094 find_peer_context.start = GNUNET_TIME_absolute_get();
4095 if (GNUNET_YES == do_find_peer)
4097 GNUNET_SCHEDULER_add_delayed (next_send_time,
4098 &send_find_peer_message, NULL);
4103 * Handler for any generic DHT messages, calls the appropriate handler
4104 * depending on message type, sends confirmation if responses aren't otherwise
4107 * @param cls closure for the service
4108 * @param client the client we received this message from
4109 * @param message the actual message received
4112 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4113 const struct GNUNET_MessageHeader *message)
4115 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
4116 const struct GNUNET_MessageHeader *enc_msg;
4117 struct DHT_MessageContext msg_ctx;
4119 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4122 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4126 ntohs (message->type),
4127 GNUNET_h2s (&dht_msg->key),
4128 GNUNET_ntohll (dht_msg->unique_id));
4130 #if DEBUG_DHT_ROUTING
4131 if (dhtlog_handle != NULL)
4132 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4134 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4135 msg_ctx.client = find_active_client (client);
4136 memcpy(&msg_ctx.key, &dht_msg->key, sizeof(GNUNET_HashCode));
4137 msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4138 msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
4139 msg_ctx.msg_options = ntohl (dht_msg->options);
4140 msg_ctx.network_size = estimate_diameter();
4141 msg_ctx.peer = &my_identity;
4142 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
4143 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4144 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4145 increment_stats(STAT_GET_START);
4146 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4147 increment_stats(STAT_PUT_START);
4148 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4149 increment_stats(STAT_FIND_PEER_START);
4151 demultiplex_message(enc_msg, &msg_ctx);
4153 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4158 * Handler for any locally received DHT control messages,
4159 * sets malicious flags mostly for now.
4161 * @param cls closure for the service
4162 * @param client the client we received this message from
4163 * @param message the actual message received
4167 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4168 const struct GNUNET_MessageHeader *message)
4170 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4171 (const struct GNUNET_DHT_ControlMessage *) message;
4173 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4174 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4175 "CONTROL", ntohs(dht_control_msg->command));
4178 switch (ntohs(dht_control_msg->command))
4180 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4181 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4182 GNUNET_SCHEDULER_add_now(&send_find_peer_message, NULL);
4185 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4186 if (ntohs(dht_control_msg->variable) > 0)
4187 malicious_get_frequency = ntohs(dht_control_msg->variable);
4188 if (malicious_get_frequency == 0)
4189 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4190 if (malicious_getter != GNUNET_YES)
4191 GNUNET_SCHEDULER_add_now(&malicious_get_task, NULL);
4192 malicious_getter = GNUNET_YES;
4193 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4194 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4196 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4197 if (ntohs(dht_control_msg->variable) > 0)
4198 malicious_put_frequency = ntohs(dht_control_msg->variable);
4199 if (malicious_put_frequency == 0)
4200 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4201 if (malicious_putter != GNUNET_YES)
4202 GNUNET_SCHEDULER_add_now(&malicious_put_task, NULL);
4203 malicious_putter = GNUNET_YES;
4204 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4205 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4207 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4208 #if DEBUG_DHT_ROUTING
4209 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4210 dhtlog_handle->set_malicious(&my_identity);
4212 malicious_dropper = GNUNET_YES;
4213 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4214 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4218 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4219 "%s:%s Unknown control command type `%d'!\n",
4221 ntohs(dht_control_msg->command));
4225 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4229 * Handler for any generic DHT stop messages, calls the appropriate handler
4230 * depending on message type (if processed locally)
4232 * @param cls closure for the service
4233 * @param client the client we received this message from
4234 * @param message the actual message received
4238 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4239 const struct GNUNET_MessageHeader *message)
4242 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4243 (const struct GNUNET_DHT_StopMessage *) message;
4244 struct DHTQueryRecord *record;
4245 struct DHTRouteSource *pos;
4247 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4248 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4249 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4251 record = GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &dht_stop_msg->key);
4258 /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
4259 if ((pos->client != NULL) && (pos->client->client_handle == client))
4261 GNUNET_SCHEDULER_cancel(pos->delete_task);
4262 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4263 GNUNET_SCHEDULER_add_continuation (&remove_forward_entry, pos, GNUNET_SCHEDULER_REASON_PREREQ_DONE);
4269 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4274 * Core handler for p2p route requests.
4277 handle_dht_p2p_route_request (void *cls,
4278 const struct GNUNET_PeerIdentity *peer,
4279 const struct GNUNET_MessageHeader *message,
4280 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4283 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4284 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4286 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4287 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4288 struct DHT_MessageContext *msg_ctx;
4290 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4293 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4298 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4304 if (get_max_send_delay().rel_value > MAX_REQUEST_TIME.rel_value)
4306 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending of previous replies took too long, backing off!\n");
4307 increment_stats("# route requests dropped due to high load");
4308 decrease_max_send_delay(get_max_send_delay());
4309 #if DEBUG_DHT_ROUTING
4310 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4312 /** Log routes that die due to high load! */
4313 dhtlog_handle->insert_route (NULL, GNUNET_ntohll(incoming->unique_id), DHTLOG_ROUTE,
4314 ntohl(incoming->hop_count), GNUNET_SYSERR,
4315 &my_identity, &incoming->key, peer,
4321 msg_ctx = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4322 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4323 GNUNET_assert(msg_ctx->bloom != NULL);
4324 msg_ctx->hop_count = ntohl(incoming->hop_count);
4325 memcpy(&msg_ctx->key, &incoming->key, sizeof(GNUNET_HashCode));
4326 msg_ctx->replication = ntohl(incoming->desired_replication_level);
4327 msg_ctx->unique_id = GNUNET_ntohll(incoming->unique_id);
4328 msg_ctx->msg_options = ntohl(incoming->options);
4329 msg_ctx->network_size = ntohl(incoming->network_size);
4330 msg_ctx->peer = peer;
4331 msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4332 msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4333 demultiplex_message (enc_msg, msg_ctx);
4334 if (msg_ctx->bloom != NULL)
4336 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4337 msg_ctx->bloom = NULL;
4339 GNUNET_free(msg_ctx);
4345 * Core handler for p2p route results.
4348 handle_dht_p2p_route_result (void *cls,
4349 const struct GNUNET_PeerIdentity *peer,
4350 const struct GNUNET_MessageHeader *message,
4351 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4354 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4355 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4357 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4358 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4359 struct DHT_MessageContext msg_ctx;
4361 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4367 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4368 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4369 msg_ctx.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4370 GNUNET_assert(msg_ctx.bloom != NULL);
4371 memcpy(&msg_ctx.key, &incoming->key, sizeof(GNUNET_HashCode));
4372 msg_ctx.unique_id = GNUNET_ntohll(incoming->unique_id);
4373 msg_ctx.msg_options = ntohl(incoming->options);
4374 msg_ctx.hop_count = ntohl(incoming->hop_count);
4375 msg_ctx.peer = peer;
4376 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4377 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4378 route_result_message(enc_msg, &msg_ctx);
4384 * Receive the HELLO from transport service,
4385 * free current and replace if necessary.
4388 * @param message HELLO message of peer
4391 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4394 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4395 "Received our `%s' from transport service\n",
4399 GNUNET_assert (message != NULL);
4400 GNUNET_free_non_null(my_hello);
4401 my_hello = GNUNET_malloc(ntohs(message->size));
4402 memcpy(my_hello, message, ntohs(message->size));
4407 * Task run during shutdown.
4413 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4416 struct PeerInfo *pos;
4418 if (transport_handle != NULL)
4420 GNUNET_free_non_null(my_hello);
4421 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4422 GNUNET_TRANSPORT_disconnect(transport_handle);
4424 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4426 while (k_buckets[bucket_count].head != NULL)
4428 pos = k_buckets[bucket_count].head;
4430 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4431 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4433 delete_peer(pos, bucket_count);
4436 if (coreAPI != NULL)
4439 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4440 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4442 GNUNET_CORE_disconnect (coreAPI);
4445 if (datacache != NULL)
4448 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4449 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4451 GNUNET_DATACACHE_destroy (datacache);
4456 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4459 if (dhtlog_handle != NULL)
4461 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4462 dhtlog_handle = NULL;
4464 if (block_context != NULL)
4466 GNUNET_BLOCK_context_destroy (block_context);
4467 block_context = NULL;
4469 GNUNET_free_non_null(my_short_id);
4475 * To be called on core init/fail.
4477 * @param cls service closure
4478 * @param server handle to the server for this service
4479 * @param identity the public identity of this peer
4480 * @param publicKey the public key of this peer
4483 core_init (void *cls,
4484 struct GNUNET_CORE_Handle *server,
4485 const struct GNUNET_PeerIdentity *identity,
4486 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4493 "%s: Connection to core FAILED!\n", "dht",
4494 GNUNET_i2s (identity));
4496 GNUNET_SCHEDULER_cancel (cleanup_task);
4497 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4502 "%s: Core connection initialized, I am peer: %s\n", "dht",
4503 GNUNET_i2s (identity));
4506 /* Copy our identity so we can use it */
4507 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4508 if (my_short_id != NULL)
4509 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4510 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4511 /* Set the server to local variable */
4514 if (dhtlog_handle != NULL)
4515 dhtlog_handle->insert_node (NULL, &my_identity);
4519 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4520 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4521 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4522 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4527 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4528 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4529 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4535 * Method called whenever a peer connects.
4537 * @param cls closure
4538 * @param peer peer identity this notification is about
4539 * @param atsi performance data
4542 handle_core_connect (void *cls,
4543 const struct GNUNET_PeerIdentity * peer,
4544 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4546 struct PeerInfo *ret;
4549 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4550 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4553 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4555 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));
4559 if (datacache != NULL)
4560 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, GNUNET_BLOCK_TYPE_DHT_HELLO, GNUNET_TIME_absolute_get_forever());
4561 ret = try_add_peer(peer,
4562 find_current_bucket(&peer->hashPubKey),
4566 newly_found_peers++;
4567 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4570 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4571 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4577 * Method called whenever a peer disconnects.
4579 * @param cls closure
4580 * @param peer peer identity this notification is about
4583 handle_core_disconnect (void *cls,
4585 GNUNET_PeerIdentity * peer)
4587 struct PeerInfo *to_remove;
4590 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");
4592 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4594 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));
4597 increment_stats(STAT_DISCONNECTS);
4598 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4599 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4600 GNUNET_assert (to_remove != NULL);
4601 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4602 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4603 delete_peer(to_remove, current_bucket);
4608 * Process dht requests.
4610 * @param cls closure
4611 * @param server the initialized server
4612 * @param c configuration to use
4616 struct GNUNET_SERVER_Handle *server,
4617 const struct GNUNET_CONFIGURATION_Handle *c)
4619 struct GNUNET_TIME_Relative next_send_time;
4620 unsigned long long temp_config_num;
4621 char *converge_modifier_buf;
4624 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4625 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4626 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4627 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
4628 DEFAULT_CORE_QUEUE_SIZE, /* queue size */
4629 NULL, /* Closure passed to DHT functions */
4630 &core_init, /* Call core_init once connected */
4631 &handle_core_connect, /* Handle connects */
4632 &handle_core_disconnect, /* remove peers on disconnects */
4633 NULL, /* Do we care about "status" updates? */
4634 NULL, /* Don't want notified about all incoming messages */
4635 GNUNET_NO, /* For header only inbound notification */
4636 NULL, /* Don't want notified about all outbound messages */
4637 GNUNET_NO, /* For header only outbound notification */
4638 core_handlers); /* Register these handlers */
4640 if (coreAPI == NULL)
4642 transport_handle = GNUNET_TRANSPORT_connect(cfg,
4643 NULL, NULL, NULL, NULL, NULL);
4644 if (transport_handle != NULL)
4645 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4647 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4648 "Failed to connect to transport service!\n");
4649 block_context = GNUNET_BLOCK_context_create (cfg);
4650 lowest_bucket = MAX_BUCKETS - 1;
4651 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4652 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4653 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4654 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4655 GNUNET_assert(all_known_peers != NULL);
4656 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4658 debug_routes = GNUNET_YES;
4662 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4665 strict_kademlia = GNUNET_YES;
4669 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4672 stop_on_closest = GNUNET_YES;
4676 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4679 stop_on_found = GNUNET_YES;
4683 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4684 "malicious_getter"))
4686 malicious_getter = GNUNET_YES;
4687 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4688 "MALICIOUS_GET_FREQUENCY",
4689 &malicious_get_frequency))
4690 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4693 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4697 max_hops = DEFAULT_MAX_HOPS;
4700 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4703 use_max_hops = GNUNET_YES;
4707 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4708 "malicious_putter"))
4710 malicious_putter = GNUNET_YES;
4711 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4712 "MALICIOUS_PUT_FREQUENCY",
4713 &malicious_put_frequency))
4714 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4717 dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
4718 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4720 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4723 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "bucket_size", &temp_config_num))
4725 bucket_size = (unsigned int)temp_config_num;
4728 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "kad_alpha", &kademlia_replication))
4730 kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
4734 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4735 "malicious_dropper"))
4737 malicious_dropper = GNUNET_YES;
4741 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4743 do_republish = GNUNET_NO;
4746 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4749 do_find_peer = GNUNET_NO;
4752 do_find_peer = GNUNET_YES;
4755 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4756 "use_real_distance"))
4757 use_real_distance = GNUNET_YES;
4760 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4761 "mysql_logging_extended"))
4763 debug_routes = GNUNET_YES;
4764 debug_routes_extended = GNUNET_YES;
4767 #if DEBUG_DHT_ROUTING
4768 if (GNUNET_YES == debug_routes)
4770 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4771 if (dhtlog_handle == NULL)
4773 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4774 "Could not connect to mysql logging server, logging will not happen!");
4779 converge_option = DHT_CONVERGE_SQUARE;
4781 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4784 converge_option = DHT_CONVERGE_LINEAR;
4786 else if (GNUNET_YES ==
4787 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4788 "converge_exponential"))
4790 converge_option = DHT_CONVERGE_EXPONENTIAL;
4792 else if (GNUNET_YES ==
4793 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4796 converge_option = DHT_CONVERGE_RANDOM;
4798 else if (GNUNET_YES ==
4799 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4802 converge_option = DHT_CONVERGE_BINARY;
4805 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht", "converge_modifier", &converge_modifier_buf))
4807 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4809 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4810 converge_modifier = 0.0;
4812 GNUNET_free(converge_modifier_buf);
4815 stats = GNUNET_STATISTICS_create("dht", cfg);
4819 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4820 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4821 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4822 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4823 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4824 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4825 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4826 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4827 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4828 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4829 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4830 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4831 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4832 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4833 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4834 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4835 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4836 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4837 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4838 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4840 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4841 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4842 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4843 if (GNUNET_YES == do_find_peer)
4845 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4846 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4847 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4848 find_peer_context.start = GNUNET_TIME_absolute_get();
4849 GNUNET_SCHEDULER_add_delayed (next_send_time,
4850 &send_find_peer_message, &find_peer_context);
4853 /* Scheduled the task to clean up when shutdown is called */
4854 cleanup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4855 &shutdown_task, NULL);
4859 * The main function for the dht service.
4861 * @param argc number of arguments from the command line
4862 * @param argv command line arguments
4863 * @return 0 ok, 1 on error
4866 main (int argc, char *const *argv)
4871 GNUNET_SERVICE_run (argc,
4874 GNUNET_SERVICE_OPTION_NONE,
4875 &run, NULL)) ? 0 : 1;
4876 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap));
4877 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap));
4878 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4879 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4880 GNUNET_CONTAINER_heap_destroy (recent.minHeap);