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 EXTRA_CHECKS GNUNET_NO
49 * How many buckets will we allow total.
51 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
54 * Should the DHT issue FIND_PEER requests to get better routing tables?
56 #define DO_FIND_PEER GNUNET_YES
59 * What is the maximum number of peers in a given bucket.
61 #define DEFAULT_BUCKET_SIZE 4
64 * Minimum number of peers we need for "good" routing,
65 * any less than this and we will allow messages to
66 * travel much further through the network!
68 #define MINIMUM_PEER_THRESHOLD 20
70 #define DHT_MAX_RECENT 100
72 #define FIND_PEER_CALC_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
75 * Default time to wait to send messages on behalf of other peers.
77 #define DHT_DEFAULT_P2P_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10)
80 * Default importance for handling messages on behalf of other peers.
82 #define DHT_DEFAULT_P2P_IMPORTANCE 0
85 * How long to keep recent requests arounds by default.
87 #define DEFAULT_RECENT_REMOVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 60)
90 * Default time to wait to send find peer messages sent by the dht service.
92 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30)
95 * Default importance for find peer messages sent by the dht service.
97 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
100 * Default replication parameter for find peer messages sent by the dht service.
102 #define DHT_DEFAULT_FIND_PEER_REPLICATION 2
105 * Default options for find peer requests sent by the dht service.
107 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_NONE
110 * How long at least to wait before sending another find peer request.
112 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
115 * How long at most to wait before sending another find peer request.
117 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 8)
120 * How often to update our preference levels for peers in our routing tables.
122 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
125 * How long at most on average will we allow a reply forward to take
126 * (before we quit sending out new requests)
128 #define MAX_REQUEST_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1)
131 * How many initial requests to send out (in true Kademlia fashion)
133 #define DHT_KADEMLIA_REPLICATION 3
136 * Default frequency for sending malicious get messages
138 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
141 * Default frequency for sending malicious put messages
143 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
146 * Type for a malicious request, so we can ignore it during testing
148 #define DHT_MALICIOUS_MESSAGE_TYPE 42
150 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
153 * Real maximum number of hops, at which point we refuse
154 * to forward the message.
159 * How many time differences between requesting a core send and
160 * the actual callback to remember.
162 #define MAX_REPLY_TIMES 8
165 * Linked list of messages to send to clients.
167 struct P2PPendingMessage
170 * Pointer to next item in the list
172 struct P2PPendingMessage *next;
175 * Pointer to previous item in the list
177 struct P2PPendingMessage *prev;
180 * Message importance level.
182 unsigned int importance;
185 * Time when this request was scheduled to be sent.
187 struct GNUNET_TIME_Absolute scheduled;
190 * How long to wait before sending message.
192 struct GNUNET_TIME_Relative timeout;
195 * Actual message to be sent; // avoid allocation
197 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
202 * Per-peer information.
207 * Next peer entry (DLL)
209 struct PeerInfo *next;
212 * Prev peer entry (DLL)
214 struct PeerInfo *prev;
217 * Head of pending messages to be sent to this peer.
219 struct P2PPendingMessage *head;
222 * Tail of pending messages to be sent to this peer.
224 struct P2PPendingMessage *tail;
227 * Core handle for sending messages to this peer.
229 struct GNUNET_CORE_TransmitHandle *th;
232 * Task for scheduling message sends.
234 GNUNET_SCHEDULER_TaskIdentifier send_task;
237 * Task for scheduling preference updates
239 GNUNET_SCHEDULER_TaskIdentifier preference_task;
242 * Preference update context
244 struct GNUNET_CORE_InformationRequestContext *info_ctx;
247 * What is the average latency for replies received?
249 struct GNUNET_TIME_Relative latency;
252 * Number of responses received
254 unsigned long long response_count;
257 * Number of requests sent
259 unsigned long long request_count;
262 * What is the identity of the peer?
264 struct GNUNET_PeerIdentity id;
267 * Transport level distance to peer.
269 unsigned int distance;
272 * Task for scheduling periodic ping messages for this peer.
274 GNUNET_SCHEDULER_TaskIdentifier ping_task;
278 * Peers are grouped into buckets.
285 struct PeerInfo *head;
290 struct PeerInfo *tail;
293 * Number of peers in the bucket.
295 unsigned int peers_size;
299 * Linked list of messages to send to clients.
301 struct PendingMessage
304 * Pointer to next item in the list
306 struct PendingMessage *next;
309 * Pointer to previous item in the list
311 struct PendingMessage *prev;
314 * Actual message to be sent; // avoid allocation
316 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
321 * Struct containing information about a client,
322 * handle to connect to it, and any pending messages
323 * that need to be sent to it.
328 * Linked list of active clients
330 struct ClientList *next;
333 * The handle to this client
335 struct GNUNET_SERVER_Client *client_handle;
338 * Handle to the current transmission request, NULL
341 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
344 * Linked list of pending messages for this client
346 struct PendingMessage *pending_head;
349 * Tail of linked list of pending messages for this client
351 struct PendingMessage *pending_tail;
356 * Context containing information about a DHT message received.
358 struct DHT_MessageContext
361 * The client this request was received from.
362 * (NULL if received from another peer)
364 struct ClientList *client;
367 * The peer this request was received from.
368 * (NULL if received from local client)
370 const struct GNUNET_PeerIdentity *peer;
373 * The key this request was about
378 * The unique identifier of this request
383 * Desired replication level
385 uint32_t replication;
388 * Network size estimate, either ours or the sum of
389 * those routed to thus far. =~ Log of number of peers
390 * chosen from for this request.
392 uint32_t network_size;
395 * Any message options for this request
397 uint32_t msg_options;
400 * How many hops has the message already traversed?
405 * How important is this message?
407 unsigned int importance;
410 * How long should we wait to transmit this request?
412 struct GNUNET_TIME_Relative timeout;
415 * Bloomfilter for this routing request.
417 struct GNUNET_CONTAINER_BloomFilter *bloom;
420 * Did we forward this message? (may need to remember it!)
425 * Are we the closest known peer to this key (out of our neighbors?)
431 * Record used for remembering what peers are waiting for what
432 * responses (based on search key).
434 struct DHTRouteSource
439 struct DHTRouteSource *next;
444 struct DHTRouteSource *prev;
447 * Source of the request. Replies should be forwarded to
450 struct GNUNET_PeerIdentity source;
453 * If this was a local request, remember the client; otherwise NULL.
455 struct ClientList *client;
458 * Pointer to this nodes heap location (for removal)
460 struct GNUNET_CONTAINER_HeapNode *hnode;
463 * Back pointer to the record storing this information.
465 struct DHTQueryRecord *record;
468 * Task to remove this entry on timeout.
470 GNUNET_SCHEDULER_TaskIdentifier delete_task;
473 * Bloomfilter of peers we have already sent back as
474 * replies to the initial request. Allows us to not
475 * forward the same peer multiple times for a find peer
478 struct GNUNET_CONTAINER_BloomFilter *find_peers_responded;
483 * Entry in the DHT routing table.
485 struct DHTQueryRecord
488 * Head of DLL for result forwarding.
490 struct DHTRouteSource *head;
493 * Tail of DLL for result forwarding.
495 struct DHTRouteSource *tail;
498 * Key that the record concerns.
503 * GET message of this record (what we already forwarded?).
505 //DV_DHT_MESSAGE get; Try to get away with not saving this.
508 * Bloomfilter of the peers we've replied to so far
510 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
515 * Context used to calculate the number of find peer messages
516 * per X time units since our last scheduled find peer message
517 * was sent. If we have seen too many messages, delay or don't
520 struct FindPeerMessageContext
524 struct GNUNET_TIME_Absolute start;
526 struct GNUNET_TIME_Absolute end;
530 * DHT Routing results structure
535 * Min heap for removal upon reaching limit
537 struct GNUNET_CONTAINER_Heap *minHeap;
540 * Hashmap for fast key based lookup
542 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
547 * DHT structure for recent requests.
549 struct RecentRequests
552 * Min heap for removal upon reaching limit
554 struct GNUNET_CONTAINER_Heap *minHeap;
557 * Hashmap for key based lookup
559 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
565 * Position of this node in the min heap.
567 struct GNUNET_CONTAINER_HeapNode *heap_node;
570 * Bloomfilter containing entries for peers
571 * we forwarded this request to.
573 struct GNUNET_CONTAINER_BloomFilter *bloom;
576 * Timestamp of this request, for ordering
579 struct GNUNET_TIME_Absolute timestamp;
582 * Key of this request.
587 * Unique identifier for this request.
592 * Task to remove this entry on timeout.
594 GNUNET_SCHEDULER_TaskIdentifier remove_task;
598 * Recent requests by hash/uid and by time inserted.
600 static struct RecentRequests recent;
603 * Context to use to calculate find peer rates.
605 static struct FindPeerMessageContext find_peer_context;
608 * Don't use our routing algorithm, always route
609 * to closest peer; initially send requests to 3
612 static int strict_kademlia;
615 * Routing option to end routing when closest peer found.
617 static int stop_on_closest;
620 * Routing option to end routing when data is found.
622 static int stop_on_found;
625 * Whether DHT needs to manage find peer requests, or
626 * an external force will do it on behalf of the DHT.
628 static int do_find_peer;
631 * How many peers have we added since we sent out our last
634 static unsigned int newly_found_peers;
637 * Container of active queries we should remember
639 static struct DHTResults forward_list;
642 * Handle to the datacache service (for inserting/retrieving data)
644 static struct GNUNET_DATACACHE_Handle *datacache;
647 * Handle for the statistics service.
649 struct GNUNET_STATISTICS_Handle *stats;
652 * The main scheduler to use for the DHT service
654 static struct GNUNET_SCHEDULER_Handle *sched;
657 * The configuration the DHT service is running with
659 static const struct GNUNET_CONFIGURATION_Handle *cfg;
662 * Handle to the core service
664 static struct GNUNET_CORE_Handle *coreAPI;
667 * Handle to the transport service, for getting our hello
669 static struct GNUNET_TRANSPORT_Handle *transport_handle;
672 * The identity of our peer.
674 static struct GNUNET_PeerIdentity my_identity;
677 * Short id of the peer, for printing
679 static char *my_short_id;
684 static struct GNUNET_MessageHeader *my_hello;
687 * Task to run when we shut down, cleaning up all our trash
689 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
692 * The lowest currently used bucket.
694 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
697 * The buckets (Kademlia routing table, complete with growth).
698 * Array of size MAX_BUCKET_SIZE.
700 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
703 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
705 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
708 * Recently seen find peer requests.
710 static struct GNUNET_CONTAINER_MultiHashMap *recent_find_peer_requests;
713 * Maximum size for each bucket.
715 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
718 * List of active clients.
720 static struct ClientList *client_list;
723 * Handle to the DHT logger.
725 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
728 * Whether or not to send routing debugging information
729 * to the dht logging server
731 static unsigned int debug_routes;
734 * Whether or not to send FULL route information to
737 static unsigned int debug_routes_extended;
740 * GNUNET_YES or GNUNET_NO, whether or not to act as
741 * a malicious node which drops all messages
743 static unsigned int malicious_dropper;
746 * GNUNET_YES or GNUNET_NO, whether or not to act as
747 * a malicious node which sends out lots of GETS
749 static unsigned int malicious_getter;
752 * GNUNET_YES or GNUNET_NO, whether or not to act as
753 * a malicious node which sends out lots of PUTS
755 static unsigned int malicious_putter;
758 * Frequency for malicious get requests.
760 static unsigned long long malicious_get_frequency;
763 * Frequency for malicious put requests.
765 static unsigned long long malicious_put_frequency;
768 * Reply times for requests, if we are busy, don't send any
771 static struct GNUNET_TIME_Relative reply_times[MAX_REPLY_TIMES];
774 * Current counter for replies.
776 static unsigned int reply_counter;
779 * Forward declaration.
781 static size_t send_generic_reply (void *cls, size_t size, void *buf);
783 /** Declare here so retry_core_send is aware of it */
784 size_t core_transmit_notify (void *cls,
785 size_t size, void *buf);
788 * Convert unique ID to hash code.
790 * @param uid unique ID to convert
791 * @param hash set to uid (extended with zeros)
794 hash_from_uid (uint64_t uid,
795 GNUNET_HashCode *hash)
797 memset (hash, 0, sizeof(GNUNET_HashCode));
798 *((uint64_t*)hash) = uid;
803 * Calculate the average send time between messages so that we can
804 * ignore certain requests if we get too busy.
806 * @return the average time between asking core to send a message
807 * and when the buffer for copying it is passed
809 static struct GNUNET_TIME_Relative get_average_send_delay()
812 unsigned int divisor;
813 struct GNUNET_TIME_Relative average_time;
814 average_time = GNUNET_TIME_relative_get_zero();
816 for (i = 0; i < MAX_REPLY_TIMES; i++)
818 average_time = GNUNET_TIME_relative_add(average_time, reply_times[i]);
819 if (reply_times[i].value == (uint64_t)0)
829 average_time = GNUNET_TIME_relative_divide(average_time, divisor);
830 fprintf(stderr, "Avg send delay: %u sends is %llu\n", divisor, (long long unsigned int)average_time.value);
836 * Find the maximum send time of the recently sent values.
838 * @return the average time between asking core to send a message
839 * and when the buffer for copying it is passed
841 static struct GNUNET_TIME_Relative get_max_send_delay()
844 struct GNUNET_TIME_Relative max_time;
845 max_time = GNUNET_TIME_relative_get_zero();
847 for (i = 0; i < MAX_REPLY_TIMES; i++)
849 if (reply_times[i].value > max_time.value)
850 max_time.value = reply_times[i].value;
853 if (max_time.value > MAX_REQUEST_TIME.value)
854 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Max send delay was %llu\n", (long long unsigned int)max_time.value);
859 increment_stats(const char *value)
863 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
868 * Try to send another message from our core send list
871 try_core_send (void *cls,
872 const struct GNUNET_SCHEDULER_TaskContext *tc)
874 struct PeerInfo *peer = cls;
875 struct P2PPendingMessage *pending;
878 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
880 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
883 if (peer->th != NULL)
884 return; /* Message send already in progress */
886 pending = peer->head;
889 ssize = ntohs(pending->msg->size);
891 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
892 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
893 "DHT", ssize, GNUNET_i2s(&peer->id));
895 pending->scheduled = GNUNET_TIME_absolute_get();
897 if (reply_counter >= MAX_REPLY_TIMES)
899 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
900 pending->timeout, &peer->id,
901 ssize, &core_transmit_notify, peer);
906 * Function called to send a request out to another peer.
907 * Called both for locally initiated requests and those
908 * received from other peers.
910 * @param cls DHT service closure argument
911 * @param msg the encapsulated message
912 * @param peer the peer to forward the message to
913 * @param msg_ctx the context of the message (hop count, bloom, etc.)
915 static void forward_result_message (void *cls,
916 const struct GNUNET_MessageHeader *msg,
917 struct PeerInfo *peer,
918 struct DHT_MessageContext *msg_ctx)
920 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
921 struct P2PPendingMessage *pending;
925 increment_stats(STAT_RESULT_FORWARDS);
926 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
927 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
928 psize = sizeof(struct P2PPendingMessage) + msize;
929 pending = GNUNET_malloc(psize);
930 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
931 pending->importance = DHT_SEND_PRIORITY;
932 pending->timeout = GNUNET_TIME_relative_get_forever();
933 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
934 result_message->header.size = htons(msize);
935 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
936 result_message->options = htonl(msg_ctx->msg_options);
937 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
938 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
939 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
940 memcpy(&result_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
941 memcpy(&result_message[1], msg, ntohs(msg->size));
943 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));
945 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
946 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
947 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
950 * Called when core is ready to send a message we asked for
951 * out to the destination.
953 * @param cls closure (NULL)
954 * @param size number of bytes available in buf
955 * @param buf where the callee should write the message
956 * @return number of bytes written to buf
958 size_t core_transmit_notify (void *cls,
959 size_t size, void *buf)
961 struct PeerInfo *peer = cls;
963 struct P2PPendingMessage *pending;
970 /* client disconnected */
972 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
977 if (peer->head == NULL)
982 pending = peer->head;
983 reply_times[reply_counter] = GNUNET_TIME_absolute_get_difference(pending->scheduled, GNUNET_TIME_absolute_get());
984 msize = ntohs(pending->msg->size);
988 memcpy (cbuf, pending->msg, msize);
989 GNUNET_CONTAINER_DLL_remove (peer->head,
993 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));
995 GNUNET_free (pending);
998 while (NULL != pending &&
999 (size - off >= (msize = ntohs (pending->msg->size))))
1001 #if DEBUG_DHT_ROUTING
1002 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);
1004 memcpy (&cbuf[off], pending->msg, msize);
1006 GNUNET_CONTAINER_DLL_remove (peer->head,
1009 GNUNET_free (pending);
1010 pending = peer->head;
1013 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
1014 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1016 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);
1022 * Determine how many low order bits match in two
1023 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
1024 * the first two lowest order bits, and therefore the
1025 * return value is two (NOT XOR distance, nor how many
1026 * bits match absolutely!).
1028 * @param first the first hashcode
1029 * @param second the hashcode to compare first to
1031 * @return the number of bits that match
1033 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
1037 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
1038 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
1040 return sizeof (GNUNET_HashCode) * 8;
1044 * Compute the distance between have and target as a 32-bit value.
1045 * Differences in the lower bits must count stronger than differences
1046 * in the higher bits.
1048 * @return 0 if have==target, otherwise a number
1049 * that is larger as the distance between
1050 * the two hash codes increases
1053 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
1055 unsigned int bucket;
1060 /* We have to represent the distance between two 2^9 (=512)-bit
1061 numbers as a 2^5 (=32)-bit number with "0" being used for the
1062 two numbers being identical; furthermore, we need to
1063 guarantee that a difference in the number of matching
1064 bits is always represented in the result.
1066 We use 2^32/2^9 numerical values to distinguish between
1067 hash codes that have the same LSB bit distance and
1068 use the highest 2^9 bits of the result to signify the
1069 number of (mis)matching LSB bits; if we have 0 matching
1070 and hence 512 mismatching LSB bits we return -1 (since
1071 512 itself cannot be represented with 9 bits) */
1073 /* first, calculate the most significant 9 bits of our
1074 result, aka the number of LSBs */
1075 bucket = matching_bits (target, have);
1076 /* bucket is now a value between 0 and 512 */
1078 return 0; /* perfect match */
1080 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1081 below, we'd end up with max+1 (overflow)) */
1083 /* calculate the most significant bits of the final result */
1084 msb = (512 - bucket) << (32 - 9);
1085 /* calculate the 32-9 least significant bits of the final result by
1086 looking at the differences in the 32-9 bits following the
1087 mismatching bit at 'bucket' */
1089 for (i = bucket + 1;
1090 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1092 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
1093 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1094 last bit set will be 31 -- if
1095 i does not reach 512 first... */
1101 * Return a number that is larger the closer the
1102 * "have" GNUNET_hash code is to the "target".
1104 * @return inverse distance metric, non-zero.
1105 * Must fudge the value if NO bits match.
1108 inverse_distance (const GNUNET_HashCode * target,
1109 const GNUNET_HashCode * have)
1111 if (matching_bits(target, have) == 0)
1112 return 1; /* Never return 0! */
1113 return ((unsigned int) -1) - distance (target, have);
1117 * Find the optimal bucket for this key, regardless
1118 * of the current number of buckets in use.
1120 * @param hc the hashcode to compare our identity to
1122 * @return the proper bucket index, or GNUNET_SYSERR
1123 * on error (same hashcode)
1125 static int find_bucket(const GNUNET_HashCode *hc)
1129 bits = matching_bits(&my_identity.hashPubKey, hc);
1130 if (bits == MAX_BUCKETS)
1131 return GNUNET_SYSERR;
1132 return MAX_BUCKETS - bits - 1;
1136 * Find which k-bucket this peer should go into,
1137 * taking into account the size of the k-bucket
1138 * array. This means that if more bits match than
1139 * there are currently buckets, lowest_bucket will
1142 * @param hc GNUNET_HashCode we are finding the bucket for.
1144 * @return the proper bucket index for this key,
1145 * or GNUNET_SYSERR on error (same hashcode)
1147 static int find_current_bucket(const GNUNET_HashCode *hc)
1150 actual_bucket = find_bucket(hc);
1152 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
1153 return GNUNET_SYSERR;
1154 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
1155 return lowest_bucket;
1157 return actual_bucket;
1162 * Find a routing table entry from a peer identity
1164 * @param peer the peer to look up
1166 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
1169 find_bucket_by_peer(const struct PeerInfo *peer)
1172 struct PeerInfo *pos;
1174 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
1176 pos = k_buckets[bucket].head;
1185 return GNUNET_SYSERR; /* No such peer. */
1191 * Print the complete routing table for this peer.
1194 print_routing_table ()
1197 struct PeerInfo *pos;
1198 char char_buf[30000];
1200 memset(char_buf, 0, sizeof(char_buf));
1202 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1203 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1204 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1206 pos = k_buckets[bucket].head;
1207 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1208 //fprintf(stderr, "Bucket %d:\n", bucket);
1211 //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));
1212 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));
1216 fprintf(stderr, "%s", char_buf);
1222 * Find a routing table entry from a peer identity
1224 * @param peer the peer identity to look up
1226 * @return the routing table entry, or NULL if not found
1228 static struct PeerInfo *
1229 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1232 struct PeerInfo *pos;
1233 bucket = find_current_bucket(&peer->hashPubKey);
1235 if (bucket == GNUNET_SYSERR)
1238 pos = k_buckets[bucket].head;
1241 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1245 return NULL; /* No such peer. */
1248 /* Forward declaration */
1250 update_core_preference (void *cls,
1251 const struct GNUNET_SCHEDULER_TaskContext *tc);
1253 * Function called with statistics about the given peer.
1255 * @param cls closure
1256 * @param peer identifies the peer
1257 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1258 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1259 * @param latency current latency estimate, "FOREVER" if we have been
1261 * @param amount set to the amount that was actually reserved or unreserved;
1262 * either the full requested amount or zero (no partial reservations)
1263 * @param preference current traffic preference for the given peer
1266 update_core_preference_finish (void *cls,
1268 GNUNET_PeerIdentity * peer,
1269 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1270 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1272 uint64_t preference)
1274 struct PeerInfo *peer_info = cls;
1275 peer_info->info_ctx = NULL;
1276 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1280 update_core_preference (void *cls,
1281 const struct GNUNET_SCHEDULER_TaskContext *tc)
1283 struct PeerInfo *peer = cls;
1284 uint64_t preference;
1286 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1291 preference = 2 << matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1292 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1294 GNUNET_TIME_relative_get_forever(),
1295 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1298 &update_core_preference_finish,
1303 * Really add a peer to a bucket (only do assertions
1306 * @param peer GNUNET_PeerIdentity of the peer to add
1307 * @param bucket the already figured out bucket to add
1309 * @param latency the core reported latency of this peer
1310 * @param distance the transport level distance to this peer
1312 * @return the newly added PeerInfo
1314 static struct PeerInfo *
1315 add_peer(const struct GNUNET_PeerIdentity *peer,
1316 unsigned int bucket,
1317 struct GNUNET_TIME_Relative latency,
1318 unsigned int distance)
1320 struct PeerInfo *new_peer;
1321 GNUNET_assert(bucket < MAX_BUCKETS);
1322 GNUNET_assert(peer != NULL);
1323 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1324 new_peer->latency = latency;
1325 new_peer->distance = distance;
1327 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1329 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1330 k_buckets[bucket].tail,
1331 k_buckets[bucket].tail,
1333 k_buckets[bucket].peers_size++;
1335 if ((matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1337 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1344 * Given a peer and its corresponding bucket,
1345 * remove it from that bucket. Does not free
1346 * the PeerInfo struct, nor cancel messages
1347 * or free messages waiting to be sent to this
1350 * @param peer the peer to remove
1351 * @param bucket the bucket the peer belongs to
1353 static void remove_peer (struct PeerInfo *peer,
1354 unsigned int bucket)
1356 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1357 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1358 k_buckets[bucket].tail,
1360 k_buckets[bucket].peers_size--;
1361 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1366 * Removes peer from a bucket, then frees associated
1367 * resources and frees peer.
1369 * @param peer peer to be removed and freed
1370 * @param bucket which bucket this peer belongs to
1372 static void delete_peer (struct PeerInfo *peer,
1373 unsigned int bucket)
1375 struct P2PPendingMessage *pos;
1376 struct P2PPendingMessage *next;
1378 struct PeerInfo *peer_pos;
1380 peer_pos = k_buckets[bucket].head;
1381 while ((peer_pos != NULL) && (peer_pos != peer))
1382 peer_pos = peer_pos->next;
1383 if (peer_pos == NULL)
1385 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1386 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));
1388 GNUNET_assert(peer_pos != NULL);
1390 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1392 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1393 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1394 if (peer->th != NULL)
1395 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1398 while (pos != NULL) /* Remove any pending messages for this peer */
1405 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1406 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1412 * Iterator over hash map entries.
1414 * @param cls closure
1415 * @param key current key code
1416 * @param value PeerInfo of the peer to move to new lowest bucket
1417 * @return GNUNET_YES if we should continue to
1421 static int move_lowest_bucket (void *cls,
1422 const GNUNET_HashCode * key,
1425 struct PeerInfo *peer = value;
1428 GNUNET_assert(lowest_bucket > 0);
1429 new_bucket = lowest_bucket - 1;
1430 remove_peer(peer, lowest_bucket);
1431 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1432 k_buckets[new_bucket].tail,
1433 k_buckets[new_bucket].tail,
1435 k_buckets[new_bucket].peers_size++;
1441 * The current lowest bucket is full, so change the lowest
1442 * bucket to the next lower down, and move any appropriate
1443 * entries in the current lowest bucket to the new bucket.
1445 static void enable_next_bucket()
1447 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1448 struct PeerInfo *pos;
1449 GNUNET_assert(lowest_bucket > 0);
1450 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1451 pos = k_buckets[lowest_bucket].head;
1454 fprintf(stderr, "Printing RT before new bucket\n");
1455 print_routing_table();
1457 /* Populate the array of peers which should be in the next lowest bucket */
1460 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1461 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1465 /* Remove peers from lowest bucket, insert into next lowest bucket */
1466 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1467 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1468 lowest_bucket = lowest_bucket - 1;
1470 fprintf(stderr, "Printing RT after new bucket\n");
1471 print_routing_table();
1476 * Find the closest peer in our routing table to the
1479 * @return The closest peer in our routing table to the
1480 * key, or NULL on error.
1482 static struct PeerInfo *
1483 find_closest_peer (const GNUNET_HashCode *hc)
1485 struct PeerInfo *pos;
1486 struct PeerInfo *current_closest;
1487 unsigned int lowest_distance;
1488 unsigned int temp_distance;
1492 lowest_distance = -1;
1494 if (k_buckets[lowest_bucket].peers_size == 0)
1497 current_closest = NULL;
1498 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1500 pos = k_buckets[bucket].head;
1502 while ((pos != NULL) && (count < bucket_size))
1504 temp_distance = distance(&pos->id.hashPubKey, hc);
1505 if (temp_distance <= lowest_distance)
1507 lowest_distance = temp_distance;
1508 current_closest = pos;
1514 GNUNET_assert(current_closest != NULL);
1515 return current_closest;
1520 * Function called to send a request out to another peer.
1521 * Called both for locally initiated requests and those
1522 * received from other peers.
1524 * @param cls DHT service closure argument (unused)
1525 * @param msg the encapsulated message
1526 * @param peer the peer to forward the message to
1527 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1529 static void forward_message (void *cls,
1530 const struct GNUNET_MessageHeader *msg,
1531 struct PeerInfo *peer,
1532 struct DHT_MessageContext *msg_ctx)
1534 struct GNUNET_DHT_P2PRouteMessage *route_message;
1535 struct P2PPendingMessage *pending;
1539 increment_stats(STAT_ROUTE_FORWARDS);
1541 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(&msg_ctx->key)))
1542 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1544 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1545 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1546 psize = sizeof(struct P2PPendingMessage) + msize;
1547 pending = GNUNET_malloc(psize);
1548 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1549 pending->importance = msg_ctx->importance;
1550 pending->timeout = msg_ctx->timeout;
1551 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1552 route_message->header.size = htons(msize);
1553 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1554 route_message->options = htonl(msg_ctx->msg_options);
1555 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1556 route_message->network_size = htonl(msg_ctx->network_size);
1557 route_message->desired_replication_level = htonl(msg_ctx->replication);
1558 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1559 if (msg_ctx->bloom != NULL)
1560 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1561 memcpy(&route_message->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
1562 memcpy(&route_message[1], msg, ntohs(msg->size));
1564 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));
1566 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1567 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1568 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1573 * Task used to send ping messages to peers so that
1574 * they don't get disconnected.
1576 * @param cls the peer to send a ping message to
1577 * @param tc context, reason, etc.
1580 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1582 struct PeerInfo *peer = cls;
1583 struct GNUNET_MessageHeader ping_message;
1584 struct DHT_MessageContext message_context;
1586 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1589 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1590 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1592 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1594 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1596 forward_message(NULL, &ping_message, peer, &message_context);
1597 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1601 * Schedule PING messages for the top X peers in each
1602 * bucket of the routing table (so core won't disconnect them!)
1604 void schedule_ping_messages()
1606 unsigned int bucket;
1608 struct PeerInfo *pos;
1609 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1611 pos = k_buckets[bucket].head;
1615 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1616 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1617 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1619 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1620 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1630 * Attempt to add a peer to our k-buckets.
1632 * @param peer, the peer identity of the peer being added
1634 * @return NULL if the peer was not added,
1635 * pointer to PeerInfo for new peer otherwise
1637 static struct PeerInfo *
1638 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1639 unsigned int bucket,
1640 struct GNUNET_TIME_Relative latency,
1641 unsigned int distance)
1644 struct PeerInfo *new_peer;
1645 peer_bucket = find_current_bucket(&peer->hashPubKey);
1646 if (peer_bucket == GNUNET_SYSERR)
1649 GNUNET_assert(peer_bucket >= lowest_bucket);
1650 new_peer = add_peer(peer, peer_bucket, latency, distance);
1652 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1653 enable_next_bucket();
1655 schedule_ping_messages();
1662 * Task run to check for messages that need to be sent to a client.
1664 * @param client a ClientList, containing the client and any messages to be sent to it
1667 process_pending_messages (struct ClientList *client)
1669 if (client->pending_head == NULL)
1671 if (client->transmit_handle != NULL)
1673 client->transmit_handle =
1674 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1675 ntohs (client->pending_head->msg->
1677 GNUNET_TIME_UNIT_FOREVER_REL,
1678 &send_generic_reply, client);
1682 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1683 * request. A ClientList is passed as closure, take the head of the list
1684 * and copy it into buf, which has the result of sending the message to the
1687 * @param cls closure to this call
1688 * @param size maximum number of bytes available to send
1689 * @param buf where to copy the actual message to
1691 * @return the number of bytes actually copied, 0 indicates failure
1694 send_generic_reply (void *cls, size_t size, void *buf)
1696 struct ClientList *client = cls;
1698 struct PendingMessage *reply;
1702 client->transmit_handle = NULL;
1705 /* client disconnected */
1709 while ( (NULL != (reply = client->pending_head)) &&
1710 (size >= off + (msize = ntohs (reply->msg->size))))
1712 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1713 client->pending_tail,
1715 memcpy (&cbuf[off], reply->msg, msize);
1716 GNUNET_free (reply);
1719 process_pending_messages (client);
1725 * Add a PendingMessage to the clients list of messages to be sent
1727 * @param client the active client to send the message to
1728 * @param pending_message the actual message to send
1731 add_pending_message (struct ClientList *client,
1732 struct PendingMessage *pending_message)
1734 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1735 client->pending_tail,
1736 client->pending_tail,
1738 process_pending_messages (client);
1745 * Called when a reply needs to be sent to a client, as
1746 * a result it found to a GET or FIND PEER request.
1748 * @param client the client to send the reply to
1749 * @param message the encapsulated message to send
1750 * @param uid the unique identifier of this request
1753 send_reply_to_client (struct ClientList *client,
1754 const struct GNUNET_MessageHeader *message,
1755 unsigned long long uid)
1757 struct GNUNET_DHT_RouteResultMessage *reply;
1758 struct PendingMessage *pending_message;
1762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1763 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1765 msize = ntohs (message->size);
1766 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1767 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1769 GNUNET_break_op (0);
1773 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1774 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1775 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1776 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1777 reply->header.size = htons (tsize);
1778 reply->unique_id = GNUNET_htonll (uid);
1779 memcpy (&reply[1], message, msize);
1781 add_pending_message (client, pending_message);
1785 * Consider whether or not we would like to have this peer added to
1786 * our routing table. Check whether bucket for this peer is full,
1787 * if so return negative; if not return positive. Since peers are
1788 * only added on CORE level connect, this doesn't actually add the
1789 * peer to the routing table.
1791 * @param peer the peer we are considering adding
1793 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1796 * FIXME: Think about making a context for this call so that we can
1797 * ping the oldest peer in the current bucket and consider
1798 * removing it in lieu of the new peer.
1800 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1804 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1805 return GNUNET_NO; /* We already know this peer (are connected even!) */
1806 bucket = find_current_bucket(&peer->hashPubKey);
1807 if (bucket == GNUNET_SYSERR)
1809 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1816 * Main function that handles whether or not to route a result
1817 * message to other peers, or to send to our local client.
1819 * @param msg the result message to be routed
1820 * @return the number of peers the message was routed to,
1821 * GNUNET_SYSERR on failure
1823 static int route_result_message(void *cls,
1824 struct GNUNET_MessageHeader *msg,
1825 struct DHT_MessageContext *message_context)
1827 struct GNUNET_PeerIdentity new_peer;
1828 struct DHTQueryRecord *record;
1829 struct DHTRouteSource *pos;
1830 struct PeerInfo *peer_info;
1831 const struct GNUNET_MessageHeader *hello_msg;
1833 increment_stats(STAT_RESULTS);
1835 * If a find peer result message is received and contains a valid
1836 * HELLO for another peer, offer it to the transport service.
1838 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1840 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1843 hello_msg = &msg[1];
1844 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1846 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1850 else /* We have a valid hello, and peer id stored in new_peer */
1852 find_peer_context.count++;
1853 increment_stats(STAT_FIND_PEER_REPLY);
1854 if (GNUNET_YES == consider_peer(&new_peer))
1856 increment_stats(STAT_HELLOS_PROVIDED);
1857 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1858 /* GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_UNIT_FOREVER_REL, &new_peer, NULL, NULL); */
1859 /* peer_request_connect call causes service to segfault */
1860 /* FIXME: Do we need this (peer_request_connect call)??? */
1865 if (malicious_dropper == GNUNET_YES)
1868 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &message_context->key);
1870 if (record == NULL) /* No record of this message! */
1873 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1874 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1875 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1877 #if DEBUG_DHT_ROUTING
1879 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1881 dhtlog_handle->insert_route (NULL,
1882 message_context->unique_id,
1884 message_context->hop_count,
1887 &message_context->key,
1888 message_context->peer, NULL);
1891 if (message_context->bloom != NULL)
1893 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1894 message_context->bloom = NULL;
1902 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT) /* If we have already forwarded this peer id, don't do it again! */
1904 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (pos->find_peers_responded, &new_peer.hashPubKey))
1906 increment_stats("# find peer responses NOT forwarded (bloom match)");
1911 GNUNET_CONTAINER_bloomfilter_add(pos->find_peers_responded, &new_peer.hashPubKey);
1914 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1918 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
1919 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1921 #if DEBUG_DHT_ROUTING
1922 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1924 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
1925 message_context->hop_count,
1926 GNUNET_YES, &my_identity, &message_context->key,
1927 message_context->peer, NULL);
1930 increment_stats(STAT_RESULTS_TO_CLIENT);
1931 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
1932 increment_stats(STAT_GET_REPLY);
1934 send_reply_to_client(pos->client, msg, message_context->unique_id);
1936 else /* Send to peer */
1938 peer_info = find_peer_by_id(&pos->source);
1939 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
1945 if (message_context->bloom == NULL)
1946 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1947 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
1948 if ((GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey)))
1951 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1952 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
1953 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1955 #if DEBUG_DHT_ROUTING
1956 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1958 dhtlog_handle->insert_route (NULL, message_context->unique_id,
1960 message_context->hop_count,
1961 GNUNET_NO, &my_identity, &message_context->key,
1962 message_context->peer, &pos->source);
1965 forward_result_message(cls, msg, peer_info, message_context);
1970 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1971 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
1972 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1978 if (message_context->bloom != NULL)
1979 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1984 * Iterator for local get request results,
1986 * @param cls closure for iterator, a DatacacheGetContext
1987 * @param exp when does this value expire?
1988 * @param key the key this data is stored under
1989 * @param size the size of the data identified by key
1990 * @param data the actual data
1991 * @param type the type of the data
1993 * @return GNUNET_OK to continue iteration, anything else
1994 * to stop iteration.
1997 datacache_get_iterator (void *cls,
1998 struct GNUNET_TIME_Absolute exp,
1999 const GNUNET_HashCode * key,
2000 uint32_t size, const char *data, uint32_t type)
2002 struct DHT_MessageContext *msg_ctx = cls;
2003 struct DHT_MessageContext *new_msg_ctx;
2004 struct GNUNET_DHT_GetResultMessage *get_result;
2006 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2007 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
2009 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2010 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
2012 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2013 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
2014 get_result->header.size =
2015 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
2016 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
2017 get_result->type = htons (type);
2018 memcpy (&get_result[1], data, size);
2019 new_msg_ctx->peer = &my_identity;
2020 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2021 new_msg_ctx->hop_count = 0;
2022 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
2023 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2024 increment_stats(STAT_GET_RESPONSE_START);
2025 route_result_message(cls, &get_result->header, new_msg_ctx);
2026 GNUNET_free(new_msg_ctx);
2027 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
2028 // datacache_get_ctx->unique_id);
2029 GNUNET_free (get_result);
2035 * Server handler for all dht get requests, look for data,
2036 * if found, send response either to clients or other peers.
2038 * @param cls closure for service
2039 * @param msg the actual get message
2040 * @param message_context struct containing pertinent information about the get request
2042 * @return number of items found for GET request
2045 handle_dht_get (void *cls,
2046 const struct GNUNET_MessageHeader *msg,
2047 struct DHT_MessageContext *message_context)
2049 const struct GNUNET_DHT_GetMessage *get_msg;
2051 unsigned int results;
2053 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
2054 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
2060 get_type = ntohs (get_msg->type);
2062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2063 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
2064 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
2065 message_context->unique_id);
2067 increment_stats(STAT_GETS);
2069 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
2072 if (datacache != NULL)
2074 GNUNET_DATACACHE_get (datacache, &message_context->key, get_type,
2075 &datacache_get_iterator, message_context);
2080 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2081 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
2082 results, "GET", message_context->unique_id);
2084 #if DEBUG_DHT_ROUTING
2085 if ((debug_routes) && (dhtlog_handle != NULL))
2087 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2088 message_context->hop_count, GNUNET_YES, &my_identity,
2089 &message_context->key);
2092 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2094 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2095 message_context->hop_count, GNUNET_YES,
2096 &my_identity, &message_context->key, message_context->peer,
2102 if (message_context->hop_count == 0) /* Locally initiated request */
2104 #if DEBUG_DHT_ROUTING
2105 if ((debug_routes) && (dhtlog_handle != NULL))
2107 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
2108 message_context->hop_count, GNUNET_NO, &my_identity,
2109 &message_context->key);
2118 remove_recent_find_peer(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2120 GNUNET_HashCode *key = cls;
2121 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent_find_peer_requests, key, key))
2128 * Server handler for initiating local dht find peer requests
2130 * @param cls closure for service
2131 * @param find_msg the actual find peer message
2132 * @param message_context struct containing pertinent information about the request
2136 handle_dht_find_peer (void *cls,
2137 const struct GNUNET_MessageHeader *find_msg,
2138 struct DHT_MessageContext *message_context)
2140 struct GNUNET_MessageHeader *find_peer_result;
2141 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
2142 struct DHT_MessageContext *new_msg_ctx;
2143 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
2146 GNUNET_HashCode *recent_hash;
2147 #if RESTRICT_FIND_PEER
2148 struct GNUNET_PeerIdentity peer_id;
2151 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
2153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2154 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
2155 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
2156 ntohs (find_msg->size),
2157 sizeof (struct GNUNET_MessageHeader));
2159 if (my_hello == NULL)
2162 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2163 "`%s': Our HELLO is null, can't return.\n",
2169 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2170 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
2172 increment_stats(STAT_BLOOM_FIND_PEER);
2173 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2174 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
2176 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
2178 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! */
2180 increment_stats("# dht find peer requests ignored (recently seen!)");
2184 #if RESTRICT_FIND_PEER
2186 * Use this check to only allow the peer to respond to find peer requests if
2187 * it would be beneficial to have the requesting peer in this peers routing
2188 * table. Can be used to thwart peers flooding the network with find peer
2189 * requests that we don't care about. However, if a new peer is joining
2190 * the network and has no other peers this is a problem (assume all buckets
2191 * full, no one will respond!).
2193 memcpy(&peer_id.hashPubKey, &message_context->key, sizeof(GNUNET_HashCode));
2194 if (GNUNET_NO == consider_peer(&peer_id))
2196 increment_stats("# dht find peer requests ignored (do not need!)");
2201 recent_hash = GNUNET_malloc(sizeof(GNUNET_HashCode));
2202 memcpy(recent_hash, &message_context->key, sizeof(GNUNET_HashCode));
2203 GNUNET_CONTAINER_multihashmap_put (recent_find_peer_requests, &message_context->key, NULL, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2204 GNUNET_SCHEDULER_add_delayed (sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 120), &remove_recent_find_peer, &recent_hash);
2206 /* Simplistic find_peer functionality, always return our hello */
2207 hello_size = ntohs(my_hello->size);
2208 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
2210 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
2212 GNUNET_break_op (0);
2216 find_peer_result = GNUNET_malloc (tsize);
2217 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
2218 find_peer_result->size = htons (tsize);
2219 memcpy (&find_peer_result[1], my_hello, hello_size);
2221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2222 "`%s': Sending hello size %d to requesting peer.\n",
2225 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
2226 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
2227 new_msg_ctx->peer = &my_identity;
2228 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2229 new_msg_ctx->hop_count = 0;
2230 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
2231 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
2232 increment_stats(STAT_FIND_PEER_ANSWER);
2233 route_result_message(cls, find_peer_result, new_msg_ctx);
2234 GNUNET_free(new_msg_ctx);
2235 #if DEBUG_DHT_ROUTING
2236 if ((debug_routes) && (dhtlog_handle != NULL))
2238 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2239 message_context->hop_count, GNUNET_YES, &my_identity,
2240 &message_context->key);
2243 GNUNET_free(find_peer_result);
2248 * Server handler for initiating local dht put requests
2250 * @param cls closure for service
2251 * @param msg the actual put message
2252 * @param message_context struct containing pertinent information about the request
2255 handle_dht_put (void *cls,
2256 const struct GNUNET_MessageHeader *msg,
2257 struct DHT_MessageContext *message_context)
2259 struct GNUNET_DHT_PutMessage *put_msg;
2263 GNUNET_assert (ntohs (msg->size) >=
2264 sizeof (struct GNUNET_DHT_PutMessage));
2267 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2268 put_type = ntohs (put_msg->type);
2270 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2273 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2275 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2276 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2277 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2279 #if DEBUG_DHT_ROUTING
2280 if (message_context->hop_count == 0) /* Locally initiated request */
2282 if ((debug_routes) && (dhtlog_handle != NULL))
2284 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2285 message_context->hop_count, GNUNET_NO, &my_identity,
2286 &message_context->key);
2291 if (message_context->closest != GNUNET_YES)
2294 #if DEBUG_DHT_ROUTING
2295 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2297 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2298 message_context->hop_count, GNUNET_YES,
2299 &my_identity, &message_context->key, message_context->peer,
2303 if ((debug_routes) && (dhtlog_handle != NULL))
2305 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2306 message_context->hop_count, GNUNET_YES, &my_identity,
2307 &message_context->key);
2311 increment_stats(STAT_PUTS_INSERTED);
2312 if (datacache != NULL)
2313 GNUNET_DATACACHE_put (datacache, &message_context->key, data_size,
2314 (char *) &put_msg[1], put_type,
2315 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2317 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2318 "`%s:%s': %s request received, but have no datacache!\n",
2319 my_short_id, "DHT", "PUT");
2323 * Estimate the diameter of the network based
2324 * on how many buckets are currently in use.
2325 * Concept here is that the diameter of the network
2326 * is roughly the distance a message must travel in
2327 * order to reach its intended destination. Since
2328 * at each hop we expect to get one bit closer, and
2329 * we have one bit per bucket, the number of buckets
2330 * in use should be the largest number of hops for
2331 * a sucessful message. (of course, this assumes we
2332 * know all peers in the network!)
2334 * @return ballpark diameter figure
2336 static unsigned int estimate_diameter()
2338 return MAX_BUCKETS - lowest_bucket;
2342 * To how many peers should we (on average)
2343 * forward the request to obtain the desired
2344 * target_replication count (on average).
2346 * Always 0, 1 or 2 (don't send, send once, split)
2349 get_forward_count (unsigned int hop_count, size_t target_replication)
2352 double target_count;
2353 double random_probability;
2355 uint32_t random_value;
2357 unsigned int target_value;
2358 unsigned int diameter;
2361 * If we are behaving in strict kademlia mode, send multiple initial requests,
2362 * but then only send to 1 or 0 peers based strictly on the number of hops.
2364 if (strict_kademlia == GNUNET_YES)
2367 return DHT_KADEMLIA_REPLICATION;
2368 else if (hop_count < MAX_HOPS)
2374 /* FIXME: the smaller we think the network is the more lenient we should be for
2375 * routing right? The estimation below only works if we think we have reasonably
2376 * full routing tables, which for our RR topologies may not be the case!
2378 diameter = estimate_diameter ();
2379 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2382 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2383 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2384 "DHT", estimate_diameter(), lowest_bucket);
2388 else if (hop_count > MAX_HOPS)
2391 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2392 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2399 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Replication %d, hop_count %u, diameter %u\n", target_replication, hop_count, diameter);
2400 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Numerator %f, denominator %f\n", (double)target_replication, ((double)target_replication * (hop_count + 1) + diameter));
2401 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2402 (double)target_replication / ((double)target_replication * (hop_count + 1) + diameter);
2403 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Target count is %f\n", target_count);
2404 random_probability = ((double)GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2405 RAND_MAX)) / RAND_MAX;
2406 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Random is %f\n", random_probability);
2409 //while (target_value < target_count)
2410 if (target_value < target_count)
2411 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? */
2414 //if ((target_count + 1 - (double)target_value) > random_probability)
2415 if ((target_count) > random_probability)
2419 random_value = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, target_replication * (hop_count + 1) + diameter) + 1;
2420 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));
2422 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "random %u, target %u, max %u\n", random_value, target_replication, target_replication * (hop_count + 1) + diameter);
2423 if (random_value < target_replication)
2426 return target_value;
2430 * Check whether my identity is closer than any known peers.
2431 * If a non-null bloomfilter is given, check if this is the closest
2432 * peer that hasn't already been routed to.
2434 * @param target hash code to check closeness to
2435 * @param bloom bloomfilter, exclude these entries from the decision
2437 * Return GNUNET_YES if node location is closest, GNUNET_NO
2441 am_closest_peer (const GNUNET_HashCode * target, struct GNUNET_CONTAINER_BloomFilter *bloom)
2447 struct PeerInfo *pos;
2448 #if INTEGER_DISTANCE
2449 unsigned int my_distance;
2451 bucket_num = find_current_bucket(target);
2452 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2455 bits = matching_bits(&my_identity.hashPubKey, target);
2456 #if INTEGER_DISTANCE
2457 my_distance = distance(&my_identity.hashPubKey, target);
2459 pos = k_buckets[bucket_num].head;
2461 while ((pos != NULL) && (count < bucket_size))
2463 if ((bloom != NULL) && (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(bloom, &pos->id.hashPubKey)))
2466 continue; /* Skip already checked entries */
2469 other_bits = matching_bits(&pos->id.hashPubKey, target);
2470 if (other_bits > bits)
2472 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2475 /* FIXME: why not just return GNUNET_YES here? We are certainly close. */
2476 /*if (distance(&pos->id.hashPubKey, target) < my_distance)
2483 GNUNET_GE_LOG (coreAPI->ectx,
2484 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2485 GNUNET_GE_BULK, "closest peer\n");
2486 printPeerBits (&closest);
2487 GNUNET_GE_LOG (coreAPI->ectx,
2488 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2489 GNUNET_GE_BULK, "me\n");
2490 printPeerBits (coreAPI->my_identity);
2491 GNUNET_GE_LOG (coreAPI->ectx,
2492 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2493 GNUNET_GE_BULK, "key\n");
2494 printKeyBits (target);
2495 GNUNET_GE_LOG (coreAPI->ectx,
2496 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2498 "closest peer inverse distance is %u, mine is %u\n",
2499 inverse_distance (target, &closest.hashPubKey),
2500 inverse_distance (target,
2501 &coreAPI->my_identity->hashPubKey));
2504 /* No peers closer, we are the closest! */
2510 * Select a peer from the routing table that would be a good routing
2511 * destination for sending a message for "target". The resulting peer
2512 * must not be in the set of blocked peers.<p>
2514 * Note that we should not ALWAYS select the closest peer to the
2515 * target, peers further away from the target should be chosen with
2516 * exponentially declining probability.
2518 * @param target the key we are selecting a peer to route to
2519 * @param bloom a bloomfilter containing entries this request has seen already
2521 * @return Peer to route to, or NULL on error
2523 static struct PeerInfo *
2524 select_peer (const GNUNET_HashCode * target,
2525 struct GNUNET_CONTAINER_BloomFilter *bloom)
2527 unsigned int distance;
2530 struct PeerInfo *pos;
2531 struct PeerInfo *chosen;
2532 unsigned long long largest_distance;
2533 unsigned long long total_distance;
2534 unsigned long long selected;
2536 if (strict_kademlia == GNUNET_YES)
2538 largest_distance = 0;
2540 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2542 pos = k_buckets[bc].head;
2544 while ((pos != NULL) && (count < bucket_size))
2546 /* If we are doing strict Kademlia like routing, then checking the bloomfilter is basically cheating! */
2547 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2549 distance = inverse_distance (target, &pos->id.hashPubKey);
2550 if (distance > largest_distance)
2553 largest_distance = distance;
2561 if ((largest_distance > 0) && (chosen != NULL))
2563 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2575 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2577 pos = k_buckets[bc].head;
2579 while ((pos != NULL) && (count < bucket_size))
2581 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2582 total_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2584 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2585 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2586 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2592 if (total_distance == 0)
2597 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2598 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2600 pos = k_buckets[bc].head;
2602 while ((pos != NULL) && (count < bucket_size))
2604 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2606 distance = inverse_distance (target, &pos->id.hashPubKey);
2607 if (distance > selected)
2609 selected -= distance;
2614 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2615 "`%s:%s': peer %s matches bloomfilter.\n",
2616 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2624 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2625 "`%s:%s': peer %s matches bloomfilter.\n",
2626 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2633 * Task used to remove recent entries, either
2634 * after timeout, when full, or on shutdown.
2636 * @param cls the entry to remove
2637 * @param tc context, reason, etc.
2640 remove_recent (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2642 struct RecentRequest *req = cls;
2643 static GNUNET_HashCode hash;
2645 GNUNET_assert(req != NULL);
2646 hash_from_uid(req->uid, &hash);
2647 GNUNET_assert (GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(recent.hashmap, &hash, req));
2648 GNUNET_CONTAINER_heap_remove_node(recent.minHeap, req->heap_node);
2649 GNUNET_CONTAINER_bloomfilter_free(req->bloom);
2652 if ((tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN) && (0 == GNUNET_CONTAINER_multihashmap_size(recent.hashmap)) && (0 == GNUNET_CONTAINER_heap_get_size(recent.minHeap)))
2654 GNUNET_CONTAINER_multihashmap_destroy(recent.hashmap);
2655 GNUNET_CONTAINER_heap_destroy(recent.minHeap);
2661 * Task used to remove forwarding entries, either
2662 * after timeout, when full, or on shutdown.
2664 * @param cls the entry to remove
2665 * @param tc context, reason, etc.
2668 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2670 struct DHTRouteSource *source_info = cls;
2671 struct DHTQueryRecord *record;
2672 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2673 record = source_info->record;
2674 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2676 if (record->head == NULL) /* No more entries in DLL */
2678 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2679 GNUNET_free(record);
2681 if (source_info->find_peers_responded != NULL)
2682 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
2683 GNUNET_free(source_info);
2687 * Remember this routing request so that if a reply is
2688 * received we can either forward it to the correct peer
2689 * or return the result locally.
2691 * @param cls DHT service closure
2692 * @param msg_ctx Context of the route request
2694 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2696 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2698 struct DHTQueryRecord *record;
2699 struct DHTRouteSource *source_info;
2700 struct DHTRouteSource *pos;
2701 struct GNUNET_TIME_Absolute now;
2702 unsigned int current_size;
2704 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2705 while (current_size >= MAX_OUTSTANDING_FORWARDS)
2707 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2708 GNUNET_assert(source_info != NULL);
2709 record = source_info->record;
2710 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2711 if (record->head == NULL) /* No more entries in DLL */
2713 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2714 GNUNET_free(record);
2716 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2717 if (source_info->find_peers_responded != NULL)
2718 GNUNET_CONTAINER_bloomfilter_free(source_info->find_peers_responded);
2719 GNUNET_free(source_info);
2720 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2722 now = GNUNET_TIME_absolute_get();
2723 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &msg_ctx->key);
2724 if (record != NULL) /* Already know this request! */
2729 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
2730 break; /* Already have this peer in reply list! */
2733 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
2735 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
2741 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
2742 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, &msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2743 memcpy(&record->key, &msg_ctx->key, sizeof(GNUNET_HashCode));
2746 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
2747 source_info->record = record;
2748 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
2749 source_info->find_peers_responded = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2750 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
2751 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
2752 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
2754 source_info->client = msg_ctx->client;
2755 now = GNUNET_TIME_absolute_get_forever();
2757 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
2759 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2760 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
2761 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
2768 * Main function that handles whether or not to route a message to other
2771 * @param cls closure for dht service (NULL)
2772 * @param msg the message to be routed
2773 * @param message_context the context containing all pertinent information about the message
2775 * @return the number of peers the message was routed to,
2776 * GNUNET_SYSERR on failure
2778 static int route_message(void *cls,
2779 const struct GNUNET_MessageHeader *msg,
2780 struct DHT_MessageContext *message_context)
2784 struct PeerInfo *selected;
2785 #if DEBUG_DHT_ROUTING > 1
2786 struct PeerInfo *nearest;
2788 unsigned int forward_count;
2789 struct RecentRequest *recent_req;
2790 GNUNET_HashCode unique_hash;
2791 char *stat_forward_count;
2792 #if DEBUG_DHT_ROUTING
2796 if (malicious_dropper == GNUNET_YES)
2798 #if DEBUG_DHT_ROUTING
2799 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2801 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2802 message_context->hop_count, GNUNET_SYSERR,
2803 &my_identity, &message_context->key, message_context->peer,
2807 if (message_context->bloom != NULL)
2808 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2812 increment_stats(STAT_ROUTES);
2813 /* Semantics of this call means we find whether we are the closest peer out of those already
2814 * routed to on this messages path.
2816 global_closest = am_closest_peer(&message_context->key, NULL);
2817 message_context->closest = am_closest_peer(&message_context->key, message_context->bloom);
2818 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
2819 GNUNET_asprintf(&stat_forward_count, "# forward counts of %d", forward_count);
2820 increment_stats(stat_forward_count);
2821 GNUNET_free(stat_forward_count);
2822 if (message_context->bloom == NULL)
2823 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2825 if ((stop_on_closest == GNUNET_YES) && (global_closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
2828 #if DEBUG_DHT_ROUTING
2829 if (forward_count == 0)
2830 ret = GNUNET_SYSERR;
2834 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2836 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2837 message_context->hop_count, ret,
2838 &my_identity, &message_context->key, message_context->peer,
2843 switch (ntohs(msg->type))
2845 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
2846 cache_response (cls, message_context);
2847 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
2850 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
2851 increment_stats(STAT_PUTS);
2852 message_context->closest = global_closest;
2853 handle_dht_put (cls, msg, message_context);
2855 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
2856 increment_stats(STAT_FIND_PEER);
2857 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
2859 cache_response (cls, message_context);
2860 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
2861 handle_dht_find_peer (cls, msg, message_context);
2863 #if DEBUG_DHT_ROUTING
2864 if (message_context->hop_count == 0) /* Locally initiated request */
2866 if ((debug_routes) && (dhtlog_handle != NULL))
2868 dhtlog_handle->insert_dhtkey(NULL, &message_context->key);
2869 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2870 message_context->hop_count, GNUNET_NO, &my_identity,
2871 &message_context->key);
2877 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2878 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
2881 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2882 hash_from_uid(message_context->unique_id, &unique_hash);
2883 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent.hashmap, &unique_hash))
2885 recent_req = GNUNET_CONTAINER_multihashmap_get(recent.hashmap, &unique_hash);
2886 GNUNET_assert(recent_req != NULL);
2887 if (0 != memcmp(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode)))
2888 increment_stats(STAT_DUPLICATE_UID);
2891 increment_stats(STAT_RECENT_SEEN);
2892 GNUNET_CONTAINER_bloomfilter_or2(message_context->bloom, recent_req->bloom, DHT_BLOOM_SIZE);
2897 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
2898 recent_req->uid = message_context->unique_id;
2899 memcpy(&recent_req->key, &message_context->key, sizeof(GNUNET_HashCode));
2900 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
2901 recent_req->heap_node = GNUNET_CONTAINER_heap_insert(recent.minHeap, recent_req, GNUNET_TIME_absolute_get().value);
2902 recent_req->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2903 GNUNET_CONTAINER_multihashmap_put(recent.hashmap, &unique_hash, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2906 if (GNUNET_CONTAINER_multihashmap_size(recent.hashmap) > DHT_MAX_RECENT)
2908 recent_req = GNUNET_CONTAINER_heap_peek(recent.minHeap);
2909 GNUNET_assert(recent_req != NULL);
2910 GNUNET_SCHEDULER_cancel(sched, recent_req->remove_task);
2911 GNUNET_SCHEDULER_add_now(sched, &remove_recent, recent_req);
2914 for (i = 0; i < forward_count; i++)
2916 selected = select_peer(&message_context->key, message_context->bloom);
2918 if (selected != NULL)
2920 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
2921 #if DEBUG_DHT_ROUTING > 1
2922 nearest = find_closest_peer(&message_context->key);
2923 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
2924 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2925 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
2926 "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));
2927 GNUNET_free(nearest_buf);
2929 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2931 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2932 message_context->hop_count, GNUNET_NO,
2933 &my_identity, &message_context->key, message_context->peer,
2936 forward_message(cls, msg, selected, message_context);
2941 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2942 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
2947 #if DEBUG_DHT_ROUTING > 1
2948 if (forward_count == 0)
2950 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2951 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
2952 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2956 if (message_context->bloom != NULL)
2958 GNUNET_CONTAINER_bloomfilter_or2(recent_req->bloom, message_context->bloom, DHT_BLOOM_SIZE);
2959 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2962 return forward_count;
2966 * Find a client if it exists, add it otherwise.
2968 * @param client the server handle to the client
2970 * @return the client if found, a new client otherwise
2972 static struct ClientList *
2973 find_active_client (struct GNUNET_SERVER_Client *client)
2975 struct ClientList *pos = client_list;
2976 struct ClientList *ret;
2980 if (pos->client_handle == client)
2985 ret = GNUNET_malloc (sizeof (struct ClientList));
2986 ret->client_handle = client;
2987 ret->next = client_list;
2993 * Task to send a malicious put message across the network.
2995 * @param cls closure for this task
2996 * @param tc the context under which the task is running
2999 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3001 static struct GNUNET_DHT_PutMessage put_message;
3002 static struct DHT_MessageContext message_context;
3003 static GNUNET_HashCode key;
3004 uint32_t random_key;
3006 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3009 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
3010 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
3011 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3012 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
3013 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3014 message_context.client = NULL;
3015 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3016 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3017 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3018 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3019 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3020 message_context.msg_options = ntohl (0);
3021 message_context.network_size = estimate_diameter();
3022 message_context.peer = &my_identity;
3023 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3024 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3025 if (dhtlog_handle != NULL)
3026 dhtlog_handle->insert_dhtkey(NULL, &key);
3027 increment_stats(STAT_PUT_START);
3028 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3029 route_message(NULL, &put_message.header, &message_context);
3030 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
3035 * Task to send a malicious put message across the network.
3037 * @param cls closure for this task
3038 * @param tc the context under which the task is running
3041 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3043 static struct GNUNET_DHT_GetMessage get_message;
3044 struct DHT_MessageContext message_context;
3045 static GNUNET_HashCode key;
3046 uint32_t random_key;
3048 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3051 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
3052 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
3053 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
3054 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3055 message_context.client = NULL;
3056 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
3057 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
3058 memcpy(&message_context.key, &key, sizeof(GNUNET_HashCode));
3059 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
3060 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
3061 message_context.msg_options = ntohl (0);
3062 message_context.network_size = estimate_diameter();
3063 message_context.peer = &my_identity;
3064 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
3065 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3066 if (dhtlog_handle != NULL)
3067 dhtlog_handle->insert_dhtkey(NULL, &key);
3068 increment_stats(STAT_GET_START);
3069 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
3070 route_message (NULL, &get_message.header, &message_context);
3071 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
3075 * Iterator over hash map entries.
3077 * @param cls closure
3078 * @param key current key code
3079 * @param value value in the hash map
3080 * @return GNUNET_YES if we should continue to
3085 add_known_to_bloom (void *cls,
3086 const GNUNET_HashCode * key,
3089 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
3090 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
3095 * Task to send a find peer message for our own peer identifier
3096 * so that we can find the closest peers in the network to ourselves
3097 * and attempt to connect to them.
3099 * @param cls closure for this task
3100 * @param tc the context under which the task is running
3103 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3105 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
3106 struct DHT_MessageContext message_context;
3108 struct GNUNET_TIME_Relative next_send_time;
3109 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
3111 struct GNUNET_TIME_Relative time_diff;
3112 struct GNUNET_TIME_Absolute end;
3114 double count_per_interval;
3116 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
3119 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! */
3121 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Have %d newly found peers since last find peer message sent!\n", newly_found_peers);
3122 GNUNET_SCHEDULER_add_delayed (sched,
3123 GNUNET_TIME_UNIT_MINUTES,
3124 &send_find_peer_message, NULL);
3125 newly_found_peers = 0;
3129 increment_stats(STAT_FIND_PEER_START);
3131 end = GNUNET_TIME_absolute_get();
3132 time_diff = GNUNET_TIME_absolute_get_difference(find_peer_context.start, end);
3134 if (time_diff.value > FIND_PEER_CALC_INTERVAL.value)
3136 multiplier = time_diff.value / FIND_PEER_CALC_INTERVAL.value;
3137 count_per_interval = find_peer_context.count / multiplier;
3141 multiplier = FIND_PEER_CALC_INTERVAL.value / time_diff.value;
3142 count_per_interval = find_peer_context.count * multiplier;
3146 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
3147 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
3148 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
3149 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3150 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
3151 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
3152 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3153 memcpy(&message_context.key, &my_identity.hashPubKey, sizeof(GNUNET_HashCode));
3154 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
3155 message_context.replication = DHT_DEFAULT_FIND_PEER_REPLICATION;
3156 message_context.msg_options = DHT_DEFAULT_FIND_PEER_OPTIONS;
3157 message_context.network_size = estimate_diameter();
3158 message_context.peer = &my_identity;
3159 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
3160 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
3162 ret = route_message(NULL, &find_peer_msg->header, &message_context);
3163 GNUNET_free(find_peer_msg);
3164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3165 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
3167 if (newly_found_peers < bucket_size)
3169 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
3170 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3171 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
3175 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3176 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3177 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3180 GNUNET_assert (next_send_time.value != 0);
3181 find_peer_context.count = 0;
3182 newly_found_peers = 0;
3183 find_peer_context.start = GNUNET_TIME_absolute_get();
3184 if (GNUNET_YES == do_find_peer)
3186 GNUNET_SCHEDULER_add_delayed (sched,
3188 &send_find_peer_message, NULL);
3193 * Handler for any generic DHT messages, calls the appropriate handler
3194 * depending on message type, sends confirmation if responses aren't otherwise
3197 * @param cls closure for the service
3198 * @param client the client we received this message from
3199 * @param message the actual message received
3202 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
3203 const struct GNUNET_MessageHeader *message)
3205 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
3206 const struct GNUNET_MessageHeader *enc_msg;
3207 struct DHT_MessageContext message_context;
3208 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
3210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3211 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
3212 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
3213 GNUNET_ntohll (dht_msg->unique_id));
3215 #if DEBUG_DHT_ROUTING
3216 if (dhtlog_handle != NULL)
3217 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
3219 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3220 message_context.client = find_active_client (client);
3221 memcpy(&message_context.key, &dht_msg->key, sizeof(GNUNET_HashCode));
3222 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
3223 message_context.replication = ntohl (dht_msg->desired_replication_level);
3224 message_context.msg_options = ntohl (dht_msg->options);
3225 message_context.network_size = estimate_diameter();
3226 message_context.peer = &my_identity;
3227 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
3228 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3229 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
3230 increment_stats(STAT_GET_START);
3231 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
3232 increment_stats(STAT_PUT_START);
3233 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
3234 increment_stats(STAT_FIND_PEER_START);
3236 route_message(cls, enc_msg, &message_context);
3238 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3243 * Handler for any locally received DHT control messages,
3244 * sets malicious flags mostly for now.
3246 * @param cls closure for the service
3247 * @param client the client we received this message from
3248 * @param message the actual message received
3252 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
3253 const struct GNUNET_MessageHeader *message)
3255 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
3256 (const struct GNUNET_DHT_ControlMessage *) message;
3258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3259 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
3260 "CONTROL", ntohs(dht_control_msg->command));
3263 switch (ntohs(dht_control_msg->command))
3265 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER:
3266 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Sending self seeking find peer request!\n");
3267 GNUNET_SCHEDULER_add_now(sched, &send_find_peer_message, NULL);
3269 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
3270 if (ntohs(dht_control_msg->variable) > 0)
3271 malicious_get_frequency = ntohs(dht_control_msg->variable);
3272 if (malicious_get_frequency == 0)
3273 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3274 if (malicious_getter != GNUNET_YES)
3275 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
3276 malicious_getter = GNUNET_YES;
3277 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
3279 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
3280 if (ntohs(dht_control_msg->variable) > 0)
3281 malicious_put_frequency = ntohs(dht_control_msg->variable);
3282 if (malicious_put_frequency == 0)
3283 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3284 if (malicious_putter != GNUNET_YES)
3285 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
3286 malicious_putter = GNUNET_YES;
3287 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
3289 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
3290 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
3291 dhtlog_handle->set_malicious(&my_identity);
3292 malicious_dropper = GNUNET_YES;
3293 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
3296 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
3299 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3303 * Handler for any generic DHT stop messages, calls the appropriate handler
3304 * depending on message type (if processed locally)
3306 * @param cls closure for the service
3307 * @param client the client we received this message from
3308 * @param message the actual message received
3312 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
3313 const struct GNUNET_MessageHeader *message)
3316 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
3317 (const struct GNUNET_DHT_StopMessage *) message;
3318 struct DHTQueryRecord *record;
3319 struct DHTRouteSource *pos;
3321 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3322 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
3323 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
3325 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
3332 if ((pos->client != NULL) && (pos->client->client_handle == client))
3334 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
3335 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
3341 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3346 * Core handler for p2p route requests.
3349 handle_dht_p2p_route_request (void *cls,
3350 const struct GNUNET_PeerIdentity *peer,
3351 const struct GNUNET_MessageHeader *message,
3352 struct GNUNET_TIME_Relative latency, uint32_t distance)
3355 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3356 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3358 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3359 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3360 struct DHT_MessageContext *message_context;
3362 if (get_max_send_delay().value > MAX_REQUEST_TIME.value)
3364 fprintf(stderr, "Sending of previous requests has taken far too long, backing off!\n");
3368 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3371 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3376 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3381 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3382 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3383 GNUNET_assert(message_context->bloom != NULL);
3384 message_context->hop_count = ntohl(incoming->hop_count);
3385 memcpy(&message_context->key, &incoming->key, sizeof(GNUNET_HashCode));
3386 message_context->replication = ntohl(incoming->desired_replication_level);
3387 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3388 message_context->msg_options = ntohl(incoming->options);
3389 message_context->network_size = ntohl(incoming->network_size);
3390 message_context->peer = peer;
3391 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3392 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3393 route_message(cls, enc_msg, message_context);
3394 GNUNET_free(message_context);
3400 * Core handler for p2p route results.
3403 handle_dht_p2p_route_result (void *cls,
3404 const struct GNUNET_PeerIdentity *peer,
3405 const struct GNUNET_MessageHeader *message,
3406 struct GNUNET_TIME_Relative latency, uint32_t distance)
3409 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3410 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3412 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3413 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3414 struct DHT_MessageContext message_context;
3416 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3422 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3423 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3424 GNUNET_assert(message_context.bloom != NULL);
3425 memcpy(&message_context.key, &incoming->key, sizeof(GNUNET_HashCode));
3426 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3427 message_context.msg_options = ntohl(incoming->options);
3428 message_context.hop_count = ntohl(incoming->hop_count);
3429 message_context.peer = peer;
3430 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3431 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3432 route_result_message(cls, enc_msg, &message_context);
3438 * Receive the HELLO from transport service,
3439 * free current and replace if necessary.
3442 * @param message HELLO message of peer
3445 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3448 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3449 "Received our `%s' from transport service\n",
3453 GNUNET_assert (message != NULL);
3454 GNUNET_free_non_null(my_hello);
3455 my_hello = GNUNET_malloc(ntohs(message->size));
3456 memcpy(my_hello, message, ntohs(message->size));
3461 * Task run during shutdown.
3467 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3470 struct PeerInfo *pos;
3471 if (transport_handle != NULL)
3473 GNUNET_free_non_null(my_hello);
3474 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3475 GNUNET_TRANSPORT_disconnect(transport_handle);
3478 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3480 while (k_buckets[bucket_count].head != NULL)
3482 pos = k_buckets[bucket_count].head;
3484 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3485 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3487 delete_peer(pos, bucket_count);
3490 if (coreAPI != NULL)
3493 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3494 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3496 GNUNET_CORE_disconnect (coreAPI);
3498 if (datacache != NULL)
3501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3502 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3504 GNUNET_DATACACHE_destroy (datacache);
3509 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3512 if (dhtlog_handle != NULL)
3513 GNUNET_DHTLOG_disconnect(dhtlog_handle);
3515 GNUNET_free_non_null(my_short_id);
3520 * To be called on core init/fail.
3522 * @param cls service closure
3523 * @param server handle to the server for this service
3524 * @param identity the public identity of this peer
3525 * @param publicKey the public key of this peer
3528 core_init (void *cls,
3529 struct GNUNET_CORE_Handle *server,
3530 const struct GNUNET_PeerIdentity *identity,
3531 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3537 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3538 "%s: Connection to core FAILED!\n", "dht",
3539 GNUNET_i2s (identity));
3541 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
3542 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3546 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3547 "%s: Core connection initialized, I am peer: %s\n", "dht",
3548 GNUNET_i2s (identity));
3551 /* Copy our identity so we can use it */
3552 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3553 if (my_short_id != NULL)
3554 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3555 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3556 /* Set the server to local variable */
3559 if (dhtlog_handle != NULL)
3560 dhtlog_handle->insert_node (NULL, &my_identity);
3564 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3565 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3566 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3567 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
3572 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3573 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
3574 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
3579 * Method called whenever a peer connects.
3581 * @param cls closure
3582 * @param peer peer identity this notification is about
3583 * @param latency reported latency of the connection with peer
3584 * @param distance reported distance (DV) to peer
3586 void handle_core_connect (void *cls,
3587 const struct GNUNET_PeerIdentity * peer,
3588 struct GNUNET_TIME_Relative latency,
3591 struct PeerInfo *ret;
3594 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3595 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
3598 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3600 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));
3604 if (datacache != NULL)
3605 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
3606 ret = try_add_peer(peer,
3607 find_current_bucket(&peer->hashPubKey),
3612 newly_found_peers++;
3613 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3616 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3617 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
3622 * Method called whenever a peer disconnects.
3624 * @param cls closure
3625 * @param peer peer identity this notification is about
3627 void handle_core_disconnect (void *cls,
3629 GNUNET_PeerIdentity * peer)
3631 struct PeerInfo *to_remove;
3634 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");
3636 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3638 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));
3641 increment_stats(STAT_DISCONNECTS);
3642 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
3643 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
3644 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
3645 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
3646 delete_peer(to_remove, current_bucket);
3650 * Process dht requests.
3652 * @param cls closure
3653 * @param scheduler scheduler to use
3654 * @param server the initialized server
3655 * @param c configuration to use
3659 struct GNUNET_SCHEDULER_Handle *scheduler,
3660 struct GNUNET_SERVER_Handle *server,
3661 const struct GNUNET_CONFIGURATION_Handle *c)
3664 struct GNUNET_TIME_Relative next_send_time;
3668 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
3669 GNUNET_SERVER_add_handlers (server, plugin_handlers);
3670 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
3671 cfg, /* Main configuration */
3672 GNUNET_TIME_UNIT_FOREVER_REL,
3673 NULL, /* Closure passed to DHT functions */
3674 &core_init, /* Call core_init once connected */
3675 &handle_core_connect, /* Handle connects */
3676 &handle_core_disconnect, /* remove peers on disconnects */
3677 NULL, /* Do we care about "status" updates? */
3678 NULL, /* Don't want notified about all incoming messages */
3679 GNUNET_NO, /* For header only inbound notification */
3680 NULL, /* Don't want notified about all outbound messages */
3681 GNUNET_NO, /* For header only outbound notification */
3682 core_handlers); /* Register these handlers */
3684 if (coreAPI == NULL)
3686 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
3687 NULL, NULL, NULL, NULL, NULL);
3688 if (transport_handle != NULL)
3689 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
3691 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
3693 lowest_bucket = MAX_BUCKETS - 1;
3694 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
3695 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3696 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
3697 recent_find_peer_requests = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
3698 GNUNET_assert(all_known_peers != NULL);
3699 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
3701 debug_routes = GNUNET_YES;
3705 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3708 strict_kademlia = GNUNET_YES;
3712 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3715 stop_on_closest = GNUNET_YES;
3719 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3722 stop_on_found = GNUNET_YES;
3726 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3727 "malicious_getter"))
3729 malicious_getter = GNUNET_YES;
3730 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3731 "MALICIOUS_GET_FREQUENCY",
3732 &malicious_get_frequency))
3733 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3737 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3738 "malicious_putter"))
3740 malicious_putter = GNUNET_YES;
3741 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3742 "MALICIOUS_PUT_FREQUENCY",
3743 &malicious_put_frequency))
3744 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3748 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3749 "malicious_dropper"))
3751 malicious_dropper = GNUNET_YES;
3755 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3758 do_find_peer = GNUNET_NO;
3761 do_find_peer = GNUNET_YES;
3764 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
3765 "mysql_logging_extended"))
3767 debug_routes = GNUNET_YES;
3768 debug_routes_extended = GNUNET_YES;
3771 if (GNUNET_YES == debug_routes)
3773 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
3774 if (dhtlog_handle == NULL)
3776 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3777 "Could not connect to mysql logging server, logging will not happen!");
3781 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
3785 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
3786 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
3787 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
3788 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
3789 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
3790 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
3791 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
3792 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
3793 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
3794 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
3795 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
3796 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
3797 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
3798 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
3799 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
3800 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
3801 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
3802 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
3803 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
3804 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
3806 /* FIXME: if there are no recent requests then these never get freed, but alternative is _annoying_! */
3807 recent.hashmap = GNUNET_CONTAINER_multihashmap_create(DHT_MAX_RECENT / 2);
3808 recent.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3809 if (GNUNET_YES == do_find_peer)
3811 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3812 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3813 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3814 find_peer_context.start = GNUNET_TIME_absolute_get();
3815 GNUNET_SCHEDULER_add_delayed (sched,
3817 &send_find_peer_message, &find_peer_context);
3820 /* Scheduled the task to clean up when shutdown is called */
3821 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
3822 GNUNET_TIME_UNIT_FOREVER_REL,
3823 &shutdown_task, NULL);
3827 * The main function for the dht service.
3829 * @param argc number of arguments from the command line
3830 * @param argv command line arguments
3831 * @return 0 ok, 1 on error
3834 main (int argc, char *const *argv)
3836 return (GNUNET_OK ==
3837 GNUNET_SERVICE_run (argc,
3840 GNUNET_SERVICE_OPTION_NONE,
3841 &run, NULL)) ? 0 : 1;