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);
1055 if (peer->th == NULL)
1056 increment_stats("# notify transmit ready failed");
1061 * Function called to send a request out to another peer.
1062 * Called both for locally initiated requests and those
1063 * received from other peers.
1065 * @param msg the encapsulated message
1066 * @param peer the peer to forward the message to
1067 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1070 forward_result_message (const struct GNUNET_MessageHeader *msg,
1071 struct PeerInfo *peer,
1072 struct DHT_MessageContext *msg_ctx)
1074 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1075 struct P2PPendingMessage *pending;
1079 increment_stats(STAT_RESULT_FORWARDS);
1080 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1081 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1082 psize = sizeof(struct P2PPendingMessage) + msize;
1083 pending = GNUNET_malloc(psize);
1084 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1085 pending->importance = DHT_SEND_PRIORITY;
1086 pending->timeout = GNUNET_TIME_relative_get_forever();
1087 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1088 result_message->header.size = htons(msize);
1089 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1090 result_message->put_path_length = htons(0); /* FIXME: implement */
1091 result_message->get_path_length = htons(0); /* FIXME: implement */
1092 result_message->options = htonl(msg_ctx->msg_options);
1093 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1094 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1095 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1096 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1097 memcpy(&result_message[1], msg, ntohs(msg->size));
1099 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));
1101 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1102 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1103 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1108 * Called when core is ready to send a message we asked for
1109 * out to the destination.
1111 * @param cls closure (NULL)
1112 * @param size number of bytes available in buf
1113 * @param buf where the callee should write the message
1114 * @return number of bytes written to buf
1117 core_transmit_notify (void *cls,
1118 size_t size, void *buf)
1120 struct PeerInfo *peer = cls;
1122 struct P2PPendingMessage *pending;
1129 /* client disconnected */
1131 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1136 if (peer->head == NULL)
1140 pending = peer->head;
1141 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1142 msize = ntohs(pending->msg->size);
1146 memcpy (cbuf, pending->msg, msize);
1147 GNUNET_CONTAINER_DLL_remove (peer->head,
1151 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));
1153 GNUNET_free (pending);
1156 while (NULL != pending &&
1157 (size - off >= (msize = ntohs (pending->msg->size))))
1159 #if DEBUG_DHT_ROUTING
1160 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);
1162 memcpy (&cbuf[off], pending->msg, msize);
1164 GNUNET_CONTAINER_DLL_remove (peer->head,
1167 GNUNET_free (pending);
1168 pending = peer->head;
1171 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1172 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1174 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);
1181 * Compute the distance between have and target as a 32-bit value.
1182 * Differences in the lower bits must count stronger than differences
1183 * in the higher bits.
1185 * @return 0 if have==target, otherwise a number
1186 * that is larger as the distance between
1187 * the two hash codes increases
1190 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1192 unsigned int bucket;
1197 /* We have to represent the distance between two 2^9 (=512)-bit
1198 numbers as a 2^5 (=32)-bit number with "0" being used for the
1199 two numbers being identical; furthermore, we need to
1200 guarantee that a difference in the number of matching
1201 bits is always represented in the result.
1203 We use 2^32/2^9 numerical values to distinguish between
1204 hash codes that have the same LSB bit distance and
1205 use the highest 2^9 bits of the result to signify the
1206 number of (mis)matching LSB bits; if we have 0 matching
1207 and hence 512 mismatching LSB bits we return -1 (since
1208 512 itself cannot be represented with 9 bits) */
1210 /* first, calculate the most significant 9 bits of our
1211 result, aka the number of LSBs */
1212 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1213 /* bucket is now a value between 0 and 512 */
1215 return 0; /* perfect match */
1217 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1218 below, we'd end up with max+1 (overflow)) */
1220 /* calculate the most significant bits of the final result */
1221 msb = (512 - bucket) << (32 - 9);
1222 /* calculate the 32-9 least significant bits of the final result by
1223 looking at the differences in the 32-9 bits following the
1224 mismatching bit at 'bucket' */
1226 for (i = bucket + 1;
1227 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1229 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1230 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1231 last bit set will be 31 -- if
1232 i does not reach 512 first... */
1238 * Return a number that is larger the closer the
1239 * "have" GNUNET_hash code is to the "target".
1241 * @return inverse distance metric, non-zero.
1242 * Must fudge the value if NO bits match.
1245 inverse_distance (const GNUNET_HashCode * target,
1246 const GNUNET_HashCode * have)
1248 if (GNUNET_CRYPTO_hash_matching_bits(target, have) == 0)
1249 return 1; /* Never return 0! */
1250 return ((unsigned int) -1) - distance (target, have);
1254 * Find the optimal bucket for this key, regardless
1255 * of the current number of buckets in use.
1257 * @param hc the hashcode to compare our identity to
1259 * @return the proper bucket index, or GNUNET_SYSERR
1260 * on error (same hashcode)
1262 static int find_bucket(const GNUNET_HashCode *hc)
1266 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, hc);
1267 if (bits == MAX_BUCKETS)
1268 return GNUNET_SYSERR;
1269 return MAX_BUCKETS - bits - 1;
1273 * Find which k-bucket this peer should go into,
1274 * taking into account the size of the k-bucket
1275 * array. This means that if more bits match than
1276 * there are currently buckets, lowest_bucket will
1279 * @param hc GNUNET_HashCode we are finding the bucket for.
1281 * @return the proper bucket index for this key,
1282 * or GNUNET_SYSERR on error (same hashcode)
1284 static int find_current_bucket(const GNUNET_HashCode *hc)
1287 actual_bucket = find_bucket(hc);
1289 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1290 return lowest_bucket;
1291 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1292 return lowest_bucket;
1294 return actual_bucket;
1299 * Find a routing table entry from a peer identity
1301 * @param peer the peer to look up
1303 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1306 find_bucket_by_peer(const struct PeerInfo *peer)
1309 struct PeerInfo *pos;
1311 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1313 pos = k_buckets[bucket].head;
1322 return GNUNET_SYSERR; /* No such peer. */
1328 * Print the complete routing table for this peer.
1331 print_routing_table ()
1334 struct PeerInfo *pos;
1335 char char_buf[30000];
1337 memset(char_buf, 0, sizeof(char_buf));
1339 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1340 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1341 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1343 pos = k_buckets[bucket].head;
1344 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1345 //fprintf(stderr, "Bucket %d:\n", bucket);
1348 //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));
1349 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));
1353 fprintf(stderr, "%s", char_buf);
1359 * Find a routing table entry from a peer identity
1361 * @param peer the peer identity to look up
1363 * @return the routing table entry, or NULL if not found
1365 static struct PeerInfo *
1366 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1369 struct PeerInfo *pos;
1370 bucket = find_current_bucket(&peer->hashPubKey);
1372 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1375 pos = k_buckets[bucket].head;
1378 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1382 return NULL; /* No such peer. */
1385 /* Forward declaration */
1387 update_core_preference (void *cls,
1388 const struct GNUNET_SCHEDULER_TaskContext *tc);
1390 * Function called with statistics about the given peer.
1392 * @param cls closure
1393 * @param peer identifies the peer
1394 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1395 * @param amount set to the amount that was actually reserved or unreserved;
1396 * either the full requested amount or zero (no partial reservations)
1397 * @param preference current traffic preference for the given peer
1400 update_core_preference_finish (void *cls,
1401 const struct GNUNET_PeerIdentity * peer,
1402 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1403 int amount, uint64_t preference)
1405 struct PeerInfo *peer_info = cls;
1406 peer_info->info_ctx = NULL;
1407 GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1411 update_core_preference (void *cls,
1412 const struct GNUNET_SCHEDULER_TaskContext *tc)
1414 struct PeerInfo *peer = cls;
1415 uint64_t preference;
1416 unsigned int matching;
1417 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1421 matching = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1424 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching);
1427 preference = 1LL << matching;
1428 peer->info_ctx = GNUNET_CORE_peer_change_preference (coreAPI,
1430 GNUNET_TIME_relative_get_forever(),
1431 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1434 &update_core_preference_finish,
1439 * Really add a peer to a bucket (only do assertions
1442 * @param peer GNUNET_PeerIdentity of the peer to add
1443 * @param bucket the already figured out bucket to add
1445 * @param atsi performance information
1447 * @return the newly added PeerInfo
1449 static struct PeerInfo *
1450 add_peer(const struct GNUNET_PeerIdentity *peer,
1451 unsigned int bucket,
1452 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1454 struct PeerInfo *new_peer;
1455 GNUNET_assert(bucket < MAX_BUCKETS);
1456 GNUNET_assert(peer != NULL);
1457 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1459 new_peer->latency = latency;
1460 new_peer->distance = distance;
1463 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1465 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1466 k_buckets[bucket].tail,
1467 k_buckets[bucket].tail,
1469 k_buckets[bucket].peers_size++;
1471 if ((GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1473 #if DO_UPDATE_PREFERENCE
1474 new_peer->preference_task = GNUNET_SCHEDULER_add_now(&update_core_preference, new_peer);
1482 * Given a peer and its corresponding bucket,
1483 * remove it from that bucket. Does not free
1484 * the PeerInfo struct, nor cancel messages
1485 * or free messages waiting to be sent to this
1488 * @param peer the peer to remove
1489 * @param bucket the bucket the peer belongs to
1491 static void remove_peer (struct PeerInfo *peer,
1492 unsigned int bucket)
1494 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1495 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1496 k_buckets[bucket].tail,
1498 k_buckets[bucket].peers_size--;
1500 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1506 * Removes peer from a bucket, then frees associated
1507 * resources and frees peer.
1509 * @param peer peer to be removed and freed
1510 * @param bucket which bucket this peer belongs to
1512 static void delete_peer (struct PeerInfo *peer,
1513 unsigned int bucket)
1515 struct P2PPendingMessage *pos;
1516 struct P2PPendingMessage *next;
1518 struct PeerInfo *peer_pos;
1520 peer_pos = k_buckets[bucket].head;
1521 while ((peer_pos != NULL) && (peer_pos != peer))
1522 peer_pos = peer_pos->next;
1523 if (peer_pos == NULL)
1525 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1526 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));
1528 GNUNET_assert(peer_pos != NULL);
1530 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1532 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1533 GNUNET_SCHEDULER_cancel(peer->send_task);
1534 if ((peer->th != NULL) && (coreAPI != NULL))
1535 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1538 while (pos != NULL) /* Remove any pending messages for this peer */
1545 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1546 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer));
1552 * Iterator over hash map entries.
1554 * @param cls closure
1555 * @param key current key code
1556 * @param value PeerInfo of the peer to move to new lowest bucket
1557 * @return GNUNET_YES if we should continue to
1561 static int move_lowest_bucket (void *cls,
1562 const GNUNET_HashCode * key,
1565 struct PeerInfo *peer = value;
1568 GNUNET_assert(lowest_bucket > 0);
1569 new_bucket = lowest_bucket - 1;
1570 remove_peer(peer, lowest_bucket);
1571 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1572 k_buckets[new_bucket].tail,
1573 k_buckets[new_bucket].tail,
1575 k_buckets[new_bucket].peers_size++;
1581 * The current lowest bucket is full, so change the lowest
1582 * bucket to the next lower down, and move any appropriate
1583 * entries in the current lowest bucket to the new bucket.
1585 static void enable_next_bucket()
1587 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1588 struct PeerInfo *pos;
1589 GNUNET_assert(lowest_bucket > 0);
1590 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1591 pos = k_buckets[lowest_bucket].head;
1594 fprintf(stderr, "Printing RT before new bucket\n");
1595 print_routing_table();
1597 /* Populate the array of peers which should be in the next lowest bucket */
1600 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1601 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1605 /* Remove peers from lowest bucket, insert into next lowest bucket */
1606 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1607 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1608 lowest_bucket = lowest_bucket - 1;
1610 fprintf(stderr, "Printing RT after new bucket\n");
1611 print_routing_table();
1616 * Find the closest peer in our routing table to the
1619 * @return The closest peer in our routing table to the
1620 * key, or NULL on error.
1622 static struct PeerInfo *
1623 find_closest_peer (const GNUNET_HashCode *hc)
1625 struct PeerInfo *pos;
1626 struct PeerInfo *current_closest;
1627 unsigned int lowest_distance;
1628 unsigned int temp_distance;
1632 lowest_distance = -1;
1634 if (k_buckets[lowest_bucket].peers_size == 0)
1637 current_closest = NULL;
1638 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1640 pos = k_buckets[bucket].head;
1642 while ((pos != NULL) && (count < bucket_size))
1644 temp_distance = distance(&pos->id.hashPubKey, hc);
1645 if (temp_distance <= lowest_distance)
1647 lowest_distance = temp_distance;
1648 current_closest = pos;
1654 GNUNET_assert(current_closest != NULL);
1655 return current_closest;
1660 * Function called to send a request out to another peer.
1661 * Called both for locally initiated requests and those
1662 * received from other peers.
1664 * @param msg the encapsulated message
1665 * @param peer the peer to forward the message to
1666 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1668 static void forward_message (const struct GNUNET_MessageHeader *msg,
1669 struct PeerInfo *peer,
1670 struct DHT_MessageContext *msg_ctx)
1672 struct GNUNET_DHT_P2PRouteMessage *route_message;
1673 struct P2PPendingMessage *pending;
1677 increment_stats(STAT_ROUTE_FORWARDS);
1678 GNUNET_assert(peer != NULL);
1679 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1680 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1682 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1683 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1684 psize = sizeof(struct P2PPendingMessage) + msize;
1685 pending = GNUNET_malloc(psize);
1686 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1687 pending->importance = msg_ctx->importance;
1688 pending->timeout = msg_ctx->timeout;
1689 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1690 route_message->header.size = htons(msize);
1691 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1692 route_message->options = htonl(msg_ctx->msg_options);
1693 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1694 route_message->network_size = htonl(msg_ctx->network_size);
1695 route_message->desired_replication_level = htonl(msg_ctx->replication);
1696 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1697 if (msg_ctx->bloom != NULL)
1698 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1699 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1700 memcpy(&route_message[1], msg, ntohs(msg->size));
1702 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));
1704 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1705 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1706 peer->send_task = GNUNET_SCHEDULER_add_now(&try_core_send, peer);
1711 * Task used to send ping messages to peers so that
1712 * they don't get disconnected.
1714 * @param cls the peer to send a ping message to
1715 * @param tc context, reason, etc.
1718 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1720 struct PeerInfo *peer = cls;
1721 struct GNUNET_MessageHeader ping_message;
1722 struct DHT_MessageContext msg_ctx;
1724 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1727 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1728 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1730 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
1732 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1734 forward_message(&ping_message, peer, &msg_ctx);
1735 peer->ping_task = GNUNET_SCHEDULER_add_delayed(DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1739 * Schedule PING messages for the top X peers in each
1740 * bucket of the routing table (so core won't disconnect them!)
1742 void schedule_ping_messages()
1744 unsigned int bucket;
1746 struct PeerInfo *pos;
1747 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1749 pos = k_buckets[bucket].head;
1753 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1754 GNUNET_SCHEDULER_add_now(&periodic_ping_task, pos);
1755 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1757 GNUNET_SCHEDULER_cancel(pos->ping_task);
1758 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1768 * Attempt to add a peer to our k-buckets.
1770 * @param peer the peer identity of the peer being added
1771 * @param bucket the bucket that we want this peer to go in
1772 * @param latency transport latency of this peer
1773 * @param distance transport distance to this peer
1775 * @return NULL if the peer was not added,
1776 * pointer to PeerInfo for new peer otherwise
1778 static struct PeerInfo *
1779 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1780 unsigned int bucket,
1781 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1784 struct PeerInfo *new_peer;
1786 if (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity)))
1789 peer_bucket = find_current_bucket(&peer->hashPubKey);
1791 GNUNET_assert(peer_bucket >= lowest_bucket);
1792 new_peer = add_peer(peer, peer_bucket, atsi);
1794 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1795 enable_next_bucket();
1797 schedule_ping_messages();
1804 * Task run to check for messages that need to be sent to a client.
1806 * @param client a ClientList, containing the client and any messages to be sent to it
1809 process_pending_messages (struct ClientList *client)
1811 if (client->pending_head == NULL)
1813 if (client->transmit_handle != NULL)
1816 client->transmit_handle =
1817 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1818 ntohs (client->pending_head->msg->
1820 GNUNET_TIME_UNIT_FOREVER_REL,
1821 &send_generic_reply, client);
1825 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1826 * request. A ClientList is passed as closure, take the head of the list
1827 * and copy it into buf, which has the result of sending the message to the
1830 * @param cls closure to this call
1831 * @param size maximum number of bytes available to send
1832 * @param buf where to copy the actual message to
1834 * @return the number of bytes actually copied, 0 indicates failure
1837 send_generic_reply (void *cls, size_t size, void *buf)
1839 struct ClientList *client = cls;
1841 struct PendingMessage *reply;
1845 client->transmit_handle = NULL;
1848 /* client disconnected */
1852 while ( (NULL != (reply = client->pending_head)) &&
1853 (size >= off + (msize = ntohs (reply->msg->size))))
1855 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1856 client->pending_tail,
1858 memcpy (&cbuf[off], reply->msg, msize);
1859 GNUNET_free (reply);
1862 process_pending_messages (client);
1864 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1865 "Transmitted %u bytes of replies to client\n",
1866 (unsigned int) off);
1873 * Add a PendingMessage to the clients list of messages to be sent
1875 * @param client the active client to send the message to
1876 * @param pending_message the actual message to send
1879 add_pending_message (struct ClientList *client,
1880 struct PendingMessage *pending_message)
1882 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1883 client->pending_tail,
1884 client->pending_tail,
1886 process_pending_messages (client);
1891 * Called when a reply needs to be sent to a client, as
1892 * a result it found to a GET or FIND PEER request.
1894 * @param client the client to send the reply to
1895 * @param message the encapsulated message to send
1896 * @param uid the unique identifier of this request
1899 send_reply_to_client (struct ClientList *client,
1900 const struct GNUNET_MessageHeader *message,
1901 unsigned long long uid,
1902 const GNUNET_HashCode *key)
1904 struct GNUNET_DHT_RouteResultMessage *reply;
1905 struct PendingMessage *pending_message;
1909 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1910 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1912 msize = ntohs (message->size);
1913 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1914 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1916 GNUNET_break_op (0);
1919 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1920 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1921 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1922 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1923 reply->header.size = htons (tsize);
1924 reply->put_path_length = htons(0); /* FIXME: implement */
1925 reply->get_path_length = htons(0); /* FIXME: implement */
1926 reply->unique_id = GNUNET_htonll (uid);
1928 memcpy (&reply[1], message, msize);
1929 add_pending_message (client, pending_message);
1933 * Consider whether or not we would like to have this peer added to
1934 * our routing table. Check whether bucket for this peer is full,
1935 * if so return negative; if not return positive. Since peers are
1936 * only added on CORE level connect, this doesn't actually add the
1937 * peer to the routing table.
1939 * @param peer the peer we are considering adding
1941 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1944 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1948 if ((GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey)) || (0 == memcmp(&my_identity, peer, sizeof(struct GNUNET_PeerIdentity))))
1949 return GNUNET_NO; /* We already know this peer (are connected even!) */
1950 bucket = find_current_bucket(&peer->hashPubKey);
1952 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1959 * Main function that handles whether or not to route a result
1960 * message to other peers, or to send to our local client.
1962 * @param msg the result message to be routed
1963 * @param msg_ctx context of the message we are routing
1965 * @return the number of peers the message was routed to,
1966 * GNUNET_SYSERR on failure
1968 static int route_result_message(struct GNUNET_MessageHeader *msg,
1969 struct DHT_MessageContext *msg_ctx)
1971 struct GNUNET_PeerIdentity new_peer;
1972 struct DHTQueryRecord *record;
1973 struct DHTRouteSource *pos;
1974 struct PeerInfo *peer_info;
1975 const struct GNUNET_MessageHeader *hello_msg;
1977 increment_stats(STAT_RESULTS);
1979 * If a find peer result message is received and contains a valid
1980 * HELLO for another peer, offer it to the transport service.
1982 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1984 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1987 hello_msg = &msg[1];
1988 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1990 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1994 else /* We have a valid hello, and peer id stored in new_peer */
1996 find_peer_context.count++;
1997 increment_stats(STAT_FIND_PEER_REPLY);
1998 if (GNUNET_YES == consider_peer(&new_peer))
2000 increment_stats(STAT_HELLOS_PROVIDED);
2001 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
2002 GNUNET_CORE_peer_request_connect(coreAPI,
2003 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
2008 if (malicious_dropper == GNUNET_YES)
2011 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2013 if (record == NULL) /* No record of this message! */
2016 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2017 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
2018 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2020 #if DEBUG_DHT_ROUTING
2021 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2023 dhtlog_handle->insert_route (NULL,
2030 msg_ctx->peer, NULL);
2033 if (msg_ctx->bloom != NULL)
2035 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
2036 msg_ctx->bloom = NULL;
2044 #if STRICT_FORWARDING
2045 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2047 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2049 increment_stats("# find peer responses NOT forwarded (bloom match)");
2054 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2058 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2061 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2062 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2063 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2065 #if DEBUG_DHT_ROUTING
2066 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2068 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2070 GNUNET_YES, &my_identity, &msg_ctx->key,
2071 msg_ctx->peer, NULL);
2074 increment_stats(STAT_RESULTS_TO_CLIENT);
2075 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2076 increment_stats(STAT_GET_REPLY);
2078 send_reply_to_client(pos->client, msg,
2082 else /* Send to peer */
2084 peer_info = find_peer_by_id(&pos->source);
2085 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2091 if (msg_ctx->bloom == NULL)
2092 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2093 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
2094 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom, &peer_info->id.hashPubKey)))
2097 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2098 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2099 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&peer_info->id));
2101 #if DEBUG_DHT_ROUTING
2102 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2104 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id,
2107 GNUNET_NO, &my_identity, &msg_ctx->key,
2108 msg_ctx->peer, &pos->source);
2111 forward_result_message(msg, peer_info, msg_ctx);
2116 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2117 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2118 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id, GNUNET_i2s(&peer_info->id));
2124 if (msg_ctx->bloom != NULL)
2126 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
2127 msg_ctx->bloom = NULL;
2133 * Iterator for local get request results,
2135 * @param cls closure for iterator, a DatacacheGetContext
2136 * @param exp when does this value expire?
2137 * @param key the key this data is stored under
2138 * @param size the size of the data identified by key
2139 * @param data the actual data
2140 * @param type the type of the data
2142 * @return GNUNET_OK to continue iteration, anything else
2143 * to stop iteration.
2146 datacache_get_iterator (void *cls,
2147 struct GNUNET_TIME_Absolute exp,
2148 const GNUNET_HashCode * key,
2149 size_t size, const char *data,
2150 enum GNUNET_BLOCK_Type type)
2152 struct DHT_MessageContext *msg_ctx = cls;
2153 struct DHT_MessageContext *new_msg_ctx;
2154 struct GNUNET_DHT_GetResultMessage *get_result;
2155 enum GNUNET_BLOCK_EvaluationResult eval;
2158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2159 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2161 eval = GNUNET_BLOCK_evaluate (block_context,
2165 msg_ctx->reply_bf_mutator,
2167 msg_ctx->xquery_size,
2172 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2173 msg_ctx->do_forward = GNUNET_NO;
2174 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2175 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2176 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2178 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2179 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2180 get_result->header.size =
2181 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2182 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2183 get_result->type = htons (type);
2184 memcpy (&get_result[1], data, size);
2185 new_msg_ctx->peer = &my_identity;
2186 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2187 new_msg_ctx->hop_count = 0;
2188 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
2189 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2190 increment_stats(STAT_GET_RESPONSE_START);
2191 route_result_message(&get_result->header, new_msg_ctx);
2192 GNUNET_free(new_msg_ctx);
2193 GNUNET_free (get_result);
2195 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2197 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2198 "`%s:%s': Duplicate block error\n", my_short_id, "DHT");
2201 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2204 "`%s:%s': Invalid request error\n", my_short_id, "DHT");
2207 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2209 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2210 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2214 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2215 GNUNET_break_op (0);
2216 msg_ctx->do_forward = GNUNET_NO;
2218 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2220 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2221 "`%s:%s': Unsupported block type (%u) in response!\n", my_short_id, "DHT", type);
2223 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2231 * Main function that handles whether or not to route a message to other
2234 * @param msg the message to be routed
2235 * @param msg_ctx the context containing all pertinent information about the message
2238 route_message(const struct GNUNET_MessageHeader *msg,
2239 struct DHT_MessageContext *msg_ctx);
2243 * Server handler for all dht get requests, look for data,
2244 * if found, send response either to clients or other peers.
2246 * @param msg the actual get message
2247 * @param msg_ctx struct containing pertinent information about the get request
2249 * @return number of items found for GET request
2252 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2253 struct DHT_MessageContext *msg_ctx)
2255 const struct GNUNET_DHT_GetMessage *get_msg;
2258 unsigned int results;
2260 enum GNUNET_BLOCK_Type type;
2262 msize = ntohs (msg->size);
2263 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2268 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2269 bf_size = ntohs (get_msg->bf_size);
2270 msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2271 msg_ctx->reply_bf_mutator = get_msg->bf_mutator; /* FIXME: ntohl? */
2272 if (msize != sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2277 end = (const char*) &get_msg[1];
2278 if (msg_ctx->xquery_size == 0)
2280 msg_ctx->xquery = NULL;
2284 msg_ctx->xquery = (const void*) end;
2285 end += msg_ctx->xquery_size;
2289 msg_ctx->reply_bf = NULL;
2293 msg_ctx->reply_bf = GNUNET_CONTAINER_bloomfilter_init (end,
2295 GNUNET_DHT_GET_BLOOMFILTER_K);
2297 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2299 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2300 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2304 GNUNET_h2s (&msg_ctx->key),
2305 msg_ctx->unique_id);
2307 increment_stats(STAT_GETS);
2310 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2312 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2316 msg_ctx->do_forward = GNUNET_YES;
2317 if (datacache != NULL)
2319 = GNUNET_DATACACHE_get (datacache,
2320 &msg_ctx->key, type,
2321 &datacache_get_iterator,
2324 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2325 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2326 results, "GET", msg_ctx->unique_id);
2330 #if DEBUG_DHT_ROUTING
2331 if ((debug_routes) && (dhtlog_handle != NULL))
2333 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2334 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2338 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2340 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2341 msg_ctx->hop_count, GNUNET_YES,
2342 &my_identity, &msg_ctx->key, msg_ctx->peer,
2349 /* check query valid */
2350 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID
2351 == GNUNET_BLOCK_evaluate (block_context,
2355 msg_ctx->reply_bf_mutator,
2357 msg_ctx->xquery_size,
2360 GNUNET_break_op (0);
2361 msg_ctx->do_forward = GNUNET_NO;
2365 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2367 #if DEBUG_DHT_ROUTING
2368 if ((debug_routes) && (dhtlog_handle != NULL))
2370 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2371 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2376 if (msg_ctx->do_forward == GNUNET_YES)
2377 route_message (msg, msg_ctx);
2378 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2383 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2385 GNUNET_HashCode *key = cls;
2387 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, NULL));
2392 * Server handler for initiating local dht find peer requests
2394 * @param find_msg the actual find peer message
2395 * @param msg_ctx struct containing pertinent information about the request
2399 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2400 struct DHT_MessageContext *msg_ctx)
2402 struct GNUNET_MessageHeader *find_peer_result;
2403 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2404 struct DHT_MessageContext *new_msg_ctx;
2405 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2408 GNUNET_HashCode *recent_hash;
2409 struct GNUNET_MessageHeader *other_hello;
2410 size_t other_hello_size;
2411 struct GNUNET_PeerIdentity peer_id;
2413 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2414 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2415 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2418 other_hello_size = 0;
2419 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2421 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2422 other_hello = GNUNET_malloc(other_hello_size);
2423 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2424 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)))
2426 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2427 GNUNET_free(other_hello);
2430 #if FIND_PEER_WITH_HELLO
2431 if (GNUNET_YES == consider_peer(&peer_id))
2433 increment_stats(STAT_HELLOS_PROVIDED);
2434 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2435 GNUNET_CORE_peer_request_connect(coreAPI,
2436 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2437 route_message (find_msg, msg_ctx);
2438 GNUNET_free (other_hello);
2441 else /* We don't want this peer! */
2443 route_message (find_msg, msg_ctx);
2444 GNUNET_free (other_hello);
2451 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2452 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2453 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2454 ntohs (find_msg->size),
2455 sizeof (struct GNUNET_MessageHeader));
2457 if (my_hello == NULL)
2460 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2461 "`%s': Our HELLO is null, can't return.\n",
2464 GNUNET_free_non_null (other_hello);
2465 route_message (find_msg, msg_ctx);
2469 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2470 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2472 increment_stats(STAT_BLOOM_FIND_PEER);
2473 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2474 GNUNET_free_non_null(other_hello);
2475 route_message (find_msg, msg_ctx);
2476 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2478 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2480 #if RESTRICT_FIND_PEER
2483 * Ignore any find peer requests from a peer we have seen very recently.
2485 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! */
2487 increment_stats("# dht find peer requests ignored (recently seen!)");
2488 GNUNET_free_non_null(other_hello);
2493 * Use this check to only allow the peer to respond to find peer requests if
2494 * it would be beneficial to have the requesting peer in this peers routing
2495 * table. Can be used to thwart peers flooding the network with find peer
2496 * requests that we don't care about. However, if a new peer is joining
2497 * the network and has no other peers this is a problem (assume all buckets
2498 * full, no one will respond!).
2500 memcpy(&peer_id.hashPubKey, &msg_ctx->key, sizeof(GNUNET_HashCode));
2501 if (GNUNET_NO == consider_peer(&peer_id))
2503 increment_stats("# dht find peer requests ignored (do not need!)");
2504 GNUNET_free_non_null(other_hello);
2505 route_message (find_msg, msg_ctx);
2510 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2511 memcpy(recent_hash, &msg_ctx->key, sizeof(GNUNET_HashCode));
2512 if (GNUNET_SYSERR != GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2513 &msg_ctx->key, NULL,
2514 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2516 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Adding recent remove task for key `%s`!\n", GNUNET_h2s(&msg_ctx->key));
2517 /* Only add a task if there wasn't one for this key already! */
2518 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30),
2519 &remove_recent_find_peer, recent_hash);
2523 GNUNET_free(recent_hash);
2524 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Received duplicate find peer request too soon!\n");
2527 /* Simplistic find_peer functionality, always return our hello */
2528 hello_size = ntohs(my_hello->size);
2529 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2531 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2533 GNUNET_break_op (0);
2534 GNUNET_free_non_null(other_hello);
2538 find_peer_result = GNUNET_malloc (tsize);
2539 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2540 find_peer_result->size = htons (tsize);
2541 memcpy (&find_peer_result[1], my_hello, hello_size);
2543 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2544 "`%s': Sending hello size %d to requesting peer.\n",
2547 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2548 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2549 new_msg_ctx->peer = &my_identity;
2550 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2551 new_msg_ctx->hop_count = 0;
2552 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make find peer requests a higher priority */
2553 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2554 increment_stats(STAT_FIND_PEER_ANSWER);
2555 route_result_message(find_peer_result, new_msg_ctx);
2556 GNUNET_free(new_msg_ctx);
2557 #if DEBUG_DHT_ROUTING
2558 if ((debug_routes) && (dhtlog_handle != NULL))
2560 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2561 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2565 GNUNET_free_non_null(other_hello);
2566 GNUNET_free(find_peer_result);
2567 route_message (find_msg, msg_ctx);
2571 * Task used to republish data.
2572 * Forward declaration; function call loop.
2574 * @param cls closure (a struct RepublishContext)
2575 * @param tc runtime context for this task
2578 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2581 * Server handler for initiating local dht put requests
2583 * @param msg the actual put message
2584 * @param msg_ctx struct containing pertinent information about the request
2587 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2588 struct DHT_MessageContext *msg_ctx)
2590 const struct GNUNET_DHT_PutMessage *put_msg;
2591 enum GNUNET_BLOCK_Type put_type;
2594 struct RepublishContext *put_context;
2595 GNUNET_HashCode key;
2597 GNUNET_assert (ntohs (msg->size) >=
2598 sizeof (struct GNUNET_DHT_PutMessage));
2601 put_msg = (const struct GNUNET_DHT_PutMessage *)msg;
2602 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2604 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2606 #if DEBUG_DHT_ROUTING
2607 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2609 /** Log routes that die due to high load! */
2610 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2611 msg_ctx->hop_count, GNUNET_SYSERR,
2612 &my_identity, &msg_ctx->key, msg_ctx->peer,
2619 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2620 ret = GNUNET_BLOCK_get_key (block_context,
2625 if (GNUNET_NO == ret)
2627 #if DEBUG_DHT_ROUTING
2628 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2630 /** Log routes that die due to high load! */
2631 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2632 msg_ctx->hop_count, GNUNET_SYSERR,
2633 &my_identity, &msg_ctx->key, msg_ctx->peer,
2638 GNUNET_break_op (0);
2641 if ( (GNUNET_YES == ret) &&
2644 sizeof (GNUNET_HashCode))) )
2646 #if DEBUG_DHT_ROUTING
2647 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2649 /** Log routes that die due to high load! */
2650 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2651 msg_ctx->hop_count, GNUNET_SYSERR,
2652 &my_identity, &msg_ctx->key, msg_ctx->peer,
2656 /* invalid wrapper: key mismatch! */
2657 GNUNET_break_op (0);
2660 /* ret == GNUNET_SYSERR means that there is no known relationship between
2661 data and the key, so we cannot check it */
2663 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2664 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2665 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2667 #if DEBUG_DHT_ROUTING
2668 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2670 if ((debug_routes) && (dhtlog_handle != NULL))
2672 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2673 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2679 if (msg_ctx->closest != GNUNET_YES)
2681 route_message (msg, msg_ctx);
2686 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2687 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2688 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
2691 #if DEBUG_DHT_ROUTING
2692 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2694 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2695 msg_ctx->hop_count, GNUNET_YES,
2696 &my_identity, &msg_ctx->key, msg_ctx->peer,
2700 if ((debug_routes) && (dhtlog_handle != NULL))
2702 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2703 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2708 increment_stats(STAT_PUTS_INSERTED);
2709 if (datacache != NULL)
2711 ret = GNUNET_DATACACHE_put (datacache, &msg_ctx->key, data_size,
2712 (char *) &put_msg[1], put_type,
2713 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2715 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2717 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2718 memcpy(&put_context->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
2719 put_context->type = put_type;
2720 GNUNET_SCHEDULER_add_delayed (dht_republish_frequency, &republish_content, put_context);
2724 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2725 "`%s:%s': %s request received, but have no datacache!\n",
2726 my_short_id, "DHT", "PUT");
2728 if (stop_on_closest == GNUNET_NO)
2729 route_message (msg, msg_ctx);
2733 * Estimate the diameter of the network based
2734 * on how many buckets are currently in use.
2735 * Concept here is that the diameter of the network
2736 * is roughly the distance a message must travel in
2737 * order to reach its intended destination. Since
2738 * at each hop we expect to get one bit closer, and
2739 * we have one bit per bucket, the number of buckets
2740 * in use should be the largest number of hops for
2741 * a successful message. (of course, this assumes we
2742 * know all peers in the network!)
2744 * @return ballpark diameter figure
2746 static unsigned int estimate_diameter()
2748 return MAX_BUCKETS - lowest_bucket;
2752 * To how many peers should we (on average)
2753 * forward the request to obtain the desired
2754 * target_replication count (on average).
2756 * returns: target_replication / (est. hops) + (target_replication * hop_count)
2757 * where est. hops is typically 2 * the routing table depth
2759 * @param hop_count number of hops the message has traversed
2760 * @param target_replication the number of total paths desired
2762 * @return Some number of peers to forward the message to
2765 get_forward_count (unsigned int hop_count, size_t target_replication)
2767 uint32_t random_value;
2768 unsigned int forward_count;
2770 unsigned int diameter;
2772 diameter = estimate_diameter ();
2774 if (GNUNET_NO == use_max_hops)
2775 max_hops = (diameter + 1) * 2;
2778 * If we are behaving in strict kademlia mode, send multiple initial requests,
2779 * but then only send to 1 or 0 peers based strictly on the number of hops.
2781 if (strict_kademlia == GNUNET_YES)
2784 return kademlia_replication;
2785 else if (hop_count < max_hops)
2791 /* FIXME: the smaller we think the network is the more lenient we should be for
2792 * routing right? The estimation below only works if we think we have reasonably
2793 * full routing tables, which for our RR topologies may not be the case!
2795 if (hop_count > max_hops)
2798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2799 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2800 "DHT", estimate_diameter(), lowest_bucket);
2806 /* FIXME: we use diameter as the expected number of hops, but with randomized routing we will likely route to more! */
2807 target_value = target_replication / (diameter + ((float)target_replication * hop_count));
2808 if (target_value > 1)
2809 return (unsigned int)target_value;
2811 random_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int)-1);
2813 if (random_value < (target_value * (unsigned int)-1))
2818 return forward_count;
2822 * Check whether my identity is closer than any known peers.
2823 * If a non-null bloomfilter is given, check if this is the closest
2824 * peer that hasn't already been routed to.
2826 * @param target hash code to check closeness to
2827 * @param bloom bloomfilter, exclude these entries from the decision
2829 * Return GNUNET_YES if node location is closest, GNUNET_NO
2833 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2839 struct PeerInfo *pos;
2840 unsigned int my_distance;
2842 if (0 == memcmp(&my_identity.hashPubKey, target, sizeof(GNUNET_HashCode)))
2845 bucket_num = find_current_bucket(target);
2847 bits = GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, target);
2848 my_distance = distance(&my_identity.hashPubKey, target);
2849 pos = k_buckets[bucket_num].head;
2851 while ((pos != NULL) && (count < bucket_size))
2853 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2856 continue; /* Skip already checked entries */
2859 other_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
2860 if (other_bits > bits)
2862 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2864 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2866 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2872 /* No peers closer, we are the closest! */
2878 * Return this peers adjusted value based on the convergence
2879 * function chosen. This is the key function for randomized
2880 * routing decisions.
2882 * @param target the key of the request
2883 * @param peer the peer we would like the value of
2884 * @param hops number of hops this message has already traveled
2886 * @return bit distance from target to peer raised to an exponent
2887 * adjusted based on the current routing convergence algorithm
2890 static unsigned long long
2891 converge_distance (const GNUNET_HashCode *target,
2892 struct PeerInfo *peer,
2895 unsigned long long ret;
2896 unsigned int other_matching_bits;
2897 double base_converge_modifier = .1; /* Value that "looks" good (when plotted), have to start somewhere */
2898 double temp_modifier;
2904 curr_max_hops = max_hops;
2906 curr_max_hops = (estimate_diameter() + 1) * 2;
2908 if (converge_modifier > 0)
2909 temp_modifier = converge_modifier * base_converge_modifier;
2912 temp_modifier = base_converge_modifier;
2913 base_converge_modifier = 0.0;
2916 GNUNET_assert(temp_modifier > 0);
2918 other_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &peer->id.hashPubKey);
2920 switch (converge_option)
2922 case DHT_CONVERGE_RANDOM:
2923 return 1; /* Always return 1, choose equally among all peers */
2924 case DHT_CONVERGE_LINEAR:
2925 calc_value = hops * curr_max_hops * temp_modifier;
2927 case DHT_CONVERGE_SQUARE:
2929 * Simple square based curve.
2931 calc_value = (sqrt(hops) / sqrt(curr_max_hops)) * (curr_max_hops / (curr_max_hops * temp_modifier));
2933 case DHT_CONVERGE_EXPONENTIAL:
2935 * Simple exponential curve.
2937 if (base_converge_modifier > 0)
2938 calc_value = (temp_modifier * hops * hops) / curr_max_hops;
2940 calc_value = (hops * hops) / curr_max_hops;
2942 case DHT_CONVERGE_BINARY:
2944 * If below the cutoff, route randomly (return 1),
2945 * If above the cutoff, return the maximum possible
2946 * value first (always route to closest, because
2950 if (hops > converge_modifier) /* Past cutoff */
2959 /* Take the log (base e) of the number of bits matching the other peer */
2960 exponent = log(other_matching_bits);
2962 /* Check if we would overflow; our largest possible value is 2^64 approx. e^44.361419555836498 */
2963 if (exponent * calc_value >= 44.361419555836498)
2966 /* Clear errno and all math exceptions */
2968 feclearexcept(FE_ALL_EXCEPT);
2969 ret = (unsigned long long)pow(other_matching_bits, calc_value);
2970 if ((errno != 0) || fetestexcept(FE_INVALID | FE_DIVBYZERO | FE_OVERFLOW |
2973 if (0 != fetestexcept(FE_OVERFLOW))
2974 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_OVERFLOW\n");
2975 if (0 != fetestexcept(FE_INVALID))
2976 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_INVALID\n");
2977 if (0 != fetestexcept(FE_UNDERFLOW))
2978 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "FE_UNDERFLOW\n");
2986 * Comparison function for two struct PeerInfo's
2987 * which have already had their matching bits to
2988 * some target calculated.
2990 * @param p1 a pointer pointer to a struct PeerInfo
2991 * @param p2 a pointer pointer to a struct PeerInfo
2993 * @return 0 if equidistant to target,
2994 * -1 if p1 is closer,
2998 compare_peers (const void *p1, const void *p2)
3000 struct PeerInfo **first = (struct PeerInfo **)p1;
3001 struct PeerInfo **second = (struct PeerInfo **)p2;
3003 if ((*first)->matching_bits > (*second)->matching_bits)
3005 if ((*first)->matching_bits < (*second)->matching_bits)
3013 * Select a peer from the routing table that would be a good routing
3014 * destination for sending a message for "target". The resulting peer
3015 * must not be in the set of blocked peers.<p>
3017 * Note that we should not ALWAYS select the closest peer to the
3018 * target, peers further away from the target should be chosen with
3019 * exponentially declining probability.
3021 * @param target the key we are selecting a peer to route to
3022 * @param bloom a bloomfilter containing entries this request has seen already
3024 * @return Peer to route to, or NULL on error
3026 static struct PeerInfo *
3027 select_peer (const GNUNET_HashCode * target,
3028 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3033 unsigned int offset;
3034 unsigned int my_matching_bits;
3036 struct PeerInfo *pos;
3037 struct PeerInfo *sorted_closest[bucket_size];
3038 unsigned long long temp_converge_distance;
3039 unsigned long long total_distance;
3040 unsigned long long selected;
3042 unsigned long long stats_total_distance;
3046 unsigned int distance;
3047 unsigned int largest_distance;
3048 struct PeerInfo *chosen;
3050 my_matching_bits = GNUNET_CRYPTO_hash_matching_bits(target, &my_identity.hashPubKey);
3053 if (strict_kademlia == GNUNET_YES)
3055 largest_distance = 0;
3057 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3059 pos = k_buckets[bc].head;
3061 while ((pos != NULL) && (count < bucket_size))
3063 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3064 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3066 distance = inverse_distance (target, &pos->id.hashPubKey);
3067 if (distance > largest_distance)
3070 largest_distance = distance;
3078 if ((largest_distance > 0) && (chosen != NULL))
3080 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
3091 /* Three steps: order peers in closest bucket (most matching bits).
3092 * Then go over all LOWER buckets (matching same bits we do)
3093 * Then go over all HIGHER buckets (matching less then we do)
3096 closest_bucket = find_current_bucket(target);
3097 GNUNET_assert(closest_bucket >= lowest_bucket);
3098 pos = k_buckets[closest_bucket].head;
3100 offset = 0; /* Need offset as well as count in case peers are bloomfiltered */
3101 memset(sorted_closest, 0, sizeof(sorted_closest));
3102 /* Put any peers in the closest bucket in the sorting array */
3103 while ((pos != NULL) && (count < bucket_size))
3105 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3109 continue; /* Ignore bloomfiltered peers */
3111 pos->matching_bits = GNUNET_CRYPTO_hash_matching_bits(&pos->id.hashPubKey, target);
3112 sorted_closest[offset] = pos;
3118 /* Sort the peers in descending order */
3119 qsort(&sorted_closest[0], offset, sizeof(struct PeerInfo *), &compare_peers);
3121 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3122 for (i = 0; i < offset; i++)
3124 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3125 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3126 break; /* Ignore bloomfiltered peers */
3127 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3128 total_distance += temp_converge_distance;
3130 break; /* overflow case */
3133 /* Now handle peers in lower buckets (matches same # of bits as target) */
3134 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3136 pos = k_buckets[bc].head;
3138 while ((pos != NULL) && (count < bucket_size))
3140 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3144 continue; /* Ignore bloomfiltered peers */
3146 temp_converge_distance = converge_distance(target, pos, hops);
3147 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3148 total_distance += temp_converge_distance;
3150 break; /* overflow case */
3156 /* Now handle all the further away peers */
3157 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3159 pos = k_buckets[bc].head;
3161 while ((pos != NULL) && (count < bucket_size))
3163 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3167 continue; /* Ignore bloomfiltered peers */
3169 temp_converge_distance = converge_distance(target, pos, hops);
3170 if ((temp_converge_distance <= ULLONG_MAX) && (total_distance + temp_converge_distance > total_distance)) /* Handle largest case and overflow */
3171 total_distance += temp_converge_distance;
3173 break; /* overflow case */
3179 if (total_distance == 0) /* No peers to select from! */
3181 increment_stats("# select_peer, total_distance == 0");
3185 #if DEBUG_DHT_ROUTING > 1
3188 /* Put the sorted closest peers into the possible bins first, in case of overflow. */
3189 stats_total_distance = 0;
3190 for (i = 0; i < offset; i++)
3192 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3193 break; /* Ignore bloomfiltered peers */
3194 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3195 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3196 stats_total_distance += temp_converge_distance;
3198 break; /* overflow case */
3199 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);
3202 /* Now handle peers in lower buckets (matches same # of bits as target) */
3203 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3205 pos = k_buckets[bc].head;
3207 while ((pos != NULL) && (count < bucket_size))
3209 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3213 continue; /* Ignore bloomfiltered peers */
3215 temp_converge_distance = converge_distance(target, pos, hops);
3216 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3217 stats_total_distance += temp_converge_distance;
3219 break; /* overflow case */
3220 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);
3226 /* Now handle all the further away peers */
3227 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3229 pos = k_buckets[bc].head;
3231 while ((pos != NULL) && (count < bucket_size))
3233 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3237 continue; /* Ignore bloomfiltered peers */
3239 temp_converge_distance = converge_distance(target, pos, hops);
3240 if ((temp_converge_distance <= ULLONG_MAX) && (stats_total_distance + temp_converge_distance > stats_total_distance)) /* Handle largest case and overflow */
3241 stats_total_distance += temp_converge_distance;
3243 break; /* overflow case */
3244 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose %d matching bits (%d bits match me) (%.2f percent) converge ret %llu\n", GNUNET_CRYPTO_hash_matching_bits(&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);
3249 /* END PRINT STATS */
3252 /* Now actually choose a peer */
3253 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
3255 /* Go over closest sorted peers. */
3256 for (i = 0; i < offset; i++)
3258 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &sorted_closest[i]->id.hashPubKey))
3259 break; /* Ignore bloomfiltered peers */
3260 temp_converge_distance = converge_distance(target, sorted_closest[i], hops);
3261 if (temp_converge_distance >= selected)
3262 return sorted_closest[i];
3264 selected -= temp_converge_distance;
3267 /* Now handle peers in lower buckets (matches same # of bits as target) */
3268 for (bc = lowest_bucket; bc < closest_bucket; bc++)
3270 pos = k_buckets[bc].head;
3272 while ((pos != NULL) && (count < bucket_size))
3274 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3278 continue; /* Ignore bloomfiltered peers */
3280 temp_converge_distance = converge_distance(target, pos, hops);
3281 if (temp_converge_distance >= selected)
3284 selected -= temp_converge_distance;
3290 /* Now handle all the further away peers */
3291 for (bc = closest_bucket + 1; bc < MAX_BUCKETS; bc++)
3293 pos = k_buckets[bc].head;
3295 while ((pos != NULL) && (count < bucket_size))
3297 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3301 continue; /* Ignore bloomfiltered peers */
3303 temp_converge_distance = converge_distance(target, pos, hops);
3304 if (temp_converge_distance >= selected)
3307 selected -= temp_converge_distance;
3313 increment_stats("# failed to select peer");
3319 * Task used to remove recent entries, either
3320 * after timeout, when full, or on shutdown.
3322 * @param cls the entry to remove
3323 * @param tc context, reason, etc.
3326 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3328 struct RecentRequest *req = cls;
3329 static GNUNET_HashCode hash;
3331 GNUNET_assert(req != NULL);
3332 hash_from_uid(req->uid, &hash);
3333 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3334 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3335 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3339 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3341 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3342 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3349 * Task used to remove forwarding entries, either
3350 * after timeout, when full, or on shutdown.
3352 * @param cls the entry to remove
3353 * @param tc context, reason, etc.
3356 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3358 struct DHTRouteSource *source_info = cls;
3359 struct DHTQueryRecord *record;
3360 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3361 record = source_info->record;
3362 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3364 if (record->head == NULL) /* No more entries in DLL */
3366 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap, &record->key, record));
3367 GNUNET_free(record);
3369 if (source_info->find_peers_responded != NULL)
3370 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3371 GNUNET_free(source_info);
3375 * Remember this routing request so that if a reply is
3376 * received we can either forward it to the correct peer
3377 * or return the result locally.
3379 * @param msg_ctx Context of the route request
3381 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3383 static int cache_response(struct DHT_MessageContext *msg_ctx)
3385 struct DHTQueryRecord *record;
3386 struct DHTRouteSource *source_info;
3387 struct DHTRouteSource *pos;
3388 struct GNUNET_TIME_Absolute now;
3389 unsigned int current_size;
3391 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3393 #if DELETE_WHEN_FULL
3394 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3396 source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3397 GNUNET_assert(source_info != NULL);
3398 record = source_info->record;
3399 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3400 if (record->head == NULL) /* No more entries in DLL */
3402 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3403 GNUNET_free(record);
3405 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3406 GNUNET_SCHEDULER_cancel(source_info->delete_task);
3407 if (source_info->find_peers_responded != NULL)
3408 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3409 GNUNET_free(source_info);
3410 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3413 /** Non-local request and have too many outstanding forwards, discard! */
3414 if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3417 now = GNUNET_TIME_absolute_get();
3418 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3419 if (record != NULL) /* Already know this request! */
3424 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3425 break; /* Already have this peer in reply list! */
3428 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3430 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.abs_value);
3436 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3437 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3438 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3441 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3442 source_info->record = record;
3443 source_info->delete_task = GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3444 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3445 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3446 GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail, source_info);
3447 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3449 source_info->client = msg_ctx->client;
3450 now = GNUNET_TIME_absolute_get_forever();
3452 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.abs_value);
3454 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3455 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3456 "DHT", GNUNET_h2s (&msg_ctx->key), msg_ctx->unique_id);
3463 * Main function that handles whether or not to route a message to other
3466 * @param msg the message to be routed
3467 * @param msg_ctx the context containing all pertinent information about the message
3470 route_message(const struct GNUNET_MessageHeader *msg,
3471 struct DHT_MessageContext *msg_ctx)
3474 struct PeerInfo *selected;
3475 #if DEBUG_DHT_ROUTING > 1
3476 struct PeerInfo *nearest;
3478 unsigned int target_forward_count;
3479 unsigned int forward_count;
3480 struct RecentRequest *recent_req;
3481 GNUNET_HashCode unique_hash;
3482 char *stat_forward_count;
3483 char *temp_stat_str;
3484 #if DEBUG_DHT_ROUTING
3488 if (malicious_dropper == GNUNET_YES)
3490 #if DEBUG_DHT_ROUTING
3491 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3493 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3494 msg_ctx->hop_count, GNUNET_SYSERR,
3495 &my_identity, &msg_ctx->key, msg_ctx->peer,
3499 if (msg_ctx->bloom != NULL)
3501 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3502 msg_ctx->bloom = NULL;
3507 increment_stats(STAT_ROUTES);
3508 target_forward_count = get_forward_count(msg_ctx->hop_count, msg_ctx->replication);
3509 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", target_forward_count);
3510 increment_stats(stat_forward_count);
3511 GNUNET_free(stat_forward_count);
3512 if (msg_ctx->bloom == NULL)
3513 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3515 if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3516 target_forward_count = 0;
3519 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3520 * any closer peers (which is being checked for below). Since we are doing recursive
3521 * routing we have no choice but to stop forwarding in this case. This means that at
3522 * any given step the request may NOT be forwarded to alpha peers (because routes will
3523 * stop and the parallel route will not be aware of it). Of course, assuming that we
3524 * have fulfilled the Kademlia requirements for routing table fullness this will never
3525 * ever ever be a problem.
3527 * However, is this fair?
3529 * Since we use these requests to build our routing tables (and we build them in the
3530 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3531 * routing tables still get constructed.
3533 if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) && (msg_ctx->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3534 target_forward_count = 0;
3537 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3538 hash_from_uid (msg_ctx->unique_id, &unique_hash);
3539 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3541 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3542 GNUNET_assert(recent_req != NULL);
3543 if (0 != memcmp(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode)))
3544 increment_stats(STAT_DUPLICATE_UID);
3547 increment_stats(STAT_RECENT_SEEN);
3548 GNUNET_CONTAINER_bloomfilter_or2(msg_ctx->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3553 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3554 recent_req->uid = msg_ctx->unique_id;
3555 memcpy(&recent_req->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3556 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3557 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().abs_value);
3558 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3559 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3562 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3564 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3565 GNUNET_assert(recent_req != NULL);
3566 GNUNET_SCHEDULER_cancel(recent_req->remove_task);
3567 GNUNET_SCHEDULER_add_now(&remove_recent, recent_req);
3571 for (i = 0; i < target_forward_count; i++)
3573 selected = select_peer(&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3575 if (selected != NULL)
3578 if (GNUNET_CRYPTO_hash_matching_bits(&selected->id.hashPubKey, &msg_ctx->key) >= GNUNET_CRYPTO_hash_matching_bits(&my_identity.hashPubKey, &msg_ctx->key))
3579 GNUNET_asprintf(&temp_stat_str, "# requests routed to close(r) peer hop %u", msg_ctx->hop_count);
3581 GNUNET_asprintf(&temp_stat_str, "# requests routed to less close peer hop %u", msg_ctx->hop_count);
3582 if (temp_stat_str != NULL)
3584 increment_stats(temp_stat_str);
3585 GNUNET_free(temp_stat_str);
3587 GNUNET_CONTAINER_bloomfilter_add(msg_ctx->bloom, &selected->id.hashPubKey);
3588 #if DEBUG_DHT_ROUTING > 1
3589 nearest = find_closest_peer(&msg_ctx->key);
3590 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3591 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3592 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3593 "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));
3594 GNUNET_free(nearest_buf);
3596 #if DEBUG_DHT_ROUTING
3597 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3599 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3600 msg_ctx->hop_count, GNUNET_NO,
3601 &my_identity, &msg_ctx->key, msg_ctx->peer,
3605 forward_message (msg, selected, msg_ctx);
3609 if (msg_ctx->bloom != NULL)
3611 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, msg_ctx->bloom, DHT_BLOOM_SIZE);
3612 GNUNET_CONTAINER_bloomfilter_free(msg_ctx->bloom);
3613 msg_ctx->bloom = NULL;
3616 #if DEBUG_DHT_ROUTING
3617 if (forward_count == 0)
3618 ret = GNUNET_SYSERR;
3622 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3624 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3625 msg_ctx->hop_count, ret,
3626 &my_identity, &msg_ctx->key, msg_ctx->peer,
3635 * Main function that handles whether or not to route a message to other
3638 * @param msg the message to be routed
3639 * @param msg_ctx the context containing all pertinent information about the message
3642 demultiplex_message(const struct GNUNET_MessageHeader *msg,
3643 struct DHT_MessageContext *msg_ctx)
3645 msg_ctx->closest = am_closest_peer(&msg_ctx->key, NULL);
3646 switch (ntohs(msg->type))
3648 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3649 cache_response (msg_ctx);
3650 handle_dht_get (msg, msg_ctx);
3652 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3653 increment_stats(STAT_PUTS);
3654 handle_dht_put (msg, msg_ctx);
3656 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3657 increment_stats(STAT_FIND_PEER);
3658 if (((msg_ctx->hop_count > 0) && (0 != memcmp(msg_ctx->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (msg_ctx->client != NULL))
3660 cache_response (msg_ctx);
3661 if ((msg_ctx->closest == GNUNET_YES) || (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3662 handle_dht_find_peer (msg, msg_ctx);
3665 route_message (msg, msg_ctx);
3666 #if DEBUG_DHT_ROUTING
3667 if (msg_ctx->hop_count == 0) /* Locally initiated request */
3669 if ((debug_routes) && (dhtlog_handle != NULL))
3671 dhtlog_handle->insert_dhtkey(NULL, &msg_ctx->key);
3672 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
3673 msg_ctx->hop_count, GNUNET_NO, &my_identity,
3680 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3681 "`%s': Message type (%d) not handled, forwarding anyway!\n", "DHT", ntohs(msg->type));
3682 route_message (msg, msg_ctx);
3690 * Iterator for local get request results,
3692 * @param cls closure for iterator, NULL
3693 * @param exp when does this value expire?
3694 * @param key the key this data is stored under
3695 * @param size the size of the data identified by key
3696 * @param data the actual data
3697 * @param type the type of the data
3699 * @return GNUNET_OK to continue iteration, anything else
3700 * to stop iteration.
3703 republish_content_iterator (void *cls,
3704 struct GNUNET_TIME_Absolute exp,
3705 const GNUNET_HashCode * key,
3706 size_t size, const char *data, uint32_t type)
3709 struct DHT_MessageContext *new_msg_ctx;
3710 struct GNUNET_DHT_PutMessage *put_msg;
3712 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3713 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3715 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3718 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3719 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3720 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3721 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3722 put_msg->type = htons (type);
3723 memcpy (&put_msg[1], data, size);
3724 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3725 new_msg_ctx->replication = ntohl (DEFAULT_PUT_REPLICATION);
3726 new_msg_ctx->msg_options = ntohl (0);
3727 new_msg_ctx->network_size = estimate_diameter();
3728 new_msg_ctx->peer = &my_identity;
3729 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3730 new_msg_ctx->hop_count = 0;
3731 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3732 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3733 increment_stats(STAT_PUT_START);
3734 demultiplex_message(&put_msg->header, new_msg_ctx);
3736 GNUNET_free(new_msg_ctx);
3737 GNUNET_free (put_msg);
3742 * Task used to republish data.
3744 * @param cls closure (a struct RepublishContext)
3745 * @param tc runtime context for this task
3748 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3750 struct RepublishContext *put_context = cls;
3752 unsigned int results;
3754 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3756 GNUNET_free(put_context);
3760 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3761 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3762 if (results == 0) /* Data must have expired */
3763 GNUNET_free(put_context);
3764 else /* Reschedule task for next time period */
3765 GNUNET_SCHEDULER_add_delayed(dht_republish_frequency, &republish_content, put_context);
3771 * Iterator over hash map entries.
3773 * @param cls client to search for in source routes
3774 * @param key current key code (ignored)
3775 * @param value value in the hash map, a DHTQueryRecord
3776 * @return GNUNET_YES if we should continue to
3780 static int find_client_records (void *cls,
3781 const GNUNET_HashCode * key, void *value)
3783 struct ClientList *client = cls;
3784 struct DHTQueryRecord *record = value;
3785 struct DHTRouteSource *pos;
3789 if (pos->client == client)
3795 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, pos);
3796 GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, pos->hnode);
3797 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3798 GNUNET_SCHEDULER_cancel(pos->delete_task);
3800 if (pos->find_peers_responded != NULL)
3801 GNUNET_CONTAINER_bloomfilter_free(pos->find_peers_responded);
3804 if (record->head == NULL) /* No more entries in DLL */
3806 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3807 GNUNET_free(record);
3813 * Functions with this signature are called whenever a client
3814 * is disconnected on the network level.
3816 * @param cls closure (NULL for dht)
3817 * @param client identification of the client; NULL
3818 * for the last call when the server is destroyed
3820 static void handle_client_disconnect (void *cls,
3821 struct GNUNET_SERVER_Client* client)
3823 struct ClientList *pos = client_list;
3824 struct ClientList *prev;
3825 struct ClientList *found;
3826 struct PendingMessage *reply;
3832 if (pos->client_handle == client)
3835 prev->next = pos->next;
3837 client_list = pos->next;
3847 if (found->transmit_handle != NULL)
3848 GNUNET_CONNECTION_notify_transmit_ready_cancel(found->transmit_handle);
3850 while(NULL != (reply = found->pending_head))
3852 GNUNET_CONTAINER_DLL_remove(found->pending_head, found->pending_tail, reply);
3855 GNUNET_CONTAINER_multihashmap_iterate(forward_list.hashmap, &find_client_records, found);
3861 * Find a client if it exists, add it otherwise.
3863 * @param client the server handle to the client
3865 * @return the client if found, a new client otherwise
3867 static struct ClientList *
3868 find_active_client (struct GNUNET_SERVER_Client *client)
3870 struct ClientList *pos = client_list;
3871 struct ClientList *ret;
3875 if (pos->client_handle == client)
3880 ret = GNUNET_malloc (sizeof (struct ClientList));
3881 ret->client_handle = client;
3882 ret->next = client_list;
3890 * Task to send a malicious put message across the network.
3892 * @param cls closure for this task
3893 * @param tc the context under which the task is running
3896 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3898 static struct GNUNET_DHT_PutMessage put_message;
3899 static struct DHT_MessageContext msg_ctx;
3900 static GNUNET_HashCode key;
3901 uint32_t random_key;
3903 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3905 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3906 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3907 put_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3908 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3909 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3910 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3911 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3912 memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3913 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3914 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3915 msg_ctx.msg_options = ntohl (0);
3916 msg_ctx.network_size = estimate_diameter();
3917 msg_ctx.peer = &my_identity;
3918 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3919 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3920 #if DEBUG_DHT_ROUTING
3921 if (dhtlog_handle != NULL)
3922 dhtlog_handle->insert_dhtkey(NULL, &key);
3924 increment_stats(STAT_PUT_START);
3925 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3926 demultiplex_message(&put_message.header, &msg_ctx);
3927 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3932 * Task to send a malicious put message across the network.
3934 * @param cls closure for this task
3935 * @param tc the context under which the task is running
3938 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3940 static struct GNUNET_DHT_GetMessage get_message;
3941 struct DHT_MessageContext msg_ctx;
3942 static GNUNET_HashCode key;
3943 uint32_t random_key;
3945 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3948 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3949 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3950 get_message.type = htonl(GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3951 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
3952 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3953 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3954 memcpy(&msg_ctx.key, &key, sizeof(GNUNET_HashCode));
3955 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3956 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3957 msg_ctx.msg_options = ntohl (0);
3958 msg_ctx.network_size = estimate_diameter();
3959 msg_ctx.peer = &my_identity;
3960 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3961 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3962 #if DEBUG_DHT_ROUTING
3963 if (dhtlog_handle != NULL)
3964 dhtlog_handle->insert_dhtkey(NULL, &key);
3966 increment_stats(STAT_GET_START);
3967 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s\n", my_short_id, "DHT", GNUNET_h2s(&key));
3968 demultiplex_message (&get_message.header, &msg_ctx);
3969 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3975 * Iterator over hash map entries.
3977 * @param cls closure
3978 * @param key current key code
3979 * @param value value in the hash map
3980 * @return GNUNET_YES if we should continue to
3985 add_known_to_bloom (void *cls,
3986 const GNUNET_HashCode * key,
3989 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3990 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3995 * Task to send a find peer message for our own peer identifier
3996 * so that we can find the closest peers in the network to ourselves
3997 * and attempt to connect to them.
3999 * @param cls closure for this task
4000 * @param tc the context under which the task is running
4003 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4005 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
4006 struct DHT_MessageContext msg_ctx;
4007 struct GNUNET_TIME_Relative next_send_time;
4008 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
4010 struct GNUNET_TIME_Relative time_diff;
4011 struct GNUNET_TIME_Absolute end;
4013 double count_per_interval;
4015 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
4018 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! */
4020 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
4021 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
4022 &send_find_peer_message, NULL);
4023 newly_found_peers = 0;
4027 increment_stats(STAT_FIND_PEER_START);
4029 end = GNUNET_TIME_absolute_get();
4030 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
4032 if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
4034 multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
4035 count_per_interval = find_peer_context.count / multiplier;
4039 multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
4040 count_per_interval = find_peer_context.count * multiplier;
4044 #if FIND_PEER_WITH_HELLO
4045 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4046 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4047 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
4049 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
4050 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
4052 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
4053 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4054 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
4055 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
4056 GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
4057 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4058 memcpy(&msg_ctx.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
4059 msg_ctx.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
4060 msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
4061 msg_ctx.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
4062 msg_ctx.network_size = estimate_diameter();
4063 msg_ctx.peer = &my_identity;
4064 msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
4065 msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
4067 demultiplex_message(&find_peer_msg->header, &msg_ctx);
4068 GNUNET_free(find_peer_msg);
4069 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4070 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id, "DHT",
4072 if (newly_found_peers < bucket_size)
4074 next_send_time.rel_value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
4075 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4076 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
4080 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4081 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4082 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4085 GNUNET_assert (next_send_time.rel_value != 0);
4086 find_peer_context.count = 0;
4087 newly_found_peers = 0;
4088 find_peer_context.start = GNUNET_TIME_absolute_get();
4089 if (GNUNET_YES == do_find_peer)
4091 GNUNET_SCHEDULER_add_delayed (next_send_time,
4092 &send_find_peer_message, NULL);
4097 * Handler for any generic DHT messages, calls the appropriate handler
4098 * depending on message type, sends confirmation if responses aren't otherwise
4101 * @param cls closure for the service
4102 * @param client the client we received this message from
4103 * @param message the actual message received
4106 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4107 const struct GNUNET_MessageHeader *message)
4109 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
4110 const struct GNUNET_MessageHeader *enc_msg;
4111 struct DHT_MessageContext msg_ctx;
4113 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4115 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4116 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4120 ntohs (message->type),
4121 GNUNET_h2s (&dht_msg->key),
4122 GNUNET_ntohll (dht_msg->unique_id));
4124 #if DEBUG_DHT_ROUTING
4125 if (dhtlog_handle != NULL)
4126 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4128 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4129 msg_ctx.client = find_active_client (client);
4130 memcpy(&msg_ctx.key, &dht_msg->key, sizeof(GNUNET_HashCode));
4131 msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4132 msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
4133 msg_ctx.msg_options = ntohl (dht_msg->options);
4134 msg_ctx.network_size = estimate_diameter();
4135 msg_ctx.peer = &my_identity;
4136 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
4137 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4138 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4139 increment_stats(STAT_GET_START);
4140 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4141 increment_stats(STAT_PUT_START);
4142 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4143 increment_stats(STAT_FIND_PEER_START);
4145 demultiplex_message(enc_msg, &msg_ctx);
4147 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4152 * Handler for any locally received DHT control messages,
4153 * sets malicious flags mostly for now.
4155 * @param cls closure for the service
4156 * @param client the client we received this message from
4157 * @param message the actual message received
4161 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4162 const struct GNUNET_MessageHeader *message)
4164 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4165 (const struct GNUNET_DHT_ControlMessage *) message;
4167 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4168 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
4169 "CONTROL", ntohs(dht_control_msg->command));
4172 switch (ntohs(dht_control_msg->command))
4174 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4175 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
4176 GNUNET_SCHEDULER_add_now(&send_find_peer_message, NULL);
4179 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4180 if (ntohs(dht_control_msg->variable) > 0)
4181 malicious_get_frequency = ntohs(dht_control_msg->variable);
4182 if (malicious_get_frequency == 0)
4183 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4184 if (malicious_getter != GNUNET_YES)
4185 GNUNET_SCHEDULER_add_now(&malicious_get_task, NULL);
4186 malicious_getter = GNUNET_YES;
4187 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4188 "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
4190 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4191 if (ntohs(dht_control_msg->variable) > 0)
4192 malicious_put_frequency = ntohs(dht_control_msg->variable);
4193 if (malicious_put_frequency == 0)
4194 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4195 if (malicious_putter != GNUNET_YES)
4196 GNUNET_SCHEDULER_add_now(&malicious_put_task, NULL);
4197 malicious_putter = GNUNET_YES;
4198 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4199 "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
4201 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4202 #if DEBUG_DHT_ROUTING
4203 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4204 dhtlog_handle->set_malicious(&my_identity);
4206 malicious_dropper = GNUNET_YES;
4207 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
4208 "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
4212 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4213 "%s:%s Unknown control command type `%d'!\n",
4215 ntohs(dht_control_msg->command));
4219 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4223 * Handler for any generic DHT stop messages, calls the appropriate handler
4224 * depending on message type (if processed locally)
4226 * @param cls closure for the service
4227 * @param client the client we received this message from
4228 * @param message the actual message received
4232 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
4233 const struct GNUNET_MessageHeader *message)
4236 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4237 (const struct GNUNET_DHT_StopMessage *) message;
4238 struct DHTQueryRecord *record;
4239 struct DHTRouteSource *pos;
4241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4242 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
4243 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
4245 record = GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &dht_stop_msg->key);
4252 /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
4253 if ((pos->client != NULL) && (pos->client->client_handle == client))
4255 GNUNET_SCHEDULER_cancel(pos->delete_task);
4256 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
4257 GNUNET_SCHEDULER_add_continuation (&remove_forward_entry, pos, GNUNET_SCHEDULER_REASON_PREREQ_DONE);
4263 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4268 * Core handler for p2p route requests.
4271 handle_dht_p2p_route_request (void *cls,
4272 const struct GNUNET_PeerIdentity *peer,
4273 const struct GNUNET_MessageHeader *message,
4274 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4277 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4278 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4280 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
4281 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4282 struct DHT_MessageContext *msg_ctx;
4284 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
4287 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
4292 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4298 if (get_max_send_delay().rel_value > MAX_REQUEST_TIME.rel_value)
4300 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending of previous replies took too long, backing off!\n");
4301 increment_stats("# route requests dropped due to high load");
4302 decrease_max_send_delay(get_max_send_delay());
4303 #if DEBUG_DHT_ROUTING
4304 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4306 /** Log routes that die due to high load! */
4307 dhtlog_handle->insert_route (NULL, GNUNET_ntohll(incoming->unique_id), DHTLOG_ROUTE,
4308 ntohl(incoming->hop_count), GNUNET_SYSERR,
4309 &my_identity, &incoming->key, peer,
4315 msg_ctx = GNUNET_malloc(sizeof (struct DHT_MessageContext));
4316 msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4317 GNUNET_assert(msg_ctx->bloom != NULL);
4318 msg_ctx->hop_count = ntohl(incoming->hop_count);
4319 memcpy(&msg_ctx->key, &incoming->key, sizeof(GNUNET_HashCode));
4320 msg_ctx->replication = ntohl(incoming->desired_replication_level);
4321 msg_ctx->unique_id = GNUNET_ntohll(incoming->unique_id);
4322 msg_ctx->msg_options = ntohl(incoming->options);
4323 msg_ctx->network_size = ntohl(incoming->network_size);
4324 msg_ctx->peer = peer;
4325 msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4326 msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4327 demultiplex_message (enc_msg, msg_ctx);
4328 if (msg_ctx->bloom != NULL)
4330 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4331 msg_ctx->bloom = NULL;
4333 GNUNET_free(msg_ctx);
4339 * Core handler for p2p route results.
4342 handle_dht_p2p_route_result (void *cls,
4343 const struct GNUNET_PeerIdentity *peer,
4344 const struct GNUNET_MessageHeader *message,
4345 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4349 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
4351 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
4352 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
4353 struct DHT_MessageContext msg_ctx;
4355 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4361 memset(&msg_ctx, 0, sizeof(struct DHT_MessageContext));
4362 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4363 msg_ctx.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
4364 GNUNET_assert(msg_ctx.bloom != NULL);
4365 memcpy(&msg_ctx.key, &incoming->key, sizeof(GNUNET_HashCode));
4366 msg_ctx.unique_id = GNUNET_ntohll(incoming->unique_id);
4367 msg_ctx.msg_options = ntohl(incoming->options);
4368 msg_ctx.hop_count = ntohl(incoming->hop_count);
4369 msg_ctx.peer = peer;
4370 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4371 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4372 route_result_message(enc_msg, &msg_ctx);
4378 * Receive the HELLO from transport service,
4379 * free current and replace if necessary.
4382 * @param message HELLO message of peer
4385 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4388 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4389 "Received our `%s' from transport service\n",
4393 GNUNET_assert (message != NULL);
4394 GNUNET_free_non_null(my_hello);
4395 my_hello = GNUNET_malloc(ntohs(message->size));
4396 memcpy(my_hello, message, ntohs(message->size));
4401 * Task run during shutdown.
4407 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4410 struct PeerInfo *pos;
4412 if (transport_handle != NULL)
4414 GNUNET_free_non_null(my_hello);
4415 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
4416 GNUNET_TRANSPORT_disconnect(transport_handle);
4418 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4420 while (k_buckets[bucket_count].head != NULL)
4422 pos = k_buckets[bucket_count].head;
4424 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4425 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
4427 delete_peer(pos, bucket_count);
4430 if (coreAPI != NULL)
4433 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4434 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
4436 GNUNET_CORE_disconnect (coreAPI);
4439 if (datacache != NULL)
4442 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4443 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
4445 GNUNET_DATACACHE_destroy (datacache);
4450 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4453 if (dhtlog_handle != NULL)
4455 GNUNET_DHTLOG_disconnect(dhtlog_handle);
4456 dhtlog_handle = NULL;
4458 if (block_context != NULL)
4460 GNUNET_BLOCK_context_destroy (block_context);
4461 block_context = NULL;
4463 GNUNET_free_non_null(my_short_id);
4469 * To be called on core init/fail.
4471 * @param cls service closure
4472 * @param server handle to the server for this service
4473 * @param identity the public identity of this peer
4474 * @param publicKey the public key of this peer
4477 core_init (void *cls,
4478 struct GNUNET_CORE_Handle *server,
4479 const struct GNUNET_PeerIdentity *identity,
4480 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4486 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4487 "%s: Connection to core FAILED!\n", "dht",
4488 GNUNET_i2s (identity));
4490 GNUNET_SCHEDULER_cancel (cleanup_task);
4491 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4495 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4496 "%s: Core connection initialized, I am peer: %s\n", "dht",
4497 GNUNET_i2s (identity));
4500 /* Copy our identity so we can use it */
4501 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4502 if (my_short_id != NULL)
4503 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4504 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4505 /* Set the server to local variable */
4508 if (dhtlog_handle != NULL)
4509 dhtlog_handle->insert_node (NULL, &my_identity);
4513 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4514 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4515 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4516 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4521 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4522 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4523 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4529 * Method called whenever a peer connects.
4531 * @param cls closure
4532 * @param peer peer identity this notification is about
4533 * @param atsi performance data
4536 handle_core_connect (void *cls,
4537 const struct GNUNET_PeerIdentity * peer,
4538 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4540 struct PeerInfo *ret;
4543 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4544 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4547 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4549 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));
4553 if (datacache != NULL)
4554 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, GNUNET_BLOCK_TYPE_DHT_HELLO, GNUNET_TIME_absolute_get_forever());
4555 ret = try_add_peer(peer,
4556 find_current_bucket(&peer->hashPubKey),
4560 newly_found_peers++;
4561 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4564 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4565 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4571 * Method called whenever a peer disconnects.
4573 * @param cls closure
4574 * @param peer peer identity this notification is about
4577 handle_core_disconnect (void *cls,
4579 GNUNET_PeerIdentity * peer)
4581 struct PeerInfo *to_remove;
4584 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");
4586 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4588 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));
4591 increment_stats(STAT_DISCONNECTS);
4592 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4593 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4594 GNUNET_assert (to_remove != NULL);
4595 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4596 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4597 delete_peer(to_remove, current_bucket);
4602 * Process dht requests.
4604 * @param cls closure
4605 * @param server the initialized server
4606 * @param c configuration to use
4610 struct GNUNET_SERVER_Handle *server,
4611 const struct GNUNET_CONFIGURATION_Handle *c)
4613 struct GNUNET_TIME_Relative next_send_time;
4614 unsigned long long temp_config_num;
4615 char *converge_modifier_buf;
4618 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4619 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4620 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4621 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
4622 DEFAULT_CORE_QUEUE_SIZE, /* queue size */
4623 NULL, /* Closure passed to DHT functions */
4624 &core_init, /* Call core_init once connected */
4625 &handle_core_connect, /* Handle connects */
4626 &handle_core_disconnect, /* remove peers on disconnects */
4627 NULL, /* Do we care about "status" updates? */
4628 NULL, /* Don't want notified about all incoming messages */
4629 GNUNET_NO, /* For header only inbound notification */
4630 NULL, /* Don't want notified about all outbound messages */
4631 GNUNET_NO, /* For header only outbound notification */
4632 core_handlers); /* Register these handlers */
4634 if (coreAPI == NULL)
4636 transport_handle = GNUNET_TRANSPORT_connect(cfg,
4637 NULL, NULL, NULL, NULL, NULL);
4638 if (transport_handle != NULL)
4639 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4641 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
4642 "Failed to connect to transport service!\n");
4643 block_context = GNUNET_BLOCK_context_create (cfg);
4644 lowest_bucket = MAX_BUCKETS - 1;
4645 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4646 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4647 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4648 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4649 GNUNET_assert(all_known_peers != NULL);
4650 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4652 debug_routes = GNUNET_YES;
4656 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4659 strict_kademlia = GNUNET_YES;
4663 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4666 stop_on_closest = GNUNET_YES;
4670 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4673 stop_on_found = GNUNET_YES;
4677 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4678 "malicious_getter"))
4680 malicious_getter = GNUNET_YES;
4681 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4682 "MALICIOUS_GET_FREQUENCY",
4683 &malicious_get_frequency))
4684 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4687 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4691 max_hops = DEFAULT_MAX_HOPS;
4694 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4697 use_max_hops = GNUNET_YES;
4701 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4702 "malicious_putter"))
4704 malicious_putter = GNUNET_YES;
4705 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4706 "MALICIOUS_PUT_FREQUENCY",
4707 &malicious_put_frequency))
4708 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4711 dht_republish_frequency = GNUNET_DHT_DEFAULT_REPUBLISH_FREQUENCY;
4712 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4714 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4717 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "bucket_size", &temp_config_num))
4719 bucket_size = (unsigned int)temp_config_num;
4722 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "kad_alpha", &kademlia_replication))
4724 kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
4728 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4729 "malicious_dropper"))
4731 malicious_dropper = GNUNET_YES;
4735 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4737 do_republish = GNUNET_NO;
4740 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4743 do_find_peer = GNUNET_NO;
4746 do_find_peer = GNUNET_YES;
4749 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4750 "use_real_distance"))
4751 use_real_distance = GNUNET_YES;
4754 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4755 "mysql_logging_extended"))
4757 debug_routes = GNUNET_YES;
4758 debug_routes_extended = GNUNET_YES;
4761 #if DEBUG_DHT_ROUTING
4762 if (GNUNET_YES == debug_routes)
4764 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4765 if (dhtlog_handle == NULL)
4767 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4768 "Could not connect to mysql logging server, logging will not happen!");
4773 converge_option = DHT_CONVERGE_SQUARE;
4775 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4778 converge_option = DHT_CONVERGE_LINEAR;
4780 else if (GNUNET_YES ==
4781 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4782 "converge_exponential"))
4784 converge_option = DHT_CONVERGE_EXPONENTIAL;
4786 else if (GNUNET_YES ==
4787 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4790 converge_option = DHT_CONVERGE_RANDOM;
4792 else if (GNUNET_YES ==
4793 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4796 converge_option = DHT_CONVERGE_BINARY;
4799 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht", "converge_modifier", &converge_modifier_buf))
4801 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4803 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4804 converge_modifier = 0.0;
4806 GNUNET_free(converge_modifier_buf);
4809 stats = GNUNET_STATISTICS_create("dht", cfg);
4813 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4814 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4815 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4816 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4817 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4818 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4819 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4820 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4821 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4822 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4823 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4824 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4825 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4826 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4827 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4828 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4829 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4830 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4831 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4832 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4834 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4835 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4836 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4837 if (GNUNET_YES == do_find_peer)
4839 next_send_time.rel_value = DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4840 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4841 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4842 find_peer_context.start = GNUNET_TIME_absolute_get();
4843 GNUNET_SCHEDULER_add_delayed (next_send_time,
4844 &send_find_peer_message, &find_peer_context);
4847 /* Scheduled the task to clean up when shutdown is called */
4848 cleanup_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4849 &shutdown_task, NULL);
4853 * The main function for the dht service.
4855 * @param argc number of arguments from the command line
4856 * @param argv command line arguments
4857 * @return 0 ok, 1 on error
4860 main (int argc, char *const *argv)
4865 GNUNET_SERVICE_run (argc,
4868 GNUNET_SERVICE_OPTION_NONE,
4869 &run, NULL)) ? 0 : 1;
4870 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap));
4871 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap));
4872 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4873 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4874 GNUNET_CONTAINER_heap_destroy (recent.minHeap);