2 This file is part of GNUnet.
3 (C) 2009, 2010 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file dht/gnunet-service-dht.c
23 * @brief main DHT service shell, building block for DHT implementations
24 * @author Christian Grothoff
25 * @author Nathan Evans
29 #include "gnunet_client_lib.h"
30 #include "gnunet_getopt_lib.h"
31 #include "gnunet_os_lib.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_service_lib.h"
34 #include "gnunet_core_service.h"
35 #include "gnunet_signal_lib.h"
36 #include "gnunet_util_lib.h"
37 #include "gnunet_datacache_lib.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_hello_lib.h"
40 #include "gnunet_dht_service.h"
41 #include "gnunet_statistics_service.h"
45 #define PRINT_TABLES GNUNET_NO
47 #define REAL_DISTANCE GNUNET_NO
49 #define EXTRA_CHECKS GNUNET_NO
51 * How many buckets will we allow total.
53 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
56 * Should the DHT issue FIND_PEER requests to get better routing tables?
58 #define DEFAULT_DO_FIND_PEER GNUNET_YES
61 * Defines whether find peer requests send their HELLO's outgoing,
62 * or expect replies to contain hellos.
64 #define FIND_PEER_WITH_HELLO GNUNET_YES
67 * What is the maximum number of peers in a given bucket.
69 #define DEFAULT_BUCKET_SIZE 4
72 * Minimum number of peers we need for "good" routing,
73 * any less than this and we will allow messages to
74 * travel much further through the network!
76 #define MINIMUM_PEER_THRESHOLD 20
78 #define DHT_MAX_RECENT 1000
80 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
83 * Default time to wait to send messages on behalf of other peers.
85 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
88 * Default importance for handling messages on behalf of other peers.
90 #define DHT_DEFAULT_P2P_IMPORTANCE 0
93 * How long to keep recent requests around by default.
95 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
98 * Default time to wait to send find peer messages sent by the dht service.
100 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
103 * Default importance for find peer messages sent by the dht service.
105 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
108 * Default replication parameter for find peer messages sent by the dht service.
110 #define DHT_DEFAULT_PUT_REPLICATION 4
113 * Default replication parameter for find peer messages sent by the dht service.
115 #define DHT_DEFAULT_FIND_PEER_REPLICATION 4
118 * Default options for find peer requests sent by the dht service.
120 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
121 /*#define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE*/
124 * How long at least to wait before sending another find peer request.
126 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
129 * How long at most to wait before sending another find peer request.
131 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
134 * How often to update our preference levels for peers in our routing tables.
136 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
139 * How long at most on average will we allow a reply forward to take
140 * (before we quit sending out new requests)
142 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
145 * How many initial requests to send out (in true Kademlia fashion)
147 #define DHT_KADEMLIA_REPLICATION 3
150 * Default frequency for sending malicious get messages
152 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
155 * Default frequency for sending malicious put messages
157 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
160 * Type for a malicious request, so we can ignore it during testing
162 #define DHT_MALICIOUS_MESSAGE_TYPE 42
164 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
167 * Real maximum number of hops, at which point we refuse
168 * to forward the message.
170 #define DEFAULT_MAX_HOPS 10
173 * How many time differences between requesting a core send and
174 * the actual callback to remember.
176 #define MAX_REPLY_TIMES 8
178 enum ConvergenceOptions
181 * Use the linear method for convergence.
186 * Converge using a fast converging square
192 * Converge using a slower exponential
195 DHT_CONVERGE_EXPONENTIAL,
198 * Don't do any special convergence, allow
199 * the algorithm to hopefully route to closer
206 * Linked list of messages to send to clients.
208 struct P2PPendingMessage
211 * Pointer to next item in the list
213 struct P2PPendingMessage *next;
216 * Pointer to previous item in the list
218 struct P2PPendingMessage *prev;
221 * Message importance level.
223 unsigned int importance;
226 * Time when this request was scheduled to be sent.
228 struct GNUNET_TIME_Absolute scheduled;
231 * How long to wait before sending message.
233 struct GNUNET_TIME_Relative timeout;
236 * Actual message to be sent; // avoid allocation
238 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
243 * Per-peer information.
248 * Next peer entry (DLL)
250 struct PeerInfo *next;
253 * Prev peer entry (DLL)
255 struct PeerInfo *prev;
258 * Head of pending messages to be sent to this peer.
260 struct P2PPendingMessage *head;
263 * Tail of pending messages to be sent to this peer.
265 struct P2PPendingMessage *tail;
268 * Core handle for sending messages to this peer.
270 struct GNUNET_CORE_TransmitHandle *th;
273 * Task for scheduling message sends.
275 GNUNET_SCHEDULER_TaskIdentifier send_task;
278 * Task for scheduling preference updates
280 GNUNET_SCHEDULER_TaskIdentifier preference_task;
283 * Preference update context
285 struct GNUNET_CORE_InformationRequestContext *info_ctx;
288 * What is the average latency for replies received?
290 struct GNUNET_TIME_Relative latency;
293 * What is the identity of the peer?
295 struct GNUNET_PeerIdentity id;
298 * Transport level distance to peer.
300 unsigned int distance;
303 * Task for scheduling periodic ping messages for this peer.
305 GNUNET_SCHEDULER_TaskIdentifier ping_task;
309 * Peers are grouped into buckets.
316 struct PeerInfo *head;
321 struct PeerInfo *tail;
324 * Number of peers in the bucket.
326 unsigned int peers_size;
330 * Linked list of messages to send to clients.
332 struct PendingMessage
335 * Pointer to next item in the list
337 struct PendingMessage *next;
340 * Pointer to previous item in the list
342 struct PendingMessage *prev;
345 * Actual message to be sent; // avoid allocation
347 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
352 * Struct containing information about a client,
353 * handle to connect to it, and any pending messages
354 * that need to be sent to it.
359 * Linked list of active clients
361 struct ClientList *next;
364 * The handle to this client
366 struct GNUNET_SERVER_Client *client_handle;
369 * Handle to the current transmission request, NULL
372 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
375 * Linked list of pending messages for this client
377 struct PendingMessage *pending_head;
380 * Tail of linked list of pending messages for this client
382 struct PendingMessage *pending_tail;
387 * Context containing information about a DHT message received.
389 struct DHT_MessageContext
392 * The client this request was received from.
393 * (NULL if received from another peer)
395 struct ClientList *client;
398 * The peer this request was received from.
399 * (NULL if received from local client)
401 const struct GNUNET_PeerIdentity *peer;
404 * The key this request was about
409 * The unique identifier of this request
414 * Desired replication level
416 uint32_t replication;
419 * Network size estimate, either ours or the sum of
420 * those routed to thus far. =~ Log of number of peers
421 * chosen from for this request.
423 uint32_t network_size;
426 * Any message options for this request
428 uint32_t msg_options;
431 * How many hops has the message already traversed?
436 * How important is this message?
438 unsigned int importance;
441 * How long should we wait to transmit this request?
443 struct GNUNET_TIME_Relative timeout;
446 * Bloomfilter for this routing request.
448 struct GNUNET_CONTAINER_BloomFilter *bloom;
451 * Did we forward this message? (may need to remember it!)
456 * Are we the closest known peer to this key (out of our neighbors?)
462 * Record used for remembering what peers are waiting for what
463 * responses (based on search key).
465 struct DHTRouteSource
470 struct DHTRouteSource *next;
475 struct DHTRouteSource *prev;
478 * Source of the request. Replies should be forwarded to
481 struct GNUNET_PeerIdentity source;
484 * If this was a local request, remember the client; otherwise NULL.
486 struct ClientList *client;
489 * Pointer to this nodes heap location (for removal)
491 struct GNUNET_CONTAINER_HeapNode *hnode;
494 * Back pointer to the record storing this information.
496 struct DHTQueryRecord *record;
499 * Task to remove this entry on timeout.
501 GNUNET_SCHEDULER_TaskIdentifier delete_task;
504 * Bloomfilter of peers we have already sent back as
505 * replies to the initial request. Allows us to not
506 * forward the same peer multiple times for a find peer
509 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
514 * Entry in the DHT routing table.
516 struct DHTQueryRecord
519 * Head of DLL for result forwarding.
521 struct DHTRouteSource *head;
524 * Tail of DLL for result forwarding.
526 struct DHTRouteSource *tail;
529 * Key that the record concerns.
534 * GET message of this record (what we already forwarded?).
536 //DV_DHT_MESSAGE get; Try to get away with not saving this.
539 * Bloomfilter of the peers we've replied to so far
541 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
546 * Context used to calculate the number of find peer messages
547 * per X time units since our last scheduled find peer message
548 * was sent. If we have seen too many messages, delay or don't
551 struct FindPeerMessageContext
555 struct GNUNET_TIME_Absolute start;
557 struct GNUNET_TIME_Absolute end;
561 * DHT Routing results structure
566 * Min heap for removal upon reaching limit
568 struct GNUNET_CONTAINER_Heap *minHeap;
571 * Hashmap for fast key based lookup
573 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
578 * DHT structure for recent requests.
580 struct RecentRequests
583 * Min heap for removal upon reaching limit
585 struct GNUNET_CONTAINER_Heap *minHeap;
588 * Hashmap for key based lookup
590 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
596 * Position of this node in the min heap.
598 struct GNUNET_CONTAINER_HeapNode *heap_node;
601 * Bloomfilter containing entries for peers
602 * we forwarded this request to.
604 struct GNUNET_CONTAINER_BloomFilter *bloom;
607 * Timestamp of this request, for ordering
610 struct GNUNET_TIME_Absolute timestamp;
613 * Key of this request.
618 * Unique identifier for this request.
623 * Task to remove this entry on timeout.
625 GNUNET_SCHEDULER_TaskIdentifier remove_task;
628 struct RepublishContext
643 * Which kind of convergence will we be using?
645 enum ConvergenceOptions converge_option;
648 * Modifier for the convergence function
650 float converge_modifier;
653 * Recent requests by hash/uid and by time inserted.
655 static struct RecentRequests recent;
658 * Context to use to calculate find peer rates.
660 static struct FindPeerMessageContext find_peer_context;
663 * Don't use our routing algorithm, always route
664 * to closest peer; initially send requests to 3
667 static unsigned int strict_kademlia;
670 * Routing option to end routing when closest peer found.
672 static unsigned int stop_on_closest;
675 * Routing option to end routing when data is found.
677 static unsigned int stop_on_found;
680 * Whether DHT needs to manage find peer requests, or
681 * an external force will do it on behalf of the DHT.
683 static unsigned int do_find_peer;
686 * Once we have stored an item in the DHT, refresh it
687 * according to our republish interval.
689 static unsigned int do_republish;
692 * Use the "real" distance metric when selecting the
693 * next routing hop. Can be less accurate.
695 static unsigned int use_real_distance;
698 * How many peers have we added since we sent out our last
701 static unsigned int newly_found_peers;
704 * Container of active queries we should remember
706 static struct DHTResults forward_list;
709 * Handle to the datacache service (for inserting/retrieving data)
711 static struct GNUNET_DATACACHE_Handle *datacache;
714 * Handle for the statistics service.
716 struct GNUNET_STATISTICS_Handle *stats;
719 * The main scheduler to use for the DHT service
721 static struct GNUNET_SCHEDULER_Handle *sched;
724 * The configuration the DHT service is running with
726 static const struct GNUNET_CONFIGURATION_Handle *cfg;
729 * Handle to the core service
731 static struct GNUNET_CORE_Handle *coreAPI;
734 * Handle to the transport service, for getting our hello
736 static struct GNUNET_TRANSPORT_Handle *transport_handle;
739 * The identity of our peer.
741 static struct GNUNET_PeerIdentity my_identity;
744 * Short id of the peer, for printing
746 static char *my_short_id;
751 static struct GNUNET_MessageHeader *my_hello;
754 * Task to run when we shut down, cleaning up all our trash
756 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
759 * The lowest currently used bucket.
761 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
764 * The maximum number of hops before we stop routing messages.
766 static unsigned long long max_hops;
769 * How often to republish content we have previously stored.
771 static struct GNUNET_TIME_Relative dht_republish_frequency;
774 * GNUNET_YES to stop at max_hops, GNUNET_NO to heuristically decide when to stop forwarding.
776 static int use_max_hops;
779 * The buckets (Kademlia routing table, complete with growth).
780 * Array of size MAX_BUCKET_SIZE.
782 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
785 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
787 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
790 * Recently seen find peer requests.
792 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
795 * Maximum size for each bucket.
797 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
800 * List of active clients.
802 static struct ClientList *client_list;
805 * Handle to the DHT logger.
807 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
810 * Whether or not to send routing debugging information
811 * to the dht logging server
813 static unsigned int debug_routes;
816 * Whether or not to send FULL route information to
819 static unsigned int debug_routes_extended;
822 * GNUNET_YES or GNUNET_NO, whether or not to act as
823 * a malicious node which drops all messages
825 static unsigned int malicious_dropper;
828 * GNUNET_YES or GNUNET_NO, whether or not to act as
829 * a malicious node which sends out lots of GETS
831 static unsigned int malicious_getter;
834 * GNUNET_YES or GNUNET_NO, whether or not to act as
835 * a malicious node which sends out lots of PUTS
837 static unsigned int malicious_putter;
840 * Frequency for malicious get requests.
842 static unsigned long long malicious_get_frequency;
845 * Frequency for malicious put requests.
847 static unsigned long long malicious_put_frequency;
850 * Reply times for requests, if we are busy, don't send any
853 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
856 * Current counter for replies.
858 static unsigned int reply_counter;
861 * Forward declaration.
863 static size_t send_generic_reply (void *cls, size_t size, void *buf);
865 /** Declare here so retry_core_send is aware of it */
866 size_t core_transmit_notify (void *cls,
867 size_t size, void *buf);
870 * Convert unique ID to hash code.
872 * @param uid unique ID to convert
873 * @param hash set to uid (extended with zeros)
876 hash_from_uid (uint64_t uid,
877 GNUNET_HashCode *hash)
879 memset (hash, 0, sizeof(GNUNET_HashCode));
880 *((uint64_t*)hash) = uid;
885 * Calculate the average send time between messages so that we can
886 * ignore certain requests if we get too busy.
888 * @return the average time between asking core to send a message
889 * and when the buffer for copying it is passed
891 static struct GNUNET_TIME_Relative get_average_send_delay()
894 unsigned int divisor;
895 struct GNUNET_TIME_Relative average_time;
896 average_time = GNUNET_TIME_relative_get_zero();
898 for (i = 0; i < MAX_REPLY_TIMES; i++)
900 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
901 if (reply_times[i].value == (uint64_t)0)
911 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
912 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
918 * Given the largest send delay, artificially decrease it
919 * so the next time around we may have a chance at sending
922 static void decrease_max_send_delay(struct GNUNET_TIME_Relative max_time)
925 for (i = 0; i < MAX_REPLY_TIMES; i++)
927 if (reply_times[i].value == max_time.value)
929 reply_times[i].value = reply_times[i].value / 2;
936 * Find the maximum send time of the recently sent values.
938 * @return the average time between asking core to send a message
939 * and when the buffer for copying it is passed
941 static struct GNUNET_TIME_Relative get_max_send_delay()
944 struct GNUNET_TIME_Relative max_time;
945 max_time = GNUNET_TIME_relative_get_zero();
947 for (i = 0; i < MAX_REPLY_TIMES; i++)
949 if (reply_times[i].value > max_time.value)
950 max_time.value = reply_times[i].value;
953 if (max_time.value > MAX_REQUEST_TIME.value)
954 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
959 increment_stats(const char *value)
963 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
968 * Try to send another message from our core send list
971 try_core_send (void *cls,
972 const struct GNUNET_SCHEDULER_TaskContext *tc)
974 struct PeerInfo *peer = cls;
975 struct P2PPendingMessage *pending;
978 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
980 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
983 if (peer->th != NULL)
984 return; /* Message send already in progress */
986 pending = peer->head;
989 ssize = ntohs(pending->msg->size);
991 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
992 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
993 "DHT", ssize, GNUNET_i2s(&peer->id));
995 pending->scheduled = GNUNET_TIME_absolute_get();
997 if (reply_counter >= MAX_REPLY_TIMES)
999 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
1000 pending->timeout, &peer->id,
1001 ssize, &core_transmit_notify, peer);
1006 * Function called to send a request out to another peer.
1007 * Called both for locally initiated requests and those
1008 * received from other peers.
1010 * @param cls DHT service closure argument
1011 * @param msg the encapsulated message
1012 * @param peer the peer to forward the message to
1013 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1015 static void forward_result_message (void *cls,
1016 const struct GNUNET_MessageHeader *msg,
1017 struct PeerInfo *peer,
1018 struct DHT_MessageContext *msg_ctx)
1020 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
1021 struct P2PPendingMessage *pending;
1025 increment_stats(STAT_RESULT_FORWARDS);
1026 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
1027 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1028 psize = sizeof(struct P2PPendingMessage) + msize;
1029 pending = GNUNET_malloc(psize);
1030 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1031 pending->importance = DHT_SEND_PRIORITY;
1032 pending->timeout = GNUNET_TIME_relative_get_forever();
1033 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
1034 result_message->header.size = htons(msize);
1035 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
1036 result_message->options = htonl(msg_ctx->msg_options);
1037 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
1038 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
1039 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1040 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1041 memcpy(&result_message[1], msg, ntohs(msg->size));
1043 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Adding pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
1045 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1046 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1047 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1050 * Called when core is ready to send a message we asked for
1051 * out to the destination.
1053 * @param cls closure (NULL)
1054 * @param size number of bytes available in buf
1055 * @param buf where the callee should write the message
1056 * @return number of bytes written to buf
1058 size_t core_transmit_notify (void *cls,
1059 size_t size, void *buf)
1061 struct PeerInfo *peer = cls;
1063 struct P2PPendingMessage *pending;
1070 /* client disconnected */
1072 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
1077 if (peer->head == NULL)
1082 pending = peer->head;
1083 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
1084 msize = ntohs(pending->msg->size);
1088 memcpy (cbuf, pending->msg, msize);
1089 GNUNET_CONTAINER_DLL_remove (peer->head,
1093 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Removing pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
1095 GNUNET_free (pending);
1098 while (NULL != pending &&
1099 (size - off >= (msize = ntohs (pending->msg->size))))
1101 #if DEBUG_DHT_ROUTING
1102 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s:%s' : transmit_notify (core) called with size %d, available %d\n", my_short_id, "dht service", msize, size);
1104 memcpy (&cbuf[off], pending->msg, msize);
1106 GNUNET_CONTAINER_DLL_remove (peer->head,
1109 GNUNET_free (pending);
1110 pending = peer->head;
1113 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1114 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1116 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "`%s:%s' : transmit_notify (core) called with size %d, available %d, returning %d\n", my_short_id, "dht service", msize, size, off);
1122 * Determine how many low order bits match in two
1123 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
1124 * the first two lowest order bits, and therefore the
1125 * return value is two (NOT XOR distance, nor how many
1126 * bits match absolutely!).
1128 * @param first the first hashcode
1129 * @param second the hashcode to compare first to
1131 * @return the number of bits that match
1133 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
1137 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
1138 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
1140 return sizeof (GNUNET_HashCode) * 8;
1144 * Compute the distance between have and target as a 32-bit value.
1145 * Differences in the lower bits must count stronger than differences
1146 * in the higher bits.
1148 * @return 0 if have==target, otherwise a number
1149 * that is larger as the distance between
1150 * the two hash codes increases
1153 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1155 unsigned int bucket;
1160 /* We have to represent the distance between two 2^9 (=512)-bit
1161 numbers as a 2^5 (=32)-bit number with "0" being used for the
1162 two numbers being identical; furthermore, we need to
1163 guarantee that a difference in the number of matching
1164 bits is always represented in the result.
1166 We use 2^32/2^9 numerical values to distinguish between
1167 hash codes that have the same LSB bit distance and
1168 use the highest 2^9 bits of the result to signify the
1169 number of (mis)matching LSB bits; if we have 0 matching
1170 and hence 512 mismatching LSB bits we return -1 (since
1171 512 itself cannot be represented with 9 bits) */
1173 /* first, calculate the most significant 9 bits of our
1174 result, aka the number of LSBs */
1175 bucket = matching_bits (target, have);
1176 /* bucket is now a value between 0 and 512 */
1178 return 0; /* perfect match */
1180 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1181 below, we'd end up with max+1 (overflow)) */
1183 /* calculate the most significant bits of the final result */
1184 msb = (512 - bucket) << (32 - 9);
1185 /* calculate the 32-9 least significant bits of the final result by
1186 looking at the differences in the 32-9 bits following the
1187 mismatching bit at 'bucket' */
1189 for (i = bucket + 1;
1190 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1192 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1193 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1194 last bit set will be 31 -- if
1195 i does not reach 512 first... */
1201 * Return a number that is larger the closer the
1202 * "have" GNUNET_hash code is to the "target".
1204 * @return inverse distance metric, non-zero.
1205 * Must fudge the value if NO bits match.
1208 inverse_distance (const GNUNET_HashCode * target,
1209 const GNUNET_HashCode * have)
1211 if (matching_bits(target, have) == 0)
1212 return 1; /* Never return 0! */
1213 return ((unsigned int) -1) - distance (target, have);
1217 * Find the optimal bucket for this key, regardless
1218 * of the current number of buckets in use.
1220 * @param hc the hashcode to compare our identity to
1222 * @return the proper bucket index, or GNUNET_SYSERR
1223 * on error (same hashcode)
1225 static int find_bucket(const GNUNET_HashCode *hc)
1229 bits = matching_bits(&my_identity.hashPubKey, hc);
1230 if (bits == MAX_BUCKETS)
1231 return GNUNET_SYSERR;
1232 return MAX_BUCKETS - bits - 1;
1236 * Find which k-bucket this peer should go into,
1237 * taking into account the size of the k-bucket
1238 * array. This means that if more bits match than
1239 * there are currently buckets, lowest_bucket will
1242 * @param hc GNUNET_HashCode we are finding the bucket for.
1244 * @return the proper bucket index for this key,
1245 * or GNUNET_SYSERR on error (same hashcode)
1247 static int find_current_bucket(const GNUNET_HashCode *hc)
1250 actual_bucket = find_bucket(hc);
1252 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1253 return GNUNET_SYSERR;
1254 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1255 return lowest_bucket;
1257 return actual_bucket;
1262 * Find a routing table entry from a peer identity
1264 * @param peer the peer to look up
1266 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1269 find_bucket_by_peer(const struct PeerInfo *peer)
1272 struct PeerInfo *pos;
1274 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1276 pos = k_buckets[bucket].head;
1285 return GNUNET_SYSERR; /* No such peer. */
1291 * Print the complete routing table for this peer.
1294 print_routing_table ()
1297 struct PeerInfo *pos;
1298 char char_buf[30000];
1300 memset(char_buf, 0, sizeof(char_buf));
1302 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1303 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1304 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1306 pos = k_buckets[bucket].head;
1307 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1308 //fprintf(stderr, "Bucket %d:\n", bucket);
1311 //fprintf(stderr, "\tPeer %s, best bucket %d, %d bits match\n", GNUNET_i2s(&pos->id), find_bucket(&pos->id.hashPubKey), matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey));
1312 char_pos += sprintf(&char_buf[char_pos], "\tPeer %s, best bucket %d, %d bits match\n", GNUNET_i2s(&pos->id), find_bucket(&pos->id.hashPubKey), matching_bits(&pos->id.hashPubKey, &my_identity.hashPubKey));
1316 fprintf(stderr, "%s", char_buf);
1322 * Find a routing table entry from a peer identity
1324 * @param peer the peer identity to look up
1326 * @return the routing table entry, or NULL if not found
1328 static struct PeerInfo *
1329 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1332 struct PeerInfo *pos;
1333 bucket = find_current_bucket(&peer->hashPubKey);
1335 if (bucket == GNUNET_SYSERR)
1338 pos = k_buckets[bucket].head;
1341 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1345 return NULL; /* No such peer. */
1348 /* Forward declaration */
1350 update_core_preference (void *cls,
1351 const struct GNUNET_SCHEDULER_TaskContext *tc);
1353 * Function called with statistics about the given peer.
1355 * @param cls closure
1356 * @param peer identifies the peer
1357 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1358 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1359 * @param amount set to the amount that was actually reserved or unreserved;
1360 * either the full requested amount or zero (no partial reservations)
1361 * @param preference current traffic preference for the given peer
1364 update_core_preference_finish (void *cls,
1365 const struct GNUNET_PeerIdentity * peer,
1366 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1367 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1368 int amount, uint64_t preference)
1370 struct PeerInfo *peer_info = cls;
1371 peer_info->info_ctx = NULL;
1372 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1376 update_core_preference (void *cls,
1377 const struct GNUNET_SCHEDULER_TaskContext *tc)
1379 struct PeerInfo *peer = cls;
1380 uint64_t preference;
1381 unsigned int matching;
1382 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1386 matching = matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1389 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Peer identifier matches by %u bits, only shifting as much as we can!\n", matching_bits);
1392 preference = 1LL << matching;
1393 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1395 GNUNET_TIME_relative_get_forever(),
1396 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1399 &update_core_preference_finish,
1404 * Really add a peer to a bucket (only do assertions
1407 * @param peer GNUNET_PeerIdentity of the peer to add
1408 * @param bucket the already figured out bucket to add
1410 * @param latency the core reported latency of this peer
1411 * @param distance the transport level distance to this peer
1413 * @return the newly added PeerInfo
1415 static struct PeerInfo *
1416 add_peer(const struct GNUNET_PeerIdentity *peer,
1417 unsigned int bucket,
1418 struct GNUNET_TIME_Relative latency,
1419 unsigned int distance)
1421 struct PeerInfo *new_peer;
1422 GNUNET_assert(bucket < MAX_BUCKETS);
1423 GNUNET_assert(peer != NULL);
1424 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1425 new_peer->latency = latency;
1426 new_peer->distance = distance;
1428 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1430 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1431 k_buckets[bucket].tail,
1432 k_buckets[bucket].tail,
1434 k_buckets[bucket].peers_size++;
1436 if ((matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1438 #if DO_UPDATE_PREFERENCE
1439 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1447 * Given a peer and its corresponding bucket,
1448 * remove it from that bucket. Does not free
1449 * the PeerInfo struct, nor cancel messages
1450 * or free messages waiting to be sent to this
1453 * @param peer the peer to remove
1454 * @param bucket the bucket the peer belongs to
1456 static void remove_peer (struct PeerInfo *peer,
1457 unsigned int bucket)
1459 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1460 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1461 k_buckets[bucket].tail,
1463 k_buckets[bucket].peers_size--;
1465 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1471 * Removes peer from a bucket, then frees associated
1472 * resources and frees peer.
1474 * @param peer peer to be removed and freed
1475 * @param bucket which bucket this peer belongs to
1477 static void delete_peer (struct PeerInfo *peer,
1478 unsigned int bucket)
1480 struct P2PPendingMessage *pos;
1481 struct P2PPendingMessage *next;
1483 struct PeerInfo *peer_pos;
1485 peer_pos = k_buckets[bucket].head;
1486 while ((peer_pos != NULL) && (peer_pos != peer))
1487 peer_pos = peer_pos->next;
1488 if (peer_pos == NULL)
1490 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1491 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Lowest bucket: %d, find_current_bucket: %d, peer resides in bucket: %d\n", my_short_id, "DHT", lowest_bucket, find_current_bucket(&peer->id.hashPubKey), find_bucket_by_peer(peer));
1493 GNUNET_assert(peer_pos != NULL);
1495 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1497 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1498 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1499 if (peer->th != NULL)
1500 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1503 while (pos != NULL) /* Remove any pending messages for this peer */
1510 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1511 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1517 * Iterator over hash map entries.
1519 * @param cls closure
1520 * @param key current key code
1521 * @param value PeerInfo of the peer to move to new lowest bucket
1522 * @return GNUNET_YES if we should continue to
1526 static int move_lowest_bucket (void *cls,
1527 const GNUNET_HashCode * key,
1530 struct PeerInfo *peer = value;
1533 GNUNET_assert(lowest_bucket > 0);
1534 new_bucket = lowest_bucket - 1;
1535 remove_peer(peer, lowest_bucket);
1536 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1537 k_buckets[new_bucket].tail,
1538 k_buckets[new_bucket].tail,
1540 k_buckets[new_bucket].peers_size++;
1546 * The current lowest bucket is full, so change the lowest
1547 * bucket to the next lower down, and move any appropriate
1548 * entries in the current lowest bucket to the new bucket.
1550 static void enable_next_bucket()
1552 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1553 struct PeerInfo *pos;
1554 GNUNET_assert(lowest_bucket > 0);
1555 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1556 pos = k_buckets[lowest_bucket].head;
1559 fprintf(stderr, "Printing RT before new bucket\n");
1560 print_routing_table();
1562 /* Populate the array of peers which should be in the next lowest bucket */
1565 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1566 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1570 /* Remove peers from lowest bucket, insert into next lowest bucket */
1571 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1572 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1573 lowest_bucket = lowest_bucket - 1;
1575 fprintf(stderr, "Printing RT after new bucket\n");
1576 print_routing_table();
1581 * Find the closest peer in our routing table to the
1584 * @return The closest peer in our routing table to the
1585 * key, or NULL on error.
1587 static struct PeerInfo *
1588 find_closest_peer (const GNUNET_HashCode *hc)
1590 struct PeerInfo *pos;
1591 struct PeerInfo *current_closest;
1592 unsigned int lowest_distance;
1593 unsigned int temp_distance;
1597 lowest_distance = -1;
1599 if (k_buckets[lowest_bucket].peers_size == 0)
1602 current_closest = NULL;
1603 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1605 pos = k_buckets[bucket].head;
1607 while ((pos != NULL) && (count < bucket_size))
1609 temp_distance = distance(&pos->id.hashPubKey, hc);
1610 if (temp_distance <= lowest_distance)
1612 lowest_distance = temp_distance;
1613 current_closest = pos;
1619 GNUNET_assert(current_closest != NULL);
1620 return current_closest;
1625 * Function called to send a request out to another peer.
1626 * Called both for locally initiated requests and those
1627 * received from other peers.
1629 * @param cls DHT service closure argument (unused)
1630 * @param msg the encapsulated message
1631 * @param peer the peer to forward the message to
1632 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1634 static void forward_message (void *cls,
1635 const struct GNUNET_MessageHeader *msg,
1636 struct PeerInfo *peer,
1637 struct DHT_MessageContext *msg_ctx)
1639 struct GNUNET_DHT_P2PRouteMessage *route_message;
1640 struct P2PPendingMessage *pending;
1644 increment_stats(STAT_ROUTE_FORWARDS);
1646 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1647 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1649 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1650 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1651 psize = sizeof(struct P2PPendingMessage) + msize;
1652 pending = GNUNET_malloc(psize);
1653 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1654 pending->importance = msg_ctx->importance;
1655 pending->timeout = msg_ctx->timeout;
1656 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1657 route_message->header.size = htons(msize);
1658 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1659 route_message->options = htonl(msg_ctx->msg_options);
1660 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1661 route_message->network_size = htonl(msg_ctx->network_size);
1662 route_message->desired_replication_level = htonl(msg_ctx->replication);
1663 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1664 if (msg_ctx->bloom != NULL)
1665 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1666 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1667 memcpy(&route_message[1], msg, ntohs(msg->size));
1669 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Adding pending message size %d for peer %s\n", my_short_id, "DHT", msize, GNUNET_i2s(&peer->id));
1671 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1672 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1673 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1678 * Task used to send ping messages to peers so that
1679 * they don't get disconnected.
1681 * @param cls the peer to send a ping message to
1682 * @param tc context, reason, etc.
1685 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1687 struct PeerInfo *peer = cls;
1688 struct GNUNET_MessageHeader ping_message;
1689 struct DHT_MessageContext message_context;
1691 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1694 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1695 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1697 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1699 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1701 forward_message(NULL, &ping_message, peer, &message_context);
1702 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1706 * Schedule PING messages for the top X peers in each
1707 * bucket of the routing table (so core won't disconnect them!)
1709 void schedule_ping_messages()
1711 unsigned int bucket;
1713 struct PeerInfo *pos;
1714 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1716 pos = k_buckets[bucket].head;
1720 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1721 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1722 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1724 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1725 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1735 * Attempt to add a peer to our k-buckets.
1737 * @param peer the peer identity of the peer being added
1738 * @param bucket the bucket that we want this peer to go in
1739 * @param latency transport latency of this peer
1740 * @param distance transport distance to this peer
1742 * @return NULL if the peer was not added,
1743 * pointer to PeerInfo for new peer otherwise
1745 static struct PeerInfo *
1746 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1747 unsigned int bucket,
1748 struct GNUNET_TIME_Relative latency,
1749 unsigned int distance)
1752 struct PeerInfo *new_peer;
1753 peer_bucket = find_current_bucket(&peer->hashPubKey);
1754 if (peer_bucket == GNUNET_SYSERR)
1757 GNUNET_assert(peer_bucket >= lowest_bucket);
1758 new_peer = add_peer(peer, peer_bucket, latency, distance);
1760 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1761 enable_next_bucket();
1763 schedule_ping_messages();
1770 * Task run to check for messages that need to be sent to a client.
1772 * @param client a ClientList, containing the client and any messages to be sent to it
1775 process_pending_messages (struct ClientList *client)
1777 if (client->pending_head == NULL)
1779 if (client->transmit_handle != NULL)
1781 client->transmit_handle =
1782 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1783 ntohs (client->pending_head->msg->
1785 GNUNET_TIME_UNIT_FOREVER_REL,
1786 &send_generic_reply, client);
1790 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1791 * request. A ClientList is passed as closure, take the head of the list
1792 * and copy it into buf, which has the result of sending the message to the
1795 * @param cls closure to this call
1796 * @param size maximum number of bytes available to send
1797 * @param buf where to copy the actual message to
1799 * @return the number of bytes actually copied, 0 indicates failure
1802 send_generic_reply (void *cls, size_t size, void *buf)
1804 struct ClientList *client = cls;
1806 struct PendingMessage *reply;
1810 client->transmit_handle = NULL;
1813 /* client disconnected */
1817 while ( (NULL != (reply = client->pending_head)) &&
1818 (size >= off + (msize = ntohs (reply->msg->size))))
1820 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1821 client->pending_tail,
1823 memcpy (&cbuf[off], reply->msg, msize);
1824 GNUNET_free (reply);
1827 process_pending_messages (client);
1833 * Add a PendingMessage to the clients list of messages to be sent
1835 * @param client the active client to send the message to
1836 * @param pending_message the actual message to send
1839 add_pending_message (struct ClientList *client,
1840 struct PendingMessage *pending_message)
1842 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1843 client->pending_tail,
1844 client->pending_tail,
1846 process_pending_messages (client);
1853 * Called when a reply needs to be sent to a client, as
1854 * a result it found to a GET or FIND PEER request.
1856 * @param client the client to send the reply to
1857 * @param message the encapsulated message to send
1858 * @param uid the unique identifier of this request
1861 send_reply_to_client (struct ClientList *client,
1862 const struct GNUNET_MessageHeader *message,
1863 unsigned long long uid)
1865 struct GNUNET_DHT_RouteResultMessage *reply;
1866 struct PendingMessage *pending_message;
1870 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1871 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1873 msize = ntohs (message->size);
1874 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1875 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1877 GNUNET_break_op (0);
1881 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1882 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1883 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1884 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1885 reply->header.size = htons (tsize);
1886 reply->unique_id = GNUNET_htonll (uid);
1887 memcpy (&reply[1], message, msize);
1889 add_pending_message (client, pending_message);
1893 * Consider whether or not we would like to have this peer added to
1894 * our routing table. Check whether bucket for this peer is full,
1895 * if so return negative; if not return positive. Since peers are
1896 * only added on CORE level connect, this doesn't actually add the
1897 * peer to the routing table.
1899 * @param peer the peer we are considering adding
1901 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1904 * FIXME: Think about making a context for this call so that we can
1905 * ping the oldest peer in the current bucket and consider
1906 * removing it in lieu of the new peer.
1908 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1912 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1913 return GNUNET_NO; /* We already know this peer (are connected even!) */
1914 bucket = find_current_bucket(&peer->hashPubKey);
1915 if (bucket == GNUNET_SYSERR)
1917 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1924 * Main function that handles whether or not to route a result
1925 * message to other peers, or to send to our local client.
1927 * @param cls closure (unused, always should be NULL)
1928 * @param msg the result message to be routed
1929 * @param message_context context of the message we are routing
1931 * @return the number of peers the message was routed to,
1932 * GNUNET_SYSERR on failure
1934 static int route_result_message(void *cls,
1935 struct GNUNET_MessageHeader *msg,
1936 struct DHT_MessageContext *message_context)
1938 struct GNUNET_PeerIdentity new_peer;
1939 struct DHTQueryRecord *record;
1940 struct DHTRouteSource *pos;
1941 struct PeerInfo *peer_info;
1942 const struct GNUNET_MessageHeader *hello_msg;
1944 increment_stats(STAT_RESULTS);
1946 * If a find peer result message is received and contains a valid
1947 * HELLO for another peer, offer it to the transport service.
1949 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1951 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1954 hello_msg = &msg[1];
1955 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1957 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1961 else /* We have a valid hello, and peer id stored in new_peer */
1963 find_peer_context.count++;
1964 increment_stats(STAT_FIND_PEER_REPLY);
1965 if (GNUNET_YES == consider_peer(&new_peer))
1967 increment_stats(STAT_HELLOS_PROVIDED);
1968 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1969 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &new_peer, NULL, NULL);
1974 if (malicious_dropper == GNUNET_YES)
1977 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1979 if (record == NULL) /* No record of this message! */
1982 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1983 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1984 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1986 #if DEBUG_DHT_ROUTING
1987 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1989 dhtlog_handle->insert_route (NULL,
1990 message_context->unique_id,
1992 message_context->hop_count,
1995 &message_context->key,
1996 message_context->peer, NULL);
1999 if (message_context->bloom != NULL)
2001 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2002 message_context->bloom = NULL;
2010 #if STRICT_FORWARDING
2011 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
2013 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
2015 increment_stats("# find peer responses NOT forwarded (bloom match)");
2020 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
2024 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
2027 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2028 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
2029 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2031 #if DEBUG_DHT_ROUTING
2032 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2034 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
2035 message_context->hop_count,
2036 GNUNET_YES, &my_identity, &message_context->key,
2037 message_context->peer, NULL);
2040 increment_stats(STAT_RESULTS_TO_CLIENT);
2041 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
2042 increment_stats(STAT_GET_REPLY);
2044 send_reply_to_client(pos->client, msg, message_context->unique_id);
2046 else /* Send to peer */
2048 peer_info = find_peer_by_id(&pos->source);
2049 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
2055 if (message_context->bloom == NULL)
2056 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2057 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2058 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
2061 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2062 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
2063 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2065 #if DEBUG_DHT_ROUTING
2066 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2068 dhtlog_handle->insert_route (NULL, message_context->unique_id,
2070 message_context->hop_count,
2071 GNUNET_NO, &my_identity, &message_context->key,
2072 message_context->peer, &pos->source);
2075 forward_result_message(cls, msg, peer_info, message_context);
2080 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2081 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
2082 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
2088 if (message_context->bloom != NULL)
2089 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2094 * Iterator for local get request results,
2096 * @param cls closure for iterator, a DatacacheGetContext
2097 * @param exp when does this value expire?
2098 * @param key the key this data is stored under
2099 * @param size the size of the data identified by key
2100 * @param data the actual data
2101 * @param type the type of the data
2103 * @return GNUNET_OK to continue iteration, anything else
2104 * to stop iteration.
2107 datacache_get_iterator (void *cls,
2108 struct GNUNET_TIME_Absolute exp,
2109 const GNUNET_HashCode * key,
2110 uint32_t size, const char *data, uint32_t type)
2112 struct DHT_MessageContext *msg_ctx = cls;
2113 struct DHT_MessageContext *new_msg_ctx;
2114 struct GNUNET_DHT_GetResultMessage *get_result;
2116 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2117 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2119 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2120 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2122 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2123 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2124 get_result->header.size =
2125 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2126 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2127 get_result->type = htons (type);
2128 memcpy (&get_result[1], data, size);
2129 new_msg_ctx->peer = &my_identity;
2130 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2131 new_msg_ctx->hop_count = 0;
2132 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2133 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2134 increment_stats(STAT_GET_RESPONSE_START);
2135 route_result_message(cls, &get_result->header, new_msg_ctx);
2136 GNUNET_free(new_msg_ctx);
2137 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2138 // datacache_get_ctx->unique_id);
2139 GNUNET_free (get_result);
2145 * Server handler for all dht get requests, look for data,
2146 * if found, send response either to clients or other peers.
2148 * @param cls closure for service
2149 * @param msg the actual get message
2150 * @param message_context struct containing pertinent information about the get request
2152 * @return number of items found for GET request
2155 handle_dht_get (void *cls,
2156 const struct GNUNET_MessageHeader *msg,
2157 struct DHT_MessageContext *message_context)
2159 const struct GNUNET_DHT_GetMessage *get_msg;
2161 unsigned int results;
2163 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2164 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2170 get_type = ntohs (get_msg->type);
2172 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2173 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2174 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2175 message_context->unique_id);
2177 increment_stats(STAT_GETS);
2179 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2182 if (datacache != NULL)
2184 GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2185 &datacache_get_iterator, message_context);
2190 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2191 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2192 results, "GET", message_context->unique_id);
2194 #if DEBUG_DHT_ROUTING
2195 if ((debug_routes) && (dhtlog_handle != NULL))
2197 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2198 message_context->hop_count, GNUNET_YES, &my_identity,
2199 &message_context->key);
2202 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2204 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2205 message_context->hop_count, GNUNET_YES,
2206 &my_identity, &message_context->key, message_context->peer,
2212 if (message_context->hop_count == 0) /* Locally initiated request */
2214 #if DEBUG_DHT_ROUTING
2215 if ((debug_routes) && (dhtlog_handle != NULL))
2217 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2218 message_context->hop_count, GNUNET_NO, &my_identity,
2219 &message_context->key);
2228 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2230 GNUNET_HashCode *key = cls;
2231 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2238 * Server handler for initiating local dht find peer requests
2240 * @param cls closure for service
2241 * @param find_msg the actual find peer message
2242 * @param message_context struct containing pertinent information about the request
2246 handle_dht_find_peer (void *cls,
2247 const struct GNUNET_MessageHeader *find_msg,
2248 struct DHT_MessageContext *message_context)
2250 struct GNUNET_MessageHeader *find_peer_result;
2251 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2252 struct DHT_MessageContext *new_msg_ctx;
2253 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2256 GNUNET_HashCode *recent_hash;
2257 struct GNUNET_MessageHeader *other_hello;
2258 size_t other_hello_size;
2259 struct GNUNET_PeerIdentity peer_id;
2261 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2262 GNUNET_break_op(ntohs(find_msg->size) >= (sizeof(struct GNUNET_DHT_FindPeerMessage)));
2263 if (ntohs(find_msg->size) < sizeof(struct GNUNET_DHT_FindPeerMessage))
2266 other_hello_size = 0;
2267 if (ntohs(find_msg->size) > sizeof(struct GNUNET_DHT_FindPeerMessage))
2269 other_hello_size = ntohs(find_msg->size) - sizeof(struct GNUNET_DHT_FindPeerMessage);
2270 other_hello = GNUNET_malloc(other_hello_size);
2271 memcpy(other_hello, &find_peer_message[1], other_hello_size);
2272 if ((GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)other_hello) == 0) || (GNUNET_OK != GNUNET_HELLO_get_id((struct GNUNET_HELLO_Message *)other_hello, &peer_id)))
2274 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Received invalid HELLO message in find peer request!\n");
2275 GNUNET_free(other_hello);
2278 #if FIND_PEER_WITH_HELLO
2280 if (GNUNET_YES == consider_peer(&peer_id))
2282 increment_stats(STAT_HELLOS_PROVIDED);
2283 GNUNET_TRANSPORT_offer_hello(transport_handle, other_hello);
2284 GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5), &peer_id, NULL, NULL);
2286 else /* We don't want this peer! */ /* Alternatively, just continue normally */
2294 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2295 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2296 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2297 ntohs (find_msg->size),
2298 sizeof (struct GNUNET_MessageHeader));
2300 if (my_hello == NULL)
2303 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2304 "`%s': Our HELLO is null, can't return.\n",
2307 GNUNET_free_non_null(other_hello);
2311 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2312 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2314 increment_stats(STAT_BLOOM_FIND_PEER);
2315 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2316 GNUNET_free_non_null(other_hello);
2317 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2319 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2321 #if RESTRICT_FIND_PEER
2324 * Ignore any find peer requests from a peer we have seen very recently.
2326 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent_find_peer_requests, &message_context->key)) /* We have recently responded to a find peer request for this peer! */
2328 increment_stats("# dht find peer requests ignored (recently seen!)");
2329 GNUNET_free_non_null(other_hello);
2334 * Use this check to only allow the peer to respond to find peer requests if
2335 * it would be beneficial to have the requesting peer in this peers routing
2336 * table. Can be used to thwart peers flooding the network with find peer
2337 * requests that we don't care about. However, if a new peer is joining
2338 * the network and has no other peers this is a problem (assume all buckets
2339 * full, no one will respond!).
2341 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2342 if (GNUNET_NO == consider_peer(&peer_id))
2344 increment_stats("# dht find peer requests ignored (do not need!)");
2345 GNUNET_free_non_null(other_hello);
2350 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2351 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2352 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2353 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30), &remove_recent_find_peer, &recent_hash);
2355 /* Simplistic find_peer functionality, always return our hello */
2356 hello_size = ntohs(my_hello->size);
2357 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2359 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2361 GNUNET_break_op (0);
2362 GNUNET_free_non_null(other_hello);
2366 find_peer_result = GNUNET_malloc (tsize);
2367 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2368 find_peer_result->size = htons (tsize);
2369 memcpy (&find_peer_result[1], my_hello, hello_size);
2371 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2372 "`%s': Sending hello size %d to requesting peer.\n",
2375 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2376 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2377 new_msg_ctx->peer = &my_identity;
2378 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2379 new_msg_ctx->hop_count = 0;
2380 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2381 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2382 increment_stats(STAT_FIND_PEER_ANSWER);
2383 route_result_message(cls, find_peer_result, new_msg_ctx);
2384 GNUNET_free(new_msg_ctx);
2385 #if DEBUG_DHT_ROUTING
2386 if ((debug_routes) && (dhtlog_handle != NULL))
2388 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2389 message_context->hop_count, GNUNET_YES, &my_identity,
2390 &message_context->key);
2393 GNUNET_free_non_null(other_hello);
2394 GNUNET_free(find_peer_result);
2398 * Task used to republish data.
2399 * Forward declaration; function call loop.
2401 * @param cls closure (a struct RepublishContext)
2402 * @param tc runtime context for this task
2405 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
2408 * Server handler for initiating local dht put requests
2410 * @param cls closure for service
2411 * @param msg the actual put message
2412 * @param message_context struct containing pertinent information about the request
2415 handle_dht_put (void *cls,
2416 const struct GNUNET_MessageHeader *msg,
2417 struct DHT_MessageContext *message_context)
2419 struct GNUNET_DHT_PutMessage *put_msg;
2423 struct RepublishContext *put_context;
2425 GNUNET_assert (ntohs (msg->size) >=
2426 sizeof (struct GNUNET_DHT_PutMessage));
2429 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2430 put_type = ntohs (put_msg->type);
2432 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2435 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2437 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2438 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2439 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2441 #if DEBUG_DHT_ROUTING
2442 if (message_context->hop_count == 0) /* Locally initiated request */
2444 if ((debug_routes) && (dhtlog_handle != NULL))
2446 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2447 message_context->hop_count, GNUNET_NO, &my_identity,
2448 &message_context->key);
2453 if (message_context->closest != GNUNET_YES)
2456 #if DEBUG_DHT_ROUTING
2457 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2459 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2460 message_context->hop_count, GNUNET_YES,
2461 &my_identity, &message_context->key, message_context->peer,
2465 if ((debug_routes) && (dhtlog_handle != NULL))
2467 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2468 message_context->hop_count, GNUNET_YES, &my_identity,
2469 &message_context->key);
2473 increment_stats(STAT_PUTS_INSERTED);
2474 if (datacache != NULL)
2476 ret = GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2477 (char *) &put_msg[1], put_type,
2478 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2480 if ((ret == GNUNET_YES) && (do_republish == GNUNET_YES))
2482 put_context = GNUNET_malloc(sizeof(struct RepublishContext));
2483 memcpy(&put_context->key, &message_context->key, sizeof(GNUNET_HashCode));
2484 put_context->type = put_type;
2485 GNUNET_SCHEDULER_add_delayed (sched, dht_republish_frequency, &republish_content, put_context);
2489 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2490 "`%s:%s': %s request received, but have no datacache!\n",
2491 my_short_id, "DHT", "PUT");
2495 * Estimate the diameter of the network based
2496 * on how many buckets are currently in use.
2497 * Concept here is that the diameter of the network
2498 * is roughly the distance a message must travel in
2499 * order to reach its intended destination. Since
2500 * at each hop we expect to get one bit closer, and
2501 * we have one bit per bucket, the number of buckets
2502 * in use should be the largest number of hops for
2503 * a sucessful message. (of course, this assumes we
2504 * know all peers in the network!)
2506 * @return ballpark diameter figure
2508 static unsigned int estimate_diameter()
2510 return MAX_BUCKETS - lowest_bucket;
2514 * To how many peers should we (on average)
2515 * forward the request to obtain the desired
2516 * target_replication count (on average).
2518 * Always 0, 1 or 2 (don't send, send once, split)
2521 get_forward_count (unsigned int hop_count, size_t target_replication)
2524 double target_count;
2525 double random_probability;
2527 uint32_t random_value;
2529 unsigned int target_value;
2530 unsigned int diameter;
2533 * If we are behaving in strict kademlia mode, send multiple initial requests,
2534 * but then only send to 1 or 0 peers based strictly on the number of hops.
2536 if (strict_kademlia == GNUNET_YES)
2539 return DHT_KADEMLIA_REPLICATION;
2540 else if (hop_count < max_hops)
2546 /* FIXME: the smaller we think the network is the more lenient we should be for
2547 * routing right? The estimation below only works if we think we have reasonably
2548 * full routing tables, which for our RR topologies may not be the case!
2550 diameter = estimate_diameter ();
2551 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2555 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2556 "DHT", estimate_diameter(), lowest_bucket);
2560 else if (hop_count > max_hops)
2563 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2564 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2571 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2572 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2573 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2574 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2575 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2576 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2577 RAND_MAX)) / RAND_MAX;
2578 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2581 //while (target_value < target_count)
2582 if (target_value < target_count)
2583 target_value++; /* target_value is ALWAYS 1 after this "loop", right? Because target_count is always > 0, right? Or does it become 0.00000... at some point because the hop count is so high? */
2586 //if ((target_count + 1 - (double)target_value) > random_probability)
2587 if ((target_count) > random_probability)
2591 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_STRONG, target_replication * (hop_count + 1) + diameter) + 1;
2592 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "replication %u, at hop %d, will split with probability %f\n", target_replication, hop_count, target_replication / (double)((target_replication * (hop_count + 1) + diameter) + 1));
2594 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2595 if (random_value < target_replication)
2598 return target_value;
2602 * Check whether my identity is closer than any known peers.
2603 * If a non-null bloomfilter is given, check if this is the closest
2604 * peer that hasn't already been routed to.
2606 * @param target hash code to check closeness to
2607 * @param bloom bloomfilter, exclude these entries from the decision
2609 * Return GNUNET_YES if node location is closest, GNUNET_NO
2613 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2619 struct PeerInfo *pos;
2620 unsigned int my_distance;
2622 bucket_num = find_current_bucket(target);
2623 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2626 bits = matching_bits(&my_identity.hashPubKey, target);
2627 my_distance = distance(&my_identity.hashPubKey, target);
2628 pos = k_buckets[bucket_num].head;
2630 while ((pos != NULL) && (count < bucket_size))
2632 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2635 continue; /* Skip already checked entries */
2638 other_bits = matching_bits(&pos->id.hashPubKey, target);
2639 if (other_bits > bits)
2641 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2643 if (strict_kademlia != GNUNET_YES) /* Return that we at as close as any other peer */
2645 else if (distance(&pos->id.hashPubKey, target) < my_distance) /* Check all known peers, only return if we are the true closest */
2652 GNUNET_GE_LOG (coreAPI->ectx,
2653 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2654 GNUNET_GE_BULK, "closest peer\n");
2655 printPeerBits (&closest);
2656 GNUNET_GE_LOG (coreAPI->ectx,
2657 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2658 GNUNET_GE_BULK, "me\n");
2659 printPeerBits (coreAPI->my_identity);
2660 GNUNET_GE_LOG (coreAPI->ectx,
2661 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2662 GNUNET_GE_BULK, "key\n");
2663 printKeyBits (target);
2664 GNUNET_GE_LOG (coreAPI->ectx,
2665 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2667 "closest peer inverse distance is %u, mine is %u\n",
2668 inverse_distance (target, &closest.hashPubKey),
2669 inverse_distance (target,
2670 &coreAPI->my_identity->hashPubKey));
2673 /* No peers closer, we are the closest! */
2679 * Decide whether to route this request exclusively
2680 * to a closer peer (if closer peers exist) or to choose
2681 * from the whole set of peers.
2683 * @param target the key of the request
2684 * @param bloom bloomfilter of peers this request has already traversed
2685 * @param hops number of hops this message has already traveled
2687 * @return GNUNET_YES if we should try to route to a closer peer
2688 * than ourselves (and one exists), GNUNET_NO if we should
2689 * choose from the set of all known peers
2693 route_closer (const GNUNET_HashCode *target,
2694 struct GNUNET_CONTAINER_BloomFilter *bloom,
2697 unsigned int my_matching_bits;
2699 uint32_t random_value;
2700 struct PeerInfo *pos;
2705 my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2707 if (GNUNET_YES == use_max_hops)
2708 curr_max_hops = max_hops;
2710 curr_max_hops = max_hops; /* FIXME: replace with heuristic! */
2712 * First check if we know any close (as close as us or closer) peers.
2714 have_closer = GNUNET_NO;
2716 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2718 pos = k_buckets[bc].head;
2720 while ((pos != NULL) && (count < bucket_size))
2722 if ((matching_bits(target, &pos->id.hashPubKey) > my_matching_bits) &&
2723 (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
2725 have_closer = GNUNET_YES;
2731 if (have_closer == GNUNET_YES)
2735 if (have_closer == GNUNET_NO) /* We don't have a same distance or closer node, can't enforce closer only! */
2738 switch (converge_option)
2740 case DHT_CONVERGE_LINEAR:
2742 * Simple linear curve for choosing whether or not to converge.
2743 * Choose to route only closer with probability hops/MAX_HOPS.
2745 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, curr_max_hops);
2746 if (random_value < hops)
2750 case DHT_CONVERGE_SQUARE:
2752 * Simple square based curve.
2754 if ((GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1) / (double)(uint32_t)-1) < (sqrt(hops) / sqrt(curr_max_hops)))
2758 case DHT_CONVERGE_EXPONENTIAL:
2760 * Simple exponential curve.
2762 if (converge_modifier > 0)
2763 calc_value = ((converge_modifier * (hops * hops)) / (curr_max_hops * curr_max_hops)) / curr_max_hops;
2765 calc_value = ((hops * hops) / (curr_max_hops * curr_max_hops)) / curr_max_hops;
2767 if ((GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1) / (double)(uint32_t)-1) < calc_value)
2778 * Select a peer from the routing table that would be a good routing
2779 * destination for sending a message for "target". The resulting peer
2780 * must not be in the set of blocked peers.<p>
2782 * Note that we should not ALWAYS select the closest peer to the
2783 * target, peers further away from the target should be chosen with
2784 * exponentially declining probability.
2786 * @param target the key we are selecting a peer to route to
2787 * @param bloom a bloomfilter containing entries this request has seen already
2788 * @param hops the number of hops this message has already traversed
2790 * @return Peer to route to, or NULL on error
2792 static struct PeerInfo *
2793 select_peer (const GNUNET_HashCode * target,
2794 struct GNUNET_CONTAINER_BloomFilter *bloom,
2797 unsigned int distance;
2800 unsigned int my_matching_bits;
2801 unsigned long long largest_distance;
2802 unsigned long long total_real_distance;
2803 unsigned long long real_selected;
2804 unsigned int total_distance;
2805 unsigned int selected;
2806 unsigned int match_num;
2808 struct PeerInfo *pos;
2809 struct PeerInfo *chosen;
2811 #if DEBUG_DHT_ROUTING > 1
2815 my_matching_bits = matching_bits(target, &my_identity.hashPubKey);
2816 only_closer = route_closer(target, bloom, hops);
2818 if (GNUNET_YES == only_closer)
2820 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "only routing to closer peers!\n");
2821 GNUNET_asprintf(&temp_stat, "# closer only routes at hop %u", hops);
2822 increment_stats(temp_stat);
2826 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "routing to all possible peers!\n");
2827 GNUNET_asprintf(&temp_stat, "# NOT closer only routes at hop %u", hops);
2828 increment_stats(temp_stat);
2831 GNUNET_free(temp_stat);
2832 total_real_distance = 0;
2833 if (strict_kademlia == GNUNET_YES)
2835 largest_distance = 0;
2837 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2839 pos = k_buckets[bc].head;
2841 while ((pos != NULL) && (count < bucket_size))
2843 /* If we are doing strict Kademlia routing, then checking the bloomfilter is basically cheating! */
2844 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2846 distance = inverse_distance (target, &pos->id.hashPubKey);
2847 if (distance > largest_distance)
2850 largest_distance = distance;
2858 if ((largest_distance > 0) && (chosen != NULL))
2860 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2872 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2874 pos = k_buckets[bc].head;
2876 while ((pos != NULL) && (count < bucket_size))
2878 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2879 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2881 if (GNUNET_YES == use_real_distance)
2882 total_real_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2885 /* Always add 1, in case 0 bits match! */
2886 match_num = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target ,&pos->id.hashPubKey));
2887 total_distance += match_num;
2891 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2892 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2893 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2900 if (((GNUNET_YES == use_real_distance) && (total_real_distance == 0)) || (total_distance == 0))
2902 increment_stats("# select_peer, total_distance == 0");
2906 #if DEBUG_DHT_ROUTING > 1
2908 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2910 pos = k_buckets[bc].head;
2912 while ((pos != NULL) && (count < bucket_size))
2914 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2915 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2917 if (GNUNET_YES == use_real_distance)
2919 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "REAL: Choose peer with %d matching bits (%.2f percent)\n", matching_bits(&pos->id.hashPubKey, target), (inverse_distance (target, &pos->id.hashPubKey) / (double)total_real_distance) * 100);
2920 sum += inverse_distance (target, &pos->id.hashPubKey) / (double)total_real_distance;
2924 match_num = 1 + (matching_bits(&pos->id.hashPubKey, target) * matching_bits(&pos->id.hashPubKey, target));
2925 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Choose peer with %d matching bits (%.2f percent)\n", matching_bits(&pos->id.hashPubKey, target), (match_num / (double)total_distance) * 100);
2926 sum += match_num / (double)total_distance;
2936 if (use_real_distance)
2938 GNUNET_assert(total_real_distance != 0);
2939 real_selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_real_distance);
2943 GNUNET_assert(total_distance != 0);
2944 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2947 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2949 pos = k_buckets[bc].head;
2951 while ((pos != NULL) && (count < bucket_size))
2953 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) &&
2954 ((only_closer == GNUNET_NO) || (matching_bits(target, &pos->id.hashPubKey) >= my_matching_bits)))
2956 if (GNUNET_YES == use_real_distance)
2958 distance = inverse_distance (target, &pos->id.hashPubKey);
2959 if (distance > real_selected)
2961 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "(REAL) Selected peer with %u matching bits to route to\n", matching_bits(target, &pos->id.hashPubKey));
2964 real_selected -= distance;
2968 distance = 1 + (matching_bits(target, &pos->id.hashPubKey) * matching_bits(target, &pos->id.hashPubKey));
2969 if (distance > selected)
2971 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Selected peer with %u matching bits to route to\n", matching_bits(target, &pos->id.hashPubKey));
2974 selected -= distance;
2980 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2981 "`%s:%s': peer %s matches bloomfilter.\n",
2982 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2991 "`%s:%s': peer %s matches bloomfilter.\n",
2992 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2994 increment_stats("# failed to select peer");
2995 GNUNET_assert(only_closer == GNUNET_NO);
3001 * Task used to remove recent entries, either
3002 * after timeout, when full, or on shutdown.
3004 * @param cls the entry to remove
3005 * @param tc context, reason, etc.
3008 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3010 struct RecentRequest *req = cls;
3011 static GNUNET_HashCode hash;
3013 GNUNET_assert(req != NULL);
3014 hash_from_uid(req->uid, &hash);
3015 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
3016 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
3017 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
3020 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
3022 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
3023 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
3029 * Task used to remove forwarding entries, either
3030 * after timeout, when full, or on shutdown.
3032 * @param cls the entry to remove
3033 * @param tc context, reason, etc.
3036 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3038 struct DHTRouteSource *source_info = cls;
3039 struct DHTQueryRecord *record;
3040 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
3041 record = source_info->record;
3042 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3044 if (record->head == NULL) /* No more entries in DLL */
3046 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3047 GNUNET_free(record);
3049 if (source_info->find_peers_responded != NULL)
3050 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3051 GNUNET_free(source_info);
3055 * Remember this routing request so that if a reply is
3056 * received we can either forward it to the correct peer
3057 * or return the result locally.
3059 * @param cls DHT service closure
3060 * @param msg_ctx Context of the route request
3062 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
3064 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
3066 struct DHTQueryRecord *record;
3067 struct DHTRouteSource *source_info;
3068 struct DHTRouteSource *pos;
3069 struct GNUNET_TIME_Absolute now;
3070 unsigned int current_size;
3072 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3073 while (current_size >= MAX_OUTSTANDING_FORWARDS)
3075 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
3076 GNUNET_assert(source_info != NULL);
3077 record = source_info->record;
3078 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
3079 if (record->head == NULL) /* No more entries in DLL */
3081 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
3082 GNUNET_free(record);
3084 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
3085 if (source_info->find_peers_responded != NULL)
3086 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
3087 GNUNET_free(source_info);
3088 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
3090 now = GNUNET_TIME_absolute_get();
3091 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
3092 if (record != NULL) /* Already know this request! */
3097 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
3098 break; /* Already have this peer in reply list! */
3101 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
3103 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
3109 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
3110 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
3111 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
3114 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
3115 source_info->record = record;
3116 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
3117 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3118 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
3119 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
3120 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
3122 source_info->client = msg_ctx->client;
3123 now = GNUNET_TIME_absolute_get_forever();
3125 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
3127 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3128 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
3129 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
3136 * Main function that handles whether or not to route a message to other
3139 * @param cls closure for dht service (NULL)
3140 * @param msg the message to be routed
3141 * @param message_context the context containing all pertinent information about the message
3143 * @return the number of peers the message was routed to,
3144 * GNUNET_SYSERR on failure
3146 static int route_message(void *cls,
3147 const struct GNUNET_MessageHeader *msg,
3148 struct DHT_MessageContext *message_context)
3152 struct PeerInfo *selected;
3153 #if DEBUG_DHT_ROUTING > 1
3154 struct PeerInfo *nearest;
3156 unsigned int forward_count;
3157 struct RecentRequest *recent_req;
3158 GNUNET_HashCode unique_hash;
3159 char *stat_forward_count;
3160 #if DEBUG_DHT_ROUTING
3164 if (malicious_dropper == GNUNET_YES)
3166 #if DEBUG_DHT_ROUTING
3167 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3169 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3170 message_context->hop_count, GNUNET_SYSERR,
3171 &my_identity, &message_context->key, message_context->peer,
3175 if (message_context->bloom != NULL)
3176 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3180 increment_stats(STAT_ROUTES);
3181 /* Semantics of this call means we find whether we are the closest peer out of those already
3182 * routed to on this messages path.
3184 global_closest = am_closest_peer(&message_context->key, NULL);
3185 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
3186 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
3187 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
3188 increment_stats(stat_forward_count);
3189 GNUNET_free(stat_forward_count);
3190 if (message_context->bloom == NULL)
3191 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3193 if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
3197 * NOTICE: In Kademlia, a find peer request goes no further if the peer doesn't return
3198 * any closer peers (which is being checked for below). Since we are doing recursive
3199 * routing we have no choice but to stop forwarding in this case. This means that at
3200 * any given step the request may NOT be forwarded to alpha peers (because routes will
3201 * stop and the parallel route will not be aware of it). Of course, assuming that we
3202 * have fulfilled the Kademlia requirements for routing table fullness this will never
3203 * ever ever be a problem.
3205 * However, is this fair?
3207 * Since we use these requests to build our routing tables (and we build them in the
3208 * testing driver) we will ignore this restriction for FIND_PEER messages so that
3209 * routing tables still get constructed.
3211 if ((GNUNET_YES == strict_kademlia) && (global_closest == GNUNET_YES) && (message_context->hop_count > 0) && (ntohs(msg->type) != GNUNET_MESSAGE_TYPE_DHT_FIND_PEER))
3214 #if DEBUG_DHT_ROUTING
3215 if (forward_count == 0)
3216 ret = GNUNET_SYSERR;
3220 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3222 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3223 message_context->hop_count, ret,
3224 &my_identity, &message_context->key, message_context->peer,
3229 switch (ntohs(msg->type))
3231 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
3232 cache_response (cls, message_context);
3233 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
3236 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
3237 increment_stats(STAT_PUTS);
3238 message_context->closest = global_closest;
3239 handle_dht_put (cls, msg, message_context);
3241 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
3242 increment_stats(STAT_FIND_PEER);
3243 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
3245 cache_response (cls, message_context);
3246 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
3247 handle_dht_find_peer (cls, msg, message_context);
3249 #if DEBUG_DHT_ROUTING
3250 if (message_context->hop_count == 0) /* Locally initiated request */
3252 if ((debug_routes) && (dhtlog_handle != NULL))
3254 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
3255 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
3256 message_context->hop_count, GNUNET_NO, &my_identity,
3257 &message_context->key);
3263 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3264 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
3267 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
3268 hash_from_uid (message_context->unique_id, &unique_hash);
3269 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (recent.hashmap, &unique_hash))
3271 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
3272 GNUNET_assert(recent_req != NULL);
3273 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
3274 increment_stats(STAT_DUPLICATE_UID);
3277 increment_stats(STAT_RECENT_SEEN);
3278 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
3283 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
3284 recent_req->uid = message_context->unique_id;
3285 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
3286 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
3287 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
3288 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3289 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3292 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
3294 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
3295 GNUNET_assert(recent_req != NULL);
3296 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
3297 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
3300 for (i = 0; i < forward_count; i++)
3302 selected = select_peer(&message_context->key, message_context->bloom, message_context->hop_count);
3304 if (selected != NULL)
3306 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
3307 #if DEBUG_DHT_ROUTING > 1
3308 nearest = find_closest_peer(&message_context->key);
3309 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
3310 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3311 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
3312 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&selected->id), nearest_buf, matching_bits(&nearest->id.hashPubKey, message_context->key), distance(&nearest->id.hashPubKey, message_context->key));
3313 GNUNET_free(nearest_buf);
3315 #if DEBUG_DHT_ROUTING
3316 if ((debug_routes_extended) && (dhtlog_handle != NULL))
3318 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
3319 message_context->hop_count, GNUNET_NO,
3320 &my_identity, &message_context->key, message_context->peer,
3324 forward_message(cls, msg, selected, message_context);
3328 increment_stats("# NULL returned from select_peer");
3329 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3330 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
3335 #if DEBUG_DHT_ROUTING > 1
3336 if (forward_count == 0)
3338 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3339 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
3340 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
3344 if (message_context->bloom != NULL)
3346 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
3347 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
3350 return forward_count;
3354 * Iterator for local get request results,
3356 * @param cls closure for iterator, NULL
3357 * @param exp when does this value expire?
3358 * @param key the key this data is stored under
3359 * @param size the size of the data identified by key
3360 * @param data the actual data
3361 * @param type the type of the data
3363 * @return GNUNET_OK to continue iteration, anything else
3364 * to stop iteration.
3367 republish_content_iterator (void *cls,
3368 struct GNUNET_TIME_Absolute exp,
3369 const GNUNET_HashCode * key,
3370 uint32_t size, const char *data, uint32_t type)
3373 struct DHT_MessageContext *new_msg_ctx;
3374 struct GNUNET_DHT_PutMessage *put_msg;
3376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3377 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
3379 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
3382 GNUNET_malloc (sizeof (struct GNUNET_DHT_PutMessage) + size);
3383 put_msg->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_PUT);
3384 put_msg->header.size = htons (sizeof (struct GNUNET_DHT_PutMessage) + size);
3385 put_msg->expiration = GNUNET_TIME_absolute_hton(exp);
3386 put_msg->type = htons (type);
3387 memcpy (&put_msg[1], data, size);
3388 new_msg_ctx->unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3389 new_msg_ctx->replication = ntohl (DHT_DEFAULT_PUT_REPLICATION);
3390 new_msg_ctx->msg_options = ntohl (0);
3391 new_msg_ctx->network_size = estimate_diameter();
3392 new_msg_ctx->peer = &my_identity;
3393 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3394 new_msg_ctx->hop_count = 0;
3395 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3396 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3397 increment_stats(STAT_PUT_START);
3398 route_message(cls, &put_msg->header, new_msg_ctx);
3400 GNUNET_free(new_msg_ctx);
3401 GNUNET_free (put_msg);
3406 * Task used to republish data.
3408 * @param cls closure (a struct RepublishContext)
3409 * @param tc runtime context for this task
3412 republish_content(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3414 struct RepublishContext *put_context = cls;
3416 unsigned int results;
3418 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3420 GNUNET_free(put_context);
3424 GNUNET_assert (datacache != NULL); /* If we have no datacache we never should have scheduled this! */
3425 results = GNUNET_DATACACHE_get(datacache, &put_context->key, put_context->type, &republish_content_iterator, NULL);
3426 if (results == 0) /* Data must have expired */
3427 GNUNET_free(put_context);
3428 else /* Reschedule task for next time period */
3429 GNUNET_SCHEDULER_add_delayed(sched, dht_republish_frequency, &republish_content, put_context);
3434 * Find a client if it exists, add it otherwise.
3436 * @param client the server handle to the client
3438 * @return the client if found, a new client otherwise
3440 static struct ClientList *
3441 find_active_client (struct GNUNET_SERVER_Client *client)
3443 struct ClientList *pos = client_list;
3444 struct ClientList *ret;
3448 if (pos->client_handle == client)
3453 ret = GNUNET_malloc (sizeof (struct ClientList));
3454 ret->client_handle = client;
3455 ret->next = client_list;
3461 * Task to send a malicious put message across the network.
3463 * @param cls closure for this task
3464 * @param tc the context under which the task is running
3467 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3469 static struct GNUNET_DHT_PutMessage put_message;
3470 static struct DHT_MessageContext message_context;
3471 static GNUNET_HashCode key;
3472 uint32_t random_key;
3474 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3477 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3478 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3479 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3480 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3481 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3482 message_context.client = NULL;
3483 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3484 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3485 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3486 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3487 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3488 message_context.msg_options = ntohl (0);
3489 message_context.network_size = estimate_diameter();
3490 message_context.peer = &my_identity;
3491 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3492 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3493 #if DEBUG_DHT_ROUTING
3494 if (dhtlog_handle != NULL)
3495 dhtlog_handle->insert_dhtkey(NULL, &key);
3497 increment_stats(STAT_PUT_START);
3498 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3499 route_message(NULL, &put_message.header, &message_context);
3500 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3505 * Task to send a malicious put message across the network.
3507 * @param cls closure for this task
3508 * @param tc the context under which the task is running
3511 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3513 static struct GNUNET_DHT_GetMessage get_message;
3514 struct DHT_MessageContext message_context;
3515 static GNUNET_HashCode key;
3516 uint32_t random_key;
3518 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3521 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3522 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3523 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3524 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3525 message_context.client = NULL;
3526 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3527 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3528 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3529 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3530 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3531 message_context.msg_options = ntohl (0);
3532 message_context.network_size = estimate_diameter();
3533 message_context.peer = &my_identity;
3534 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3535 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3536 #if DEBUG_DHT_ROUTING
3537 if (dhtlog_handle != NULL)
3538 dhtlog_handle->insert_dhtkey(NULL, &key);
3540 increment_stats(STAT_GET_START);
3541 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3542 route_message (NULL, &get_message.header, &message_context);
3543 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3547 * Iterator over hash map entries.
3549 * @param cls closure
3550 * @param key current key code
3551 * @param value value in the hash map
3552 * @return GNUNET_YES if we should continue to
3557 add_known_to_bloom (void *cls,
3558 const GNUNET_HashCode * key,
3561 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3562 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3567 * Task to send a find peer message for our own peer identifier
3568 * so that we can find the closest peers in the network to ourselves
3569 * and attempt to connect to them.
3571 * @param cls closure for this task
3572 * @param tc the context under which the task is running
3575 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3577 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3578 struct DHT_MessageContext message_context;
3580 struct GNUNET_TIME_Relative next_send_time;
3581 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3583 struct GNUNET_TIME_Relative time_diff;
3584 struct GNUNET_TIME_Absolute end;
3586 double count_per_interval;
3588 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3591 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! */
3593 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3594 GNUNET_SCHEDULER_add_delayed (sched,
3595 GNUNET_TIME_UNIT_MINUTES,
3596 &send_find_peer_message, NULL);
3597 newly_found_peers = 0;
3601 increment_stats(STAT_FIND_PEER_START);
3603 end = GNUNET_TIME_absolute_get();
3604 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3606 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3608 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3609 count_per_interval = find_peer_context.count / multiplier;
3613 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3614 count_per_interval = find_peer_context.count * multiplier;
3618 #if FIND_PEER_WITH_HELLO
3619 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3620 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage) + GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3621 memcpy(&find_peer_msg[1], my_hello, GNUNET_HELLO_size((struct GNUNET_HELLO_Message *)my_hello));
3623 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3624 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3626 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3627 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3628 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3629 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3630 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3631 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3632 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3633 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3634 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3635 message_context.network_size = estimate_diameter();
3636 message_context.peer = &my_identity;
3637 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3638 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3640 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3641 GNUNET_free(find_peer_msg);
3642 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3643 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3645 if (newly_found_peers < bucket_size)
3647 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3648 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3649 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3653 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3654 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3655 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3658 GNUNET_assert (next_send_time.value != 0);
3659 find_peer_context.count = 0;
3660 newly_found_peers = 0;
3661 find_peer_context.start = GNUNET_TIME_absolute_get();
3662 if (GNUNET_YES == do_find_peer)
3664 GNUNET_SCHEDULER_add_delayed (sched,
3666 &send_find_peer_message, NULL);
3671 * Handler for any generic DHT messages, calls the appropriate handler
3672 * depending on message type, sends confirmation if responses aren't otherwise
3675 * @param cls closure for the service
3676 * @param client the client we received this message from
3677 * @param message the actual message received
3680 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3681 const struct GNUNET_MessageHeader *message)
3683 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3684 const struct GNUNET_MessageHeader *enc_msg;
3685 struct DHT_MessageContext message_context;
3686 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3689 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3690 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3691 GNUNET_ntohll (dht_msg->unique_id));
3693 #if DEBUG_DHT_ROUTING
3694 if (dhtlog_handle != NULL)
3695 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3697 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3698 message_context.client = find_active_client (client);
3699 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3700 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3701 message_context.replication = ntohl (dht_msg->desired_replication_level);
3702 message_context.msg_options = ntohl (dht_msg->options);
3703 message_context.network_size = estimate_diameter();
3704 message_context.peer = &my_identity;
3705 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3706 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3707 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3708 increment_stats(STAT_GET_START);
3709 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3710 increment_stats(STAT_PUT_START);
3711 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3712 increment_stats(STAT_FIND_PEER_START);
3714 route_message(cls, enc_msg, &message_context);
3716 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3721 * Handler for any locally received DHT control messages,
3722 * sets malicious flags mostly for now.
3724 * @param cls closure for the service
3725 * @param client the client we received this message from
3726 * @param message the actual message received
3730 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3731 const struct GNUNET_MessageHeader *message)
3733 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3734 (const struct GNUNET_DHT_ControlMessage *) message;
3736 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3737 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3738 "CONTROL", ntohs(dht_control_msg->command));
3741 switch (ntohs(dht_control_msg->command))
3743 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3744 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending self seeking find peer request!\n");
3745 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3747 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3748 if (ntohs(dht_control_msg->variable) > 0)
3749 malicious_get_frequency = ntohs(dht_control_msg->variable);
3750 if (malicious_get_frequency == 0)
3751 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3752 if (malicious_getter != GNUNET_YES)
3753 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3754 malicious_getter = GNUNET_YES;
3755 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3757 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3758 if (ntohs(dht_control_msg->variable) > 0)
3759 malicious_put_frequency = ntohs(dht_control_msg->variable);
3760 if (malicious_put_frequency == 0)
3761 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3762 if (malicious_putter != GNUNET_YES)
3763 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3764 malicious_putter = GNUNET_YES;
3765 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3767 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3768 #if DEBUG_DHT_ROUTING
3769 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3770 dhtlog_handle->set_malicious(&my_identity);
3772 malicious_dropper = GNUNET_YES;
3773 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3776 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3779 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3783 * Handler for any generic DHT stop messages, calls the appropriate handler
3784 * depending on message type (if processed locally)
3786 * @param cls closure for the service
3787 * @param client the client we received this message from
3788 * @param message the actual message received
3792 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3793 const struct GNUNET_MessageHeader *message)
3796 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3797 (const struct GNUNET_DHT_StopMessage *) message;
3798 struct DHTQueryRecord *record;
3799 struct DHTRouteSource *pos;
3801 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3802 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3803 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3805 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3812 if ((pos->client != NULL) && (pos->client->client_handle == client))
3814 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3815 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3821 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3826 * Core handler for p2p route requests.
3829 handle_dht_p2p_route_request (void *cls,
3830 const struct GNUNET_PeerIdentity *peer,
3831 const struct GNUNET_MessageHeader *message,
3832 struct GNUNET_TIME_Relative latency, uint32_t distance)
3835 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3836 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3838 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3839 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3840 struct DHT_MessageContext *message_context;
3842 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
3844 fprintf(stderr, "Sending of previous replies took far too long, backing off!\n");
3845 decrease_max_send_delay(get_max_send_delay());
3849 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3852 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3857 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
3862 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3863 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3864 GNUNET_assert(message_context->bloom != NULL);
3865 message_context->hop_count = ntohl(incoming->hop_count);
3866 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
3867 message_context->replication = ntohl(incoming->desired_replication_level);
3868 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3869 message_context->msg_options = ntohl(incoming->options);
3870 message_context->network_size = ntohl(incoming->network_size);
3871 message_context->peer = peer;
3872 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3873 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3874 route_message(cls, enc_msg, message_context);
3875 GNUNET_free(message_context);
3881 * Core handler for p2p route results.
3884 handle_dht_p2p_route_result (void *cls,
3885 const struct GNUNET_PeerIdentity *peer,
3886 const struct GNUNET_MessageHeader *message,
3887 struct GNUNET_TIME_Relative latency, uint32_t distance)
3890 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3891 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3893 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3894 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3895 struct DHT_MessageContext message_context;
3897 if (ntohs(enc_msg->size) >= GNUNET_SERVER_MAX_MESSAGE_SIZE - 1)
3903 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3904 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3905 GNUNET_assert(message_context.bloom != NULL);
3906 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
3907 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3908 message_context.msg_options = ntohl(incoming->options);
3909 message_context.hop_count = ntohl(incoming->hop_count);
3910 message_context.peer = peer;
3911 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3912 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3913 route_result_message(cls, enc_msg, &message_context);
3919 * Receive the HELLO from transport service,
3920 * free current and replace if necessary.
3923 * @param message HELLO message of peer
3926 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3929 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3930 "Received our `%s' from transport service\n",
3934 GNUNET_assert (message != NULL);
3935 GNUNET_free_non_null(my_hello);
3936 my_hello = GNUNET_malloc(ntohs(message->size));
3937 memcpy(my_hello, message, ntohs(message->size));
3942 * Task run during shutdown.
3948 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3951 struct PeerInfo *pos;
3952 if (transport_handle != NULL)
3954 GNUNET_free_non_null(my_hello);
3955 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3956 GNUNET_TRANSPORT_disconnect(transport_handle);
3959 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3961 while (k_buckets[bucket_count].head != NULL)
3963 pos = k_buckets[bucket_count].head;
3965 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3966 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3968 delete_peer(pos, bucket_count);
3971 if (coreAPI != NULL)
3974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3975 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3977 GNUNET_CORE_disconnect (coreAPI);
3979 if (datacache != NULL)
3982 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3983 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3985 GNUNET_DATACACHE_destroy (datacache);
3990 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3993 if (dhtlog_handle != NULL)
3994 GNUNET_DHTLOG_disconnect(dhtlog_handle);
3996 GNUNET_free_non_null(my_short_id);
4001 * To be called on core init/fail.
4003 * @param cls service closure
4004 * @param server handle to the server for this service
4005 * @param identity the public identity of this peer
4006 * @param publicKey the public key of this peer
4009 core_init (void *cls,
4010 struct GNUNET_CORE_Handle *server,
4011 const struct GNUNET_PeerIdentity *identity,
4012 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
4018 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4019 "%s: Connection to core FAILED!\n", "dht",
4020 GNUNET_i2s (identity));
4022 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
4023 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
4027 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4028 "%s: Core connection initialized, I am peer: %s\n", "dht",
4029 GNUNET_i2s (identity));
4032 /* Copy our identity so we can use it */
4033 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
4034 if (my_short_id != NULL)
4035 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
4036 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
4037 /* Set the server to local variable */
4040 if (dhtlog_handle != NULL)
4041 dhtlog_handle->insert_node (NULL, &my_identity);
4045 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
4046 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
4047 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
4048 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
4053 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
4054 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
4055 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
4060 * Method called whenever a peer connects.
4062 * @param cls closure
4063 * @param peer peer identity this notification is about
4064 * @param latency reported latency of the connection with peer
4065 * @param distance reported distance (DV) to peer
4067 void handle_core_connect (void *cls,
4068 const struct GNUNET_PeerIdentity * peer,
4069 struct GNUNET_TIME_Relative latency,
4072 struct PeerInfo *ret;
4075 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4076 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
4079 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4081 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received %s message for peer %s, but already have peer in RT!", my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s(peer));
4085 if (datacache != NULL)
4086 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
4087 ret = try_add_peer(peer,
4088 find_current_bucket(&peer->hashPubKey),
4093 newly_found_peers++;
4094 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
4097 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
4098 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
4103 * Method called whenever a peer disconnects.
4105 * @param cls closure
4106 * @param peer peer identity this notification is about
4108 void handle_core_disconnect (void *cls,
4110 GNUNET_PeerIdentity * peer)
4112 struct PeerInfo *to_remove;
4115 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s: Received peer disconnect message for peer `%s' from %s\n", my_short_id, "DHT", GNUNET_i2s(peer), "CORE");
4117 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
4119 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s: do not have peer `%s' in RT, can't disconnect!\n", my_short_id, "DHT", GNUNET_i2s(peer));
4122 increment_stats(STAT_DISCONNECTS);
4123 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
4124 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
4125 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
4126 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
4127 delete_peer(to_remove, current_bucket);
4131 * Process dht requests.
4133 * @param cls closure
4134 * @param scheduler scheduler to use
4135 * @param server the initialized server
4136 * @param c configuration to use
4140 struct GNUNET_SCHEDULER_Handle *scheduler,
4141 struct GNUNET_SERVER_Handle *server,
4142 const struct GNUNET_CONFIGURATION_Handle *c)
4144 struct GNUNET_TIME_Relative next_send_time;
4145 unsigned long long temp_config_num;
4146 char *converge_modifier_buf;
4149 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
4150 GNUNET_SERVER_add_handlers (server, plugin_handlers);
4151 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
4152 cfg, /* Main configuration */
4153 GNUNET_TIME_UNIT_FOREVER_REL,
4154 NULL, /* Closure passed to DHT functions */
4155 &core_init, /* Call core_init once connected */
4156 &handle_core_connect, /* Handle connects */
4157 &handle_core_disconnect, /* remove peers on disconnects */
4158 NULL, /* Do we care about "status" updates? */
4159 NULL, /* Don't want notified about all incoming messages */
4160 GNUNET_NO, /* For header only inbound notification */
4161 NULL, /* Don't want notified about all outbound messages */
4162 GNUNET_NO, /* For header only outbound notification */
4163 core_handlers); /* Register these handlers */
4165 if (coreAPI == NULL)
4167 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
4168 NULL, NULL, NULL, NULL, NULL);
4169 if (transport_handle != NULL)
4170 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
4172 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
4174 lowest_bucket = MAX_BUCKETS - 1;
4175 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
4176 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4177 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4178 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
4179 GNUNET_assert(all_known_peers != NULL);
4180 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
4182 debug_routes = GNUNET_YES;
4186 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4189 strict_kademlia = GNUNET_YES;
4193 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4196 stop_on_closest = GNUNET_YES;
4200 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4203 stop_on_found = GNUNET_YES;
4207 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4208 "malicious_getter"))
4210 malicious_getter = GNUNET_YES;
4211 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4212 "MALICIOUS_GET_FREQUENCY",
4213 &malicious_get_frequency))
4214 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
4217 if (GNUNET_YES != GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4221 max_hops = DEFAULT_MAX_HOPS;
4224 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno (cfg, "DHT",
4227 use_max_hops = GNUNET_YES;
4231 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4232 "malicious_putter"))
4234 malicious_putter = GNUNET_YES;
4235 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
4236 "MALICIOUS_PUT_FREQUENCY",
4237 &malicious_put_frequency))
4238 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
4241 dht_republish_frequency = DEFAULT_DHT_REPUBLISH_FREQUENCY;
4242 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cfg, "DHT", "REPLICATION_FREQUENCY", &temp_config_num))
4244 dht_republish_frequency = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, temp_config_num);
4248 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4249 "malicious_dropper"))
4251 malicious_dropper = GNUNET_YES;
4255 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4257 do_republish = GNUNET_NO;
4260 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4263 do_find_peer = GNUNET_NO;
4266 do_find_peer = GNUNET_YES;
4269 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
4270 "use_real_distance"))
4271 use_real_distance = GNUNET_YES;
4274 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4275 "mysql_logging_extended"))
4277 debug_routes = GNUNET_YES;
4278 debug_routes_extended = GNUNET_YES;
4281 #if DEBUG_DHT_ROUTING
4282 if (GNUNET_YES == debug_routes)
4284 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
4285 if (dhtlog_handle == NULL)
4287 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
4288 "Could not connect to mysql logging server, logging will not happen!");
4293 converge_option = DHT_CONVERGE_SQUARE;
4295 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4298 converge_option = DHT_CONVERGE_LINEAR;
4300 else if (GNUNET_YES ==
4301 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
4302 "converge_exponential"))
4304 converge_option = DHT_CONVERGE_EXPONENTIAL;
4307 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(cfg, "dht_testing", "converge_modifier", &converge_modifier_buf))
4309 if (1 != sscanf(converge_modifier_buf, "%f", &converge_modifier))
4311 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to read decimal value for %s from `%s'\n", "CONVERGE_MODIFIER", converge_modifier_buf);
4312 converge_modifier = 0.0;
4314 GNUNET_free(converge_modifier_buf);
4317 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
4321 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
4322 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
4323 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
4324 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
4325 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
4326 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
4327 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
4328 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
4329 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
4330 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
4331 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
4332 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
4333 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
4334 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
4335 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
4336 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
4337 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
4338 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
4339 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
4340 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
4342 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
4343 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
4344 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
4345 if (GNUNET_YES == do_find_peer)
4347 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
4348 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
4349 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
4350 find_peer_context.start = GNUNET_TIME_absolute_get();
4351 GNUNET_SCHEDULER_add_delayed (sched,
4353 &send_find_peer_message, &find_peer_context);
4356 /* Scheduled the task to clean up when shutdown is called */
4357 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
4358 GNUNET_TIME_UNIT_FOREVER_REL,
4359 &shutdown_task, NULL);
4363 * The main function for the dht service.
4365 * @param argc number of arguments from the command line
4366 * @param argv command line arguments
4367 * @return 0 ok, 1 on error
4370 main (int argc, char *const *argv)
4372 return (GNUNET_OK ==
4373 GNUNET_SERVICE_run (argc,
4376 GNUNET_SERVICE_OPTION_NONE,
4377 &run, NULL)) ? 0 : 1;