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 * Head of pending messages to be sent to this peer.
262 struct P2PPendingMessage *head;
265 * Tail of pending messages to be sent to this peer.
267 struct P2PPendingMessage *tail;
270 * Core handle for sending messages to this peer.
272 struct GNUNET_CORE_TransmitHandle *th;
275 * Task for scheduling message sends.
277 GNUNET_SCHEDULER_TaskIdentifier send_task;
280 * Task for scheduling preference updates
282 GNUNET_SCHEDULER_TaskIdentifier preference_task;
285 * Preference update context
287 struct GNUNET_CORE_InformationRequestContext *info_ctx;
290 * What is the identity of the peer?
292 struct GNUNET_PeerIdentity id;
296 * What is the average latency for replies received?
298 struct GNUNET_TIME_Relative latency;
301 * Transport level distance to peer.
303 unsigned int distance;
307 * Holds matching bits from peer to current target,
308 * used for distance comparisons between peers. May
309 * be considered a really bad idea.
310 * FIXME: remove this value (create struct which holds
311 * a single peerinfo and the matching bits, use
312 * that to pass to comparator)
314 unsigned int matching_bits;
317 * Task for scheduling periodic ping messages for this peer.
319 GNUNET_SCHEDULER_TaskIdentifier ping_task;
323 * Peers are grouped into buckets.
330 struct PeerInfo *head;
335 struct PeerInfo *tail;
338 * Number of peers in the bucket.
340 unsigned int peers_size;
344 * Linked list of messages to send to clients.
346 struct PendingMessage
349 * Pointer to next item in the list
351 struct PendingMessage *next;
354 * Pointer to previous item in the list
356 struct PendingMessage *prev;
359 * Actual message to be sent; // avoid allocation
361 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
366 * Struct containing information about a client,
367 * handle to connect to it, and any pending messages
368 * that need to be sent to it.
373 * Linked list of active clients
375 struct ClientList *next;
378 * The handle to this client
380 struct GNUNET_SERVER_Client *client_handle;
383 * Handle to the current transmission request, NULL
386 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
389 * Linked list of pending messages for this client
391 struct PendingMessage *pending_head;
394 * Tail of linked list of pending messages for this client
396 struct PendingMessage *pending_tail;
401 * Context containing information about a DHT message received.
403 struct DHT_MessageContext
406 * The client this request was received from.
407 * (NULL if received from another peer)
409 struct ClientList *client;
412 * The peer this request was received from.
413 * (NULL if received from local client)
415 const struct GNUNET_PeerIdentity *peer;
418 * Bloomfilter for this routing request.
420 struct GNUNET_CONTAINER_BloomFilter *bloom;
423 * extended query (see gnunet_block_lib.h).
428 * Bloomfilter to filter out duplicate replies.
430 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
433 * The key this request was about
438 * How long should we wait to transmit this request?
440 struct GNUNET_TIME_Relative timeout;
443 * The unique identifier of this request
448 * Number of bytes in xquery.
453 * Mutator value for the reply_bf, see gnunet_block_lib.h
455 uint32_t reply_bf_mutator;
458 * Desired replication level
460 uint32_t replication;
463 * Network size estimate, either ours or the sum of
464 * those routed to thus far. =~ Log of number of peers
465 * chosen from for this request.
467 uint32_t network_size;
470 * Any message options for this request
472 uint32_t msg_options;
475 * How many hops has the message already traversed?
480 * How important is this message?
482 unsigned int importance;
485 * Should we (still) forward the request on to other peers?
490 * Did we forward this message? (may need to remember it!)
495 * Are we the closest known peer to this key (out of our neighbors?)
501 * Record used for remembering what peers are waiting for what
502 * responses (based on search key).
504 struct DHTRouteSource
509 struct DHTRouteSource *next;
514 struct DHTRouteSource *prev;
517 * Source of the request. Replies should be forwarded to
520 struct GNUNET_PeerIdentity source;
523 * If this was a local request, remember the client; otherwise NULL.
525 struct ClientList *client;
528 * Pointer to this nodes heap location (for removal)
530 struct GNUNET_CONTAINER_HeapNode *hnode;
533 * Back pointer to the record storing this information.
535 struct DHTQueryRecord *record;
538 * Task to remove this entry on timeout.
540 GNUNET_SCHEDULER_TaskIdentifier delete_task;
543 * Bloomfilter of peers we have already sent back as
544 * replies to the initial request. Allows us to not
545 * forward the same peer multiple times for a find peer
548 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
553 * Entry in the DHT routing table.
555 struct DHTQueryRecord
558 * Head of DLL for result forwarding.
560 struct DHTRouteSource *head;
563 * Tail of DLL for result forwarding.
565 struct DHTRouteSource *tail;
568 * Key that the record concerns.
573 * GET message of this record (what we already forwarded?).
575 //DV_DHT_MESSAGE get; Try to get away with not saving this.
578 * Bloomfilter of the peers we've replied to so far
580 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
585 * Context used to calculate the number of find peer messages
586 * per X time units since our last scheduled find peer message
587 * was sent. If we have seen too many messages, delay or don't
590 struct FindPeerMessageContext
594 struct GNUNET_TIME_Absolute start;
596 struct GNUNET_TIME_Absolute end;
600 * DHT Routing results structure
605 * Min heap for removal upon reaching limit
607 struct GNUNET_CONTAINER_Heap *minHeap;
610 * Hashmap for fast key based lookup
612 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
617 * DHT structure for recent requests.
619 struct RecentRequests
622 * Min heap for removal upon reaching limit
624 struct GNUNET_CONTAINER_Heap *minHeap;
627 * Hashmap for key based lookup
629 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
635 * Position of this node in the min heap.
637 struct GNUNET_CONTAINER_HeapNode *heap_node;
640 * Bloomfilter containing entries for peers
641 * we forwarded this request to.
643 struct GNUNET_CONTAINER_BloomFilter *bloom;
646 * Timestamp of this request, for ordering
649 struct GNUNET_TIME_Absolute timestamp;
652 * Key of this request.
657 * Unique identifier for this request.
662 * Task to remove this entry on timeout.
664 GNUNET_SCHEDULER_TaskIdentifier remove_task;
667 struct RepublishContext
682 * Which kind of convergence will we be using?
684 static enum ConvergenceOptions converge_option;
687 * Modifier for the convergence function
689 static float converge_modifier;
692 * Recent requests by hash/uid and by time inserted.
694 static struct RecentRequests recent;
697 * Context to use to calculate find peer rates.
699 static struct FindPeerMessageContext find_peer_context;
702 * Don't use our routing algorithm, always route
703 * to closest peer; initially send requests to 3
706 static unsigned int strict_kademlia;
709 * Routing option to end routing when closest peer found.
711 static unsigned int stop_on_closest;
714 * Routing option to end routing when data is found.
716 static unsigned int stop_on_found;
719 * Whether DHT needs to manage find peer requests, or
720 * an external force will do it on behalf of the DHT.
722 static unsigned int do_find_peer;
725 * Once we have stored an item in the DHT, refresh it
726 * according to our republish interval.
728 static unsigned int do_republish;
731 * Use the "real" distance metric when selecting the
732 * next routing hop. Can be less accurate.
734 static unsigned int use_real_distance;
737 * How many peers have we added since we sent out our last
740 static unsigned int newly_found_peers;
743 * Container of active queries we should remember
745 static struct DHTResults forward_list;
748 * Handle to the datacache service (for inserting/retrieving data)
750 static struct GNUNET_DATACACHE_Handle *datacache;
753 * Handle for the statistics service.
755 struct GNUNET_STATISTICS_Handle *stats;
759 * The configuration the DHT service is running with
761 static const struct GNUNET_CONFIGURATION_Handle *cfg;
764 * Handle to the core service
766 static struct GNUNET_CORE_Handle *coreAPI;
769 * Handle to the transport service, for getting our hello
771 static struct GNUNET_TRANSPORT_Handle *transport_handle;
774 * The identity of our peer.
776 static struct GNUNET_PeerIdentity my_identity;
779 * Short id of the peer, for printing
781 static char *my_short_id;
786 static struct GNUNET_MessageHeader *my_hello;
789 * Task to run when we shut down, cleaning up all our trash
791 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
794 * The lowest currently used bucket.
796 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
799 * The maximum number of hops before we stop routing messages.
801 static unsigned long long max_hops;
804 * How often to republish content we have previously stored.
806 static struct GNUNET_TIME_Relative dht_republish_frequency;
809 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
811 static int use_max_hops;
814 * The buckets (Kademlia routing table, complete with growth).
815 * Array of size MAX_BUCKET_SIZE.
817 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
820 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
822 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
825 * Recently seen find peer requests.
827 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
830 * Maximum size for each bucket.
832 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
835 * List of active clients.
837 static struct ClientList *client_list;
840 * Handle to the DHT logger.
842 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
845 * Whether or not to send routing debugging information
846 * to the dht logging server
848 static unsigned int debug_routes;
851 * Whether or not to send FULL route information to
854 static unsigned int debug_routes_extended;
857 * GNUNET_YES or GNUNET_NO, whether or not to act as
858 * a malicious node which drops all messages
860 static unsigned int malicious_dropper;
863 * GNUNET_YES or GNUNET_NO, whether or not to act as
864 * a malicious node which sends out lots of GETS
866 static unsigned int malicious_getter;
869 * GNUNET_YES or GNUNET_NO, whether or not to act as
870 * a malicious node which sends out lots of PUTS
872 static unsigned int malicious_putter;
875 * Frequency for malicious get requests.
877 static unsigned long long malicious_get_frequency;
880 * Frequency for malicious put requests.
882 static unsigned long long malicious_put_frequency;
885 * Kademlia replication
887 static unsigned long long kademlia_replication;
890 * Reply times for requests, if we are busy, don't send any
893 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
896 * Current counter for replies.
898 static unsigned int reply_counter;
901 * Our handle to the BLOCK library.
903 static struct GNUNET_BLOCK_Context *block_context;
907 * Forward declaration.
910 send_generic_reply (void *cls, size_t size, void *buf);
913 /** Declare here so retry_core_send is aware of it */
915 core_transmit_notify (void *cls,
916 size_t size, void *buf);
919 * Convert unique ID to hash code.
921 * @param uid unique ID to convert
922 * @param hash set to uid (extended with zeros)
925 hash_from_uid (uint64_t uid,
926 GNUNET_HashCode *hash)
928 memset (hash, 0, sizeof(GNUNET_HashCode));
929 *((uint64_t*)hash) = uid;
934 * Calculate the average send time between messages so that we can
935 * ignore certain requests if we get too busy.
937 * @return the average time between asking core to send a message
938 * and when the buffer for copying it is passed
940 static struct GNUNET_TIME_Relative get_average_send_delay()
943 unsigned int divisor;
944 struct GNUNET_TIME_Relative average_time;
945 average_time = GNUNET_TIME_relative_get_zero();
947 for (i = 0; i < MAX_REPLY_TIMES; i++)
949 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
950 if (reply_times[i].abs_value == (uint64_t)0)
960 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
962 "Avg send delay: %u sends is %llu\n",
964 (unsigned long long) average_time.abs_value);
970 * Given the largest send delay, artificially decrease it
971 * so the next time around we may have a chance at sending
974 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
977 for (i = 0; i < MAX_REPLY_TIMES; i++)
979 if (reply_times[i].rel_value == max_time.rel_value)
981 reply_times[i].rel_value = reply_times[i].rel_value / 2;
988 * Find the maximum send time of the recently sent values.
990 * @return the average time between asking core to send a message
991 * and when the buffer for copying it is passed
993 static struct GNUNET_TIME_Relative get_max_send_delay()
996 struct GNUNET_TIME_Relative max_time;
997 max_time = GNUNET_TIME_relative_get_zero();
999 for (i = 0; i < MAX_REPLY_TIMES; i++)
1001 if (reply_times[i].rel_value > max_time.rel_value)
1002 max_time.rel_value = reply_times[i].rel_value;
1005 if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
1006 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n",
1007 (unsigned long long) max_time.rel_value);
1012 increment_stats(const char *value)
1016 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
1021 * Try to send another message from our core send list
1024 try_core_send (void *cls,
1025 const struct GNUNET_SCHEDULER_TaskContext *tc)
1027 struct PeerInfo *peer = cls;
1028 struct P2PPendingMessage *pending;
1031 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
1033 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1036 if (peer->th != NULL)
1037 return; /* Message send already in progress */
1039 pending = peer->head;
1040 if (pending != NULL)
1042 ssize = ntohs(pending->msg->size);
1044 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1045 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
1046 "DHT", ssize, GNUNET_i2s(&peer->id));
1048 pending->scheduled = GNUNET_TIME_absolute_get();
1050 if (reply_counter >= MAX_REPLY_TIMES)
1052 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
1053 pending->timeout, &peer->id,
1054 ssize, &core_transmit_notify, peer);
1059 * Function called to send a request out to another peer.
1060 * Called both for locally initiated requests and those
1061 * received from other peers.
1063 * @param msg the encapsulated message
1064 * @param peer the peer to forward the message to
1065 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1068 forward_result_message (const struct GNUNET_MessageHeader *msg,
1069 struct PeerInfo *peer,
1070 struct DHT_MessageContext *msg_ctx)
1072 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1073 struct P2PPendingMessage *pending;
1077 increment_stats(STAT_RESULT_FORWARDS);
1078 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1079 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1080 psize = sizeof(struct P2PPendingMessage) + msize;
1081 pending = GNUNET_malloc(psize);
1082 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1083 pending->importance = DHT_SEND_PRIORITY;
1084 pending->timeout = GNUNET_TIME_relative_get_forever();
1085 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1086 result_message->header.size = htons(msize);
1087 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1088 result_message->put_path_length = htons(0); /* FIXME: implement */
1089 result_message->get_path_length = htons(0); /* FIXME: implement */
1090 result_message->options = htonl(msg_ctx->msg_options);
1091 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1092 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1093 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1094 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1095 memcpy(&result_message[1], msg, ntohs(msg->size));
1097 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));
1099 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1100 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1101 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1106 * Called when core is ready to send a message we asked for
1107 * out to the destination.
1109 * @param cls closure (NULL)
1110 * @param size number of bytes available in buf
1111 * @param buf where the callee should write the message
1112 * @return number of bytes written to buf
1115 core_transmit_notify (void *cls,
1116 size_t size, void *buf)
1118 struct PeerInfo *peer = cls;
1120 struct P2PPendingMessage *pending;
1127 /* client disconnected */
1129 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1134 if (peer->head == NULL)
1138 pending = peer->head;
1139 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1140 msize = ntohs(pending->msg->size);
1144 memcpy (cbuf, pending->msg, msize);
1145 GNUNET_CONTAINER_DLL_remove (peer->head,
1149 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Removing pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
1151 GNUNET_free (pending);
1154 while (NULL != pending &&
1155 (size - off >= (msize = ntohs (pending->msg->size))))
1157 #if DEBUG_DHT_ROUTING
1158 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s:%s' : transmit_notify (core) called with size %d, available %d\n", my_short_id, "dht service", msize, size);
1160 memcpy (&cbuf[off], pending->msg, msize);
1162 GNUNET_CONTAINER_DLL_remove (peer->head,
1165 GNUNET_free (pending);
1166 pending = peer->head;
1169 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1170 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1172 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s:%s' : transmit_notify (core) called with size %d, available %d, returning %d\n", my_short_id, "dht service", msize, size, off);
1179 * Compute the distance between have and target as a 32-bit value.
1180 * Differences in the lower bits must count stronger than differences
1181 * in the higher bits.
1183 * @return 0 if have==target, otherwise a number
1184 * that is larger as the distance between
1185 * the two hash codes increases
1188 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1190 unsigned int bucket;
1195 /* We have to represent the distance between two 2^9 (=512)-bit
1196 numbers as a 2^5 (=32)-bit number with "0" being used for the
1197 two numbers being identical; furthermore, we need to
1198 guarantee that a difference in the number of matching
1199 bits is always represented in the result.
1201 We use 2^32/2^9 numerical values to distinguish between
1202 hash codes that have the same LSB bit distance and
1203 use the highest 2^9 bits of the result to signify the
1204 number of (mis)matching LSB bits; if we have 0 matching
1205 and hence 512 mismatching LSB bits we return -1 (since
1206 512 itself cannot be represented with 9 bits) */
1208 /* first, calculate the most significant 9 bits of our
1209 result, aka the number of LSBs */
1210 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1211 /* bucket is now a value between 0 and 512 */
1213 return 0; /* perfect match */
1215 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1216 below, we'd end up with max+1 (overflow)) */
1218 /* calculate the most significant bits of the final result */
1219 msb = (512 - bucket) << (32 - 9);
1220 /* calculate the 32-9 least significant bits of the final result by
1221 looking at the differences in the 32-9 bits following the
1222 mismatching bit at 'bucket' */
1224 for (i = bucket + 1;
1225 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1227 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1228 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1229 last bit set will be 31 -- if
1230 i does not reach 512 first... */
1236 * Return a number that is larger the closer the
1237 * "have" GNUNET_hash code is to the "target".
1239 * @return inverse distance metric, non-zero.
1240 * Must fudge the value if NO bits match.
1243 inverse_distance (const GNUNET_HashCode * target,
1244 const GNUNET_HashCode * have)
1246 if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1247 return 1; /* Never return 0! */
1248 return ((unsigned int) -1) - distance (target, have);
1252 * Find the optimal bucket for this key, regardless
1253 * of the current number of buckets in use.
1255 * @param hc the hashcode to compare our identity to
1257 * @return the proper bucket index, or GNUNET_SYSERR
1258 * on error (same hashcode)
1260 static int find_bucket(const GNUNET_HashCode *hc)
1264 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1265 if (bits == MAX_BUCKETS)
1266 return GNUNET_SYSERR;
1267 return MAX_BUCKETS - bits - 1;
1271 * Find which k-bucket this peer should go into,
1272 * taking into account the size of the k-bucket
1273 * array. This means that if more bits match than
1274 * there are currently buckets, lowest_bucket will
1277 * @param hc GNUNET_HashCode we are finding the bucket for.
1279 * @return the proper bucket index for this key,
1280 * or GNUNET_SYSERR on error (same hashcode)
1282 static int find_current_bucket(const GNUNET_HashCode *hc)
1285 actual_bucket = find_bucket(hc);
1287 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1288 return lowest_bucket;
1289 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1290 return lowest_bucket;
1292 return actual_bucket;
1297 * Find a routing table entry from a peer identity
1299 * @param peer the peer to look up
1301 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1304 find_bucket_by_peer(const struct PeerInfo *peer)
1307 struct PeerInfo *pos;
1309 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1311 pos = k_buckets[bucket].head;
1320 return GNUNET_SYSERR; /* No such peer. */
1326 * Print the complete routing table for this peer.
1329 print_routing_table ()
1332 struct PeerInfo *pos;
1333 char char_buf[30000];
1335 memset(char_buf, 0, sizeof(char_buf));
1337 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1338 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1339 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1341 pos = k_buckets[bucket].head;
1342 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1343 //fprintf(stderr, "Bucket %d:\n", bucket);
1346 //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));
1347 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));
1351 fprintf(stderr, "%s", char_buf);
1357 * Find a routing table entry from a peer identity
1359 * @param peer the peer identity to look up
1361 * @return the routing table entry, or NULL if not found
1363 static struct PeerInfo *
1364 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1367 struct PeerInfo *pos;
1368 bucket = find_current_bucket(&peer->hashPubKey);
1370 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1373 pos = k_buckets[bucket].head;
1376 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1380 return NULL; /* No such peer. */
1383 /* Forward declaration */
1385 update_core_preference (void *cls,
1386 const struct GNUNET_SCHEDULER_TaskContext *tc);
1388 * Function called with statistics about the given peer.
1390 * @param cls closure
1391 * @param peer identifies the peer
1392 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1393 * @param amount set to the amount that was actually reserved or unreserved;
1394 * either the full requested amount or zero (no partial reservations)
1395 * @param preference current traffic preference for the given peer
1398 update_core_preference_finish (void *cls,
1399 const struct GNUNET_PeerIdentity * peer,
1400 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1401 int amount, uint64_t preference)
1403 struct PeerInfo *peer_info = cls;
1404 peer_info->info_ctx = NULL;
1405 GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1409 update_core_preference (void *cls,
1410 const struct GNUNET_SCHEDULER_TaskContext *tc)
1412 struct PeerInfo *peer = cls;
1413 uint64_t preference;
1414 unsigned int matching;
1415 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1419 matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1422 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1425 preference = 1LL << matching;
1426 peer->info_ctx = GNUNET_CORE_peer_change_preference (coreAPI,
1428 GNUNET_TIME_relative_get_forever(),
1429 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1432 &update_core_preference_finish,
1437 * Really add a peer to a bucket (only do assertions
1440 * @param peer GNUNET_PeerIdentity of the peer to add
1441 * @param bucket the already figured out bucket to add
1443 * @param atsi performance information
1445 * @return the newly added PeerInfo
1447 static struct PeerInfo *
1448 add_peer(const struct GNUNET_PeerIdentity *peer,
1449 unsigned int bucket,
1450 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1452 struct PeerInfo *new_peer;
1453 GNUNET_assert(bucket < MAX_BUCKETS);
1454 GNUNET_assert(peer != NULL);
1455 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1457 new_peer->latency = latency;
1458 new_peer->distance = distance;
1461 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1463 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1464 k_buckets[bucket].tail,
1465 k_buckets[bucket].tail,
1467 k_buckets[bucket].peers_size++;
1469 if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1471 #if DO_UPDATE_PREFERENCE
1472 new_peer->preference_task = GNUNET_SCHEDULER_add_now(&update_core_preference, new_peer);
1480 * Given a peer and its corresponding bucket,
1481 * remove it from that bucket. Does not free
1482 * the PeerInfo struct, nor cancel messages
1483 * or free messages waiting to be sent to this
1486 * @param peer the peer to remove
1487 * @param bucket the bucket the peer belongs to
1489 static void remove_peer (struct PeerInfo *peer,
1490 unsigned int bucket)
1492 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1493 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1494 k_buckets[bucket].tail,
1496 k_buckets[bucket].peers_size--;
1498 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1504 * Removes peer from a bucket, then frees associated
1505 * resources and frees peer.
1507 * @param peer peer to be removed and freed
1508 * @param bucket which bucket this peer belongs to
1510 static void delete_peer (struct PeerInfo *peer,
1511 unsigned int bucket)
1513 struct P2PPendingMessage *pos;
1514 struct P2PPendingMessage *next;
1516 struct PeerInfo *peer_pos;
1518 peer_pos = k_buckets[bucket].head;
1519 while ((peer_pos != NULL) && (peer_pos != peer))
1520 peer_pos = peer_pos->next;
1521 if (peer_pos == NULL)
1523 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1524 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));
1526 GNUNET_assert(peer_pos != NULL);
1528 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1530 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1531 GNUNET_SCHEDULER_cancel(peer->send_task);
1532 if ((peer->th != NULL) && (coreAPI != NULL))
1533 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1536 while (pos != NULL) /* Remove any pending messages for this peer */
1543 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1544 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer));
1550 * Iterator over hash map entries.
1552 * @param cls closure
1553 * @param key current key code
1554 * @param value PeerInfo of the peer to move to new lowest bucket
1555 * @return GNUNET_YES if we should continue to
1559 static int move_lowest_bucket (void *cls,
1560 const GNUNET_HashCode * key,
1563 struct PeerInfo *peer = value;
1566 GNUNET_assert(lowest_bucket > 0);
1567 new_bucket = lowest_bucket - 1;
1568 remove_peer(peer, lowest_bucket);
1569 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1570 k_buckets[new_bucket].tail,
1571 k_buckets[new_bucket].tail,
1573 k_buckets[new_bucket].peers_size++;
1579 * The current lowest bucket is full, so change the lowest
1580 * bucket to the next lower down, and move any appropriate
1581 * entries in the current lowest bucket to the new bucket.
1583 static void enable_next_bucket()
1585 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1586 struct PeerInfo *pos;
1587 GNUNET_assert(lowest_bucket > 0);
1588 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1589 pos = k_buckets[lowest_bucket].head;
1592 fprintf(stderr, "Printing RT before new bucket\n");
1593 print_routing_table();
1595 /* Populate the array of peers which should be in the next lowest bucket */
1598 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1599 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1603 /* Remove peers from lowest bucket, insert into next lowest bucket */
1604 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1605 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1606 lowest_bucket = lowest_bucket - 1;
1608 fprintf(stderr, "Printing RT after new bucket\n");
1609 print_routing_table();
1614 * Find the closest peer in our routing table to the
1617 * @return The closest peer in our routing table to the
1618 * key, or NULL on error.
1620 static struct PeerInfo *
1621 find_closest_peer (const GNUNET_HashCode *hc)
1623 struct PeerInfo *pos;
1624 struct PeerInfo *current_closest;
1625 unsigned int lowest_distance;
1626 unsigned int temp_distance;
1630 lowest_distance = -1;
1632 if (k_buckets[lowest_bucket].peers_size == 0)
1635 current_closest = NULL;
1636 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1638 pos = k_buckets[bucket].head;
1640 while ((pos != NULL) && (count < bucket_size))
1642 temp_distance = distance(&pos->id.hashPubKey, hc);
1643 if (temp_distance <= lowest_distance)
1645 lowest_distance = temp_distance;
1646 current_closest = pos;
1652 GNUNET_assert(current_closest != NULL);
1653 return current_closest;
1658 * Function called to send a request out to another peer.
1659 * Called both for locally initiated requests and those
1660 * received from other peers.
1662 * @param msg the encapsulated message
1663 * @param peer the peer to forward the message to
1664 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1666 static void forward_message (const struct GNUNET_MessageHeader *msg,
1667 struct PeerInfo *peer,
1668 struct DHT_MessageContext *msg_ctx)
1670 struct GNUNET_DHT_P2PRouteMessage *route_message;
1671 struct P2PPendingMessage *pending;
1675 increment_stats(STAT_ROUTE_FORWARDS);
1676 GNUNET_assert(peer != NULL);
1677 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1678 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1680 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1681 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1682 psize = sizeof(struct P2PPendingMessage) + msize;
1683 pending = GNUNET_malloc(psize);
1684 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1685 pending->importance = msg_ctx->importance;
1686 pending->timeout = msg_ctx->timeout;
1687 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1688 route_message->header.size = htons(msize);
1689 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1690 route_message->options = htonl(msg_ctx->msg_options);
1691 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1692 route_message->network_size = htonl(msg_ctx->network_size);
1693 route_message->desired_replication_level = htonl(msg_ctx->replication);
1694 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1695 if (msg_ctx->bloom != NULL)
1696 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1697 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1698 memcpy(&route_message[1], msg, ntohs(msg->size));
1700 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));
1702 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1703 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1704 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1709 * Task used to send ping messages to peers so that
1710 * they don't get disconnected.
1712 * @param cls the peer to send a ping message to
1713 * @param tc context, reason, etc.
1716 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1718 struct PeerInfo *peer = cls;
1719 struct GNUNET_MessageHeader ping_message;
1720 struct DHT_MessageContext msg_ctx;
1722 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1725 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1726 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1728 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
1730 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1732 forward_message(&ping_message, peer, &msg_ctx);
1733 peer->ping_task = GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1737 * Schedule PING messages for the top X peers in each
1738 * bucket of the routing table (so core won't disconnect them!)
1740 void schedule_ping_messages()
1742 unsigned int bucket;
1744 struct PeerInfo *pos;
1745 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1747 pos = k_buckets[bucket].head;
1751 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1752 GNUNET_SCHEDULER_add_now(&periodic_ping_task, pos);
1753 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1755 GNUNET_SCHEDULER_cancel(pos->ping_task);
1756 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1766 * Attempt to add a peer to our k-buckets.
1768 * @param peer the peer identity of the peer being added
1769 * @param bucket the bucket that we want this peer to go in
1770 * @param latency transport latency of this peer
1771 * @param distance transport distance to this peer
1773 * @return NULL if the peer was not added,
1774 * pointer to PeerInfo for new peer otherwise
1776 static struct PeerInfo *
1777 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1778 unsigned int bucket,
1779 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1782 struct PeerInfo *new_peer;
1784 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1787 peer_bucket = find_current_bucket(&peer->hashPubKey);
1789 GNUNET_assert(peer_bucket >= lowest_bucket);
1790 new_peer = add_peer(peer, peer_bucket, atsi);
1792 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1793 enable_next_bucket();
1795 schedule_ping_messages();
1802 * Task run to check for messages that need to be sent to a client.
1804 * @param client a ClientList, containing the client and any messages to be sent to it
1807 process_pending_messages (struct ClientList *client)
1809 if (client->pending_head == NULL)
1811 if (client->transmit_handle != NULL)
1814 client->transmit_handle =
1815 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1816 ntohs (client->pending_head->msg->
1818 GNUNET_TIME_UNIT_FOREVER_REL,
1819 &send_generic_reply, client);
1823 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1824 * request. A ClientList is passed as closure, take the head of the list
1825 * and copy it into buf, which has the result of sending the message to the
1828 * @param cls closure to this call
1829 * @param size maximum number of bytes available to send
1830 * @param buf where to copy the actual message to
1832 * @return the number of bytes actually copied, 0 indicates failure
1835 send_generic_reply (void *cls, size_t size, void *buf)
1837 struct ClientList *client = cls;
1839 struct PendingMessage *reply;
1843 client->transmit_handle = NULL;
1846 /* client disconnected */
1850 while ( (NULL != (reply = client->pending_head)) &&
1851 (size >= off + (msize = ntohs (reply->msg->size))))
1853 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1854 client->pending_tail,
1856 memcpy (&cbuf[off], reply->msg, msize);
1857 GNUNET_free (reply);
1860 process_pending_messages (client);
1862 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1863 "Transmitted %u bytes of replies to client\n",
1864 (unsigned int) off);
1871 * Add a PendingMessage to the clients list of messages to be sent
1873 * @param client the active client to send the message to
1874 * @param pending_message the actual message to send
1877 add_pending_message (struct ClientList *client,
1878 struct PendingMessage *pending_message)
1880 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1881 client->pending_tail,
1882 client->pending_tail,
1884 process_pending_messages (client);
1889 * Called when a reply needs to be sent to a client, as
1890 * a result it found to a GET or FIND PEER request.
1892 * @param client the client to send the reply to
1893 * @param message the encapsulated message to send
1894 * @param uid the unique identifier of this request
1897 send_reply_to_client (struct ClientList *client,
1898 const struct GNUNET_MessageHeader *message,
1899 unsigned long long uid,
1900 const GNUNET_HashCode *key)
1902 struct GNUNET_DHT_RouteResultMessage *reply;
1903 struct PendingMessage *pending_message;
1907 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1908 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1910 msize = ntohs (message->size);
1911 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1912 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1914 GNUNET_break_op (0);
1917 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1918 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1919 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1920 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1921 reply->header.size = htons (tsize);
1922 reply->put_path_length = htons(0); /* FIXME: implement */
1923 reply->get_path_length = htons(0); /* FIXME: implement */
1924 reply->unique_id = GNUNET_htonll (uid);
1926 memcpy (&reply[1], message, msize);
1927 add_pending_message (client, pending_message);
1931 * Consider whether or not we would like to have this peer added to
1932 * our routing table. Check whether bucket for this peer is full,
1933 * if so return negative; if not return positive. Since peers are
1934 * only added on CORE level connect, this doesn't actually add the
1935 * peer to the routing table.
1937 * @param peer the peer we are considering adding
1939 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1942 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1946 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1947 return GNUNET_NO; /* We already know this peer (are connected even!) */
1948 bucket = find_current_bucket(&peer->hashPubKey);
1950 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1957 * Main function that handles whether or not to route a result
1958 * message to other peers, or to send to our local client.
1960 * @param msg the result message to be routed
1961 * @param msg_ctx context of the message we are routing
1963 * @return the number of peers the message was routed to,
1964 * GNUNET_SYSERR on failure
1966 static int route_result_message(struct GNUNET_MessageHeader *msg,
1967 struct DHT_MessageContext *msg_ctx)
1969 struct GNUNET_PeerIdentity new_peer;
1970 struct DHTQueryRecord *record;
1971 struct DHTRouteSource *pos;
1972 struct PeerInfo *peer_info;
1973 const struct GNUNET_MessageHeader *hello_msg;
1975 increment_stats(STAT_RESULTS);
1977 * If a find peer result message is received and contains a valid
1978 * HELLO for another peer, offer it to the transport service.
1980 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1982 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1985 hello_msg = &msg[1];
1986 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1988 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1992 else /* We have a valid hello, and peer id stored in new_peer */
1994 find_peer_context.count++;
1995 increment_stats(STAT_FIND_PEER_REPLY);
1996 if (GNUNET_YES == consider_peer(&new_peer))
1998 increment_stats(STAT_HELLOS_PROVIDED);
1999 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
2000 GNUNET_CORE_peer_request_connect(coreAPI,
2001 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
2006 if (malicious_dropper == GNUNET_YES)
2009 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2011 if (record == NULL) /* No record of this message! */
2014 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2015 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
2016 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2018 #if DEBUG_DHT_ROUTING
2019 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2021 dhtlog_handle->insert_route (NULL,
2028 msg_ctx->peer, NULL);
2031 if (msg_ctx->bloom != NULL)
2033 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
2034 msg_ctx->bloom = NULL;
2042 #if STRICT_FORWARDING
2043 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2045 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2047 increment_stats("# find peer responses NOT forwarded (bloom match)");
2052 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2056 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2059 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2060 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2061 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2063 #if DEBUG_DHT_ROUTING
2064 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2066 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2068 GNUNET_YES, &my_identity, &msg_ctx->key,
2069 msg_ctx->peer, NULL);
2072 increment_stats(STAT_RESULTS_TO_CLIENT);
2073 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2074 increment_stats(STAT_GET_REPLY);
2076 send_reply_to_client(pos->client, msg,
2080 else /* Send to peer */
2082 peer_info = find_peer_by_id(&pos->source);
2083 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2089 if (msg_ctx->bloom == NULL)
2090 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2091 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
2092 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom, &peer_info->id.hashPubKey)))
2095 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2096 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2097 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&peer_info->id));
2099 #if DEBUG_DHT_ROUTING
2100 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2102 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id,
2105 GNUNET_NO, &my_identity, &msg_ctx->key,
2106 msg_ctx->peer, &pos->source);
2109 forward_result_message(msg, peer_info, msg_ctx);
2114 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2115 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2116 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&peer_info->id));
2122 if (msg_ctx->bloom != NULL)
2124 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
2125 msg_ctx->bloom = NULL;
2131 * Iterator for local get request results,
2133 * @param cls closure for iterator, a DatacacheGetContext
2134 * @param exp when does this value expire?
2135 * @param key the key this data is stored under
2136 * @param size the size of the data identified by key
2137 * @param data the actual data
2138 * @param type the type of the data
2140 * @return GNUNET_OK to continue iteration, anything else
2141 * to stop iteration.
2144 datacache_get_iterator (void *cls,
2145 struct GNUNET_TIME_Absolute exp,
2146 const GNUNET_HashCode * key,
2147 size_t size, const char *data,
2148 enum GNUNET_BLOCK_Type type)
2150 struct DHT_MessageContext *msg_ctx = cls;
2151 struct DHT_MessageContext *new_msg_ctx;
2152 struct GNUNET_DHT_GetResultMessage *get_result;
2153 enum GNUNET_BLOCK_EvaluationResult eval;
2156 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2157 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2159 eval = GNUNET_BLOCK_evaluate (block_context,
2163 msg_ctx->reply_bf_mutator,
2165 msg_ctx->xquery_size,
2170 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2171 msg_ctx->do_forward = GNUNET_NO;
2172 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2173 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2174 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2176 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2177 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2178 get_result->header.size =
2179 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2180 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2181 get_result->type = htons (type);
2182 memcpy (&get_result[1], data, size);
2183 new_msg_ctx->peer = &my_identity;
2184 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2185 new_msg_ctx->hop_count = 0;
2186 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
2187 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2188 increment_stats(STAT_GET_RESPONSE_START);
2189 route_result_message(&get_result->header, new_msg_ctx);
2190 GNUNET_free(new_msg_ctx);
2191 GNUNET_free (get_result);
2193 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2195 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2196 "`%s:%s': Duplicate block error\n", my_short_id, "DHT");
2199 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2201 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2202 "`%s:%s': Invalid request error\n", my_short_id, "DHT");
2205 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2208 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2212 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2213 GNUNET_break_op (0);
2214 msg_ctx->do_forward = GNUNET_NO;
2216 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2218 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2219 "`%s:%s': Unsupported block type (%u) in response!\n", my_short_id, "DHT", type);
2221 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2229 * Main function that handles whether or not to route a message to other
2232 * @param msg the message to be routed
2233 * @param msg_ctx the context containing all pertinent information about the message
2236 route_message(const struct GNUNET_MessageHeader *msg,
2237 struct DHT_MessageContext *msg_ctx);
2241 * Server handler for all dht get requests, look for data,
2242 * if found, send response either to clients or other peers.
2244 * @param msg the actual get message
2245 * @param msg_ctx struct containing pertinent information about the get request
2247 * @return number of items found for GET request
2250 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2251 struct DHT_MessageContext *msg_ctx)
2253 const struct GNUNET_DHT_GetMessage *get_msg;
2256 unsigned int results;
2258 enum GNUNET_BLOCK_Type type;
2260 msize = ntohs (msg->size);
2261 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2266 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2267 bf_size = ntohs (get_msg->bf_size);
2268 msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2269 msg_ctx->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2270 if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2275 end = (const char*) &get_msg[1];
2276 if (msg_ctx->xquery_size == 0)
2278 msg_ctx->xquery = NULL;
2282 msg_ctx->xquery = (const void*) end;
2283 end += msg_ctx->xquery_size;
2287 msg_ctx->reply_bf = NULL;
2291 msg_ctx->reply_bf = GNUNET_CONTAINER_bloomfilter_init (end,
2293 GNUNET_DHT_GET_BLOOMFILTER_K);
2295 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2297 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2298 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2302 GNUNET_h2s (&msg_ctx->key),
2303 msg_ctx->unique_id);
2305 increment_stats(STAT_GETS);
2308 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2310 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2314 msg_ctx->do_forward = GNUNET_YES;
2315 if (datacache != NULL)
2317 = GNUNET_DATACACHE_get (datacache,
2318 &msg_ctx->key, type,
2319 &datacache_get_iterator,
2322 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2323 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2324 results, "GET", msg_ctx->unique_id);
2328 #if DEBUG_DHT_ROUTING
2329 if ((debug_routes) && (dhtlog_handle != NULL))
2331 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2332 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2336 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2338 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2339 msg_ctx->hop_count, GNUNET_YES,
2340 &my_identity, &msg_ctx->key, msg_ctx->peer,
2347 /* check query valid */
2348 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID
2349 == GNUNET_BLOCK_evaluate (block_context,
2353 msg_ctx->reply_bf_mutator,
2355 msg_ctx->xquery_size,
2358 GNUNET_break_op (0);
2359 msg_ctx->do_forward = GNUNET_NO;
2363 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2365 #if DEBUG_DHT_ROUTING
2366 if ((debug_routes) && (dhtlog_handle != NULL))
2368 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2369 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2374 if (msg_ctx->do_forward == GNUNET_YES)
2375 route_message (msg, msg_ctx);
2376 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2381 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2383 GNUNET_HashCode *key = cls;
2385 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, NULL));
2390 * Server handler for initiating local dht find peer requests
2392 * @param find_msg the actual find peer message
2393 * @param msg_ctx struct containing pertinent information about the request
2397 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2398 struct DHT_MessageContext *msg_ctx)
2400 struct GNUNET_MessageHeader *find_peer_result;
2401 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2402 struct DHT_MessageContext *new_msg_ctx;
2403 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2406 GNUNET_HashCode *recent_hash;
2407 struct GNUNET_MessageHeader *other_hello;
2408 size_t other_hello_size;
2409 struct GNUNET_PeerIdentity peer_id;
2411 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2412 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2413 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2416 other_hello_size = 0;
2417 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2419 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2420 other_hello = GNUNET_malloc(other_hello_size);
2421 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2422 if ((GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)other_hello) == 0) || (GNUNET_OK != GNUNET_HELLO_get_id((struct GNUNET_HELLO_Message *)other_hello, &peer_id)))
2424 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2425 GNUNET_free(other_hello);
2428 #if FIND_PEER_WITH_HELLO
2429 if (GNUNET_YES == consider_peer(&peer_id))
2431 increment_stats(STAT_HELLOS_PROVIDED);
2432 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2433 GNUNET_CORE_peer_request_connect(coreAPI,
2434 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2435 route_message (find_msg, msg_ctx);
2436 GNUNET_free (other_hello);
2439 else /* We don't want this peer! */
2441 route_message (find_msg, msg_ctx);
2442 GNUNET_free (other_hello);
2449 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2450 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2451 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2452 ntohs (find_msg->size),
2453 sizeof (struct GNUNET_MessageHeader));
2455 if (my_hello == NULL)
2458 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2459 "`%s': Our HELLO is null, can't return.\n",
2462 GNUNET_free_non_null (other_hello);
2463 route_message (find_msg, msg_ctx);
2467 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2468 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2470 increment_stats(STAT_BLOOM_FIND_PEER);
2471 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2472 GNUNET_free_non_null(other_hello);
2473 route_message (find_msg, msg_ctx);
2474 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2476 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2478 #if RESTRICT_FIND_PEER
2481 * Ignore any find peer requests from a peer we have seen very recently.
2483 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! */
2485 increment_stats("# dht find peer requests ignored (recently seen!)");
2486 GNUNET_free_non_null(other_hello);
2491 * Use this check to only allow the peer to respond to find peer requests if
2492 * it would be beneficial to have the requesting peer in this peers routing
2493 * table. Can be used to thwart peers flooding the network with find peer
2494 * requests that we don't care about. However, if a new peer is joining
2495 * the network and has no other peers this is a problem (assume all buckets
2496 * full, no one will respond!).
2498 memcpy(&peer_id.hashPubKey, &msg_ctx->key, sizeof(GNUNET_HashCode));
2499 if (GNUNET_NO == consider_peer(&peer_id))
2501 increment_stats("# dht find peer requests ignored (do not need!)");
2502 GNUNET_free_non_null(other_hello);
2503 route_message (find_msg, msg_ctx);
2508 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2509 memcpy(recent_hash, &msg_ctx->key, sizeof(GNUNET_HashCode));
2510 if (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2511 &msg_ctx->key, NULL,
2512 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2514 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding recent remove task for key `%s`!\n", GNUNET_h2s(&msg_ctx->key));
2515 /* Only add a task if there wasn't one for this key already! */
2516 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30),
2517 &remove_recent_find_peer, recent_hash);
2521 GNUNET_free(recent_hash);
2522 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received duplicate find peer request too soon!\n");
2525 /* Simplistic find_peer functionality, always return our hello */
2526 hello_size = ntohs(my_hello->size);
2527 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2529 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2531 GNUNET_break_op (0);
2532 GNUNET_free_non_null(other_hello);
2536 find_peer_result = GNUNET_malloc (tsize);
2537 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2538 find_peer_result->size = htons (tsize);
2539 memcpy (&find_peer_result[1], my_hello, hello_size);
2541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2542 "`%s': Sending hello size %d to requesting peer.\n",
2545 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2546 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2547 new_msg_ctx->peer = &my_identity;
2548 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2549 new_msg_ctx->hop_count = 0;
2550 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make find peer requests a higher priority */
2551 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2552 increment_stats(STAT_FIND_PEER_ANSWER);
2553 route_result_message(find_peer_result, new_msg_ctx);
2554 GNUNET_free(new_msg_ctx);
2555 #if DEBUG_DHT_ROUTING
2556 if ((debug_routes) && (dhtlog_handle != NULL))
2558 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2559 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2563 GNUNET_free_non_null(other_hello);
2564 GNUNET_free(find_peer_result);
2565 route_message (find_msg, msg_ctx);
2569 * Task used to republish data.
2570 * Forward declaration; function call loop.
2572 * @param cls closure (a struct RepublishContext)
2573 * @param tc runtime context for this task
2576 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2579 * Server handler for initiating local dht put requests
2581 * @param msg the actual put message
2582 * @param msg_ctx struct containing pertinent information about the request
2585 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2586 struct DHT_MessageContext *msg_ctx)
2588 const struct GNUNET_DHT_PutMessage *put_msg;
2589 enum GNUNET_BLOCK_Type put_type;
2592 struct RepublishContext *put_context;
2593 GNUNET_HashCode key;
2595 GNUNET_assert (ntohs (msg->size) >=
2596 sizeof (struct GNUNET_DHT_PutMessage));
2599 put_msg = (const struct GNUNET_DHT_PutMessage *)msg;
2600 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2602 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2604 #if DEBUG_DHT_ROUTING
2605 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2607 /** Log routes that die due to high load! */
2608 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2609 msg_ctx->hop_count, GNUNET_SYSERR,
2610 &my_identity, &msg_ctx->key, msg_ctx->peer,
2617 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2618 ret = GNUNET_BLOCK_get_key (block_context,
2623 if (GNUNET_NO == ret)
2625 #if DEBUG_DHT_ROUTING
2626 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2628 /** Log routes that die due to high load! */
2629 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2630 msg_ctx->hop_count, GNUNET_SYSERR,
2631 &my_identity, &msg_ctx->key, msg_ctx->peer,
2636 GNUNET_break_op (0);
2639 if ( (GNUNET_YES == ret) &&
2642 sizeof (GNUNET_HashCode))) )
2644 #if DEBUG_DHT_ROUTING
2645 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2647 /** Log routes that die due to high load! */
2648 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2649 msg_ctx->hop_count, GNUNET_SYSERR,
2650 &my_identity, &msg_ctx->key, msg_ctx->peer,
2654 /* invalid wrapper: key mismatch! */
2655 GNUNET_break_op (0);
2658 /* ret == GNUNET_SYSERR means that there is no known relationship between
2659 data and the key, so we cannot check it */
2661 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2662 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2663 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2665 #if DEBUG_DHT_ROUTING
2666 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2668 if ((debug_routes) && (dhtlog_handle != NULL))
2670 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2671 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2677 if (msg_ctx->closest != GNUNET_YES)
2679 route_message (msg, msg_ctx);
2684 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2685 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2686 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2689 #if DEBUG_DHT_ROUTING
2690 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2692 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2693 msg_ctx->hop_count, GNUNET_YES,
2694 &my_identity, &msg_ctx->key, msg_ctx->peer,
2698 if ((debug_routes) && (dhtlog_handle != NULL))
2700 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2701 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2706 increment_stats(STAT_PUTS_INSERTED);
2707 if (datacache != NULL)
2709 ret = GNUNET_DATACACHE_put (datacache, &msg_ctx->key, data_size,
2710 (char *) &put_msg[1], put_type,
2711 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2713 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2715 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2716 memcpy(&put_context->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
2717 put_context->type = put_type;
2718 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content, put_context);
2722 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2723 "`%s:%s': %s request received, but have no datacache!\n",
2724 my_short_id, "DHT", "PUT");
2726 if (stop_on_closest == GNUNET_NO)
2727 route_message (msg, msg_ctx);
2731 * Estimate the diameter of the network based
2732 * on how many buckets are currently in use.
2733 * Concept here is that the diameter of the network
2734 * is roughly the distance a message must travel in
2735 * order to reach its intended destination. Since
2736 * at each hop we expect to get one bit closer, and
2737 * we have one bit per bucket, the number of buckets
2738 * in use should be the largest number of hops for
2739 * a successful message. (of course, this assumes we
2740 * know all peers in the network!)
2742 * @return ballpark diameter figure
2744 static unsigned int estimate_diameter()
2746 return MAX_BUCKETS - lowest_bucket;
2750 * To how many peers should we (on average)
2751 * forward the request to obtain the desired
2752 * target_replication count (on average).
2754 * returns: target_replication / (est. hops) + (target_replication * hop_count)
2755 * where est. hops is typically 2 * the routing table depth
2757 * @param hop_count number of hops the message has traversed
2758 * @param target_replication the number of total paths desired
2760 * @return Some number of peers to forward the message to
2763 get_forward_count (unsigned int hop_count, size_t target_replication)
2765 uint32_t random_value;
2766 unsigned int forward_count;
2768 unsigned int diameter;
2770 diameter = estimate_diameter ();
2772 if (GNUNET_NO == use_max_hops)
2773 max_hops = (diameter + 1) * 2;
2776 * If we are behaving in strict kademlia mode, send multiple initial requests,
2777 * but then only send to 1 or 0 peers based strictly on the number of hops.
2779 if (strict_kademlia == GNUNET_YES)
2782 return kademlia_replication;
2783 else if (hop_count < max_hops)
2789 /* FIXME: the smaller we think the network is the more lenient we should be for
2790 * routing right? The estimation below only works if we think we have reasonably
2791 * full routing tables, which for our RR topologies may not be the case!
2793 if (hop_count > max_hops)
2796 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2797 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2798 "DHT", estimate_diameter(), lowest_bucket);
2804 /* FIXME: we use diameter as the expected number of hops, but with randomized routing we will likely route to more! */
2805 target_value = target_replication / (diameter + ((float)target_replication * hop_count));
2806 if (target_value > 1)
2807 return (unsigned int)target_value;
2809 random_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int)-1);
2811 if (random_value < (target_value * (unsigned int)-1))
2816 return forward_count;
2820 * Check whether my identity is closer than any known peers.
2821 * If a non-null bloomfilter is given, check if this is the closest
2822 * peer that hasn't already been routed to.
2824 * @param target hash code to check closeness to
2825 * @param bloom bloomfilter, exclude these entries from the decision
2827 * Return GNUNET_YES if node location is closest, GNUNET_NO
2831 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2837 struct PeerInfo *pos;
2838 unsigned int my_distance;
2840 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2843 bucket_num = find_current_bucket(target);
2845 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2846 my_distance = distance(&my_identity.hashPubKey, target);
2847 pos = k_buckets[bucket_num].head;
2849 while ((pos != NULL) && (count < bucket_size))
2851 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2854 continue; /* Skip already checked entries */
2857 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2858 if (other_bits > bits)
2860 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2862 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2864 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2870 /* No peers closer, we are the closest! */
2876 * Return this peers adjusted value based on the convergence
2877 * function chosen. This is the key function for randomized
2878 * routing decisions.
2880 * @param target the key of the request
2881 * @param peer the peer we would like the value of
2882 * @param hops number of hops this message has already traveled
2884 * @return bit distance from target to peer raised to an exponent
2885 * adjusted based on the current routing convergence algorithm
2888 static unsigned long long
2889 converge_distance (const GNUNET_HashCode *target,
2890 struct PeerInfo *peer,
2893 unsigned long long ret;
2894 unsigned int other_matching_bits;
2895 double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
2896 double temp_modifier;
2902 curr_max_hops = max_hops;
2904 curr_max_hops = (estimate_diameter() + 1) * 2;
2906 if (converge_modifier > 0)
2907 temp_modifier = converge_modifier * base_converge_modifier;
2910 temp_modifier = base_converge_modifier;
2911 base_converge_modifier = 0.0;
2914 GNUNET_assert(temp_modifier > 0);
2916 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2918 switch (converge_option)
2920 case DHT_CONVERGE_RANDOM:
2921 return 1; /* Always return 1, choose equally among all peers */
2922 case DHT_CONVERGE_LINEAR:
2923 calc_value = hops * curr_max_hops * temp_modifier;
2925 case DHT_CONVERGE_SQUARE:
2927 * Simple square based curve.
2929 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * temp_modifier));
2931 case DHT_CONVERGE_EXPONENTIAL:
2933 * Simple exponential curve.
2935 if (base_converge_modifier > 0)
2936 calc_value = (temp_modifier * hops * hops) / curr_max_hops;
2938 calc_value = (hops * hops) / curr_max_hops;
2940 case DHT_CONVERGE_BINARY:
2942 * If below the cutoff, route randomly (return 1),
2943 * If above the cutoff, return the maximum possible
2944 * value first (always route to closest, because
2948 if (hops > converge_modifier) /* Past cutoff */
2957 /* Take the log (base e) of the number of bits matching the other peer */
2958 exponent = log(other_matching_bits);
2960 /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
2961 if (exponent * calc_value >= 44.361419555836498)
2964 /* Clear errno and all math exceptions */
2966 feclearexcept(FE_ALL_EXCEPT);
2967 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2968 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2971 if (0 != fetestexcept(FE_OVERFLOW))
2972 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2973 if (0 != fetestexcept(FE_INVALID))
2974 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2975 if (0 != fetestexcept(FE_UNDERFLOW))
2976 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2984 * Comparison function for two struct PeerInfo's
2985 * which have already had their matching bits to
2986 * some target calculated.
2988 * @param p1 a pointer pointer to a struct PeerInfo
2989 * @param p2 a pointer pointer to a struct PeerInfo
2991 * @return 0 if equidistant to target,
2992 * -1 if p1 is closer,
2996 compare_peers (const void *p1, const void *p2)
2998 struct PeerInfo **first = (struct PeerInfo **)p1;
2999 struct PeerInfo **second = (struct PeerInfo **)p2;
3001 if ((*first)->matching_bits > (*second)->matching_bits)
3003 if ((*first)->matching_bits < (*second)->matching_bits)
3011 * Select a peer from the routing table that would be a good routing
3012 * destination for sending a message for "target". The resulting peer
3013 * must not be in the set of blocked peers.<p>
3015 * Note that we should not ALWAYS select the closest peer to the
3016 * target, peers further away from the target should be chosen with
3017 * exponentially declining probability.
3019 * @param target the key we are selecting a peer to route to
3020 * @param bloom a bloomfilter containing entries this request has seen already
3022 * @return Peer to route to, or NULL on error
3024 static struct PeerInfo *
3025 select_peer (const GNUNET_HashCode * target,
3026 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3031 unsigned int offset;
3032 unsigned int my_matching_bits;
3034 struct PeerInfo *pos;
3035 struct PeerInfo *sorted_closest[bucket_size];
3036 unsigned long long temp_converge_distance;
3037 unsigned long long total_distance;
3038 unsigned long long selected;
3040 unsigned long long stats_total_distance;
3044 unsigned int distance;
3045 unsigned int largest_distance;
3046 struct PeerInfo *chosen;
3048 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
3051 if (strict_kademlia == GNUNET_YES)
3053 largest_distance = 0;
3055 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3057 pos = k_buckets[bc].head;
3059 while ((pos != NULL) && (count < bucket_size))
3061 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3062 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3064 distance = inverse_distance (target, &pos->id.hashPubKey);
3065 if (distance > largest_distance)
3068 largest_distance = distance;
3076 if ((largest_distance > 0) && (chosen != NULL))
3078 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
3089 /* Three steps: order peers in closest bucket (most matching bits).
3090 * Then go over all LOWER buckets (matching same bits we do)
3091 * Then go over all HIGHER buckets (matching less then we do)
3094 closest_bucket = find_current_bucket(target);
3095 GNUNET_assert(closest_bucket >= lowest_bucket);
3096 pos = k_buckets[closest_bucket].head;
3098 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3099 memset(sorted_closest, 0, sizeof(sorted_closest));
3100 /* Put any peers in the closest bucket in the sorting array */
3101 while ((pos != NULL) && (count < bucket_size))
3103 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3107 continue; /* Ignore bloomfiltered peers */
3109 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
3110 sorted_closest[offset] = pos;
3116 /* Sort the peers in descending order */
3117 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
3119 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3120 for (i = 0; i < offset; i++)
3122 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3123 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3124 break; /* Ignore bloomfiltered peers */
3125 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3126 total_distance += temp_converge_distance;
3128 break; /* overflow case */
3131 /* Now handle peers in lower buckets (matches same # of bits as target) */
3132 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3134 pos = k_buckets[bc].head;
3136 while ((pos != NULL) && (count < bucket_size))
3138 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3142 continue; /* Ignore bloomfiltered peers */
3144 temp_converge_distance = converge_distance(target, pos, hops);
3145 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3146 total_distance += temp_converge_distance;
3148 break; /* overflow case */
3154 /* Now handle all the further away peers */
3155 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3157 pos = k_buckets[bc].head;
3159 while ((pos != NULL) && (count < bucket_size))
3161 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3165 continue; /* Ignore bloomfiltered peers */
3167 temp_converge_distance = converge_distance(target, pos, hops);
3168 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3169 total_distance += temp_converge_distance;
3171 break; /* overflow case */
3177 if (total_distance == 0) /* No peers to select from! */
3179 increment_stats("# select_peer, total_distance == 0");
3183 #if DEBUG_DHT_ROUTING > 1
3186 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3187 stats_total_distance = 0;
3188 for (i = 0; i < offset; i++)
3190 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3191 break; /* Ignore bloomfiltered peers */
3192 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3193 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3194 stats_total_distance += temp_converge_distance;
3196 break; /* overflow case */
3197 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);
3200 /* Now handle peers in lower buckets (matches same # of bits as target) */
3201 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3203 pos = k_buckets[bc].head;
3205 while ((pos != NULL) && (count < bucket_size))
3207 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3211 continue; /* Ignore bloomfiltered peers */
3213 temp_converge_distance = converge_distance(target, pos, hops);
3214 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3215 stats_total_distance += temp_converge_distance;
3217 break; /* overflow case */
3218 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);
3224 /* Now handle all the further away peers */
3225 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3227 pos = k_buckets[bc].head;
3229 while ((pos != NULL) && (count < bucket_size))
3231 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3235 continue; /* Ignore bloomfiltered peers */
3237 temp_converge_distance = converge_distance(target, pos, hops);
3238 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3239 stats_total_distance += temp_converge_distance;
3241 break; /* overflow case */
3242 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);
3247 /* END PRINT STATS */
3250 /* Now actually choose a peer */
3251 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3253 /* Go over closest sorted peers. */
3254 for (i = 0; i < offset; i++)
3256 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3257 break; /* Ignore bloomfiltered peers */
3258 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3259 if (temp_converge_distance >= selected)
3260 return sorted_closest[i];
3262 selected -= temp_converge_distance;
3265 /* Now handle peers in lower buckets (matches same # of bits as target) */
3266 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3268 pos = k_buckets[bc].head;
3270 while ((pos != NULL) && (count < bucket_size))
3272 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3276 continue; /* Ignore bloomfiltered peers */
3278 temp_converge_distance = converge_distance(target, pos, hops);
3279 if (temp_converge_distance >= selected)
3282 selected -= temp_converge_distance;
3288 /* Now handle all the further away peers */
3289 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3291 pos = k_buckets[bc].head;
3293 while ((pos != NULL) && (count < bucket_size))
3295 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3299 continue; /* Ignore bloomfiltered peers */
3301 temp_converge_distance = converge_distance(target, pos, hops);
3302 if (temp_converge_distance >= selected)
3305 selected -= temp_converge_distance;
3311 increment_stats("# failed to select peer");
3317 * Task used to remove recent entries, either
3318 * after timeout, when full, or on shutdown.
3320 * @param cls the entry to remove
3321 * @param tc context, reason, etc.
3324 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3326 struct RecentRequest *req = cls;
3327 static GNUNET_HashCode hash;
3329 GNUNET_assert(req != NULL);
3330 hash_from_uid(req->uid, &hash);
3331 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3332 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3333 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3337 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3339 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3340 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3347 * Task used to remove forwarding entries, either
3348 * after timeout, when full, or on shutdown.
3350 * @param cls the entry to remove
3351 * @param tc context, reason, etc.
3354 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3356 struct DHTRouteSource *source_info = cls;
3357 struct DHTQueryRecord *record;
3358 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3359 record = source_info->record;
3360 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3362 if (record->head == NULL) /* No more entries in DLL */
3364 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap, &record->key, record));
3365 GNUNET_free(record);
3367 if (source_info->find_peers_responded != NULL)
3368 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3369 GNUNET_free(source_info);
3373 * Remember this routing request so that if a reply is
3374 * received we can either forward it to the correct peer
3375 * or return the result locally.
3377 * @param msg_ctx Context of the route request
3379 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3381 static int cache_response(struct DHT_MessageContext *msg_ctx)
3383 struct DHTQueryRecord *record;
3384 struct DHTRouteSource *source_info;
3385 struct DHTRouteSource *pos;
3386 struct GNUNET_TIME_Absolute now;
3387 unsigned int current_size;
3389 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3391 #if DELETE_WHEN_FULL
3392 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3394 source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3395 GNUNET_assert(source_info != NULL);
3396 record = source_info->record;
3397 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3398 if (record->head == NULL) /* No more entries in DLL */
3400 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3401 GNUNET_free(record);
3403 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3404 GNUNET_SCHEDULER_cancel(source_info->delete_task);
3405 if (source_info->find_peers_responded != NULL)
3406 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3407 GNUNET_free(source_info);
3408 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3411 /** Non-local request and have too many outstanding forwards, discard! */
3412 if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3415 now = GNUNET_TIME_absolute_get();
3416 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3417 if (record != NULL) /* Already know this request! */
3422 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3423 break; /* Already have this peer in reply list! */
3426 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3428 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.abs_value);
3434 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3435 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3436 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3439 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3440 source_info->record = record;
3441 source_info->delete_task = GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3442 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3443 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3444 GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail, source_info);
3445 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3447 source_info->client = msg_ctx->client;
3448 now = GNUNET_TIME_absolute_get_forever();
3450 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.abs_value);
3452 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3453 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3454 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3461 * Main function that handles whether or not to route a message to other
3464 * @param msg the message to be routed
3465 * @param msg_ctx the context containing all pertinent information about the message
3468 route_message(const struct GNUNET_MessageHeader *msg,
3469 struct DHT_MessageContext *msg_ctx)
3472 struct PeerInfo *selected;
3473 #if DEBUG_DHT_ROUTING > 1
3474 struct PeerInfo *nearest;
3476 unsigned int target_forward_count;
3477 unsigned int forward_count;
3478 struct RecentRequest *recent_req;
3479 GNUNET_HashCode unique_hash;
3480 char *stat_forward_count;
3481 char *temp_stat_str;
3482 #if DEBUG_DHT_ROUTING
3486 if (malicious_dropper == GNUNET_YES)
3488 #if DEBUG_DHT_ROUTING
3489 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3491 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3492 msg_ctx->hop_count, GNUNET_SYSERR,
3493 &my_identity, &msg_ctx->key, msg_ctx->peer,
3497 if (msg_ctx->bloom != NULL)
3499 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3500 msg_ctx->bloom = NULL;
3505 increment_stats(STAT_ROUTES);
3506 target_forward_count = get_forward_count(msg_ctx->hop_count, msg_ctx->replication);
3507 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", target_forward_count);
3508 increment_stats(stat_forward_count);
3509 GNUNET_free(stat_forward_count);
3510 if (msg_ctx->bloom == NULL)
3511 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3513 if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3514 target_forward_count = 0;
3517 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3518 * any closer peers (which is being checked for below). Since we are doing recursive
3519 * routing we have no choice but to stop forwarding in this case. This means that at
3520 * any given step the request may NOT be forwarded to alpha peers (because routes will
3521 * stop and the parallel route will not be aware of it). Of course, assuming that we
3522 * have fulfilled the Kademlia requirements for routing table fullness this will never
3523 * ever ever be a problem.
3525 * However, is this fair?
3527 * Since we use these requests to build our routing tables (and we build them in the
3528 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3529 * routing tables still get constructed.
3531 if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) && (msg_ctx->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3532 target_forward_count = 0;
3535 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3536 hash_from_uid (msg_ctx->unique_id, &unique_hash);
3537 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3539 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3540 GNUNET_assert(recent_req != NULL);
3541 if (0 != memcmp(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode)))
3542 increment_stats(STAT_DUPLICATE_UID);
3545 increment_stats(STAT_RECENT_SEEN);
3546 GNUNET_CONTAINER_bloomfilter_or2(msg_ctx->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3551 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3552 recent_req->uid = msg_ctx->unique_id;
3553 memcpy(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3554 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3555 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().abs_value);
3556 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3557 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3560 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3562 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3563 GNUNET_assert(recent_req != NULL);
3564 GNUNET_SCHEDULER_cancel(recent_req->remove_task);
3565 GNUNET_SCHEDULER_add_now(&remove_recent, recent_req);
3569 for (i = 0; i < target_forward_count; i++)
3571 selected = select_peer(&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3573 if (selected != NULL)
3576 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &msg_ctx->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &msg_ctx->key))
3577 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", msg_ctx->hop_count);
3579 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", msg_ctx->hop_count);
3580 if (temp_stat_str != NULL)
3582 increment_stats(temp_stat_str);
3583 GNUNET_free(temp_stat_str);
3585 GNUNET_CONTAINER_bloomfilter_add(msg_ctx->bloom, &selected->id.hashPubKey);
3586 #if DEBUG_DHT_ROUTING > 1
3587 nearest = find_closest_peer(&msg_ctx->key);
3588 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3590 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3591 "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));
3592 GNUNET_free(nearest_buf);
3594 #if DEBUG_DHT_ROUTING
3595 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3597 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3598 msg_ctx->hop_count, GNUNET_NO,
3599 &my_identity, &msg_ctx->key, msg_ctx->peer,
3603 forward_message(msg, selected, msg_ctx);
3607 if (msg_ctx->bloom != NULL)
3609 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, msg_ctx->bloom, DHT_BLOOM_SIZE);
3610 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3611 msg_ctx->bloom = NULL;
3614 #if DEBUG_DHT_ROUTING
3615 if (forward_count == 0)
3616 ret = GNUNET_SYSERR;
3620 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3622 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3623 msg_ctx->hop_count, ret,
3624 &my_identity, &msg_ctx->key, msg_ctx->peer,
3633 * Main function that handles whether or not to route a message to other
3636 * @param msg the message to be routed
3637 * @param msg_ctx the context containing all pertinent information about the message
3640 demultiplex_message(const struct GNUNET_MessageHeader *msg,
3641 struct DHT_MessageContext *msg_ctx)
3643 msg_ctx->closest = am_closest_peer(&msg_ctx->key, NULL);
3644 switch (ntohs(msg->type))
3646 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3647 cache_response (msg_ctx);
3648 handle_dht_get (msg, msg_ctx);
3650 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3651 increment_stats(STAT_PUTS);
3652 handle_dht_put (msg, msg_ctx);
3654 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3655 increment_stats(STAT_FIND_PEER);
3656 if (((msg_ctx->hop_count > 0) && (0 != memcmp(msg_ctx->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (msg_ctx->client != NULL))
3658 cache_response (msg_ctx);
3659 if ((msg_ctx->closest == GNUNET_YES) || (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3660 handle_dht_find_peer (msg, msg_ctx);
3663 route_message (msg, msg_ctx);
3664 #if DEBUG_DHT_ROUTING
3665 if (msg_ctx->hop_count == 0) /* Locally initiated request */
3667 if ((debug_routes) && (dhtlog_handle != NULL))
3669 dhtlog_handle->insert_dhtkey(NULL, &msg_ctx->key);
3670 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
3671 msg_ctx->hop_count, GNUNET_NO, &my_identity,
3678 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3679 "`%s': Message type (%d) not handled, forwarding anyway!\n", "DHT", ntohs(msg->type));
3680 route_message (msg, msg_ctx);
3688 * Iterator for local get request results,
3690 * @param cls closure for iterator, NULL
3691 * @param exp when does this value expire?
3692 * @param key the key this data is stored under
3693 * @param size the size of the data identified by key
3694 * @param data the actual data
3695 * @param type the type of the data
3697 * @return GNUNET_OK to continue iteration, anything else
3698 * to stop iteration.
3701 republish_content_iterator (void *cls,
3702 struct GNUNET_TIME_Absolute exp,
3703 const GNUNET_HashCode * key,
3704 size_t size, const char *data, uint32_t type)
3707 struct DHT_MessageContext *new_msg_ctx;
3708 struct GNUNET_DHT_PutMessage *put_msg;
3710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3711 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3713 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3716 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3717 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3718 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3719 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3720 put_msg->type = htons (type);
3721 memcpy (&put_msg[1], data, size);
3722 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3723 new_msg_ctx->replication = ntohl (DEFAULT_PUT_REPLICATION);
3724 new_msg_ctx->msg_options = ntohl (0);
3725 new_msg_ctx->network_size = estimate_diameter();
3726 new_msg_ctx->peer = &my_identity;
3727 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3728 new_msg_ctx->hop_count = 0;
3729 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3730 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3731 increment_stats(STAT_PUT_START);
3732 demultiplex_message(&put_msg->header, new_msg_ctx);
3734 GNUNET_free(new_msg_ctx);
3735 GNUNET_free (put_msg);
3740 * Task used to republish data.
3742 * @param cls closure (a struct RepublishContext)
3743 * @param tc runtime context for this task
3746 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3748 struct RepublishContext *put_context = cls;
3750 unsigned int results;
3752 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3754 GNUNET_free(put_context);
3758 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3759 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3760 if (results == 0) /* Data must have expired */
3761 GNUNET_free(put_context);
3762 else /* Reschedule task for next time period */
3763 GNUNET_SCHEDULER_add_delayed(dht_republish_frequency, &republish_content, put_context);
3769 * Iterator over hash map entries.
3771 * @param cls client to search for in source routes
3772 * @param key current key code (ignored)
3773 * @param value value in the hash map, a DHTQueryRecord
3774 * @return GNUNET_YES if we should continue to
3778 static int find_client_records (void *cls,
3779 const GNUNET_HashCode * key, void *value)
3781 struct ClientList *client = cls;
3782 struct DHTQueryRecord *record = value;
3783 struct DHTRouteSource *pos;
3787 if (pos->client == client)
3793 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3794 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3795 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3796 GNUNET_SCHEDULER_cancel(pos->delete_task);
3798 if (pos->find_peers_responded != NULL)
3799 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3802 if (record->head == NULL) /* No more entries in DLL */
3804 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3805 GNUNET_free(record);
3811 * Functions with this signature are called whenever a client
3812 * is disconnected on the network level.
3814 * @param cls closure (NULL for dht)
3815 * @param client identification of the client; NULL
3816 * for the last call when the server is destroyed
3818 static void handle_client_disconnect (void *cls,
3819 struct GNUNET_SERVER_Client* client)
3821 struct ClientList *pos = client_list;
3822 struct ClientList *prev;
3823 struct ClientList *found;
3824 struct PendingMessage *reply;
3830 if (pos->client_handle == client)
3833 prev->next = pos->next;
3835 client_list = pos->next;
3845 if (found->transmit_handle != NULL)
3846 GNUNET_CONNECTION_notify_transmit_ready_cancel(found->transmit_handle);
3848 while(NULL != (reply = found->pending_head))
3850 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3853 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3859 * Find a client if it exists, add it otherwise.
3861 * @param client the server handle to the client
3863 * @return the client if found, a new client otherwise
3865 static struct ClientList *
3866 find_active_client (struct GNUNET_SERVER_Client *client)
3868 struct ClientList *pos = client_list;
3869 struct ClientList *ret;
3873 if (pos->client_handle == client)
3878 ret = GNUNET_malloc (sizeof (struct ClientList));
3879 ret->client_handle = client;
3880 ret->next = client_list;
3888 * Task to send a malicious put message across the network.
3890 * @param cls closure for this task
3891 * @param tc the context under which the task is running
3894 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3896 static struct GNUNET_DHT_PutMessage put_message;
3897 static struct DHT_MessageContext msg_ctx;
3898 static GNUNET_HashCode key;
3899 uint32_t random_key;
3901 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3903 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3904 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3905 put_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3906 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3907 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3908 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3909 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3910 memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3911 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3912 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3913 msg_ctx.msg_options = ntohl (0);
3914 msg_ctx.network_size = estimate_diameter();
3915 msg_ctx.peer = &my_identity;
3916 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3917 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3918 #if DEBUG_DHT_ROUTING
3919 if (dhtlog_handle != NULL)
3920 dhtlog_handle->insert_dhtkey(NULL, &key);
3922 increment_stats(STAT_PUT_START);
3923 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3924 demultiplex_message(&put_message.header, &msg_ctx);
3925 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3930 * Task to send a malicious put message across the network.
3932 * @param cls closure for this task
3933 * @param tc the context under which the task is running
3936 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3938 static struct GNUNET_DHT_GetMessage get_message;
3939 struct DHT_MessageContext msg_ctx;
3940 static GNUNET_HashCode key;
3941 uint32_t random_key;
3943 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3946 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3947 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3948 get_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3949 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3950 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3951 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3952 memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3953 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3954 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3955 msg_ctx.msg_options = ntohl (0);
3956 msg_ctx.network_size = estimate_diameter();
3957 msg_ctx.peer = &my_identity;
3958 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3959 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3960 #if DEBUG_DHT_ROUTING
3961 if (dhtlog_handle != NULL)
3962 dhtlog_handle->insert_dhtkey(NULL, &key);
3964 increment_stats(STAT_GET_START);
3965 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3966 demultiplex_message (&get_message.header, &msg_ctx);
3967 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3973 * Iterator over hash map entries.
3975 * @param cls closure
3976 * @param key current key code
3977 * @param value value in the hash map
3978 * @return GNUNET_YES if we should continue to
3983 add_known_to_bloom (void *cls,
3984 const GNUNET_HashCode * key,
3987 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3988 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3993 * Task to send a find peer message for our own peer identifier
3994 * so that we can find the closest peers in the network to ourselves
3995 * and attempt to connect to them.
3997 * @param cls closure for this task
3998 * @param tc the context under which the task is running
4001 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4003 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
4004 struct DHT_MessageContext msg_ctx;
4005 struct GNUNET_TIME_Relative next_send_time;
4006 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
4008 struct GNUNET_TIME_Relative time_diff;
4009 struct GNUNET_TIME_Absolute end;
4011 double count_per_interval;
4013 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
4016 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! */
4018 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
4019 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
4020 &send_find_peer_message, NULL);
4021 newly_found_peers = 0;
4025 increment_stats(STAT_FIND_PEER_START);
4027 end = GNUNET_TIME_absolute_get();
4028 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
4030 if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
4032 multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
4033 count_per_interval = find_peer_context.count / multiplier;
4037 multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
4038 count_per_interval = find_peer_context.count * multiplier;
4042 #if FIND_PEER_WITH_HELLO
4043 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4044 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4045 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4047 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
4048 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
4050 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4051 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4052 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
4053 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
4054 GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
4055 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4056 memcpy(&msg_ctx.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
4057 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
4058 msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4059 msg_ctx.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4060 msg_ctx.network_size = estimate_diameter();
4061 msg_ctx.peer = &my_identity;
4062 msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4063 msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4065 demultiplex_message(&find_peer_msg->header, &msg_ctx);
4066 GNUNET_free(find_peer_msg);
4067 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4068 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
4070 if (newly_found_peers < bucket_size)
4072 next_send_time.rel_value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4073 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4074 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4078 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4079 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4080 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4083 GNUNET_assert (next_send_time.rel_value != 0);
4084 find_peer_context.count = 0;
4085 newly_found_peers = 0;
4086 find_peer_context.start = GNUNET_TIME_absolute_get();
4087 if (GNUNET_YES == do_find_peer)
4089 GNUNET_SCHEDULER_add_delayed (next_send_time,
4090 &send_find_peer_message, NULL);
4095 * Handler for any generic DHT messages, calls the appropriate handler
4096 * depending on message type, sends confirmation if responses aren't otherwise
4099 * @param cls closure for the service
4100 * @param client the client we received this message from
4101 * @param message the actual message received
4104 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4105 const struct GNUNET_MessageHeader *message)
4107 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
4108 const struct GNUNET_MessageHeader *enc_msg;
4109 struct DHT_MessageContext msg_ctx;
4111 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4113 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4114 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4118 ntohs (message->type),
4119 GNUNET_h2s (&dht_msg->key),
4120 GNUNET_ntohll (dht_msg->unique_id));
4122 #if DEBUG_DHT_ROUTING
4123 if (dhtlog_handle != NULL)
4124 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4126 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4127 msg_ctx.client = find_active_client (client);
4128 memcpy(&msg_ctx.key, &dht_msg->key, sizeof(GNUNET_HashCode));
4129 msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4130 msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
4131 msg_ctx.msg_options = ntohl (dht_msg->options);
4132 msg_ctx.network_size = estimate_diameter();
4133 msg_ctx.peer = &my_identity;
4134 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
4135 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4136 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4137 increment_stats(STAT_GET_START);
4138 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4139 increment_stats(STAT_PUT_START);
4140 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4141 increment_stats(STAT_FIND_PEER_START);
4143 demultiplex_message(enc_msg, &msg_ctx);
4145 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4150 * Handler for any locally received DHT control messages,
4151 * sets malicious flags mostly for now.
4153 * @param cls closure for the service
4154 * @param client the client we received this message from
4155 * @param message the actual message received
4159 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4160 const struct GNUNET_MessageHeader *message)
4162 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4163 (const struct GNUNET_DHT_ControlMessage *) message;
4165 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4166 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4167 "CONTROL", ntohs(dht_control_msg->command));
4170 switch (ntohs(dht_control_msg->command))
4172 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4173 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4174 GNUNET_SCHEDULER_add_now(&send_find_peer_message, NULL);
4177 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4178 if (ntohs(dht_control_msg->variable) > 0)
4179 malicious_get_frequency = ntohs(dht_control_msg->variable);
4180 if (malicious_get_frequency == 0)
4181 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4182 if (malicious_getter != GNUNET_YES)
4183 GNUNET_SCHEDULER_add_now(&malicious_get_task, NULL);
4184 malicious_getter = GNUNET_YES;
4185 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4186 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4188 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4189 if (ntohs(dht_control_msg->variable) > 0)
4190 malicious_put_frequency = ntohs(dht_control_msg->variable);
4191 if (malicious_put_frequency == 0)
4192 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4193 if (malicious_putter != GNUNET_YES)
4194 GNUNET_SCHEDULER_add_now(&malicious_put_task, NULL);
4195 malicious_putter = GNUNET_YES;
4196 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4197 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4199 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4200 #if DEBUG_DHT_ROUTING
4201 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4202 dhtlog_handle->set_malicious(&my_identity);
4204 malicious_dropper = GNUNET_YES;
4205 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4206 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4210 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4211 "%s:%s Unknown control command type `%d'!\n",
4213 ntohs(dht_control_msg->command));
4217 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4221 * Handler for any generic DHT stop messages, calls the appropriate handler
4222 * depending on message type (if processed locally)
4224 * @param cls closure for the service
4225 * @param client the client we received this message from
4226 * @param message the actual message received
4230 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4231 const struct GNUNET_MessageHeader *message)
4234 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4235 (const struct GNUNET_DHT_StopMessage *) message;
4236 struct DHTQueryRecord *record;
4237 struct DHTRouteSource *pos;
4239 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4240 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4241 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4243 record = GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &dht_stop_msg->key);
4250 /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
4251 if ((pos->client != NULL) && (pos->client->client_handle == client))
4253 GNUNET_SCHEDULER_cancel(pos->delete_task);
4254 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4255 GNUNET_SCHEDULER_add_continuation (&remove_forward_entry, pos, GNUNET_SCHEDULER_REASON_PREREQ_DONE);
4261 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4266 * Core handler for p2p route requests.
4269 handle_dht_p2p_route_request (void *cls,
4270 const struct GNUNET_PeerIdentity *peer,
4271 const struct GNUNET_MessageHeader *message,
4272 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4276 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4278 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4279 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4280 struct DHT_MessageContext *msg_ctx;
4282 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4285 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4290 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4296 if (get_max_send_delay().rel_value > MAX_REQUEST_TIME.rel_value)
4298 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending of previous replies took too long, backing off!\n");
4299 increment_stats("# route requests dropped due to high load");
4300 decrease_max_send_delay(get_max_send_delay());
4301 #if DEBUG_DHT_ROUTING
4302 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4304 /** Log routes that die due to high load! */
4305 dhtlog_handle->insert_route (NULL, GNUNET_ntohll(incoming->unique_id), DHTLOG_ROUTE,
4306 ntohl(incoming->hop_count), GNUNET_SYSERR,
4307 &my_identity, &incoming->key, peer,
4313 msg_ctx = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4314 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4315 GNUNET_assert(msg_ctx->bloom != NULL);
4316 msg_ctx->hop_count = ntohl(incoming->hop_count);
4317 memcpy(&msg_ctx->key, &incoming->key, sizeof(GNUNET_HashCode));
4318 msg_ctx->replication = ntohl(incoming->desired_replication_level);
4319 msg_ctx->unique_id = GNUNET_ntohll(incoming->unique_id);
4320 msg_ctx->msg_options = ntohl(incoming->options);
4321 msg_ctx->network_size = ntohl(incoming->network_size);
4322 msg_ctx->peer = peer;
4323 msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4324 msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4325 demultiplex_message (enc_msg, msg_ctx);
4326 if (msg_ctx->bloom != NULL)
4328 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4329 msg_ctx->bloom = NULL;
4331 GNUNET_free(msg_ctx);
4337 * Core handler for p2p route results.
4340 handle_dht_p2p_route_result (void *cls,
4341 const struct GNUNET_PeerIdentity *peer,
4342 const struct GNUNET_MessageHeader *message,
4343 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4346 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4347 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4349 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4350 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4351 struct DHT_MessageContext msg_ctx;
4353 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4359 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4360 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4361 msg_ctx.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4362 GNUNET_assert(msg_ctx.bloom != NULL);
4363 memcpy(&msg_ctx.key, &incoming->key, sizeof(GNUNET_HashCode));
4364 msg_ctx.unique_id = GNUNET_ntohll(incoming->unique_id);
4365 msg_ctx.msg_options = ntohl(incoming->options);
4366 msg_ctx.hop_count = ntohl(incoming->hop_count);
4367 msg_ctx.peer = peer;
4368 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4369 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4370 route_result_message(enc_msg, &msg_ctx);
4376 * Receive the HELLO from transport service,
4377 * free current and replace if necessary.
4380 * @param message HELLO message of peer
4383 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4387 "Received our `%s' from transport service\n",
4391 GNUNET_assert (message != NULL);
4392 GNUNET_free_non_null(my_hello);
4393 my_hello = GNUNET_malloc(ntohs(message->size));
4394 memcpy(my_hello, message, ntohs(message->size));
4399 * Task run during shutdown.
4405 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4408 struct PeerInfo *pos;
4410 if (transport_handle != NULL)
4412 GNUNET_free_non_null(my_hello);
4413 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4414 GNUNET_TRANSPORT_disconnect(transport_handle);
4416 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4418 while (k_buckets[bucket_count].head != NULL)
4420 pos = k_buckets[bucket_count].head;
4422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4423 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4425 delete_peer(pos, bucket_count);
4428 if (coreAPI != NULL)
4431 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4432 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4434 GNUNET_CORE_disconnect (coreAPI);
4437 if (datacache != NULL)
4440 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4441 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4443 GNUNET_DATACACHE_destroy (datacache);
4448 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4451 if (dhtlog_handle != NULL)
4453 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4454 dhtlog_handle = NULL;
4456 if (block_context != NULL)
4458 GNUNET_BLOCK_context_destroy (block_context);
4459 block_context = NULL;
4461 GNUNET_free_non_null(my_short_id);
4467 * To be called on core init/fail.
4469 * @param cls service closure
4470 * @param server handle to the server for this service
4471 * @param identity the public identity of this peer
4472 * @param publicKey the public key of this peer
4475 core_init (void *cls,
4476 struct GNUNET_CORE_Handle *server,
4477 const struct GNUNET_PeerIdentity *identity,
4478 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4485 "%s: Connection to core FAILED!\n", "dht",
4486 GNUNET_i2s (identity));
4488 GNUNET_SCHEDULER_cancel (cleanup_task);
4489 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4494 "%s: Core connection initialized, I am peer: %s\n", "dht",
4495 GNUNET_i2s (identity));
4498 /* Copy our identity so we can use it */
4499 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4500 if (my_short_id != NULL)
4501 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4502 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4503 /* Set the server to local variable */
4506 if (dhtlog_handle != NULL)
4507 dhtlog_handle->insert_node (NULL, &my_identity);
4511 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4512 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4513 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4514 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4519 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4520 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4521 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4527 * Method called whenever a peer connects.
4529 * @param cls closure
4530 * @param peer peer identity this notification is about
4531 * @param atsi performance data
4534 handle_core_connect (void *cls,
4535 const struct GNUNET_PeerIdentity * peer,
4536 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4538 struct PeerInfo *ret;
4541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4542 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4545 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4547 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));
4551 if (datacache != NULL)
4552 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, GNUNET_BLOCK_TYPE_DHT_HELLO, GNUNET_TIME_absolute_get_forever());
4553 ret = try_add_peer(peer,
4554 find_current_bucket(&peer->hashPubKey),
4558 newly_found_peers++;
4559 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4563 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4569 * Method called whenever a peer disconnects.
4571 * @param cls closure
4572 * @param peer peer identity this notification is about
4575 handle_core_disconnect (void *cls,
4577 GNUNET_PeerIdentity * peer)
4579 struct PeerInfo *to_remove;
4582 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");
4584 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4586 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));
4589 increment_stats(STAT_DISCONNECTS);
4590 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4591 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4592 GNUNET_assert (to_remove != NULL);
4593 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4594 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4595 delete_peer(to_remove, current_bucket);
4600 * Process dht requests.
4602 * @param cls closure
4603 * @param server the initialized server
4604 * @param c configuration to use
4608 struct GNUNET_SERVER_Handle *server,
4609 const struct GNUNET_CONFIGURATION_Handle *c)
4611 struct GNUNET_TIME_Relative next_send_time;
4612 unsigned long long temp_config_num;
4613 char *converge_modifier_buf;
4616 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4617 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4618 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4619 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
4620 DEFAULT_CORE_QUEUE_SIZE, /* queue size */
4621 NULL, /* Closure passed to DHT functions */
4622 &core_init, /* Call core_init once connected */
4623 &handle_core_connect, /* Handle connects */
4624 &handle_core_disconnect, /* remove peers on disconnects */
4625 NULL, /* Do we care about "status" updates? */
4626 NULL, /* Don't want notified about all incoming messages */
4627 GNUNET_NO, /* For header only inbound notification */
4628 NULL, /* Don't want notified about all outbound messages */
4629 GNUNET_NO, /* For header only outbound notification */
4630 core_handlers); /* Register these handlers */
4632 if (coreAPI == NULL)
4634 transport_handle = GNUNET_TRANSPORT_connect(cfg,
4635 NULL, NULL, NULL, NULL, NULL);
4636 if (transport_handle != NULL)
4637 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4639 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4640 "Failed to connect to transport service!\n");
4641 block_context = GNUNET_BLOCK_context_create (cfg);
4642 lowest_bucket = MAX_BUCKETS - 1;
4643 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4644 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4645 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4646 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4647 GNUNET_assert(all_known_peers != NULL);
4648 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4650 debug_routes = GNUNET_YES;
4654 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4657 strict_kademlia = GNUNET_YES;
4661 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4664 stop_on_closest = GNUNET_YES;
4668 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4671 stop_on_found = GNUNET_YES;
4675 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4676 "malicious_getter"))
4678 malicious_getter = GNUNET_YES;
4679 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4680 "MALICIOUS_GET_FREQUENCY",
4681 &malicious_get_frequency))
4682 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4685 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4689 max_hops = DEFAULT_MAX_HOPS;
4692 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4695 use_max_hops = GNUNET_YES;
4699 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4700 "malicious_putter"))
4702 malicious_putter = GNUNET_YES;
4703 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4704 "MALICIOUS_PUT_FREQUENCY",
4705 &malicious_put_frequency))
4706 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4709 dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
4710 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4712 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4715 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "bucket_size", &temp_config_num))
4717 bucket_size = (unsigned int)temp_config_num;
4720 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "kad_alpha", &kademlia_replication))
4722 kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
4726 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4727 "malicious_dropper"))
4729 malicious_dropper = GNUNET_YES;
4733 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4735 do_republish = GNUNET_NO;
4738 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4741 do_find_peer = GNUNET_NO;
4744 do_find_peer = GNUNET_YES;
4747 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4748 "use_real_distance"))
4749 use_real_distance = GNUNET_YES;
4752 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4753 "mysql_logging_extended"))
4755 debug_routes = GNUNET_YES;
4756 debug_routes_extended = GNUNET_YES;
4759 #if DEBUG_DHT_ROUTING
4760 if (GNUNET_YES == debug_routes)
4762 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4763 if (dhtlog_handle == NULL)
4765 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4766 "Could not connect to mysql logging server, logging will not happen!");
4771 converge_option = DHT_CONVERGE_SQUARE;
4773 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4776 converge_option = DHT_CONVERGE_LINEAR;
4778 else if (GNUNET_YES ==
4779 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4780 "converge_exponential"))
4782 converge_option = DHT_CONVERGE_EXPONENTIAL;
4784 else if (GNUNET_YES ==
4785 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4788 converge_option = DHT_CONVERGE_RANDOM;
4790 else if (GNUNET_YES ==
4791 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4794 converge_option = DHT_CONVERGE_BINARY;
4797 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht", "converge_modifier", &converge_modifier_buf))
4799 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4801 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4802 converge_modifier = 0.0;
4804 GNUNET_free(converge_modifier_buf);
4807 stats = GNUNET_STATISTICS_create("dht", cfg);
4811 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4812 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4813 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4814 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4815 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4816 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4817 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4818 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4819 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4820 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4821 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4822 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4823 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4824 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4825 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4826 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4827 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4828 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4829 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4830 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4832 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4833 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4834 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4835 if (GNUNET_YES == do_find_peer)
4837 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4838 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4839 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4840 find_peer_context.start = GNUNET_TIME_absolute_get();
4841 GNUNET_SCHEDULER_add_delayed (next_send_time,
4842 &send_find_peer_message, &find_peer_context);
4845 /* Scheduled the task to clean up when shutdown is called */
4846 cleanup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4847 &shutdown_task, NULL);
4851 * The main function for the dht service.
4853 * @param argc number of arguments from the command line
4854 * @param argv command line arguments
4855 * @return 0 ok, 1 on error
4858 main (int argc, char *const *argv)
4863 GNUNET_SERVICE_run (argc,
4866 GNUNET_SERVICE_OPTION_NONE,
4867 &run, NULL)) ? 0 : 1;
4868 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap));
4869 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap));
4870 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4871 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4872 GNUNET_CONTAINER_heap_destroy (recent.minHeap);