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;
1149 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1150 msize = ntohs(pending->msg->size);
1154 memcpy (cbuf, pending->msg, msize);
1155 peer->pending_count--;
1156 increment_stats("# pending messages sent");
1157 GNUNET_assert(peer->pending_count >= 0);
1158 GNUNET_CONTAINER_DLL_remove (peer->head,
1161 GNUNET_free (pending);
1164 while (NULL != pending &&
1165 (size - off >= (msize = ntohs (pending->msg->size))))
1167 memcpy (&cbuf[off], pending->msg, msize);
1169 peer->pending_count--;
1170 increment_stats("# pending messages sent");
1171 GNUNET_assert(peer->pending_count >= 0);
1172 GNUNET_CONTAINER_DLL_remove (peer->head,
1175 GNUNET_free (pending);
1176 pending = peer->head;
1179 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1180 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1187 * Compute the distance between have and target as a 32-bit value.
1188 * Differences in the lower bits must count stronger than differences
1189 * in the higher bits.
1191 * @return 0 if have==target, otherwise a number
1192 * that is larger as the distance between
1193 * the two hash codes increases
1196 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1198 unsigned int bucket;
1203 /* We have to represent the distance between two 2^9 (=512)-bit
1204 numbers as a 2^5 (=32)-bit number with "0" being used for the
1205 two numbers being identical; furthermore, we need to
1206 guarantee that a difference in the number of matching
1207 bits is always represented in the result.
1209 We use 2^32/2^9 numerical values to distinguish between
1210 hash codes that have the same LSB bit distance and
1211 use the highest 2^9 bits of the result to signify the
1212 number of (mis)matching LSB bits; if we have 0 matching
1213 and hence 512 mismatching LSB bits we return -1 (since
1214 512 itself cannot be represented with 9 bits) */
1216 /* first, calculate the most significant 9 bits of our
1217 result, aka the number of LSBs */
1218 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1219 /* bucket is now a value between 0 and 512 */
1221 return 0; /* perfect match */
1223 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1224 below, we'd end up with max+1 (overflow)) */
1226 /* calculate the most significant bits of the final result */
1227 msb = (512 - bucket) << (32 - 9);
1228 /* calculate the 32-9 least significant bits of the final result by
1229 looking at the differences in the 32-9 bits following the
1230 mismatching bit at 'bucket' */
1232 for (i = bucket + 1;
1233 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1235 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1236 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1237 last bit set will be 31 -- if
1238 i does not reach 512 first... */
1244 * Return a number that is larger the closer the
1245 * "have" GNUNET_hash code is to the "target".
1247 * @return inverse distance metric, non-zero.
1248 * Must fudge the value if NO bits match.
1251 inverse_distance (const GNUNET_HashCode * target,
1252 const GNUNET_HashCode * have)
1254 if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1255 return 1; /* Never return 0! */
1256 return ((unsigned int) -1) - distance (target, have);
1260 * Find the optimal bucket for this key, regardless
1261 * of the current number of buckets in use.
1263 * @param hc the hashcode to compare our identity to
1265 * @return the proper bucket index, or GNUNET_SYSERR
1266 * on error (same hashcode)
1268 static int find_bucket(const GNUNET_HashCode *hc)
1272 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1273 if (bits == MAX_BUCKETS)
1274 return GNUNET_SYSERR;
1275 return MAX_BUCKETS - bits - 1;
1279 * Find which k-bucket this peer should go into,
1280 * taking into account the size of the k-bucket
1281 * array. This means that if more bits match than
1282 * there are currently buckets, lowest_bucket will
1285 * @param hc GNUNET_HashCode we are finding the bucket for.
1287 * @return the proper bucket index for this key,
1288 * or GNUNET_SYSERR on error (same hashcode)
1290 static int find_current_bucket(const GNUNET_HashCode *hc)
1293 actual_bucket = find_bucket(hc);
1295 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1296 return lowest_bucket;
1297 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1298 return lowest_bucket;
1300 return actual_bucket;
1305 * Find a routing table entry from a peer identity
1307 * @param peer the peer to look up
1309 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1312 find_bucket_by_peer(const struct PeerInfo *peer)
1315 struct PeerInfo *pos;
1317 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1319 pos = k_buckets[bucket].head;
1328 return GNUNET_SYSERR; /* No such peer. */
1334 * Print the complete routing table for this peer.
1337 print_routing_table ()
1340 struct PeerInfo *pos;
1341 char char_buf[30000];
1343 memset(char_buf, 0, sizeof(char_buf));
1345 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1346 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1347 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1349 pos = k_buckets[bucket].head;
1350 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1351 //fprintf(stderr, "Bucket %d:\n", bucket);
1354 //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));
1355 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));
1359 fprintf(stderr, "%s", char_buf);
1365 * Find a routing table entry from a peer identity
1367 * @param peer the peer identity to look up
1369 * @return the routing table entry, or NULL if not found
1371 static struct PeerInfo *
1372 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1375 struct PeerInfo *pos;
1376 bucket = find_current_bucket(&peer->hashPubKey);
1378 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1381 pos = k_buckets[bucket].head;
1384 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1388 return NULL; /* No such peer. */
1391 /* Forward declaration */
1393 update_core_preference (void *cls,
1394 const struct GNUNET_SCHEDULER_TaskContext *tc);
1396 * Function called with statistics about the given peer.
1398 * @param cls closure
1399 * @param peer identifies the peer
1400 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1401 * @param amount set to the amount that was actually reserved or unreserved;
1402 * either the full requested amount or zero (no partial reservations)
1403 * @param preference current traffic preference for the given peer
1406 update_core_preference_finish (void *cls,
1407 const struct GNUNET_PeerIdentity * peer,
1408 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1409 int amount, uint64_t preference)
1411 struct PeerInfo *peer_info = cls;
1412 peer_info->info_ctx = NULL;
1413 GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1417 update_core_preference (void *cls,
1418 const struct GNUNET_SCHEDULER_TaskContext *tc)
1420 struct PeerInfo *peer = cls;
1421 uint64_t preference;
1422 unsigned int matching;
1423 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1427 matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1430 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1433 preference = 1LL << matching;
1434 peer->info_ctx = GNUNET_CORE_peer_change_preference (coreAPI,
1436 GNUNET_TIME_relative_get_forever(),
1437 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1440 &update_core_preference_finish,
1445 * Really add a peer to a bucket (only do assertions
1448 * @param peer GNUNET_PeerIdentity of the peer to add
1449 * @param bucket the already figured out bucket to add
1451 * @param atsi performance information
1453 * @return the newly added PeerInfo
1455 static struct PeerInfo *
1456 add_peer(const struct GNUNET_PeerIdentity *peer,
1457 unsigned int bucket,
1458 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1460 struct PeerInfo *new_peer;
1461 GNUNET_assert(bucket < MAX_BUCKETS);
1462 GNUNET_assert(peer != NULL);
1463 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1465 new_peer->latency = latency;
1466 new_peer->distance = distance;
1469 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1471 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1472 k_buckets[bucket].tail,
1473 k_buckets[bucket].tail,
1475 k_buckets[bucket].peers_size++;
1477 if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1479 #if DO_UPDATE_PREFERENCE
1480 new_peer->preference_task = GNUNET_SCHEDULER_add_now(&update_core_preference, new_peer);
1488 * Given a peer and its corresponding bucket,
1489 * remove it from that bucket. Does not free
1490 * the PeerInfo struct, nor cancel messages
1491 * or free messages waiting to be sent to this
1494 * @param peer the peer to remove
1495 * @param bucket the bucket the peer belongs to
1497 static void remove_peer (struct PeerInfo *peer,
1498 unsigned int bucket)
1500 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1501 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1502 k_buckets[bucket].tail,
1504 k_buckets[bucket].peers_size--;
1506 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1512 * Removes peer from a bucket, then frees associated
1513 * resources and frees peer.
1515 * @param peer peer to be removed and freed
1516 * @param bucket which bucket this peer belongs to
1518 static void delete_peer (struct PeerInfo *peer,
1519 unsigned int bucket)
1521 struct P2PPendingMessage *pos;
1522 struct P2PPendingMessage *next;
1524 struct PeerInfo *peer_pos;
1526 peer_pos = k_buckets[bucket].head;
1527 while ((peer_pos != NULL) && (peer_pos != peer))
1528 peer_pos = peer_pos->next;
1529 if (peer_pos == NULL)
1531 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1532 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));
1534 GNUNET_assert(peer_pos != NULL);
1536 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1538 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1539 GNUNET_SCHEDULER_cancel(peer->send_task);
1540 if ((peer->th != NULL) && (coreAPI != NULL))
1541 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1544 while (pos != NULL) /* Remove any pending messages for this peer */
1546 increment_stats("# dht pending messages discarded (due to disconnect/shutdown)");
1552 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1553 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer));
1559 * Iterator over hash map entries.
1561 * @param cls closure
1562 * @param key current key code
1563 * @param value PeerInfo of the peer to move to new lowest bucket
1564 * @return GNUNET_YES if we should continue to
1568 static int move_lowest_bucket (void *cls,
1569 const GNUNET_HashCode * key,
1572 struct PeerInfo *peer = value;
1575 GNUNET_assert(lowest_bucket > 0);
1576 new_bucket = lowest_bucket - 1;
1577 remove_peer(peer, lowest_bucket);
1578 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1579 k_buckets[new_bucket].tail,
1580 k_buckets[new_bucket].tail,
1582 k_buckets[new_bucket].peers_size++;
1588 * The current lowest bucket is full, so change the lowest
1589 * bucket to the next lower down, and move any appropriate
1590 * entries in the current lowest bucket to the new bucket.
1592 static void enable_next_bucket()
1594 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1595 struct PeerInfo *pos;
1596 GNUNET_assert(lowest_bucket > 0);
1597 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1598 pos = k_buckets[lowest_bucket].head;
1601 fprintf(stderr, "Printing RT before new bucket\n");
1602 print_routing_table();
1604 /* Populate the array of peers which should be in the next lowest bucket */
1607 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1608 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1612 /* Remove peers from lowest bucket, insert into next lowest bucket */
1613 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1614 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1615 lowest_bucket = lowest_bucket - 1;
1617 fprintf(stderr, "Printing RT after new bucket\n");
1618 print_routing_table();
1623 * Find the closest peer in our routing table to the
1626 * @return The closest peer in our routing table to the
1627 * key, or NULL on error.
1629 static struct PeerInfo *
1630 find_closest_peer (const GNUNET_HashCode *hc)
1632 struct PeerInfo *pos;
1633 struct PeerInfo *current_closest;
1634 unsigned int lowest_distance;
1635 unsigned int temp_distance;
1639 lowest_distance = -1;
1641 if (k_buckets[lowest_bucket].peers_size == 0)
1644 current_closest = NULL;
1645 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1647 pos = k_buckets[bucket].head;
1649 while ((pos != NULL) && (count < bucket_size))
1651 temp_distance = distance(&pos->id.hashPubKey, hc);
1652 if (temp_distance <= lowest_distance)
1654 lowest_distance = temp_distance;
1655 current_closest = pos;
1661 GNUNET_assert(current_closest != NULL);
1662 return current_closest;
1667 * Function called to send a request out to another peer.
1668 * Called both for locally initiated requests and those
1669 * received from other peers.
1671 * @param msg the encapsulated message
1672 * @param peer the peer to forward the message to
1673 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1675 static void forward_message (const struct GNUNET_MessageHeader *msg,
1676 struct PeerInfo *peer,
1677 struct DHT_MessageContext *msg_ctx)
1679 struct GNUNET_DHT_P2PRouteMessage *route_message;
1680 struct P2PPendingMessage *pending;
1684 increment_stats(STAT_ROUTE_FORWARDS);
1685 GNUNET_assert(peer != NULL);
1686 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1687 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1689 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1690 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1691 psize = sizeof(struct P2PPendingMessage) + msize;
1692 pending = GNUNET_malloc(psize);
1693 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1694 pending->importance = msg_ctx->importance;
1695 pending->timeout = msg_ctx->timeout;
1696 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1697 route_message->header.size = htons(msize);
1698 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1699 route_message->options = htonl(msg_ctx->msg_options);
1700 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1701 route_message->network_size = htonl(msg_ctx->network_size);
1702 route_message->desired_replication_level = htonl(msg_ctx->replication);
1703 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1704 if (msg_ctx->bloom != NULL)
1705 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1706 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1707 memcpy(&route_message[1], msg, ntohs(msg->size));
1709 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));
1711 peer->pending_count++;
1712 increment_stats("# pending messages scheduled");
1713 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1714 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1715 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1720 * Task used to send ping messages to peers so that
1721 * they don't get disconnected.
1723 * @param cls the peer to send a ping message to
1724 * @param tc context, reason, etc.
1727 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1729 struct PeerInfo *peer = cls;
1730 struct GNUNET_MessageHeader ping_message;
1731 struct DHT_MessageContext msg_ctx;
1733 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1736 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1737 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1739 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
1741 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1743 forward_message(&ping_message, peer, &msg_ctx);
1744 peer->ping_task = GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1748 * Schedule PING messages for the top X peers in each
1749 * bucket of the routing table (so core won't disconnect them!)
1751 void schedule_ping_messages()
1753 unsigned int bucket;
1755 struct PeerInfo *pos;
1756 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1758 pos = k_buckets[bucket].head;
1762 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1763 GNUNET_SCHEDULER_add_now(&periodic_ping_task, pos);
1764 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1766 GNUNET_SCHEDULER_cancel(pos->ping_task);
1767 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1777 * Attempt to add a peer to our k-buckets.
1779 * @param peer the peer identity of the peer being added
1780 * @param bucket the bucket that we want this peer to go in
1781 * @param latency transport latency of this peer
1782 * @param distance transport distance to this peer
1784 * @return NULL if the peer was not added,
1785 * pointer to PeerInfo for new peer otherwise
1787 static struct PeerInfo *
1788 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1789 unsigned int bucket,
1790 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1793 struct PeerInfo *new_peer;
1795 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1798 peer_bucket = find_current_bucket(&peer->hashPubKey);
1800 GNUNET_assert(peer_bucket >= lowest_bucket);
1801 new_peer = add_peer(peer, peer_bucket, atsi);
1803 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1804 enable_next_bucket();
1806 schedule_ping_messages();
1813 * Task run to check for messages that need to be sent to a client.
1815 * @param client a ClientList, containing the client and any messages to be sent to it
1818 process_pending_messages (struct ClientList *client)
1820 if (client->pending_head == NULL)
1822 if (client->transmit_handle != NULL)
1825 client->transmit_handle =
1826 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1827 ntohs (client->pending_head->msg->
1829 GNUNET_TIME_UNIT_FOREVER_REL,
1830 &send_generic_reply, client);
1834 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1835 * request. A ClientList is passed as closure, take the head of the list
1836 * and copy it into buf, which has the result of sending the message to the
1839 * @param cls closure to this call
1840 * @param size maximum number of bytes available to send
1841 * @param buf where to copy the actual message to
1843 * @return the number of bytes actually copied, 0 indicates failure
1846 send_generic_reply (void *cls, size_t size, void *buf)
1848 struct ClientList *client = cls;
1850 struct PendingMessage *reply;
1854 client->transmit_handle = NULL;
1857 /* client disconnected */
1861 while ( (NULL != (reply = client->pending_head)) &&
1862 (size >= off + (msize = ntohs (reply->msg->size))))
1864 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1865 client->pending_tail,
1867 memcpy (&cbuf[off], reply->msg, msize);
1868 GNUNET_free (reply);
1871 process_pending_messages (client);
1873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1874 "Transmitted %u bytes of replies to client\n",
1875 (unsigned int) off);
1882 * Add a PendingMessage to the clients list of messages to be sent
1884 * @param client the active client to send the message to
1885 * @param pending_message the actual message to send
1888 add_pending_message (struct ClientList *client,
1889 struct PendingMessage *pending_message)
1891 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1892 client->pending_tail,
1893 client->pending_tail,
1895 process_pending_messages (client);
1900 * Called when a reply needs to be sent to a client, as
1901 * a result it found to a GET or FIND PEER request.
1903 * @param client the client to send the reply to
1904 * @param message the encapsulated message to send
1905 * @param uid the unique identifier of this request
1908 send_reply_to_client (struct ClientList *client,
1909 const struct GNUNET_MessageHeader *message,
1910 unsigned long long uid,
1911 const GNUNET_HashCode *key)
1913 struct GNUNET_DHT_RouteResultMessage *reply;
1914 struct PendingMessage *pending_message;
1918 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1919 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1921 msize = ntohs (message->size);
1922 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1923 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1925 GNUNET_break_op (0);
1928 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1929 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1930 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1931 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1932 reply->header.size = htons (tsize);
1933 reply->put_path_length = htons(0); /* FIXME: implement */
1934 reply->get_path_length = htons(0); /* FIXME: implement */
1935 reply->unique_id = GNUNET_htonll (uid);
1937 memcpy (&reply[1], message, msize);
1938 add_pending_message (client, pending_message);
1942 * Consider whether or not we would like to have this peer added to
1943 * our routing table. Check whether bucket for this peer is full,
1944 * if so return negative; if not return positive. Since peers are
1945 * only added on CORE level connect, this doesn't actually add the
1946 * peer to the routing table.
1948 * @param peer the peer we are considering adding
1950 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1953 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1957 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1958 return GNUNET_NO; /* We already know this peer (are connected even!) */
1959 bucket = find_current_bucket(&peer->hashPubKey);
1961 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1969 * Task used to remove forwarding entries, either
1970 * after timeout, when full, or on shutdown.
1972 * @param cls the entry to remove
1973 * @param tc context, reason, etc.
1976 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1978 struct DHTRouteSource *source_info = cls;
1979 struct DHTQueryRecord *record;
1980 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
1981 record = source_info->record;
1982 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
1984 if (record->head == NULL) /* No more entries in DLL */
1986 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap, &record->key, record));
1987 GNUNET_free(record);
1989 if (source_info->find_peers_responded != NULL)
1990 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
1991 GNUNET_free(source_info);
1995 * Main function that handles whether or not to route a result
1996 * message to other peers, or to send to our local client.
1998 * @param msg the result message to be routed
1999 * @param msg_ctx context of the message we are routing
2001 * @return the number of peers the message was routed to,
2002 * GNUNET_SYSERR on failure
2004 static int route_result_message(struct GNUNET_MessageHeader *msg,
2005 struct DHT_MessageContext *msg_ctx)
2007 struct GNUNET_PeerIdentity new_peer;
2008 struct DHTQueryRecord *record;
2009 struct DHTRouteSource *pos;
2010 struct PeerInfo *peer_info;
2011 const struct GNUNET_MessageHeader *hello_msg;
2013 increment_stats(STAT_RESULTS);
2015 * If a find peer result message is received and contains a valid
2016 * HELLO for another peer, offer it to the transport service.
2018 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
2020 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
2023 hello_msg = &msg[1];
2024 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
2026 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
2030 else /* We have a valid hello, and peer id stored in new_peer */
2032 find_peer_context.count++;
2033 increment_stats(STAT_FIND_PEER_REPLY);
2034 if (GNUNET_YES == consider_peer(&new_peer))
2036 increment_stats(STAT_HELLOS_PROVIDED);
2037 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
2038 GNUNET_CORE_peer_request_connect(coreAPI,
2039 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
2044 if (malicious_dropper == GNUNET_YES)
2047 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2049 if (record == NULL) /* No record of this message! */
2052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2053 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
2054 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2056 #if DEBUG_DHT_ROUTING
2057 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2059 dhtlog_handle->insert_route (NULL,
2066 msg_ctx->peer, NULL);
2069 if (msg_ctx->bloom != NULL)
2071 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
2072 msg_ctx->bloom = NULL;
2080 #if STRICT_FORWARDING
2081 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2083 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2085 increment_stats("# find peer responses NOT forwarded (bloom match)");
2090 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2094 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2097 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2098 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2099 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2101 #if DEBUG_DHT_ROUTING
2102 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2104 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2106 GNUNET_YES, &my_identity, &msg_ctx->key,
2107 msg_ctx->peer, NULL);
2110 increment_stats(STAT_RESULTS_TO_CLIENT);
2111 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2112 increment_stats(STAT_GET_REPLY);
2114 send_reply_to_client(pos->client, msg,
2118 else /* Send to peer */
2120 peer_info = find_peer_by_id(&pos->source);
2121 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2127 if (msg_ctx->bloom == NULL)
2128 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2129 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
2130 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom, &peer_info->id.hashPubKey)))
2133 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2134 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2135 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&peer_info->id));
2137 #if DEBUG_DHT_ROUTING
2138 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2140 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id,
2143 GNUNET_NO, &my_identity, &msg_ctx->key,
2144 msg_ctx->peer, &pos->source);
2147 forward_result_message (msg, peer_info, msg_ctx);
2148 /* Try removing forward entries after sending once, only allows ONE response per request */
2149 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
2151 GNUNET_SCHEDULER_cancel(pos->delete_task);
2152 pos->delete_task = GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
2158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2159 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2160 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&peer_info->id));
2166 if (msg_ctx->bloom != NULL)
2168 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
2169 msg_ctx->bloom = NULL;
2175 * Iterator for local get request results,
2177 * @param cls closure for iterator, a DatacacheGetContext
2178 * @param exp when does this value expire?
2179 * @param key the key this data is stored under
2180 * @param size the size of the data identified by key
2181 * @param data the actual data
2182 * @param type the type of the data
2184 * @return GNUNET_OK to continue iteration, anything else
2185 * to stop iteration.
2188 datacache_get_iterator (void *cls,
2189 struct GNUNET_TIME_Absolute exp,
2190 const GNUNET_HashCode * key,
2191 size_t size, const char *data,
2192 enum GNUNET_BLOCK_Type type)
2194 struct DHT_MessageContext *msg_ctx = cls;
2195 struct DHT_MessageContext *new_msg_ctx;
2196 struct GNUNET_DHT_GetResultMessage *get_result;
2197 enum GNUNET_BLOCK_EvaluationResult eval;
2200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2201 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2203 eval = GNUNET_BLOCK_evaluate (block_context,
2207 msg_ctx->reply_bf_mutator,
2209 msg_ctx->xquery_size,
2214 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2215 msg_ctx->do_forward = GNUNET_NO;
2216 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2217 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2218 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2220 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2221 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2222 get_result->header.size =
2223 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2224 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2225 get_result->type = htons (type);
2226 memcpy (&get_result[1], data, size);
2227 new_msg_ctx->peer = &my_identity;
2228 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2229 new_msg_ctx->hop_count = 0;
2230 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
2231 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2232 increment_stats(STAT_GET_RESPONSE_START);
2233 route_result_message(&get_result->header, new_msg_ctx);
2234 GNUNET_free(new_msg_ctx);
2235 GNUNET_free (get_result);
2237 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2239 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2240 "`%s:%s': Duplicate block error\n", my_short_id, "DHT");
2243 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2245 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2246 "`%s:%s': Invalid request error\n", my_short_id, "DHT");
2249 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2251 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2252 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2256 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2257 GNUNET_break_op (0);
2258 msg_ctx->do_forward = GNUNET_NO;
2260 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2262 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2263 "`%s:%s': Unsupported block type (%u) in response!\n", my_short_id, "DHT", type);
2265 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2273 * Main function that handles whether or not to route a message to other
2276 * @param msg the message to be routed
2277 * @param msg_ctx the context containing all pertinent information about the message
2280 route_message(const struct GNUNET_MessageHeader *msg,
2281 struct DHT_MessageContext *msg_ctx);
2285 * Server handler for all dht get requests, look for data,
2286 * if found, send response either to clients or other peers.
2288 * @param msg the actual get message
2289 * @param msg_ctx struct containing pertinent information about the get request
2291 * @return number of items found for GET request
2294 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2295 struct DHT_MessageContext *msg_ctx)
2297 const struct GNUNET_DHT_GetMessage *get_msg;
2300 unsigned int results;
2302 enum GNUNET_BLOCK_Type type;
2304 msize = ntohs (msg->size);
2305 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2310 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2311 bf_size = ntohs (get_msg->bf_size);
2312 msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2313 msg_ctx->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2314 if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2319 end = (const char*) &get_msg[1];
2320 if (msg_ctx->xquery_size == 0)
2322 msg_ctx->xquery = NULL;
2326 msg_ctx->xquery = (const void*) end;
2327 end += msg_ctx->xquery_size;
2331 msg_ctx->reply_bf = NULL;
2335 msg_ctx->reply_bf = GNUNET_CONTAINER_bloomfilter_init (end,
2337 GNUNET_DHT_GET_BLOOMFILTER_K);
2339 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2341 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2342 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2346 GNUNET_h2s (&msg_ctx->key),
2347 msg_ctx->unique_id);
2349 increment_stats(STAT_GETS);
2352 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2354 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2358 msg_ctx->do_forward = GNUNET_YES;
2359 if (datacache != NULL)
2361 = GNUNET_DATACACHE_get (datacache,
2362 &msg_ctx->key, type,
2363 &datacache_get_iterator,
2366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2367 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2368 results, "GET", msg_ctx->unique_id);
2372 #if DEBUG_DHT_ROUTING
2373 if ((debug_routes) && (dhtlog_handle != NULL))
2375 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2376 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2380 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2382 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2383 msg_ctx->hop_count, GNUNET_YES,
2384 &my_identity, &msg_ctx->key, msg_ctx->peer,
2391 /* check query valid */
2392 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID
2393 == GNUNET_BLOCK_evaluate (block_context,
2397 msg_ctx->reply_bf_mutator,
2399 msg_ctx->xquery_size,
2402 GNUNET_break_op (0);
2403 msg_ctx->do_forward = GNUNET_NO;
2407 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2409 #if DEBUG_DHT_ROUTING
2410 if ((debug_routes) && (dhtlog_handle != NULL))
2412 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2413 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2418 if (msg_ctx->do_forward == GNUNET_YES)
2419 route_message (msg, msg_ctx);
2420 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2425 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2427 GNUNET_HashCode *key = cls;
2429 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, NULL));
2434 * Server handler for initiating local dht find peer requests
2436 * @param find_msg the actual find peer message
2437 * @param msg_ctx struct containing pertinent information about the request
2441 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2442 struct DHT_MessageContext *msg_ctx)
2444 struct GNUNET_MessageHeader *find_peer_result;
2445 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2446 struct DHT_MessageContext *new_msg_ctx;
2447 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2450 GNUNET_HashCode *recent_hash;
2451 struct GNUNET_MessageHeader *other_hello;
2452 size_t other_hello_size;
2453 struct GNUNET_PeerIdentity peer_id;
2455 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2456 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2457 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2460 other_hello_size = 0;
2461 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2463 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2464 other_hello = GNUNET_malloc(other_hello_size);
2465 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2466 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)))
2468 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2469 GNUNET_free(other_hello);
2472 #if FIND_PEER_WITH_HELLO
2473 if (GNUNET_YES == consider_peer(&peer_id))
2475 increment_stats(STAT_HELLOS_PROVIDED);
2476 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2477 GNUNET_CORE_peer_request_connect(coreAPI,
2478 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2479 route_message (find_msg, msg_ctx);
2480 GNUNET_free (other_hello);
2483 else /* We don't want this peer! */
2485 route_message (find_msg, msg_ctx);
2486 GNUNET_free (other_hello);
2493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2494 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2495 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2496 ntohs (find_msg->size),
2497 sizeof (struct GNUNET_MessageHeader));
2499 if (my_hello == NULL)
2502 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2503 "`%s': Our HELLO is null, can't return.\n",
2506 GNUNET_free_non_null (other_hello);
2507 route_message (find_msg, msg_ctx);
2511 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2512 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2514 increment_stats(STAT_BLOOM_FIND_PEER);
2515 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2516 GNUNET_free_non_null(other_hello);
2517 route_message (find_msg, msg_ctx);
2518 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2520 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2522 #if RESTRICT_FIND_PEER
2525 * Ignore any find peer requests from a peer we have seen very recently.
2527 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! */
2529 increment_stats("# dht find peer requests ignored (recently seen!)");
2530 GNUNET_free_non_null(other_hello);
2535 * Use this check to only allow the peer to respond to find peer requests if
2536 * it would be beneficial to have the requesting peer in this peers routing
2537 * table. Can be used to thwart peers flooding the network with find peer
2538 * requests that we don't care about. However, if a new peer is joining
2539 * the network and has no other peers this is a problem (assume all buckets
2540 * full, no one will respond!).
2542 memcpy(&peer_id.hashPubKey, &msg_ctx->key, sizeof(GNUNET_HashCode));
2543 if (GNUNET_NO == consider_peer(&peer_id))
2545 increment_stats("# dht find peer requests ignored (do not need!)");
2546 GNUNET_free_non_null(other_hello);
2547 route_message (find_msg, msg_ctx);
2552 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2553 memcpy(recent_hash, &msg_ctx->key, sizeof(GNUNET_HashCode));
2554 if (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2555 &msg_ctx->key, NULL,
2556 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2558 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding recent remove task for key `%s`!\n", GNUNET_h2s(&msg_ctx->key));
2559 /* Only add a task if there wasn't one for this key already! */
2560 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30),
2561 &remove_recent_find_peer, recent_hash);
2565 GNUNET_free(recent_hash);
2566 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received duplicate find peer request too soon!\n");
2569 /* Simplistic find_peer functionality, always return our hello */
2570 hello_size = ntohs(my_hello->size);
2571 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2573 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2575 GNUNET_break_op (0);
2576 GNUNET_free_non_null(other_hello);
2580 find_peer_result = GNUNET_malloc (tsize);
2581 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2582 find_peer_result->size = htons (tsize);
2583 memcpy (&find_peer_result[1], my_hello, hello_size);
2585 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2586 "`%s': Sending hello size %d to requesting peer.\n",
2589 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2590 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2591 new_msg_ctx->peer = &my_identity;
2592 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2593 new_msg_ctx->hop_count = 0;
2594 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make find peer requests a higher priority */
2595 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2596 increment_stats(STAT_FIND_PEER_ANSWER);
2597 route_result_message(find_peer_result, new_msg_ctx);
2598 GNUNET_free(new_msg_ctx);
2599 #if DEBUG_DHT_ROUTING
2600 if ((debug_routes) && (dhtlog_handle != NULL))
2602 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2603 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2607 GNUNET_free_non_null(other_hello);
2608 GNUNET_free(find_peer_result);
2609 route_message (find_msg, msg_ctx);
2613 * Task used to republish data.
2614 * Forward declaration; function call loop.
2616 * @param cls closure (a struct RepublishContext)
2617 * @param tc runtime context for this task
2620 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2623 * Server handler for initiating local dht put requests
2625 * @param msg the actual put message
2626 * @param msg_ctx struct containing pertinent information about the request
2629 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2630 struct DHT_MessageContext *msg_ctx)
2632 const struct GNUNET_DHT_PutMessage *put_msg;
2633 enum GNUNET_BLOCK_Type put_type;
2636 struct RepublishContext *put_context;
2637 GNUNET_HashCode key;
2639 GNUNET_assert (ntohs (msg->size) >=
2640 sizeof (struct GNUNET_DHT_PutMessage));
2643 put_msg = (const struct GNUNET_DHT_PutMessage *)msg;
2644 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2646 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2648 #if DEBUG_DHT_ROUTING
2649 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2651 /** Log routes that die due to high load! */
2652 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2653 msg_ctx->hop_count, GNUNET_SYSERR,
2654 &my_identity, &msg_ctx->key, msg_ctx->peer,
2661 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2662 ret = GNUNET_BLOCK_get_key (block_context,
2667 if (GNUNET_NO == ret)
2669 #if DEBUG_DHT_ROUTING
2670 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2672 /** Log routes that die due to high load! */
2673 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2674 msg_ctx->hop_count, GNUNET_SYSERR,
2675 &my_identity, &msg_ctx->key, msg_ctx->peer,
2680 GNUNET_break_op (0);
2683 if ( (GNUNET_YES == ret) &&
2686 sizeof (GNUNET_HashCode))) )
2688 #if DEBUG_DHT_ROUTING
2689 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2691 /** Log routes that die due to high load! */
2692 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2693 msg_ctx->hop_count, GNUNET_SYSERR,
2694 &my_identity, &msg_ctx->key, msg_ctx->peer,
2698 /* invalid wrapper: key mismatch! */
2699 GNUNET_break_op (0);
2702 /* ret == GNUNET_SYSERR means that there is no known relationship between
2703 data and the key, so we cannot check it */
2705 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2706 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2707 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2709 #if DEBUG_DHT_ROUTING
2710 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2712 if ((debug_routes) && (dhtlog_handle != NULL))
2714 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2715 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2721 if (msg_ctx->closest != GNUNET_YES)
2723 route_message (msg, msg_ctx);
2728 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2729 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2730 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2733 #if DEBUG_DHT_ROUTING
2734 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2736 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2737 msg_ctx->hop_count, GNUNET_YES,
2738 &my_identity, &msg_ctx->key, msg_ctx->peer,
2742 if ((debug_routes) && (dhtlog_handle != NULL))
2744 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2745 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2750 increment_stats(STAT_PUTS_INSERTED);
2751 if (datacache != NULL)
2753 ret = GNUNET_DATACACHE_put (datacache, &msg_ctx->key, data_size,
2754 (char *) &put_msg[1], put_type,
2755 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2757 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2759 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2760 memcpy(&put_context->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
2761 put_context->type = put_type;
2762 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content, put_context);
2766 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2767 "`%s:%s': %s request received, but have no datacache!\n",
2768 my_short_id, "DHT", "PUT");
2770 if (stop_on_closest == GNUNET_NO)
2771 route_message (msg, msg_ctx);
2775 * Estimate the diameter of the network based
2776 * on how many buckets are currently in use.
2777 * Concept here is that the diameter of the network
2778 * is roughly the distance a message must travel in
2779 * order to reach its intended destination. Since
2780 * at each hop we expect to get one bit closer, and
2781 * we have one bit per bucket, the number of buckets
2782 * in use should be the largest number of hops for
2783 * a successful message. (of course, this assumes we
2784 * know all peers in the network!)
2786 * @return ballpark diameter figure
2788 static unsigned int estimate_diameter()
2790 return MAX_BUCKETS - lowest_bucket;
2794 * To how many peers should we (on average)
2795 * forward the request to obtain the desired
2796 * target_replication count (on average).
2798 * returns: target_replication / (est. hops) + (target_replication * hop_count)
2799 * where est. hops is typically 2 * the routing table depth
2801 * @param hop_count number of hops the message has traversed
2802 * @param target_replication the number of total paths desired
2804 * @return Some number of peers to forward the message to
2807 get_forward_count (unsigned int hop_count, size_t target_replication)
2809 uint32_t random_value;
2810 unsigned int forward_count;
2812 unsigned int diameter;
2814 diameter = estimate_diameter ();
2816 if (GNUNET_NO == use_max_hops)
2817 max_hops = (diameter + 1) * 2;
2820 * If we are behaving in strict kademlia mode, send multiple initial requests,
2821 * but then only send to 1 or 0 peers based strictly on the number of hops.
2823 if (strict_kademlia == GNUNET_YES)
2826 return kademlia_replication;
2827 else if (hop_count < max_hops)
2833 /* FIXME: the smaller we think the network is the more lenient we should be for
2834 * routing right? The estimation below only works if we think we have reasonably
2835 * full routing tables, which for our RR topologies may not be the case!
2837 if (hop_count > max_hops)
2840 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2841 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2842 "DHT", estimate_diameter(), lowest_bucket);
2849 target_value = target_replication / (diameter + ((float)target_replication * hop_count));
2850 if (target_value > 1)
2852 /* Set forward count to floor of target_value */
2853 forward_count = (unsigned int)target_value;
2854 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
2855 target_value = target_value - forward_count;
2858 random_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int)-1);
2860 if (random_value < (target_value * (unsigned int)-1))
2863 return forward_count;
2867 * Check whether my identity is closer than any known peers.
2868 * If a non-null bloomfilter is given, check if this is the closest
2869 * peer that hasn't already been routed to.
2871 * @param target hash code to check closeness to
2872 * @param bloom bloomfilter, exclude these entries from the decision
2874 * Return GNUNET_YES if node location is closest, GNUNET_NO
2878 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2884 struct PeerInfo *pos;
2885 unsigned int my_distance;
2887 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2890 bucket_num = find_current_bucket(target);
2892 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2893 my_distance = distance(&my_identity.hashPubKey, target);
2894 pos = k_buckets[bucket_num].head;
2896 while ((pos != NULL) && (count < bucket_size))
2898 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2901 continue; /* Skip already checked entries */
2904 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2905 if (other_bits > bits)
2907 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2909 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2911 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2917 /* No peers closer, we are the closest! */
2923 * Return this peers adjusted value based on the convergence
2924 * function chosen. This is the key function for randomized
2925 * routing decisions.
2927 * @param target the key of the request
2928 * @param peer the peer we would like the value of
2929 * @param hops number of hops this message has already traveled
2931 * @return bit distance from target to peer raised to an exponent
2932 * adjusted based on the current routing convergence algorithm
2935 static unsigned long long
2936 converge_distance (const GNUNET_HashCode *target,
2937 struct PeerInfo *peer,
2940 unsigned long long ret;
2941 unsigned int other_matching_bits;
2942 double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
2943 double temp_modifier;
2949 curr_max_hops = max_hops;
2951 curr_max_hops = (estimate_diameter() + 1) * 2;
2953 if (converge_modifier > 0)
2954 temp_modifier = converge_modifier * base_converge_modifier;
2957 temp_modifier = base_converge_modifier;
2958 base_converge_modifier = 0.0;
2961 GNUNET_assert(temp_modifier > 0);
2963 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2965 switch (converge_option)
2967 case DHT_CONVERGE_RANDOM:
2968 return 1; /* Always return 1, choose equally among all peers */
2969 case DHT_CONVERGE_LINEAR:
2970 calc_value = hops * curr_max_hops * temp_modifier;
2972 case DHT_CONVERGE_SQUARE:
2974 * Simple square based curve.
2976 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * temp_modifier));
2978 case DHT_CONVERGE_EXPONENTIAL:
2980 * Simple exponential curve.
2982 if (base_converge_modifier > 0)
2983 calc_value = (temp_modifier * hops * hops) / curr_max_hops;
2985 calc_value = (hops * hops) / curr_max_hops;
2987 case DHT_CONVERGE_BINARY:
2989 * If below the cutoff, route randomly (return 1),
2990 * If above the cutoff, return the maximum possible
2991 * value first (always route to closest, because
2995 if (hops > converge_modifier) /* Past cutoff */
3004 /* Take the log (base e) of the number of bits matching the other peer */
3005 exponent = log(other_matching_bits);
3007 /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
3008 if (exponent * calc_value >= 44.361419555836498)
3011 /* Clear errno and all math exceptions */
3013 feclearexcept(FE_ALL_EXCEPT);
3014 ret = (unsigned long long)pow(other_matching_bits, calc_value);
3015 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
3018 if (0 != fetestexcept(FE_OVERFLOW))
3019 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
3020 if (0 != fetestexcept(FE_INVALID))
3021 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
3022 if (0 != fetestexcept(FE_UNDERFLOW))
3023 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
3031 * Comparison function for two struct PeerInfo's
3032 * which have already had their matching bits to
3033 * some target calculated.
3035 * @param p1 a pointer pointer to a struct PeerInfo
3036 * @param p2 a pointer pointer to a struct PeerInfo
3038 * @return 0 if equidistant to target,
3039 * -1 if p1 is closer,
3043 compare_peers (const void *p1, const void *p2)
3045 struct PeerInfo **first = (struct PeerInfo **)p1;
3046 struct PeerInfo **second = (struct PeerInfo **)p2;
3048 if ((*first)->matching_bits > (*second)->matching_bits)
3050 if ((*first)->matching_bits < (*second)->matching_bits)
3058 * Select a peer from the routing table that would be a good routing
3059 * destination for sending a message for "target". The resulting peer
3060 * must not be in the set of blocked peers.<p>
3062 * Note that we should not ALWAYS select the closest peer to the
3063 * target, peers further away from the target should be chosen with
3064 * exponentially declining probability.
3066 * @param target the key we are selecting a peer to route to
3067 * @param bloom a bloomfilter containing entries this request has seen already
3069 * @return Peer to route to, or NULL on error
3071 static struct PeerInfo *
3072 select_peer (const GNUNET_HashCode * target,
3073 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3078 unsigned int offset;
3079 unsigned int my_matching_bits;
3081 struct PeerInfo *pos;
3082 struct PeerInfo *sorted_closest[bucket_size];
3083 unsigned long long temp_converge_distance;
3084 unsigned long long total_distance;
3085 unsigned long long selected;
3087 unsigned long long stats_total_distance;
3091 unsigned int distance;
3092 unsigned int largest_distance;
3093 struct PeerInfo *chosen;
3095 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
3098 if (strict_kademlia == GNUNET_YES)
3100 largest_distance = 0;
3102 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3104 pos = k_buckets[bc].head;
3106 while ((pos != NULL) && (count < bucket_size))
3108 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3109 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3111 distance = inverse_distance (target, &pos->id.hashPubKey);
3112 if (distance > largest_distance)
3115 largest_distance = distance;
3123 if ((largest_distance > 0) && (chosen != NULL))
3125 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
3136 /* Three steps: order peers in closest bucket (most matching bits).
3137 * Then go over all LOWER buckets (matching same bits we do)
3138 * Then go over all HIGHER buckets (matching less then we do)
3141 closest_bucket = find_current_bucket(target);
3142 GNUNET_assert(closest_bucket >= lowest_bucket);
3143 pos = k_buckets[closest_bucket].head;
3145 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3146 memset(sorted_closest, 0, sizeof(sorted_closest));
3147 /* Put any peers in the closest bucket in the sorting array */
3148 while ((pos != NULL) && (count < bucket_size))
3150 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3154 continue; /* Ignore bloomfiltered peers */
3156 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
3157 sorted_closest[offset] = pos;
3163 /* Sort the peers in descending order */
3164 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
3166 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3167 for (i = 0; i < offset; i++)
3169 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3170 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3171 break; /* Ignore bloomfiltered peers */
3172 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3173 total_distance += temp_converge_distance;
3175 break; /* overflow case */
3178 /* Now handle peers in lower buckets (matches same # of bits as target) */
3179 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3181 pos = k_buckets[bc].head;
3183 while ((pos != NULL) && (count < bucket_size))
3185 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3189 continue; /* Ignore bloomfiltered peers */
3191 temp_converge_distance = converge_distance(target, pos, hops);
3192 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3193 total_distance += temp_converge_distance;
3195 break; /* overflow case */
3201 /* Now handle all the further away peers */
3202 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3204 pos = k_buckets[bc].head;
3206 while ((pos != NULL) && (count < bucket_size))
3208 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3212 continue; /* Ignore bloomfiltered peers */
3214 temp_converge_distance = converge_distance(target, pos, hops);
3215 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3216 total_distance += temp_converge_distance;
3218 break; /* overflow case */
3224 if (total_distance == 0) /* No peers to select from! */
3226 increment_stats("# select_peer, total_distance == 0");
3230 #if DEBUG_DHT_ROUTING > 1
3233 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3234 stats_total_distance = 0;
3235 for (i = 0; i < offset; i++)
3237 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3238 break; /* Ignore bloomfiltered peers */
3239 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3240 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3241 stats_total_distance += temp_converge_distance;
3243 break; /* overflow case */
3244 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);
3247 /* Now handle peers in lower buckets (matches same # of bits as target) */
3248 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3250 pos = k_buckets[bc].head;
3252 while ((pos != NULL) && (count < bucket_size))
3254 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3258 continue; /* Ignore bloomfiltered peers */
3260 temp_converge_distance = converge_distance(target, pos, hops);
3261 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3262 stats_total_distance += temp_converge_distance;
3264 break; /* overflow case */
3265 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);
3271 /* Now handle all the further away peers */
3272 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3274 pos = k_buckets[bc].head;
3276 while ((pos != NULL) && (count < bucket_size))
3278 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3282 continue; /* Ignore bloomfiltered peers */
3284 temp_converge_distance = converge_distance(target, pos, hops);
3285 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3286 stats_total_distance += temp_converge_distance;
3288 break; /* overflow case */
3289 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);
3294 /* END PRINT STATS */
3297 /* Now actually choose a peer */
3298 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3300 /* Go over closest sorted peers. */
3301 for (i = 0; i < offset; i++)
3303 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3304 break; /* Ignore bloomfiltered peers */
3305 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3306 if (temp_converge_distance >= selected)
3307 return sorted_closest[i];
3309 selected -= temp_converge_distance;
3312 /* Now handle peers in lower buckets (matches same # of bits as target) */
3313 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3315 pos = k_buckets[bc].head;
3317 while ((pos != NULL) && (count < bucket_size))
3319 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3323 continue; /* Ignore bloomfiltered peers */
3325 temp_converge_distance = converge_distance(target, pos, hops);
3326 if (temp_converge_distance >= selected)
3329 selected -= temp_converge_distance;
3335 /* Now handle all the further away peers */
3336 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3338 pos = k_buckets[bc].head;
3340 while ((pos != NULL) && (count < bucket_size))
3342 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3346 continue; /* Ignore bloomfiltered peers */
3348 temp_converge_distance = converge_distance(target, pos, hops);
3349 if (temp_converge_distance >= selected)
3352 selected -= temp_converge_distance;
3358 increment_stats("# failed to select peer");
3364 * Task used to remove recent entries, either
3365 * after timeout, when full, or on shutdown.
3367 * @param cls the entry to remove
3368 * @param tc context, reason, etc.
3371 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3373 struct RecentRequest *req = cls;
3374 static GNUNET_HashCode hash;
3376 GNUNET_assert(req != NULL);
3377 hash_from_uid(req->uid, &hash);
3378 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3379 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3380 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3384 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3386 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3387 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3393 * Remember this routing request so that if a reply is
3394 * received we can either forward it to the correct peer
3395 * or return the result locally.
3397 * @param msg_ctx Context of the route request
3399 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3401 static int cache_response(struct DHT_MessageContext *msg_ctx)
3403 struct DHTQueryRecord *record;
3404 struct DHTRouteSource *source_info;
3405 struct DHTRouteSource *pos;
3406 struct GNUNET_TIME_Absolute now;
3407 unsigned int current_size;
3409 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3411 #if DELETE_WHEN_FULL
3412 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3414 source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3415 GNUNET_assert(source_info != NULL);
3416 record = source_info->record;
3417 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3418 if (record->head == NULL) /* No more entries in DLL */
3420 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3421 GNUNET_free(record);
3423 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3424 GNUNET_SCHEDULER_cancel(source_info->delete_task);
3425 if (source_info->find_peers_responded != NULL)
3426 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3427 GNUNET_free(source_info);
3428 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3431 /** Non-local request and have too many outstanding forwards, discard! */
3432 if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3435 now = GNUNET_TIME_absolute_get();
3436 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3437 if (record != NULL) /* Already know this request! */
3442 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3443 break; /* Already have this peer in reply list! */
3446 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3448 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.abs_value);
3454 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3455 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3456 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3459 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3460 source_info->record = record;
3461 source_info->delete_task = GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3462 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3463 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3464 GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail, source_info);
3465 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3467 source_info->client = msg_ctx->client;
3468 now = GNUNET_TIME_absolute_get_forever();
3470 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.abs_value);
3472 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3473 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3474 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3481 * Main function that handles whether or not to route a message to other
3484 * @param msg the message to be routed
3485 * @param msg_ctx the context containing all pertinent information about the message
3488 route_message(const struct GNUNET_MessageHeader *msg,
3489 struct DHT_MessageContext *msg_ctx)
3492 struct PeerInfo *selected;
3493 #if DEBUG_DHT_ROUTING > 1
3494 struct PeerInfo *nearest;
3496 unsigned int target_forward_count;
3497 unsigned int forward_count;
3498 struct RecentRequest *recent_req;
3499 GNUNET_HashCode unique_hash;
3500 char *stat_forward_count;
3501 char *temp_stat_str;
3502 #if DEBUG_DHT_ROUTING
3506 if (malicious_dropper == GNUNET_YES)
3508 #if DEBUG_DHT_ROUTING
3509 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3511 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3512 msg_ctx->hop_count, GNUNET_SYSERR,
3513 &my_identity, &msg_ctx->key, msg_ctx->peer,
3517 if (msg_ctx->bloom != NULL)
3519 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3520 msg_ctx->bloom = NULL;
3525 increment_stats(STAT_ROUTES);
3526 target_forward_count = get_forward_count(msg_ctx->hop_count, msg_ctx->replication);
3527 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", target_forward_count);
3528 increment_stats(stat_forward_count);
3529 GNUNET_free(stat_forward_count);
3530 if (msg_ctx->bloom == NULL)
3531 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3533 if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3534 target_forward_count = 0;
3537 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3538 * any closer peers (which is being checked for below). Since we are doing recursive
3539 * routing we have no choice but to stop forwarding in this case. This means that at
3540 * any given step the request may NOT be forwarded to alpha peers (because routes will
3541 * stop and the parallel route will not be aware of it). Of course, assuming that we
3542 * have fulfilled the Kademlia requirements for routing table fullness this will never
3543 * ever ever be a problem.
3545 * However, is this fair?
3547 * Since we use these requests to build our routing tables (and we build them in the
3548 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3549 * routing tables still get constructed.
3551 if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) && (msg_ctx->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3552 target_forward_count = 0;
3555 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3556 hash_from_uid (msg_ctx->unique_id, &unique_hash);
3557 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3559 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3560 GNUNET_assert(recent_req != NULL);
3561 if (0 != memcmp(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode)))
3562 increment_stats(STAT_DUPLICATE_UID);
3565 increment_stats(STAT_RECENT_SEEN);
3566 GNUNET_CONTAINER_bloomfilter_or2(msg_ctx->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3571 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3572 recent_req->uid = msg_ctx->unique_id;
3573 memcpy(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3574 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3575 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().abs_value);
3576 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3577 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3580 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3582 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3583 GNUNET_assert(recent_req != NULL);
3584 GNUNET_SCHEDULER_cancel(recent_req->remove_task);
3585 GNUNET_SCHEDULER_add_now(&remove_recent, recent_req);
3589 for (i = 0; i < target_forward_count; i++)
3591 selected = select_peer(&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3593 if (selected != NULL)
3596 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &msg_ctx->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &msg_ctx->key))
3597 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", msg_ctx->hop_count);
3599 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", msg_ctx->hop_count);
3600 if (temp_stat_str != NULL)
3602 increment_stats(temp_stat_str);
3603 GNUNET_free(temp_stat_str);
3605 GNUNET_CONTAINER_bloomfilter_add(msg_ctx->bloom, &selected->id.hashPubKey);
3606 #if DEBUG_DHT_ROUTING > 1
3607 nearest = find_closest_peer(&msg_ctx->key);
3608 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3609 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3610 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3611 "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));
3612 GNUNET_free(nearest_buf);
3614 #if DEBUG_DHT_ROUTING
3615 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3617 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3618 msg_ctx->hop_count, GNUNET_NO,
3619 &my_identity, &msg_ctx->key, msg_ctx->peer,
3623 forward_message (msg, selected, msg_ctx);
3627 if (msg_ctx->bloom != NULL)
3629 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, msg_ctx->bloom, DHT_BLOOM_SIZE);
3630 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3631 msg_ctx->bloom = NULL;
3634 #if DEBUG_DHT_ROUTING
3635 if (forward_count == 0)
3636 ret = GNUNET_SYSERR;
3640 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3642 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3643 msg_ctx->hop_count, ret,
3644 &my_identity, &msg_ctx->key, msg_ctx->peer,
3653 * Main function that handles whether or not to route a message to other
3656 * @param msg the message to be routed
3657 * @param msg_ctx the context containing all pertinent information about the message
3660 demultiplex_message(const struct GNUNET_MessageHeader *msg,
3661 struct DHT_MessageContext *msg_ctx)
3663 msg_ctx->closest = am_closest_peer(&msg_ctx->key, NULL);
3664 switch (ntohs(msg->type))
3666 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3667 cache_response (msg_ctx);
3668 handle_dht_get (msg, msg_ctx);
3670 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3671 increment_stats(STAT_PUTS);
3672 handle_dht_put (msg, msg_ctx);
3674 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3675 increment_stats(STAT_FIND_PEER);
3676 if (((msg_ctx->hop_count > 0) && (0 != memcmp(msg_ctx->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (msg_ctx->client != NULL))
3678 cache_response (msg_ctx);
3679 if ((msg_ctx->closest == GNUNET_YES) || (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3680 handle_dht_find_peer (msg, msg_ctx);
3683 route_message (msg, msg_ctx);
3684 #if DEBUG_DHT_ROUTING
3685 if (msg_ctx->hop_count == 0) /* Locally initiated request */
3687 if ((debug_routes) && (dhtlog_handle != NULL))
3689 dhtlog_handle->insert_dhtkey(NULL, &msg_ctx->key);
3690 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
3691 msg_ctx->hop_count, GNUNET_NO, &my_identity,
3698 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3699 "`%s': Message type (%d) not handled, forwarding anyway!\n", "DHT", ntohs(msg->type));
3700 route_message (msg, msg_ctx);
3708 * Iterator for local get request results,
3710 * @param cls closure for iterator, NULL
3711 * @param exp when does this value expire?
3712 * @param key the key this data is stored under
3713 * @param size the size of the data identified by key
3714 * @param data the actual data
3715 * @param type the type of the data
3717 * @return GNUNET_OK to continue iteration, anything else
3718 * to stop iteration.
3721 republish_content_iterator (void *cls,
3722 struct GNUNET_TIME_Absolute exp,
3723 const GNUNET_HashCode * key,
3724 size_t size, const char *data, uint32_t type)
3727 struct DHT_MessageContext *new_msg_ctx;
3728 struct GNUNET_DHT_PutMessage *put_msg;
3730 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3731 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3733 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3736 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3737 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3738 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3739 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3740 put_msg->type = htons (type);
3741 memcpy (&put_msg[1], data, size);
3742 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3743 new_msg_ctx->replication = ntohl (DEFAULT_PUT_REPLICATION);
3744 new_msg_ctx->msg_options = ntohl (0);
3745 new_msg_ctx->network_size = estimate_diameter();
3746 new_msg_ctx->peer = &my_identity;
3747 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3748 new_msg_ctx->hop_count = 0;
3749 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3750 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3751 increment_stats(STAT_PUT_START);
3752 demultiplex_message(&put_msg->header, new_msg_ctx);
3754 GNUNET_free(new_msg_ctx);
3755 GNUNET_free (put_msg);
3760 * Task used to republish data.
3762 * @param cls closure (a struct RepublishContext)
3763 * @param tc runtime context for this task
3766 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3768 struct RepublishContext *put_context = cls;
3770 unsigned int results;
3772 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3774 GNUNET_free(put_context);
3778 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3779 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3780 if (results == 0) /* Data must have expired */
3781 GNUNET_free(put_context);
3782 else /* Reschedule task for next time period */
3783 GNUNET_SCHEDULER_add_delayed(dht_republish_frequency, &republish_content, put_context);
3789 * Iterator over hash map entries.
3791 * @param cls client to search for in source routes
3792 * @param key current key code (ignored)
3793 * @param value value in the hash map, a DHTQueryRecord
3794 * @return GNUNET_YES if we should continue to
3798 static int find_client_records (void *cls,
3799 const GNUNET_HashCode * key, void *value)
3801 struct ClientList *client = cls;
3802 struct DHTQueryRecord *record = value;
3803 struct DHTRouteSource *pos;
3807 if (pos->client == client)
3813 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3814 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3815 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3816 GNUNET_SCHEDULER_cancel(pos->delete_task);
3818 if (pos->find_peers_responded != NULL)
3819 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3822 if (record->head == NULL) /* No more entries in DLL */
3824 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3825 GNUNET_free(record);
3831 * Functions with this signature are called whenever a client
3832 * is disconnected on the network level.
3834 * @param cls closure (NULL for dht)
3835 * @param client identification of the client; NULL
3836 * for the last call when the server is destroyed
3838 static void handle_client_disconnect (void *cls,
3839 struct GNUNET_SERVER_Client* client)
3841 struct ClientList *pos = client_list;
3842 struct ClientList *prev;
3843 struct ClientList *found;
3844 struct PendingMessage *reply;
3850 if (pos->client_handle == client)
3853 prev->next = pos->next;
3855 client_list = pos->next;
3865 if (found->transmit_handle != NULL)
3866 GNUNET_CONNECTION_notify_transmit_ready_cancel(found->transmit_handle);
3868 while(NULL != (reply = found->pending_head))
3870 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3873 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3879 * Find a client if it exists, add it otherwise.
3881 * @param client the server handle to the client
3883 * @return the client if found, a new client otherwise
3885 static struct ClientList *
3886 find_active_client (struct GNUNET_SERVER_Client *client)
3888 struct ClientList *pos = client_list;
3889 struct ClientList *ret;
3893 if (pos->client_handle == client)
3898 ret = GNUNET_malloc (sizeof (struct ClientList));
3899 ret->client_handle = client;
3900 ret->next = client_list;
3908 * Task to send a malicious put message across the network.
3910 * @param cls closure for this task
3911 * @param tc the context under which the task is running
3914 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3916 static struct GNUNET_DHT_PutMessage put_message;
3917 static struct DHT_MessageContext msg_ctx;
3918 static GNUNET_HashCode key;
3919 uint32_t random_key;
3921 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3923 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3924 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3925 put_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3926 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3927 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3928 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3929 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3930 memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3931 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3932 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3933 msg_ctx.msg_options = ntohl (0);
3934 msg_ctx.network_size = estimate_diameter();
3935 msg_ctx.peer = &my_identity;
3936 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3937 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3938 #if DEBUG_DHT_ROUTING
3939 if (dhtlog_handle != NULL)
3940 dhtlog_handle->insert_dhtkey(NULL, &key);
3942 increment_stats(STAT_PUT_START);
3943 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3944 demultiplex_message(&put_message.header, &msg_ctx);
3945 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3950 * Task to send a malicious put message across the network.
3952 * @param cls closure for this task
3953 * @param tc the context under which the task is running
3956 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3958 static struct GNUNET_DHT_GetMessage get_message;
3959 struct DHT_MessageContext msg_ctx;
3960 static GNUNET_HashCode key;
3961 uint32_t random_key;
3963 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3966 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3967 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3968 get_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3969 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3970 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3971 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3972 memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3973 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3974 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3975 msg_ctx.msg_options = ntohl (0);
3976 msg_ctx.network_size = estimate_diameter();
3977 msg_ctx.peer = &my_identity;
3978 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3979 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3980 #if DEBUG_DHT_ROUTING
3981 if (dhtlog_handle != NULL)
3982 dhtlog_handle->insert_dhtkey(NULL, &key);
3984 increment_stats(STAT_GET_START);
3985 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3986 demultiplex_message (&get_message.header, &msg_ctx);
3987 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3993 * Iterator over hash map entries.
3995 * @param cls closure
3996 * @param key current key code
3997 * @param value value in the hash map
3998 * @return GNUNET_YES if we should continue to
4003 add_known_to_bloom (void *cls,
4004 const GNUNET_HashCode * key,
4007 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
4008 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
4013 * Task to send a find peer message for our own peer identifier
4014 * so that we can find the closest peers in the network to ourselves
4015 * and attempt to connect to them.
4017 * @param cls closure for this task
4018 * @param tc the context under which the task is running
4021 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4023 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
4024 struct DHT_MessageContext msg_ctx;
4025 struct GNUNET_TIME_Relative next_send_time;
4026 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
4028 struct GNUNET_TIME_Relative time_diff;
4029 struct GNUNET_TIME_Absolute end;
4031 double count_per_interval;
4033 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
4036 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! */
4038 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
4039 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
4040 &send_find_peer_message, NULL);
4041 newly_found_peers = 0;
4045 increment_stats(STAT_FIND_PEER_START);
4047 end = GNUNET_TIME_absolute_get();
4048 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
4050 if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
4052 multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
4053 count_per_interval = find_peer_context.count / multiplier;
4057 multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
4058 count_per_interval = find_peer_context.count * multiplier;
4062 #if FIND_PEER_WITH_HELLO
4063 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4064 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4065 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4067 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
4068 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
4070 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4071 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4072 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
4073 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
4074 GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
4075 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4076 memcpy(&msg_ctx.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
4077 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
4078 msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4079 msg_ctx.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4080 msg_ctx.network_size = estimate_diameter();
4081 msg_ctx.peer = &my_identity;
4082 msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4083 msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4085 demultiplex_message(&find_peer_msg->header, &msg_ctx);
4086 GNUNET_free(find_peer_msg);
4087 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4088 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
4090 if (newly_found_peers < bucket_size)
4092 next_send_time.rel_value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4093 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4094 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4098 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4099 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4100 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4103 GNUNET_assert (next_send_time.rel_value != 0);
4104 find_peer_context.count = 0;
4105 newly_found_peers = 0;
4106 find_peer_context.start = GNUNET_TIME_absolute_get();
4107 if (GNUNET_YES == do_find_peer)
4109 GNUNET_SCHEDULER_add_delayed (next_send_time,
4110 &send_find_peer_message, NULL);
4115 * Handler for any generic DHT messages, calls the appropriate handler
4116 * depending on message type, sends confirmation if responses aren't otherwise
4119 * @param cls closure for the service
4120 * @param client the client we received this message from
4121 * @param message the actual message received
4124 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4125 const struct GNUNET_MessageHeader *message)
4127 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
4128 const struct GNUNET_MessageHeader *enc_msg;
4129 struct DHT_MessageContext msg_ctx;
4131 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4133 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4134 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4138 ntohs (message->type),
4139 GNUNET_h2s (&dht_msg->key),
4140 GNUNET_ntohll (dht_msg->unique_id));
4142 #if DEBUG_DHT_ROUTING
4143 if (dhtlog_handle != NULL)
4144 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4146 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4147 msg_ctx.client = find_active_client (client);
4148 memcpy(&msg_ctx.key, &dht_msg->key, sizeof(GNUNET_HashCode));
4149 msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4150 msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
4151 msg_ctx.msg_options = ntohl (dht_msg->options);
4152 msg_ctx.network_size = estimate_diameter();
4153 msg_ctx.peer = &my_identity;
4154 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
4155 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4156 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4157 increment_stats(STAT_GET_START);
4158 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4159 increment_stats(STAT_PUT_START);
4160 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4161 increment_stats(STAT_FIND_PEER_START);
4163 demultiplex_message(enc_msg, &msg_ctx);
4165 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4170 * Handler for any locally received DHT control messages,
4171 * sets malicious flags mostly for now.
4173 * @param cls closure for the service
4174 * @param client the client we received this message from
4175 * @param message the actual message received
4179 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4180 const struct GNUNET_MessageHeader *message)
4182 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4183 (const struct GNUNET_DHT_ControlMessage *) message;
4185 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4186 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4187 "CONTROL", ntohs(dht_control_msg->command));
4190 switch (ntohs(dht_control_msg->command))
4192 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4193 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4194 GNUNET_SCHEDULER_add_now(&send_find_peer_message, NULL);
4197 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4198 if (ntohs(dht_control_msg->variable) > 0)
4199 malicious_get_frequency = ntohs(dht_control_msg->variable);
4200 if (malicious_get_frequency == 0)
4201 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4202 if (malicious_getter != GNUNET_YES)
4203 GNUNET_SCHEDULER_add_now(&malicious_get_task, NULL);
4204 malicious_getter = GNUNET_YES;
4205 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4206 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4208 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4209 if (ntohs(dht_control_msg->variable) > 0)
4210 malicious_put_frequency = ntohs(dht_control_msg->variable);
4211 if (malicious_put_frequency == 0)
4212 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4213 if (malicious_putter != GNUNET_YES)
4214 GNUNET_SCHEDULER_add_now(&malicious_put_task, NULL);
4215 malicious_putter = GNUNET_YES;
4216 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4217 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4219 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4220 #if DEBUG_DHT_ROUTING
4221 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4222 dhtlog_handle->set_malicious(&my_identity);
4224 malicious_dropper = GNUNET_YES;
4225 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4226 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4230 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4231 "%s:%s Unknown control command type `%d'!\n",
4233 ntohs(dht_control_msg->command));
4237 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4241 * Handler for any generic DHT stop messages, calls the appropriate handler
4242 * depending on message type (if processed locally)
4244 * @param cls closure for the service
4245 * @param client the client we received this message from
4246 * @param message the actual message received
4250 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4251 const struct GNUNET_MessageHeader *message)
4254 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4255 (const struct GNUNET_DHT_StopMessage *) message;
4256 struct DHTQueryRecord *record;
4257 struct DHTRouteSource *pos;
4259 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4260 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4261 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4263 record = GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &dht_stop_msg->key);
4270 /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
4271 if ((pos->client != NULL) && (pos->client->client_handle == client))
4273 GNUNET_SCHEDULER_cancel(pos->delete_task);
4274 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4275 GNUNET_SCHEDULER_add_continuation (&remove_forward_entry, pos, GNUNET_SCHEDULER_REASON_PREREQ_DONE);
4281 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4286 * Core handler for p2p route requests.
4289 handle_dht_p2p_route_request (void *cls,
4290 const struct GNUNET_PeerIdentity *peer,
4291 const struct GNUNET_MessageHeader *message,
4292 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4295 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4296 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4298 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4299 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4300 struct DHT_MessageContext *msg_ctx;
4302 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4305 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4310 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4316 if (get_max_send_delay().rel_value > MAX_REQUEST_TIME.rel_value)
4318 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending of previous replies took too long, backing off!\n");
4319 increment_stats("# route requests dropped due to high load");
4320 decrease_max_send_delay(get_max_send_delay());
4321 #if DEBUG_DHT_ROUTING
4322 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4324 /** Log routes that die due to high load! */
4325 dhtlog_handle->insert_route (NULL, GNUNET_ntohll(incoming->unique_id), DHTLOG_ROUTE,
4326 ntohl(incoming->hop_count), GNUNET_SYSERR,
4327 &my_identity, &incoming->key, peer,
4333 msg_ctx = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4334 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4335 GNUNET_assert(msg_ctx->bloom != NULL);
4336 msg_ctx->hop_count = ntohl(incoming->hop_count);
4337 memcpy(&msg_ctx->key, &incoming->key, sizeof(GNUNET_HashCode));
4338 msg_ctx->replication = ntohl(incoming->desired_replication_level);
4339 msg_ctx->unique_id = GNUNET_ntohll(incoming->unique_id);
4340 msg_ctx->msg_options = ntohl(incoming->options);
4341 msg_ctx->network_size = ntohl(incoming->network_size);
4342 msg_ctx->peer = peer;
4343 msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4344 msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4345 demultiplex_message (enc_msg, msg_ctx);
4346 if (msg_ctx->bloom != NULL)
4348 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4349 msg_ctx->bloom = NULL;
4351 GNUNET_free(msg_ctx);
4357 * Core handler for p2p route results.
4360 handle_dht_p2p_route_result (void *cls,
4361 const struct GNUNET_PeerIdentity *peer,
4362 const struct GNUNET_MessageHeader *message,
4363 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4367 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4369 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4370 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4371 struct DHT_MessageContext msg_ctx;
4373 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4379 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4380 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4381 msg_ctx.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4382 GNUNET_assert(msg_ctx.bloom != NULL);
4383 memcpy(&msg_ctx.key, &incoming->key, sizeof(GNUNET_HashCode));
4384 msg_ctx.unique_id = GNUNET_ntohll(incoming->unique_id);
4385 msg_ctx.msg_options = ntohl(incoming->options);
4386 msg_ctx.hop_count = ntohl(incoming->hop_count);
4387 msg_ctx.peer = peer;
4388 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4389 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4390 route_result_message(enc_msg, &msg_ctx);
4396 * Receive the HELLO from transport service,
4397 * free current and replace if necessary.
4400 * @param message HELLO message of peer
4403 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4406 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4407 "Received our `%s' from transport service\n",
4411 GNUNET_assert (message != NULL);
4412 GNUNET_free_non_null(my_hello);
4413 my_hello = GNUNET_malloc(ntohs(message->size));
4414 memcpy(my_hello, message, ntohs(message->size));
4419 * Task run during shutdown.
4425 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4428 struct PeerInfo *pos;
4430 if (transport_handle != NULL)
4432 GNUNET_free_non_null(my_hello);
4433 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4434 GNUNET_TRANSPORT_disconnect(transport_handle);
4436 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4438 while (k_buckets[bucket_count].head != NULL)
4440 pos = k_buckets[bucket_count].head;
4442 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4443 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4445 delete_peer (pos, bucket_count);
4448 if (coreAPI != NULL)
4451 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4452 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4454 GNUNET_CORE_disconnect (coreAPI);
4457 if (datacache != NULL)
4460 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4461 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4463 GNUNET_DATACACHE_destroy (datacache);
4468 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4471 if (dhtlog_handle != NULL)
4473 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4474 dhtlog_handle = NULL;
4476 if (block_context != NULL)
4478 GNUNET_BLOCK_context_destroy (block_context);
4479 block_context = NULL;
4481 GNUNET_free_non_null(my_short_id);
4487 * To be called on core init/fail.
4489 * @param cls service closure
4490 * @param server handle to the server for this service
4491 * @param identity the public identity of this peer
4492 * @param publicKey the public key of this peer
4495 core_init (void *cls,
4496 struct GNUNET_CORE_Handle *server,
4497 const struct GNUNET_PeerIdentity *identity,
4498 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4504 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4505 "%s: Connection to core FAILED!\n", "dht",
4506 GNUNET_i2s (identity));
4508 GNUNET_SCHEDULER_cancel (cleanup_task);
4509 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4513 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4514 "%s: Core connection initialized, I am peer: %s\n", "dht",
4515 GNUNET_i2s (identity));
4518 /* Copy our identity so we can use it */
4519 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4520 if (my_short_id != NULL)
4521 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4522 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4523 /* Set the server to local variable */
4526 if (dhtlog_handle != NULL)
4527 dhtlog_handle->insert_node (NULL, &my_identity);
4531 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4532 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4533 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4534 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4539 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4540 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4541 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4547 * Method called whenever a peer connects.
4549 * @param cls closure
4550 * @param peer peer identity this notification is about
4551 * @param atsi performance data
4554 handle_core_connect (void *cls,
4555 const struct GNUNET_PeerIdentity * peer,
4556 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4558 struct PeerInfo *ret;
4561 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4562 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4565 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4567 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));
4571 if (datacache != NULL)
4572 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, GNUNET_BLOCK_TYPE_DHT_HELLO, GNUNET_TIME_absolute_get_forever());
4573 ret = try_add_peer(peer,
4574 find_current_bucket(&peer->hashPubKey),
4578 newly_found_peers++;
4579 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4583 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4589 * Method called whenever a peer disconnects.
4591 * @param cls closure
4592 * @param peer peer identity this notification is about
4595 handle_core_disconnect (void *cls,
4597 GNUNET_PeerIdentity * peer)
4599 struct PeerInfo *to_remove;
4602 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");
4604 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4606 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));
4609 increment_stats(STAT_DISCONNECTS);
4610 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4611 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4612 GNUNET_assert (to_remove != NULL);
4613 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4614 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4615 delete_peer(to_remove, current_bucket);
4620 * Process dht requests.
4622 * @param cls closure
4623 * @param server the initialized server
4624 * @param c configuration to use
4628 struct GNUNET_SERVER_Handle *server,
4629 const struct GNUNET_CONFIGURATION_Handle *c)
4631 struct GNUNET_TIME_Relative next_send_time;
4632 unsigned long long temp_config_num;
4633 char *converge_modifier_buf;
4636 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4637 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4638 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4639 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
4640 DEFAULT_CORE_QUEUE_SIZE, /* queue size */
4641 NULL, /* Closure passed to DHT functions */
4642 &core_init, /* Call core_init once connected */
4643 &handle_core_connect, /* Handle connects */
4644 &handle_core_disconnect, /* remove peers on disconnects */
4645 NULL, /* Do we care about "status" updates? */
4646 NULL, /* Don't want notified about all incoming messages */
4647 GNUNET_NO, /* For header only inbound notification */
4648 NULL, /* Don't want notified about all outbound messages */
4649 GNUNET_NO, /* For header only outbound notification */
4650 core_handlers); /* Register these handlers */
4652 if (coreAPI == NULL)
4654 transport_handle = GNUNET_TRANSPORT_connect(cfg,
4655 NULL, NULL, NULL, NULL, NULL);
4656 if (transport_handle != NULL)
4657 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4659 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4660 "Failed to connect to transport service!\n");
4661 block_context = GNUNET_BLOCK_context_create (cfg);
4662 lowest_bucket = MAX_BUCKETS - 1;
4663 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4664 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4665 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4666 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4667 GNUNET_assert(all_known_peers != NULL);
4668 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4670 debug_routes = GNUNET_YES;
4674 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4677 strict_kademlia = GNUNET_YES;
4681 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4684 stop_on_closest = GNUNET_YES;
4688 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4691 stop_on_found = GNUNET_YES;
4695 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4696 "malicious_getter"))
4698 malicious_getter = GNUNET_YES;
4699 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4700 "MALICIOUS_GET_FREQUENCY",
4701 &malicious_get_frequency))
4702 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4705 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4709 max_hops = DEFAULT_MAX_HOPS;
4712 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4715 use_max_hops = GNUNET_YES;
4719 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4720 "malicious_putter"))
4722 malicious_putter = GNUNET_YES;
4723 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4724 "MALICIOUS_PUT_FREQUENCY",
4725 &malicious_put_frequency))
4726 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4729 dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
4730 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4732 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4735 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "bucket_size", &temp_config_num))
4737 bucket_size = (unsigned int)temp_config_num;
4740 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "kad_alpha", &kademlia_replication))
4742 kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
4746 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4747 "malicious_dropper"))
4749 malicious_dropper = GNUNET_YES;
4753 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4755 do_republish = GNUNET_NO;
4758 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4761 do_find_peer = GNUNET_NO;
4764 do_find_peer = GNUNET_YES;
4767 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4768 "use_real_distance"))
4769 use_real_distance = GNUNET_YES;
4772 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4773 "mysql_logging_extended"))
4775 debug_routes = GNUNET_YES;
4776 debug_routes_extended = GNUNET_YES;
4779 #if DEBUG_DHT_ROUTING
4780 if (GNUNET_YES == debug_routes)
4782 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4783 if (dhtlog_handle == NULL)
4785 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4786 "Could not connect to mysql logging server, logging will not happen!");
4791 converge_option = DHT_CONVERGE_SQUARE;
4793 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4796 converge_option = DHT_CONVERGE_LINEAR;
4798 else if (GNUNET_YES ==
4799 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4800 "converge_exponential"))
4802 converge_option = DHT_CONVERGE_EXPONENTIAL;
4804 else if (GNUNET_YES ==
4805 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4808 converge_option = DHT_CONVERGE_RANDOM;
4810 else if (GNUNET_YES ==
4811 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4814 converge_option = DHT_CONVERGE_BINARY;
4817 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht", "converge_modifier", &converge_modifier_buf))
4819 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4821 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4822 converge_modifier = 0.0;
4824 GNUNET_free(converge_modifier_buf);
4827 stats = GNUNET_STATISTICS_create("dht", cfg);
4831 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4832 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4833 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4834 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4835 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4836 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4837 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4838 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4839 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4840 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4841 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4842 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4843 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4844 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4845 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4846 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4847 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4848 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4849 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4850 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4852 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4853 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4854 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4855 if (GNUNET_YES == do_find_peer)
4857 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4858 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4859 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4860 find_peer_context.start = GNUNET_TIME_absolute_get();
4861 GNUNET_SCHEDULER_add_delayed (next_send_time,
4862 &send_find_peer_message, &find_peer_context);
4865 /* Scheduled the task to clean up when shutdown is called */
4866 cleanup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4867 &shutdown_task, NULL);
4871 * The main function for the dht service.
4873 * @param argc number of arguments from the command line
4874 * @param argv command line arguments
4875 * @return 0 ok, 1 on error
4878 main (int argc, char *const *argv)
4883 GNUNET_SERVICE_run (argc,
4886 GNUNET_SERVICE_OPTION_NONE,
4887 &run, NULL)) ? 0 : 1;
4888 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap));
4889 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap));
4890 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4891 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4892 GNUNET_CONTAINER_heap_destroy (recent.minHeap);