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
28 * - decide which 'benchmark'/test functions to keep (malicious code, kademlia, etc.)
29 * - integrate properly with 'block' library (instead of manual bloomfiltering)
30 * - decide on 'stop_on_closest', 'stop_on_found', 'do_find_peer', 'paper_forwarding'
34 #include "gnunet_block_lib.h"
35 #include "gnunet_client_lib.h"
36 #include "gnunet_getopt_lib.h"
37 #include "gnunet_os_lib.h"
38 #include "gnunet_protocols.h"
39 #include "gnunet_service_lib.h"
40 #include "gnunet_nse_service.h"
41 #include "gnunet_core_service.h"
42 #include "gnunet_signal_lib.h"
43 #include "gnunet_util_lib.h"
44 #include "gnunet_datacache_lib.h"
45 #include "gnunet_transport_service.h"
46 #include "gnunet_hello_lib.h"
47 #include "gnunet_dht_service.h"
48 #include "gnunet_statistics_service.h"
53 #define PRINT_TABLES GNUNET_NO
55 #define REAL_DISTANCE GNUNET_NO
57 #define EXTRA_CHECKS GNUNET_NO
60 * How many buckets will we allow total.
62 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
65 * Should the DHT issue FIND_PEER requests to get better routing tables?
67 #define DEFAULT_DO_FIND_PEER GNUNET_YES
70 * Defines whether find peer requests send their HELLO's outgoing,
71 * or expect replies to contain hellos.
73 #define FIND_PEER_WITH_HELLO GNUNET_YES
76 * What is the maximum number of peers in a given bucket.
78 #define DEFAULT_BUCKET_SIZE 4
80 #define DEFAULT_CORE_QUEUE_SIZE 32
83 * Minimum number of peers we need for "good" routing,
84 * any less than this and we will allow messages to
85 * travel much further through the network!
87 #define MINIMUM_PEER_THRESHOLD 20
89 #define DHT_MAX_RECENT 1000
91 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
94 * Default time to wait to send messages on behalf of other peers.
96 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
99 * Default importance for handling messages on behalf of other peers.
101 #define DHT_DEFAULT_P2P_IMPORTANCE 0
104 * How long to keep recent requests around by default.
106 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 15)
109 * Default time to wait to send find peer messages sent by the dht service.
111 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
114 * Default importance for find peer messages sent by the dht service.
116 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
119 * Default replication parameter for find peer messages sent by the dht service.
121 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
124 * Default options for find peer requests sent by the dht service.
126 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
127 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
130 * How long at least to wait before sending another find peer request.
132 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
135 * How long at most to wait before sending another find peer request.
137 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
140 * How often to update our preference levels for peers in our routing tables.
142 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
145 * How long at most on average will we allow a reply forward to take
146 * (before we quit sending out new requests)
148 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
151 * How many initial requests to send out (in true Kademlia fashion)
153 #define DEFAULT_KADEMLIA_REPLICATION 3
156 * Default frequency for sending malicious get messages
158 #define DEFAULT_MALICIOUS_GET_FREQUENCY GNUNET_TIME_UNIT_SECONDS
161 * Default frequency for sending malicious put messages
163 #define DEFAULT_MALICIOUS_PUT_FREQUENCY GNUNET_TIME_UNIT_SECONDS
166 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
169 * How many time differences between requesting a core send and
170 * the actual callback to remember.
172 #define MAX_REPLY_TIMES 8
176 * Linked list of messages to send to clients.
178 struct P2PPendingMessage
181 * Pointer to next item in the list
183 struct P2PPendingMessage *next;
186 * Pointer to previous item in the list
188 struct P2PPendingMessage *prev;
191 * Message importance level.
193 unsigned int importance;
196 * Time when this request was scheduled to be sent.
198 struct GNUNET_TIME_Absolute scheduled;
201 * How long to wait before sending message.
203 struct GNUNET_TIME_Relative timeout;
206 * Actual message to be sent; // avoid allocation
208 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
213 * Per-peer information.
218 * Next peer entry (DLL)
220 struct PeerInfo *next;
223 * Prev peer entry (DLL)
225 struct PeerInfo *prev;
228 * Count of outstanding messages for peer.
230 unsigned int pending_count;
233 * Head of pending messages to be sent to this peer.
235 struct P2PPendingMessage *head;
238 * Tail of pending messages to be sent to this peer.
240 struct P2PPendingMessage *tail;
243 * Core handle for sending messages to this peer.
245 struct GNUNET_CORE_TransmitHandle *th;
248 * Task for scheduling message sends.
250 GNUNET_SCHEDULER_TaskIdentifier send_task;
253 * Task for scheduling preference updates
255 GNUNET_SCHEDULER_TaskIdentifier preference_task;
258 * Preference update context
260 struct GNUNET_CORE_InformationRequestContext *info_ctx;
263 * What is the identity of the peer?
265 struct GNUNET_PeerIdentity id;
269 * What is the average latency for replies received?
271 struct GNUNET_TIME_Relative latency;
274 * Transport level distance to peer.
276 unsigned int distance;
280 * Task for scheduling periodic ping messages for this peer.
282 GNUNET_SCHEDULER_TaskIdentifier ping_task;
286 * Peers are grouped into buckets.
293 struct PeerInfo *head;
298 struct PeerInfo *tail;
301 * Number of peers in the bucket.
303 unsigned int peers_size;
307 * Linked list of messages to send to clients.
309 struct PendingMessage
312 * Pointer to next item in the list
314 struct PendingMessage *next;
317 * Pointer to previous item in the list
319 struct PendingMessage *prev;
322 * Actual message to be sent; // avoid allocation
324 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
329 * Struct containing information about a client,
330 * handle to connect to it, and any pending messages
331 * that need to be sent to it.
336 * Linked list of active clients
338 struct ClientList *next;
341 * The handle to this client
343 struct GNUNET_SERVER_Client *client_handle;
346 * Handle to the current transmission request, NULL
349 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
352 * Linked list of pending messages for this client
354 struct PendingMessage *pending_head;
357 * Tail of linked list of pending messages for this client
359 struct PendingMessage *pending_tail;
364 * Context containing information about a DHT message received.
366 struct DHT_MessageContext
369 * The client this request was received from.
370 * (NULL if received from another peer)
372 struct ClientList *client;
375 * The peer this request was received from.
376 * (NULL if received from local client)
378 const struct GNUNET_PeerIdentity *peer;
381 * Bloomfilter for this routing request.
383 struct GNUNET_CONTAINER_BloomFilter *bloom;
386 * extended query (see gnunet_block_lib.h).
391 * Bloomfilter to filter out duplicate replies.
393 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
396 * The key this request was about
401 * How long should we wait to transmit this request?
403 struct GNUNET_TIME_Relative timeout;
406 * The unique identifier of this request
411 * Number of bytes in xquery.
416 * Mutator value for the reply_bf, see gnunet_block_lib.h
418 uint32_t reply_bf_mutator;
421 * Desired replication level
423 uint32_t replication;
426 * Network size estimate, either ours or the sum of
427 * those routed to thus far. =~ Log of number of peers
428 * chosen from for this request.
430 uint32_t network_size;
433 * Any message options for this request
435 uint32_t msg_options;
438 * How many hops has the message already traversed?
443 * How many peer identities are present in the path history?
445 uint32_t path_history_len;
453 * How important is this message?
455 unsigned int importance;
458 * Should we (still) forward the request on to other peers?
463 * Did we forward this message? (may need to remember it!)
468 * Are we the closest known peer to this key (out of our neighbors?)
474 * Record used for remembering what peers are waiting for what
475 * responses (based on search key).
477 struct DHTRouteSource
482 struct DHTRouteSource *next;
487 struct DHTRouteSource *prev;
490 * Source of the request. Replies should be forwarded to
493 struct GNUNET_PeerIdentity source;
496 * If this was a local request, remember the client; otherwise NULL.
498 struct ClientList *client;
501 * Pointer to this nodes heap location (for removal)
503 struct GNUNET_CONTAINER_HeapNode *hnode;
506 * Back pointer to the record storing this information.
508 struct DHTQueryRecord *record;
511 * Task to remove this entry on timeout.
513 GNUNET_SCHEDULER_TaskIdentifier delete_task;
516 * Bloomfilter of peers we have already sent back as
517 * replies to the initial request. Allows us to not
518 * forward the same peer multiple times for a find peer
521 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
526 * Entry in the DHT routing table.
528 struct DHTQueryRecord
531 * Head of DLL for result forwarding.
533 struct DHTRouteSource *head;
536 * Tail of DLL for result forwarding.
538 struct DHTRouteSource *tail;
541 * Key that the record concerns.
546 * Bloomfilter of the peers we've replied to so far
548 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
553 * Context used to calculate the number of find peer messages
554 * per X time units since our last scheduled find peer message
555 * was sent. If we have seen too many messages, delay or don't
558 struct FindPeerMessageContext
562 struct GNUNET_TIME_Absolute start;
564 struct GNUNET_TIME_Absolute end;
568 * DHT Routing results structure
573 * Min heap for removal upon reaching limit
575 struct GNUNET_CONTAINER_Heap *minHeap;
578 * Hashmap for fast key based lookup
580 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
585 * DHT structure for recent requests.
587 struct RecentRequests
590 * Min heap for removal upon reaching limit
592 struct GNUNET_CONTAINER_Heap *minHeap;
595 * Hashmap for key based lookup
597 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
603 * Position of this node in the min heap.
605 struct GNUNET_CONTAINER_HeapNode *heap_node;
608 * Bloomfilter containing entries for peers
609 * we forwarded this request to.
611 struct GNUNET_CONTAINER_BloomFilter *bloom;
614 * Timestamp of this request, for ordering
617 struct GNUNET_TIME_Absolute timestamp;
620 * Key of this request.
625 * Unique identifier for this request.
630 * Task to remove this entry on timeout.
632 GNUNET_SCHEDULER_TaskIdentifier remove_task;
637 * log of the current network size estimate, used as the point where
638 * we switch between random and deterministic routing. Default
639 * value of 4.0 is used if NSE module is not available (i.e. not
642 static double log_of_network_size_estimate = 4.0;
645 * Recent requests by hash/uid and by time inserted.
647 static struct RecentRequests recent;
650 * Context to use to calculate find peer rates.
652 static struct FindPeerMessageContext find_peer_context;
655 * Don't use our routing algorithm, always route
656 * to closest peer; initially send requests to 3
659 static int strict_kademlia;
662 * Routing option to end routing when closest peer found.
664 static int stop_on_closest;
667 * Routing option to end routing when data is found.
669 static int stop_on_found;
672 * Whether DHT needs to manage find peer requests, or
673 * an external force will do it on behalf of the DHT.
675 static int do_find_peer;
678 * Use exactly the forwarding formula as described in
679 * the paper if set to GNUNET_YES, otherwise use the
680 * slightly modified version.
682 static int paper_forwarding;
685 * PUT Peer Identities of peers we know about into
688 static int put_peer_identities;
691 * Use the "real" distance metric when selecting the
692 * next routing hop. Can be less accurate.
694 static int use_real_distance;
697 * How many peers have we added since we sent out our last
700 static unsigned int newly_found_peers;
703 * Container of active queries we should remember
705 static struct DHTResults forward_list;
708 * Handle to the datacache service (for inserting/retrieving data)
710 static struct GNUNET_DATACACHE_Handle *datacache;
713 * Handle for the statistics service.
715 struct GNUNET_STATISTICS_Handle *stats;
718 * Handle to get our current HELLO.
720 static struct GNUNET_TRANSPORT_GetHelloHandle *ghh;
723 * The configuration the DHT service is running with
725 static const struct GNUNET_CONFIGURATION_Handle *cfg;
728 * Handle to the core service
730 static struct GNUNET_CORE_Handle *coreAPI;
733 * Handle to the transport service, for getting our hello
735 static struct GNUNET_TRANSPORT_Handle *transport_handle;
738 * The identity of our peer.
740 static struct GNUNET_PeerIdentity my_identity;
743 * Short id of the peer, for printing
745 static char *my_short_id;
750 static struct GNUNET_MessageHeader *my_hello;
753 * Task to run when we shut down, cleaning up all our trash
755 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
758 * The lowest currently used bucket.
760 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
763 * The buckets (Kademlia routing table, complete with growth).
764 * Array of size MAX_BUCKET_SIZE.
766 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
769 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
771 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
774 * Recently seen find peer requests.
776 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
779 * Maximum size for each bucket.
781 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
784 * List of active clients.
786 static struct ClientList *client_list;
789 * Handle to the DHT logger.
791 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
794 * Whether or not to send routing debugging information
795 * to the dht logging server
797 static unsigned int debug_routes;
800 * Whether or not to send FULL route information to
803 static unsigned int debug_routes_extended;
806 * GNUNET_YES or GNUNET_NO, whether or not to act as
807 * a malicious node which drops all messages
809 static unsigned int malicious_dropper;
812 * GNUNET_YES or GNUNET_NO, whether or not to act as
813 * a malicious node which sends out lots of GETS
815 static unsigned int malicious_getter;
818 * GNUNET_YES or GNUNET_NO, whether or not to act as
819 * a malicious node which sends out lots of PUTS
821 static unsigned int malicious_putter;
824 * Frequency for malicious get requests.
826 static struct GNUNET_TIME_Relative malicious_get_frequency;
829 * Frequency for malicious put requests.
831 static struct GNUNET_TIME_Relative malicious_put_frequency;
834 * Kademlia replication
836 static unsigned long long kademlia_replication;
839 * Reply times for requests, if we are busy, don't send any
842 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
845 * Current counter for replies.
847 static unsigned int reply_counter;
850 * Our handle to the BLOCK library.
852 static struct GNUNET_BLOCK_Context *block_context;
855 * Network size estimation handle.
857 static struct GNUNET_NSE_Handle *nse;
861 * Callback that is called when network size estimate is updated.
864 * @param timestamp time when the estimate was received from the server (or created by the server)
865 * @param logestimate the log(Base 2) value of the current network size estimate
866 * @param std_dev standard deviation for the estimate
870 update_network_size_estimate (void *cls,
871 struct GNUNET_TIME_Absolute timestamp,
872 double logestimate, double std_dev)
874 log_of_network_size_estimate = logestimate;
881 * Forward declaration.
884 send_generic_reply (void *cls, size_t size, void *buf);
887 /** Declare here so retry_core_send is aware of it */
889 core_transmit_notify (void *cls, size_t size, void *buf);
893 * Convert unique ID to hash code.
895 * @param uid unique ID to convert
896 * @param hash set to uid (extended with zeros)
899 hash_from_uid (uint64_t uid, GNUNET_HashCode * hash)
901 memset (hash, 0, sizeof (GNUNET_HashCode));
902 *((uint64_t *) hash) = uid;
907 * Calculate the average send time between messages so that we can
908 * ignore certain requests if we get too busy.
910 * @return the average time between asking core to send a message
911 * and when the buffer for copying it is passed
913 static struct GNUNET_TIME_Relative
914 get_average_send_delay ()
917 unsigned int divisor;
918 struct GNUNET_TIME_Relative average_time;
920 average_time = GNUNET_TIME_relative_get_zero ();
922 for (i = 0; i < MAX_REPLY_TIMES; i++)
924 average_time = GNUNET_TIME_relative_add (average_time, reply_times[i]);
925 if (reply_times[i].abs_value == (uint64_t) 0)
935 average_time = GNUNET_TIME_relative_divide (average_time, divisor);
936 fprintf (stderr, "Avg send delay: %u sends is %llu\n", divisor,
937 (unsigned long long) average_time.abs_value);
943 * Given the largest send delay, artificially decrease it
944 * so the next time around we may have a chance at sending
948 decrease_max_send_delay (struct GNUNET_TIME_Relative max_time)
952 for (i = 0; i < MAX_REPLY_TIMES; i++)
954 if (reply_times[i].rel_value == max_time.rel_value)
956 reply_times[i].rel_value = reply_times[i].rel_value / 2;
963 * Find the maximum send time of the recently sent values.
965 * @return the average time between asking core to send a message
966 * and when the buffer for copying it is passed
968 static struct GNUNET_TIME_Relative
969 get_max_send_delay ()
972 struct GNUNET_TIME_Relative max_time;
974 max_time = GNUNET_TIME_relative_get_zero ();
976 for (i = 0; i < MAX_REPLY_TIMES; i++)
978 if (reply_times[i].rel_value > max_time.rel_value)
979 max_time.rel_value = reply_times[i].rel_value;
982 if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
983 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n",
984 (unsigned long long) max_time.rel_value);
990 increment_stats (const char *value)
994 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
999 decrement_stats (const char *value)
1003 GNUNET_STATISTICS_update (stats, value, -1, GNUNET_NO);
1008 * Try to send another message from our core send list
1011 try_core_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1013 struct PeerInfo *peer = cls;
1014 struct P2PPendingMessage *pending;
1017 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
1019 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1022 if (peer->th != NULL)
1023 return; /* Message send already in progress */
1025 pending = peer->head;
1026 if (pending != NULL)
1028 ssize = ntohs (pending->msg->size);
1030 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1031 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n",
1032 my_short_id, "DHT", ssize, GNUNET_i2s (&peer->id));
1034 pending->scheduled = GNUNET_TIME_absolute_get ();
1036 if (reply_counter >= MAX_REPLY_TIMES)
1039 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
1040 pending->importance,
1041 pending->timeout, &peer->id, ssize,
1042 &core_transmit_notify, peer);
1043 if (peer->th == NULL)
1044 increment_stats ("# notify transmit ready failed");
1049 * Function called to send a request out to another peer.
1050 * Called both for locally initiated requests and those
1051 * received from other peers.
1053 * @param msg the encapsulated message
1054 * @param peer the peer to forward the message to
1055 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1058 forward_result_message (const struct GNUNET_MessageHeader *msg,
1059 struct PeerInfo *peer,
1060 struct DHT_MessageContext *msg_ctx)
1062 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1063 struct P2PPendingMessage *pending;
1073 increment_stats (STAT_RESULT_FORWARDS);
1075 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs (msg->size) +
1076 (sizeof (struct GNUNET_PeerIdentity) * msg_ctx->path_history_len);
1077 GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1078 psize = sizeof (struct P2PPendingMessage) + msize;
1079 pending = GNUNET_malloc (psize);
1080 pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1081 pending->importance = DHT_SEND_PRIORITY;
1082 pending->timeout = GNUNET_TIME_relative_get_forever ();
1083 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *) pending->msg;
1084 result_message->header.size = htons (msize);
1085 result_message->header.type =
1086 htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1087 result_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1088 if (msg_ctx->path_history_len > 0)
1090 /* End of pending is where enc_msg starts */
1091 path_start = (char *) &pending[1];
1092 /* Offset by the size of the enc_msg */
1093 path_start += ntohs (msg->size);
1094 memcpy (path_start, msg_ctx->path_history,
1095 msg_ctx->path_history_len * (sizeof (struct GNUNET_PeerIdentity)));
1097 for (i = 0; i < msg_ctx->path_history_len; i++)
1100 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1101 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1102 "(forward_result) Key %s Found peer %d:%s\n",
1103 GNUNET_h2s (&msg_ctx->key), i,
1104 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1108 result_message->options = htonl (msg_ctx->msg_options);
1109 result_message->hop_count = htonl (msg_ctx->hop_count + 1);
1110 GNUNET_assert (GNUNET_OK ==
1111 GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1115 result_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1116 memcpy (&result_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1117 /* Copy the enc_msg, then the path history as well! */
1118 memcpy (&result_message[1], msg, ntohs (msg->size));
1119 path_offset = (char *) &result_message[1];
1120 path_offset += ntohs (msg->size);
1121 /* If we have path history, copy it to the end of the whole thing */
1122 if (msg_ctx->path_history_len > 0)
1123 memcpy (path_offset, msg_ctx->path_history,
1124 msg_ctx->path_history_len * (sizeof (struct GNUNET_PeerIdentity)));
1126 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1127 "%s:%s Adding pending message size %d for peer %s\n", my_short_id,
1128 "DHT", msize, GNUNET_i2s (&peer->id));
1130 peer->pending_count++;
1131 increment_stats ("# pending messages scheduled");
1132 GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1134 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1135 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1140 * Called when core is ready to send a message we asked for
1141 * out to the destination.
1143 * @param cls closure (NULL)
1144 * @param size number of bytes available in buf
1145 * @param buf where the callee should write the message
1146 * @return number of bytes written to buf
1149 core_transmit_notify (void *cls, size_t size, void *buf)
1151 struct PeerInfo *peer = cls;
1153 struct P2PPendingMessage *pending;
1161 /* client disconnected */
1163 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n",
1164 my_short_id, "DHT");
1169 if (peer->head == NULL)
1173 pending = peer->head;
1175 reply_times[reply_counter] =
1176 GNUNET_TIME_absolute_get_difference (pending->scheduled,
1177 GNUNET_TIME_absolute_get ());
1178 msize = ntohs (pending->msg->size);
1182 memcpy (cbuf, pending->msg, msize);
1183 peer->pending_count--;
1184 increment_stats ("# pending messages sent");
1185 GNUNET_assert (peer->pending_count >= 0);
1186 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1187 GNUNET_free (pending);
1190 while (NULL != pending &&
1191 (size - off >= (msize = ntohs (pending->msg->size))))
1193 memcpy (&cbuf[off], pending->msg, msize);
1195 peer->pending_count--;
1196 increment_stats ("# pending messages sent");
1197 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1198 GNUNET_free (pending);
1199 pending = peer->head;
1202 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1203 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1210 * Compute the distance between have and target as a 32-bit value.
1211 * Differences in the lower bits must count stronger than differences
1212 * in the higher bits.
1214 * @return 0 if have==target, otherwise a number
1215 * that is larger as the distance between
1216 * the two hash codes increases
1219 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1221 unsigned int bucket;
1226 /* We have to represent the distance between two 2^9 (=512)-bit
1227 * numbers as a 2^5 (=32)-bit number with "0" being used for the
1228 * two numbers being identical; furthermore, we need to
1229 * guarantee that a difference in the number of matching
1230 * bits is always represented in the result.
1232 * We use 2^32/2^9 numerical values to distinguish between
1233 * hash codes that have the same LSB bit distance and
1234 * use the highest 2^9 bits of the result to signify the
1235 * number of (mis)matching LSB bits; if we have 0 matching
1236 * and hence 512 mismatching LSB bits we return -1 (since
1237 * 512 itself cannot be represented with 9 bits) */
1239 /* first, calculate the most significant 9 bits of our
1240 * result, aka the number of LSBs */
1241 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1242 /* bucket is now a value between 0 and 512 */
1244 return 0; /* perfect match */
1246 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1247 * below, we'd end up with max+1 (overflow)) */
1249 /* calculate the most significant bits of the final result */
1250 msb = (512 - bucket) << (32 - 9);
1251 /* calculate the 32-9 least significant bits of the final result by
1252 * looking at the differences in the 32-9 bits following the
1253 * mismatching bit at 'bucket' */
1255 for (i = bucket + 1;
1256 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1258 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
1259 GNUNET_CRYPTO_hash_get_bit (have, i))
1260 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1261 * last bit set will be 31 -- if
1262 * i does not reach 512 first... */
1268 * Return a number that is larger the closer the
1269 * "have" GNUNET_hash code is to the "target".
1271 * @return inverse distance metric, non-zero.
1272 * Must fudge the value if NO bits match.
1275 inverse_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1277 if (GNUNET_CRYPTO_hash_matching_bits (target, have) == 0)
1278 return 1; /* Never return 0! */
1279 return ((unsigned int) -1) - distance (target, have);
1284 * Find the optimal bucket for this key, regardless
1285 * of the current number of buckets in use.
1287 * @param hc the hashcode to compare our identity to
1289 * @return the proper bucket index, or GNUNET_SYSERR
1290 * on error (same hashcode)
1293 find_bucket (const GNUNET_HashCode * hc)
1297 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
1298 if (bits == MAX_BUCKETS)
1299 return GNUNET_SYSERR;
1300 return MAX_BUCKETS - bits - 1;
1305 * Find which k-bucket this peer should go into,
1306 * taking into account the size of the k-bucket
1307 * array. This means that if more bits match than
1308 * there are currently buckets, lowest_bucket will
1311 * @param hc GNUNET_HashCode we are finding the bucket for.
1313 * @return the proper bucket index for this key,
1314 * or GNUNET_SYSERR on error (same hashcode)
1317 find_current_bucket (const GNUNET_HashCode * hc)
1321 actual_bucket = find_bucket (hc);
1322 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1323 return lowest_bucket;
1324 if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1325 return lowest_bucket;
1326 return actual_bucket;
1331 * Find a routing table entry from a peer identity
1333 * @param peer the peer to look up
1335 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1338 find_bucket_by_peer (const struct PeerInfo *peer)
1341 struct PeerInfo *pos;
1343 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1345 pos = k_buckets[bucket].head;
1354 return GNUNET_SYSERR; /* No such peer. */
1360 * Print the complete routing table for this peer.
1363 print_routing_table ()
1366 struct PeerInfo *pos;
1367 char char_buf[30000];
1370 memset (char_buf, 0, sizeof (char_buf));
1373 sprintf (&char_buf[char_pos], "Printing routing table for peer %s\n",
1375 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1376 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1378 pos = k_buckets[bucket].head;
1379 char_pos += sprintf (&char_buf[char_pos], "Bucket %d:\n", bucket);
1380 //fprintf(stderr, "Bucket %d:\n", bucket);
1383 //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));
1385 sprintf (&char_buf[char_pos],
1386 "\tPeer %s, best bucket %d, %d bits match\n",
1387 GNUNET_i2s (&pos->id), find_bucket (&pos->id.hashPubKey),
1388 GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey,
1389 &my_identity.hashPubKey));
1393 fprintf (stderr, "%s", char_buf);
1399 * Find a routing table entry from a peer identity
1401 * @param peer the peer identity to look up
1403 * @return the routing table entry, or NULL if not found
1405 static struct PeerInfo *
1406 find_peer_by_id (const struct GNUNET_PeerIdentity *peer)
1409 struct PeerInfo *pos;
1411 bucket = find_current_bucket (&peer->hashPubKey);
1413 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
1416 pos = k_buckets[bucket].head;
1419 if (0 == memcmp (&pos->id, peer, sizeof (struct GNUNET_PeerIdentity)))
1423 return NULL; /* No such peer. */
1426 /* Forward declaration */
1428 update_core_preference (void *cls,
1429 const struct GNUNET_SCHEDULER_TaskContext *tc);
1431 * Function called with statistics about the given peer.
1433 * @param cls closure
1434 * @param peer identifies the peer
1435 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1436 * @param amount set to the amount that was actually reserved or unreserved;
1437 * either the full requested amount or zero (no partial reservations)
1438 * @param res_delay if the reservation could not be satisfied (amount was 0), how
1439 * long should the client wait until re-trying?
1440 * @param preference current traffic preference for the given peer
1443 update_core_preference_finish (void *cls,
1444 const struct GNUNET_PeerIdentity *peer,
1445 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1447 struct GNUNET_TIME_Relative res_delay,
1448 uint64_t preference)
1450 struct PeerInfo *peer_info = cls;
1452 peer_info->info_ctx = NULL;
1453 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
1454 &update_core_preference, peer_info);
1458 update_core_preference (void *cls,
1459 const struct GNUNET_SCHEDULER_TaskContext *tc)
1461 struct PeerInfo *peer = cls;
1462 uint64_t preference;
1463 unsigned int matching;
1465 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1470 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
1471 &peer->id.hashPubKey);
1475 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1476 "Peer identifier matches by %u bits, only shifting as much as we can!\n",
1481 preference = 1LL << matching;
1483 GNUNET_CORE_peer_change_preference (coreAPI, &peer->id,
1484 GNUNET_TIME_UNIT_FOREVER_REL,
1485 GNUNET_BANDWIDTH_VALUE_MAX, 0,
1487 &update_core_preference_finish, peer);
1492 * Given a peer and its corresponding bucket,
1493 * remove it from that bucket. Does not free
1494 * the PeerInfo struct, nor cancel messages
1495 * or free messages waiting to be sent to this
1498 * @param peer the peer to remove
1499 * @param bucket the bucket the peer belongs to
1502 remove_peer (struct PeerInfo *peer, unsigned int bucket)
1504 GNUNET_assert (k_buckets[bucket].peers_size > 0);
1505 GNUNET_CONTAINER_DLL_remove (k_buckets[bucket].head, k_buckets[bucket].tail,
1507 k_buckets[bucket].peers_size--;
1509 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) &&
1510 (lowest_bucket < MAX_BUCKETS - 1))
1516 * Removes peer from a bucket, then frees associated
1517 * resources and frees peer.
1519 * @param peer peer to be removed and freed
1520 * @param bucket which bucket this peer belongs to
1523 delete_peer (struct PeerInfo *peer, unsigned int bucket)
1525 struct P2PPendingMessage *pos;
1526 struct P2PPendingMessage *next;
1529 struct PeerInfo *peer_pos;
1531 peer_pos = k_buckets[bucket].head;
1532 while ((peer_pos != NULL) && (peer_pos != peer))
1533 peer_pos = peer_pos->next;
1534 if (peer_pos == NULL)
1536 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1537 "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT",
1538 GNUNET_i2s (&peer->id), bucket);
1539 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1540 "%s:%s: Lowest bucket: %d, find_current_bucket: %d, peer resides in bucket: %d\n",
1541 my_short_id, "DHT", lowest_bucket,
1542 find_current_bucket (&peer->id.hashPubKey),
1543 find_bucket_by_peer (peer));
1545 GNUNET_assert (peer_pos != NULL);
1547 remove_peer (peer, bucket); /* First remove the peer from its bucket */
1549 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1550 GNUNET_SCHEDULER_cancel (peer->send_task);
1551 if ((peer->th != NULL) && (coreAPI != NULL))
1552 GNUNET_CORE_notify_transmit_ready_cancel (peer->th);
1555 while (pos != NULL) /* Remove any pending messages for this peer */
1558 ("# dht pending messages discarded (due to disconnect/shutdown)");
1564 GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
1565 (all_known_peers, &peer->id.hashPubKey));
1566 GNUNET_assert (GNUNET_YES ==
1567 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
1568 &peer->id.hashPubKey,
1571 decrement_stats (STAT_PEERS_KNOWN);
1576 * Iterator over hash map entries.
1578 * @param cls closure
1579 * @param key current key code
1580 * @param value PeerInfo of the peer to move to new lowest bucket
1581 * @return GNUNET_YES if we should continue to
1586 move_lowest_bucket (void *cls, const GNUNET_HashCode * key, void *value)
1588 struct PeerInfo *peer = value;
1591 GNUNET_assert (lowest_bucket > 0);
1592 new_bucket = lowest_bucket - 1;
1593 remove_peer (peer, lowest_bucket);
1594 GNUNET_CONTAINER_DLL_insert_after (k_buckets[new_bucket].head,
1595 k_buckets[new_bucket].tail,
1596 k_buckets[new_bucket].tail, peer);
1597 k_buckets[new_bucket].peers_size++;
1603 * The current lowest bucket is full, so change the lowest
1604 * bucket to the next lower down, and move any appropriate
1605 * entries in the current lowest bucket to the new bucket.
1608 enable_next_bucket ()
1610 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1611 struct PeerInfo *pos;
1613 GNUNET_assert (lowest_bucket > 0);
1614 to_remove = GNUNET_CONTAINER_multihashmap_create (bucket_size);
1615 pos = k_buckets[lowest_bucket].head;
1618 fprintf (stderr, "Printing RT before new bucket\n");
1619 print_routing_table ();
1621 /* Populate the array of peers which should be in the next lowest bucket */
1624 if (find_bucket (&pos->id.hashPubKey) < lowest_bucket)
1625 GNUNET_CONTAINER_multihashmap_put (to_remove, &pos->id.hashPubKey, pos,
1626 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1630 /* Remove peers from lowest bucket, insert into next lowest bucket */
1631 GNUNET_CONTAINER_multihashmap_iterate (to_remove, &move_lowest_bucket, NULL);
1632 GNUNET_CONTAINER_multihashmap_destroy (to_remove);
1633 lowest_bucket = lowest_bucket - 1;
1635 fprintf (stderr, "Printing RT after new bucket\n");
1636 print_routing_table ();
1641 * Find the closest peer in our routing table to the
1644 * @return The closest peer in our routing table to the
1645 * key, or NULL on error.
1647 static struct PeerInfo *
1648 find_closest_peer (const GNUNET_HashCode * hc)
1650 struct PeerInfo *pos;
1651 struct PeerInfo *current_closest;
1652 unsigned int lowest_distance;
1653 unsigned int temp_distance;
1657 lowest_distance = -1;
1659 if (k_buckets[lowest_bucket].peers_size == 0)
1662 current_closest = NULL;
1663 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1665 pos = k_buckets[bucket].head;
1667 while ((pos != NULL) && (count < bucket_size))
1669 temp_distance = distance (&pos->id.hashPubKey, hc);
1670 if (temp_distance <= lowest_distance)
1672 lowest_distance = temp_distance;
1673 current_closest = pos;
1679 GNUNET_assert (current_closest != NULL);
1680 return current_closest;
1685 * Function called to send a request out to another peer.
1686 * Called both for locally initiated requests and those
1687 * received from other peers.
1689 * @param msg the encapsulated message
1690 * @param peer the peer to forward the message to
1691 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1694 forward_message (const struct GNUNET_MessageHeader *msg, struct PeerInfo *peer,
1695 struct DHT_MessageContext *msg_ctx)
1697 struct GNUNET_DHT_P2PRouteMessage *route_message;
1698 struct P2PPendingMessage *pending;
1703 increment_stats (STAT_ROUTE_FORWARDS);
1704 GNUNET_assert (peer != NULL);
1705 if ((msg_ctx->closest != GNUNET_YES) &&
1706 (peer == find_closest_peer (&msg_ctx->key)))
1707 increment_stats (STAT_ROUTE_FORWARDS_CLOSEST);
1710 sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs (msg->size) +
1711 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1712 GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1713 psize = sizeof (struct P2PPendingMessage) + msize;
1714 pending = GNUNET_malloc (psize);
1715 pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1716 pending->importance = msg_ctx->importance;
1717 pending->timeout = msg_ctx->timeout;
1718 route_message = (struct GNUNET_DHT_P2PRouteMessage *) pending->msg;
1719 route_message->header.size = htons (msize);
1720 route_message->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1721 route_message->options = htonl (msg_ctx->msg_options);
1722 route_message->hop_count = htonl (msg_ctx->hop_count + 1);
1723 route_message->network_size = htonl (msg_ctx->network_size);
1724 route_message->desired_replication_level = htonl (msg_ctx->replication);
1725 route_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1726 if (msg_ctx->bloom != NULL)
1727 GNUNET_assert (GNUNET_OK ==
1728 GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1732 memcpy (&route_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1733 memcpy (&route_message[1], msg, ntohs (msg->size));
1734 if (GNUNET_DHT_RO_RECORD_ROUTE ==
1735 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
1737 route_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1738 /* Set pointer to start of enc_msg */
1739 route_path = (char *) &route_message[1];
1740 /* Offset to the end of the enc_msg */
1741 route_path += ntohs (msg->size);
1742 /* Copy the route_path after enc_msg */
1743 memcpy (route_path, msg_ctx->path_history,
1744 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1747 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1748 "%s:%s Adding pending message size %d for peer %s\n", my_short_id,
1749 "DHT", msize, GNUNET_i2s (&peer->id));
1751 peer->pending_count++;
1752 increment_stats ("# pending messages scheduled");
1753 GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1755 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1756 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1761 * Task used to send ping messages to peers so that
1762 * they don't get disconnected.
1764 * @param cls the peer to send a ping message to
1765 * @param tc context, reason, etc.
1768 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1770 struct PeerInfo *peer = cls;
1771 struct GNUNET_MessageHeader ping_message;
1772 struct DHT_MessageContext msg_ctx;
1774 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1777 ping_message.size = htons (sizeof (struct GNUNET_MessageHeader));
1778 ping_message.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1780 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
1782 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n",
1783 my_short_id, "DHT", GNUNET_i2s (&peer->id));
1785 forward_message (&ping_message, peer, &msg_ctx);
1787 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PING_DELAY, &periodic_ping_task,
1792 * Schedule PING messages for the top X peers in each
1793 * bucket of the routing table (so core won't disconnect them!)
1796 schedule_ping_messages ()
1798 unsigned int bucket;
1800 struct PeerInfo *pos;
1802 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1804 pos = k_buckets[bucket].head;
1808 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1809 GNUNET_SCHEDULER_add_now (&periodic_ping_task, pos);
1810 else if ((count >= bucket_size) &&
1811 (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1813 GNUNET_SCHEDULER_cancel (pos->ping_task);
1814 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1825 * Task run to check for messages that need to be sent to a client.
1827 * @param client a ClientList, containing the client and any messages to be sent to it
1830 process_pending_messages (struct ClientList *client)
1832 if (client->pending_head == NULL)
1834 if (client->transmit_handle != NULL)
1837 client->transmit_handle =
1838 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1839 ntohs (client->pending_head->
1841 GNUNET_TIME_UNIT_FOREVER_REL,
1842 &send_generic_reply, client);
1846 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1847 * request. A ClientList is passed as closure, take the head of the list
1848 * and copy it into buf, which has the result of sending the message to the
1851 * @param cls closure to this call
1852 * @param size maximum number of bytes available to send
1853 * @param buf where to copy the actual message to
1855 * @return the number of bytes actually copied, 0 indicates failure
1858 send_generic_reply (void *cls, size_t size, void *buf)
1860 struct ClientList *client = cls;
1862 struct PendingMessage *reply;
1866 client->transmit_handle = NULL;
1869 /* client disconnected */
1873 while ((NULL != (reply = client->pending_head)) &&
1874 (size >= off + (msize = ntohs (reply->msg->size))))
1876 GNUNET_CONTAINER_DLL_remove (client->pending_head, client->pending_tail,
1878 memcpy (&cbuf[off], reply->msg, msize);
1879 GNUNET_free (reply);
1882 process_pending_messages (client);
1884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1885 "Transmitted %u bytes of replies to client\n",
1886 (unsigned int) off);
1893 * Add a PendingMessage to the clients list of messages to be sent
1895 * @param client the active client to send the message to
1896 * @param pending_message the actual message to send
1899 add_pending_message (struct ClientList *client,
1900 struct PendingMessage *pending_message)
1902 GNUNET_CONTAINER_DLL_insert_after (client->pending_head, client->pending_tail,
1903 client->pending_tail, pending_message);
1904 process_pending_messages (client);
1909 * Called when a reply needs to be sent to a client, as
1910 * a result it found to a GET or FIND PEER request.
1912 * @param client the client to send the reply to
1913 * @param message the encapsulated message to send
1914 * @param msg_ctx the context of the received message
1917 send_reply_to_client (struct ClientList *client,
1918 const struct GNUNET_MessageHeader *message,
1919 struct DHT_MessageContext *msg_ctx)
1921 struct GNUNET_DHT_RouteResultMessage *reply;
1922 struct PendingMessage *pending_message;
1932 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': Sending reply to client.\n",
1933 my_short_id, "DHT");
1935 msize = ntohs (message->size);
1937 sizeof (struct GNUNET_DHT_RouteResultMessage) + msize +
1938 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1939 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1941 GNUNET_break_op (0);
1944 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1945 pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1946 reply = (struct GNUNET_DHT_RouteResultMessage *) &pending_message[1];
1947 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1948 reply->header.size = htons (tsize);
1949 reply->outgoing_path_length = htonl (msg_ctx->path_history_len);
1950 reply->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1951 memcpy (&reply->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1952 reply_offset = (char *) &reply[1];
1953 memcpy (&reply[1], message, msize);
1954 if (msg_ctx->path_history_len > 0)
1956 reply_offset += msize;
1957 memcpy (reply_offset, msg_ctx->path_history,
1958 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1961 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1962 "Returning message with outgoing path length %d\n",
1963 msg_ctx->path_history_len);
1964 for (i = 0; i < msg_ctx->path_history_len; i++)
1967 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1968 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found peer %d:%s\n", i,
1969 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1972 add_pending_message (client, pending_message);
1976 * Consider whether or not we would like to have this peer added to
1977 * our routing table. Check whether bucket for this peer is full,
1978 * if so return negative; if not return positive. Since peers are
1979 * only added on CORE level connect, this doesn't actually add the
1980 * peer to the routing table.
1982 * @param peer the peer we are considering adding
1984 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1988 consider_peer (struct GNUNET_PeerIdentity *peer)
1993 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
1994 &peer->hashPubKey)) ||
1995 (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity))))
1996 return GNUNET_NO; /* We already know this peer (are connected even!) */
1997 bucket = find_current_bucket (&peer->hashPubKey);
1999 if ((k_buckets[bucket].peers_size < bucket_size) ||
2000 ((bucket == lowest_bucket) && (lowest_bucket > 0)))
2008 * Task used to remove forwarding entries, either
2009 * after timeout, when full, or on shutdown.
2011 * @param cls the entry to remove
2012 * @param tc context, reason, etc.
2015 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2017 struct DHTRouteSource *source_info = cls;
2018 struct DHTQueryRecord *record;
2020 source_info = GNUNET_CONTAINER_heap_remove_node (source_info->hnode);
2021 record = source_info->record;
2022 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
2024 if (record->head == NULL) /* No more entries in DLL */
2026 GNUNET_assert (GNUNET_YES ==
2027 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
2028 &record->key, record));
2029 GNUNET_free (record);
2031 if (source_info->find_peers_responded != NULL)
2032 GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
2033 GNUNET_free (source_info);
2037 * Main function that handles whether or not to route a result
2038 * message to other peers, or to send to our local client.
2040 * @param msg the result message to be routed
2041 * @param msg_ctx context of the message we are routing
2043 * @return the number of peers the message was routed to,
2044 * GNUNET_SYSERR on failure
2047 route_result_message (struct GNUNET_MessageHeader *msg,
2048 struct DHT_MessageContext *msg_ctx)
2050 struct GNUNET_PeerIdentity new_peer;
2051 struct DHTQueryRecord *record;
2052 struct DHTRouteSource *pos;
2053 struct PeerInfo *peer_info;
2054 const struct GNUNET_MessageHeader *hello_msg;
2060 increment_stats (STAT_RESULTS);
2062 * If a find peer result message is received and contains a valid
2063 * HELLO for another peer, offer it to the transport service.
2065 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
2067 if (ntohs (msg->size) <= sizeof (struct GNUNET_MessageHeader))
2068 GNUNET_break_op (0);
2070 hello_msg = &msg[1];
2071 if ((ntohs (hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
2073 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello_msg,
2076 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2077 "%s:%s Received non-HELLO message type in find peer result message!\n",
2078 my_short_id, "DHT");
2079 GNUNET_break_op (0);
2082 else /* We have a valid hello, and peer id stored in new_peer */
2084 find_peer_context.count++;
2085 increment_stats (STAT_FIND_PEER_REPLY);
2086 if (GNUNET_YES == consider_peer (&new_peer))
2088 increment_stats (STAT_HELLOS_PROVIDED);
2089 GNUNET_TRANSPORT_offer_hello (transport_handle, hello_msg, NULL, NULL);
2090 GNUNET_CORE_peer_request_connect (coreAPI, &new_peer, NULL, NULL);
2095 if (malicious_dropper == GNUNET_YES)
2099 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
2101 if (record == NULL) /* No record of this message! */
2104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2105 "`%s:%s': Have no record of response key %s uid %llu\n",
2106 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2107 msg_ctx->unique_id);
2109 #if DEBUG_DHT_ROUTING
2110 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2112 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2113 msg_ctx->hop_count, GNUNET_SYSERR,
2114 &my_identity, &msg_ctx->key, msg_ctx->peer,
2118 if (msg_ctx->bloom != NULL)
2120 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
2121 msg_ctx->bloom = NULL;
2129 #if STRICT_FORWARDING
2130 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2133 GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded,
2134 &new_peer.hashPubKey))
2136 increment_stats ("# find peer responses NOT forwarded (bloom match)");
2141 GNUNET_CONTAINER_bloomfilter_add (pos->find_peers_responded,
2142 &new_peer.hashPubKey);
2146 if (0 == memcmp (&pos->source, &my_identity, sizeof (struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2150 "`%s:%s': Sending response key %s uid %llu to client\n",
2151 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2152 msg_ctx->unique_id);
2154 #if DEBUG_DHT_ROUTING
2155 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2157 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2158 msg_ctx->hop_count, GNUNET_YES,
2159 &my_identity, &msg_ctx->key, msg_ctx->peer,
2163 increment_stats (STAT_RESULTS_TO_CLIENT);
2164 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2165 increment_stats (STAT_GET_REPLY);
2167 for (i = 0; i < msg_ctx->path_history_len; i++)
2172 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
2173 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2174 "(before client) Key %s Found peer %d:%s\n",
2175 GNUNET_h2s (&msg_ctx->key), i,
2176 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
2179 send_reply_to_client (pos->client, msg, msg_ctx);
2181 else /* Send to peer */
2183 peer_info = find_peer_by_id (&pos->source);
2184 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2190 if (msg_ctx->bloom == NULL)
2192 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
2194 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
2195 &my_identity.hashPubKey);
2197 GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom,
2198 &peer_info->id.hashPubKey)))
2201 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2202 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n",
2203 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2204 msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2206 #if DEBUG_DHT_ROUTING
2207 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2209 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2210 msg_ctx->hop_count, GNUNET_NO,
2211 &my_identity, &msg_ctx->key,
2212 msg_ctx->peer, &pos->source);
2215 forward_result_message (msg, peer_info, msg_ctx);
2216 /* Try removing forward entries after sending once, only allows ONE response per request */
2217 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
2219 GNUNET_SCHEDULER_cancel (pos->delete_task);
2221 GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
2227 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2228 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n",
2229 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2230 msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2236 if (msg_ctx->bloom != NULL)
2238 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
2239 msg_ctx->bloom = NULL;
2246 * Iterator for local get request results,
2248 * @param cls closure for iterator, a DatacacheGetContext
2249 * @param exp when does this value expire?
2250 * @param key the key this data is stored under
2251 * @param size the size of the data identified by key
2252 * @param data the actual data
2253 * @param type the type of the data
2255 * @return GNUNET_OK to continue iteration, anything else
2256 * to stop iteration.
2259 datacache_get_iterator (void *cls, struct GNUNET_TIME_Absolute exp,
2260 const GNUNET_HashCode * key, size_t size,
2261 const char *data, enum GNUNET_BLOCK_Type type)
2263 struct DHT_MessageContext *msg_ctx = cls;
2264 struct DHT_MessageContext *new_msg_ctx;
2265 struct GNUNET_DHT_GetResultMessage *get_result;
2266 enum GNUNET_BLOCK_EvaluationResult eval;
2267 const struct DHTPutEntry *put_entry;
2276 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2277 "`%s:%s': Received `%s' response from datacache\n", my_short_id,
2281 put_entry = (const struct DHTPutEntry *) data;
2284 sizeof (struct DHTPutEntry) + put_entry->data_size +
2285 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)))
2287 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2288 "Path + data size doesn't add up for data inserted into datacache!\nData size %d, path length %d, expected %d, got %d\n",
2289 put_entry->data_size, put_entry->path_length,
2290 sizeof (struct DHTPutEntry) + put_entry->data_size +
2291 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)),
2293 msg_ctx->do_forward = GNUNET_NO;
2298 GNUNET_BLOCK_evaluate (block_context, type, key, &msg_ctx->reply_bf,
2299 msg_ctx->reply_bf_mutator, msg_ctx->xquery,
2300 msg_ctx->xquery_size, &put_entry[1],
2301 put_entry->data_size);
2305 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2306 msg_ctx->do_forward = GNUNET_NO;
2307 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2308 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2309 memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2310 if (GNUNET_DHT_RO_RECORD_ROUTE ==
2311 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2313 new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2314 new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2315 /* Assign to previous msg_ctx path history, caller should free after our return */
2316 new_msg_ctx->path_history = msg_ctx->path_history;
2318 for (i = 0; i < new_msg_ctx->path_history_len; i++)
2321 &new_msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
2322 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2323 "(get_iterator) Key %s Found peer %d:%s\n",
2324 GNUNET_h2s (&msg_ctx->key), i,
2325 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
2331 sizeof (struct GNUNET_DHT_GetResultMessage) + put_entry->data_size +
2332 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity));
2333 get_result = GNUNET_malloc (get_size);
2334 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2335 get_result->header.size = htons (get_size);
2336 get_result->expiration = GNUNET_TIME_absolute_hton (exp);
2337 get_result->type = htons (type);
2338 get_result->put_path_length = htons (put_entry->path_length);
2339 path_offset = (char *) &put_entry[1];
2340 path_offset += put_entry->data_size;
2342 for (i = 0; i < put_entry->path_length; i++)
2344 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2345 "(get_iterator PUT path) Key %s Found peer %d:%s\n",
2346 GNUNET_h2s (&msg_ctx->key), i,
2347 GNUNET_i2s ((struct GNUNET_PeerIdentity *)
2350 GNUNET_PeerIdentity)]));
2353 /* Copy the actual data and the path_history to the end of the get result */
2354 memcpy (&get_result[1], &put_entry[1],
2355 put_entry->data_size +
2356 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)));
2357 new_msg_ctx->peer = &my_identity;
2358 new_msg_ctx->bloom =
2359 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2360 new_msg_ctx->hop_count = 0;
2361 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
2362 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2363 increment_stats (STAT_GET_RESPONSE_START);
2364 route_result_message (&get_result->header, new_msg_ctx);
2365 GNUNET_free (new_msg_ctx);
2366 GNUNET_free (get_result);
2368 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': Duplicate block error\n",
2371 my_short_id, "DHT");
2374 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2376 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "`%s:%s': Invalid request error\n",
2377 my_short_id, "DHT");
2380 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2382 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2383 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2387 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2388 GNUNET_break_op (0);
2389 msg_ctx->do_forward = GNUNET_NO;
2391 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2393 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2394 "`%s:%s': Unsupported block type (%u) in response!\n",
2395 my_short_id, "DHT", type);
2397 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2405 * Main function that handles whether or not to route a message to other
2408 * @param msg the message to be routed
2409 * @param msg_ctx the context containing all pertinent information about the message
2412 route_message (const struct GNUNET_MessageHeader *msg,
2413 struct DHT_MessageContext *msg_ctx);
2417 * Server handler for all dht get requests, look for data,
2418 * if found, send response either to clients or other peers.
2420 * @param msg the actual get message
2421 * @param msg_ctx struct containing pertinent information about the get request
2423 * @return number of items found for GET request
2426 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2427 struct DHT_MessageContext *msg_ctx)
2429 const struct GNUNET_DHT_GetMessage *get_msg;
2432 unsigned int results;
2434 enum GNUNET_BLOCK_Type type;
2436 msize = ntohs (msg->size);
2437 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2442 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2443 bf_size = ntohs (get_msg->bf_size);
2444 msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2445 msg_ctx->reply_bf_mutator = get_msg->bf_mutator;
2447 sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2452 end = (const char *) &get_msg[1];
2453 if (msg_ctx->xquery_size == 0)
2455 msg_ctx->xquery = NULL;
2459 msg_ctx->xquery = (const void *) end;
2460 end += msg_ctx->xquery_size;
2464 msg_ctx->reply_bf = NULL;
2469 GNUNET_CONTAINER_bloomfilter_init (end, bf_size,
2470 GNUNET_DHT_GET_BLOOMFILTER_K);
2472 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2474 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2475 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2476 my_short_id, "DHT", "GET", type, GNUNET_h2s (&msg_ctx->key),
2477 msg_ctx->unique_id);
2479 increment_stats (STAT_GETS);
2482 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2484 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2488 msg_ctx->do_forward = GNUNET_YES;
2489 if (datacache != NULL)
2491 GNUNET_DATACACHE_get (datacache, &msg_ctx->key, type,
2492 &datacache_get_iterator, msg_ctx);
2494 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2495 "`%s:%s': Found %d results for `%s' request uid %llu\n",
2496 my_short_id, "DHT", results, "GET", msg_ctx->unique_id);
2500 #if DEBUG_DHT_ROUTING
2501 if ((debug_routes) && (dhtlog_handle != NULL))
2503 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2504 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2508 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2510 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2511 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2512 &msg_ctx->key, msg_ctx->peer, NULL);
2518 /* check query valid */
2519 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID ==
2520 GNUNET_BLOCK_evaluate (block_context, type, &msg_ctx->key,
2521 &msg_ctx->reply_bf, msg_ctx->reply_bf_mutator,
2522 msg_ctx->xquery, msg_ctx->xquery_size, NULL, 0))
2524 GNUNET_break_op (0);
2525 msg_ctx->do_forward = GNUNET_NO;
2529 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2531 #if DEBUG_DHT_ROUTING
2532 if ((debug_routes) && (dhtlog_handle != NULL))
2534 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2535 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2540 if (msg_ctx->do_forward == GNUNET_YES)
2541 route_message (msg, msg_ctx);
2542 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2547 remove_recent_find_peer (void *cls,
2548 const struct GNUNET_SCHEDULER_TaskContext *tc)
2550 GNUNET_HashCode *key = cls;
2552 GNUNET_assert (GNUNET_YES ==
2553 GNUNET_CONTAINER_multihashmap_remove
2554 (recent_find_peer_requests, key, NULL));
2559 * Server handler for initiating local dht find peer requests
2561 * @param find_msg the actual find peer message
2562 * @param msg_ctx struct containing pertinent information about the request
2566 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2567 struct DHT_MessageContext *msg_ctx)
2569 struct GNUNET_MessageHeader *find_peer_result;
2570 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2571 struct DHT_MessageContext *new_msg_ctx;
2572 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2575 GNUNET_HashCode *recent_hash;
2576 struct GNUNET_MessageHeader *other_hello;
2577 size_t other_hello_size;
2578 struct GNUNET_PeerIdentity peer_id;
2580 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *) find_msg;
2581 GNUNET_break_op (ntohs (find_msg->size) >=
2582 (sizeof (struct GNUNET_DHT_FindPeerMessage)));
2583 if (ntohs (find_msg->size) < sizeof (struct GNUNET_DHT_FindPeerMessage))
2586 other_hello_size = 0;
2587 if (ntohs (find_msg->size) > sizeof (struct GNUNET_DHT_FindPeerMessage))
2590 ntohs (find_msg->size) - sizeof (struct GNUNET_DHT_FindPeerMessage);
2591 other_hello = GNUNET_malloc (other_hello_size);
2592 memcpy (other_hello, &find_peer_message[1], other_hello_size);
2593 if ((GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) other_hello) == 0)
2595 GNUNET_HELLO_get_id ((struct GNUNET_HELLO_Message *) other_hello,
2598 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2599 "Received invalid HELLO message in find peer request!\n");
2600 GNUNET_free (other_hello);
2603 #if FIND_PEER_WITH_HELLO
2604 if (GNUNET_YES == consider_peer (&peer_id))
2606 increment_stats (STAT_HELLOS_PROVIDED);
2607 GNUNET_TRANSPORT_offer_hello (transport_handle, other_hello, NULL, NULL);
2608 GNUNET_CORE_peer_request_connect (coreAPI, &peer_id, NULL, NULL);
2609 route_message (find_msg, msg_ctx);
2610 GNUNET_free (other_hello);
2613 else /* We don't want this peer! */
2615 route_message (find_msg, msg_ctx);
2616 GNUNET_free (other_hello);
2623 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2624 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2625 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2626 ntohs (find_msg->size), sizeof (struct GNUNET_MessageHeader));
2628 if (my_hello == NULL)
2631 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2632 "`%s': Our HELLO is null, can't return.\n", "DHT");
2634 GNUNET_free_non_null (other_hello);
2635 route_message (find_msg, msg_ctx);
2640 GNUNET_CONTAINER_bloomfilter_init (find_peer_message->bloomfilter,
2641 DHT_BLOOM_SIZE, DHT_BLOOM_K);
2643 GNUNET_CONTAINER_bloomfilter_test (incoming_bloom,
2644 &my_identity.hashPubKey))
2646 increment_stats (STAT_BLOOM_FIND_PEER);
2647 GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2648 GNUNET_free_non_null (other_hello);
2649 route_message (find_msg, msg_ctx);
2650 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!) */
2652 GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2654 #if RESTRICT_FIND_PEER
2657 * Ignore any find peer requests from a peer we have seen very recently.
2659 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! */
2661 increment_stats ("# dht find peer requests ignored (recently seen!)");
2662 GNUNET_free_non_null (other_hello);
2667 * Use this check to only allow the peer to respond to find peer requests if
2668 * it would be beneficial to have the requesting peer in this peers routing
2669 * table. Can be used to thwart peers flooding the network with find peer
2670 * requests that we don't care about. However, if a new peer is joining
2671 * the network and has no other peers this is a problem (assume all buckets
2672 * full, no one will respond!).
2674 memcpy (&peer_id.hashPubKey, &msg_ctx->key, sizeof (GNUNET_HashCode));
2675 if (GNUNET_NO == consider_peer (&peer_id))
2677 increment_stats ("# dht find peer requests ignored (do not need!)");
2678 GNUNET_free_non_null (other_hello);
2679 route_message (find_msg, msg_ctx);
2684 recent_hash = GNUNET_malloc (sizeof (GNUNET_HashCode));
2685 memcpy (recent_hash, &msg_ctx->key, sizeof (GNUNET_HashCode));
2686 if (GNUNET_SYSERR !=
2687 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2688 &msg_ctx->key, NULL,
2689 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2692 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2693 "Adding recent remove task for key `%s`!\n",
2694 GNUNET_h2s (&msg_ctx->key));
2696 /* Only add a task if there wasn't one for this key already! */
2697 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2698 (GNUNET_TIME_UNIT_SECONDS, 30),
2699 &remove_recent_find_peer, recent_hash);
2703 GNUNET_free (recent_hash);
2705 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2706 "Received duplicate find peer request too soon!\n");
2710 /* Simplistic find_peer functionality, always return our hello */
2711 hello_size = ntohs (my_hello->size);
2712 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2714 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2716 GNUNET_break_op (0);
2717 GNUNET_free_non_null (other_hello);
2721 find_peer_result = GNUNET_malloc (tsize);
2722 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2723 find_peer_result->size = htons (tsize);
2724 memcpy (&find_peer_result[1], my_hello, hello_size);
2726 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2727 "`%s': Sending hello size %d to requesting peer.\n", "DHT",
2731 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2732 memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2733 new_msg_ctx->peer = &my_identity;
2734 new_msg_ctx->bloom =
2735 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2736 new_msg_ctx->hop_count = 0;
2737 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make find peer requests a higher priority */
2738 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2739 increment_stats (STAT_FIND_PEER_ANSWER);
2740 if (GNUNET_DHT_RO_RECORD_ROUTE ==
2741 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2743 new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2744 new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2745 /* Assign to previous msg_ctx path history, caller should free after our return */
2746 new_msg_ctx->path_history = msg_ctx->path_history;
2748 route_result_message (find_peer_result, new_msg_ctx);
2749 GNUNET_free (new_msg_ctx);
2750 #if DEBUG_DHT_ROUTING
2751 if ((debug_routes) && (dhtlog_handle != NULL))
2753 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2754 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2758 GNUNET_free_non_null (other_hello);
2759 GNUNET_free (find_peer_result);
2760 route_message (find_msg, msg_ctx);
2765 * Server handler for initiating local dht put requests
2767 * @param msg the actual put message
2768 * @param msg_ctx struct containing pertinent information about the request
2771 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2772 struct DHT_MessageContext *msg_ctx)
2774 const struct GNUNET_DHT_PutMessage *put_msg;
2775 struct DHTPutEntry *put_entry;
2776 unsigned int put_size;
2778 enum GNUNET_BLOCK_Type put_type;
2781 GNUNET_HashCode key;
2782 struct DHTQueryRecord *record;
2784 GNUNET_assert (ntohs (msg->size) >= sizeof (struct GNUNET_DHT_PutMessage));
2786 put_msg = (const struct GNUNET_DHT_PutMessage *) msg;
2787 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2789 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2791 #if DEBUG_DHT_ROUTING
2792 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2794 /** Log routes that die due to high load! */
2795 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2796 msg_ctx->hop_count, GNUNET_SYSERR,
2797 &my_identity, &msg_ctx->key, msg_ctx->peer,
2805 ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2807 GNUNET_BLOCK_get_key (block_context, put_type, &put_msg[1], data_size,
2809 if (GNUNET_NO == ret)
2811 #if DEBUG_DHT_ROUTING
2812 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2814 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2815 msg_ctx->hop_count, GNUNET_SYSERR,
2816 &my_identity, &msg_ctx->key, msg_ctx->peer,
2821 GNUNET_break_op (0);
2824 if ((GNUNET_YES == ret) &&
2825 (0 != memcmp (&key, &msg_ctx->key, sizeof (GNUNET_HashCode))))
2827 #if DEBUG_DHT_ROUTING
2828 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2830 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2831 msg_ctx->hop_count, GNUNET_SYSERR,
2832 &my_identity, &msg_ctx->key, msg_ctx->peer,
2836 /* invalid wrapper: key mismatch! */
2837 GNUNET_break_op (0);
2840 /* ret == GNUNET_SYSERR means that there is no known relationship between
2841 * data and the key, so we cannot check it */
2843 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2844 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2845 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2846 msg_ctx->unique_id);
2848 #if DEBUG_DHT_ROUTING
2849 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2851 if ((debug_routes) && (dhtlog_handle != NULL))
2853 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2854 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2860 // GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT 1\n");
2861 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2864 struct DHTRouteSource *pos;
2865 struct GNUNET_DHT_GetMessage *gmsg;
2868 // GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT 2\n");
2872 /* TODO: do only for local started requests? or also for remote peers? */
2873 /* TODO: include this in statistics? under what? */
2874 if (NULL == pos->client)
2877 gsize = data_size + sizeof(struct GNUNET_DHT_GetMessage);
2878 gmsg = GNUNET_malloc(gsize);
2879 gmsg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2880 gmsg->header.size = htons(gsize);
2881 gmsg->type = put_msg->type;
2882 memcpy(&gmsg[1], &put_msg[1], data_size);
2884 /* TODO: duplicate and reverse order of path_history? */
2885 send_reply_to_client (pos->client, &gmsg->header, msg_ctx);
2889 // GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT END\n");
2891 if (msg_ctx->closest != GNUNET_YES)
2893 route_message (msg, msg_ctx);
2898 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2899 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2900 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2901 msg_ctx->unique_id);
2904 #if DEBUG_DHT_ROUTING
2905 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2907 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2908 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2909 &msg_ctx->key, msg_ctx->peer, NULL);
2912 if ((debug_routes) && (dhtlog_handle != NULL))
2914 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2915 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2920 increment_stats (STAT_PUTS_INSERTED);
2921 if (datacache != NULL)
2923 /* Put size is actual data size plus struct overhead plus path length (if any) */
2925 data_size + sizeof (struct DHTPutEntry) +
2926 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2927 put_entry = GNUNET_malloc (put_size);
2928 put_entry->data_size = data_size;
2929 put_entry->path_length = msg_ctx->path_history_len;
2930 /* Copy data to end of put entry */
2931 memcpy (&put_entry[1], &put_msg[1], data_size);
2932 if (msg_ctx->path_history_len > 0)
2934 /* Copy path after data */
2935 path_offset = (char *) &put_entry[1];
2936 path_offset += data_size;
2937 memcpy (path_offset, msg_ctx->path_history,
2938 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2942 GNUNET_DATACACHE_put (datacache, &msg_ctx->key, put_size,
2943 (const char *) put_entry, put_type,
2944 GNUNET_TIME_absolute_ntoh (put_msg->expiration));
2945 GNUNET_free (put_entry);
2948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2949 "`%s:%s': %s request received, but have no datacache!\n",
2950 my_short_id, "DHT", "PUT");
2952 if (stop_on_closest == GNUNET_NO)
2953 route_message (msg, msg_ctx);
2958 * To how many peers should we (on average)
2959 * forward the request to obtain the desired
2960 * target_replication count (on average).
2962 * returns: target_replication / (est. hops) + (target_replication * hop_count)
2963 * where est. hops is typically 2 * the routing table depth
2965 * @param hop_count number of hops the message has traversed
2966 * @param target_replication the number of total paths desired
2968 * @return Some number of peers to forward the message to
2971 get_forward_count (unsigned int hop_count, size_t target_replication)
2973 uint32_t random_value;
2974 unsigned int forward_count;
2978 * If we are behaving in strict kademlia mode, send multiple initial requests,
2979 * but then only send to 1 or 0 peers based strictly on the number of hops.
2981 if (strict_kademlia == GNUNET_YES)
2984 return kademlia_replication;
2985 if (hop_count < log_of_network_size_estimate * 2.0)
2990 if (hop_count > log_of_network_size_estimate * 2.0)
2992 if (GNUNET_YES == paper_forwarding)
2994 /* Once we have reached our ideal number of hops, don't stop forwarding! */
2998 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2999 "Hop count too high (est %f, lowest %d), NOT Forwarding request\n",
3000 log_of_network_size_estimate * 2.0, lowest_bucket);
3005 if (GNUNET_YES == paper_forwarding)
3007 /* FIXME: re-run replication trials with this formula */
3009 1 + (target_replication - 1.0) / (log_of_network_size_estimate +
3010 ((float) (target_replication - 1.0) *
3012 /* Set forward count to floor of target_value */
3013 forward_count = (unsigned int) target_value;
3014 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
3015 target_value = target_value - forward_count;
3017 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
3019 if (random_value < (target_value * UINT32_MAX))
3027 target_replication / (log_of_network_size_estimate +
3028 ((float) target_replication * hop_count));
3029 if (target_value > 1)
3031 /* Set forward count to floor of target_value */
3032 forward_count = (unsigned int) target_value;
3033 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
3034 target_value = target_value - forward_count;
3038 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
3040 if (random_value < (target_value * UINT32_MAX))
3044 return forward_count;
3049 * Check whether my identity is closer than any known peers.
3050 * If a non-null bloomfilter is given, check if this is the closest
3051 * peer that hasn't already been routed to.
3053 * @param target hash code to check closeness to
3054 * @param bloom bloomfilter, exclude these entries from the decision
3055 * @return GNUNET_YES if node location is closest,
3056 * GNUNET_NO otherwise.
3059 am_closest_peer (const GNUNET_HashCode * target,
3060 struct GNUNET_CONTAINER_BloomFilter *bloom)
3066 struct PeerInfo *pos;
3067 unsigned int my_distance;
3069 if (0 == memcmp (&my_identity.hashPubKey, target, sizeof (GNUNET_HashCode)))
3072 bucket_num = find_current_bucket (target);
3074 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, target);
3075 my_distance = distance (&my_identity.hashPubKey, target);
3076 pos = k_buckets[bucket_num].head;
3078 while ((pos != NULL) && (count < bucket_size))
3080 if ((bloom != NULL) &&
3082 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
3085 continue; /* Skip already checked entries */
3088 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, target);
3089 if (other_bits > bits)
3091 else if (other_bits == bits) /* We match the same number of bits */
3093 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
3095 if (distance (&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
3101 /* No peers closer, we are the closest! */
3107 * Select a peer from the routing table that would be a good routing
3108 * destination for sending a message for "target". The resulting peer
3109 * must not be in the set of blocked peers.<p>
3111 * Note that we should not ALWAYS select the closest peer to the
3112 * target, peers further away from the target should be chosen with
3113 * exponentially declining probability.
3115 * @param target the key we are selecting a peer to route to
3116 * @param bloom a bloomfilter containing entries this request has seen already
3117 * @param hops how many hops has this message traversed thus far
3119 * @return Peer to route to, or NULL on error
3121 static struct PeerInfo *
3122 select_peer (const GNUNET_HashCode * target,
3123 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
3127 unsigned int selected;
3128 struct PeerInfo *pos;
3129 unsigned int distance;
3130 unsigned int largest_distance;
3131 struct PeerInfo *chosen;
3133 /** If we are doing kademlia routing (saves some cycles) */
3134 if ( (strict_kademlia == GNUNET_YES) ||
3135 (hops >= log_of_network_size_estimate) )
3137 /* greedy selection (closest peer that is not in bloomfilter) */
3138 largest_distance = 0;
3140 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3142 pos = k_buckets[bc].head;
3144 while ((pos != NULL) && (count < bucket_size))
3146 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
3148 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3150 distance = inverse_distance (target, &pos->id.hashPubKey);
3151 if (distance > largest_distance)
3154 largest_distance = distance;
3161 if ((largest_distance > 0) && (chosen != NULL))
3163 GNUNET_CONTAINER_bloomfilter_add (bloom, &chosen->id.hashPubKey);
3166 return NULL; /* no peer available or we are the closest */
3170 /* select "random" peer */
3171 /* count number of peers that are available and not filtered */
3173 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3175 pos = k_buckets[bc].head;
3176 while ((pos != NULL) && (count < bucket_size))
3179 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3182 continue; /* Ignore bloomfiltered peers */
3188 if (count == 0) /* No peers to select from! */
3190 increment_stats ("# failed to select peer");
3193 /* Now actually choose a peer */
3195 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
3197 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3199 pos = k_buckets[bc].head;
3200 while ((pos != NULL) && (count < bucket_size))
3203 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3206 continue; /* Ignore bloomfiltered peers */
3219 * Task used to remove recent entries, either
3220 * after timeout, when full, or on shutdown.
3222 * @param cls the entry to remove
3223 * @param tc context, reason, etc.
3226 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3228 struct RecentRequest *req = cls;
3229 static GNUNET_HashCode hash;
3231 GNUNET_assert (req != NULL);
3232 hash_from_uid (req->uid, &hash);
3233 GNUNET_assert (GNUNET_YES ==
3234 GNUNET_CONTAINER_multihashmap_remove (recent.hashmap, &hash,
3236 GNUNET_CONTAINER_heap_remove_node (req->heap_node);
3237 GNUNET_CONTAINER_bloomfilter_free (req->bloom);
3241 * if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3243 * GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3244 * GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3250 * Remember this routing request so that if a reply is
3251 * received we can either forward it to the correct peer
3252 * or return the result locally.
3254 * @param msg_ctx Context of the route request
3256 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3259 cache_response (struct DHT_MessageContext *msg_ctx)
3261 struct DHTQueryRecord *record;
3262 struct DHTRouteSource *source_info;
3263 struct DHTRouteSource *pos;
3264 struct GNUNET_TIME_Absolute now;
3265 unsigned int current_size;
3267 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3269 #if DELETE_WHEN_FULL
3270 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3272 source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3273 GNUNET_assert (source_info != NULL);
3274 record = source_info->record;
3275 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3276 if (record->head == NULL) /* No more entries in DLL */
3278 GNUNET_assert (GNUNET_YES ==
3279 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
3282 GNUNET_free (record);
3284 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3286 GNUNET_SCHEDULER_cancel (source_info->delete_task);
3287 source_info->delete_task = GNUNET_SCHEDULER_NO_TASK;
3289 if (source_info->find_peers_responded != NULL)
3290 GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
3291 GNUNET_free (source_info);
3292 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3295 /** Non-local request and have too many outstanding forwards, discard! */
3296 if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3299 now = GNUNET_TIME_absolute_get ();
3301 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
3302 if (record != NULL) /* Already know this request! */
3307 if ( (NULL != msg_ctx->peer) &&
3309 memcmp (msg_ctx->peer, &pos->source,
3310 sizeof (struct GNUNET_PeerIdentity))) )
3311 break; /* Already have this peer in reply list! */
3314 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3316 GNUNET_CONTAINER_heap_update_cost (forward_list.minHeap, pos->hnode,
3323 record = GNUNET_malloc (sizeof (struct DHTQueryRecord));
3324 GNUNET_assert (GNUNET_OK ==
3325 GNUNET_CONTAINER_multihashmap_put (forward_list.hashmap,
3326 &msg_ctx->key, record,
3327 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3328 memcpy (&record->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3331 source_info = GNUNET_malloc (sizeof (struct DHTRouteSource));
3332 source_info->record = record;
3333 source_info->delete_task =
3334 GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry,
3336 source_info->find_peers_responded =
3337 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3338 memcpy (&source_info->source, msg_ctx->peer,
3339 sizeof (struct GNUNET_PeerIdentity));
3340 GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail,
3342 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3344 source_info->client = msg_ctx->client;
3345 now = GNUNET_TIME_absolute_get_forever ();
3347 source_info->hnode =
3348 GNUNET_CONTAINER_heap_insert (forward_list.minHeap, source_info,
3351 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3352 "`%s:%s': Created new forward source info for %s uid %llu\n",
3353 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3354 msg_ctx->unique_id);
3361 * Main function that handles whether or not to route a message to other
3364 * @param msg the message to be routed
3365 * @param msg_ctx the context containing all pertinent information about the message
3368 route_message (const struct GNUNET_MessageHeader *msg,
3369 struct DHT_MessageContext *msg_ctx)
3372 struct PeerInfo *selected;
3374 #if DEBUG_DHT_ROUTING > 1
3375 struct PeerInfo *nearest;
3377 unsigned int target_forward_count;
3378 unsigned int forward_count;
3379 struct RecentRequest *recent_req;
3380 GNUNET_HashCode unique_hash;
3381 char *stat_forward_count;
3382 char *temp_stat_str;
3384 #if DEBUG_DHT_ROUTING
3388 if (malicious_dropper == GNUNET_YES)
3390 #if DEBUG_DHT_ROUTING
3391 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3393 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3394 msg_ctx->hop_count, GNUNET_SYSERR,
3395 &my_identity, &msg_ctx->key, msg_ctx->peer,
3399 if (msg_ctx->bloom != NULL)
3401 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3402 msg_ctx->bloom = NULL;
3407 increment_stats (STAT_ROUTES);
3408 target_forward_count =
3409 get_forward_count (msg_ctx->hop_count, msg_ctx->replication);
3410 GNUNET_asprintf (&stat_forward_count, "# forward counts of %d",
3411 target_forward_count);
3412 increment_stats (stat_forward_count);
3413 GNUNET_free (stat_forward_count);
3414 if (msg_ctx->bloom == NULL)
3416 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3418 if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) &&
3419 (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3420 target_forward_count = 0;
3423 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3424 * any closer peers (which is being checked for below). Since we are doing recursive
3425 * routing we have no choice but to stop forwarding in this case. This means that at
3426 * any given step the request may NOT be forwarded to alpha peers (because routes will
3427 * stop and the parallel route will not be aware of it). Of course, assuming that we
3428 * have fulfilled the Kademlia requirements for routing table fullness this will never
3429 * ever ever be a problem.
3431 * However, is this fair?
3433 * Since we use these requests to build our routing tables (and we build them in the
3434 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3435 * routing tables still get constructed.
3437 if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) &&
3438 (msg_ctx->hop_count > 0) &&
3439 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3440 target_forward_count = 0;
3443 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3444 hash_from_uid (msg_ctx->unique_id, &unique_hash);
3446 GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3449 GNUNET_CONTAINER_multihashmap_get (recent.hashmap, &unique_hash);
3450 GNUNET_assert (recent_req != NULL);
3451 if (0 != memcmp (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode)))
3452 increment_stats (STAT_DUPLICATE_UID);
3455 increment_stats (STAT_RECENT_SEEN);
3456 GNUNET_CONTAINER_bloomfilter_or2 (msg_ctx->bloom, recent_req->bloom,
3462 recent_req = GNUNET_malloc (sizeof (struct RecentRequest));
3463 recent_req->uid = msg_ctx->unique_id;
3464 memcpy (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3465 recent_req->remove_task =
3466 GNUNET_SCHEDULER_add_delayed (DEFAULT_RECENT_REMOVAL, &remove_recent,
3468 recent_req->heap_node =
3469 GNUNET_CONTAINER_heap_insert (recent.minHeap, recent_req,
3470 GNUNET_TIME_absolute_get ().abs_value);
3472 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3473 GNUNET_CONTAINER_multihashmap_put (recent.hashmap, &unique_hash, recent_req,
3474 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3477 if (GNUNET_CONTAINER_multihashmap_size (recent.hashmap) > DHT_MAX_RECENT)
3479 recent_req = GNUNET_CONTAINER_heap_peek (recent.minHeap);
3480 GNUNET_assert (recent_req != NULL);
3481 GNUNET_SCHEDULER_cancel (recent_req->remove_task);
3482 GNUNET_SCHEDULER_add_now (&remove_recent, recent_req);
3486 for (i = 0; i < target_forward_count; i++)
3488 selected = select_peer (&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3490 if (selected != NULL)
3493 if (GNUNET_CRYPTO_hash_matching_bits
3494 (&selected->id.hashPubKey,
3496 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
3498 GNUNET_asprintf (&temp_stat_str,
3499 "# requests routed to close(r) peer hop %u",
3500 msg_ctx->hop_count);
3502 GNUNET_asprintf (&temp_stat_str,
3503 "# requests routed to less close peer hop %u",
3504 msg_ctx->hop_count);
3505 if (temp_stat_str != NULL)
3507 increment_stats (temp_stat_str);
3508 GNUNET_free (temp_stat_str);
3510 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
3511 &selected->id.hashPubKey);
3512 #if DEBUG_DHT_ROUTING > 1
3513 nearest = find_closest_peer (&msg_ctx->key);
3514 nearest_buf = GNUNET_strdup (GNUNET_i2s (&nearest->id));
3515 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3516 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n",
3517 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3518 msg_ctx->unique_id, GNUNET_i2s (&selected->id), nearest_buf,
3519 GNUNET_CRYPTO_hash_matching_bits (&nearest->id.hashPubKey,
3521 distance (&nearest->id.hashPubKey, msg_ctx->key));
3522 GNUNET_free (nearest_buf);
3524 #if DEBUG_DHT_ROUTING
3525 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3527 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3528 msg_ctx->hop_count, GNUNET_NO,
3529 &my_identity, &msg_ctx->key, msg_ctx->peer,
3533 forward_message (msg, selected, msg_ctx);
3537 if (msg_ctx->bloom != NULL)
3539 GNUNET_CONTAINER_bloomfilter_or2 (recent_req->bloom, msg_ctx->bloom,
3541 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3542 msg_ctx->bloom = NULL;
3545 #if DEBUG_DHT_ROUTING
3546 if (forward_count == 0)
3547 ret = GNUNET_SYSERR;
3551 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3553 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3554 msg_ctx->hop_count, ret, &my_identity,
3555 &msg_ctx->key, msg_ctx->peer, NULL);
3562 * Main function that handles whether or not to route a message to other
3565 * @param msg the message to be routed
3566 * @param msg_ctx the context containing all pertinent information about the message
3569 demultiplex_message (const struct GNUNET_MessageHeader *msg,
3570 struct DHT_MessageContext *msg_ctx)
3572 /* FIXME: Should we use closest excluding those we won't route to (the bloomfilter problem)? */
3573 msg_ctx->closest = am_closest_peer (&msg_ctx->key, msg_ctx->bloom);
3575 switch (ntohs (msg->type))
3577 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3578 cache_response (msg_ctx);
3579 handle_dht_get (msg, msg_ctx);
3581 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3582 increment_stats (STAT_PUTS);
3583 handle_dht_put (msg, msg_ctx);
3585 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3586 increment_stats (STAT_FIND_PEER);
3587 if (((msg_ctx->hop_count > 0) &&
3589 memcmp (msg_ctx->peer, &my_identity,
3590 sizeof (struct GNUNET_PeerIdentity)))) ||
3591 (msg_ctx->client != NULL))
3593 cache_response (msg_ctx);
3594 if ((msg_ctx->closest == GNUNET_YES) ||
3595 (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3596 handle_dht_find_peer (msg, msg_ctx);
3599 route_message (msg, msg_ctx);
3600 #if DEBUG_DHT_ROUTING
3601 if (msg_ctx->hop_count == 0) /* Locally initiated request */
3603 if ((debug_routes) && (dhtlog_handle != NULL))
3605 dhtlog_handle->insert_dhtkey (NULL, &msg_ctx->key);
3606 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
3607 msg_ctx->hop_count, GNUNET_NO,
3608 &my_identity, &msg_ctx->key);
3614 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3615 "`%s': Message type (%d) not handled, forwarding anyway!\n",
3616 "DHT", ntohs (msg->type));
3617 route_message (msg, msg_ctx);
3623 * Iterator over hash map entries.
3625 * @param cls client to search for in source routes
3626 * @param key current key code (ignored)
3627 * @param value value in the hash map, a DHTQueryRecord
3628 * @return GNUNET_YES if we should continue to
3633 find_client_records (void *cls, const GNUNET_HashCode * key, void *value)
3635 struct ClientList *client = cls;
3636 struct DHTQueryRecord *record = value;
3637 struct DHTRouteSource *pos;
3642 if (pos->client == client)
3648 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, pos);
3649 GNUNET_CONTAINER_heap_remove_node (pos->hnode);
3650 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3652 GNUNET_SCHEDULER_cancel (pos->delete_task);
3653 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
3655 if (pos->find_peers_responded != NULL)
3656 GNUNET_CONTAINER_bloomfilter_free (pos->find_peers_responded);
3659 if (record->head == NULL) /* No more entries in DLL */
3661 GNUNET_assert (GNUNET_YES ==
3662 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
3663 &record->key, record));
3664 GNUNET_free (record);
3670 * Functions with this signature are called whenever a client
3671 * is disconnected on the network level.
3673 * @param cls closure (NULL for dht)
3674 * @param client identification of the client; NULL
3675 * for the last call when the server is destroyed
3678 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
3680 struct ClientList *pos = client_list;
3681 struct ClientList *prev;
3682 struct ClientList *found;
3683 struct PendingMessage *reply;
3689 if (pos->client_handle == client)
3692 prev->next = pos->next;
3694 client_list = pos->next;
3704 if (found->transmit_handle != NULL)
3705 GNUNET_CONNECTION_notify_transmit_ready_cancel (found->transmit_handle);
3707 while (NULL != (reply = found->pending_head))
3709 GNUNET_CONTAINER_DLL_remove (found->pending_head, found->pending_tail,
3711 GNUNET_free (reply);
3713 GNUNET_CONTAINER_multihashmap_iterate (forward_list.hashmap,
3714 &find_client_records, found);
3715 GNUNET_free (found);
3720 * Find a client if it exists, add it otherwise.
3722 * @param client the server handle to the client
3724 * @return the client if found, a new client otherwise
3726 static struct ClientList *
3727 find_active_client (struct GNUNET_SERVER_Client *client)
3729 struct ClientList *pos = client_list;
3730 struct ClientList *ret;
3734 if (pos->client_handle == client)
3739 ret = GNUNET_malloc (sizeof (struct ClientList));
3740 ret->client_handle = client;
3741 ret->next = client_list;
3749 * Task to send a malicious put message across the network.
3751 * @param cls closure for this task
3752 * @param tc the context under which the task is running
3755 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3757 static struct GNUNET_DHT_PutMessage put_message;
3758 static struct DHT_MessageContext msg_ctx;
3759 static GNUNET_HashCode key;
3760 uint32_t random_key;
3762 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3764 put_message.header.size = htons (sizeof (struct GNUNET_DHT_PutMessage));
3765 put_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3766 put_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3767 put_message.expiration =
3768 GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_forever ());
3769 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3771 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
3772 GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
3773 memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
3775 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
3776 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
3777 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3778 msg_ctx.msg_options = ntohl (0);
3779 msg_ctx.network_size = log_of_network_size_estimate;
3780 msg_ctx.peer = &my_identity;
3781 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3782 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3783 #if DEBUG_DHT_ROUTING
3784 if (dhtlog_handle != NULL)
3785 dhtlog_handle->insert_dhtkey (NULL, &key);
3787 increment_stats (STAT_PUT_START);
3788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3789 "%s:%s Sending malicious PUT message with hash %s\n", my_short_id,
3790 "DHT", GNUNET_h2s (&key));
3791 demultiplex_message (&put_message.header, &msg_ctx);
3792 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
3793 (GNUNET_TIME_UNIT_MILLISECONDS,
3794 malicious_put_frequency), &malicious_put_task,
3800 * Task to send a malicious put message across the network.
3802 * @param cls closure for this task
3803 * @param tc the context under which the task is running
3806 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3808 static struct GNUNET_DHT_GetMessage get_message;
3809 struct DHT_MessageContext msg_ctx;
3810 static GNUNET_HashCode key;
3811 uint32_t random_key;
3813 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3816 get_message.header.size = htons (sizeof (struct GNUNET_DHT_GetMessage));
3817 get_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET);
3818 get_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3819 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3821 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
3822 GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
3823 memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
3825 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
3826 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
3827 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3828 msg_ctx.msg_options = ntohl (0);
3829 msg_ctx.network_size = log_of_network_size_estimate;
3830 msg_ctx.peer = &my_identity;
3831 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3832 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3833 #if DEBUG_DHT_ROUTING
3834 if (dhtlog_handle != NULL)
3835 dhtlog_handle->insert_dhtkey (NULL, &key);
3837 increment_stats (STAT_GET_START);
3838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3839 "%s:%s Sending malicious GET message with hash %s\n", my_short_id,
3840 "DHT", GNUNET_h2s (&key));
3841 demultiplex_message (&get_message.header, &msg_ctx);
3842 GNUNET_SCHEDULER_add_delayed (malicious_get_frequency,
3843 &malicious_get_task, NULL);
3849 * Iterator over hash map entries.
3851 * @param cls closure
3852 * @param key current key code
3853 * @param value value in the hash map
3854 * @return GNUNET_YES if we should continue to
3859 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
3861 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3863 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3868 * Task to send a find peer message for our own peer identifier
3869 * so that we can find the closest peers in the network to ourselves
3870 * and attempt to connect to them.
3872 * @param cls closure for this task
3873 * @param tc the context under which the task is running
3876 send_find_peer_message (void *cls,
3877 const struct GNUNET_SCHEDULER_TaskContext *tc)
3879 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3880 struct DHT_MessageContext msg_ctx;
3881 struct GNUNET_TIME_Relative next_send_time;
3882 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3885 struct GNUNET_TIME_Relative time_diff;
3886 struct GNUNET_TIME_Absolute end;
3888 double count_per_interval;
3890 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3893 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! */
3895 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3896 "Have %d newly found peers since last find peer message sent!\n",
3898 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3899 &send_find_peer_message, NULL);
3900 newly_found_peers = 0;
3904 increment_stats (STAT_FIND_PEER_START);
3906 end = GNUNET_TIME_absolute_get ();
3908 GNUNET_TIME_absolute_get_difference (find_peer_context.start, end);
3910 if (time_diff.abs_value > FIND_PEER_CALC_INTERVAL.abs_value)
3912 multiplier = time_diff.abs_value / FIND_PEER_CALC_INTERVAL.abs_value;
3913 count_per_interval = find_peer_context.count / multiplier;
3917 multiplier = FIND_PEER_CALC_INTERVAL.abs_value / time_diff.abs_value;
3918 count_per_interval = find_peer_context.count * multiplier;
3922 #if FIND_PEER_WITH_HELLO
3924 GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage) +
3925 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *)
3927 find_peer_msg->header.size =
3928 htons (sizeof (struct GNUNET_DHT_FindPeerMessage) +
3929 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
3930 memcpy (&find_peer_msg[1], my_hello,
3931 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
3933 find_peer_msg = GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage));
3934 find_peer_msg->header.size =
3935 htons (sizeof (struct GNUNET_DHT_FindPeerMessage));
3937 find_peer_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3939 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3940 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
3942 GNUNET_assert (GNUNET_OK ==
3943 GNUNET_CONTAINER_bloomfilter_get_raw_data (temp_bloom,
3947 GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
3948 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3949 memcpy (&msg_ctx.key, &my_identity.hashPubKey, sizeof (GNUNET_HashCode));
3951 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
3952 (GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX));
3953 msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3954 msg_ctx.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3955 msg_ctx.network_size = log_of_network_size_estimate;
3956 msg_ctx.peer = &my_identity;
3957 msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3958 msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3960 demultiplex_message (&find_peer_msg->header, &msg_ctx);
3961 GNUNET_free (find_peer_msg);
3962 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3963 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id,
3964 "DHT", "FIND PEER");
3965 if (newly_found_peers < bucket_size)
3967 next_send_time.rel_value =
3968 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
3969 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
3970 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
3974 next_send_time.rel_value =
3975 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
3976 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
3977 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value -
3978 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
3981 GNUNET_assert (next_send_time.rel_value != 0);
3982 find_peer_context.count = 0;
3983 newly_found_peers = 0;
3984 find_peer_context.start = GNUNET_TIME_absolute_get ();
3985 if (GNUNET_YES == do_find_peer)
3987 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
3993 * Handler for any generic DHT messages, calls the appropriate handler
3994 * depending on message type, sends confirmation if responses aren't otherwise
3997 * @param cls closure for the service
3998 * @param client the client we received this message from
3999 * @param message the actual message received
4002 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
4003 const struct GNUNET_MessageHeader *message)
4005 const struct GNUNET_DHT_RouteMessage *dht_msg =
4006 (const struct GNUNET_DHT_RouteMessage *) message;
4007 const struct GNUNET_MessageHeader *enc_msg;
4008 struct DHT_MessageContext msg_ctx;
4010 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
4012 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4013 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
4014 my_short_id, "DHT", "GENERIC", ntohs (message->type),
4015 GNUNET_h2s (&dht_msg->key), GNUNET_ntohll (dht_msg->unique_id));
4017 #if DEBUG_DHT_ROUTING
4018 if (dhtlog_handle != NULL)
4019 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
4022 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4023 msg_ctx.client = find_active_client (client);
4024 memcpy (&msg_ctx.key, &dht_msg->key, sizeof (GNUNET_HashCode));
4025 msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
4026 msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
4027 msg_ctx.msg_options = ntohl (dht_msg->options);
4028 if (GNUNET_DHT_RO_RECORD_ROUTE ==
4029 (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
4031 msg_ctx.path_history = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
4032 memcpy (msg_ctx.path_history, &my_identity,
4033 sizeof (struct GNUNET_PeerIdentity));
4034 msg_ctx.path_history_len = 1;
4036 msg_ctx.network_size = log_of_network_size_estimate;
4037 msg_ctx.peer = &my_identity; /* FIXME bart NULL? Fix doxygen? */
4038 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
4039 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4041 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4042 increment_stats (STAT_GET_START);
4043 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4044 increment_stats (STAT_PUT_START);
4045 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
4046 increment_stats (STAT_FIND_PEER_START);
4048 if (GNUNET_YES == malicious_dropper)
4050 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
4052 #if DEBUG_DHT_ROUTING
4053 if ((debug_routes) && (dhtlog_handle != NULL))
4055 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_GET,
4056 msg_ctx.hop_count, GNUNET_NO, &my_identity,
4061 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
4063 #if DEBUG_DHT_ROUTING
4064 if ((debug_routes) && (dhtlog_handle != NULL))
4066 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_PUT,
4067 msg_ctx.hop_count, GNUNET_NO, &my_identity,
4072 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4073 GNUNET_free_non_null (msg_ctx.path_history);
4077 demultiplex_message (enc_msg, &msg_ctx);
4078 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4083 * Handler for any locally received DHT control messages,
4084 * sets malicious flags mostly for now.
4086 * @param cls closure for the service
4087 * @param client the client we received this message from
4088 * @param message the actual message received
4092 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
4093 const struct GNUNET_MessageHeader *message)
4095 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
4096 (const struct GNUNET_DHT_ControlMessage *) message;
4099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4100 "`%s:%s': Received `%s' request from client, command %d\n",
4101 my_short_id, "DHT", "CONTROL", ntohs (dht_control_msg->command));
4104 switch (ntohs (dht_control_msg->command))
4106 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
4107 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4108 "Sending self seeking find peer request!\n");
4109 GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
4112 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
4113 if (ntohs (dht_control_msg->variable) > 0)
4114 malicious_get_frequency.value = ntohs (dht_control_msg->variable);
4115 if (malicious_get_frequency == 0)
4116 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4117 if (malicious_getter != GNUNET_YES)
4118 GNUNET_SCHEDULER_add_now (&malicious_get_task, NULL);
4119 malicious_getter = GNUNET_YES;
4120 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4121 "%s:%s Initiating malicious GET behavior, frequency %llu\n",
4122 my_short_id, "DHT", malicious_get_frequency.value);
4124 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
4125 if (ntohs (dht_control_msg->variable) > 0)
4126 malicious_put_frequency = ntohs (dht_control_msg->variable);
4127 if (malicious_put_frequency == 0)
4128 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4129 if (malicious_putter != GNUNET_YES)
4130 GNUNET_SCHEDULER_add_now (&malicious_put_task, NULL);
4131 malicious_putter = GNUNET_YES;
4132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4133 "%s:%s Initiating malicious PUT behavior, frequency %d\n",
4134 my_short_id, "DHT", malicious_put_frequency);
4136 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
4137 #if DEBUG_DHT_ROUTING
4138 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
4139 dhtlog_handle->set_malicious (&my_identity);
4141 malicious_dropper = GNUNET_YES;
4142 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4143 "%s:%s Initiating malicious DROP behavior\n", my_short_id,
4148 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4149 "%s:%s Unknown control command type `%d'!\n", my_short_id,
4150 "DHT", ntohs (dht_control_msg->command));
4154 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4158 * Handler for any generic DHT stop messages, calls the appropriate handler
4159 * depending on message type (if processed locally)
4161 * @param cls closure for the service
4162 * @param client the client we received this message from
4163 * @param message the actual message received
4167 handle_dht_local_route_stop (void *cls, struct GNUNET_SERVER_Client *client,
4168 const struct GNUNET_MessageHeader *message)
4171 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
4172 (const struct GNUNET_DHT_StopMessage *) message;
4173 struct DHTQueryRecord *record;
4174 struct DHTRouteSource *pos;
4177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4178 "`%s:%s': Received `%s' request from client, uid %llu\n",
4179 my_short_id, "DHT", "GENERIC STOP",
4180 GNUNET_ntohll (dht_stop_msg->unique_id));
4183 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap,
4184 &dht_stop_msg->key);
4191 /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
4192 if ((pos->client != NULL) && (pos->client->client_handle == client))
4194 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
4195 GNUNET_SCHEDULER_cancel (pos->delete_task);
4197 GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
4203 GNUNET_SERVER_receive_done (client, GNUNET_OK);
4208 * Core handler for p2p route requests.
4210 * @param cls closure
4211 * @param message message
4212 * @param peer peer identity this notification is about
4213 * @param atsi performance data
4214 * @return GNUNET_OK to keep the connection open,
4215 * GNUNET_SYSERR to close it (signal serious error)
4218 handle_dht_p2p_route_request (void *cls, const struct GNUNET_PeerIdentity *peer,
4219 const struct GNUNET_MessageHeader *message,
4220 const struct GNUNET_TRANSPORT_ATS_Information
4224 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4225 "`%s:%s': Received P2P request from peer %s\n", my_short_id,
4226 "DHT", GNUNET_i2s (peer));
4228 struct GNUNET_DHT_P2PRouteMessage *incoming =
4229 (struct GNUNET_DHT_P2PRouteMessage *) message;
4230 struct GNUNET_MessageHeader *enc_msg =
4231 (struct GNUNET_MessageHeader *) &incoming[1];
4232 struct DHT_MessageContext *msg_ctx;
4236 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING)
4238 /* Throw these away. FIXME: Don't throw these away? (reply) */
4240 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n",
4241 my_short_id, "DHT");
4246 if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4248 GNUNET_break_op (0);
4252 if (malicious_dropper == GNUNET_YES)
4254 #if DEBUG_DHT_ROUTING
4255 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4257 /** Log routes that die due to high load! */
4258 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4259 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4260 GNUNET_SYSERR, &my_identity, &incoming->key,
4267 if (get_max_send_delay ().rel_value > MAX_REQUEST_TIME.rel_value)
4269 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4270 "Sending of previous replies took too long, backing off!\n");
4271 increment_stats ("# route requests dropped due to high load");
4272 decrease_max_send_delay (get_max_send_delay ());
4273 #if DEBUG_DHT_ROUTING
4274 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4276 /** Log routes that die due to high load! */
4277 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4278 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4279 GNUNET_SYSERR, &my_identity, &incoming->key,
4285 msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
4287 GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4289 GNUNET_assert (msg_ctx->bloom != NULL);
4290 msg_ctx->hop_count = ntohl (incoming->hop_count);
4291 memcpy (&msg_ctx->key, &incoming->key, sizeof (GNUNET_HashCode));
4292 msg_ctx->replication = ntohl (incoming->desired_replication_level);
4293 msg_ctx->unique_id = GNUNET_ntohll (incoming->unique_id);
4294 msg_ctx->msg_options = ntohl (incoming->options);
4295 if (GNUNET_DHT_RO_RECORD_ROUTE ==
4296 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
4299 ntohl (incoming->outgoing_path_length) *
4300 sizeof (struct GNUNET_PeerIdentity);
4301 if (ntohs (message->size) !=
4302 (sizeof (struct GNUNET_DHT_P2PRouteMessage) +
4303 ntohs (enc_msg->size) + path_size))
4308 route_path = (char *) &incoming[1];
4309 route_path = route_path + ntohs (enc_msg->size);
4310 msg_ctx->path_history =
4311 GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) + path_size);
4312 memcpy (msg_ctx->path_history, route_path, path_size);
4313 memcpy (&msg_ctx->path_history[path_size], &my_identity,
4314 sizeof (struct GNUNET_PeerIdentity));
4315 msg_ctx->path_history_len = ntohl (incoming->outgoing_path_length) + 1;
4317 msg_ctx->network_size = ntohl (incoming->network_size);
4318 msg_ctx->peer = peer;
4319 msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4320 msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4321 demultiplex_message (enc_msg, msg_ctx);
4322 if (msg_ctx->bloom != NULL)
4324 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4325 msg_ctx->bloom = NULL;
4327 GNUNET_free (msg_ctx);
4333 * Core handler for p2p route results.
4335 * @param cls closure
4336 * @param message message
4337 * @param peer peer identity this notification is about
4338 * @param atsi performance data
4342 handle_dht_p2p_route_result (void *cls, const struct GNUNET_PeerIdentity *peer,
4343 const struct GNUNET_MessageHeader *message,
4344 const struct GNUNET_TRANSPORT_ATS_Information
4348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4349 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT",
4352 struct GNUNET_DHT_P2PRouteResultMessage *incoming =
4353 (struct GNUNET_DHT_P2PRouteResultMessage *) message;
4354 struct GNUNET_MessageHeader *enc_msg =
4355 (struct GNUNET_MessageHeader *) &incoming[1];
4356 struct DHT_MessageContext msg_ctx;
4362 if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4364 GNUNET_break_op (0);
4368 if (malicious_dropper == GNUNET_YES)
4370 #if DEBUG_DHT_ROUTING
4371 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4373 /** Log routes that die due to high load! */
4374 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4375 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4376 GNUNET_SYSERR, &my_identity, &incoming->key,
4383 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4384 // FIXME: call GNUNET_BLOCK_evaluate (...) -- instead of doing your own bloomfilter!
4385 memcpy (&msg_ctx.key, &incoming->key, sizeof (GNUNET_HashCode));
4386 msg_ctx.unique_id = GNUNET_ntohll (incoming->unique_id);
4387 msg_ctx.msg_options = ntohl (incoming->options);
4388 msg_ctx.hop_count = ntohl (incoming->hop_count);
4389 msg_ctx.peer = peer;
4390 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4391 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4392 if ((GNUNET_DHT_RO_RECORD_ROUTE ==
4393 (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE)) &&
4394 (ntohl (incoming->outgoing_path_length) > 0))
4396 if (ntohs (message->size) -
4397 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) -
4398 ntohs (enc_msg->size) !=
4399 ntohl (incoming->outgoing_path_length) *
4400 sizeof (struct GNUNET_PeerIdentity))
4403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4404 "Return message indicated a path was included, but sizes are wrong: Total size %d, enc size %d, left %d, expected %d\n",
4405 ntohs (message->size), ntohs (enc_msg->size),
4406 ntohs (message->size) -
4407 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) -
4408 ntohs (enc_msg->size),
4409 ntohl (incoming->outgoing_path_length) *
4410 sizeof (struct GNUNET_PeerIdentity));
4412 GNUNET_break_op (0);
4415 msg_ctx.path_history = (char *) &incoming[1];
4416 msg_ctx.path_history += ntohs (enc_msg->size);
4417 msg_ctx.path_history_len = ntohl (incoming->outgoing_path_length);
4419 for (i = 0; i < msg_ctx.path_history_len; i++)
4422 &msg_ctx.path_history[i * sizeof (struct GNUNET_PeerIdentity)];
4423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4424 "(handle_p2p_route_result) Key %s Found peer %d:%s\n",
4425 GNUNET_h2s (&msg_ctx.key), i,
4426 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
4431 GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4433 GNUNET_assert (msg_ctx.bloom != NULL);
4434 route_result_message (enc_msg, &msg_ctx);
4440 * Receive the HELLO from transport service,
4441 * free current and replace if necessary.
4444 * @param message HELLO message of peer
4447 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4450 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4451 "Received our `%s' from transport service\n", "HELLO");
4454 GNUNET_assert (message != NULL);
4455 GNUNET_free_non_null (my_hello);
4456 my_hello = GNUNET_malloc (ntohs (message->size));
4457 memcpy (my_hello, message, ntohs (message->size));
4462 * Task run during shutdown.
4468 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4471 struct PeerInfo *pos;
4475 GNUNET_TRANSPORT_get_hello_cancel (ghh);
4478 if (transport_handle != NULL)
4480 GNUNET_free_non_null (my_hello);
4481 GNUNET_TRANSPORT_disconnect (transport_handle);
4482 transport_handle = NULL;
4486 GNUNET_NSE_disconnect (nse);
4489 if (coreAPI != NULL)
4492 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Disconnecting core!\n",
4493 my_short_id, "DHT");
4495 GNUNET_CORE_disconnect (coreAPI);
4498 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4500 while (k_buckets[bucket_count].head != NULL)
4502 pos = k_buckets[bucket_count].head;
4504 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4505 "%s:%s Removing peer %s from bucket %d!\n", my_short_id,
4506 "DHT", GNUNET_i2s (&pos->id), bucket_count);
4508 delete_peer (pos, bucket_count);
4511 if (datacache != NULL)
4514 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Destroying datacache!\n",
4515 my_short_id, "DHT");
4517 GNUNET_DATACACHE_destroy (datacache);
4522 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4525 if (dhtlog_handle != NULL)
4527 GNUNET_DHTLOG_disconnect (dhtlog_handle);
4528 dhtlog_handle = NULL;
4530 if (block_context != NULL)
4532 GNUNET_BLOCK_context_destroy (block_context);
4533 block_context = NULL;
4535 GNUNET_free_non_null (my_short_id);
4541 * To be called on core init/fail.
4543 * @param cls service closure
4544 * @param server handle to the server for this service
4545 * @param identity the public identity of this peer
4546 * @param publicKey the public key of this peer
4549 core_init (void *cls, struct GNUNET_CORE_Handle *server,
4550 const struct GNUNET_PeerIdentity *identity,
4551 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4557 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s: Connection to core FAILED!\n",
4558 "dht", GNUNET_i2s (identity));
4560 GNUNET_SCHEDULER_cancel (cleanup_task);
4561 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4565 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4566 "%s: Core connection initialized, I am peer: %s\n", "dht",
4567 GNUNET_i2s (identity));
4570 /* Copy our identity so we can use it */
4571 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4572 if (my_short_id != NULL)
4573 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4574 "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n",
4576 my_short_id = GNUNET_strdup (GNUNET_i2s (&my_identity));
4577 if (dhtlog_handle != NULL)
4578 dhtlog_handle->insert_node (NULL, &my_identity);
4582 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4583 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE,
4585 {&handle_dht_local_route_stop, NULL,
4586 GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4587 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4592 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4593 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4594 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4600 * Method called whenever a peer connects.
4602 * @param cls closure
4603 * @param peer peer identity this notification is about
4604 * @param atsi performance data
4607 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
4608 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4610 struct PeerInfo *ret;
4611 struct DHTPutEntry *put_entry;
4614 /* Check for connect to self message */
4615 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
4619 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4620 "%s:%s Receives core connect message for peer %s distance %d!\n",
4621 my_short_id, "dht", GNUNET_i2s (peer), distance);
4625 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
4629 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4630 "%s:%s Received %s message for peer %s, but already have peer in RT!",
4631 my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s (peer));
4637 if ((datacache != NULL) && (GNUNET_YES == put_peer_identities))
4640 GNUNET_malloc (sizeof (struct DHTPutEntry) +
4641 sizeof (struct GNUNET_PeerIdentity));
4642 put_entry->path_length = 0;
4643 put_entry->data_size = sizeof (struct GNUNET_PeerIdentity);
4644 memcpy (&put_entry[1], peer, sizeof (struct GNUNET_PeerIdentity));
4645 GNUNET_DATACACHE_put (datacache, &peer->hashPubKey,
4646 sizeof (struct DHTPutEntry) +
4647 sizeof (struct GNUNET_PeerIdentity),
4648 (char *) put_entry, GNUNET_BLOCK_TYPE_DHT_HELLO,
4649 GNUNET_TIME_absolute_get_forever ());
4650 GNUNET_free (put_entry);
4652 else if (datacache == NULL)
4653 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4654 "DHT has no connection to datacache!\n");
4656 peer_bucket = find_current_bucket (&peer->hashPubKey);
4657 GNUNET_assert (peer_bucket >= lowest_bucket);
4658 GNUNET_assert (peer_bucket < MAX_BUCKETS);
4659 ret = GNUNET_malloc (sizeof (struct PeerInfo));
4661 ret->latency = latency;
4662 ret->distance = distance;
4665 GNUNET_CONTAINER_DLL_insert_after (k_buckets[peer_bucket].head,
4666 k_buckets[peer_bucket].tail,
4667 k_buckets[peer_bucket].tail, ret);
4668 k_buckets[peer_bucket].peers_size++;
4669 #if DO_UPDATE_PREFERENCE
4670 if ((GNUNET_CRYPTO_hash_matching_bits
4671 (&my_identity.hashPubKey, &peer->hashPubKey) > 0) &&
4672 (k_buckets[peer_bucket].peers_size <= bucket_size))
4673 ret->preference_task =
4674 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
4676 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
4677 enable_next_bucket ();
4679 schedule_ping_messages ();
4681 newly_found_peers++;
4682 GNUNET_CONTAINER_multihashmap_put (all_known_peers, &peer->hashPubKey, ret,
4683 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4684 increment_stats (STAT_PEERS_KNOWN);
4687 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4688 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT",
4689 ret == NULL ? "NOT ADDED" : "PEER ADDED");
4695 * Method called whenever a peer disconnects.
4697 * @param cls closure
4698 * @param peer peer identity this notification is about
4701 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
4703 struct PeerInfo *to_remove;
4706 /* Check for disconnect from self message */
4707 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
4710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4711 "%s:%s: Received peer disconnect message for peer `%s' from %s\n",
4712 my_short_id, "DHT", GNUNET_i2s (peer), "CORE");
4716 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
4721 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4722 "%s:%s: do not have peer `%s' in RT, can't disconnect!\n",
4723 my_short_id, "DHT", GNUNET_i2s (peer));
4727 increment_stats (STAT_DISCONNECTS);
4728 GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
4729 (all_known_peers, &peer->hashPubKey));
4731 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
4732 GNUNET_assert (to_remove != NULL);
4733 if (NULL != to_remove->info_ctx)
4735 GNUNET_CORE_peer_change_preference_cancel (to_remove->info_ctx);
4736 to_remove->info_ctx = NULL;
4739 memcmp (peer, &to_remove->id,
4740 sizeof (struct GNUNET_PeerIdentity)));
4741 current_bucket = find_current_bucket (&to_remove->id.hashPubKey);
4742 delete_peer (to_remove, current_bucket);
4747 * Process dht requests.
4749 * @param cls closure
4750 * @param server the initialized server
4751 * @param c configuration to use
4754 run (void *cls, struct GNUNET_SERVER_Handle *server,
4755 const struct GNUNET_CONFIGURATION_Handle *c)
4757 struct GNUNET_TIME_Relative next_send_time;
4758 unsigned long long temp_config_num;
4761 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4762 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4763 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4764 nse = GNUNET_NSE_connect (cfg,
4765 &update_network_size_estimate, NULL);
4766 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
4767 DEFAULT_CORE_QUEUE_SIZE, /* queue size */
4768 NULL, /* Closure passed to DHT functions */
4769 &core_init, /* Call core_init once connected */
4770 &handle_core_connect, /* Handle connects */
4771 &handle_core_disconnect, /* remove peers on disconnects */
4772 NULL, /* Do we care about "status" updates? */
4773 NULL, /* Don't want notified about all incoming messages */
4774 GNUNET_NO, /* For header only inbound notification */
4775 NULL, /* Don't want notified about all outbound messages */
4776 GNUNET_NO, /* For header only outbound notification */
4777 core_handlers); /* Register these handlers */
4779 if (coreAPI == NULL)
4782 GNUNET_TRANSPORT_connect (cfg, NULL, NULL, NULL, NULL, NULL);
4783 if (transport_handle != NULL)
4784 ghh = GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4786 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4787 "Failed to connect to transport service!\n");
4788 block_context = GNUNET_BLOCK_context_create (cfg);
4789 lowest_bucket = MAX_BUCKETS - 1;
4790 forward_list.hashmap =
4791 GNUNET_CONTAINER_multihashmap_create (MAX_OUTSTANDING_FORWARDS / 10);
4792 forward_list.minHeap =
4793 GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4794 all_known_peers = GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
4795 recent_find_peer_requests =
4796 GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
4797 GNUNET_assert (all_known_peers != NULL);
4799 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
4802 debug_routes = GNUNET_YES;
4806 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "strict_kademlia"))
4808 strict_kademlia = GNUNET_YES;
4812 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_on_closest"))
4814 stop_on_closest = GNUNET_YES;
4818 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_found"))
4820 stop_on_found = GNUNET_YES;
4824 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_getter"))
4826 malicious_getter = GNUNET_YES;
4828 GNUNET_CONFIGURATION_get_value_time (cfg, "DHT",
4829 "MALICIOUS_GET_FREQUENCY",
4830 &malicious_get_frequency))
4831 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4835 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_putter"))
4837 malicious_putter = GNUNET_YES;
4839 GNUNET_CONFIGURATION_get_value_time (cfg, "DHT",
4840 "MALICIOUS_PUT_FREQUENCY",
4841 &malicious_put_frequency))
4842 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4846 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "bucket_size",
4849 bucket_size = (unsigned int) temp_config_num;
4853 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "kad_alpha",
4854 &kademlia_replication))
4856 kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
4860 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_dropper"))
4862 malicious_dropper = GNUNET_YES;
4866 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "do_find_peer"))
4868 do_find_peer = GNUNET_NO;
4871 do_find_peer = GNUNET_YES;
4874 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "use_real_distance"))
4875 use_real_distance = GNUNET_YES;
4878 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
4879 "mysql_logging_extended"))
4881 debug_routes = GNUNET_YES;
4882 debug_routes_extended = GNUNET_YES;
4885 #if DEBUG_DHT_ROUTING
4886 if (GNUNET_YES == debug_routes)
4888 dhtlog_handle = GNUNET_DHTLOG_connect (cfg);
4889 if (dhtlog_handle == NULL)
4891 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4892 "Could not connect to mysql logging server, logging will not happen!");
4898 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "paper_forwarding"))
4899 paper_forwarding = GNUNET_YES;
4902 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "put_peer_identities"))
4903 put_peer_identities = GNUNET_YES;
4905 stats = GNUNET_STATISTICS_create ("dht", cfg);
4909 GNUNET_STATISTICS_set (stats, STAT_ROUTES, 0, GNUNET_NO);
4910 GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4911 GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4912 GNUNET_STATISTICS_set (stats, STAT_RESULTS, 0, GNUNET_NO);
4913 GNUNET_STATISTICS_set (stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4914 GNUNET_STATISTICS_set (stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4915 GNUNET_STATISTICS_set (stats, STAT_GETS, 0, GNUNET_NO);
4916 GNUNET_STATISTICS_set (stats, STAT_PUTS, 0, GNUNET_NO);
4917 GNUNET_STATISTICS_set (stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4918 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER, 0, GNUNET_NO);
4919 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4920 GNUNET_STATISTICS_set (stats, STAT_GET_START, 0, GNUNET_NO);
4921 GNUNET_STATISTICS_set (stats, STAT_PUT_START, 0, GNUNET_NO);
4922 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4923 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4924 GNUNET_STATISTICS_set (stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4925 GNUNET_STATISTICS_set (stats, STAT_GET_REPLY, 0, GNUNET_NO);
4926 GNUNET_STATISTICS_set (stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4927 GNUNET_STATISTICS_set (stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4928 GNUNET_STATISTICS_set (stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4930 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4931 recent.hashmap = GNUNET_CONTAINER_multihashmap_create (DHT_MAX_RECENT / 2);
4933 GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4934 if (GNUNET_YES == do_find_peer)
4936 next_send_time.rel_value =
4937 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4938 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
4939 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value /
4941 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4942 find_peer_context.start = GNUNET_TIME_absolute_get ();
4943 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
4944 &find_peer_context);
4947 /* Scheduled the task to clean up when shutdown is called */
4949 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4950 &shutdown_task, NULL);
4954 * The main function for the dht service.
4956 * @param argc number of arguments from the command line
4957 * @param argv command line arguments
4958 * @return 0 ok, 1 on error
4961 main (int argc, char *const *argv)
4967 GNUNET_SERVICE_run (argc, argv, "dht", GNUNET_SERVICE_OPTION_NONE, &run,
4969 if (NULL != recent.hashmap)
4971 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (recent.hashmap));
4972 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4973 recent.hashmap = NULL;
4975 if (NULL != recent.minHeap)
4977 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (recent.minHeap));
4978 GNUNET_CONTAINER_heap_destroy (recent.minHeap);
4979 recent.minHeap = NULL;
4981 if (NULL != recent_find_peer_requests)
4983 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4984 recent_find_peer_requests = NULL;