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, struct GNUNET_TIME_Absolute timestamp,
863 double logestimate, double std_dev)
865 log_of_network_size_estimate = logestimate;
870 * Forward declaration.
873 send_generic_reply (void *cls, size_t size, void *buf);
876 /** Declare here so retry_core_send is aware of it */
878 core_transmit_notify (void *cls, size_t size, void *buf);
882 * Convert unique ID to hash code.
884 * @param uid unique ID to convert
885 * @param hash set to uid (extended with zeros)
888 hash_from_uid (uint64_t uid, GNUNET_HashCode * hash)
890 memset (hash, 0, sizeof (GNUNET_HashCode));
891 *((uint64_t *) hash) = uid;
896 * Given the largest send delay, artificially decrease it
897 * so the next time around we may have a chance at sending
901 decrease_max_send_delay (struct GNUNET_TIME_Relative max_time)
905 for (i = 0; i < MAX_REPLY_TIMES; i++)
907 if (reply_times[i].rel_value == max_time.rel_value)
909 reply_times[i].rel_value = reply_times[i].rel_value / 2;
917 * Find the maximum send time of the recently sent values.
919 * @return the average time between asking core to send a message
920 * and when the buffer for copying it is passed
922 static struct GNUNET_TIME_Relative
923 get_max_send_delay ()
926 struct GNUNET_TIME_Relative max_time;
928 max_time = GNUNET_TIME_relative_get_zero ();
930 for (i = 0; i < MAX_REPLY_TIMES; i++)
932 if (reply_times[i].rel_value > max_time.rel_value)
933 max_time.rel_value = reply_times[i].rel_value;
936 if (max_time.rel_value > MAX_REQUEST_TIME.rel_value)
937 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n",
938 (unsigned long long) max_time.rel_value);
945 increment_stats (const char *value)
949 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
954 decrement_stats (const char *value)
958 GNUNET_STATISTICS_update (stats, value, -1, GNUNET_NO);
963 * Try to send another message from our core send list
966 try_core_send (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
968 struct PeerInfo *peer = cls;
969 struct P2PPendingMessage *pending;
972 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
974 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
977 if (peer->th != NULL)
978 return; /* Message send already in progress */
980 pending = peer->head;
983 ssize = ntohs (pending->msg->size);
985 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
986 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n",
987 my_short_id, "DHT", ssize, GNUNET_i2s (&peer->id));
989 pending->scheduled = GNUNET_TIME_absolute_get ();
991 if (reply_counter >= MAX_REPLY_TIMES)
994 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
996 pending->timeout, &peer->id, ssize,
997 &core_transmit_notify, peer);
998 if (peer->th == NULL)
999 increment_stats ("# notify transmit ready failed");
1005 * Function called to send a request out to another peer.
1006 * Called both for locally initiated requests and those
1007 * received from other peers.
1009 * @param msg the encapsulated message
1010 * @param peer the peer to forward the message to
1011 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1014 forward_result_message (const struct GNUNET_MessageHeader *msg,
1015 struct PeerInfo *peer,
1016 struct DHT_MessageContext *msg_ctx)
1018 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1019 struct P2PPendingMessage *pending;
1029 increment_stats (STAT_RESULT_FORWARDS);
1031 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs (msg->size) +
1032 (sizeof (struct GNUNET_PeerIdentity) * msg_ctx->path_history_len);
1033 GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1034 psize = sizeof (struct P2PPendingMessage) + msize;
1035 pending = GNUNET_malloc (psize);
1036 pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1037 pending->importance = DHT_SEND_PRIORITY;
1038 pending->timeout = GNUNET_TIME_relative_get_forever ();
1039 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *) pending->msg;
1040 result_message->header.size = htons (msize);
1041 result_message->header.type =
1042 htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1043 result_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1044 if (msg_ctx->path_history_len > 0)
1046 /* End of pending is where enc_msg starts */
1047 path_start = (char *) &pending[1];
1048 /* Offset by the size of the enc_msg */
1049 path_start += ntohs (msg->size);
1050 memcpy (path_start, msg_ctx->path_history,
1051 msg_ctx->path_history_len * (sizeof (struct GNUNET_PeerIdentity)));
1053 for (i = 0; i < msg_ctx->path_history_len; i++)
1056 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1057 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1058 "(forward_result) Key %s Found peer %d:%s\n",
1059 GNUNET_h2s (&msg_ctx->key), i,
1060 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1064 result_message->options = htonl (msg_ctx->msg_options);
1065 result_message->hop_count = htonl (msg_ctx->hop_count + 1);
1066 GNUNET_assert (GNUNET_OK ==
1067 GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1071 result_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1072 memcpy (&result_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1073 /* Copy the enc_msg, then the path history as well! */
1074 memcpy (&result_message[1], msg, ntohs (msg->size));
1075 path_offset = (char *) &result_message[1];
1076 path_offset += ntohs (msg->size);
1077 /* If we have path history, copy it to the end of the whole thing */
1078 if (msg_ctx->path_history_len > 0)
1079 memcpy (path_offset, msg_ctx->path_history,
1080 msg_ctx->path_history_len * (sizeof (struct GNUNET_PeerIdentity)));
1082 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1083 "%s:%s Adding pending message size %d for peer %s\n", my_short_id,
1084 "DHT", msize, GNUNET_i2s (&peer->id));
1086 peer->pending_count++;
1087 increment_stats ("# pending messages scheduled");
1088 GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1090 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1091 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1096 * Called when core is ready to send a message we asked for
1097 * out to the destination.
1099 * @param cls closure (NULL)
1100 * @param size number of bytes available in buf
1101 * @param buf where the callee should write the message
1102 * @return number of bytes written to buf
1105 core_transmit_notify (void *cls, size_t size, void *buf)
1107 struct PeerInfo *peer = cls;
1109 struct P2PPendingMessage *pending;
1117 /* client disconnected */
1119 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n",
1120 my_short_id, "DHT");
1125 if (peer->head == NULL)
1129 pending = peer->head;
1131 reply_times[reply_counter] =
1132 GNUNET_TIME_absolute_get_difference (pending->scheduled,
1133 GNUNET_TIME_absolute_get ());
1134 msize = ntohs (pending->msg->size);
1138 memcpy (cbuf, pending->msg, msize);
1139 peer->pending_count--;
1140 increment_stats ("# pending messages sent");
1141 GNUNET_assert (peer->pending_count >= 0);
1142 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1143 GNUNET_free (pending);
1146 while (NULL != pending &&
1147 (size - off >= (msize = ntohs (pending->msg->size))))
1149 memcpy (&cbuf[off], pending->msg, msize);
1151 peer->pending_count--;
1152 increment_stats ("# pending messages sent");
1153 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
1154 GNUNET_free (pending);
1155 pending = peer->head;
1158 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1159 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1166 * Compute the distance between have and target as a 32-bit value.
1167 * Differences in the lower bits must count stronger than differences
1168 * in the higher bits.
1170 * @return 0 if have==target, otherwise a number
1171 * that is larger as the distance between
1172 * the two hash codes increases
1175 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1177 unsigned int bucket;
1182 /* We have to represent the distance between two 2^9 (=512)-bit
1183 * numbers as a 2^5 (=32)-bit number with "0" being used for the
1184 * two numbers being identical; furthermore, we need to
1185 * guarantee that a difference in the number of matching
1186 * bits is always represented in the result.
1188 * We use 2^32/2^9 numerical values to distinguish between
1189 * hash codes that have the same LSB bit distance and
1190 * use the highest 2^9 bits of the result to signify the
1191 * number of (mis)matching LSB bits; if we have 0 matching
1192 * and hence 512 mismatching LSB bits we return -1 (since
1193 * 512 itself cannot be represented with 9 bits) */
1195 /* first, calculate the most significant 9 bits of our
1196 * result, aka the number of LSBs */
1197 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1198 /* bucket is now a value between 0 and 512 */
1200 return 0; /* perfect match */
1202 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1203 * below, we'd end up with max+1 (overflow)) */
1205 /* calculate the most significant bits of the final result */
1206 msb = (512 - bucket) << (32 - 9);
1207 /* calculate the 32-9 least significant bits of the final result by
1208 * looking at the differences in the 32-9 bits following the
1209 * mismatching bit at 'bucket' */
1211 for (i = bucket + 1;
1212 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1214 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
1215 GNUNET_CRYPTO_hash_get_bit (have, i))
1216 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1217 * last bit set will be 31 -- if
1218 * i does not reach 512 first... */
1225 * Return a number that is larger the closer the
1226 * "have" GNUNET_hash code is to the "target".
1228 * @return inverse distance metric, non-zero.
1229 * Must fudge the value if NO bits match.
1232 inverse_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1234 if (GNUNET_CRYPTO_hash_matching_bits (target, have) == 0)
1235 return 1; /* Never return 0! */
1236 return ((unsigned int) -1) - distance (target, have);
1241 * Find the optimal bucket for this key, regardless
1242 * of the current number of buckets in use.
1244 * @param hc the hashcode to compare our identity to
1246 * @return the proper bucket index, or GNUNET_SYSERR
1247 * on error (same hashcode)
1250 find_bucket (const GNUNET_HashCode * hc)
1254 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
1255 if (bits == MAX_BUCKETS)
1256 return GNUNET_SYSERR;
1257 return MAX_BUCKETS - bits - 1;
1262 * Find which k-bucket this peer should go into,
1263 * taking into account the size of the k-bucket
1264 * array. This means that if more bits match than
1265 * there are currently buckets, lowest_bucket will
1268 * @param hc GNUNET_HashCode we are finding the bucket for.
1270 * @return the proper bucket index for this key,
1271 * or GNUNET_SYSERR on error (same hashcode)
1274 find_current_bucket (const GNUNET_HashCode * hc)
1278 actual_bucket = find_bucket (hc);
1279 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1280 return lowest_bucket;
1281 if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1282 return lowest_bucket;
1283 return actual_bucket;
1288 * Find a routing table entry from a peer identity
1290 * @param peer the peer identity to look up
1292 * @return the routing table entry, or NULL if not found
1294 static struct PeerInfo *
1295 find_peer_by_id (const struct GNUNET_PeerIdentity *peer)
1298 struct PeerInfo *pos;
1300 bucket = find_current_bucket (&peer->hashPubKey);
1302 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
1305 pos = k_buckets[bucket].head;
1308 if (0 == memcmp (&pos->id, peer, sizeof (struct GNUNET_PeerIdentity)))
1312 return NULL; /* No such peer. */
1315 /* Forward declaration */
1317 update_core_preference (void *cls,
1318 const struct GNUNET_SCHEDULER_TaskContext *tc);
1322 * Function called with statistics about the given peer.
1324 * @param cls closure
1325 * @param peer identifies the peer
1326 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1327 * @param amount set to the amount that was actually reserved or unreserved;
1328 * either the full requested amount or zero (no partial reservations)
1329 * @param res_delay if the reservation could not be satisfied (amount was 0), how
1330 * long should the client wait until re-trying?
1331 * @param preference current traffic preference for the given peer
1334 update_core_preference_finish (void *cls,
1335 const struct GNUNET_PeerIdentity *peer,
1336 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1338 struct GNUNET_TIME_Relative res_delay,
1339 uint64_t preference)
1341 struct PeerInfo *peer_info = cls;
1343 peer_info->info_ctx = NULL;
1344 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
1345 &update_core_preference, peer_info);
1349 update_core_preference (void *cls,
1350 const struct GNUNET_SCHEDULER_TaskContext *tc)
1352 struct PeerInfo *peer = cls;
1353 uint64_t preference;
1354 unsigned int matching;
1356 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
1361 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
1362 &peer->id.hashPubKey);
1366 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1367 "Peer identifier matches by %u bits, only shifting as much as we can!\n",
1372 preference = 1LL << matching;
1374 GNUNET_CORE_peer_change_preference (coreAPI, &peer->id,
1375 GNUNET_TIME_UNIT_FOREVER_REL,
1376 GNUNET_BANDWIDTH_VALUE_MAX, 0,
1378 &update_core_preference_finish, peer);
1383 * Given a peer and its corresponding bucket,
1384 * remove it from that bucket. Does not free
1385 * the PeerInfo struct, nor cancel messages
1386 * or free messages waiting to be sent to this
1389 * @param peer the peer to remove
1390 * @param bucket the bucket the peer belongs to
1393 remove_peer (struct PeerInfo *peer, unsigned int bucket)
1395 GNUNET_assert (k_buckets[bucket].peers_size > 0);
1396 GNUNET_CONTAINER_DLL_remove (k_buckets[bucket].head, k_buckets[bucket].tail,
1398 k_buckets[bucket].peers_size--;
1400 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) &&
1401 (lowest_bucket < MAX_BUCKETS - 1))
1407 * Removes peer from a bucket, then frees associated
1408 * resources and frees peer.
1410 * @param peer peer to be removed and freed
1411 * @param bucket which bucket this peer belongs to
1414 delete_peer (struct PeerInfo *peer, unsigned int bucket)
1416 struct P2PPendingMessage *pos;
1417 struct P2PPendingMessage *next;
1419 remove_peer (peer, bucket); /* First remove the peer from its bucket */
1420 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1421 GNUNET_SCHEDULER_cancel (peer->send_task);
1422 if ((peer->th != NULL) && (coreAPI != NULL))
1423 GNUNET_CORE_notify_transmit_ready_cancel (peer->th);
1426 while (pos != NULL) /* Remove any pending messages for this peer */
1429 ("# dht pending messages discarded (due to disconnect/shutdown)");
1435 GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
1436 (all_known_peers, &peer->id.hashPubKey));
1437 GNUNET_assert (GNUNET_YES ==
1438 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
1439 &peer->id.hashPubKey,
1442 decrement_stats (STAT_PEERS_KNOWN);
1447 * Iterator over hash map entries.
1449 * @param cls closure
1450 * @param key current key code
1451 * @param value PeerInfo of the peer to move to new lowest bucket
1452 * @return GNUNET_YES if we should continue to
1457 move_lowest_bucket (void *cls, const GNUNET_HashCode * key, void *value)
1459 struct PeerInfo *peer = value;
1462 GNUNET_assert (lowest_bucket > 0);
1463 new_bucket = lowest_bucket - 1;
1464 remove_peer (peer, lowest_bucket);
1465 GNUNET_CONTAINER_DLL_insert_after (k_buckets[new_bucket].head,
1466 k_buckets[new_bucket].tail,
1467 k_buckets[new_bucket].tail, peer);
1468 k_buckets[new_bucket].peers_size++;
1474 * The current lowest bucket is full, so change the lowest
1475 * bucket to the next lower down, and move any appropriate
1476 * entries in the current lowest bucket to the new bucket.
1479 enable_next_bucket ()
1481 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1482 struct PeerInfo *pos;
1484 GNUNET_assert (lowest_bucket > 0);
1485 to_remove = GNUNET_CONTAINER_multihashmap_create (bucket_size);
1486 pos = k_buckets[lowest_bucket].head;
1488 /* Populate the array of peers which should be in the next lowest bucket */
1491 if (find_bucket (&pos->id.hashPubKey) < lowest_bucket)
1492 GNUNET_CONTAINER_multihashmap_put (to_remove, &pos->id.hashPubKey, pos,
1493 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1497 /* Remove peers from lowest bucket, insert into next lowest bucket */
1498 GNUNET_CONTAINER_multihashmap_iterate (to_remove, &move_lowest_bucket, NULL);
1499 GNUNET_CONTAINER_multihashmap_destroy (to_remove);
1500 lowest_bucket = lowest_bucket - 1;
1505 * Find the closest peer in our routing table to the
1508 * @return The closest peer in our routing table to the
1509 * key, or NULL on error.
1511 static struct PeerInfo *
1512 find_closest_peer (const GNUNET_HashCode * hc)
1514 struct PeerInfo *pos;
1515 struct PeerInfo *current_closest;
1516 unsigned int lowest_distance;
1517 unsigned int temp_distance;
1521 lowest_distance = -1;
1523 if (k_buckets[lowest_bucket].peers_size == 0)
1526 current_closest = NULL;
1527 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1529 pos = k_buckets[bucket].head;
1531 while ((pos != NULL) && (count < bucket_size))
1533 temp_distance = distance (&pos->id.hashPubKey, hc);
1534 if (temp_distance <= lowest_distance)
1536 lowest_distance = temp_distance;
1537 current_closest = pos;
1543 GNUNET_assert (current_closest != NULL);
1544 return current_closest;
1549 * Function called to send a request out to another peer.
1550 * Called both for locally initiated requests and those
1551 * received from other peers.
1553 * @param msg the encapsulated message
1554 * @param peer the peer to forward the message to
1555 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1558 forward_message (const struct GNUNET_MessageHeader *msg, struct PeerInfo *peer,
1559 struct DHT_MessageContext *msg_ctx)
1561 struct GNUNET_DHT_P2PRouteMessage *route_message;
1562 struct P2PPendingMessage *pending;
1567 increment_stats (STAT_ROUTE_FORWARDS);
1568 GNUNET_assert (peer != NULL);
1569 if ((msg_ctx->closest != GNUNET_YES) &&
1570 (peer == find_closest_peer (&msg_ctx->key)))
1571 increment_stats (STAT_ROUTE_FORWARDS_CLOSEST);
1574 sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs (msg->size) +
1575 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1576 GNUNET_assert (msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1577 psize = sizeof (struct P2PPendingMessage) + msize;
1578 pending = GNUNET_malloc (psize);
1579 pending->msg = (struct GNUNET_MessageHeader *) &pending[1];
1580 pending->importance = msg_ctx->importance;
1581 pending->timeout = msg_ctx->timeout;
1582 route_message = (struct GNUNET_DHT_P2PRouteMessage *) pending->msg;
1583 route_message->header.size = htons (msize);
1584 route_message->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1585 route_message->options = htonl (msg_ctx->msg_options);
1586 route_message->hop_count = htonl (msg_ctx->hop_count + 1);
1587 route_message->network_size = htonl (msg_ctx->network_size);
1588 route_message->desired_replication_level = htonl (msg_ctx->replication);
1589 route_message->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1590 if (msg_ctx->bloom != NULL)
1591 GNUNET_assert (GNUNET_OK ==
1592 GNUNET_CONTAINER_bloomfilter_get_raw_data (msg_ctx->bloom,
1596 memcpy (&route_message->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1597 memcpy (&route_message[1], msg, ntohs (msg->size));
1598 if (GNUNET_DHT_RO_RECORD_ROUTE ==
1599 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
1601 route_message->outgoing_path_length = htonl (msg_ctx->path_history_len);
1602 /* Set pointer to start of enc_msg */
1603 route_path = (char *) &route_message[1];
1604 /* Offset to the end of the enc_msg */
1605 route_path += ntohs (msg->size);
1606 /* Copy the route_path after enc_msg */
1607 memcpy (route_path, msg_ctx->path_history,
1608 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1612 "%s:%s Adding pending message size %d for peer %s\n", my_short_id,
1613 "DHT", msize, GNUNET_i2s (&peer->id));
1615 peer->pending_count++;
1616 increment_stats ("# pending messages scheduled");
1617 GNUNET_CONTAINER_DLL_insert_after (peer->head, peer->tail, peer->tail,
1619 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1620 peer->send_task = GNUNET_SCHEDULER_add_now (&try_core_send, peer);
1625 * Task run to check for messages that need to be sent to a client.
1627 * @param client a ClientList, containing the client and any messages to be sent to it
1630 process_pending_messages (struct ClientList *client)
1632 if ((client->pending_head == NULL) || (client->transmit_handle != NULL))
1634 client->transmit_handle =
1635 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1636 ntohs (client->pending_head->
1638 GNUNET_TIME_UNIT_FOREVER_REL,
1639 &send_generic_reply, client);
1643 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1644 * request. A ClientList is passed as closure, take the head of the list
1645 * and copy it into buf, which has the result of sending the message to the
1648 * @param cls closure to this call
1649 * @param size maximum number of bytes available to send
1650 * @param buf where to copy the actual message to
1652 * @return the number of bytes actually copied, 0 indicates failure
1655 send_generic_reply (void *cls, size_t size, void *buf)
1657 struct ClientList *client = cls;
1659 struct PendingMessage *reply;
1663 client->transmit_handle = NULL;
1666 /* client disconnected */
1670 while ((NULL != (reply = client->pending_head)) &&
1671 (size >= off + (msize = ntohs (reply->msg->size))))
1673 GNUNET_CONTAINER_DLL_remove (client->pending_head, client->pending_tail,
1675 memcpy (&cbuf[off], reply->msg, msize);
1676 GNUNET_free (reply);
1679 process_pending_messages (client);
1681 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1682 "Transmitted %u bytes of replies to client\n",
1683 (unsigned int) off);
1690 * Add a PendingMessage to the clients list of messages to be sent
1692 * @param client the active client to send the message to
1693 * @param pending_message the actual message to send
1696 add_pending_message (struct ClientList *client,
1697 struct PendingMessage *pending_message)
1699 GNUNET_CONTAINER_DLL_insert_after (client->pending_head, client->pending_tail,
1700 client->pending_tail, pending_message);
1701 process_pending_messages (client);
1706 * Called when a reply needs to be sent to a client, as
1707 * a result it found to a GET or FIND PEER request.
1709 * @param client the client to send the reply to
1710 * @param message the encapsulated message to send
1711 * @param msg_ctx the context of the received message
1714 send_reply_to_client (struct ClientList *client,
1715 const struct GNUNET_MessageHeader *message,
1716 struct DHT_MessageContext *msg_ctx)
1718 struct GNUNET_DHT_RouteResultMessage *reply;
1719 struct PendingMessage *pending_message;
1729 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': Sending reply to client.\n",
1730 my_short_id, "DHT");
1732 msize = ntohs (message->size);
1734 sizeof (struct GNUNET_DHT_RouteResultMessage) + msize +
1735 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1736 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1738 GNUNET_break_op (0);
1741 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1742 pending_message->msg = (struct GNUNET_MessageHeader *) &pending_message[1];
1743 reply = (struct GNUNET_DHT_RouteResultMessage *) &pending_message[1];
1744 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1745 reply->header.size = htons (tsize);
1746 reply->outgoing_path_length = htonl (msg_ctx->path_history_len);
1747 reply->unique_id = GNUNET_htonll (msg_ctx->unique_id);
1748 memcpy (&reply->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
1749 reply_offset = (char *) &reply[1];
1750 memcpy (&reply[1], message, msize);
1751 if (msg_ctx->path_history_len > 0)
1753 reply_offset += msize;
1754 memcpy (reply_offset, msg_ctx->path_history,
1755 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
1758 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1759 "Returning message with outgoing path length %d\n",
1760 msg_ctx->path_history_len);
1761 for (i = 0; i < msg_ctx->path_history_len; i++)
1764 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1765 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Found peer %d:%s\n", i,
1766 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1769 add_pending_message (client, pending_message);
1773 * Consider whether or not we would like to have this peer added to
1774 * our routing table. Check whether bucket for this peer is full,
1775 * if so return negative; if not return positive. Since peers are
1776 * only added on CORE level connect, this doesn't actually add the
1777 * peer to the routing table.
1779 * @param peer the peer we are considering adding
1781 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1785 consider_peer (struct GNUNET_PeerIdentity *peer)
1790 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
1791 &peer->hashPubKey)) ||
1792 (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity))))
1793 return GNUNET_NO; /* We already know this peer (are connected even!) */
1794 bucket = find_current_bucket (&peer->hashPubKey);
1796 if ((k_buckets[bucket].peers_size < bucket_size) ||
1797 ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1805 * Task used to remove forwarding entries, either
1806 * after timeout, when full, or on shutdown.
1808 * @param cls the entry to remove
1809 * @param tc context, reason, etc.
1812 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1814 struct DHTRouteSource *source_info = cls;
1815 struct DHTQueryRecord *record;
1817 source_info = GNUNET_CONTAINER_heap_remove_node (source_info->hnode);
1818 record = source_info->record;
1819 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
1821 if (record->head == NULL) /* No more entries in DLL */
1823 GNUNET_assert (GNUNET_YES ==
1824 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
1825 &record->key, record));
1826 GNUNET_free (record);
1828 if (source_info->find_peers_responded != NULL)
1829 GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
1830 GNUNET_free (source_info);
1834 * Main function that handles whether or not to route a result
1835 * message to other peers, or to send to our local client.
1837 * @param msg the result message to be routed
1838 * @param msg_ctx context of the message we are routing
1840 * @return the number of peers the message was routed to,
1841 * GNUNET_SYSERR on failure
1844 route_result_message (struct GNUNET_MessageHeader *msg,
1845 struct DHT_MessageContext *msg_ctx)
1847 struct GNUNET_PeerIdentity new_peer;
1848 struct DHTQueryRecord *record;
1849 struct DHTRouteSource *pos;
1850 struct PeerInfo *peer_info;
1851 const struct GNUNET_MessageHeader *hello_msg;
1857 increment_stats (STAT_RESULTS);
1859 * If a find peer result message is received and contains a valid
1860 * HELLO for another peer, offer it to the transport service.
1862 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1864 if (ntohs (msg->size) <= sizeof (struct GNUNET_MessageHeader))
1865 GNUNET_break_op (0);
1867 hello_msg = &msg[1];
1868 if ((ntohs (hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) ||
1870 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) hello_msg,
1873 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1874 "%s:%s Received non-HELLO message type in find peer result message!\n",
1875 my_short_id, "DHT");
1876 GNUNET_break_op (0);
1879 else /* We have a valid hello, and peer id stored in new_peer */
1881 find_peer_context.count++;
1882 increment_stats (STAT_FIND_PEER_REPLY);
1883 if (GNUNET_YES == consider_peer (&new_peer))
1885 increment_stats (STAT_HELLOS_PROVIDED);
1886 GNUNET_TRANSPORT_offer_hello (transport_handle, hello_msg, NULL, NULL);
1887 GNUNET_CORE_peer_request_connect (coreAPI, &new_peer, NULL, NULL);
1892 if (malicious_dropper == GNUNET_YES)
1896 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
1898 if (record == NULL) /* No record of this message! */
1901 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1902 "`%s:%s': Have no record of response key %s uid %llu\n",
1903 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
1904 msg_ctx->unique_id);
1906 #if DEBUG_DHT_ROUTING
1907 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1909 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
1910 msg_ctx->hop_count, GNUNET_SYSERR,
1911 &my_identity, &msg_ctx->key, msg_ctx->peer,
1915 if (msg_ctx->bloom != NULL)
1917 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
1918 msg_ctx->bloom = NULL;
1926 #if STRICT_FORWARDING
1927 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
1930 GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded,
1931 &new_peer.hashPubKey))
1933 increment_stats ("# find peer responses NOT forwarded (bloom match)");
1938 GNUNET_CONTAINER_bloomfilter_add (pos->find_peers_responded,
1939 &new_peer.hashPubKey);
1943 if (0 == memcmp (&pos->source, &my_identity, sizeof (struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1946 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1947 "`%s:%s': Sending response key %s uid %llu to client\n",
1948 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
1949 msg_ctx->unique_id);
1951 #if DEBUG_DHT_ROUTING
1952 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1954 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
1955 msg_ctx->hop_count, GNUNET_YES,
1956 &my_identity, &msg_ctx->key, msg_ctx->peer,
1960 increment_stats (STAT_RESULTS_TO_CLIENT);
1961 if (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
1962 increment_stats (STAT_GET_REPLY);
1964 for (i = 0; i < msg_ctx->path_history_len; i++)
1969 &msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
1970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1971 "(before client) Key %s Found peer %d:%s\n",
1972 GNUNET_h2s (&msg_ctx->key), i,
1973 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
1976 send_reply_to_client (pos->client, msg, msg_ctx);
1978 else /* Send to peer */
1980 peer_info = find_peer_by_id (&pos->source);
1981 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
1987 if (msg_ctx->bloom == NULL)
1989 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
1991 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
1992 &my_identity.hashPubKey);
1994 GNUNET_CONTAINER_bloomfilter_test (msg_ctx->bloom,
1995 &peer_info->id.hashPubKey)))
1998 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1999 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n",
2000 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2001 msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2003 #if DEBUG_DHT_ROUTING
2004 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2006 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_RESULT,
2007 msg_ctx->hop_count, GNUNET_NO,
2008 &my_identity, &msg_ctx->key,
2009 msg_ctx->peer, &pos->source);
2012 forward_result_message (msg, peer_info, msg_ctx);
2013 /* Try removing forward entries after sending once, only allows ONE response per request */
2014 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
2016 GNUNET_SCHEDULER_cancel (pos->delete_task);
2018 GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
2024 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2025 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n",
2026 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
2027 msg_ctx->unique_id, GNUNET_i2s (&peer_info->id));
2033 if (msg_ctx->bloom != NULL)
2035 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
2036 msg_ctx->bloom = NULL;
2043 * Iterator for local get request results,
2045 * @param cls closure for iterator, a DatacacheGetContext
2046 * @param exp when does this value expire?
2047 * @param key the key this data is stored under
2048 * @param size the size of the data identified by key
2049 * @param data the actual data
2050 * @param type the type of the data
2052 * @return GNUNET_OK to continue iteration, anything else
2053 * to stop iteration.
2056 datacache_get_iterator (void *cls, struct GNUNET_TIME_Absolute exp,
2057 const GNUNET_HashCode * key, size_t size,
2058 const char *data, enum GNUNET_BLOCK_Type type)
2060 struct DHT_MessageContext *msg_ctx = cls;
2061 struct DHT_MessageContext *new_msg_ctx;
2062 struct GNUNET_DHT_GetResultMessage *get_result;
2063 enum GNUNET_BLOCK_EvaluationResult eval;
2064 const struct DHTPutEntry *put_entry;
2073 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2074 "`%s:%s': Received `%s' response from datacache\n", my_short_id,
2078 put_entry = (const struct DHTPutEntry *) data;
2081 sizeof (struct DHTPutEntry) + put_entry->data_size +
2082 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)))
2084 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2085 "Path + data size doesn't add up for data inserted into datacache!\nData size %d, path length %d, expected %d, got %d\n",
2086 put_entry->data_size, put_entry->path_length,
2087 sizeof (struct DHTPutEntry) + put_entry->data_size +
2088 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)),
2090 msg_ctx->do_forward = GNUNET_NO;
2095 GNUNET_BLOCK_evaluate (block_context, type, key, &msg_ctx->reply_bf,
2096 msg_ctx->reply_bf_mutator, msg_ctx->xquery,
2097 msg_ctx->xquery_size, &put_entry[1],
2098 put_entry->data_size);
2102 case GNUNET_BLOCK_EVALUATION_OK_LAST:
2103 msg_ctx->do_forward = GNUNET_NO;
2104 case GNUNET_BLOCK_EVALUATION_OK_MORE:
2105 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2106 memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2107 if (GNUNET_DHT_RO_RECORD_ROUTE ==
2108 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2110 new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2111 new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2112 /* Assign to previous msg_ctx path history, caller should free after our return */
2113 new_msg_ctx->path_history = msg_ctx->path_history;
2115 for (i = 0; i < new_msg_ctx->path_history_len; i++)
2118 &new_msg_ctx->path_history[i * sizeof (struct GNUNET_PeerIdentity)];
2119 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2120 "(get_iterator) Key %s Found peer %d:%s\n",
2121 GNUNET_h2s (&msg_ctx->key), i,
2122 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
2128 sizeof (struct GNUNET_DHT_GetResultMessage) + put_entry->data_size +
2129 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity));
2130 get_result = GNUNET_malloc (get_size);
2131 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2132 get_result->header.size = htons (get_size);
2133 get_result->expiration = GNUNET_TIME_absolute_hton (exp);
2134 get_result->type = htons (type);
2135 get_result->put_path_length = htons (put_entry->path_length);
2136 path_offset = (char *) &put_entry[1];
2137 path_offset += put_entry->data_size;
2139 for (i = 0; i < put_entry->path_length; i++)
2141 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2142 "(get_iterator PUT path) Key %s Found peer %d:%s\n",
2143 GNUNET_h2s (&msg_ctx->key), i,
2144 GNUNET_i2s ((struct GNUNET_PeerIdentity *)
2147 GNUNET_PeerIdentity)]));
2150 /* Copy the actual data and the path_history to the end of the get result */
2151 memcpy (&get_result[1], &put_entry[1],
2152 put_entry->data_size +
2153 (put_entry->path_length * sizeof (struct GNUNET_PeerIdentity)));
2154 new_msg_ctx->peer = &my_identity;
2155 new_msg_ctx->bloom =
2156 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2157 new_msg_ctx->hop_count = 0;
2158 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
2159 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2160 increment_stats (STAT_GET_RESPONSE_START);
2161 route_result_message (&get_result->header, new_msg_ctx);
2162 GNUNET_free (new_msg_ctx);
2163 GNUNET_free (get_result);
2165 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
2167 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': Duplicate block error\n",
2168 my_short_id, "DHT");
2171 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
2173 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "`%s:%s': Invalid request error\n",
2174 my_short_id, "DHT");
2177 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
2179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2180 "`%s:%s': Valid request, no results.\n", my_short_id, "DHT");
2184 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
2185 GNUNET_break_op (0);
2186 msg_ctx->do_forward = GNUNET_NO;
2188 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
2190 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2191 "`%s:%s': Unsupported block type (%u) in response!\n",
2192 my_short_id, "DHT", type);
2194 /* msg_ctx->do_forward = GNUNET_NO; // not sure... */
2202 * Main function that handles whether or not to route a message to other
2205 * @param msg the message to be routed
2206 * @param msg_ctx the context containing all pertinent information about the message
2209 route_message (const struct GNUNET_MessageHeader *msg,
2210 struct DHT_MessageContext *msg_ctx);
2214 * Server handler for all dht get requests, look for data,
2215 * if found, send response either to clients or other peers.
2217 * @param msg the actual get message
2218 * @param msg_ctx struct containing pertinent information about the get request
2220 * @return number of items found for GET request
2223 handle_dht_get (const struct GNUNET_MessageHeader *msg,
2224 struct DHT_MessageContext *msg_ctx)
2226 const struct GNUNET_DHT_GetMessage *get_msg;
2229 unsigned int results;
2231 enum GNUNET_BLOCK_Type type;
2233 msize = ntohs (msg->size);
2234 if (msize < sizeof (struct GNUNET_DHT_GetMessage))
2239 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2240 bf_size = ntohs (get_msg->bf_size);
2241 msg_ctx->xquery_size = ntohs (get_msg->xquery_size);
2242 msg_ctx->reply_bf_mutator = get_msg->bf_mutator;
2244 sizeof (struct GNUNET_DHT_GetMessage) + bf_size + msg_ctx->xquery_size)
2249 end = (const char *) &get_msg[1];
2250 if (msg_ctx->xquery_size == 0)
2252 msg_ctx->xquery = NULL;
2256 msg_ctx->xquery = (const void *) end;
2257 end += msg_ctx->xquery_size;
2261 msg_ctx->reply_bf = NULL;
2266 GNUNET_CONTAINER_bloomfilter_init (end, bf_size,
2267 GNUNET_DHT_GET_BLOOMFILTER_K);
2269 type = (enum GNUNET_BLOCK_Type) ntohl (get_msg->type);
2271 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2272 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n",
2273 my_short_id, "DHT", "GET", type, GNUNET_h2s (&msg_ctx->key),
2274 msg_ctx->unique_id);
2276 increment_stats (STAT_GETS);
2279 if (type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2281 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2285 msg_ctx->do_forward = GNUNET_YES;
2286 if (datacache != NULL)
2288 GNUNET_DATACACHE_get (datacache, &msg_ctx->key, type,
2289 &datacache_get_iterator, msg_ctx);
2291 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2292 "`%s:%s': Found %d results for `%s' request uid %llu\n",
2293 my_short_id, "DHT", results, "GET", msg_ctx->unique_id);
2297 #if DEBUG_DHT_ROUTING
2298 if ((debug_routes) && (dhtlog_handle != NULL))
2300 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2301 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2305 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2307 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2308 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2309 &msg_ctx->key, msg_ctx->peer, NULL);
2315 /* check query valid */
2316 if (GNUNET_BLOCK_EVALUATION_REQUEST_INVALID ==
2317 GNUNET_BLOCK_evaluate (block_context, type, &msg_ctx->key,
2318 &msg_ctx->reply_bf, msg_ctx->reply_bf_mutator,
2319 msg_ctx->xquery, msg_ctx->xquery_size, NULL, 0))
2321 GNUNET_break_op (0);
2322 msg_ctx->do_forward = GNUNET_NO;
2326 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2328 #if DEBUG_DHT_ROUTING
2329 if ((debug_routes) && (dhtlog_handle != NULL))
2331 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_GET,
2332 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2337 if (msg_ctx->do_forward == GNUNET_YES)
2338 route_message (msg, msg_ctx);
2339 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->reply_bf);
2345 remove_recent_find_peer (void *cls,
2346 const struct GNUNET_SCHEDULER_TaskContext *tc)
2348 GNUNET_HashCode *key = cls;
2350 GNUNET_assert (GNUNET_YES ==
2351 GNUNET_CONTAINER_multihashmap_remove
2352 (recent_find_peer_requests, key, NULL));
2358 * Server handler for initiating local dht find peer requests
2360 * @param find_msg the actual find peer message
2361 * @param msg_ctx struct containing pertinent information about the request
2365 handle_dht_find_peer (const struct GNUNET_MessageHeader *find_msg,
2366 struct DHT_MessageContext *msg_ctx)
2368 struct GNUNET_MessageHeader *find_peer_result;
2369 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2370 struct DHT_MessageContext *new_msg_ctx;
2371 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2374 GNUNET_HashCode *recent_hash;
2375 struct GNUNET_MessageHeader *other_hello;
2376 size_t other_hello_size;
2377 struct GNUNET_PeerIdentity peer_id;
2379 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *) find_msg;
2380 GNUNET_break_op (ntohs (find_msg->size) >=
2381 (sizeof (struct GNUNET_DHT_FindPeerMessage)));
2382 if (ntohs (find_msg->size) < sizeof (struct GNUNET_DHT_FindPeerMessage))
2385 other_hello_size = 0;
2386 if (ntohs (find_msg->size) > sizeof (struct GNUNET_DHT_FindPeerMessage))
2389 ntohs (find_msg->size) - sizeof (struct GNUNET_DHT_FindPeerMessage);
2390 other_hello = GNUNET_malloc (other_hello_size);
2391 memcpy (other_hello, &find_peer_message[1], other_hello_size);
2392 if ((GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) other_hello) == 0)
2394 GNUNET_HELLO_get_id ((struct GNUNET_HELLO_Message *) other_hello,
2397 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2398 "Received invalid HELLO message in find peer request!\n");
2399 GNUNET_free (other_hello);
2402 #if FIND_PEER_WITH_HELLO
2403 if (GNUNET_YES == consider_peer (&peer_id))
2405 increment_stats (STAT_HELLOS_PROVIDED);
2406 GNUNET_TRANSPORT_offer_hello (transport_handle, other_hello, NULL, NULL);
2407 GNUNET_CORE_peer_request_connect (coreAPI, &peer_id, NULL, NULL);
2408 route_message (find_msg, msg_ctx);
2409 GNUNET_free (other_hello);
2412 else /* We don't want this peer! */
2414 route_message (find_msg, msg_ctx);
2415 GNUNET_free (other_hello);
2422 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2423 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2424 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (&msg_ctx->key),
2425 ntohs (find_msg->size), sizeof (struct GNUNET_MessageHeader));
2427 if (my_hello == NULL)
2430 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2431 "`%s': Our HELLO is null, can't return.\n", "DHT");
2433 GNUNET_free_non_null (other_hello);
2434 route_message (find_msg, msg_ctx);
2439 GNUNET_CONTAINER_bloomfilter_init (find_peer_message->bloomfilter,
2440 DHT_BLOOM_SIZE, DHT_BLOOM_K);
2442 GNUNET_CONTAINER_bloomfilter_test (incoming_bloom,
2443 &my_identity.hashPubKey))
2445 increment_stats (STAT_BLOOM_FIND_PEER);
2446 GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2447 GNUNET_free_non_null (other_hello);
2448 route_message (find_msg, msg_ctx);
2449 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!) */
2451 GNUNET_CONTAINER_bloomfilter_free (incoming_bloom);
2453 #if RESTRICT_FIND_PEER
2456 * Ignore any find peer requests from a peer we have seen very recently.
2458 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! */
2460 increment_stats ("# dht find peer requests ignored (recently seen!)");
2461 GNUNET_free_non_null (other_hello);
2466 * Use this check to only allow the peer to respond to find peer requests if
2467 * it would be beneficial to have the requesting peer in this peers routing
2468 * table. Can be used to thwart peers flooding the network with find peer
2469 * requests that we don't care about. However, if a new peer is joining
2470 * the network and has no other peers this is a problem (assume all buckets
2471 * full, no one will respond!).
2473 memcpy (&peer_id.hashPubKey, &msg_ctx->key, sizeof (GNUNET_HashCode));
2474 if (GNUNET_NO == consider_peer (&peer_id))
2476 increment_stats ("# dht find peer requests ignored (do not need!)");
2477 GNUNET_free_non_null (other_hello);
2478 route_message (find_msg, msg_ctx);
2483 recent_hash = GNUNET_malloc (sizeof (GNUNET_HashCode));
2484 memcpy (recent_hash, &msg_ctx->key, sizeof (GNUNET_HashCode));
2485 if (GNUNET_SYSERR !=
2486 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests,
2487 &msg_ctx->key, NULL,
2488 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
2491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2492 "Adding recent remove task for key `%s`!\n",
2493 GNUNET_h2s (&msg_ctx->key));
2495 /* Only add a task if there wasn't one for this key already! */
2496 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply
2497 (GNUNET_TIME_UNIT_SECONDS, 30),
2498 &remove_recent_find_peer, recent_hash);
2502 GNUNET_free (recent_hash);
2504 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2505 "Received duplicate find peer request too soon!\n");
2509 /* Simplistic find_peer functionality, always return our hello */
2510 hello_size = ntohs (my_hello->size);
2511 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2513 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2515 GNUNET_break_op (0);
2516 GNUNET_free_non_null (other_hello);
2520 find_peer_result = GNUNET_malloc (tsize);
2521 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2522 find_peer_result->size = htons (tsize);
2523 memcpy (&find_peer_result[1], my_hello, hello_size);
2525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2526 "`%s': Sending hello size %d to requesting peer.\n", "DHT",
2530 new_msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
2531 memcpy (new_msg_ctx, msg_ctx, sizeof (struct DHT_MessageContext));
2532 new_msg_ctx->peer = &my_identity;
2533 new_msg_ctx->bloom =
2534 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2535 new_msg_ctx->hop_count = 0;
2536 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make find peer requests a higher priority */
2537 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2538 increment_stats (STAT_FIND_PEER_ANSWER);
2539 if (GNUNET_DHT_RO_RECORD_ROUTE ==
2540 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
2542 new_msg_ctx->msg_options = GNUNET_DHT_RO_RECORD_ROUTE;
2543 new_msg_ctx->path_history_len = msg_ctx->path_history_len;
2544 /* Assign to previous msg_ctx path history, caller should free after our return */
2545 new_msg_ctx->path_history = msg_ctx->path_history;
2547 route_result_message (find_peer_result, new_msg_ctx);
2548 GNUNET_free (new_msg_ctx);
2549 #if DEBUG_DHT_ROUTING
2550 if ((debug_routes) && (dhtlog_handle != NULL))
2552 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
2553 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2557 GNUNET_free_non_null (other_hello);
2558 GNUNET_free (find_peer_result);
2559 route_message (find_msg, msg_ctx);
2564 * Server handler for initiating local dht put requests
2566 * @param msg the actual put message
2567 * @param msg_ctx struct containing pertinent information about the request
2570 handle_dht_put (const struct GNUNET_MessageHeader *msg,
2571 struct DHT_MessageContext *msg_ctx)
2573 const struct GNUNET_DHT_PutMessage *put_msg;
2574 struct DHTPutEntry *put_entry;
2575 unsigned int put_size;
2577 enum GNUNET_BLOCK_Type put_type;
2580 GNUNET_HashCode key;
2581 struct DHTQueryRecord *record;
2583 GNUNET_assert (ntohs (msg->size) >= sizeof (struct GNUNET_DHT_PutMessage));
2585 put_msg = (const struct GNUNET_DHT_PutMessage *) msg;
2586 put_type = (enum GNUNET_BLOCK_Type) ntohl (put_msg->type);
2588 if (put_type == GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE)
2590 #if DEBUG_DHT_ROUTING
2591 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2593 /** Log routes that die due to high load! */
2594 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2595 msg_ctx->hop_count, GNUNET_SYSERR,
2596 &my_identity, &msg_ctx->key, msg_ctx->peer,
2604 ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2606 GNUNET_BLOCK_get_key (block_context, put_type, &put_msg[1], data_size,
2608 if (GNUNET_NO == ret)
2610 #if DEBUG_DHT_ROUTING
2611 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2613 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2614 msg_ctx->hop_count, GNUNET_SYSERR,
2615 &my_identity, &msg_ctx->key, msg_ctx->peer,
2620 GNUNET_break_op (0);
2623 if ((GNUNET_YES == ret) &&
2624 (0 != memcmp (&key, &msg_ctx->key, sizeof (GNUNET_HashCode))))
2626 #if DEBUG_DHT_ROUTING
2627 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2629 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2630 msg_ctx->hop_count, GNUNET_SYSERR,
2631 &my_identity, &msg_ctx->key, msg_ctx->peer,
2635 /* invalid wrapper: key mismatch! */
2636 GNUNET_break_op (0);
2639 /* ret == GNUNET_SYSERR means that there is no known relationship between
2640 * data and the key, so we cannot check it */
2642 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2643 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2644 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2645 msg_ctx->unique_id);
2647 #if DEBUG_DHT_ROUTING
2648 if (msg_ctx->hop_count == 0) /* Locally initiated request */
2650 if ((debug_routes) && (dhtlog_handle != NULL))
2652 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2653 msg_ctx->hop_count, GNUNET_NO, &my_identity,
2659 // GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT 1\n");
2661 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
2664 struct DHTRouteSource *pos;
2665 struct GNUNET_DHT_GetMessage *gmsg;
2668 // GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT 2\n");
2672 /* TODO: do only for local started requests? or also for remote peers? */
2673 /* TODO: include this in statistics? under what? */
2674 if (NULL == pos->client)
2677 gsize = data_size + sizeof (struct GNUNET_DHT_GetMessage);
2678 gmsg = GNUNET_malloc (gsize);
2679 gmsg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2680 gmsg->header.size = htons (gsize);
2681 gmsg->type = put_msg->type;
2682 memcpy (&gmsg[1], &put_msg[1], data_size);
2684 /* TODO: duplicate and reverse order of path_history? */
2685 send_reply_to_client (pos->client, &gmsg->header, msg_ctx);
2689 // GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "******************************************************** PUT END\n");
2691 if (msg_ctx->closest != GNUNET_YES)
2693 route_message (msg, msg_ctx);
2698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2699 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2700 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (&msg_ctx->key),
2701 msg_ctx->unique_id);
2704 #if DEBUG_DHT_ROUTING
2705 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2707 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
2708 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2709 &msg_ctx->key, msg_ctx->peer, NULL);
2712 if ((debug_routes) && (dhtlog_handle != NULL))
2714 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_PUT,
2715 msg_ctx->hop_count, GNUNET_YES, &my_identity,
2720 increment_stats (STAT_PUTS_INSERTED);
2721 if (datacache != NULL)
2723 /* Put size is actual data size plus struct overhead plus path length (if any) */
2725 data_size + sizeof (struct DHTPutEntry) +
2726 (msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2727 put_entry = GNUNET_malloc (put_size);
2728 put_entry->data_size = data_size;
2729 put_entry->path_length = msg_ctx->path_history_len;
2730 /* Copy data to end of put entry */
2731 memcpy (&put_entry[1], &put_msg[1], data_size);
2732 if (msg_ctx->path_history_len > 0)
2734 /* Copy path after data */
2735 path_offset = (char *) &put_entry[1];
2736 path_offset += data_size;
2737 memcpy (path_offset, msg_ctx->path_history,
2738 msg_ctx->path_history_len * sizeof (struct GNUNET_PeerIdentity));
2742 GNUNET_DATACACHE_put (datacache, &msg_ctx->key, put_size,
2743 (const char *) put_entry, put_type,
2744 GNUNET_TIME_absolute_ntoh (put_msg->expiration));
2745 GNUNET_free (put_entry);
2748 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2749 "`%s:%s': %s request received, but have no datacache!\n",
2750 my_short_id, "DHT", "PUT");
2752 if (stop_on_closest == GNUNET_NO)
2753 route_message (msg, msg_ctx);
2758 * To how many peers should we (on average)
2759 * forward the request to obtain the desired
2760 * target_replication count (on average).
2762 * returns: target_replication / (est. hops) + (target_replication * hop_count)
2763 * where est. hops is typically 2 * the routing table depth
2765 * @param hop_count number of hops the message has traversed
2766 * @param target_replication the number of total paths desired
2768 * @return Some number of peers to forward the message to
2771 get_forward_count (unsigned int hop_count, size_t target_replication)
2773 uint32_t random_value;
2774 unsigned int forward_count;
2778 * If we are behaving in strict kademlia mode, send multiple initial requests,
2779 * but then only send to 1 or 0 peers based strictly on the number of hops.
2781 if (strict_kademlia == GNUNET_YES)
2784 return kademlia_replication;
2785 if (hop_count < log_of_network_size_estimate * 2.0)
2790 if (hop_count > log_of_network_size_estimate * 2.0)
2792 if (GNUNET_YES == paper_forwarding)
2794 /* Once we have reached our ideal number of hops, don't stop forwarding! */
2798 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2799 "Hop count too high (est %f, lowest %d), NOT Forwarding request\n",
2800 log_of_network_size_estimate * 2.0, lowest_bucket);
2805 if (GNUNET_YES == paper_forwarding)
2807 /* FIXME: re-run replication trials with this formula */
2809 1 + (target_replication - 1.0) / (log_of_network_size_estimate +
2810 ((float) (target_replication - 1.0) *
2812 /* Set forward count to floor of target_value */
2813 forward_count = (unsigned int) target_value;
2814 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
2815 target_value = target_value - forward_count;
2817 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
2819 if (random_value < (target_value * UINT32_MAX))
2827 target_replication / (log_of_network_size_estimate +
2828 ((float) target_replication * hop_count));
2829 if (target_value > 1)
2831 /* Set forward count to floor of target_value */
2832 forward_count = (unsigned int) target_value;
2833 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
2834 target_value = target_value - forward_count;
2838 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_STRONG, UINT32_MAX);
2840 if (random_value < (target_value * UINT32_MAX))
2844 return forward_count;
2849 * Check whether my identity is closer than any known peers.
2850 * If a non-null bloomfilter is given, check if this is the closest
2851 * peer that hasn't already been routed to.
2853 * @param target hash code to check closeness to
2854 * @param bloom bloomfilter, exclude these entries from the decision
2855 * @return GNUNET_YES if node location is closest,
2856 * GNUNET_NO otherwise.
2859 am_closest_peer (const GNUNET_HashCode * target,
2860 struct GNUNET_CONTAINER_BloomFilter *bloom)
2866 struct PeerInfo *pos;
2867 unsigned int my_distance;
2869 if (0 == memcmp (&my_identity.hashPubKey, target, sizeof (GNUNET_HashCode)))
2872 bucket_num = find_current_bucket (target);
2874 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, target);
2875 my_distance = distance (&my_identity.hashPubKey, target);
2876 pos = k_buckets[bucket_num].head;
2878 while ((pos != NULL) && (count < bucket_size))
2880 if ((bloom != NULL) &&
2882 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
2885 continue; /* Skip already checked entries */
2888 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, target);
2889 if (other_bits > bits)
2891 else if (other_bits == bits) /* We match the same number of bits */
2893 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2895 if (distance (&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2901 /* No peers closer, we are the closest! */
2907 * Select a peer from the routing table that would be a good routing
2908 * destination for sending a message for "target". The resulting peer
2909 * must not be in the set of blocked peers.<p>
2911 * Note that we should not ALWAYS select the closest peer to the
2912 * target, peers further away from the target should be chosen with
2913 * exponentially declining probability.
2915 * @param target the key we are selecting a peer to route to
2916 * @param bloom a bloomfilter containing entries this request has seen already
2917 * @param hops how many hops has this message traversed thus far
2919 * @return Peer to route to, or NULL on error
2921 static struct PeerInfo *
2922 select_peer (const GNUNET_HashCode * target,
2923 struct GNUNET_CONTAINER_BloomFilter *bloom, unsigned int hops)
2927 unsigned int selected;
2928 struct PeerInfo *pos;
2929 unsigned int distance;
2930 unsigned int largest_distance;
2931 struct PeerInfo *chosen;
2933 /** If we are doing kademlia routing (saves some cycles) */
2934 if ((strict_kademlia == GNUNET_YES) || (hops >= log_of_network_size_estimate))
2936 /* greedy selection (closest peer that is not in bloomfilter) */
2937 largest_distance = 0;
2939 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2941 pos = k_buckets[bc].head;
2943 while ((pos != NULL) && (count < bucket_size))
2945 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2947 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2949 distance = inverse_distance (target, &pos->id.hashPubKey);
2950 if (distance > largest_distance)
2953 largest_distance = distance;
2960 if ((largest_distance > 0) && (chosen != NULL))
2962 GNUNET_CONTAINER_bloomfilter_add (bloom, &chosen->id.hashPubKey);
2965 return NULL; /* no peer available or we are the closest */
2969 /* select "random" peer */
2970 /* count number of peers that are available and not filtered */
2972 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2974 pos = k_buckets[bc].head;
2975 while ((pos != NULL) && (count < bucket_size))
2978 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2981 continue; /* Ignore bloomfiltered peers */
2987 if (count == 0) /* No peers to select from! */
2989 increment_stats ("# failed to select peer");
2992 /* Now actually choose a peer */
2993 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
2995 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2997 pos = k_buckets[bc].head;
2998 while ((pos != NULL) && (count < bucket_size))
3001 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
3004 continue; /* Ignore bloomfiltered peers */
3006 if (0 == selected--)
3017 * Task used to remove recent entries, either
3018 * after timeout, when full, or on shutdown.
3020 * @param cls the entry to remove
3021 * @param tc context, reason, etc.
3024 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3026 struct RecentRequest *req = cls;
3027 static GNUNET_HashCode hash;
3029 GNUNET_assert (req != NULL);
3030 hash_from_uid (req->uid, &hash);
3031 GNUNET_assert (GNUNET_YES ==
3032 GNUNET_CONTAINER_multihashmap_remove (recent.hashmap, &hash,
3034 GNUNET_CONTAINER_heap_remove_node (req->heap_node);
3035 GNUNET_CONTAINER_bloomfilter_free (req->bloom);
3039 * if ( (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3041 * GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3042 * GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3048 * Remember this routing request so that if a reply is
3049 * received we can either forward it to the correct peer
3050 * or return the result locally.
3052 * @param msg_ctx Context of the route request
3054 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3057 cache_response (struct DHT_MessageContext *msg_ctx)
3059 struct DHTQueryRecord *record;
3060 struct DHTRouteSource *source_info;
3061 struct DHTRouteSource *pos;
3062 struct GNUNET_TIME_Absolute now;
3063 unsigned int current_size;
3065 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3067 #if DELETE_WHEN_FULL
3068 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3070 source_info = GNUNET_CONTAINER_heap_remove_root (forward_list.minHeap);
3071 GNUNET_assert (source_info != NULL);
3072 record = source_info->record;
3073 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, source_info);
3074 if (record->head == NULL) /* No more entries in DLL */
3076 GNUNET_assert (GNUNET_YES ==
3077 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
3080 GNUNET_free (record);
3082 if (source_info->delete_task != GNUNET_SCHEDULER_NO_TASK)
3084 GNUNET_SCHEDULER_cancel (source_info->delete_task);
3085 source_info->delete_task = GNUNET_SCHEDULER_NO_TASK;
3087 if (source_info->find_peers_responded != NULL)
3088 GNUNET_CONTAINER_bloomfilter_free (source_info->find_peers_responded);
3089 GNUNET_free (source_info);
3090 current_size = GNUNET_CONTAINER_multihashmap_size (forward_list.hashmap);
3093 /** Non-local request and have too many outstanding forwards, discard! */
3094 if ((current_size >= MAX_OUTSTANDING_FORWARDS) && (msg_ctx->client == NULL))
3097 now = GNUNET_TIME_absolute_get ();
3099 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap, &msg_ctx->key);
3100 if (record != NULL) /* Already know this request! */
3105 if ((NULL != msg_ctx->peer) &&
3107 memcmp (msg_ctx->peer, &pos->source,
3108 sizeof (struct GNUNET_PeerIdentity))))
3109 break; /* Already have this peer in reply list! */
3112 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3114 GNUNET_CONTAINER_heap_update_cost (forward_list.minHeap, pos->hnode,
3121 record = GNUNET_malloc (sizeof (struct DHTQueryRecord));
3122 GNUNET_assert (GNUNET_OK ==
3123 GNUNET_CONTAINER_multihashmap_put (forward_list.hashmap,
3124 &msg_ctx->key, record,
3125 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3126 memcpy (&record->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3129 source_info = GNUNET_malloc (sizeof (struct DHTRouteSource));
3130 source_info->record = record;
3131 source_info->delete_task =
3132 GNUNET_SCHEDULER_add_delayed (DHT_FORWARD_TIMEOUT, &remove_forward_entry,
3134 source_info->find_peers_responded =
3135 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3136 memcpy (&source_info->source, msg_ctx->peer,
3137 sizeof (struct GNUNET_PeerIdentity));
3138 GNUNET_CONTAINER_DLL_insert_after (record->head, record->tail, record->tail,
3140 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3142 source_info->client = msg_ctx->client;
3143 now = GNUNET_TIME_absolute_get_forever ();
3145 source_info->hnode =
3146 GNUNET_CONTAINER_heap_insert (forward_list.minHeap, source_info,
3149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3150 "`%s:%s': Created new forward source info for %s uid %llu\n",
3151 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3152 msg_ctx->unique_id);
3159 * Main function that handles whether or not to route a message to other
3162 * @param msg the message to be routed
3163 * @param msg_ctx the context containing all pertinent information about the message
3166 route_message (const struct GNUNET_MessageHeader *msg,
3167 struct DHT_MessageContext *msg_ctx)
3170 struct PeerInfo *selected;
3172 #if DEBUG_DHT_ROUTING > 1
3173 struct PeerInfo *nearest;
3175 unsigned int target_forward_count;
3176 unsigned int forward_count;
3177 struct RecentRequest *recent_req;
3178 GNUNET_HashCode unique_hash;
3179 char *stat_forward_count;
3180 char *temp_stat_str;
3182 #if DEBUG_DHT_ROUTING
3186 if (malicious_dropper == GNUNET_YES)
3188 #if DEBUG_DHT_ROUTING
3189 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3191 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3192 msg_ctx->hop_count, GNUNET_SYSERR,
3193 &my_identity, &msg_ctx->key, msg_ctx->peer,
3197 if (msg_ctx->bloom != NULL)
3199 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3200 msg_ctx->bloom = NULL;
3205 increment_stats (STAT_ROUTES);
3206 target_forward_count =
3207 get_forward_count (msg_ctx->hop_count, msg_ctx->replication);
3208 GNUNET_asprintf (&stat_forward_count, "# forward counts of %d",
3209 target_forward_count);
3210 increment_stats (stat_forward_count);
3211 GNUNET_free (stat_forward_count);
3212 if (msg_ctx->bloom == NULL)
3214 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3216 if ((stop_on_closest == GNUNET_YES) && (msg_ctx->closest == GNUNET_YES) &&
3217 (ntohs (msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3218 target_forward_count = 0;
3221 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3222 * any closer peers (which is being checked for below). Since we are doing recursive
3223 * routing we have no choice but to stop forwarding in this case. This means that at
3224 * any given step the request may NOT be forwarded to alpha peers (because routes will
3225 * stop and the parallel route will not be aware of it). Of course, assuming that we
3226 * have fulfilled the Kademlia requirements for routing table fullness this will never
3227 * ever ever be a problem.
3229 * However, is this fair?
3231 * Since we use these requests to build our routing tables (and we build them in the
3232 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3233 * routing tables still get constructed.
3235 if ((GNUNET_YES == strict_kademlia) && (msg_ctx->closest == GNUNET_YES) &&
3236 (msg_ctx->hop_count > 0) &&
3237 (ntohs (msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3238 target_forward_count = 0;
3241 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom, &my_identity.hashPubKey);
3242 hash_from_uid (msg_ctx->unique_id, &unique_hash);
3244 GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3247 GNUNET_CONTAINER_multihashmap_get (recent.hashmap, &unique_hash);
3248 GNUNET_assert (recent_req != NULL);
3249 if (0 != memcmp (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode)))
3250 increment_stats (STAT_DUPLICATE_UID);
3253 increment_stats (STAT_RECENT_SEEN);
3254 GNUNET_CONTAINER_bloomfilter_or2 (msg_ctx->bloom, recent_req->bloom,
3260 recent_req = GNUNET_malloc (sizeof (struct RecentRequest));
3261 recent_req->uid = msg_ctx->unique_id;
3262 memcpy (&recent_req->key, &msg_ctx->key, sizeof (GNUNET_HashCode));
3263 recent_req->remove_task =
3264 GNUNET_SCHEDULER_add_delayed (DEFAULT_RECENT_REMOVAL, &remove_recent,
3266 recent_req->heap_node =
3267 GNUNET_CONTAINER_heap_insert (recent.minHeap, recent_req,
3268 GNUNET_TIME_absolute_get ().abs_value);
3270 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3271 GNUNET_CONTAINER_multihashmap_put (recent.hashmap, &unique_hash, recent_req,
3272 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3275 if (GNUNET_CONTAINER_multihashmap_size (recent.hashmap) > DHT_MAX_RECENT)
3277 recent_req = GNUNET_CONTAINER_heap_peek (recent.minHeap);
3278 GNUNET_assert (recent_req != NULL);
3279 GNUNET_SCHEDULER_cancel (recent_req->remove_task);
3280 recent_req->remove_task =
3281 GNUNET_SCHEDULER_add_now (&remove_recent, recent_req);
3285 for (i = 0; i < target_forward_count; i++)
3287 selected = select_peer (&msg_ctx->key, msg_ctx->bloom, msg_ctx->hop_count);
3289 if (selected != NULL)
3292 if (GNUNET_CRYPTO_hash_matching_bits
3293 (&selected->id.hashPubKey,
3295 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
3297 GNUNET_asprintf (&temp_stat_str,
3298 "# requests routed to close(r) peer hop %u",
3299 msg_ctx->hop_count);
3301 GNUNET_asprintf (&temp_stat_str,
3302 "# requests routed to less close peer hop %u",
3303 msg_ctx->hop_count);
3304 if (temp_stat_str != NULL)
3306 increment_stats (temp_stat_str);
3307 GNUNET_free (temp_stat_str);
3309 GNUNET_CONTAINER_bloomfilter_add (msg_ctx->bloom,
3310 &selected->id.hashPubKey);
3311 #if DEBUG_DHT_ROUTING > 1
3312 nearest = find_closest_peer (&msg_ctx->key);
3313 nearest_buf = GNUNET_strdup (GNUNET_i2s (&nearest->id));
3314 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3315 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n",
3316 my_short_id, "DHT", GNUNET_h2s (&msg_ctx->key),
3317 msg_ctx->unique_id, GNUNET_i2s (&selected->id), nearest_buf,
3318 GNUNET_CRYPTO_hash_matching_bits (&nearest->id.hashPubKey,
3320 distance (&nearest->id.hashPubKey, msg_ctx->key));
3321 GNUNET_free (nearest_buf);
3323 #if DEBUG_DHT_ROUTING
3324 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3326 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3327 msg_ctx->hop_count, GNUNET_NO,
3328 &my_identity, &msg_ctx->key, msg_ctx->peer,
3332 forward_message (msg, selected, msg_ctx);
3336 if (msg_ctx->bloom != NULL)
3338 GNUNET_CONTAINER_bloomfilter_or2 (recent_req->bloom, msg_ctx->bloom,
3340 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
3341 msg_ctx->bloom = NULL;
3344 #if DEBUG_DHT_ROUTING
3345 if (forward_count == 0)
3346 ret = GNUNET_SYSERR;
3350 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3352 dhtlog_handle->insert_route (NULL, msg_ctx->unique_id, DHTLOG_ROUTE,
3353 msg_ctx->hop_count, ret, &my_identity,
3354 &msg_ctx->key, msg_ctx->peer, NULL);
3361 * Main function that handles whether or not to route a message to other
3364 * @param msg the message to be routed
3365 * @param msg_ctx the context containing all pertinent information about the message
3368 demultiplex_message (const struct GNUNET_MessageHeader *msg,
3369 struct DHT_MessageContext *msg_ctx)
3371 /* FIXME: Should we use closest excluding those we won't route to (the bloomfilter problem)? */
3372 msg_ctx->closest = am_closest_peer (&msg_ctx->key, msg_ctx->bloom);
3374 switch (ntohs (msg->type))
3376 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3377 cache_response (msg_ctx);
3378 handle_dht_get (msg, msg_ctx);
3380 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. */
3381 increment_stats (STAT_PUTS);
3382 handle_dht_put (msg, msg_ctx);
3384 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3385 increment_stats (STAT_FIND_PEER);
3386 if (((msg_ctx->hop_count > 0) &&
3388 memcmp (msg_ctx->peer, &my_identity,
3389 sizeof (struct GNUNET_PeerIdentity)))) ||
3390 (msg_ctx->client != NULL))
3392 cache_response (msg_ctx);
3393 if ((msg_ctx->closest == GNUNET_YES) ||
3394 (msg_ctx->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3395 handle_dht_find_peer (msg, msg_ctx);
3398 route_message (msg, msg_ctx);
3399 #if DEBUG_DHT_ROUTING
3400 if (msg_ctx->hop_count == 0) /* Locally initiated request */
3402 if ((debug_routes) && (dhtlog_handle != NULL))
3404 dhtlog_handle->insert_dhtkey (NULL, &msg_ctx->key);
3405 dhtlog_handle->insert_query (NULL, msg_ctx->unique_id, DHTLOG_FIND_PEER,
3406 msg_ctx->hop_count, GNUNET_NO,
3407 &my_identity, &msg_ctx->key);
3413 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3414 "`%s': Message type (%d) not handled, forwarding anyway!\n",
3415 "DHT", ntohs (msg->type));
3416 route_message (msg, msg_ctx);
3422 * Iterator over hash map entries.
3424 * @param cls client to search for in source routes
3425 * @param key current key code (ignored)
3426 * @param value value in the hash map, a DHTQueryRecord
3427 * @return GNUNET_YES if we should continue to
3432 find_client_records (void *cls, const GNUNET_HashCode * key, void *value)
3434 struct ClientList *client = cls;
3435 struct DHTQueryRecord *record = value;
3436 struct DHTRouteSource *pos;
3441 if (pos->client == client)
3447 GNUNET_CONTAINER_DLL_remove (record->head, record->tail, pos);
3448 GNUNET_CONTAINER_heap_remove_node (pos->hnode);
3449 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3451 GNUNET_SCHEDULER_cancel (pos->delete_task);
3452 pos->delete_task = GNUNET_SCHEDULER_NO_TASK;
3454 if (pos->find_peers_responded != NULL)
3455 GNUNET_CONTAINER_bloomfilter_free (pos->find_peers_responded);
3458 if (record->head == NULL) /* No more entries in DLL */
3460 GNUNET_assert (GNUNET_YES ==
3461 GNUNET_CONTAINER_multihashmap_remove (forward_list.hashmap,
3462 &record->key, record));
3463 GNUNET_free (record);
3469 * Functions with this signature are called whenever a client
3470 * is disconnected on the network level.
3472 * @param cls closure (NULL for dht)
3473 * @param client identification of the client; NULL
3474 * for the last call when the server is destroyed
3477 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
3479 struct ClientList *pos = client_list;
3480 struct ClientList *prev;
3481 struct ClientList *found;
3482 struct PendingMessage *reply;
3488 if (pos->client_handle == client)
3491 prev->next = pos->next;
3493 client_list = pos->next;
3503 if (found->transmit_handle != NULL)
3504 GNUNET_CONNECTION_notify_transmit_ready_cancel (found->transmit_handle);
3506 while (NULL != (reply = found->pending_head))
3508 GNUNET_CONTAINER_DLL_remove (found->pending_head, found->pending_tail,
3510 GNUNET_free (reply);
3512 GNUNET_CONTAINER_multihashmap_iterate (forward_list.hashmap,
3513 &find_client_records, found);
3514 GNUNET_free (found);
3519 * Find a client if it exists, add it otherwise.
3521 * @param client the server handle to the client
3523 * @return the client if found, a new client otherwise
3525 static struct ClientList *
3526 find_active_client (struct GNUNET_SERVER_Client *client)
3528 struct ClientList *pos = client_list;
3529 struct ClientList *ret;
3533 if (pos->client_handle == client)
3538 ret = GNUNET_malloc (sizeof (struct ClientList));
3539 ret->client_handle = client;
3540 ret->next = client_list;
3548 * Task to send a malicious put message across the network.
3550 * @param cls closure for this task
3551 * @param tc the context under which the task is running
3554 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3556 static struct GNUNET_DHT_PutMessage put_message;
3557 static struct DHT_MessageContext msg_ctx;
3558 static GNUNET_HashCode key;
3559 uint32_t random_key;
3561 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3563 put_message.header.size = htons (sizeof (struct GNUNET_DHT_PutMessage));
3564 put_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3565 put_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3566 put_message.expiration =
3567 GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get_forever ());
3568 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3570 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
3571 GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
3572 memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
3574 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
3575 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
3576 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3577 msg_ctx.msg_options = ntohl (0);
3578 msg_ctx.network_size = log_of_network_size_estimate;
3579 msg_ctx.peer = &my_identity;
3580 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3581 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3582 #if DEBUG_DHT_ROUTING
3583 if (dhtlog_handle != NULL)
3584 dhtlog_handle->insert_dhtkey (NULL, &key);
3586 increment_stats (STAT_PUT_START);
3587 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3588 "%s:%s Sending malicious PUT message with hash %s\n", my_short_id,
3589 "DHT", GNUNET_h2s (&key));
3590 demultiplex_message (&put_message.header, &msg_ctx);
3591 GNUNET_SCHEDULER_add_delayed (malicious_put_frequency, &malicious_put_task,
3597 * Task to send a malicious put message across the network.
3599 * @param cls closure for this task
3600 * @param tc the context under which the task is running
3603 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3605 static struct GNUNET_DHT_GetMessage get_message;
3606 struct DHT_MessageContext msg_ctx;
3607 static GNUNET_HashCode key;
3608 uint32_t random_key;
3610 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3613 get_message.header.size = htons (sizeof (struct GNUNET_DHT_GetMessage));
3614 get_message.header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET);
3615 get_message.type = htonl (GNUNET_BLOCK_DHT_MALICIOUS_MESSAGE_TYPE);
3616 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3618 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
3619 GNUNET_CRYPTO_hash (&random_key, sizeof (uint32_t), &key);
3620 memcpy (&msg_ctx.key, &key, sizeof (GNUNET_HashCode));
3622 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
3623 (GNUNET_CRYPTO_QUALITY_WEAK, UINT64_MAX));
3624 msg_ctx.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3625 msg_ctx.msg_options = ntohl (0);
3626 msg_ctx.network_size = log_of_network_size_estimate;
3627 msg_ctx.peer = &my_identity;
3628 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE;
3629 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3630 #if DEBUG_DHT_ROUTING
3631 if (dhtlog_handle != NULL)
3632 dhtlog_handle->insert_dhtkey (NULL, &key);
3634 increment_stats (STAT_GET_START);
3635 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3636 "%s:%s Sending malicious GET message with hash %s\n", my_short_id,
3637 "DHT", GNUNET_h2s (&key));
3638 demultiplex_message (&get_message.header, &msg_ctx);
3639 GNUNET_SCHEDULER_add_delayed (malicious_get_frequency, &malicious_get_task,
3646 * Iterator over hash map entries.
3648 * @param cls closure
3649 * @param key current key code
3650 * @param value value in the hash map
3651 * @return GNUNET_YES if we should continue to
3656 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
3658 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3660 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3665 * Task to send a find peer message for our own peer identifier
3666 * so that we can find the closest peers in the network to ourselves
3667 * and attempt to connect to them.
3669 * @param cls closure for this task
3670 * @param tc the context under which the task is running
3673 send_find_peer_message (void *cls,
3674 const struct GNUNET_SCHEDULER_TaskContext *tc)
3676 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3677 struct DHT_MessageContext msg_ctx;
3678 struct GNUNET_TIME_Relative next_send_time;
3679 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3681 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
3684 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! */
3686 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3687 "Have %d newly found peers since last find peer message sent!\n",
3689 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
3690 &send_find_peer_message, NULL);
3691 newly_found_peers = 0;
3695 increment_stats (STAT_FIND_PEER_START);
3696 #if FIND_PEER_WITH_HELLO
3698 GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage) +
3699 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *)
3701 find_peer_msg->header.size =
3702 htons (sizeof (struct GNUNET_DHT_FindPeerMessage) +
3703 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
3704 memcpy (&find_peer_msg[1], my_hello,
3705 GNUNET_HELLO_size ((struct GNUNET_HELLO_Message *) my_hello));
3707 find_peer_msg = GNUNET_malloc (sizeof (struct GNUNET_DHT_FindPeerMessage));
3708 find_peer_msg->header.size =
3709 htons (sizeof (struct GNUNET_DHT_FindPeerMessage));
3711 find_peer_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3713 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3714 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
3716 GNUNET_assert (GNUNET_OK ==
3717 GNUNET_CONTAINER_bloomfilter_get_raw_data (temp_bloom,
3721 GNUNET_CONTAINER_bloomfilter_free (temp_bloom);
3722 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3723 memcpy (&msg_ctx.key, &my_identity.hashPubKey, sizeof (GNUNET_HashCode));
3725 GNUNET_ntohll (GNUNET_CRYPTO_random_u64
3726 (GNUNET_CRYPTO_QUALITY_STRONG, UINT64_MAX));
3727 msg_ctx.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3728 msg_ctx.msg_options = GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE;
3729 msg_ctx.network_size = log_of_network_size_estimate;
3730 msg_ctx.peer = &my_identity;
3731 msg_ctx.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3732 msg_ctx.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3734 demultiplex_message (&find_peer_msg->header, &msg_ctx);
3735 GNUNET_free (find_peer_msg);
3736 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3737 "`%s:%s': Sent `%s' request to some (?) peers\n", my_short_id,
3738 "DHT", "FIND PEER");
3739 if (newly_found_peers < bucket_size)
3741 next_send_time.rel_value =
3742 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2) +
3743 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
3744 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / 2);
3748 next_send_time.rel_value =
3749 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
3750 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
3751 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value -
3752 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
3755 GNUNET_assert (next_send_time.rel_value != 0);
3756 find_peer_context.count = 0;
3757 newly_found_peers = 0;
3758 find_peer_context.start = GNUNET_TIME_absolute_get ();
3759 if (GNUNET_YES == do_find_peer)
3761 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
3767 * Handler for any generic DHT messages, calls the appropriate handler
3768 * depending on message type, sends confirmation if responses aren't otherwise
3771 * @param cls closure for the service
3772 * @param client the client we received this message from
3773 * @param message the actual message received
3776 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3777 const struct GNUNET_MessageHeader *message)
3779 const struct GNUNET_DHT_RouteMessage *dht_msg =
3780 (const struct GNUNET_DHT_RouteMessage *) message;
3781 const struct GNUNET_MessageHeader *enc_msg;
3782 struct DHT_MessageContext msg_ctx;
3784 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3786 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3787 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3788 my_short_id, "DHT", "GENERIC", ntohs (message->type),
3789 GNUNET_h2s (&dht_msg->key), GNUNET_ntohll (dht_msg->unique_id));
3791 #if DEBUG_DHT_ROUTING
3792 if (dhtlog_handle != NULL)
3793 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3796 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
3797 msg_ctx.client = find_active_client (client);
3798 memcpy (&msg_ctx.key, &dht_msg->key, sizeof (GNUNET_HashCode));
3799 msg_ctx.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3800 msg_ctx.replication = ntohl (dht_msg->desired_replication_level);
3801 msg_ctx.msg_options = ntohl (dht_msg->options);
3802 if (GNUNET_DHT_RO_RECORD_ROUTE ==
3803 (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
3805 msg_ctx.path_history = GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity));
3806 memcpy (msg_ctx.path_history, &my_identity,
3807 sizeof (struct GNUNET_PeerIdentity));
3808 msg_ctx.path_history_len = 1;
3810 msg_ctx.network_size = log_of_network_size_estimate;
3811 msg_ctx.peer = &my_identity; /* FIXME bart NULL? Fix doxygen? */
3812 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 4; /* Make local routing a higher priority */
3813 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3815 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3816 increment_stats (STAT_GET_START);
3817 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3818 increment_stats (STAT_PUT_START);
3819 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3820 increment_stats (STAT_FIND_PEER_START);
3822 if (GNUNET_YES == malicious_dropper)
3824 if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3826 #if DEBUG_DHT_ROUTING
3827 if ((debug_routes) && (dhtlog_handle != NULL))
3829 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_GET,
3830 msg_ctx.hop_count, GNUNET_NO, &my_identity,
3835 else if (ntohs (enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3837 #if DEBUG_DHT_ROUTING
3838 if ((debug_routes) && (dhtlog_handle != NULL))
3840 dhtlog_handle->insert_query (NULL, msg_ctx.unique_id, DHTLOG_PUT,
3841 msg_ctx.hop_count, GNUNET_NO, &my_identity,
3846 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3847 GNUNET_free_non_null (msg_ctx.path_history);
3851 demultiplex_message (enc_msg, &msg_ctx);
3852 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3857 * Handler for any locally received DHT control messages,
3858 * sets malicious flags mostly for now.
3860 * @param cls closure for the service
3861 * @param client the client we received this message from
3862 * @param message the actual message received
3866 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3867 const struct GNUNET_MessageHeader *message)
3869 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3870 (const struct GNUNET_DHT_ControlMessage *) message;
3873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3874 "`%s:%s': Received `%s' request from client, command %d\n",
3875 my_short_id, "DHT", "CONTROL", ntohs (dht_control_msg->command));
3878 switch (ntohs (dht_control_msg->command))
3880 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3881 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3882 "Sending self seeking find peer request!\n");
3883 GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
3886 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3887 if (ntohs (dht_control_msg->variable) > 0)
3888 malicious_get_frequency.rel_value = ntohs (dht_control_msg->variable);
3889 if (malicious_get_frequency.rel_value == 0)
3890 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3891 if (malicious_getter != GNUNET_YES)
3892 GNUNET_SCHEDULER_add_now (&malicious_get_task, NULL);
3893 malicious_getter = GNUNET_YES;
3894 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3895 "%s:%s Initiating malicious GET behavior, frequency %llu\n",
3896 my_short_id, "DHT", malicious_get_frequency.rel_value);
3898 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3899 if (ntohs (dht_control_msg->variable) > 0)
3900 malicious_put_frequency.rel_value = ntohs (dht_control_msg->variable);
3901 if (malicious_put_frequency.rel_value == 0)
3902 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3903 if (malicious_putter != GNUNET_YES)
3904 GNUNET_SCHEDULER_add_now (&malicious_put_task, NULL);
3905 malicious_putter = GNUNET_YES;
3906 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3907 "%s:%s Initiating malicious PUT behavior, frequency %d\n",
3908 my_short_id, "DHT", malicious_put_frequency);
3910 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3911 #if DEBUG_DHT_ROUTING
3912 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3913 dhtlog_handle->set_malicious (&my_identity);
3915 malicious_dropper = GNUNET_YES;
3916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3917 "%s:%s Initiating malicious DROP behavior\n", my_short_id,
3922 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3923 "%s:%s Unknown control command type `%d'!\n", my_short_id,
3924 "DHT", ntohs (dht_control_msg->command));
3928 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3932 * Handler for any generic DHT stop messages, calls the appropriate handler
3933 * depending on message type (if processed locally)
3935 * @param cls closure for the service
3936 * @param client the client we received this message from
3937 * @param message the actual message received
3941 handle_dht_local_route_stop (void *cls, struct GNUNET_SERVER_Client *client,
3942 const struct GNUNET_MessageHeader *message)
3945 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3946 (const struct GNUNET_DHT_StopMessage *) message;
3947 struct DHTQueryRecord *record;
3948 struct DHTRouteSource *pos;
3951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3952 "`%s:%s': Received `%s' request from client, uid %llu\n",
3953 my_short_id, "DHT", "GENERIC STOP",
3954 GNUNET_ntohll (dht_stop_msg->unique_id));
3957 GNUNET_CONTAINER_multihashmap_get (forward_list.hashmap,
3958 &dht_stop_msg->key);
3965 /* If the client is non-null (local request) and the client matches the requesting client, remove the entry. */
3966 if ((pos->client != NULL) && (pos->client->client_handle == client))
3968 if (pos->delete_task != GNUNET_SCHEDULER_NO_TASK)
3969 GNUNET_SCHEDULER_cancel (pos->delete_task);
3971 GNUNET_SCHEDULER_add_now (&remove_forward_entry, pos);
3977 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3982 * Core handler for p2p route requests.
3984 * @param cls closure
3985 * @param message message
3986 * @param peer peer identity this notification is about
3987 * @param atsi performance data
3988 * @return GNUNET_OK to keep the connection open,
3989 * GNUNET_SYSERR to close it (signal serious error)
3992 handle_dht_p2p_route_request (void *cls, const struct GNUNET_PeerIdentity *peer,
3993 const struct GNUNET_MessageHeader *message,
3994 const struct GNUNET_TRANSPORT_ATS_Information
3998 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3999 "`%s:%s': Received P2P request from peer %s\n", my_short_id,
4000 "DHT", GNUNET_i2s (peer));
4002 struct GNUNET_DHT_P2PRouteMessage *incoming =
4003 (struct GNUNET_DHT_P2PRouteMessage *) message;
4004 struct GNUNET_MessageHeader *enc_msg =
4005 (struct GNUNET_MessageHeader *) &incoming[1];
4006 struct DHT_MessageContext *msg_ctx;
4010 if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4012 GNUNET_break_op (0);
4016 if (malicious_dropper == GNUNET_YES)
4018 #if DEBUG_DHT_ROUTING
4019 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4021 /** Log routes that die due to high load! */
4022 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4023 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4024 GNUNET_SYSERR, &my_identity, &incoming->key,
4031 if (get_max_send_delay ().rel_value > MAX_REQUEST_TIME.rel_value)
4033 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4034 "Sending of previous replies took too long, backing off!\n");
4035 increment_stats ("# route requests dropped due to high load");
4036 decrease_max_send_delay (get_max_send_delay ());
4037 #if DEBUG_DHT_ROUTING
4038 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4040 /** Log routes that die due to high load! */
4041 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4042 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4043 GNUNET_SYSERR, &my_identity, &incoming->key,
4049 msg_ctx = GNUNET_malloc (sizeof (struct DHT_MessageContext));
4051 GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4053 GNUNET_assert (msg_ctx->bloom != NULL);
4054 msg_ctx->hop_count = ntohl (incoming->hop_count);
4055 memcpy (&msg_ctx->key, &incoming->key, sizeof (GNUNET_HashCode));
4056 msg_ctx->replication = ntohl (incoming->desired_replication_level);
4057 msg_ctx->unique_id = GNUNET_ntohll (incoming->unique_id);
4058 msg_ctx->msg_options = ntohl (incoming->options);
4059 if (GNUNET_DHT_RO_RECORD_ROUTE ==
4060 (msg_ctx->msg_options & GNUNET_DHT_RO_RECORD_ROUTE))
4063 ntohl (incoming->outgoing_path_length) *
4064 sizeof (struct GNUNET_PeerIdentity);
4065 if (ntohs (message->size) !=
4066 (sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs (enc_msg->size) +
4069 GNUNET_break_op (0);
4072 route_path = (char *) &incoming[1];
4073 route_path = route_path + ntohs (enc_msg->size);
4074 msg_ctx->path_history =
4075 GNUNET_malloc (sizeof (struct GNUNET_PeerIdentity) + path_size);
4076 memcpy (msg_ctx->path_history, route_path, path_size);
4077 memcpy (&msg_ctx->path_history[path_size], &my_identity,
4078 sizeof (struct GNUNET_PeerIdentity));
4079 msg_ctx->path_history_len = ntohl (incoming->outgoing_path_length) + 1;
4081 msg_ctx->network_size = ntohl (incoming->network_size);
4082 msg_ctx->peer = peer;
4083 msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
4084 msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
4085 demultiplex_message (enc_msg, msg_ctx);
4086 if (msg_ctx->bloom != NULL)
4088 GNUNET_CONTAINER_bloomfilter_free (msg_ctx->bloom);
4089 msg_ctx->bloom = NULL;
4091 GNUNET_free (msg_ctx);
4097 * Core handler for p2p route results.
4099 * @param cls closure
4100 * @param message message
4101 * @param peer peer identity this notification is about
4102 * @param atsi performance data
4106 handle_dht_p2p_route_result (void *cls, const struct GNUNET_PeerIdentity *peer,
4107 const struct GNUNET_MessageHeader *message,
4108 const struct GNUNET_TRANSPORT_ATS_Information
4112 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4113 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT",
4116 const struct GNUNET_DHT_P2PRouteResultMessage *incoming =
4117 (const struct GNUNET_DHT_P2PRouteResultMessage *) message;
4118 struct GNUNET_MessageHeader *enc_msg =
4119 (struct GNUNET_MessageHeader *) &incoming[1];
4120 struct DHT_MessageContext msg_ctx;
4126 if (ntohs (enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
4128 GNUNET_break_op (0);
4132 if (malicious_dropper == GNUNET_YES)
4134 #if DEBUG_DHT_ROUTING
4135 if ((debug_routes_extended) && (dhtlog_handle != NULL))
4137 /** Log routes that die due to high load! */
4138 dhtlog_handle->insert_route (NULL, GNUNET_ntohll (incoming->unique_id),
4139 DHTLOG_ROUTE, ntohl (incoming->hop_count),
4140 GNUNET_SYSERR, &my_identity, &incoming->key,
4147 memset (&msg_ctx, 0, sizeof (struct DHT_MessageContext));
4148 memcpy (&msg_ctx.key, &incoming->key, sizeof (GNUNET_HashCode));
4149 msg_ctx.unique_id = GNUNET_ntohll (incoming->unique_id);
4150 msg_ctx.msg_options = ntohl (incoming->options);
4151 msg_ctx.hop_count = ntohl (incoming->hop_count);
4152 msg_ctx.peer = peer;
4153 msg_ctx.importance = DHT_DEFAULT_P2P_IMPORTANCE + 2; /* Make result routing a higher priority */
4154 msg_ctx.timeout = DHT_DEFAULT_P2P_TIMEOUT;
4155 if ((GNUNET_DHT_RO_RECORD_ROUTE ==
4156 (msg_ctx.msg_options & GNUNET_DHT_RO_RECORD_ROUTE)) &&
4157 (ntohl (incoming->outgoing_path_length) > 0))
4159 if (ntohs (message->size) -
4160 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) -
4161 ntohs (enc_msg->size) !=
4162 ntohl (incoming->outgoing_path_length) *
4163 sizeof (struct GNUNET_PeerIdentity))
4166 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4167 "Return message indicated a path was included, but sizes are wrong: Total size %d, enc size %d, left %d, expected %d\n",
4168 ntohs (message->size), ntohs (enc_msg->size),
4169 ntohs (message->size) -
4170 sizeof (struct GNUNET_DHT_P2PRouteResultMessage) -
4171 ntohs (enc_msg->size),
4172 ntohl (incoming->outgoing_path_length) *
4173 sizeof (struct GNUNET_PeerIdentity));
4175 GNUNET_break_op (0);
4178 msg_ctx.path_history = (char *) &incoming[1];
4179 msg_ctx.path_history += ntohs (enc_msg->size);
4180 msg_ctx.path_history_len = ntohl (incoming->outgoing_path_length);
4182 for (i = 0; i < msg_ctx.path_history_len; i++)
4185 &msg_ctx.path_history[i * sizeof (struct GNUNET_PeerIdentity)];
4186 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4187 "(handle_p2p_route_result) Key %s Found peer %d:%s\n",
4188 GNUNET_h2s (&msg_ctx.key), i,
4189 GNUNET_i2s ((struct GNUNET_PeerIdentity *) path_offset));
4194 GNUNET_CONTAINER_bloomfilter_init (incoming->bloomfilter, DHT_BLOOM_SIZE,
4196 GNUNET_assert (msg_ctx.bloom != NULL);
4197 route_result_message (enc_msg, &msg_ctx);
4203 * Receive the HELLO from transport service,
4204 * free current and replace if necessary.
4207 * @param message HELLO message of peer
4210 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
4213 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4214 "Received our `%s' from transport service\n", "HELLO");
4217 GNUNET_assert (message != NULL);
4218 GNUNET_free_non_null (my_hello);
4219 my_hello = GNUNET_malloc (ntohs (message->size));
4220 memcpy (my_hello, message, ntohs (message->size));
4225 * Task run during shutdown.
4231 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
4234 struct PeerInfo *pos;
4238 GNUNET_TRANSPORT_get_hello_cancel (ghh);
4241 if (transport_handle != NULL)
4243 GNUNET_free_non_null (my_hello);
4244 GNUNET_TRANSPORT_disconnect (transport_handle);
4245 transport_handle = NULL;
4249 GNUNET_NSE_disconnect (nse);
4252 if (coreAPI != NULL)
4255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Disconnecting core!\n",
4256 my_short_id, "DHT");
4258 GNUNET_CORE_disconnect (coreAPI);
4261 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
4263 while (k_buckets[bucket_count].head != NULL)
4265 pos = k_buckets[bucket_count].head;
4267 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4268 "%s:%s Removing peer %s from bucket %d!\n", my_short_id,
4269 "DHT", GNUNET_i2s (&pos->id), bucket_count);
4271 delete_peer (pos, bucket_count);
4274 if (datacache != NULL)
4277 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Destroying datacache!\n",
4278 my_short_id, "DHT");
4280 GNUNET_DATACACHE_destroy (datacache);
4285 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
4288 if (dhtlog_handle != NULL)
4290 GNUNET_DHTLOG_disconnect (dhtlog_handle);
4291 dhtlog_handle = NULL;
4293 if (block_context != NULL)
4295 GNUNET_BLOCK_context_destroy (block_context);
4296 block_context = NULL;
4298 GNUNET_free_non_null (my_short_id);
4304 * To be called on core init/fail.
4306 * @param cls service closure
4307 * @param server handle to the server for this service
4308 * @param identity the public identity of this peer
4309 * @param publicKey the public key of this peer
4312 core_init (void *cls, struct GNUNET_CORE_Handle *server,
4313 const struct GNUNET_PeerIdentity *identity,
4314 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4320 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s: Connection to core FAILED!\n",
4321 "dht", GNUNET_i2s (identity));
4323 GNUNET_SCHEDULER_cancel (cleanup_task);
4324 GNUNET_SCHEDULER_add_now (&shutdown_task, NULL);
4328 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4329 "%s: Core connection initialized, I am peer: %s\n", "dht",
4330 GNUNET_i2s (identity));
4333 /* Copy our identity so we can use it */
4334 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4335 if (my_short_id != NULL)
4336 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4337 "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n",
4339 my_short_id = GNUNET_strdup (GNUNET_i2s (&my_identity));
4340 if (dhtlog_handle != NULL)
4341 dhtlog_handle->insert_node (NULL, &my_identity);
4345 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4346 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE,
4348 {&handle_dht_local_route_stop, NULL,
4349 GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4350 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4355 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4356 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4357 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4363 * Method called whenever a peer connects.
4365 * @param cls closure
4366 * @param peer peer identity this notification is about
4367 * @param atsi performance data
4370 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
4371 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
4373 struct PeerInfo *ret;
4374 struct DHTPutEntry *put_entry;
4377 /* Check for connect to self message */
4378 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
4382 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4383 "%s:%s Receives core connect message for peer %s distance %d!\n",
4384 my_short_id, "dht", GNUNET_i2s (peer), distance);
4388 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
4392 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4393 "%s:%s Received %s message for peer %s, but already have peer in RT!",
4394 my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s (peer));
4400 if ((datacache != NULL) && (GNUNET_YES == put_peer_identities))
4403 GNUNET_malloc (sizeof (struct DHTPutEntry) +
4404 sizeof (struct GNUNET_PeerIdentity));
4405 put_entry->path_length = 0;
4406 put_entry->data_size = sizeof (struct GNUNET_PeerIdentity);
4407 memcpy (&put_entry[1], peer, sizeof (struct GNUNET_PeerIdentity));
4408 GNUNET_DATACACHE_put (datacache, &peer->hashPubKey,
4409 sizeof (struct DHTPutEntry) +
4410 sizeof (struct GNUNET_PeerIdentity),
4411 (char *) put_entry, GNUNET_BLOCK_TYPE_DHT_HELLO,
4412 GNUNET_TIME_absolute_get_forever ());
4413 GNUNET_free (put_entry);
4415 else if (datacache == NULL)
4416 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4417 "DHT has no connection to datacache!\n");
4419 peer_bucket = find_current_bucket (&peer->hashPubKey);
4420 GNUNET_assert (peer_bucket >= lowest_bucket);
4421 GNUNET_assert (peer_bucket < MAX_BUCKETS);
4422 ret = GNUNET_malloc (sizeof (struct PeerInfo));
4424 ret->latency = latency;
4425 ret->distance = distance;
4428 GNUNET_CONTAINER_DLL_insert_after (k_buckets[peer_bucket].head,
4429 k_buckets[peer_bucket].tail,
4430 k_buckets[peer_bucket].tail, ret);
4431 k_buckets[peer_bucket].peers_size++;
4432 #if DO_UPDATE_PREFERENCE
4433 if ((GNUNET_CRYPTO_hash_matching_bits
4434 (&my_identity.hashPubKey, &peer->hashPubKey) > 0) &&
4435 (k_buckets[peer_bucket].peers_size <= bucket_size))
4436 ret->preference_task =
4437 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
4439 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
4440 enable_next_bucket ();
4441 newly_found_peers++;
4442 GNUNET_CONTAINER_multihashmap_put (all_known_peers, &peer->hashPubKey, ret,
4443 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4444 increment_stats (STAT_PEERS_KNOWN);
4447 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4448 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT",
4449 ret == NULL ? "NOT ADDED" : "PEER ADDED");
4455 * Method called whenever a peer disconnects.
4457 * @param cls closure
4458 * @param peer peer identity this notification is about
4461 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
4463 struct PeerInfo *to_remove;
4466 /* Check for disconnect from self message */
4467 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
4470 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4471 "%s:%s: Received peer disconnect message for peer `%s' from %s\n",
4472 my_short_id, "DHT", GNUNET_i2s (peer), "CORE");
4476 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
4481 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4482 "%s:%s: do not have peer `%s' in RT, can't disconnect!\n",
4483 my_short_id, "DHT", GNUNET_i2s (peer));
4487 increment_stats (STAT_DISCONNECTS);
4488 GNUNET_assert (GNUNET_CONTAINER_multihashmap_contains
4489 (all_known_peers, &peer->hashPubKey));
4491 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
4492 GNUNET_assert (to_remove != NULL);
4493 if (NULL != to_remove->info_ctx)
4495 GNUNET_CORE_peer_change_preference_cancel (to_remove->info_ctx);
4496 to_remove->info_ctx = NULL;
4499 memcmp (peer, &to_remove->id,
4500 sizeof (struct GNUNET_PeerIdentity)));
4501 current_bucket = find_current_bucket (&to_remove->id.hashPubKey);
4502 delete_peer (to_remove, current_bucket);
4507 * Process dht requests.
4509 * @param cls closure
4510 * @param server the initialized server
4511 * @param c configuration to use
4514 run (void *cls, struct GNUNET_SERVER_Handle *server,
4515 const struct GNUNET_CONFIGURATION_Handle *c)
4517 struct GNUNET_TIME_Relative next_send_time;
4518 unsigned long long temp_config_num;
4521 datacache = GNUNET_DATACACHE_create (cfg, "dhtcache");
4522 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4523 GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
4524 nse = GNUNET_NSE_connect (cfg, &update_network_size_estimate, NULL);
4525 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
4526 DEFAULT_CORE_QUEUE_SIZE, /* queue size */
4527 NULL, /* Closure passed to DHT functions */
4528 &core_init, /* Call core_init once connected */
4529 &handle_core_connect, /* Handle connects */
4530 &handle_core_disconnect, /* remove peers on disconnects */
4531 NULL, /* Do we care about "status" updates? */
4532 NULL, /* Don't want notified about all incoming messages */
4533 GNUNET_NO, /* For header only inbound notification */
4534 NULL, /* Don't want notified about all outbound messages */
4535 GNUNET_NO, /* For header only outbound notification */
4536 core_handlers); /* Register these handlers */
4538 if (coreAPI == NULL)
4541 GNUNET_TRANSPORT_connect (cfg, NULL, NULL, NULL, NULL, NULL);
4542 if (transport_handle != NULL)
4543 ghh = GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4545 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4546 "Failed to connect to transport service!\n");
4547 block_context = GNUNET_BLOCK_context_create (cfg);
4548 lowest_bucket = MAX_BUCKETS - 1;
4549 forward_list.hashmap =
4550 GNUNET_CONTAINER_multihashmap_create (MAX_OUTSTANDING_FORWARDS / 10);
4551 forward_list.minHeap =
4552 GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4553 all_known_peers = GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
4554 GNUNET_assert (all_known_peers != NULL);
4556 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
4559 debug_routes = GNUNET_YES;
4563 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "strict_kademlia"))
4565 strict_kademlia = GNUNET_YES;
4569 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_on_closest"))
4571 stop_on_closest = GNUNET_YES;
4575 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "stop_found"))
4577 stop_on_found = GNUNET_YES;
4581 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_getter"))
4583 malicious_getter = GNUNET_YES;
4585 GNUNET_CONFIGURATION_get_value_time (cfg, "DHT",
4586 "MALICIOUS_GET_FREQUENCY",
4587 &malicious_get_frequency))
4588 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4592 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_putter"))
4594 malicious_putter = GNUNET_YES;
4596 GNUNET_CONFIGURATION_get_value_time (cfg, "DHT",
4597 "MALICIOUS_PUT_FREQUENCY",
4598 &malicious_put_frequency))
4599 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4603 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "bucket_size",
4606 bucket_size = (unsigned int) temp_config_num;
4610 GNUNET_CONFIGURATION_get_value_number (cfg, "DHT", "kad_alpha",
4611 &kademlia_replication))
4613 kademlia_replication = DEFAULT_KADEMLIA_REPLICATION;
4617 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "malicious_dropper"))
4619 malicious_dropper = GNUNET_YES;
4623 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "do_find_peer"))
4625 do_find_peer = GNUNET_NO;
4628 do_find_peer = GNUNET_YES;
4631 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "use_real_distance"))
4632 use_real_distance = GNUNET_YES;
4635 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht_testing",
4636 "mysql_logging_extended"))
4638 debug_routes = GNUNET_YES;
4639 debug_routes_extended = GNUNET_YES;
4642 #if DEBUG_DHT_ROUTING
4643 if (GNUNET_YES == debug_routes)
4645 dhtlog_handle = GNUNET_DHTLOG_connect (cfg);
4646 if (dhtlog_handle == NULL)
4648 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4649 "Could not connect to mysql logging server, logging will not happen!");
4655 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "paper_forwarding"))
4656 paper_forwarding = GNUNET_YES;
4659 GNUNET_CONFIGURATION_get_value_yesno (cfg, "dht", "put_peer_identities"))
4660 put_peer_identities = GNUNET_YES;
4662 stats = GNUNET_STATISTICS_create ("dht", cfg);
4666 GNUNET_STATISTICS_set (stats, STAT_ROUTES, 0, GNUNET_NO);
4667 GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4668 GNUNET_STATISTICS_set (stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4669 GNUNET_STATISTICS_set (stats, STAT_RESULTS, 0, GNUNET_NO);
4670 GNUNET_STATISTICS_set (stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4671 GNUNET_STATISTICS_set (stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4672 GNUNET_STATISTICS_set (stats, STAT_GETS, 0, GNUNET_NO);
4673 GNUNET_STATISTICS_set (stats, STAT_PUTS, 0, GNUNET_NO);
4674 GNUNET_STATISTICS_set (stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4675 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER, 0, GNUNET_NO);
4676 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4677 GNUNET_STATISTICS_set (stats, STAT_GET_START, 0, GNUNET_NO);
4678 GNUNET_STATISTICS_set (stats, STAT_PUT_START, 0, GNUNET_NO);
4679 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4680 GNUNET_STATISTICS_set (stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4681 GNUNET_STATISTICS_set (stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4682 GNUNET_STATISTICS_set (stats, STAT_GET_REPLY, 0, GNUNET_NO);
4683 GNUNET_STATISTICS_set (stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4684 GNUNET_STATISTICS_set (stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4685 GNUNET_STATISTICS_set (stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4687 if (GNUNET_YES == do_find_peer)
4689 next_send_time.rel_value =
4690 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
4691 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
4692 (DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value /
4694 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value);
4695 find_peer_context.start = GNUNET_TIME_absolute_get ();
4696 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
4697 &find_peer_context);
4700 /* Scheduled the task to clean up when shutdown is called */
4702 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
4703 &shutdown_task, NULL);
4708 * The main function for the dht service.
4710 * @param argc number of arguments from the command line
4711 * @param argv command line arguments
4712 * @return 0 ok, 1 on error
4715 main (int argc, char *const *argv)
4719 recent.hashmap = GNUNET_CONTAINER_multihashmap_create (DHT_MAX_RECENT / 2);
4721 GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN);
4722 recent_find_peer_requests =
4723 GNUNET_CONTAINER_multihashmap_create (MAX_BUCKETS / 8);
4726 GNUNET_SERVICE_run (argc, argv, "dht", GNUNET_SERVICE_OPTION_NONE, &run,
4728 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (recent.hashmap));
4729 GNUNET_CONTAINER_multihashmap_destroy (recent.hashmap);
4730 recent.hashmap = NULL;
4731 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (recent.minHeap));
4732 GNUNET_CONTAINER_heap_destroy (recent.minHeap);
4733 recent.minHeap = NULL;
4734 GNUNET_CONTAINER_multihashmap_destroy (recent_find_peer_requests);
4735 recent_find_peer_requests = NULL;
4739 /* end of gnunet-service-dht.c */