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 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2673 msg_ctx->hop_count, GNUNET_SYSERR,
2674 &my_identity, &msg_ctx->key, msg_ctx->peer,
2679 GNUNET_break_op (0);
2682 if ( (GNUNET_YES == ret) &&
2685 sizeof (GNUNET_HashCode))) )
2687 #if DEBUG_DHT_ROUTING
2688 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2690 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2691 msg_ctx->hop_count, GNUNET_SYSERR,
2692 &my_identity, &msg_ctx->key, msg_ctx->peer,
2696 /* invalid wrapper: key mismatch! */
2697 GNUNET_break_op (0);
2700 /* ret == GNUNET_SYSERR means that there is no known relationship between
2701 data and the key, so we cannot check it */
2703 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2704 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2705 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2707 #if DEBUG_DHT_ROUTING
2708 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2710 if ((debug_routes) && (dhtlog_handle != NULL))
2712 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2713 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2719 if (msg_ctx->closest != GNUNET_YES)
2721 route_message (msg, msg_ctx);
2726 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2727 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2728 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2731 #if DEBUG_DHT_ROUTING
2732 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2734 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2735 msg_ctx->hop_count, GNUNET_YES,
2736 &my_identity, &msg_ctx->key, msg_ctx->peer,
2740 if ((debug_routes) && (dhtlog_handle != NULL))
2742 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2743 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2748 increment_stats(STAT_PUTS_INSERTED);
2749 if (datacache != NULL)
2751 ret = GNUNET_DATACACHE_put (datacache, &msg_ctx->key, data_size,
2752 (char *) &put_msg[1], put_type,
2753 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2755 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2757 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2758 memcpy(&put_context->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
2759 put_context->type = put_type;
2760 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content, put_context);
2764 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2765 "`%s:%s': %s request received, but have no datacache!\n",
2766 my_short_id, "DHT", "PUT");
2768 if (stop_on_closest == GNUNET_NO)
2769 route_message (msg, msg_ctx);
2773 * Estimate the diameter of the network based
2774 * on how many buckets are currently in use.
2775 * Concept here is that the diameter of the network
2776 * is roughly the distance a message must travel in
2777 * order to reach its intended destination. Since
2778 * at each hop we expect to get one bit closer, and
2779 * we have one bit per bucket, the number of buckets
2780 * in use should be the largest number of hops for
2781 * a successful message. (of course, this assumes we
2782 * know all peers in the network!)
2784 * @return ballpark diameter figure
2786 static unsigned int estimate_diameter()
2788 return MAX_BUCKETS - lowest_bucket;
2792 * To how many peers should we (on average)
2793 * forward the request to obtain the desired
2794 * target_replication count (on average).
2796 * returns: target_replication / (est. hops) + (target_replication * hop_count)
2797 * where est. hops is typically 2 * the routing table depth
2799 * @param hop_count number of hops the message has traversed
2800 * @param target_replication the number of total paths desired
2802 * @return Some number of peers to forward the message to
2805 get_forward_count (unsigned int hop_count, size_t target_replication)
2807 uint32_t random_value;
2808 unsigned int forward_count;
2810 unsigned int diameter;
2812 diameter = estimate_diameter ();
2814 if (GNUNET_NO == use_max_hops)
2815 max_hops = (diameter + 1) * 2;
2818 * If we are behaving in strict kademlia mode, send multiple initial requests,
2819 * but then only send to 1 or 0 peers based strictly on the number of hops.
2821 if (strict_kademlia == GNUNET_YES)
2824 return kademlia_replication;
2825 else if (hop_count < max_hops)
2831 /* FIXME: the smaller we think the network is the more lenient we should be for
2832 * routing right? The estimation below only works if we think we have reasonably
2833 * full routing tables, which for our RR topologies may not be the case!
2835 if (hop_count > max_hops)
2838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2839 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2840 "DHT", estimate_diameter(), lowest_bucket);
2847 target_value = target_replication / (diameter + ((float)target_replication * hop_count));
2848 if (target_value > 1)
2850 /* Set forward count to floor of target_value */
2851 forward_count = (unsigned int)target_value;
2852 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
2853 target_value = target_value - forward_count;
2856 random_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int)-1);
2858 if (random_value < (target_value * (unsigned int)-1))
2861 return forward_count;
2865 * Check whether my identity is closer than any known peers.
2866 * If a non-null bloomfilter is given, check if this is the closest
2867 * peer that hasn't already been routed to.
2869 * @param target hash code to check closeness to
2870 * @param bloom bloomfilter, exclude these entries from the decision
2872 * Return GNUNET_YES if node location is closest, GNUNET_NO
2876 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2882 struct PeerInfo *pos;
2883 unsigned int my_distance;
2885 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2888 bucket_num = find_current_bucket(target);
2890 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2891 my_distance = distance(&my_identity.hashPubKey, target);
2892 pos = k_buckets[bucket_num].head;
2894 while ((pos != NULL) && (count < bucket_size))
2896 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2899 continue; /* Skip already checked entries */
2902 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2903 if (other_bits > bits)
2905 else if (other_bits == bits) /* We match the same number of bits */
2907 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2909 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2915 /* No peers closer, we are the closest! */
2921 * Return this peers adjusted value based on the convergence
2922 * function chosen. This is the key function for randomized
2923 * routing decisions.
2925 * @param target the key of the request
2926 * @param peer the peer we would like the value of
2927 * @param hops number of hops this message has already traveled
2929 * @return bit distance from target to peer raised to an exponent
2930 * adjusted based on the current routing convergence algorithm
2933 static unsigned long long
2934 converge_distance (const GNUNET_HashCode *target,
2935 struct PeerInfo *peer,
2938 unsigned long long ret;
2939 unsigned int other_matching_bits;
2940 double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
2941 double temp_modifier;
2947 curr_max_hops = max_hops;
2949 curr_max_hops = (estimate_diameter() + 1) * 2;
2951 if (converge_modifier > 0)
2952 temp_modifier = converge_modifier * base_converge_modifier;
2955 temp_modifier = base_converge_modifier;
2956 base_converge_modifier = 0.0;
2959 GNUNET_assert(temp_modifier > 0);
2961 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2963 switch (converge_option)
2965 case DHT_CONVERGE_RANDOM:
2966 return 1; /* Always return 1, choose equally among all peers */
2967 case DHT_CONVERGE_LINEAR:
2968 calc_value = hops * curr_max_hops * temp_modifier;
2970 case DHT_CONVERGE_SQUARE:
2972 * Simple square based curve.
2974 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * temp_modifier));
2976 case DHT_CONVERGE_EXPONENTIAL:
2978 * Simple exponential curve.
2980 if (base_converge_modifier > 0)
2981 calc_value = (temp_modifier * hops * hops) / curr_max_hops;
2983 calc_value = (hops * hops) / curr_max_hops;
2985 case DHT_CONVERGE_BINARY:
2987 * If below the cutoff, route randomly (return 1),
2988 * If above the cutoff, return the maximum possible
2989 * value first (always route to closest, because
2993 if (hops >= converge_modifier) /* Past cutoff */
3002 /* Take the log (base e) of the number of bits matching the other peer */
3003 exponent = log(other_matching_bits);
3005 /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
3006 if (exponent * calc_value >= 44.361419555836498)
3009 /* Clear errno and all math exceptions */
3011 feclearexcept(FE_ALL_EXCEPT);
3012 ret = (unsigned long long)pow(other_matching_bits, calc_value);
3013 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
3016 if (0 != fetestexcept(FE_OVERFLOW))
3017 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
3018 if (0 != fetestexcept(FE_INVALID))
3019 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
3020 if (0 != fetestexcept(FE_UNDERFLOW))
3021 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
3029 * Comparison function for two struct PeerInfo's
3030 * which have already had their matching bits to
3031 * some target calculated.
3033 * @param p1 a pointer pointer to a struct PeerInfo
3034 * @param p2 a pointer pointer to a struct PeerInfo
3036 * @return 0 if equidistant to target,
3037 * -1 if p1 is closer,
3041 compare_peers (const void *p1, const void *p2)
3043 struct PeerInfo **first = (struct PeerInfo **)p1;
3044 struct PeerInfo **second = (struct PeerInfo **)p2;
3046 if ((*first)->matching_bits > (*second)->matching_bits)
3048 if ((*first)->matching_bits < (*second)->matching_bits)
3056 * Select a peer from the routing table that would be a good routing
3057 * destination for sending a message for "target". The resulting peer
3058 * must not be in the set of blocked peers.<p>
3060 * Note that we should not ALWAYS select the closest peer to the
3061 * target, peers further away from the target should be chosen with
3062 * exponentially declining probability.
3064 * @param target the key we are selecting a peer to route to
3065 * @param bloom a bloomfilter containing entries this request has seen already
3067 * @return Peer to route to, or NULL on error
3069 static struct PeerInfo *
3070 select_peer (const GNUNET_HashCode * target,
3071 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3076 unsigned int offset;
3077 unsigned int my_matching_bits;
3079 struct PeerInfo *pos;
3080 struct PeerInfo *sorted_closest[bucket_size];
3081 unsigned long long temp_converge_distance;
3082 unsigned long long total_distance;
3083 unsigned long long selected;
3085 unsigned long long stats_total_distance;
3089 unsigned int distance;
3090 unsigned int largest_distance;
3091 struct PeerInfo *chosen;
3093 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
3096 /** If we are doing kademlia routing, or converge is binary (saves some cycles) */
3097 if ((strict_kademlia == GNUNET_YES) ||
3098 ((converge_option == DHT_CONVERGE_BINARY) && (hops >= converge_modifier)))
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("# failed to select peer");
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 /* FIXME: Should we use closest excluding those we won't route to (the bloomfilter problem)? */
3664 msg_ctx->closest = am_closest_peer(&msg_ctx->key, msg_ctx->bloom);
3665 switch (ntohs(msg->type))
3667 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3668 cache_response (msg_ctx);
3669 handle_dht_get (msg, msg_ctx);
3671 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3672 increment_stats(STAT_PUTS);
3673 handle_dht_put (msg, msg_ctx);
3675 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3676 increment_stats(STAT_FIND_PEER);
3677 if (((msg_ctx->hop_count > 0) && (0 != memcmp(msg_ctx->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (msg_ctx->client != NULL))
3679 cache_response (msg_ctx);
3680 if ((msg_ctx->closest == GNUNET_YES) || (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3681 handle_dht_find_peer (msg, msg_ctx);
3684 route_message (msg, msg_ctx);
3685 #if DEBUG_DHT_ROUTING
3686 if (msg_ctx->hop_count == 0) /* Locally initiated request */
3688 if ((debug_routes) && (dhtlog_handle != NULL))
3690 dhtlog_handle->insert_dhtkey(NULL, &msg_ctx->key);
3691 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
3692 msg_ctx->hop_count, GNUNET_NO, &my_identity,
3699 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3700 "`%s': Message type (%d) not handled, forwarding anyway!\n", "DHT", ntohs(msg->type));
3701 route_message (msg, msg_ctx);
3709 * Iterator for local get request results,
3711 * @param cls closure for iterator, NULL
3712 * @param exp when does this value expire?
3713 * @param key the key this data is stored under
3714 * @param size the size of the data identified by key
3715 * @param data the actual data
3716 * @param type the type of the data
3718 * @return GNUNET_OK to continue iteration, anything else
3719 * to stop iteration.
3722 republish_content_iterator (void *cls,
3723 struct GNUNET_TIME_Absolute exp,
3724 const GNUNET_HashCode * key,
3725 size_t size, const char *data, uint32_t type)
3728 struct DHT_MessageContext *new_msg_ctx;
3729 struct GNUNET_DHT_PutMessage *put_msg;
3731 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3732 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3734 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3737 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3738 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3739 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3740 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3741 put_msg->type = htons (type);
3742 memcpy (&put_msg[1], data, size);
3743 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3744 new_msg_ctx->replication = ntohl (DEFAULT_PUT_REPLICATION);
3745 new_msg_ctx->msg_options = ntohl (0);
3746 new_msg_ctx->network_size = estimate_diameter();
3747 new_msg_ctx->peer = &my_identity;
3748 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3749 new_msg_ctx->hop_count = 0;
3750 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3751 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3752 increment_stats(STAT_PUT_START);
3753 demultiplex_message(&put_msg->header, new_msg_ctx);
3755 GNUNET_free(new_msg_ctx);
3756 GNUNET_free (put_msg);
3761 * Task used to republish data.
3763 * @param cls closure (a struct RepublishContext)
3764 * @param tc runtime context for this task
3767 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3769 struct RepublishContext *put_context = cls;
3771 unsigned int results;
3773 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3775 GNUNET_free(put_context);
3779 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3780 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3781 if (results == 0) /* Data must have expired */
3782 GNUNET_free(put_context);
3783 else /* Reschedule task for next time period */
3784 GNUNET_SCHEDULER_add_delayed(dht_republish_frequency, &republish_content, put_context);
3790 * Iterator over hash map entries.
3792 * @param cls client to search for in source routes
3793 * @param key current key code (ignored)
3794 * @param value value in the hash map, a DHTQueryRecord
3795 * @return GNUNET_YES if we should continue to
3799 static int find_client_records (void *cls,
3800 const GNUNET_HashCode * key, void *value)
3802 struct ClientList *client = cls;
3803 struct DHTQueryRecord *record = value;
3804 struct DHTRouteSource *pos;
3808 if (pos->client == client)
3814 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3815 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3816 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3817 GNUNET_SCHEDULER_cancel(pos->delete_task);
3819 if (pos->find_peers_responded != NULL)
3820 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3823 if (record->head == NULL) /* No more entries in DLL */
3825 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3826 GNUNET_free(record);
3832 * Functions with this signature are called whenever a client
3833 * is disconnected on the network level.
3835 * @param cls closure (NULL for dht)
3836 * @param client identification of the client; NULL
3837 * for the last call when the server is destroyed
3839 static void handle_client_disconnect (void *cls,
3840 struct GNUNET_SERVER_Client* client)
3842 struct ClientList *pos = client_list;
3843 struct ClientList *prev;
3844 struct ClientList *found;
3845 struct PendingMessage *reply;
3851 if (pos->client_handle == client)
3854 prev->next = pos->next;
3856 client_list = pos->next;
3866 if (found->transmit_handle != NULL)
3867 GNUNET_CONNECTION_notify_transmit_ready_cancel(found->transmit_handle);
3869 while(NULL != (reply = found->pending_head))
3871 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3874 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3880 * Find a client if it exists, add it otherwise.
3882 * @param client the server handle to the client
3884 * @return the client if found, a new client otherwise
3886 static struct ClientList *
3887 find_active_client (struct GNUNET_SERVER_Client *client)
3889 struct ClientList *pos = client_list;
3890 struct ClientList *ret;
3894 if (pos->client_handle == client)
3899 ret = GNUNET_malloc (sizeof (struct ClientList));
3900 ret->client_handle = client;
3901 ret->next = client_list;
3909 * Task to send a malicious put message across the network.
3911 * @param cls closure for this task
3912 * @param tc the context under which the task is running
3915 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3917 static struct GNUNET_DHT_PutMessage put_message;
3918 static struct DHT_MessageContext msg_ctx;
3919 static GNUNET_HashCode key;
3920 uint32_t random_key;
3922 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3924 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3925 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3926 put_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3927 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3928 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3929 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3930 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3931 memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3932 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3933 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3934 msg_ctx.msg_options = ntohl (0);
3935 msg_ctx.network_size = estimate_diameter();
3936 msg_ctx.peer = &my_identity;
3937 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3938 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3939 #if DEBUG_DHT_ROUTING
3940 if (dhtlog_handle != NULL)
3941 dhtlog_handle->insert_dhtkey(NULL, &key);
3943 increment_stats(STAT_PUT_START);
3944 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3945 demultiplex_message(&put_message.header, &msg_ctx);
3946 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3951 * Task to send a malicious put message across the network.
3953 * @param cls closure for this task
3954 * @param tc the context under which the task is running
3957 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3959 static struct GNUNET_DHT_GetMessage get_message;
3960 struct DHT_MessageContext msg_ctx;
3961 static GNUNET_HashCode key;
3962 uint32_t random_key;
3964 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3967 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3968 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3969 get_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3970 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3971 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3972 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3973 memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3974 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3975 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3976 msg_ctx.msg_options = ntohl (0);
3977 msg_ctx.network_size = estimate_diameter();
3978 msg_ctx.peer = &my_identity;
3979 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3980 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3981 #if DEBUG_DHT_ROUTING
3982 if (dhtlog_handle != NULL)
3983 dhtlog_handle->insert_dhtkey(NULL, &key);
3985 increment_stats(STAT_GET_START);
3986 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3987 demultiplex_message (&get_message.header, &msg_ctx);
3988 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3994 * Iterator over hash map entries.
3996 * @param cls closure
3997 * @param key current key code
3998 * @param value value in the hash map
3999 * @return GNUNET_YES if we should continue to
4004 add_known_to_bloom (void *cls,
4005 const GNUNET_HashCode * key,
4008 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
4009 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
4014 * Task to send a find peer message for our own peer identifier
4015 * so that we can find the closest peers in the network to ourselves
4016 * and attempt to connect to them.
4018 * @param cls closure for this task
4019 * @param tc the context under which the task is running
4022 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4024 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
4025 struct DHT_MessageContext msg_ctx;
4026 struct GNUNET_TIME_Relative next_send_time;
4027 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
4029 struct GNUNET_TIME_Relative time_diff;
4030 struct GNUNET_TIME_Absolute end;
4032 double count_per_interval;
4034 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
4037 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! */
4039 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
4040 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
4041 &send_find_peer_message, NULL);
4042 newly_found_peers = 0;
4046 increment_stats(STAT_FIND_PEER_START);
4048 end = GNUNET_TIME_absolute_get();
4049 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
4051 if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
4053 multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
4054 count_per_interval = find_peer_context.count / multiplier;
4058 multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
4059 count_per_interval = find_peer_context.count * multiplier;
4063 #if FIND_PEER_WITH_HELLO
4064 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4065 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4066 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4068 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
4069 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
4071 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4072 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4073 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
4074 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
4075 GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
4076 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4077 memcpy(&msg_ctx.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
4078 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
4079 msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4080 msg_ctx.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4081 msg_ctx.network_size = estimate_diameter();
4082 msg_ctx.peer = &my_identity;
4083 msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4084 msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4086 demultiplex_message(&find_peer_msg->header, &msg_ctx);
4087 GNUNET_free(find_peer_msg);
4088 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4089 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
4091 if (newly_found_peers < bucket_size)
4093 next_send_time.rel_value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4094 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4095 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4099 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4100 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4101 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4104 GNUNET_assert (next_send_time.rel_value != 0);
4105 find_peer_context.count = 0;
4106 newly_found_peers = 0;
4107 find_peer_context.start = GNUNET_TIME_absolute_get();
4108 if (GNUNET_YES == do_find_peer)
4110 GNUNET_SCHEDULER_add_delayed (next_send_time,
4111 &send_find_peer_message, NULL);
4116 * Handler for any generic DHT messages, calls the appropriate handler
4117 * depending on message type, sends confirmation if responses aren't otherwise
4120 * @param cls closure for the service
4121 * @param client the client we received this message from
4122 * @param message the actual message received
4125 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4126 const struct GNUNET_MessageHeader *message)
4128 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
4129 const struct GNUNET_MessageHeader *enc_msg;
4130 struct DHT_MessageContext msg_ctx;
4132 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4134 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4135 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4139 ntohs (message->type),
4140 GNUNET_h2s (&dht_msg->key),
4141 GNUNET_ntohll (dht_msg->unique_id));
4143 #if DEBUG_DHT_ROUTING
4144 if (dhtlog_handle != NULL)
4145 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4148 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4149 msg_ctx.client = find_active_client (client);
4150 memcpy(&msg_ctx.key, &dht_msg->key, sizeof(GNUNET_HashCode));
4151 msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4152 msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
4153 msg_ctx.msg_options = ntohl (dht_msg->options);
4154 msg_ctx.network_size = estimate_diameter();
4155 msg_ctx.peer = &my_identity;
4156 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
4157 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4159 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4160 increment_stats(STAT_GET_START);
4161 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4162 increment_stats(STAT_PUT_START);
4163 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4164 increment_stats(STAT_FIND_PEER_START);
4166 if (GNUNET_YES == malicious_dropper)
4168 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4170 #if DEBUG_DHT_ROUTING
4171 if ((debug_routes) && (dhtlog_handle != NULL))
4173 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_GET,
4174 msg_ctx.hop_count, GNUNET_NO, &my_identity,
4179 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4181 #if DEBUG_DHT_ROUTING
4182 if ((debug_routes) && (dhtlog_handle != NULL))
4184 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_PUT,
4185 msg_ctx.hop_count, GNUNET_NO, &my_identity,
4190 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4194 demultiplex_message(enc_msg, &msg_ctx);
4195 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4200 * Handler for any locally received DHT control messages,
4201 * sets malicious flags mostly for now.
4203 * @param cls closure for the service
4204 * @param client the client we received this message from
4205 * @param message the actual message received
4209 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4210 const struct GNUNET_MessageHeader *message)
4212 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4213 (const struct GNUNET_DHT_ControlMessage *) message;
4215 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4216 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4217 "CONTROL", ntohs(dht_control_msg->command));
4220 switch (ntohs(dht_control_msg->command))
4222 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4223 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4224 GNUNET_SCHEDULER_add_now(&send_find_peer_message, NULL);
4227 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4228 if (ntohs(dht_control_msg->variable) > 0)
4229 malicious_get_frequency = ntohs(dht_control_msg->variable);
4230 if (malicious_get_frequency == 0)
4231 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4232 if (malicious_getter != GNUNET_YES)
4233 GNUNET_SCHEDULER_add_now(&malicious_get_task, NULL);
4234 malicious_getter = GNUNET_YES;
4235 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4236 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4238 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4239 if (ntohs(dht_control_msg->variable) > 0)
4240 malicious_put_frequency = ntohs(dht_control_msg->variable);
4241 if (malicious_put_frequency == 0)
4242 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4243 if (malicious_putter != GNUNET_YES)
4244 GNUNET_SCHEDULER_add_now(&malicious_put_task, NULL);
4245 malicious_putter = GNUNET_YES;
4246 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4247 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4249 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4250 #if DEBUG_DHT_ROUTING
4251 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4252 dhtlog_handle->set_malicious(&my_identity);
4254 malicious_dropper = GNUNET_YES;
4255 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4256 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4260 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4261 "%s:%s Unknown control command type `%d'!\n",
4263 ntohs(dht_control_msg->command));
4267 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4271 * Handler for any generic DHT stop messages, calls the appropriate handler
4272 * depending on message type (if processed locally)
4274 * @param cls closure for the service
4275 * @param client the client we received this message from
4276 * @param message the actual message received
4280 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4281 const struct GNUNET_MessageHeader *message)
4284 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4285 (const struct GNUNET_DHT_StopMessage *) message;
4286 struct DHTQueryRecord *record;
4287 struct DHTRouteSource *pos;
4289 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4290 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4291 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4293 record = GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &dht_stop_msg->key);
4300 /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
4301 if ((pos->client != NULL) && (pos->client->client_handle == client))
4303 GNUNET_SCHEDULER_cancel(pos->delete_task);
4304 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4305 GNUNET_SCHEDULER_add_continuation (&remove_forward_entry, pos, GNUNET_SCHEDULER_REASON_PREREQ_DONE);
4311 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4316 * Core handler for p2p route requests.
4319 handle_dht_p2p_route_request (void *cls,
4320 const struct GNUNET_PeerIdentity *peer,
4321 const struct GNUNET_MessageHeader *message,
4322 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4325 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4326 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4328 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4329 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4330 struct DHT_MessageContext *msg_ctx;
4332 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4335 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4340 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4346 if (malicious_dropper == GNUNET_YES)
4348 #if DEBUG_DHT_ROUTING
4349 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4351 /** Log routes that die due to high load! */
4352 dhtlog_handle->insert_route (NULL, GNUNET_ntohll(incoming->unique_id), DHTLOG_ROUTE,
4353 ntohl(incoming->hop_count), GNUNET_SYSERR,
4354 &my_identity, &incoming->key, peer,
4361 if (get_max_send_delay().rel_value > MAX_REQUEST_TIME.rel_value)
4363 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending of previous replies took too long, backing off!\n");
4364 increment_stats("# route requests dropped due to high load");
4365 decrease_max_send_delay(get_max_send_delay());
4366 #if DEBUG_DHT_ROUTING
4367 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4369 /** Log routes that die due to high load! */
4370 dhtlog_handle->insert_route (NULL, GNUNET_ntohll(incoming->unique_id), DHTLOG_ROUTE,
4371 ntohl(incoming->hop_count), GNUNET_SYSERR,
4372 &my_identity, &incoming->key, peer,
4378 msg_ctx = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4379 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4380 GNUNET_assert(msg_ctx->bloom != NULL);
4381 msg_ctx->hop_count = ntohl(incoming->hop_count);
4382 memcpy(&msg_ctx->key, &incoming->key, sizeof(GNUNET_HashCode));
4383 msg_ctx->replication = ntohl(incoming->desired_replication_level);
4384 msg_ctx->unique_id = GNUNET_ntohll(incoming->unique_id);
4385 msg_ctx->msg_options = ntohl(incoming->options);
4386 msg_ctx->network_size = ntohl(incoming->network_size);
4387 msg_ctx->peer = peer;
4388 msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4389 msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4390 demultiplex_message (enc_msg, msg_ctx);
4391 if (msg_ctx->bloom != NULL)
4393 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4394 msg_ctx->bloom = NULL;
4396 GNUNET_free(msg_ctx);
4402 * Core handler for p2p route results.
4405 handle_dht_p2p_route_result (void *cls,
4406 const struct GNUNET_PeerIdentity *peer,
4407 const struct GNUNET_MessageHeader *message,
4408 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4411 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4412 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4414 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4415 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4416 struct DHT_MessageContext msg_ctx;
4418 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4424 if (malicious_dropper == GNUNET_YES)
4426 #if DEBUG_DHT_ROUTING
4427 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4429 /** Log routes that die due to high load! */
4430 dhtlog_handle->insert_route (NULL, GNUNET_ntohll(incoming->unique_id), DHTLOG_ROUTE,
4431 ntohl(incoming->hop_count), GNUNET_SYSERR,
4432 &my_identity, &incoming->key, peer,
4439 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4440 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4441 msg_ctx.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4442 GNUNET_assert(msg_ctx.bloom != NULL);
4443 memcpy(&msg_ctx.key, &incoming->key, sizeof(GNUNET_HashCode));
4444 msg_ctx.unique_id = GNUNET_ntohll(incoming->unique_id);
4445 msg_ctx.msg_options = ntohl(incoming->options);
4446 msg_ctx.hop_count = ntohl(incoming->hop_count);
4447 msg_ctx.peer = peer;
4448 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4449 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4450 route_result_message(enc_msg, &msg_ctx);
4456 * Receive the HELLO from transport service,
4457 * free current and replace if necessary.
4460 * @param message HELLO message of peer
4463 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4466 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4467 "Received our `%s' from transport service\n",
4471 GNUNET_assert (message != NULL);
4472 GNUNET_free_non_null(my_hello);
4473 my_hello = GNUNET_malloc(ntohs(message->size));
4474 memcpy(my_hello, message, ntohs(message->size));
4479 * Task run during shutdown.
4485 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4488 struct PeerInfo *pos;
4490 if (transport_handle != NULL)
4492 GNUNET_free_non_null(my_hello);
4493 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4494 GNUNET_TRANSPORT_disconnect(transport_handle);
4496 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4498 while (k_buckets[bucket_count].head != NULL)
4500 pos = k_buckets[bucket_count].head;
4502 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4503 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4505 delete_peer (pos, bucket_count);
4508 if (coreAPI != NULL)
4511 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4512 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4514 GNUNET_CORE_disconnect (coreAPI);
4517 if (datacache != NULL)
4520 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4521 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4523 GNUNET_DATACACHE_destroy (datacache);
4528 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4531 if (dhtlog_handle != NULL)
4533 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4534 dhtlog_handle = NULL;
4536 if (block_context != NULL)
4538 GNUNET_BLOCK_context_destroy (block_context);
4539 block_context = NULL;
4541 GNUNET_free_non_null(my_short_id);
4547 * To be called on core init/fail.
4549 * @param cls service closure
4550 * @param server handle to the server for this service
4551 * @param identity the public identity of this peer
4552 * @param publicKey the public key of this peer
4555 core_init (void *cls,
4556 struct GNUNET_CORE_Handle *server,
4557 const struct GNUNET_PeerIdentity *identity,
4558 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4564 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4565 "%s: Connection to core FAILED!\n", "dht",
4566 GNUNET_i2s (identity));
4568 GNUNET_SCHEDULER_cancel (cleanup_task);
4569 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4573 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4574 "%s: Core connection initialized, I am peer: %s\n", "dht",
4575 GNUNET_i2s (identity));
4578 /* Copy our identity so we can use it */
4579 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4580 if (my_short_id != NULL)
4581 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4582 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4583 /* Set the server to local variable */
4586 if (dhtlog_handle != NULL)
4587 dhtlog_handle->insert_node (NULL, &my_identity);
4591 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4592 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4593 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4594 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4599 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4600 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4601 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4607 * Method called whenever a peer connects.
4609 * @param cls closure
4610 * @param peer peer identity this notification is about
4611 * @param atsi performance data
4614 handle_core_connect (void *cls,
4615 const struct GNUNET_PeerIdentity * peer,
4616 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4618 struct PeerInfo *ret;
4621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4622 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4625 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4627 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));
4631 if (datacache != NULL)
4632 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, GNUNET_BLOCK_TYPE_DHT_HELLO, GNUNET_TIME_absolute_get_forever());
4633 ret = try_add_peer(peer,
4634 find_current_bucket(&peer->hashPubKey),
4638 newly_found_peers++;
4639 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4642 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4643 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4649 * Method called whenever a peer disconnects.
4651 * @param cls closure
4652 * @param peer peer identity this notification is about
4655 handle_core_disconnect (void *cls,
4657 GNUNET_PeerIdentity * peer)
4659 struct PeerInfo *to_remove;
4662 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");
4664 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4666 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));
4669 increment_stats(STAT_DISCONNECTS);
4670 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4671 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4672 GNUNET_assert (to_remove != NULL);
4673 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4674 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4675 delete_peer(to_remove, current_bucket);
4680 * Process dht requests.
4682 * @param cls closure
4683 * @param server the initialized server
4684 * @param c configuration to use
4688 struct GNUNET_SERVER_Handle *server,
4689 const struct GNUNET_CONFIGURATION_Handle *c)
4691 struct GNUNET_TIME_Relative next_send_time;
4692 unsigned long long temp_config_num;
4693 char *converge_modifier_buf;
4696 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4697 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4698 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4699 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
4700 DEFAULT_CORE_QUEUE_SIZE, /* queue size */
4701 NULL, /* Closure passed to DHT functions */
4702 &core_init, /* Call core_init once connected */
4703 &handle_core_connect, /* Handle connects */
4704 &handle_core_disconnect, /* remove peers on disconnects */
4705 NULL, /* Do we care about "status" updates? */
4706 NULL, /* Don't want notified about all incoming messages */
4707 GNUNET_NO, /* For header only inbound notification */
4708 NULL, /* Don't want notified about all outbound messages */
4709 GNUNET_NO, /* For header only outbound notification */
4710 core_handlers); /* Register these handlers */
4712 if (coreAPI == NULL)
4714 transport_handle = GNUNET_TRANSPORT_connect(cfg,
4715 NULL, NULL, NULL, NULL, NULL);
4716 if (transport_handle != NULL)
4717 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4719 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4720 "Failed to connect to transport service!\n");
4721 block_context = GNUNET_BLOCK_context_create (cfg);
4722 lowest_bucket = MAX_BUCKETS - 1;
4723 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4724 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4725 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4726 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4727 GNUNET_assert(all_known_peers != NULL);
4728 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4730 debug_routes = GNUNET_YES;
4734 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4737 strict_kademlia = GNUNET_YES;
4741 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4744 stop_on_closest = GNUNET_YES;
4748 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4751 stop_on_found = GNUNET_YES;
4755 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4756 "malicious_getter"))
4758 malicious_getter = GNUNET_YES;
4759 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4760 "MALICIOUS_GET_FREQUENCY",
4761 &malicious_get_frequency))
4762 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4765 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4769 max_hops = DEFAULT_MAX_HOPS;
4772 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4775 use_max_hops = GNUNET_YES;
4779 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4780 "malicious_putter"))
4782 malicious_putter = GNUNET_YES;
4783 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4784 "MALICIOUS_PUT_FREQUENCY",
4785 &malicious_put_frequency))
4786 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4789 dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
4790 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4792 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4795 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "bucket_size", &temp_config_num))
4797 bucket_size = (unsigned int)temp_config_num;
4800 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "kad_alpha", &kademlia_replication))
4802 kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
4806 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4807 "malicious_dropper"))
4809 malicious_dropper = GNUNET_YES;
4813 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4815 do_republish = GNUNET_NO;
4818 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4821 do_find_peer = GNUNET_NO;
4824 do_find_peer = GNUNET_YES;
4827 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4828 "use_real_distance"))
4829 use_real_distance = GNUNET_YES;
4832 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4833 "mysql_logging_extended"))
4835 debug_routes = GNUNET_YES;
4836 debug_routes_extended = GNUNET_YES;
4839 #if DEBUG_DHT_ROUTING
4840 if (GNUNET_YES == debug_routes)
4842 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4843 if (dhtlog_handle == NULL)
4845 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4846 "Could not connect to mysql logging server, logging will not happen!");
4851 converge_option = DHT_CONVERGE_SQUARE;
4853 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4856 converge_option = DHT_CONVERGE_LINEAR;
4858 else if (GNUNET_YES ==
4859 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4860 "converge_exponential"))
4862 converge_option = DHT_CONVERGE_EXPONENTIAL;
4864 else if (GNUNET_YES ==
4865 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4868 converge_option = DHT_CONVERGE_RANDOM;
4870 else if (GNUNET_YES ==
4871 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4874 converge_option = DHT_CONVERGE_BINARY;
4877 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht", "converge_modifier", &converge_modifier_buf))
4879 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4881 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4882 converge_modifier = 0.0;
4884 GNUNET_free(converge_modifier_buf);
4887 stats = GNUNET_STATISTICS_create("dht", cfg);
4891 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4892 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4893 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4894 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4895 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4896 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4897 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4898 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4899 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4900 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4901 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4902 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4903 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4904 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4905 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4906 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4907 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4908 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4909 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4910 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4912 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4913 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4914 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4915 if (GNUNET_YES == do_find_peer)
4917 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4918 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4919 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4920 find_peer_context.start = GNUNET_TIME_absolute_get();
4921 GNUNET_SCHEDULER_add_delayed (next_send_time,
4922 &send_find_peer_message, &find_peer_context);
4925 /* Scheduled the task to clean up when shutdown is called */
4926 cleanup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4927 &shutdown_task, NULL);
4931 * The main function for the dht service.
4933 * @param argc number of arguments from the command line
4934 * @param argv command line arguments
4935 * @return 0 ok, 1 on error
4938 main (int argc, char *const *argv)
4943 GNUNET_SERVICE_run (argc,
4946 GNUNET_SERVICE_OPTION_NONE,
4947 &run, NULL)) ? 0 : 1;
4948 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap));
4949 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap));
4950 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4951 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4952 GNUNET_CONTAINER_heap_destroy (recent.minHeap);