2 This file is part of GNUnet.
3 (C) 2009, 2010, 2011 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 * - decide on 'stop_on_closest', 'stop_on_found', 'do_find_peer', 'paper_forwarding'
33 #include "gnunet_block_lib.h"
34 #include "gnunet_client_lib.h"
35 #include "gnunet_getopt_lib.h"
36 #include "gnunet_os_lib.h"
37 #include "gnunet_protocols.h"
38 #include "gnunet_service_lib.h"
39 #include "gnunet_nse_service.h"
40 #include "gnunet_core_service.h"
41 #include "gnunet_signal_lib.h"
42 #include "gnunet_util_lib.h"
43 #include "gnunet_datacache_lib.h"
44 #include "gnunet_transport_service.h"
45 #include "gnunet_hello_lib.h"
46 #include "gnunet_dht_service.h"
47 #include "gnunet_statistics_service.h"
54 * How many buckets will we allow total.
56 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
59 * Should the DHT issue FIND_PEER requests to get better routing tables?
61 #define DEFAULT_DO_FIND_PEER GNUNET_YES
64 * Defines whether find peer requests send their HELLO's outgoing,
65 * or expect replies to contain hellos.
67 #define FIND_PEER_WITH_HELLO GNUNET_YES
70 * What is the maximum number of peers in a given bucket.
72 #define DEFAULT_BUCKET_SIZE 4
74 #define DEFAULT_CORE_QUEUE_SIZE 32
77 * Minimum number of peers we need for "good" routing,
78 * any less than this and we will allow messages to
79 * travel much further through the network!
81 #define MINIMUM_PEER_THRESHOLD 20
84 * Number of requests we track at most (for routing replies).
86 #define DHT_MAX_RECENT (1024 * 16)
89 * How long do we wait at most when queueing messages with core
90 * that we are sending on behalf of other peers.
92 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
95 * Default importance for handling messages on behalf of other peers.
97 #define DHT_DEFAULT_P2P_IMPORTANCE 0
100 * How long to keep recent requests around by default.
102 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
105 * Default time to wait to send find peer messages sent by the dht service.
107 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
110 * Default importance for find peer messages sent by the dht service.
112 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
115 * Default replication parameter for find peer messages sent by the dht service.
117 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
120 * How long at least to wait before sending another find peer request.
122 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
125 * How long at most to wait before sending another find peer request.
127 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
130 * How often to update our preference levels for peers in our routing tables.
132 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
135 * How long at most on average will we allow a reply forward to take
136 * (before we quit sending out new requests)
138 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
141 * How many initial requests to send out (in true Kademlia fashion)
143 #define DEFAULT_KADEMLIA_REPLICATION 3
146 * Default frequency for sending malicious get messages
148 #define DEFAULT_MALICIOUS_GET_FREQUENCY GNUNET_TIME_UNIT_SECONDS
151 * Default frequency for sending malicious put messages
153 #define DEFAULT_MALICIOUS_PUT_FREQUENCY GNUNET_TIME_UNIT_SECONDS
156 * How many time differences between requesting a core send and
157 * the actual callback to remember.
159 #define MAX_REPLY_TIMES 8
163 * Linked list of messages to send to clients.
165 struct P2PPendingMessage
168 * Pointer to next item in the list
170 struct P2PPendingMessage *next;
173 * Pointer to previous item in the list
175 struct P2PPendingMessage *prev;
178 * Message importance level.
180 unsigned int importance;
183 * Time when this request was scheduled to be sent.
185 struct GNUNET_TIME_Absolute scheduled;
188 * How long to wait before sending message.
190 struct GNUNET_TIME_Relative timeout;
193 * Actual message to be sent; // avoid allocation
195 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
201 * Per-peer information.
206 * Next peer entry (DLL)
208 struct PeerInfo *next;
211 * Prev peer entry (DLL)
213 struct PeerInfo *prev;
216 * Count of outstanding messages for peer.
218 unsigned int pending_count;
221 * Head of pending messages to be sent to this peer.
223 struct P2PPendingMessage *head;
226 * Tail of pending messages to be sent to this peer.
228 struct P2PPendingMessage *tail;
231 * Core handle for sending messages to this peer.
233 struct GNUNET_CORE_TransmitHandle *th;
236 * Task for scheduling message sends.
238 GNUNET_SCHEDULER_TaskIdentifier send_task;
241 * Task for scheduling preference updates
243 GNUNET_SCHEDULER_TaskIdentifier preference_task;
246 * Preference update context
248 struct GNUNET_CORE_InformationRequestContext *info_ctx;
251 * What is the identity of the peer?
253 struct GNUNET_PeerIdentity id;
257 * What is the average latency for replies received?
259 struct GNUNET_TIME_Relative latency;
262 * Transport level distance to peer.
264 unsigned int distance;
268 * Task for scheduling periodic ping messages for this peer.
270 GNUNET_SCHEDULER_TaskIdentifier ping_task;
275 * Peers are grouped into buckets.
282 struct PeerInfo *head;
287 struct PeerInfo *tail;
290 * Number of peers in the bucket.
292 unsigned int peers_size;
297 * Linked list of messages to send to clients.
299 struct PendingMessage
302 * Pointer to next item in the list
304 struct PendingMessage *next;
307 * Pointer to previous item in the list
309 struct PendingMessage *prev;
312 * Actual message to be sent; // avoid allocation
314 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
320 * Struct containing information about a client,
321 * handle to connect to it, and any pending messages
322 * that need to be sent to it.
327 * Linked list of active clients
329 struct ClientList *next;
332 * The handle to this client
334 struct GNUNET_SERVER_Client *client_handle;
337 * Handle to the current transmission request, NULL
340 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
343 * Linked list of pending messages for this client
345 struct PendingMessage *pending_head;
348 * Tail of linked list of pending messages for this client
350 struct PendingMessage *pending_tail;
355 * Context containing information about a DHT message received.
357 struct DHT_MessageContext
360 * The client this request was received from.
361 * (NULL if received from another peer)
363 struct ClientList *client;
366 * The peer this request was received from.
367 * (NULL if received from local client)
369 const struct GNUNET_PeerIdentity *peer;
372 * Bloomfilter for this routing request.
374 struct GNUNET_CONTAINER_BloomFilter *bloom;
377 * extended query (see gnunet_block_lib.h).
382 * Bloomfilter to filter out duplicate replies.
384 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
387 * The key this request was about
392 * How long should we wait to transmit this request?
394 struct GNUNET_TIME_Relative timeout;
397 * The unique identifier of this request
402 * Number of bytes in xquery.
407 * Mutator value for the reply_bf, see gnunet_block_lib.h
409 uint32_t reply_bf_mutator;
412 * Desired replication level
414 uint32_t replication;
417 * Network size estimate, either ours or the sum of
418 * those routed to thus far. =~ Log of number of peers
419 * chosen from for this request.
421 uint32_t network_size;
424 * Any message options for this request
426 uint32_t msg_options;
429 * How many hops has the message already traversed?
434 * How many peer identities are present in the path history?
436 uint32_t path_history_len;
444 * How important is this message?
446 unsigned int importance;
449 * Should we (still) forward the request on to other peers?
454 * Did we forward this message? (may need to remember it!)
459 * Are we the closest known peer to this key (out of our neighbors?)
466 * Record used for remembering what peers are waiting for what
467 * responses (based on search key).
469 struct DHTRouteSource
474 struct DHTRouteSource *next;
479 struct DHTRouteSource *prev;
482 * Source of the request. Replies should be forwarded to
485 struct GNUNET_PeerIdentity source;
488 * If this was a local request, remember the client; otherwise NULL.
490 struct ClientList *client;
493 * Pointer to this nodes heap location (for removal)
495 struct GNUNET_CONTAINER_HeapNode *hnode;
498 * Back pointer to the record storing this information.
500 struct DHTQueryRecord *record;
503 * Task to remove this entry on timeout.
505 GNUNET_SCHEDULER_TaskIdentifier delete_task;
508 * Bloomfilter of peers we have already sent back as
509 * replies to the initial request. Allows us to not
510 * forward the same peer multiple times for a find peer
513 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
519 * Entry in the DHT routing table.
521 struct DHTQueryRecord
524 * Head of DLL for result forwarding.
526 struct DHTRouteSource *head;
529 * Tail of DLL for result forwarding.
531 struct DHTRouteSource *tail;
534 * Key that the record concerns.
542 * Context used to calculate the number of find peer messages
543 * per X time units since our last scheduled find peer message
544 * was sent. If we have seen too many messages, delay or don't
547 struct FindPeerMessageContext
551 struct GNUNET_TIME_Absolute start;
553 struct GNUNET_TIME_Absolute end;
558 * DHT Routing results structure
563 * Min heap for removal upon reaching limit
565 struct GNUNET_CONTAINER_Heap *minHeap;
568 * Hashmap for fast key based lookup
570 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
576 * DHT structure for recent requests.
578 struct RecentRequests
581 * Min heap for removal upon reaching limit
583 struct GNUNET_CONTAINER_Heap *minHeap;
586 * Hashmap for key based lookup
588 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
595 * Position of this node in the min heap.
597 struct GNUNET_CONTAINER_HeapNode *heap_node;
600 * Bloomfilter containing entries for peers
601 * we forwarded this request to.
603 struct GNUNET_CONTAINER_BloomFilter *bloom;
606 * Timestamp of this request, for ordering
609 struct GNUNET_TIME_Absolute timestamp;
612 * Key of this request.
617 * Unique identifier for this request.
622 * Task to remove this entry on timeout.
624 GNUNET_SCHEDULER_TaskIdentifier remove_task;
629 * log of the current network size estimate, used as the point where
630 * we switch between random and deterministic routing. Default
631 * value of 4.0 is used if NSE module is not available (i.e. not
634 static double log_of_network_size_estimate = 4.0;
637 * Recent requests by hash/uid and by time inserted.
639 static struct RecentRequests recent;
642 * Context to use to calculate find peer rates.
644 static struct FindPeerMessageContext find_peer_context;
647 * Don't use our routing algorithm, always route
648 * to closest peer; initially send requests to 3
651 static int strict_kademlia;
654 * Routing option to end routing when closest peer found.
656 static int stop_on_closest;
659 * Routing option to end routing when data is found.
661 static int stop_on_found;
664 * Whether DHT needs to manage find peer requests, or
665 * an external force will do it on behalf of the DHT.
667 static int do_find_peer;
670 * Use exactly the forwarding formula as described in
671 * the paper if set to GNUNET_YES, otherwise use the
672 * slightly modified version.
674 static int paper_forwarding;
677 * PUT Peer Identities of peers we know about into
680 static int put_peer_identities;
683 * Use the "real" distance metric when selecting the
684 * next routing hop. Can be less accurate.
686 static int use_real_distance;
689 * How many peers have we added since we sent out our last
692 static unsigned int newly_found_peers;
695 * Container of active queries we should remember
697 static struct DHTResults forward_list;
700 * Handle to the datacache service (for inserting/retrieving data)
702 static struct GNUNET_DATACACHE_Handle *datacache;
705 * Handle for the statistics service.
707 struct GNUNET_STATISTICS_Handle *stats;
710 * Handle to get our current HELLO.
712 static struct GNUNET_TRANSPORT_GetHelloHandle *ghh;
715 * The configuration the DHT service is running with
717 static const struct GNUNET_CONFIGURATION_Handle *cfg;
720 * Handle to the core service
722 static struct GNUNET_CORE_Handle *coreAPI;
725 * Handle to the transport service, for getting our hello
727 static struct GNUNET_TRANSPORT_Handle *transport_handle;
730 * The identity of our peer.
732 static struct GNUNET_PeerIdentity my_identity;
735 * Short id of the peer, for printing
737 static char *my_short_id;
742 static struct GNUNET_MessageHeader *my_hello;
745 * Task to run when we shut down, cleaning up all our trash
747 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
750 * The lowest currently used bucket.
752 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
755 * The buckets (Kademlia routing table, complete with growth).
756 * Array of size MAX_BUCKET_SIZE.
758 static struct PeerBucket k_buckets[MAX_BUCKETS];
761 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
763 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
766 * Recently seen find peer requests.
768 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
771 * Maximum size for each bucket.
773 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
776 * List of active clients.
778 static struct ClientList *client_list;
781 * Handle to the DHT logger.
783 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
786 * Whether or not to send routing debugging information
787 * to the dht logging server
789 static unsigned int debug_routes;
792 * Whether or not to send FULL route information to
795 static unsigned int debug_routes_extended;
798 * GNUNET_YES or GNUNET_NO, whether or not to act as
799 * a malicious node which drops all messages
801 static unsigned int malicious_dropper;
804 * GNUNET_YES or GNUNET_NO, whether or not to act as
805 * a malicious node which sends out lots of GETS
807 static unsigned int malicious_getter;
810 * GNUNET_YES or GNUNET_NO, whether or not to act as
811 * a malicious node which sends out lots of PUTS
813 static unsigned int malicious_putter;
816 * Frequency for malicious get requests.
818 static struct GNUNET_TIME_Relative malicious_get_frequency;
821 * Frequency for malicious put requests.
823 static struct GNUNET_TIME_Relative malicious_put_frequency;
826 * Kademlia replication
828 static unsigned long long kademlia_replication;
831 * Reply times for requests, if we are busy, don't send any
834 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
837 * Current counter for replies.
839 static unsigned int reply_counter;
842 * Our handle to the BLOCK library.
844 static struct GNUNET_BLOCK_Context *block_context;
847 * Network size estimation handle.
849 static struct GNUNET_NSE_Handle *nse;
853 * Callback that is called when network size estimate is updated.
856 * @param timestamp time when the estimate was received from the server (or created by the server)
857 * @param logestimate the log(Base 2) value of the current network size estimate
858 * @param std_dev standard deviation for the estimate
862 update_network_size_estimate (void *cls,
863 struct GNUNET_TIME_Absolute timestamp,
864 double logestimate, double std_dev)
866 log_of_network_size_estimate = logestimate;
871 * Forward declaration.
874 send_generic_reply (void *cls, size_t size, void *buf);
877 /** Declare here so retry_core_send is aware of it */
879 core_transmit_notify (void *cls, size_t size, void *buf);
883 * Convert unique ID to hash code.
885 * @param uid unique ID to convert
886 * @param hash set to uid (extended with zeros)
889 hash_from_uid (uint64_t uid, GNUNET_HashCode * hash)
891 memset (hash, 0, sizeof (GNUNET_HashCode));
892 *((uint64_t *) hash) = uid;
897 * Given the largest send delay, artificially decrease it
898 * so the next time around we may have a chance at sending
902 decrease_max_send_delay (struct GNUNET_TIME_Relative max_time)
906 for (i = 0; i < MAX_REPLY_TIMES; i++)
908 if (reply_times[i].rel_value == max_time.rel_value)
910 reply_times[i].rel_value = reply_times[i].rel_value / 2;
918 * Find the maximum send time of the recently sent values.
920 * @return the average time between asking core to send a message
921 * and when the buffer for copying it is passed
923 static struct GNUNET_TIME_Relative
924 get_max_send_delay ()
927 struct GNUNET_TIME_Relative max_time;
929 max_time = GNUNET_TIME_relative_get_zero ();
931 for (i = 0; i < MAX_REPLY_TIMES; i++)
933 if (reply_times[i].rel_value > max_time.rel_value)
934 max_time.rel_value = reply_times[i].rel_value;
937 if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
938 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n",
939 (unsigned long long) max_time.rel_value);
946 increment_stats (const char *value)
950 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
955 decrement_stats (const char *value)
959 GNUNET_STATISTICS_update (stats, value, -1, GNUNET_NO);
964 * Try to send another message from our core send list
967 try_core_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
969 struct PeerInfo *peer = cls;
970 struct P2PPendingMessage *pending;
973 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
975 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
978 if (peer->th != NULL)
979 return; /* Message send already in progress */
981 pending = peer->head;
984 ssize = ntohs (pending->msg->size);
986 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
987 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n",
988 my_short_id, "DHT", ssize, GNUNET_i2s (&peer->id));
990 pending->scheduled = GNUNET_TIME_absolute_get ();
992 if (reply_counter >= MAX_REPLY_TIMES)
995 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
997 pending->timeout, &peer->id, ssize,
998 &core_transmit_notify, peer);
999 if (peer->th == NULL)
1000 increment_stats ("# notify transmit ready failed");
1006 * Function called to send a request out to another peer.
1007 * Called both for locally initiated requests and those
1008 * received from other peers.
1010 * @param msg the encapsulated message
1011 * @param peer the peer to forward the message to
1012 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1015 forward_result_message (const struct GNUNET_MessageHeader *msg,
1016 struct PeerInfo *peer,
1017 struct DHT_MessageContext *msg_ctx)
1019 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1020 struct P2PPendingMessage *pending;
1030 increment_stats (STAT_RESULT_FORWARDS);
1032 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs (msg->size) +
1033 (sizeof (struct GNUNET_PeerIdentity) * msg_ctx->path_history_len);
1034 GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1035 psize = sizeof (struct P2PPendingMessage) + msize;
1036 pending = GNUNET_malloc (psize);
1037 pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1038 pending->importance = DHT_SEND_PRIORITY;
1039 pending->timeout = GNUNET_TIME_relative_get_forever ();
1040 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *) pending->msg;
1041 result_message->header.size = htons (msize);
1042 result_message->header.type =
1043 htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1044 result_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1045 if (msg_ctx->path_history_len > 0)
1047 /* End of pending is where enc_msg starts */
1048 path_start = (char *) &pending[1];
1049 /* Offset by the size of the enc_msg */
1050 path_start += ntohs (msg->size);
1051 memcpy (path_start, msg_ctx->path_history,
1052 msg_ctx->path_history_len * (sizeof (struct GNUNET_PeerIdentity)));
1054 for (i = 0; i < msg_ctx->path_history_len; i++)
1057 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1058 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1059 "(forward_result) Key %s Found peer %d:%s\n",
1060 GNUNET_h2s (&msg_ctx->key), i,
1061 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1065 result_message->options = htonl (msg_ctx->msg_options);
1066 result_message->hop_count = htonl (msg_ctx->hop_count + 1);
1067 GNUNET_assert (GNUNET_OK ==
1068 GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1072 result_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1073 memcpy (&result_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1074 /* Copy the enc_msg, then the path history as well! */
1075 memcpy (&result_message[1], msg, ntohs (msg->size));
1076 path_offset = (char *) &result_message[1];
1077 path_offset += ntohs (msg->size);
1078 /* If we have path history, copy it to the end of the whole thing */
1079 if (msg_ctx->path_history_len > 0)
1080 memcpy (path_offset, msg_ctx->path_history,
1081 msg_ctx->path_history_len * (sizeof (struct GNUNET_PeerIdentity)));
1083 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1084 "%s:%s Adding pending message size %d for peer %s\n", my_short_id,
1085 "DHT", msize, GNUNET_i2s (&peer->id));
1087 peer->pending_count++;
1088 increment_stats ("# pending messages scheduled");
1089 GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1091 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1092 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1097 * Called when core is ready to send a message we asked for
1098 * out to the destination.
1100 * @param cls closure (NULL)
1101 * @param size number of bytes available in buf
1102 * @param buf where the callee should write the message
1103 * @return number of bytes written to buf
1106 core_transmit_notify (void *cls, size_t size, void *buf)
1108 struct PeerInfo *peer = cls;
1110 struct P2PPendingMessage *pending;
1118 /* client disconnected */
1120 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n",
1121 my_short_id, "DHT");
1126 if (peer->head == NULL)
1130 pending = peer->head;
1132 reply_times[reply_counter] =
1133 GNUNET_TIME_absolute_get_difference (pending->scheduled,
1134 GNUNET_TIME_absolute_get ());
1135 msize = ntohs (pending->msg->size);
1139 memcpy (cbuf, pending->msg, msize);
1140 peer->pending_count--;
1141 increment_stats ("# pending messages sent");
1142 GNUNET_assert (peer->pending_count >= 0);
1143 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1144 GNUNET_free (pending);
1147 while (NULL != pending &&
1148 (size - off >= (msize = ntohs (pending->msg->size))))
1150 memcpy (&cbuf[off], pending->msg, msize);
1152 peer->pending_count--;
1153 increment_stats ("# pending messages sent");
1154 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1155 GNUNET_free (pending);
1156 pending = peer->head;
1159 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1160 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1167 * Compute the distance between have and target as a 32-bit value.
1168 * Differences in the lower bits must count stronger than differences
1169 * in the higher bits.
1171 * @return 0 if have==target, otherwise a number
1172 * that is larger as the distance between
1173 * the two hash codes increases
1176 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1178 unsigned int bucket;
1183 /* We have to represent the distance between two 2^9 (=512)-bit
1184 * numbers as a 2^5 (=32)-bit number with "0" being used for the
1185 * two numbers being identical; furthermore, we need to
1186 * guarantee that a difference in the number of matching
1187 * bits is always represented in the result.
1189 * We use 2^32/2^9 numerical values to distinguish between
1190 * hash codes that have the same LSB bit distance and
1191 * use the highest 2^9 bits of the result to signify the
1192 * number of (mis)matching LSB bits; if we have 0 matching
1193 * and hence 512 mismatching LSB bits we return -1 (since
1194 * 512 itself cannot be represented with 9 bits) */
1196 /* first, calculate the most significant 9 bits of our
1197 * result, aka the number of LSBs */
1198 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1199 /* bucket is now a value between 0 and 512 */
1201 return 0; /* perfect match */
1203 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1204 * below, we'd end up with max+1 (overflow)) */
1206 /* calculate the most significant bits of the final result */
1207 msb = (512 - bucket) << (32 - 9);
1208 /* calculate the 32-9 least significant bits of the final result by
1209 * looking at the differences in the 32-9 bits following the
1210 * mismatching bit at 'bucket' */
1212 for (i = bucket + 1;
1213 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1215 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
1216 GNUNET_CRYPTO_hash_get_bit (have, i))
1217 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1218 * last bit set will be 31 -- if
1219 * i does not reach 512 first... */
1226 * Return a number that is larger the closer the
1227 * "have" GNUNET_hash code is to the "target".
1229 * @return inverse distance metric, non-zero.
1230 * Must fudge the value if NO bits match.
1233 inverse_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1235 if (GNUNET_CRYPTO_hash_matching_bits (target, have) == 0)
1236 return 1; /* Never return 0! */
1237 return ((unsigned int) -1) - distance (target, have);
1242 * Find the optimal bucket for this key, regardless
1243 * of the current number of buckets in use.
1245 * @param hc the hashcode to compare our identity to
1247 * @return the proper bucket index, or GNUNET_SYSERR
1248 * on error (same hashcode)
1251 find_bucket (const GNUNET_HashCode * hc)
1255 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
1256 if (bits == MAX_BUCKETS)
1257 return GNUNET_SYSERR;
1258 return MAX_BUCKETS - bits - 1;
1263 * Find which k-bucket this peer should go into,
1264 * taking into account the size of the k-bucket
1265 * array. This means that if more bits match than
1266 * there are currently buckets, lowest_bucket will
1269 * @param hc GNUNET_HashCode we are finding the bucket for.
1271 * @return the proper bucket index for this key,
1272 * or GNUNET_SYSERR on error (same hashcode)
1275 find_current_bucket (const GNUNET_HashCode * hc)
1279 actual_bucket = find_bucket (hc);
1280 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1281 return lowest_bucket;
1282 if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1283 return lowest_bucket;
1284 return actual_bucket;
1289 * Find a routing table entry from a peer identity
1291 * @param peer the peer identity to look up
1293 * @return the routing table entry, or NULL if not found
1295 static struct PeerInfo *
1296 find_peer_by_id (const struct GNUNET_PeerIdentity *peer)
1299 struct PeerInfo *pos;
1301 bucket = find_current_bucket (&peer->hashPubKey);
1303 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
1306 pos = k_buckets[bucket].head;
1309 if (0 == memcmp (&pos->id, peer, sizeof (struct GNUNET_PeerIdentity)))
1313 return NULL; /* No such peer. */
1316 /* Forward declaration */
1318 update_core_preference (void *cls,
1319 const struct GNUNET_SCHEDULER_TaskContext *tc);
1323 * Function called with statistics about the given peer.
1325 * @param cls closure
1326 * @param peer identifies the peer
1327 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1328 * @param amount set to the amount that was actually reserved or unreserved;
1329 * either the full requested amount or zero (no partial reservations)
1330 * @param res_delay if the reservation could not be satisfied (amount was 0), how
1331 * long should the client wait until re-trying?
1332 * @param preference current traffic preference for the given peer
1335 update_core_preference_finish (void *cls,
1336 const struct GNUNET_PeerIdentity *peer,
1337 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1339 struct GNUNET_TIME_Relative res_delay,
1340 uint64_t preference)
1342 struct PeerInfo *peer_info = cls;
1344 peer_info->info_ctx = NULL;
1345 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
1346 &update_core_preference, peer_info);
1350 update_core_preference (void *cls,
1351 const struct GNUNET_SCHEDULER_TaskContext *tc)
1353 struct PeerInfo *peer = cls;
1354 uint64_t preference;
1355 unsigned int matching;
1357 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1362 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
1363 &peer->id.hashPubKey);
1367 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1368 "Peer identifier matches by %u bits, only shifting as much as we can!\n",
1373 preference = 1LL << matching;
1375 GNUNET_CORE_peer_change_preference (coreAPI, &peer->id,
1376 GNUNET_TIME_UNIT_FOREVER_REL,
1377 GNUNET_BANDWIDTH_VALUE_MAX, 0,
1379 &update_core_preference_finish, peer);
1384 * Given a peer and its corresponding bucket,
1385 * remove it from that bucket. Does not free
1386 * the PeerInfo struct, nor cancel messages
1387 * or free messages waiting to be sent to this
1390 * @param peer the peer to remove
1391 * @param bucket the bucket the peer belongs to
1394 remove_peer (struct PeerInfo *peer, unsigned int bucket)
1396 GNUNET_assert (k_buckets[bucket].peers_size > 0);
1397 GNUNET_CONTAINER_DLL_remove (k_buckets[bucket].head, k_buckets[bucket].tail,
1399 k_buckets[bucket].peers_size--;
1401 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) &&
1402 (lowest_bucket < MAX_BUCKETS - 1))
1408 * Removes peer from a bucket, then frees associated
1409 * resources and frees peer.
1411 * @param peer peer to be removed and freed
1412 * @param bucket which bucket this peer belongs to
1415 delete_peer (struct PeerInfo *peer, unsigned int bucket)
1417 struct P2PPendingMessage *pos;
1418 struct P2PPendingMessage *next;
1420 remove_peer (peer, bucket); /* First remove the peer from its bucket */
1421 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1422 GNUNET_SCHEDULER_cancel (peer->send_task);
1423 if ((peer->th != NULL) && (coreAPI != NULL))
1424 GNUNET_CORE_notify_transmit_ready_cancel (peer->th);
1427 while (pos != NULL) /* Remove any pending messages for this peer */
1430 ("# dht pending messages discarded (due to disconnect/shutdown)");
1436 GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
1437 (all_known_peers, &peer->id.hashPubKey));
1438 GNUNET_assert (GNUNET_YES ==
1439 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
1440 &peer->id.hashPubKey,
1443 decrement_stats (STAT_PEERS_KNOWN);
1448 * Iterator over hash map entries.
1450 * @param cls closure
1451 * @param key current key code
1452 * @param value PeerInfo of the peer to move to new lowest bucket
1453 * @return GNUNET_YES if we should continue to
1458 move_lowest_bucket (void *cls, const GNUNET_HashCode * key, void *value)
1460 struct PeerInfo *peer = value;
1463 GNUNET_assert (lowest_bucket > 0);
1464 new_bucket = lowest_bucket - 1;
1465 remove_peer (peer, lowest_bucket);
1466 GNUNET_CONTAINER_DLL_insert_after (k_buckets[new_bucket].head,
1467 k_buckets[new_bucket].tail,
1468 k_buckets[new_bucket].tail, peer);
1469 k_buckets[new_bucket].peers_size++;
1475 * The current lowest bucket is full, so change the lowest
1476 * bucket to the next lower down, and move any appropriate
1477 * entries in the current lowest bucket to the new bucket.
1480 enable_next_bucket ()
1482 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1483 struct PeerInfo *pos;
1485 GNUNET_assert (lowest_bucket > 0);
1486 to_remove = GNUNET_CONTAINER_multihashmap_create (bucket_size);
1487 pos = k_buckets[lowest_bucket].head;
1489 /* Populate the array of peers which should be in the next lowest bucket */
1492 if (find_bucket (&pos->id.hashPubKey) < lowest_bucket)
1493 GNUNET_CONTAINER_multihashmap_put (to_remove, &pos->id.hashPubKey, pos,
1494 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1498 /* Remove peers from lowest bucket, insert into next lowest bucket */
1499 GNUNET_CONTAINER_multihashmap_iterate (to_remove, &move_lowest_bucket, NULL);
1500 GNUNET_CONTAINER_multihashmap_destroy (to_remove);
1501 lowest_bucket = lowest_bucket - 1;
1506 * Find the closest peer in our routing table to the
1509 * @return The closest peer in our routing table to the
1510 * key, or NULL on error.
1512 static struct PeerInfo *
1513 find_closest_peer (const GNUNET_HashCode * hc)
1515 struct PeerInfo *pos;
1516 struct PeerInfo *current_closest;
1517 unsigned int lowest_distance;
1518 unsigned int temp_distance;
1522 lowest_distance = -1;
1524 if (k_buckets[lowest_bucket].peers_size == 0)
1527 current_closest = NULL;
1528 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1530 pos = k_buckets[bucket].head;
1532 while ((pos != NULL) && (count < bucket_size))
1534 temp_distance = distance (&pos->id.hashPubKey, hc);
1535 if (temp_distance <= lowest_distance)
1537 lowest_distance = temp_distance;
1538 current_closest = pos;
1544 GNUNET_assert (current_closest != NULL);
1545 return current_closest;
1550 * Function called to send a request out to another peer.
1551 * Called both for locally initiated requests and those
1552 * received from other peers.
1554 * @param msg the encapsulated message
1555 * @param peer the peer to forward the message to
1556 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1559 forward_message (const struct GNUNET_MessageHeader *msg, struct PeerInfo *peer,
1560 struct DHT_MessageContext *msg_ctx)
1562 struct GNUNET_DHT_P2PRouteMessage *route_message;
1563 struct P2PPendingMessage *pending;
1568 increment_stats (STAT_ROUTE_FORWARDS);
1569 GNUNET_assert (peer != NULL);
1570 if ((msg_ctx->closest != GNUNET_YES) &&
1571 (peer == find_closest_peer (&msg_ctx->key)))
1572 increment_stats (STAT_ROUTE_FORWARDS_CLOSEST);
1575 sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs (msg->size) +
1576 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1577 GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1578 psize = sizeof (struct P2PPendingMessage) + msize;
1579 pending = GNUNET_malloc (psize);
1580 pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1581 pending->importance = msg_ctx->importance;
1582 pending->timeout = msg_ctx->timeout;
1583 route_message = (struct GNUNET_DHT_P2PRouteMessage *) pending->msg;
1584 route_message->header.size = htons (msize);
1585 route_message->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1586 route_message->options = htonl (msg_ctx->msg_options);
1587 route_message->hop_count = htonl (msg_ctx->hop_count + 1);
1588 route_message->network_size = htonl (msg_ctx->network_size);
1589 route_message->desired_replication_level = htonl (msg_ctx->replication);
1590 route_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1591 if (msg_ctx->bloom != NULL)
1592 GNUNET_assert (GNUNET_OK ==
1593 GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1597 memcpy (&route_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1598 memcpy (&route_message[1], msg, ntohs (msg->size));
1599 if (GNUNET_DHT_RO_RECORD_ROUTE ==
1600 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
1602 route_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1603 /* Set pointer to start of enc_msg */
1604 route_path = (char *) &route_message[1];
1605 /* Offset to the end of the enc_msg */
1606 route_path += ntohs (msg->size);
1607 /* Copy the route_path after enc_msg */
1608 memcpy (route_path, msg_ctx->path_history,
1609 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1612 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1613 "%s:%s Adding pending message size %d for peer %s\n", my_short_id,
1614 "DHT", msize, GNUNET_i2s (&peer->id));
1616 peer->pending_count++;
1617 increment_stats ("# pending messages scheduled");
1618 GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1620 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1621 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1626 * Task run to check for messages that need to be sent to a client.
1628 * @param client a ClientList, containing the client and any messages to be sent to it
1631 process_pending_messages (struct ClientList *client)
1633 if ( (client->pending_head == NULL) ||
1634 (client->transmit_handle != NULL) )
1636 client->transmit_handle =
1637 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1638 ntohs (client->pending_head->
1640 GNUNET_TIME_UNIT_FOREVER_REL,
1641 &send_generic_reply, client);
1645 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1646 * request. A ClientList is passed as closure, take the head of the list
1647 * and copy it into buf, which has the result of sending the message to the
1650 * @param cls closure to this call
1651 * @param size maximum number of bytes available to send
1652 * @param buf where to copy the actual message to
1654 * @return the number of bytes actually copied, 0 indicates failure
1657 send_generic_reply (void *cls, size_t size, void *buf)
1659 struct ClientList *client = cls;
1661 struct PendingMessage *reply;
1665 client->transmit_handle = NULL;
1668 /* client disconnected */
1672 while ((NULL != (reply = client->pending_head)) &&
1673 (size >= off + (msize = ntohs (reply->msg->size))))
1675 GNUNET_CONTAINER_DLL_remove (client->pending_head, client->pending_tail,
1677 memcpy (&cbuf[off], reply->msg, msize);
1678 GNUNET_free (reply);
1681 process_pending_messages (client);
1683 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1684 "Transmitted %u bytes of replies to client\n",
1685 (unsigned int) off);
1692 * Add a PendingMessage to the clients list of messages to be sent
1694 * @param client the active client to send the message to
1695 * @param pending_message the actual message to send
1698 add_pending_message (struct ClientList *client,
1699 struct PendingMessage *pending_message)
1701 GNUNET_CONTAINER_DLL_insert_after (client->pending_head, client->pending_tail,
1702 client->pending_tail, pending_message);
1703 process_pending_messages (client);
1708 * Called when a reply needs to be sent to a client, as
1709 * a result it found to a GET or FIND PEER request.
1711 * @param client the client to send the reply to
1712 * @param message the encapsulated message to send
1713 * @param msg_ctx the context of the received message
1716 send_reply_to_client (struct ClientList *client,
1717 const struct GNUNET_MessageHeader *message,
1718 struct DHT_MessageContext *msg_ctx)
1720 struct GNUNET_DHT_RouteResultMessage *reply;
1721 struct PendingMessage *pending_message;
1731 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': Sending reply to client.\n",
1732 my_short_id, "DHT");
1734 msize = ntohs (message->size);
1736 sizeof (struct GNUNET_DHT_RouteResultMessage) + msize +
1737 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1738 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1740 GNUNET_break_op (0);
1743 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1744 pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1745 reply = (struct GNUNET_DHT_RouteResultMessage *) &pending_message[1];
1746 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1747 reply->header.size = htons (tsize);
1748 reply->outgoing_path_length = htonl (msg_ctx->path_history_len);
1749 reply->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1750 memcpy (&reply->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1751 reply_offset = (char *) &reply[1];
1752 memcpy (&reply[1], message, msize);
1753 if (msg_ctx->path_history_len > 0)
1755 reply_offset += msize;
1756 memcpy (reply_offset, msg_ctx->path_history,
1757 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1760 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1761 "Returning message with outgoing path length %d\n",
1762 msg_ctx->path_history_len);
1763 for (i = 0; i < msg_ctx->path_history_len; i++)
1766 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1767 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found peer %d:%s\n", i,
1768 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1771 add_pending_message (client, pending_message);
1775 * Consider whether or not we would like to have this peer added to
1776 * our routing table. Check whether bucket for this peer is full,
1777 * if so return negative; if not return positive. Since peers are
1778 * only added on CORE level connect, this doesn't actually add the
1779 * peer to the routing table.
1781 * @param peer the peer we are considering adding
1783 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1787 consider_peer (struct GNUNET_PeerIdentity *peer)
1792 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
1793 &peer->hashPubKey)) ||
1794 (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity))))
1795 return GNUNET_NO; /* We already know this peer (are connected even!) */
1796 bucket = find_current_bucket (&peer->hashPubKey);
1798 if ((k_buckets[bucket].peers_size < bucket_size) ||
1799 ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1807 * Task used to remove forwarding entries, either
1808 * after timeout, when full, or on shutdown.
1810 * @param cls the entry to remove
1811 * @param tc context, reason, etc.
1814 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1816 struct DHTRouteSource *source_info = cls;
1817 struct DHTQueryRecord *record;
1819 source_info = GNUNET_CONTAINER_heap_remove_node (source_info->hnode);
1820 record = source_info->record;
1821 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
1823 if (record->head == NULL) /* No more entries in DLL */
1825 GNUNET_assert (GNUNET_YES ==
1826 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
1827 &record->key, record));
1828 GNUNET_free (record);
1830 if (source_info->find_peers_responded != NULL)
1831 GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
1832 GNUNET_free (source_info);
1836 * Main function that handles whether or not to route a result
1837 * message to other peers, or to send to our local client.
1839 * @param msg the result message to be routed
1840 * @param msg_ctx context of the message we are routing
1842 * @return the number of peers the message was routed to,
1843 * GNUNET_SYSERR on failure
1846 route_result_message (struct GNUNET_MessageHeader *msg,
1847 struct DHT_MessageContext *msg_ctx)
1849 struct GNUNET_PeerIdentity new_peer;
1850 struct DHTQueryRecord *record;
1851 struct DHTRouteSource *pos;
1852 struct PeerInfo *peer_info;
1853 const struct GNUNET_MessageHeader *hello_msg;
1859 increment_stats (STAT_RESULTS);
1861 * If a find peer result message is received and contains a valid
1862 * HELLO for another peer, offer it to the transport service.
1864 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1866 if (ntohs (msg->size) <= sizeof (struct GNUNET_MessageHeader))
1867 GNUNET_break_op (0);
1869 hello_msg = &msg[1];
1870 if ((ntohs (hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
1872 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello_msg,
1875 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1876 "%s:%s Received non-HELLO message type in find peer result message!\n",
1877 my_short_id, "DHT");
1878 GNUNET_break_op (0);
1881 else /* We have a valid hello, and peer id stored in new_peer */
1883 find_peer_context.count++;
1884 increment_stats (STAT_FIND_PEER_REPLY);
1885 if (GNUNET_YES == consider_peer (&new_peer))
1887 increment_stats (STAT_HELLOS_PROVIDED);
1888 GNUNET_TRANSPORT_offer_hello (transport_handle, hello_msg, NULL, NULL);
1889 GNUNET_CORE_peer_request_connect (coreAPI, &new_peer, NULL, NULL);
1894 if (malicious_dropper == GNUNET_YES)
1898 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
1900 if (record == NULL) /* No record of this message! */
1903 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1904 "`%s:%s': Have no record of response key %s uid %llu\n",
1905 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
1906 msg_ctx->unique_id);
1908 #if DEBUG_DHT_ROUTING
1909 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1911 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
1912 msg_ctx->hop_count, GNUNET_SYSERR,
1913 &my_identity, &msg_ctx->key, msg_ctx->peer,
1917 if (msg_ctx->bloom != NULL)
1919 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
1920 msg_ctx->bloom = NULL;
1928 #if STRICT_FORWARDING
1929 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
1932 GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded,
1933 &new_peer.hashPubKey))
1935 increment_stats ("# find peer responses NOT forwarded (bloom match)");
1940 GNUNET_CONTAINER_bloomfilter_add (pos->find_peers_responded,
1941 &new_peer.hashPubKey);
1945 if (0 == memcmp (&pos->source, &my_identity, sizeof (struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1949 "`%s:%s': Sending response key %s uid %llu to client\n",
1950 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
1951 msg_ctx->unique_id);
1953 #if DEBUG_DHT_ROUTING
1954 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1956 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
1957 msg_ctx->hop_count, GNUNET_YES,
1958 &my_identity, &msg_ctx->key, msg_ctx->peer,
1962 increment_stats (STAT_RESULTS_TO_CLIENT);
1963 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
1964 increment_stats (STAT_GET_REPLY);
1966 for (i = 0; i < msg_ctx->path_history_len; i++)
1971 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1972 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1973 "(before client) Key %s Found peer %d:%s\n",
1974 GNUNET_h2s (&msg_ctx->key), i,
1975 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1978 send_reply_to_client (pos->client, msg, msg_ctx);
1980 else /* Send to peer */
1982 peer_info = find_peer_by_id (&pos->source);
1983 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
1989 if (msg_ctx->bloom == NULL)
1991 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
1993 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
1994 &my_identity.hashPubKey);
1996 GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom,
1997 &peer_info->id.hashPubKey)))
2000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2001 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n",
2002 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2003 msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2005 #if DEBUG_DHT_ROUTING
2006 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2008 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2009 msg_ctx->hop_count, GNUNET_NO,
2010 &my_identity, &msg_ctx->key,
2011 msg_ctx->peer, &pos->source);
2014 forward_result_message (msg, peer_info, msg_ctx);
2015 /* Try removing forward entries after sending once, only allows ONE response per request */
2016 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
2018 GNUNET_SCHEDULER_cancel (pos->delete_task);
2020 GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
2026 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2027 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n",
2028 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2029 msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2035 if (msg_ctx->bloom != NULL)
2037 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
2038 msg_ctx->bloom = NULL;
2045 * Iterator for local get request results,
2047 * @param cls closure for iterator, a DatacacheGetContext
2048 * @param exp when does this value expire?
2049 * @param key the key this data is stored under
2050 * @param size the size of the data identified by key
2051 * @param data the actual data
2052 * @param type the type of the data
2054 * @return GNUNET_OK to continue iteration, anything else
2055 * to stop iteration.
2058 datacache_get_iterator (void *cls, struct GNUNET_TIME_Absolute exp,
2059 const GNUNET_HashCode * key, size_t size,
2060 const char *data, enum GNUNET_BLOCK_Type type)
2062 struct DHT_MessageContext *msg_ctx = cls;
2063 struct DHT_MessageContext *new_msg_ctx;
2064 struct GNUNET_DHT_GetResultMessage *get_result;
2065 enum GNUNET_BLOCK_EvaluationResult eval;
2066 const struct DHTPutEntry *put_entry;
2075 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2076 "`%s:%s': Received `%s' response from datacache\n", my_short_id,
2080 put_entry = (const struct DHTPutEntry *) data;
2083 sizeof (struct DHTPutEntry) + put_entry->data_size +
2084 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)))
2086 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2087 "Path + data size doesn't add up for data inserted into datacache!\nData size %d, path length %d, expected %d, got %d\n",
2088 put_entry->data_size, put_entry->path_length,
2089 sizeof (struct DHTPutEntry) + put_entry->data_size +
2090 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)),
2092 msg_ctx->do_forward = GNUNET_NO;
2097 GNUNET_BLOCK_evaluate (block_context, type, key, &msg_ctx->reply_bf,
2098 msg_ctx->reply_bf_mutator, msg_ctx->xquery,
2099 msg_ctx->xquery_size, &put_entry[1],
2100 put_entry->data_size);
2104 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2105 msg_ctx->do_forward = GNUNET_NO;
2106 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2107 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2108 memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2109 if (GNUNET_DHT_RO_RECORD_ROUTE ==
2110 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2112 new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2113 new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2114 /* Assign to previous msg_ctx path history, caller should free after our return */
2115 new_msg_ctx->path_history = msg_ctx->path_history;
2117 for (i = 0; i < new_msg_ctx->path_history_len; i++)
2120 &new_msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
2121 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2122 "(get_iterator) Key %s Found peer %d:%s\n",
2123 GNUNET_h2s (&msg_ctx->key), i,
2124 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
2130 sizeof (struct GNUNET_DHT_GetResultMessage) + put_entry->data_size +
2131 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity));
2132 get_result = GNUNET_malloc (get_size);
2133 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2134 get_result->header.size = htons (get_size);
2135 get_result->expiration = GNUNET_TIME_absolute_hton (exp);
2136 get_result->type = htons (type);
2137 get_result->put_path_length = htons (put_entry->path_length);
2138 path_offset = (char *) &put_entry[1];
2139 path_offset += put_entry->data_size;
2141 for (i = 0; i < put_entry->path_length; i++)
2143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2144 "(get_iterator PUT path) Key %s Found peer %d:%s\n",
2145 GNUNET_h2s (&msg_ctx->key), i,
2146 GNUNET_i2s ((struct GNUNET_PeerIdentity *)
2149 GNUNET_PeerIdentity)]));
2152 /* Copy the actual data and the path_history to the end of the get result */
2153 memcpy (&get_result[1], &put_entry[1],
2154 put_entry->data_size +
2155 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)));
2156 new_msg_ctx->peer = &my_identity;
2157 new_msg_ctx->bloom =
2158 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2159 new_msg_ctx->hop_count = 0;
2160 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
2161 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2162 increment_stats (STAT_GET_RESPONSE_START);
2163 route_result_message (&get_result->header, new_msg_ctx);
2164 GNUNET_free (new_msg_ctx);
2165 GNUNET_free (get_result);
2167 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2169 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': Duplicate block error\n",
2170 my_short_id, "DHT");
2173 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2175 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "`%s:%s': Invalid request error\n",
2176 my_short_id, "DHT");
2179 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2181 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2182 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2186 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2187 GNUNET_break_op (0);
2188 msg_ctx->do_forward = GNUNET_NO;
2190 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2192 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2193 "`%s:%s': Unsupported block type (%u) in response!\n",
2194 my_short_id, "DHT", type);
2196 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2204 * Main function that handles whether or not to route a message to other
2207 * @param msg the message to be routed
2208 * @param msg_ctx the context containing all pertinent information about the message
2211 route_message (const struct GNUNET_MessageHeader *msg,
2212 struct DHT_MessageContext *msg_ctx);
2216 * Server handler for all dht get requests, look for data,
2217 * if found, send response either to clients or other peers.
2219 * @param msg the actual get message
2220 * @param msg_ctx struct containing pertinent information about the get request
2222 * @return number of items found for GET request
2225 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2226 struct DHT_MessageContext *msg_ctx)
2228 const struct GNUNET_DHT_GetMessage *get_msg;
2231 unsigned int results;
2233 enum GNUNET_BLOCK_Type type;
2235 msize = ntohs (msg->size);
2236 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2241 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2242 bf_size = ntohs (get_msg->bf_size);
2243 msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2244 msg_ctx->reply_bf_mutator = get_msg->bf_mutator;
2246 sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2251 end = (const char *) &get_msg[1];
2252 if (msg_ctx->xquery_size == 0)
2254 msg_ctx->xquery = NULL;
2258 msg_ctx->xquery = (const void *) end;
2259 end += msg_ctx->xquery_size;
2263 msg_ctx->reply_bf = NULL;
2268 GNUNET_CONTAINER_bloomfilter_init (end, bf_size,
2269 GNUNET_DHT_GET_BLOOMFILTER_K);
2271 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2273 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2274 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2275 my_short_id, "DHT", "GET", type, GNUNET_h2s (&msg_ctx->key),
2276 msg_ctx->unique_id);
2278 increment_stats (STAT_GETS);
2281 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2283 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2287 msg_ctx->do_forward = GNUNET_YES;
2288 if (datacache != NULL)
2290 GNUNET_DATACACHE_get (datacache, &msg_ctx->key, type,
2291 &datacache_get_iterator, msg_ctx);
2293 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2294 "`%s:%s': Found %d results for `%s' request uid %llu\n",
2295 my_short_id, "DHT", results, "GET", msg_ctx->unique_id);
2299 #if DEBUG_DHT_ROUTING
2300 if ((debug_routes) && (dhtlog_handle != NULL))
2302 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2303 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2307 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2309 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2310 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2311 &msg_ctx->key, msg_ctx->peer, NULL);
2317 /* check query valid */
2318 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID ==
2319 GNUNET_BLOCK_evaluate (block_context, type, &msg_ctx->key,
2320 &msg_ctx->reply_bf, msg_ctx->reply_bf_mutator,
2321 msg_ctx->xquery, msg_ctx->xquery_size, NULL, 0))
2323 GNUNET_break_op (0);
2324 msg_ctx->do_forward = GNUNET_NO;
2328 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2330 #if DEBUG_DHT_ROUTING
2331 if ((debug_routes) && (dhtlog_handle != NULL))
2333 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2334 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2339 if (msg_ctx->do_forward == GNUNET_YES)
2340 route_message (msg, msg_ctx);
2341 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2347 remove_recent_find_peer (void *cls,
2348 const struct GNUNET_SCHEDULER_TaskContext *tc)
2350 GNUNET_HashCode *key = cls;
2352 GNUNET_assert (GNUNET_YES ==
2353 GNUNET_CONTAINER_multihashmap_remove
2354 (recent_find_peer_requests, key, NULL));
2360 * Server handler for initiating local dht find peer requests
2362 * @param find_msg the actual find peer message
2363 * @param msg_ctx struct containing pertinent information about the request
2367 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2368 struct DHT_MessageContext *msg_ctx)
2370 struct GNUNET_MessageHeader *find_peer_result;
2371 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2372 struct DHT_MessageContext *new_msg_ctx;
2373 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2376 GNUNET_HashCode *recent_hash;
2377 struct GNUNET_MessageHeader *other_hello;
2378 size_t other_hello_size;
2379 struct GNUNET_PeerIdentity peer_id;
2381 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *) find_msg;
2382 GNUNET_break_op (ntohs (find_msg->size) >=
2383 (sizeof (struct GNUNET_DHT_FindPeerMessage)));
2384 if (ntohs (find_msg->size) < sizeof (struct GNUNET_DHT_FindPeerMessage))
2387 other_hello_size = 0;
2388 if (ntohs (find_msg->size) > sizeof (struct GNUNET_DHT_FindPeerMessage))
2391 ntohs (find_msg->size) - sizeof (struct GNUNET_DHT_FindPeerMessage);
2392 other_hello = GNUNET_malloc (other_hello_size);
2393 memcpy (other_hello, &find_peer_message[1], other_hello_size);
2394 if ((GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) other_hello) == 0)
2396 GNUNET_HELLO_get_id ((struct GNUNET_HELLO_Message *) other_hello,
2399 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2400 "Received invalid HELLO message in find peer request!\n");
2401 GNUNET_free (other_hello);
2404 #if FIND_PEER_WITH_HELLO
2405 if (GNUNET_YES == consider_peer (&peer_id))
2407 increment_stats (STAT_HELLOS_PROVIDED);
2408 GNUNET_TRANSPORT_offer_hello (transport_handle, other_hello, NULL, NULL);
2409 GNUNET_CORE_peer_request_connect (coreAPI, &peer_id, NULL, NULL);
2410 route_message (find_msg, msg_ctx);
2411 GNUNET_free (other_hello);
2414 else /* We don't want this peer! */
2416 route_message (find_msg, msg_ctx);
2417 GNUNET_free (other_hello);
2424 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2425 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2426 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2427 ntohs (find_msg->size), sizeof (struct GNUNET_MessageHeader));
2429 if (my_hello == NULL)
2432 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2433 "`%s': Our HELLO is null, can't return.\n", "DHT");
2435 GNUNET_free_non_null (other_hello);
2436 route_message (find_msg, msg_ctx);
2441 GNUNET_CONTAINER_bloomfilter_init (find_peer_message->bloomfilter,
2442 DHT_BLOOM_SIZE, DHT_BLOOM_K);
2444 GNUNET_CONTAINER_bloomfilter_test (incoming_bloom,
2445 &my_identity.hashPubKey))
2447 increment_stats (STAT_BLOOM_FIND_PEER);
2448 GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2449 GNUNET_free_non_null (other_hello);
2450 route_message (find_msg, msg_ctx);
2451 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!) */
2453 GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2455 #if RESTRICT_FIND_PEER
2458 * Ignore any find peer requests from a peer we have seen very recently.
2460 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! */
2462 increment_stats ("# dht find peer requests ignored (recently seen!)");
2463 GNUNET_free_non_null (other_hello);
2468 * Use this check to only allow the peer to respond to find peer requests if
2469 * it would be beneficial to have the requesting peer in this peers routing
2470 * table. Can be used to thwart peers flooding the network with find peer
2471 * requests that we don't care about. However, if a new peer is joining
2472 * the network and has no other peers this is a problem (assume all buckets
2473 * full, no one will respond!).
2475 memcpy (&peer_id.hashPubKey, &msg_ctx->key, sizeof (GNUNET_HashCode));
2476 if (GNUNET_NO == consider_peer (&peer_id))
2478 increment_stats ("# dht find peer requests ignored (do not need!)");
2479 GNUNET_free_non_null (other_hello);
2480 route_message (find_msg, msg_ctx);
2485 recent_hash = GNUNET_malloc (sizeof (GNUNET_HashCode));
2486 memcpy (recent_hash, &msg_ctx->key, sizeof (GNUNET_HashCode));
2487 if (GNUNET_SYSERR !=
2488 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2489 &msg_ctx->key, NULL,
2490 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2494 "Adding recent remove task for key `%s`!\n",
2495 GNUNET_h2s (&msg_ctx->key));
2497 /* Only add a task if there wasn't one for this key already! */
2498 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2499 (GNUNET_TIME_UNIT_SECONDS, 30),
2500 &remove_recent_find_peer, recent_hash);
2504 GNUNET_free (recent_hash);
2506 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2507 "Received duplicate find peer request too soon!\n");
2511 /* Simplistic find_peer functionality, always return our hello */
2512 hello_size = ntohs (my_hello->size);
2513 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2515 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2517 GNUNET_break_op (0);
2518 GNUNET_free_non_null (other_hello);
2522 find_peer_result = GNUNET_malloc (tsize);
2523 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2524 find_peer_result->size = htons (tsize);
2525 memcpy (&find_peer_result[1], my_hello, hello_size);
2527 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2528 "`%s': Sending hello size %d to requesting peer.\n", "DHT",
2532 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2533 memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2534 new_msg_ctx->peer = &my_identity;
2535 new_msg_ctx->bloom =
2536 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2537 new_msg_ctx->hop_count = 0;
2538 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make find peer requests a higher priority */
2539 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2540 increment_stats (STAT_FIND_PEER_ANSWER);
2541 if (GNUNET_DHT_RO_RECORD_ROUTE ==
2542 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2544 new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2545 new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2546 /* Assign to previous msg_ctx path history, caller should free after our return */
2547 new_msg_ctx->path_history = msg_ctx->path_history;
2549 route_result_message (find_peer_result, new_msg_ctx);
2550 GNUNET_free (new_msg_ctx);
2551 #if DEBUG_DHT_ROUTING
2552 if ((debug_routes) && (dhtlog_handle != NULL))
2554 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2555 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2559 GNUNET_free_non_null (other_hello);
2560 GNUNET_free (find_peer_result);
2561 route_message (find_msg, msg_ctx);
2566 * Server handler for initiating local dht put requests
2568 * @param msg the actual put message
2569 * @param msg_ctx struct containing pertinent information about the request
2572 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2573 struct DHT_MessageContext *msg_ctx)
2575 const struct GNUNET_DHT_PutMessage *put_msg;
2576 struct DHTPutEntry *put_entry;
2577 unsigned int put_size;
2579 enum GNUNET_BLOCK_Type put_type;
2582 GNUNET_HashCode key;
2583 struct DHTQueryRecord *record;
2585 GNUNET_assert (ntohs (msg->size) >= sizeof (struct GNUNET_DHT_PutMessage));
2587 put_msg = (const struct GNUNET_DHT_PutMessage *) msg;
2588 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2590 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2592 #if DEBUG_DHT_ROUTING
2593 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2595 /** Log routes that die due to high load! */
2596 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2597 msg_ctx->hop_count, GNUNET_SYSERR,
2598 &my_identity, &msg_ctx->key, msg_ctx->peer,
2606 ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2608 GNUNET_BLOCK_get_key (block_context, put_type, &put_msg[1], data_size,
2610 if (GNUNET_NO == ret)
2612 #if DEBUG_DHT_ROUTING
2613 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2615 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2616 msg_ctx->hop_count, GNUNET_SYSERR,
2617 &my_identity, &msg_ctx->key, msg_ctx->peer,
2622 GNUNET_break_op (0);
2625 if ((GNUNET_YES == ret) &&
2626 (0 != memcmp (&key, &msg_ctx->key, sizeof (GNUNET_HashCode))))
2628 #if DEBUG_DHT_ROUTING
2629 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2631 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2632 msg_ctx->hop_count, GNUNET_SYSERR,
2633 &my_identity, &msg_ctx->key, msg_ctx->peer,
2637 /* invalid wrapper: key mismatch! */
2638 GNUNET_break_op (0);
2641 /* ret == GNUNET_SYSERR means that there is no known relationship between
2642 * data and the key, so we cannot check it */
2644 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2645 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2646 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2647 msg_ctx->unique_id);
2649 #if DEBUG_DHT_ROUTING
2650 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2652 if ((debug_routes) && (dhtlog_handle != NULL))
2654 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2655 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2661 // GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT 1\n");
2662 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2665 struct DHTRouteSource *pos;
2666 struct GNUNET_DHT_GetMessage *gmsg;
2669 // GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT 2\n");
2673 /* TODO: do only for local started requests? or also for remote peers? */
2674 /* TODO: include this in statistics? under what? */
2675 if (NULL == pos->client)
2678 gsize = data_size + sizeof(struct GNUNET_DHT_GetMessage);
2679 gmsg = GNUNET_malloc(gsize);
2680 gmsg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2681 gmsg->header.size = htons(gsize);
2682 gmsg->type = put_msg->type;
2683 memcpy(&gmsg[1], &put_msg[1], data_size);
2685 /* TODO: duplicate and reverse order of path_history? */
2686 send_reply_to_client (pos->client, &gmsg->header, msg_ctx);
2690 // GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT END\n");
2692 if (msg_ctx->closest != GNUNET_YES)
2694 route_message (msg, msg_ctx);
2699 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2700 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2701 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2702 msg_ctx->unique_id);
2705 #if DEBUG_DHT_ROUTING
2706 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2708 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2709 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2710 &msg_ctx->key, msg_ctx->peer, NULL);
2713 if ((debug_routes) && (dhtlog_handle != NULL))
2715 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2716 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2721 increment_stats (STAT_PUTS_INSERTED);
2722 if (datacache != NULL)
2724 /* Put size is actual data size plus struct overhead plus path length (if any) */
2726 data_size + sizeof (struct DHTPutEntry) +
2727 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2728 put_entry = GNUNET_malloc (put_size);
2729 put_entry->data_size = data_size;
2730 put_entry->path_length = msg_ctx->path_history_len;
2731 /* Copy data to end of put entry */
2732 memcpy (&put_entry[1], &put_msg[1], data_size);
2733 if (msg_ctx->path_history_len > 0)
2735 /* Copy path after data */
2736 path_offset = (char *) &put_entry[1];
2737 path_offset += data_size;
2738 memcpy (path_offset, msg_ctx->path_history,
2739 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2743 GNUNET_DATACACHE_put (datacache, &msg_ctx->key, put_size,
2744 (const char *) put_entry, put_type,
2745 GNUNET_TIME_absolute_ntoh (put_msg->expiration));
2746 GNUNET_free (put_entry);
2749 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2750 "`%s:%s': %s request received, but have no datacache!\n",
2751 my_short_id, "DHT", "PUT");
2753 if (stop_on_closest == GNUNET_NO)
2754 route_message (msg, msg_ctx);
2759 * To how many peers should we (on average)
2760 * forward the request to obtain the desired
2761 * target_replication count (on average).
2763 * returns: target_replication / (est. hops) + (target_replication * hop_count)
2764 * where est. hops is typically 2 * the routing table depth
2766 * @param hop_count number of hops the message has traversed
2767 * @param target_replication the number of total paths desired
2769 * @return Some number of peers to forward the message to
2772 get_forward_count (unsigned int hop_count, size_t target_replication)
2774 uint32_t random_value;
2775 unsigned int forward_count;
2779 * If we are behaving in strict kademlia mode, send multiple initial requests,
2780 * but then only send to 1 or 0 peers based strictly on the number of hops.
2782 if (strict_kademlia == GNUNET_YES)
2785 return kademlia_replication;
2786 if (hop_count < log_of_network_size_estimate * 2.0)
2791 if (hop_count > log_of_network_size_estimate * 2.0)
2793 if (GNUNET_YES == paper_forwarding)
2795 /* Once we have reached our ideal number of hops, don't stop forwarding! */
2799 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2800 "Hop count too high (est %f, lowest %d), NOT Forwarding request\n",
2801 log_of_network_size_estimate * 2.0, lowest_bucket);
2806 if (GNUNET_YES == paper_forwarding)
2808 /* FIXME: re-run replication trials with this formula */
2810 1 + (target_replication - 1.0) / (log_of_network_size_estimate +
2811 ((float) (target_replication - 1.0) *
2813 /* Set forward count to floor of target_value */
2814 forward_count = (unsigned int) target_value;
2815 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
2816 target_value = target_value - forward_count;
2818 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
2820 if (random_value < (target_value * UINT32_MAX))
2828 target_replication / (log_of_network_size_estimate +
2829 ((float) target_replication * hop_count));
2830 if (target_value > 1)
2832 /* Set forward count to floor of target_value */
2833 forward_count = (unsigned int) target_value;
2834 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
2835 target_value = target_value - forward_count;
2839 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
2841 if (random_value < (target_value * UINT32_MAX))
2845 return forward_count;
2850 * Check whether my identity is closer than any known peers.
2851 * If a non-null bloomfilter is given, check if this is the closest
2852 * peer that hasn't already been routed to.
2854 * @param target hash code to check closeness to
2855 * @param bloom bloomfilter, exclude these entries from the decision
2856 * @return GNUNET_YES if node location is closest,
2857 * GNUNET_NO otherwise.
2860 am_closest_peer (const GNUNET_HashCode * target,
2861 struct GNUNET_CONTAINER_BloomFilter *bloom)
2867 struct PeerInfo *pos;
2868 unsigned int my_distance;
2870 if (0 == memcmp (&my_identity.hashPubKey, target, sizeof (GNUNET_HashCode)))
2873 bucket_num = find_current_bucket (target);
2875 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, target);
2876 my_distance = distance (&my_identity.hashPubKey, target);
2877 pos = k_buckets[bucket_num].head;
2879 while ((pos != NULL) && (count < bucket_size))
2881 if ((bloom != NULL) &&
2883 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
2886 continue; /* Skip already checked entries */
2889 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, target);
2890 if (other_bits > bits)
2892 else if (other_bits == bits) /* We match the same number of bits */
2894 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2896 if (distance (&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2902 /* No peers closer, we are the closest! */
2908 * Select a peer from the routing table that would be a good routing
2909 * destination for sending a message for "target". The resulting peer
2910 * must not be in the set of blocked peers.<p>
2912 * Note that we should not ALWAYS select the closest peer to the
2913 * target, peers further away from the target should be chosen with
2914 * exponentially declining probability.
2916 * @param target the key we are selecting a peer to route to
2917 * @param bloom a bloomfilter containing entries this request has seen already
2918 * @param hops how many hops has this message traversed thus far
2920 * @return Peer to route to, or NULL on error
2922 static struct PeerInfo *
2923 select_peer (const GNUNET_HashCode * target,
2924 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2928 unsigned int selected;
2929 struct PeerInfo *pos;
2930 unsigned int distance;
2931 unsigned int largest_distance;
2932 struct PeerInfo *chosen;
2934 /** If we are doing kademlia routing (saves some cycles) */
2935 if ( (strict_kademlia == GNUNET_YES) ||
2936 (hops >= log_of_network_size_estimate) )
2938 /* greedy selection (closest peer that is not in bloomfilter) */
2939 largest_distance = 0;
2941 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2943 pos = k_buckets[bc].head;
2945 while ((pos != NULL) && (count < bucket_size))
2947 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2949 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2951 distance = inverse_distance (target, &pos->id.hashPubKey);
2952 if (distance > largest_distance)
2955 largest_distance = distance;
2962 if ((largest_distance > 0) && (chosen != NULL))
2964 GNUNET_CONTAINER_bloomfilter_add (bloom, &chosen->id.hashPubKey);
2967 return NULL; /* no peer available or we are the closest */
2971 /* select "random" peer */
2972 /* count number of peers that are available and not filtered */
2974 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2976 pos = k_buckets[bc].head;
2977 while ((pos != NULL) && (count < bucket_size))
2980 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2983 continue; /* Ignore bloomfiltered peers */
2989 if (count == 0) /* No peers to select from! */
2991 increment_stats ("# failed to select peer");
2994 /* Now actually choose a peer */
2996 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
2998 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
3000 pos = k_buckets[bc].head;
3001 while ((pos != NULL) && (count < bucket_size))
3004 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3007 continue; /* Ignore bloomfiltered peers */
3009 if (0 == selected--)
3020 * Task used to remove recent entries, either
3021 * after timeout, when full, or on shutdown.
3023 * @param cls the entry to remove
3024 * @param tc context, reason, etc.
3027 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3029 struct RecentRequest *req = cls;
3030 static GNUNET_HashCode hash;
3032 GNUNET_assert (req != NULL);
3033 hash_from_uid (req->uid, &hash);
3034 GNUNET_assert (GNUNET_YES ==
3035 GNUNET_CONTAINER_multihashmap_remove (recent.hashmap, &hash,
3037 GNUNET_CONTAINER_heap_remove_node (req->heap_node);
3038 GNUNET_CONTAINER_bloomfilter_free (req->bloom);
3042 * if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3044 * GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3045 * GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3051 * Remember this routing request so that if a reply is
3052 * received we can either forward it to the correct peer
3053 * or return the result locally.
3055 * @param msg_ctx Context of the route request
3057 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3060 cache_response (struct DHT_MessageContext *msg_ctx)
3062 struct DHTQueryRecord *record;
3063 struct DHTRouteSource *source_info;
3064 struct DHTRouteSource *pos;
3065 struct GNUNET_TIME_Absolute now;
3066 unsigned int current_size;
3068 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3070 #if DELETE_WHEN_FULL
3071 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3073 source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3074 GNUNET_assert (source_info != NULL);
3075 record = source_info->record;
3076 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3077 if (record->head == NULL) /* No more entries in DLL */
3079 GNUNET_assert (GNUNET_YES ==
3080 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
3083 GNUNET_free (record);
3085 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3087 GNUNET_SCHEDULER_cancel (source_info->delete_task);
3088 source_info->delete_task = GNUNET_SCHEDULER_NO_TASK;
3090 if (source_info->find_peers_responded != NULL)
3091 GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
3092 GNUNET_free (source_info);
3093 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3096 /** Non-local request and have too many outstanding forwards, discard! */
3097 if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3100 now = GNUNET_TIME_absolute_get ();
3102 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
3103 if (record != NULL) /* Already know this request! */
3108 if ( (NULL != msg_ctx->peer) &&
3110 memcmp (msg_ctx->peer, &pos->source,
3111 sizeof (struct GNUNET_PeerIdentity))) )
3112 break; /* Already have this peer in reply list! */
3115 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3117 GNUNET_CONTAINER_heap_update_cost (forward_list.minHeap, pos->hnode,
3124 record = GNUNET_malloc (sizeof (struct DHTQueryRecord));
3125 GNUNET_assert (GNUNET_OK ==
3126 GNUNET_CONTAINER_multihashmap_put (forward_list.hashmap,
3127 &msg_ctx->key, record,
3128 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3129 memcpy (&record->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3132 source_info = GNUNET_malloc (sizeof (struct DHTRouteSource));
3133 source_info->record = record;
3134 source_info->delete_task =
3135 GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry,
3137 source_info->find_peers_responded =
3138 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3139 memcpy (&source_info->source, msg_ctx->peer,
3140 sizeof (struct GNUNET_PeerIdentity));
3141 GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail,
3143 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3145 source_info->client = msg_ctx->client;
3146 now = GNUNET_TIME_absolute_get_forever ();
3148 source_info->hnode =
3149 GNUNET_CONTAINER_heap_insert (forward_list.minHeap, source_info,
3152 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3153 "`%s:%s': Created new forward source info for %s uid %llu\n",
3154 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3155 msg_ctx->unique_id);
3162 * Main function that handles whether or not to route a message to other
3165 * @param msg the message to be routed
3166 * @param msg_ctx the context containing all pertinent information about the message
3169 route_message (const struct GNUNET_MessageHeader *msg,
3170 struct DHT_MessageContext *msg_ctx)
3173 struct PeerInfo *selected;
3175 #if DEBUG_DHT_ROUTING > 1
3176 struct PeerInfo *nearest;
3178 unsigned int target_forward_count;
3179 unsigned int forward_count;
3180 struct RecentRequest *recent_req;
3181 GNUNET_HashCode unique_hash;
3182 char *stat_forward_count;
3183 char *temp_stat_str;
3185 #if DEBUG_DHT_ROUTING
3189 if (malicious_dropper == GNUNET_YES)
3191 #if DEBUG_DHT_ROUTING
3192 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3194 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3195 msg_ctx->hop_count, GNUNET_SYSERR,
3196 &my_identity, &msg_ctx->key, msg_ctx->peer,
3200 if (msg_ctx->bloom != NULL)
3202 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3203 msg_ctx->bloom = NULL;
3208 increment_stats (STAT_ROUTES);
3209 target_forward_count =
3210 get_forward_count (msg_ctx->hop_count, msg_ctx->replication);
3211 GNUNET_asprintf (&stat_forward_count, "# forward counts of %d",
3212 target_forward_count);
3213 increment_stats (stat_forward_count);
3214 GNUNET_free (stat_forward_count);
3215 if (msg_ctx->bloom == NULL)
3217 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3219 if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) &&
3220 (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3221 target_forward_count = 0;
3224 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3225 * any closer peers (which is being checked for below). Since we are doing recursive
3226 * routing we have no choice but to stop forwarding in this case. This means that at
3227 * any given step the request may NOT be forwarded to alpha peers (because routes will
3228 * stop and the parallel route will not be aware of it). Of course, assuming that we
3229 * have fulfilled the Kademlia requirements for routing table fullness this will never
3230 * ever ever be a problem.
3232 * However, is this fair?
3234 * Since we use these requests to build our routing tables (and we build them in the
3235 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3236 * routing tables still get constructed.
3238 if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) &&
3239 (msg_ctx->hop_count > 0) &&
3240 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3241 target_forward_count = 0;
3244 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3245 hash_from_uid (msg_ctx->unique_id, &unique_hash);
3247 GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3250 GNUNET_CONTAINER_multihashmap_get (recent.hashmap, &unique_hash);
3251 GNUNET_assert (recent_req != NULL);
3252 if (0 != memcmp (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode)))
3253 increment_stats (STAT_DUPLICATE_UID);
3256 increment_stats (STAT_RECENT_SEEN);
3257 GNUNET_CONTAINER_bloomfilter_or2 (msg_ctx->bloom, recent_req->bloom,
3263 recent_req = GNUNET_malloc (sizeof (struct RecentRequest));
3264 recent_req->uid = msg_ctx->unique_id;
3265 memcpy (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3266 recent_req->remove_task =
3267 GNUNET_SCHEDULER_add_delayed (DEFAULT_RECENT_REMOVAL, &remove_recent,
3269 recent_req->heap_node =
3270 GNUNET_CONTAINER_heap_insert (recent.minHeap, recent_req,
3271 GNUNET_TIME_absolute_get ().abs_value);
3273 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3274 GNUNET_CONTAINER_multihashmap_put (recent.hashmap, &unique_hash, recent_req,
3275 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3278 if (GNUNET_CONTAINER_multihashmap_size (recent.hashmap) > DHT_MAX_RECENT)
3280 recent_req = GNUNET_CONTAINER_heap_peek (recent.minHeap);
3281 GNUNET_assert (recent_req != NULL);
3282 GNUNET_SCHEDULER_cancel (recent_req->remove_task);
3283 recent_req->remove_task =
3284 GNUNET_SCHEDULER_add_now (&remove_recent, recent_req);
3288 for (i = 0; i < target_forward_count; i++)
3290 selected = select_peer (&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3292 if (selected != NULL)
3295 if (GNUNET_CRYPTO_hash_matching_bits
3296 (&selected->id.hashPubKey,
3298 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
3300 GNUNET_asprintf (&temp_stat_str,
3301 "# requests routed to close(r) peer hop %u",
3302 msg_ctx->hop_count);
3304 GNUNET_asprintf (&temp_stat_str,
3305 "# requests routed to less close peer hop %u",
3306 msg_ctx->hop_count);
3307 if (temp_stat_str != NULL)
3309 increment_stats (temp_stat_str);
3310 GNUNET_free (temp_stat_str);
3312 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
3313 &selected->id.hashPubKey);
3314 #if DEBUG_DHT_ROUTING > 1
3315 nearest = find_closest_peer (&msg_ctx->key);
3316 nearest_buf = GNUNET_strdup (GNUNET_i2s (&nearest->id));
3317 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3318 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n",
3319 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3320 msg_ctx->unique_id, GNUNET_i2s (&selected->id), nearest_buf,
3321 GNUNET_CRYPTO_hash_matching_bits (&nearest->id.hashPubKey,
3323 distance (&nearest->id.hashPubKey, msg_ctx->key));
3324 GNUNET_free (nearest_buf);
3326 #if DEBUG_DHT_ROUTING
3327 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3329 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3330 msg_ctx->hop_count, GNUNET_NO,
3331 &my_identity, &msg_ctx->key, msg_ctx->peer,
3335 forward_message (msg, selected, msg_ctx);
3339 if (msg_ctx->bloom != NULL)
3341 GNUNET_CONTAINER_bloomfilter_or2 (recent_req->bloom, msg_ctx->bloom,
3343 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3344 msg_ctx->bloom = NULL;
3347 #if DEBUG_DHT_ROUTING
3348 if (forward_count == 0)
3349 ret = GNUNET_SYSERR;
3353 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3355 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3356 msg_ctx->hop_count, ret, &my_identity,
3357 &msg_ctx->key, msg_ctx->peer, NULL);
3364 * Main function that handles whether or not to route a message to other
3367 * @param msg the message to be routed
3368 * @param msg_ctx the context containing all pertinent information about the message
3371 demultiplex_message (const struct GNUNET_MessageHeader *msg,
3372 struct DHT_MessageContext *msg_ctx)
3374 /* FIXME: Should we use closest excluding those we won't route to (the bloomfilter problem)? */
3375 msg_ctx->closest = am_closest_peer (&msg_ctx->key, msg_ctx->bloom);
3377 switch (ntohs (msg->type))
3379 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3380 cache_response (msg_ctx);
3381 handle_dht_get (msg, msg_ctx);
3383 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3384 increment_stats (STAT_PUTS);
3385 handle_dht_put (msg, msg_ctx);
3387 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3388 increment_stats (STAT_FIND_PEER);
3389 if (((msg_ctx->hop_count > 0) &&
3391 memcmp (msg_ctx->peer, &my_identity,
3392 sizeof (struct GNUNET_PeerIdentity)))) ||
3393 (msg_ctx->client != NULL))
3395 cache_response (msg_ctx);
3396 if ((msg_ctx->closest == GNUNET_YES) ||
3397 (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3398 handle_dht_find_peer (msg, msg_ctx);
3401 route_message (msg, msg_ctx);
3402 #if DEBUG_DHT_ROUTING
3403 if (msg_ctx->hop_count == 0) /* Locally initiated request */
3405 if ((debug_routes) && (dhtlog_handle != NULL))
3407 dhtlog_handle->insert_dhtkey (NULL, &msg_ctx->key);
3408 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
3409 msg_ctx->hop_count, GNUNET_NO,
3410 &my_identity, &msg_ctx->key);
3416 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3417 "`%s': Message type (%d) not handled, forwarding anyway!\n",
3418 "DHT", ntohs (msg->type));
3419 route_message (msg, msg_ctx);
3425 * Iterator over hash map entries.
3427 * @param cls client to search for in source routes
3428 * @param key current key code (ignored)
3429 * @param value value in the hash map, a DHTQueryRecord
3430 * @return GNUNET_YES if we should continue to
3435 find_client_records (void *cls, const GNUNET_HashCode * key, void *value)
3437 struct ClientList *client = cls;
3438 struct DHTQueryRecord *record = value;
3439 struct DHTRouteSource *pos;
3444 if (pos->client == client)
3450 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, pos);
3451 GNUNET_CONTAINER_heap_remove_node (pos->hnode);
3452 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3454 GNUNET_SCHEDULER_cancel (pos->delete_task);
3455 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
3457 if (pos->find_peers_responded != NULL)
3458 GNUNET_CONTAINER_bloomfilter_free (pos->find_peers_responded);
3461 if (record->head == NULL) /* No more entries in DLL */
3463 GNUNET_assert (GNUNET_YES ==
3464 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
3465 &record->key, record));
3466 GNUNET_free (record);
3472 * Functions with this signature are called whenever a client
3473 * is disconnected on the network level.
3475 * @param cls closure (NULL for dht)
3476 * @param client identification of the client; NULL
3477 * for the last call when the server is destroyed
3480 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
3482 struct ClientList *pos = client_list;
3483 struct ClientList *prev;
3484 struct ClientList *found;
3485 struct PendingMessage *reply;
3491 if (pos->client_handle == client)
3494 prev->next = pos->next;
3496 client_list = pos->next;
3506 if (found->transmit_handle != NULL)
3507 GNUNET_CONNECTION_notify_transmit_ready_cancel (found->transmit_handle);
3509 while (NULL != (reply = found->pending_head))
3511 GNUNET_CONTAINER_DLL_remove (found->pending_head, found->pending_tail,
3513 GNUNET_free (reply);
3515 GNUNET_CONTAINER_multihashmap_iterate (forward_list.hashmap,
3516 &find_client_records, found);
3517 GNUNET_free (found);
3522 * Find a client if it exists, add it otherwise.
3524 * @param client the server handle to the client
3526 * @return the client if found, a new client otherwise
3528 static struct ClientList *
3529 find_active_client (struct GNUNET_SERVER_Client *client)
3531 struct ClientList *pos = client_list;
3532 struct ClientList *ret;
3536 if (pos->client_handle == client)
3541 ret = GNUNET_malloc (sizeof (struct ClientList));
3542 ret->client_handle = client;
3543 ret->next = client_list;
3551 * Task to send a malicious put message across the network.
3553 * @param cls closure for this task
3554 * @param tc the context under which the task is running
3557 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3559 static struct GNUNET_DHT_PutMessage put_message;
3560 static struct DHT_MessageContext msg_ctx;
3561 static GNUNET_HashCode key;
3562 uint32_t random_key;
3564 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3566 put_message.header.size = htons (sizeof (struct GNUNET_DHT_PutMessage));
3567 put_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3568 put_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3569 put_message.expiration =
3570 GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_forever ());
3571 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3573 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
3574 GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
3575 memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
3577 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
3578 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
3579 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3580 msg_ctx.msg_options = ntohl (0);
3581 msg_ctx.network_size = log_of_network_size_estimate;
3582 msg_ctx.peer = &my_identity;
3583 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3584 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3585 #if DEBUG_DHT_ROUTING
3586 if (dhtlog_handle != NULL)
3587 dhtlog_handle->insert_dhtkey (NULL, &key);
3589 increment_stats (STAT_PUT_START);
3590 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3591 "%s:%s Sending malicious PUT message with hash %s\n", my_short_id,
3592 "DHT", GNUNET_h2s (&key));
3593 demultiplex_message (&put_message.header, &msg_ctx);
3594 GNUNET_SCHEDULER_add_delayed (malicious_put_frequency,
3595 &malicious_put_task, NULL);
3600 * Task to send a malicious put message across the network.
3602 * @param cls closure for this task
3603 * @param tc the context under which the task is running
3606 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3608 static struct GNUNET_DHT_GetMessage get_message;
3609 struct DHT_MessageContext msg_ctx;
3610 static GNUNET_HashCode key;
3611 uint32_t random_key;
3613 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3616 get_message.header.size = htons (sizeof (struct GNUNET_DHT_GetMessage));
3617 get_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET);
3618 get_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3619 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3621 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
3622 GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
3623 memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
3625 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
3626 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
3627 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3628 msg_ctx.msg_options = ntohl (0);
3629 msg_ctx.network_size = log_of_network_size_estimate;
3630 msg_ctx.peer = &my_identity;
3631 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3632 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3633 #if DEBUG_DHT_ROUTING
3634 if (dhtlog_handle != NULL)
3635 dhtlog_handle->insert_dhtkey (NULL, &key);
3637 increment_stats (STAT_GET_START);
3638 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3639 "%s:%s Sending malicious GET message with hash %s\n", my_short_id,
3640 "DHT", GNUNET_h2s (&key));
3641 demultiplex_message (&get_message.header, &msg_ctx);
3642 GNUNET_SCHEDULER_add_delayed (malicious_get_frequency,
3643 &malicious_get_task, NULL);
3649 * Iterator over hash map entries.
3651 * @param cls closure
3652 * @param key current key code
3653 * @param value value in the hash map
3654 * @return GNUNET_YES if we should continue to
3659 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
3661 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3663 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3668 * Task to send a find peer message for our own peer identifier
3669 * so that we can find the closest peers in the network to ourselves
3670 * and attempt to connect to them.
3672 * @param cls closure for this task
3673 * @param tc the context under which the task is running
3676 send_find_peer_message (void *cls,
3677 const struct GNUNET_SCHEDULER_TaskContext *tc)
3679 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3680 struct DHT_MessageContext msg_ctx;
3681 struct GNUNET_TIME_Relative next_send_time;
3682 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3684 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3687 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! */
3689 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3690 "Have %d newly found peers since last find peer message sent!\n",
3692 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3693 &send_find_peer_message, NULL);
3694 newly_found_peers = 0;
3698 increment_stats (STAT_FIND_PEER_START);
3699 #if FIND_PEER_WITH_HELLO
3701 GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage) +
3702 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *)
3704 find_peer_msg->header.size =
3705 htons (sizeof (struct GNUNET_DHT_FindPeerMessage) +
3706 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
3707 memcpy (&find_peer_msg[1], my_hello,
3708 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
3710 find_peer_msg = GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage));
3711 find_peer_msg->header.size =
3712 htons (sizeof (struct GNUNET_DHT_FindPeerMessage));
3714 find_peer_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3716 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3717 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
3719 GNUNET_assert (GNUNET_OK ==
3720 GNUNET_CONTAINER_bloomfilter_get_raw_data (temp_bloom,
3724 GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
3725 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3726 memcpy (&msg_ctx.key, &my_identity.hashPubKey, sizeof (GNUNET_HashCode));
3728 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
3729 (GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX));
3730 msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3731 msg_ctx.msg_options = GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE;
3732 msg_ctx.network_size = log_of_network_size_estimate;
3733 msg_ctx.peer = &my_identity;
3734 msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3735 msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3737 demultiplex_message (&find_peer_msg->header, &msg_ctx);
3738 GNUNET_free (find_peer_msg);
3739 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3740 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id,
3741 "DHT", "FIND PEER");
3742 if (newly_found_peers < bucket_size)
3744 next_send_time.rel_value =
3745 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
3746 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
3747 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
3751 next_send_time.rel_value =
3752 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
3753 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
3754 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value -
3755 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
3758 GNUNET_assert (next_send_time.rel_value != 0);
3759 find_peer_context.count = 0;
3760 newly_found_peers = 0;
3761 find_peer_context.start = GNUNET_TIME_absolute_get ();
3762 if (GNUNET_YES == do_find_peer)
3764 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
3770 * Handler for any generic DHT messages, calls the appropriate handler
3771 * depending on message type, sends confirmation if responses aren't otherwise
3774 * @param cls closure for the service
3775 * @param client the client we received this message from
3776 * @param message the actual message received
3779 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3780 const struct GNUNET_MessageHeader *message)
3782 const struct GNUNET_DHT_RouteMessage *dht_msg =
3783 (const struct GNUNET_DHT_RouteMessage *) message;
3784 const struct GNUNET_MessageHeader *enc_msg;
3785 struct DHT_MessageContext msg_ctx;
3787 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3789 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3790 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3791 my_short_id, "DHT", "GENERIC", ntohs (message->type),
3792 GNUNET_h2s (&dht_msg->key), GNUNET_ntohll (dht_msg->unique_id));
3794 #if DEBUG_DHT_ROUTING
3795 if (dhtlog_handle != NULL)
3796 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3799 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3800 msg_ctx.client = find_active_client (client);
3801 memcpy (&msg_ctx.key, &dht_msg->key, sizeof (GNUNET_HashCode));
3802 msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3803 msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
3804 msg_ctx.msg_options = ntohl (dht_msg->options);
3805 if (GNUNET_DHT_RO_RECORD_ROUTE ==
3806 (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
3808 msg_ctx.path_history = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
3809 memcpy (msg_ctx.path_history, &my_identity,
3810 sizeof (struct GNUNET_PeerIdentity));
3811 msg_ctx.path_history_len = 1;
3813 msg_ctx.network_size = log_of_network_size_estimate;
3814 msg_ctx.peer = &my_identity; /* FIXME bart NULL? Fix doxygen? */
3815 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
3816 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3818 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3819 increment_stats (STAT_GET_START);
3820 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3821 increment_stats (STAT_PUT_START);
3822 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3823 increment_stats (STAT_FIND_PEER_START);
3825 if (GNUNET_YES == malicious_dropper)
3827 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3829 #if DEBUG_DHT_ROUTING
3830 if ((debug_routes) && (dhtlog_handle != NULL))
3832 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_GET,
3833 msg_ctx.hop_count, GNUNET_NO, &my_identity,
3838 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3840 #if DEBUG_DHT_ROUTING
3841 if ((debug_routes) && (dhtlog_handle != NULL))
3843 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_PUT,
3844 msg_ctx.hop_count, GNUNET_NO, &my_identity,
3849 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3850 GNUNET_free_non_null (msg_ctx.path_history);
3854 demultiplex_message (enc_msg, &msg_ctx);
3855 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3860 * Handler for any locally received DHT control messages,
3861 * sets malicious flags mostly for now.
3863 * @param cls closure for the service
3864 * @param client the client we received this message from
3865 * @param message the actual message received
3869 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3870 const struct GNUNET_MessageHeader *message)
3872 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3873 (const struct GNUNET_DHT_ControlMessage *) message;
3876 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3877 "`%s:%s': Received `%s' request from client, command %d\n",
3878 my_short_id, "DHT", "CONTROL", ntohs (dht_control_msg->command));
3881 switch (ntohs (dht_control_msg->command))
3883 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3885 "Sending self seeking find peer request!\n");
3886 GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
3889 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3890 if (ntohs (dht_control_msg->variable) > 0)
3891 malicious_get_frequency.rel_value = ntohs (dht_control_msg->variable);
3892 if (malicious_get_frequency.rel_value == 0)
3893 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3894 if (malicious_getter != GNUNET_YES)
3895 GNUNET_SCHEDULER_add_now (&malicious_get_task, NULL);
3896 malicious_getter = GNUNET_YES;
3897 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3898 "%s:%s Initiating malicious GET behavior, frequency %llu\n",
3899 my_short_id, "DHT", malicious_get_frequency.rel_value);
3901 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3902 if (ntohs (dht_control_msg->variable) > 0)
3903 malicious_put_frequency.rel_value = ntohs (dht_control_msg->variable);
3904 if (malicious_put_frequency.rel_value == 0)
3905 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3906 if (malicious_putter != GNUNET_YES)
3907 GNUNET_SCHEDULER_add_now (&malicious_put_task, NULL);
3908 malicious_putter = GNUNET_YES;
3909 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3910 "%s:%s Initiating malicious PUT behavior, frequency %d\n",
3911 my_short_id, "DHT", malicious_put_frequency);
3913 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3914 #if DEBUG_DHT_ROUTING
3915 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3916 dhtlog_handle->set_malicious (&my_identity);
3918 malicious_dropper = GNUNET_YES;
3919 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3920 "%s:%s Initiating malicious DROP behavior\n", my_short_id,
3925 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3926 "%s:%s Unknown control command type `%d'!\n", my_short_id,
3927 "DHT", ntohs (dht_control_msg->command));
3931 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3935 * Handler for any generic DHT stop messages, calls the appropriate handler
3936 * depending on message type (if processed locally)
3938 * @param cls closure for the service
3939 * @param client the client we received this message from
3940 * @param message the actual message received
3944 handle_dht_local_route_stop (void *cls, struct GNUNET_SERVER_Client *client,
3945 const struct GNUNET_MessageHeader *message)
3948 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3949 (const struct GNUNET_DHT_StopMessage *) message;
3950 struct DHTQueryRecord *record;
3951 struct DHTRouteSource *pos;
3954 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3955 "`%s:%s': Received `%s' request from client, uid %llu\n",
3956 my_short_id, "DHT", "GENERIC STOP",
3957 GNUNET_ntohll (dht_stop_msg->unique_id));
3960 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap,
3961 &dht_stop_msg->key);
3968 /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
3969 if ((pos->client != NULL) && (pos->client->client_handle == client))
3971 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3972 GNUNET_SCHEDULER_cancel (pos->delete_task);
3974 GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
3980 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3985 * Core handler for p2p route requests.
3987 * @param cls closure
3988 * @param message message
3989 * @param peer peer identity this notification is about
3990 * @param atsi performance data
3991 * @return GNUNET_OK to keep the connection open,
3992 * GNUNET_SYSERR to close it (signal serious error)
3995 handle_dht_p2p_route_request (void *cls, const struct GNUNET_PeerIdentity *peer,
3996 const struct GNUNET_MessageHeader *message,
3997 const struct GNUNET_TRANSPORT_ATS_Information
4001 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4002 "`%s:%s': Received P2P request from peer %s\n", my_short_id,
4003 "DHT", GNUNET_i2s (peer));
4005 struct GNUNET_DHT_P2PRouteMessage *incoming =
4006 (struct GNUNET_DHT_P2PRouteMessage *) message;
4007 struct GNUNET_MessageHeader *enc_msg =
4008 (struct GNUNET_MessageHeader *) &incoming[1];
4009 struct DHT_MessageContext *msg_ctx;
4013 if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4015 GNUNET_break_op (0);
4019 if (malicious_dropper == GNUNET_YES)
4021 #if DEBUG_DHT_ROUTING
4022 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4024 /** Log routes that die due to high load! */
4025 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4026 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4027 GNUNET_SYSERR, &my_identity, &incoming->key,
4034 if (get_max_send_delay ().rel_value > MAX_REQUEST_TIME.rel_value)
4036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4037 "Sending of previous replies took too long, backing off!\n");
4038 increment_stats ("# route requests dropped due to high load");
4039 decrease_max_send_delay (get_max_send_delay ());
4040 #if DEBUG_DHT_ROUTING
4041 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4043 /** Log routes that die due to high load! */
4044 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4045 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4046 GNUNET_SYSERR, &my_identity, &incoming->key,
4052 msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
4054 GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4056 GNUNET_assert (msg_ctx->bloom != NULL);
4057 msg_ctx->hop_count = ntohl (incoming->hop_count);
4058 memcpy (&msg_ctx->key, &incoming->key, sizeof (GNUNET_HashCode));
4059 msg_ctx->replication = ntohl (incoming->desired_replication_level);
4060 msg_ctx->unique_id = GNUNET_ntohll (incoming->unique_id);
4061 msg_ctx->msg_options = ntohl (incoming->options);
4062 if (GNUNET_DHT_RO_RECORD_ROUTE ==
4063 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
4066 ntohl (incoming->outgoing_path_length) *
4067 sizeof (struct GNUNET_PeerIdentity);
4068 if (ntohs (message->size) !=
4069 (sizeof (struct GNUNET_DHT_P2PRouteMessage) +
4070 ntohs (enc_msg->size) + path_size))
4075 route_path = (char *) &incoming[1];
4076 route_path = route_path + ntohs (enc_msg->size);
4077 msg_ctx->path_history =
4078 GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) + path_size);
4079 memcpy (msg_ctx->path_history, route_path, path_size);
4080 memcpy (&msg_ctx->path_history[path_size], &my_identity,
4081 sizeof (struct GNUNET_PeerIdentity));
4082 msg_ctx->path_history_len = ntohl (incoming->outgoing_path_length) + 1;
4084 msg_ctx->network_size = ntohl (incoming->network_size);
4085 msg_ctx->peer = peer;
4086 msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4087 msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4088 demultiplex_message (enc_msg, msg_ctx);
4089 if (msg_ctx->bloom != NULL)
4091 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4092 msg_ctx->bloom = NULL;
4094 GNUNET_free (msg_ctx);
4100 * Core handler for p2p route results.
4102 * @param cls closure
4103 * @param message message
4104 * @param peer peer identity this notification is about
4105 * @param atsi performance data
4109 handle_dht_p2p_route_result (void *cls, const struct GNUNET_PeerIdentity *peer,
4110 const struct GNUNET_MessageHeader *message,
4111 const struct GNUNET_TRANSPORT_ATS_Information
4115 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4116 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT",
4119 const struct GNUNET_DHT_P2PRouteResultMessage *incoming =
4120 (const struct GNUNET_DHT_P2PRouteResultMessage *) message;
4121 struct GNUNET_MessageHeader *enc_msg =
4122 (struct GNUNET_MessageHeader *) &incoming[1];
4123 struct DHT_MessageContext msg_ctx;
4129 if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4131 GNUNET_break_op (0);
4135 if (malicious_dropper == GNUNET_YES)
4137 #if DEBUG_DHT_ROUTING
4138 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4140 /** Log routes that die due to high load! */
4141 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4142 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4143 GNUNET_SYSERR, &my_identity, &incoming->key,
4150 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4151 memcpy (&msg_ctx.key, &incoming->key, sizeof (GNUNET_HashCode));
4152 msg_ctx.unique_id = GNUNET_ntohll (incoming->unique_id);
4153 msg_ctx.msg_options = ntohl (incoming->options);
4154 msg_ctx.hop_count = ntohl (incoming->hop_count);
4155 msg_ctx.peer = peer;
4156 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4157 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4158 if ((GNUNET_DHT_RO_RECORD_ROUTE ==
4159 (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE)) &&
4160 (ntohl (incoming->outgoing_path_length) > 0))
4162 if (ntohs (message->size) -
4163 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) -
4164 ntohs (enc_msg->size) !=
4165 ntohl (incoming->outgoing_path_length) *
4166 sizeof (struct GNUNET_PeerIdentity))
4169 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4170 "Return message indicated a path was included, but sizes are wrong: Total size %d, enc size %d, left %d, expected %d\n",
4171 ntohs (message->size), ntohs (enc_msg->size),
4172 ntohs (message->size) -
4173 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) -
4174 ntohs (enc_msg->size),
4175 ntohl (incoming->outgoing_path_length) *
4176 sizeof (struct GNUNET_PeerIdentity));
4178 GNUNET_break_op (0);
4181 msg_ctx.path_history = (char *) &incoming[1];
4182 msg_ctx.path_history += ntohs (enc_msg->size);
4183 msg_ctx.path_history_len = ntohl (incoming->outgoing_path_length);
4185 for (i = 0; i < msg_ctx.path_history_len; i++)
4188 &msg_ctx.path_history[i * sizeof (struct GNUNET_PeerIdentity)];
4189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4190 "(handle_p2p_route_result) Key %s Found peer %d:%s\n",
4191 GNUNET_h2s (&msg_ctx.key), i,
4192 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
4197 GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4199 GNUNET_assert (msg_ctx.bloom != NULL);
4200 route_result_message (enc_msg, &msg_ctx);
4206 * Receive the HELLO from transport service,
4207 * free current and replace if necessary.
4210 * @param message HELLO message of peer
4213 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4217 "Received our `%s' from transport service\n", "HELLO");
4220 GNUNET_assert (message != NULL);
4221 GNUNET_free_non_null (my_hello);
4222 my_hello = GNUNET_malloc (ntohs (message->size));
4223 memcpy (my_hello, message, ntohs (message->size));
4228 * Task run during shutdown.
4234 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4237 struct PeerInfo *pos;
4241 GNUNET_TRANSPORT_get_hello_cancel (ghh);
4244 if (transport_handle != NULL)
4246 GNUNET_free_non_null (my_hello);
4247 GNUNET_TRANSPORT_disconnect (transport_handle);
4248 transport_handle = NULL;
4252 GNUNET_NSE_disconnect (nse);
4255 if (coreAPI != NULL)
4258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Disconnecting core!\n",
4259 my_short_id, "DHT");
4261 GNUNET_CORE_disconnect (coreAPI);
4264 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4266 while (k_buckets[bucket_count].head != NULL)
4268 pos = k_buckets[bucket_count].head;
4270 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4271 "%s:%s Removing peer %s from bucket %d!\n", my_short_id,
4272 "DHT", GNUNET_i2s (&pos->id), bucket_count);
4274 delete_peer (pos, bucket_count);
4277 if (datacache != NULL)
4280 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Destroying datacache!\n",
4281 my_short_id, "DHT");
4283 GNUNET_DATACACHE_destroy (datacache);
4288 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4291 if (dhtlog_handle != NULL)
4293 GNUNET_DHTLOG_disconnect (dhtlog_handle);
4294 dhtlog_handle = NULL;
4296 if (block_context != NULL)
4298 GNUNET_BLOCK_context_destroy (block_context);
4299 block_context = NULL;
4301 GNUNET_free_non_null (my_short_id);
4307 * To be called on core init/fail.
4309 * @param cls service closure
4310 * @param server handle to the server for this service
4311 * @param identity the public identity of this peer
4312 * @param publicKey the public key of this peer
4315 core_init (void *cls, struct GNUNET_CORE_Handle *server,
4316 const struct GNUNET_PeerIdentity *identity,
4317 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4323 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s: Connection to core FAILED!\n",
4324 "dht", GNUNET_i2s (identity));
4326 GNUNET_SCHEDULER_cancel (cleanup_task);
4327 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4331 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4332 "%s: Core connection initialized, I am peer: %s\n", "dht",
4333 GNUNET_i2s (identity));
4336 /* Copy our identity so we can use it */
4337 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4338 if (my_short_id != NULL)
4339 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4340 "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n",
4342 my_short_id = GNUNET_strdup (GNUNET_i2s (&my_identity));
4343 if (dhtlog_handle != NULL)
4344 dhtlog_handle->insert_node (NULL, &my_identity);
4348 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4349 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE,
4351 {&handle_dht_local_route_stop, NULL,
4352 GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4353 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4358 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4359 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4360 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4366 * Method called whenever a peer connects.
4368 * @param cls closure
4369 * @param peer peer identity this notification is about
4370 * @param atsi performance data
4373 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
4374 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4376 struct PeerInfo *ret;
4377 struct DHTPutEntry *put_entry;
4380 /* Check for connect to self message */
4381 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
4385 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4386 "%s:%s Receives core connect message for peer %s distance %d!\n",
4387 my_short_id, "dht", GNUNET_i2s (peer), distance);
4391 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
4395 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4396 "%s:%s Received %s message for peer %s, but already have peer in RT!",
4397 my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s (peer));
4403 if ((datacache != NULL) && (GNUNET_YES == put_peer_identities))
4406 GNUNET_malloc (sizeof (struct DHTPutEntry) +
4407 sizeof (struct GNUNET_PeerIdentity));
4408 put_entry->path_length = 0;
4409 put_entry->data_size = sizeof (struct GNUNET_PeerIdentity);
4410 memcpy (&put_entry[1], peer, sizeof (struct GNUNET_PeerIdentity));
4411 GNUNET_DATACACHE_put (datacache, &peer->hashPubKey,
4412 sizeof (struct DHTPutEntry) +
4413 sizeof (struct GNUNET_PeerIdentity),
4414 (char *) put_entry, GNUNET_BLOCK_TYPE_DHT_HELLO,
4415 GNUNET_TIME_absolute_get_forever ());
4416 GNUNET_free (put_entry);
4418 else if (datacache == NULL)
4419 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4420 "DHT has no connection to datacache!\n");
4422 peer_bucket = find_current_bucket (&peer->hashPubKey);
4423 GNUNET_assert (peer_bucket >= lowest_bucket);
4424 GNUNET_assert (peer_bucket < MAX_BUCKETS);
4425 ret = GNUNET_malloc (sizeof (struct PeerInfo));
4427 ret->latency = latency;
4428 ret->distance = distance;
4431 GNUNET_CONTAINER_DLL_insert_after (k_buckets[peer_bucket].head,
4432 k_buckets[peer_bucket].tail,
4433 k_buckets[peer_bucket].tail, ret);
4434 k_buckets[peer_bucket].peers_size++;
4435 #if DO_UPDATE_PREFERENCE
4436 if ((GNUNET_CRYPTO_hash_matching_bits
4437 (&my_identity.hashPubKey, &peer->hashPubKey) > 0) &&
4438 (k_buckets[peer_bucket].peers_size <= bucket_size))
4439 ret->preference_task =
4440 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
4442 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
4443 enable_next_bucket ();
4444 newly_found_peers++;
4445 GNUNET_CONTAINER_multihashmap_put (all_known_peers, &peer->hashPubKey, ret,
4446 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4447 increment_stats (STAT_PEERS_KNOWN);
4450 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4451 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT",
4452 ret == NULL ? "NOT ADDED" : "PEER ADDED");
4458 * Method called whenever a peer disconnects.
4460 * @param cls closure
4461 * @param peer peer identity this notification is about
4464 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
4466 struct PeerInfo *to_remove;
4469 /* Check for disconnect from self message */
4470 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
4473 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4474 "%s:%s: Received peer disconnect message for peer `%s' from %s\n",
4475 my_short_id, "DHT", GNUNET_i2s (peer), "CORE");
4479 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
4484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4485 "%s:%s: do not have peer `%s' in RT, can't disconnect!\n",
4486 my_short_id, "DHT", GNUNET_i2s (peer));
4490 increment_stats (STAT_DISCONNECTS);
4491 GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
4492 (all_known_peers, &peer->hashPubKey));
4494 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
4495 GNUNET_assert (to_remove != NULL);
4496 if (NULL != to_remove->info_ctx)
4498 GNUNET_CORE_peer_change_preference_cancel (to_remove->info_ctx);
4499 to_remove->info_ctx = NULL;
4502 memcmp (peer, &to_remove->id,
4503 sizeof (struct GNUNET_PeerIdentity)));
4504 current_bucket = find_current_bucket (&to_remove->id.hashPubKey);
4505 delete_peer (to_remove, current_bucket);
4510 * Process dht requests.
4512 * @param cls closure
4513 * @param server the initialized server
4514 * @param c configuration to use
4517 run (void *cls, struct GNUNET_SERVER_Handle *server,
4518 const struct GNUNET_CONFIGURATION_Handle *c)
4520 struct GNUNET_TIME_Relative next_send_time;
4521 unsigned long long temp_config_num;
4524 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4525 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4526 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4527 nse = GNUNET_NSE_connect (cfg,
4528 &update_network_size_estimate, NULL);
4529 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
4530 DEFAULT_CORE_QUEUE_SIZE, /* queue size */
4531 NULL, /* Closure passed to DHT functions */
4532 &core_init, /* Call core_init once connected */
4533 &handle_core_connect, /* Handle connects */
4534 &handle_core_disconnect, /* remove peers on disconnects */
4535 NULL, /* Do we care about "status" updates? */
4536 NULL, /* Don't want notified about all incoming messages */
4537 GNUNET_NO, /* For header only inbound notification */
4538 NULL, /* Don't want notified about all outbound messages */
4539 GNUNET_NO, /* For header only outbound notification */
4540 core_handlers); /* Register these handlers */
4542 if (coreAPI == NULL)
4545 GNUNET_TRANSPORT_connect (cfg, NULL, NULL, NULL, NULL, NULL);
4546 if (transport_handle != NULL)
4547 ghh = GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4549 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4550 "Failed to connect to transport service!\n");
4551 block_context = GNUNET_BLOCK_context_create (cfg);
4552 lowest_bucket = MAX_BUCKETS - 1;
4553 forward_list.hashmap =
4554 GNUNET_CONTAINER_multihashmap_create (MAX_OUTSTANDING_FORWARDS / 10);
4555 forward_list.minHeap =
4556 GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4557 all_known_peers = GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
4558 GNUNET_assert (all_known_peers != NULL);
4560 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
4563 debug_routes = GNUNET_YES;
4567 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "strict_kademlia"))
4569 strict_kademlia = GNUNET_YES;
4573 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_on_closest"))
4575 stop_on_closest = GNUNET_YES;
4579 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_found"))
4581 stop_on_found = GNUNET_YES;
4585 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_getter"))
4587 malicious_getter = GNUNET_YES;
4589 GNUNET_CONFIGURATION_get_value_time (cfg, "DHT",
4590 "MALICIOUS_GET_FREQUENCY",
4591 &malicious_get_frequency))
4592 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4596 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_putter"))
4598 malicious_putter = GNUNET_YES;
4600 GNUNET_CONFIGURATION_get_value_time (cfg, "DHT",
4601 "MALICIOUS_PUT_FREQUENCY",
4602 &malicious_put_frequency))
4603 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4607 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "bucket_size",
4610 bucket_size = (unsigned int) temp_config_num;
4614 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "kad_alpha",
4615 &kademlia_replication))
4617 kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
4621 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_dropper"))
4623 malicious_dropper = GNUNET_YES;
4627 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "do_find_peer"))
4629 do_find_peer = GNUNET_NO;
4632 do_find_peer = GNUNET_YES;
4635 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "use_real_distance"))
4636 use_real_distance = GNUNET_YES;
4639 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
4640 "mysql_logging_extended"))
4642 debug_routes = GNUNET_YES;
4643 debug_routes_extended = GNUNET_YES;
4646 #if DEBUG_DHT_ROUTING
4647 if (GNUNET_YES == debug_routes)
4649 dhtlog_handle = GNUNET_DHTLOG_connect (cfg);
4650 if (dhtlog_handle == NULL)
4652 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4653 "Could not connect to mysql logging server, logging will not happen!");
4659 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "paper_forwarding"))
4660 paper_forwarding = GNUNET_YES;
4663 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "put_peer_identities"))
4664 put_peer_identities = GNUNET_YES;
4666 stats = GNUNET_STATISTICS_create ("dht", cfg);
4670 GNUNET_STATISTICS_set (stats, STAT_ROUTES, 0, GNUNET_NO);
4671 GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4672 GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4673 GNUNET_STATISTICS_set (stats, STAT_RESULTS, 0, GNUNET_NO);
4674 GNUNET_STATISTICS_set (stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4675 GNUNET_STATISTICS_set (stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4676 GNUNET_STATISTICS_set (stats, STAT_GETS, 0, GNUNET_NO);
4677 GNUNET_STATISTICS_set (stats, STAT_PUTS, 0, GNUNET_NO);
4678 GNUNET_STATISTICS_set (stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4679 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER, 0, GNUNET_NO);
4680 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4681 GNUNET_STATISTICS_set (stats, STAT_GET_START, 0, GNUNET_NO);
4682 GNUNET_STATISTICS_set (stats, STAT_PUT_START, 0, GNUNET_NO);
4683 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4684 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4685 GNUNET_STATISTICS_set (stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4686 GNUNET_STATISTICS_set (stats, STAT_GET_REPLY, 0, GNUNET_NO);
4687 GNUNET_STATISTICS_set (stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4688 GNUNET_STATISTICS_set (stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4689 GNUNET_STATISTICS_set (stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4691 if (GNUNET_YES == do_find_peer)
4693 next_send_time.rel_value =
4694 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4695 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
4696 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value /
4698 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4699 find_peer_context.start = GNUNET_TIME_absolute_get ();
4700 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
4701 &find_peer_context);
4704 /* Scheduled the task to clean up when shutdown is called */
4706 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4707 &shutdown_task, NULL);
4712 * The main function for the dht service.
4714 * @param argc number of arguments from the command line
4715 * @param argv command line arguments
4716 * @return 0 ok, 1 on error
4719 main (int argc, char *const *argv)
4723 recent.hashmap = GNUNET_CONTAINER_multihashmap_create (DHT_MAX_RECENT / 2);
4724 recent.minHeap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4725 recent_find_peer_requests =
4726 GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
4729 GNUNET_SERVICE_run (argc, argv, "dht", GNUNET_SERVICE_OPTION_NONE, &run,
4731 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (recent.hashmap));
4732 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4733 recent.hashmap = NULL;
4734 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (recent.minHeap));
4735 GNUNET_CONTAINER_heap_destroy (recent.minHeap);
4736 recent.minHeap = NULL;
4737 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4738 recent_find_peer_requests = NULL;
4742 /* end of gnunet-service-dht.c */