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
72 #define DHT_MAX_RECENT 100
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 * Default time to wait to send find peer messages sent by the dht service.
87 #define DHT_DEFAULT_FIND_PEER_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30);
90 * Default importance for find peer messages sent by the dht service.
92 #define DHT_DEFAULT_FIND_PEER_IMPORTANCE 8
95 * Default replication parameter for find peer messages sent by the dht service.
97 #define DHT_DEFAULT_FIND_PEER_REPLICATION 10
100 * Default options for find peer requests sent by the dht service.
102 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
105 * How long at least to wait before sending another find peer request.
107 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
110 * How long at most to wait before sending another find peer request.
112 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
115 * How often to update our preference levels for peers in our routing tables.
117 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
120 * How many initial requests to send out (in true Kademlia fashion)
122 #define DHT_KADEMLIA_REPLICATION 3
125 * Default frequency for sending malicious get messages
127 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
130 * Default frequency for sending malicious put messages
132 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
135 * Type for a malicious request, so we can ignore it during testing
137 #define DHT_MALICIOUS_MESSAGE_TYPE 42
139 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
142 * Real maximum number of hops, at which point we refuse
143 * to forward the message.
148 * Linked list of messages to send to clients.
150 struct P2PPendingMessage
153 * Pointer to next item in the list
155 struct P2PPendingMessage *next;
158 * Pointer to previous item in the list
160 struct P2PPendingMessage *prev;
163 * Message importance level.
165 unsigned int importance;
168 * How long to wait before sending message.
170 struct GNUNET_TIME_Relative timeout;
173 * Actual message to be sent; // avoid allocation
175 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
181 * Per-peer information.
186 * Next peer entry (DLL)
188 struct PeerInfo *next;
191 * Prev peer entry (DLL)
193 struct PeerInfo *prev;
196 * Head of pending messages to be sent to this peer.
198 struct P2PPendingMessage *head;
201 * Tail of pending messages to be sent to this peer.
203 struct P2PPendingMessage *tail;
206 * Core handle for sending messages to this peer.
208 struct GNUNET_CORE_TransmitHandle *th;
211 * Task for scheduling message sends.
213 GNUNET_SCHEDULER_TaskIdentifier send_task;
216 * Task for scheduling preference updates
218 GNUNET_SCHEDULER_TaskIdentifier preference_task;
221 * Preference update context
223 struct GNUNET_CORE_InformationRequestContext *info_ctx;
226 * What is the average latency for replies received?
228 struct GNUNET_TIME_Relative latency;
231 * Number of responses received
233 unsigned long long response_count;
236 * Number of requests sent
238 unsigned long long request_count;
241 * What is the identity of the peer?
243 struct GNUNET_PeerIdentity id;
246 * Transport level distance to peer.
248 unsigned int distance;
251 * Task for scheduling periodic ping messages for this peer.
253 GNUNET_SCHEDULER_TaskIdentifier ping_task;
258 * Peers are grouped into buckets.
265 struct PeerInfo *head;
270 struct PeerInfo *tail;
273 * Number of peers in the bucket.
275 unsigned int peers_size;
279 * Linked list of messages to send to clients.
281 struct PendingMessage
284 * Pointer to next item in the list
286 struct PendingMessage *next;
289 * Pointer to previous item in the list
291 struct PendingMessage *prev;
294 * Actual message to be sent; // avoid allocation
296 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
301 * Struct containing information about a client,
302 * handle to connect to it, and any pending messages
303 * that need to be sent to it.
308 * Linked list of active clients
310 struct ClientList *next;
313 * The handle to this client
315 struct GNUNET_SERVER_Client *client_handle;
318 * Handle to the current transmission request, NULL
321 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
324 * Linked list of pending messages for this client
326 struct PendingMessage *pending_head;
329 * Tail of linked list of pending messages for this client
331 struct PendingMessage *pending_tail;
337 * Context containing information about a DHT message received.
339 struct DHT_MessageContext
342 * The client this request was received from.
343 * (NULL if received from another peer)
345 struct ClientList *client;
348 * The peer this request was received from.
349 * (NULL if received from local client)
351 const struct GNUNET_PeerIdentity *peer;
354 * The key this request was about
356 const GNUNET_HashCode *key;
359 * The unique identifier of this request
364 * Desired replication level
366 uint32_t replication;
369 * Network size estimate, either ours or the sum of
370 * those routed to thus far. =~ Log of number of peers
371 * chosen from for this request.
373 uint32_t network_size;
376 * Any message options for this request
378 uint32_t msg_options;
381 * How many hops has the message already traversed?
386 * How important is this message?
388 unsigned int importance;
391 * How long should we wait to transmit this request?
393 struct GNUNET_TIME_Relative timeout;
396 * Bloomfilter for this routing request.
398 struct GNUNET_CONTAINER_BloomFilter *bloom;
401 * Did we forward this message? (may need to remember it!)
406 * Are we the closest known peer to this key (out of our neighbors?)
412 * Record used for remembering what peers are waiting for what
413 * responses (based on search key).
415 struct DHTRouteSource
420 struct DHTRouteSource *next;
425 struct DHTRouteSource *prev;
428 * Source of the request. Replies should be forwarded to
431 struct GNUNET_PeerIdentity source;
434 * If this was a local request, remember the client; otherwise NULL.
436 struct ClientList *client;
439 * Pointer to this nodes heap location (for removal)
441 struct GNUNET_CONTAINER_HeapNode *hnode;
444 * Back pointer to the record storing this information.
446 struct DHTQueryRecord *record;
449 * Task to remove this entry on timeout.
451 GNUNET_SCHEDULER_TaskIdentifier delete_task;
455 * Entry in the DHT routing table.
457 struct DHTQueryRecord
460 * Head of DLL for result forwarding.
462 struct DHTRouteSource *head;
465 * Tail of DLL for result forwarding.
467 struct DHTRouteSource *tail;
470 * Key that the record concerns.
475 * GET message of this record (what we already forwarded?).
477 //DV_DHT_MESSAGE get; Try to get away with not saving this.
480 * Bloomfilter of the peers we've replied to so far
482 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
487 * DHT Routing results structure
492 * Min heap for removal upon reaching limit
494 struct GNUNET_CONTAINER_Heap *minHeap;
497 * Hashmap for fast key based lookup
499 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
504 * DHT structure for recent requests.
506 struct RecentRequests
509 * Min heap for removal upon reaching limit
511 struct GNUNET_CONTAINER_Heap *minHeap;
514 * Hashmap for key based lookup
516 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
528 * Recent requests by hash/uid and by time inserted.
530 static struct RecentRequests recent;
533 * Don't use our routing algorithm, always route
534 * to closest peer; initially send requests to 3
537 static int strict_kademlia;
540 * Routing option to end routing when closest peer found.
542 static int stop_on_closest;
545 * Routing option to end routing when data is found.
547 static int stop_on_found;
550 * How many peers have we added since we sent out our last
553 static unsigned int newly_found_peers;
556 * Container of active queries we should remember
558 static struct DHTResults forward_list;
561 * Handle to the datacache service (for inserting/retrieving data)
563 static struct GNUNET_DATACACHE_Handle *datacache;
566 * Handle for the statistics service.
568 struct GNUNET_STATISTICS_Handle *stats;
571 * The main scheduler to use for the DHT service
573 static struct GNUNET_SCHEDULER_Handle *sched;
576 * The configuration the DHT service is running with
578 static const struct GNUNET_CONFIGURATION_Handle *cfg;
581 * Handle to the core service
583 static struct GNUNET_CORE_Handle *coreAPI;
586 * Handle to the transport service, for getting our hello
588 static struct GNUNET_TRANSPORT_Handle *transport_handle;
591 * The identity of our peer.
593 static struct GNUNET_PeerIdentity my_identity;
596 * Short id of the peer, for printing
598 static char *my_short_id;
603 static struct GNUNET_MessageHeader *my_hello;
606 * Task to run when we shut down, cleaning up all our trash
608 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
611 * The lowest currently used bucket.
613 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
616 * The buckets (Kademlia routing table, complete with growth).
617 * Array of size MAX_BUCKET_SIZE.
619 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
622 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
624 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
627 * Maximum size for each bucket.
629 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
632 * List of active clients.
634 static struct ClientList *client_list;
637 * Handle to the DHT logger.
639 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
642 * Whether or not to send routing debugging information
643 * to the dht logging server
645 static unsigned int debug_routes;
648 * Whether or not to send FULL route information to
651 static unsigned int debug_routes_extended;
654 * GNUNET_YES or GNUNET_NO, whether or not to act as
655 * a malicious node which drops all messages
657 static unsigned int malicious_dropper;
660 * GNUNET_YES or GNUNET_NO, whether or not to act as
661 * a malicious node which sends out lots of GETS
663 static unsigned int malicious_getter;
666 * GNUNET_YES or GNUNET_NO, whether or not to act as
667 * a malicious node which sends out lots of PUTS
669 static unsigned int malicious_putter;
671 static unsigned long long malicious_get_frequency;
673 static unsigned long long malicious_put_frequency;
676 * Forward declaration.
678 static size_t send_generic_reply (void *cls, size_t size, void *buf);
680 /* Declare here so retry_core_send is aware of it */
681 size_t core_transmit_notify (void *cls,
682 size_t size, void *buf);
685 increment_stats(const char *value)
689 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
694 * Try to send another message from our core send list
697 try_core_send (void *cls,
698 const struct GNUNET_SCHEDULER_TaskContext *tc)
700 struct PeerInfo *peer = cls;
701 struct P2PPendingMessage *pending;
704 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
706 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
709 if (peer->th != NULL)
710 return; /* Message send already in progress */
712 pending = peer->head;
715 ssize = ntohs(pending->msg->size);
717 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
718 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
719 "DHT", ssize, GNUNET_i2s(&peer->id));
721 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
722 pending->timeout, &peer->id,
723 ssize, &core_transmit_notify, peer);
728 * Function called to send a request out to another peer.
729 * Called both for locally initiated requests and those
730 * received from other peers.
732 * @param cls DHT service closure argument
733 * @param msg the encapsulated message
734 * @param peer the peer to forward the message to
735 * @param msg_ctx the context of the message (hop count, bloom, etc.)
737 static void forward_result_message (void *cls,
738 const struct GNUNET_MessageHeader *msg,
739 struct PeerInfo *peer,
740 struct DHT_MessageContext *msg_ctx)
742 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
743 struct P2PPendingMessage *pending;
747 increment_stats(STAT_RESULT_FORWARDS);
748 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
749 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
750 psize = sizeof(struct P2PPendingMessage) + msize;
751 pending = GNUNET_malloc(psize);
752 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
753 pending->importance = DHT_SEND_PRIORITY;
754 pending->timeout = GNUNET_TIME_relative_get_forever();
755 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
756 result_message->header.size = htons(msize);
757 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
758 result_message->options = htonl(msg_ctx->msg_options);
759 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
760 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
761 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
762 memcpy(&result_message->key, msg_ctx->key, sizeof(GNUNET_HashCode));
763 memcpy(&result_message[1], msg, ntohs(msg->size));
765 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));
767 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
768 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
769 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
772 * Called when core is ready to send a message we asked for
773 * out to the destination.
775 * @param cls closure (NULL)
776 * @param size number of bytes available in buf
777 * @param buf where the callee should write the message
778 * @return number of bytes written to buf
780 size_t core_transmit_notify (void *cls,
781 size_t size, void *buf)
783 struct PeerInfo *peer = cls;
785 struct P2PPendingMessage *pending;
792 /* client disconnected */
794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
799 if (peer->head == NULL)
804 pending = peer->head;
805 msize = ntohs(pending->msg->size);
809 memcpy (cbuf, pending->msg, msize);
810 GNUNET_CONTAINER_DLL_remove (peer->head,
814 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));
816 GNUNET_free (pending);
819 while (NULL != pending &&
820 (size - off >= (msize = ntohs (pending->msg->size))))
822 #if DEBUG_DHT_ROUTING
823 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);
825 memcpy (&cbuf[off], pending->msg, msize);
827 GNUNET_CONTAINER_DLL_remove (peer->head,
830 GNUNET_free (pending);
831 pending = peer->head;
834 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
835 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
837 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);
843 * Determine how many low order bits match in two
844 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
845 * the first two lowest order bits, and therefore the
846 * return value is two (NOT XOR distance, nor how many
847 * bits match absolutely!).
849 * @param first the first hashcode
850 * @param second the hashcode to compare first to
852 * @return the number of bits that match
854 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
858 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
859 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
861 return sizeof (GNUNET_HashCode) * 8;
865 * Compute the distance between have and target as a 32-bit value.
866 * Differences in the lower bits must count stronger than differences
867 * in the higher bits.
869 * @return 0 if have==target, otherwise a number
870 * that is larger as the distance between
871 * the two hash codes increases
874 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
881 /* We have to represent the distance between two 2^9 (=512)-bit
882 numbers as a 2^5 (=32)-bit number with "0" being used for the
883 two numbers being identical; furthermore, we need to
884 guarantee that a difference in the number of matching
885 bits is always represented in the result.
887 We use 2^32/2^9 numerical values to distinguish between
888 hash codes that have the same LSB bit distance and
889 use the highest 2^9 bits of the result to signify the
890 number of (mis)matching LSB bits; if we have 0 matching
891 and hence 512 mismatching LSB bits we return -1 (since
892 512 itself cannot be represented with 9 bits) */
894 /* first, calculate the most significant 9 bits of our
895 result, aka the number of LSBs */
896 bucket = matching_bits (target, have);
897 /* bucket is now a value between 0 and 512 */
899 return 0; /* perfect match */
901 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
902 below, we'd end up with max+1 (overflow)) */
904 /* calculate the most significant bits of the final result */
905 msb = (512 - bucket) << (32 - 9);
906 /* calculate the 32-9 least significant bits of the final result by
907 looking at the differences in the 32-9 bits following the
908 mismatching bit at 'bucket' */
911 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
913 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
914 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
915 last bit set will be 31 -- if
916 i does not reach 512 first... */
922 * Return a number that is larger the closer the
923 * "have" GNUNET_hash code is to the "target".
925 * @return inverse distance metric, non-zero.
926 * Must fudge the value if NO bits match.
929 inverse_distance (const GNUNET_HashCode * target,
930 const GNUNET_HashCode * have)
932 if (matching_bits(target, have) == 0)
933 return 1; /* Never return 0! */
934 return ((unsigned int) -1) - distance (target, have);
938 * Find the optimal bucket for this key, regardless
939 * of the current number of buckets in use.
941 * @param hc the hashcode to compare our identity to
943 * @return the proper bucket index, or GNUNET_SYSERR
944 * on error (same hashcode)
946 static int find_bucket(const GNUNET_HashCode *hc)
950 bits = matching_bits(&my_identity.hashPubKey, hc);
951 if (bits == MAX_BUCKETS)
952 return GNUNET_SYSERR;
953 return MAX_BUCKETS - bits - 1;
957 * Find which k-bucket this peer should go into,
958 * taking into account the size of the k-bucket
959 * array. This means that if more bits match than
960 * there are currently buckets, lowest_bucket will
963 * @param hc GNUNET_HashCode we are finding the bucket for.
965 * @return the proper bucket index for this key,
966 * or GNUNET_SYSERR on error (same hashcode)
968 static int find_current_bucket(const GNUNET_HashCode *hc)
971 actual_bucket = find_bucket(hc);
973 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
974 return GNUNET_SYSERR;
975 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
976 return lowest_bucket;
978 return actual_bucket;
983 * Find a routing table entry from a peer identity
985 * @param peer the peer to look up
987 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
990 find_bucket_by_peer(const struct PeerInfo *peer)
993 struct PeerInfo *pos;
995 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
997 pos = k_buckets[bucket].head;
1006 return GNUNET_SYSERR; /* No such peer. */
1012 * Print the complete routing table for this peer.
1015 print_routing_table ()
1018 struct PeerInfo *pos;
1019 char char_buf[30000];
1021 memset(char_buf, 0, sizeof(char_buf));
1023 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
1024 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
1025 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1027 pos = k_buckets[bucket].head;
1028 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
1029 //fprintf(stderr, "Bucket %d:\n", bucket);
1032 //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));
1033 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));
1037 fprintf(stderr, "%s", char_buf);
1043 * Find a routing table entry from a peer identity
1045 * @param peer the peer identity to look up
1047 * @return the routing table entry, or NULL if not found
1049 static struct PeerInfo *
1050 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
1053 struct PeerInfo *pos;
1054 bucket = find_current_bucket(&peer->hashPubKey);
1056 if (bucket == GNUNET_SYSERR)
1059 pos = k_buckets[bucket].head;
1062 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
1066 return NULL; /* No such peer. */
1069 /* Forward declaration */
1071 update_core_preference (void *cls,
1072 const struct GNUNET_SCHEDULER_TaskContext *tc);
1074 * Function called with statistics about the given peer.
1076 * @param cls closure
1077 * @param peer identifies the peer
1078 * @param bpm_in set to the current bandwidth limit (receiving) for this peer
1079 * @param bpm_out set to the current bandwidth limit (sending) for this peer
1080 * @param latency current latency estimate, "FOREVER" if we have been
1082 * @param amount set to the amount that was actually reserved or unreserved;
1083 * either the full requested amount or zero (no partial reservations)
1084 * @param preference current traffic preference for the given peer
1087 update_core_preference_finish (void *cls,
1089 GNUNET_PeerIdentity * peer,
1090 struct GNUNET_BANDWIDTH_Value32NBO bpm_in,
1091 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
1093 uint64_t preference)
1095 struct PeerInfo *peer_info = cls;
1096 peer_info->info_ctx = NULL;
1097 GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PREFERENCE_INTERVAL, &update_core_preference, peer_info);
1101 update_core_preference (void *cls,
1102 const struct GNUNET_SCHEDULER_TaskContext *tc)
1104 struct PeerInfo *peer = cls;
1105 uint64_t preference;
1107 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1112 preference = 2 << matching_bits(&my_identity.hashPubKey, &peer->id.hashPubKey);
1113 peer->info_ctx = GNUNET_CORE_peer_change_preference (sched, cfg,
1115 GNUNET_TIME_relative_get_forever(),
1116 GNUNET_BANDWIDTH_value_init (UINT32_MAX),
1119 &update_core_preference_finish,
1124 * Really add a peer to a bucket (only do assertions
1127 * @param peer GNUNET_PeerIdentity of the peer to add
1128 * @param bucket the already figured out bucket to add
1130 * @param latency the core reported latency of this peer
1131 * @param distance the transport level distance to this peer
1133 * @return the newly added PeerInfo
1135 static struct PeerInfo *
1136 add_peer(const struct GNUNET_PeerIdentity *peer,
1137 unsigned int bucket,
1138 struct GNUNET_TIME_Relative latency,
1139 unsigned int distance)
1141 struct PeerInfo *new_peer;
1142 GNUNET_assert(bucket < MAX_BUCKETS);
1143 GNUNET_assert(peer != NULL);
1144 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1145 new_peer->latency = latency;
1146 new_peer->distance = distance;
1148 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1150 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1151 k_buckets[bucket].tail,
1152 k_buckets[bucket].tail,
1154 k_buckets[bucket].peers_size++;
1156 if ((matching_bits(&my_identity.hashPubKey, &peer->hashPubKey) > 0) && (k_buckets[bucket].peers_size <= bucket_size))
1158 new_peer->preference_task = GNUNET_SCHEDULER_add_now(sched, &update_core_preference, new_peer);
1165 * Given a peer and its corresponding bucket,
1166 * remove it from that bucket. Does not free
1167 * the PeerInfo struct, nor cancel messages
1168 * or free messages waiting to be sent to this
1171 * @param peer the peer to remove
1172 * @param bucket the bucket the peer belongs to
1174 static void remove_peer (struct PeerInfo *peer,
1175 unsigned int bucket)
1177 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1178 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1179 k_buckets[bucket].tail,
1181 k_buckets[bucket].peers_size--;
1182 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1187 * Removes peer from a bucket, then frees associated
1188 * resources and frees peer.
1190 * @param peer peer to be removed and freed
1191 * @param bucket which bucket this peer belongs to
1193 static void delete_peer (struct PeerInfo *peer,
1194 unsigned int bucket)
1196 struct P2PPendingMessage *pos;
1197 struct P2PPendingMessage *next;
1199 struct PeerInfo *peer_pos;
1201 peer_pos = k_buckets[bucket].head;
1202 while ((peer_pos != NULL) && (peer_pos != peer))
1203 peer_pos = peer_pos->next;
1204 if (peer_pos == NULL)
1206 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1207 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));
1209 GNUNET_assert(peer_pos != NULL);
1211 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1213 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1214 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1215 if (peer->th != NULL)
1216 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1219 while (pos != NULL) /* Remove any pending messages for this peer */
1226 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1227 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1233 * Iterator over hash map entries.
1235 * @param cls closure
1236 * @param key current key code
1237 * @param value PeerInfo of the peer to move to new lowest bucket
1238 * @return GNUNET_YES if we should continue to
1242 static int move_lowest_bucket (void *cls,
1243 const GNUNET_HashCode * key,
1246 struct PeerInfo *peer = value;
1249 new_bucket = lowest_bucket - 1;
1250 remove_peer(peer, lowest_bucket);
1251 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1252 k_buckets[new_bucket].tail,
1253 k_buckets[new_bucket].tail,
1255 k_buckets[new_bucket].peers_size++;
1261 * The current lowest bucket is full, so change the lowest
1262 * bucket to the next lower down, and move any appropriate
1263 * entries in the current lowest bucket to the new bucket.
1265 static void enable_next_bucket()
1267 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1268 struct PeerInfo *pos;
1269 GNUNET_assert(lowest_bucket > 0);
1270 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1271 pos = k_buckets[lowest_bucket].head;
1274 fprintf(stderr, "Printing RT before new bucket\n");
1275 print_routing_table();
1277 /* Populate the array of peers which should be in the next lowest bucket */
1280 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1281 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1285 /* Remove peers from lowest bucket, insert into next lowest bucket */
1286 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1287 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1288 lowest_bucket = lowest_bucket - 1;
1290 fprintf(stderr, "Printing RT after new bucket\n");
1291 print_routing_table();
1296 * Find the closest peer in our routing table to the
1299 * @return The closest peer in our routing table to the
1300 * key, or NULL on error.
1302 static struct PeerInfo *
1303 find_closest_peer (const GNUNET_HashCode *hc)
1305 struct PeerInfo *pos;
1306 struct PeerInfo *current_closest;
1307 unsigned int lowest_distance;
1308 unsigned int temp_distance;
1312 lowest_distance = -1;
1314 if (k_buckets[lowest_bucket].peers_size == 0)
1317 current_closest = NULL;
1318 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1320 pos = k_buckets[bucket].head;
1322 while ((pos != NULL) && (count < bucket_size))
1324 temp_distance = distance(&pos->id.hashPubKey, hc);
1325 if (temp_distance <= lowest_distance)
1327 lowest_distance = temp_distance;
1328 current_closest = pos;
1334 GNUNET_assert(current_closest != NULL);
1335 return current_closest;
1340 * Function called to send a request out to another peer.
1341 * Called both for locally initiated requests and those
1342 * received from other peers.
1344 * @param cls DHT service closure argument (unused)
1345 * @param msg the encapsulated message
1346 * @param peer the peer to forward the message to
1347 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1349 static void forward_message (void *cls,
1350 const struct GNUNET_MessageHeader *msg,
1351 struct PeerInfo *peer,
1352 struct DHT_MessageContext *msg_ctx)
1354 struct GNUNET_DHT_P2PRouteMessage *route_message;
1355 struct P2PPendingMessage *pending;
1359 increment_stats(STAT_ROUTE_FORWARDS);
1361 if ((msg_ctx->closest != GNUNET_YES) && (peer == find_closest_peer(msg_ctx->key)))
1362 increment_stats(STAT_ROUTE_FORWARDS_CLOSEST);
1364 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1365 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1366 psize = sizeof(struct P2PPendingMessage) + msize;
1367 pending = GNUNET_malloc(psize);
1368 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1369 pending->importance = msg_ctx->importance;
1370 pending->timeout = msg_ctx->timeout;
1371 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1372 route_message->header.size = htons(msize);
1373 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1374 route_message->options = htonl(msg_ctx->msg_options);
1375 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1376 route_message->network_size = htonl(msg_ctx->network_size);
1377 route_message->desired_replication_level = htonl(msg_ctx->replication);
1378 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1379 if (msg_ctx->bloom != NULL)
1380 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1381 if (msg_ctx->key != NULL)
1382 memcpy(&route_message->key, msg_ctx->key, sizeof(GNUNET_HashCode));
1383 memcpy(&route_message[1], msg, ntohs(msg->size));
1385 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));
1387 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1388 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1389 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1394 * Task used to send ping messages to peers so that
1395 * they don't get disconnected.
1397 * @param cls the peer to send a ping message to
1398 * @param tc context, reason, etc.
1401 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1403 struct PeerInfo *peer = cls;
1404 struct GNUNET_MessageHeader ping_message;
1405 struct DHT_MessageContext message_context;
1407 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1410 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1411 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1413 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1415 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1417 forward_message(NULL, &ping_message, peer, &message_context);
1418 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1422 * Schedule PING messages for the top X peers in each
1423 * bucket of the routing table (so core won't disconnect them!)
1425 void schedule_ping_messages()
1427 unsigned int bucket;
1429 struct PeerInfo *pos;
1430 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1432 pos = k_buckets[bucket].head;
1436 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1437 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1438 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1440 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1441 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1451 * Attempt to add a peer to our k-buckets.
1453 * @param peer, the peer identity of the peer being added
1455 * @return NULL if the peer was not added,
1456 * pointer to PeerInfo for new peer otherwise
1458 static struct PeerInfo *
1459 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1460 unsigned int bucket,
1461 struct GNUNET_TIME_Relative latency,
1462 unsigned int distance)
1465 struct PeerInfo *new_peer;
1466 peer_bucket = find_current_bucket(&peer->hashPubKey);
1467 if (peer_bucket == GNUNET_SYSERR)
1470 GNUNET_assert(peer_bucket >= lowest_bucket);
1471 new_peer = add_peer(peer, peer_bucket, latency, distance);
1473 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1474 enable_next_bucket();
1476 schedule_ping_messages();
1483 * Task run to check for messages that need to be sent to a client.
1485 * @param client a ClientList, containing the client and any messages to be sent to it
1488 process_pending_messages (struct ClientList *client)
1490 if (client->pending_head == NULL)
1492 if (client->transmit_handle != NULL)
1494 client->transmit_handle =
1495 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1496 ntohs (client->pending_head->msg->
1498 GNUNET_TIME_UNIT_FOREVER_REL,
1499 &send_generic_reply, client);
1503 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1504 * request. A ClientList is passed as closure, take the head of the list
1505 * and copy it into buf, which has the result of sending the message to the
1508 * @param cls closure to this call
1509 * @param size maximum number of bytes available to send
1510 * @param buf where to copy the actual message to
1512 * @return the number of bytes actually copied, 0 indicates failure
1515 send_generic_reply (void *cls, size_t size, void *buf)
1517 struct ClientList *client = cls;
1519 struct PendingMessage *reply;
1523 client->transmit_handle = NULL;
1526 /* client disconnected */
1530 while ( (NULL != (reply = client->pending_head)) &&
1531 (size >= off + (msize = ntohs (reply->msg->size))))
1533 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1534 client->pending_tail,
1536 memcpy (&cbuf[off], reply->msg, msize);
1537 GNUNET_free (reply);
1540 process_pending_messages (client);
1546 * Add a PendingMessage to the clients list of messages to be sent
1548 * @param client the active client to send the message to
1549 * @param pending_message the actual message to send
1552 add_pending_message (struct ClientList *client,
1553 struct PendingMessage *pending_message)
1555 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1556 client->pending_tail,
1557 client->pending_tail,
1559 process_pending_messages (client);
1566 * Called when a reply needs to be sent to a client, as
1567 * a result it found to a GET or FIND PEER request.
1569 * @param client the client to send the reply to
1570 * @param message the encapsulated message to send
1571 * @param uid the unique identifier of this request
1574 send_reply_to_client (struct ClientList *client,
1575 const struct GNUNET_MessageHeader *message,
1576 unsigned long long uid)
1578 struct GNUNET_DHT_RouteResultMessage *reply;
1579 struct PendingMessage *pending_message;
1583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1584 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1586 msize = ntohs (message->size);
1587 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1588 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1590 GNUNET_break_op (0);
1594 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1595 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1596 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1597 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1598 reply->header.size = htons (tsize);
1599 reply->unique_id = GNUNET_htonll (uid);
1600 memcpy (&reply[1], message, msize);
1602 add_pending_message (client, pending_message);
1606 * Consider whether or not we would like to have this peer added to
1607 * our routing table. Check whether bucket for this peer is full,
1608 * if so return negative; if not return positive. Since peers are
1609 * only added on CORE level connect, this doesn't actually add the
1610 * peer to the routing table.
1612 * @param peer the peer we are considering adding
1614 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1617 * FIXME: Think about making a context for this call so that we can
1618 * ping the oldest peer in the current bucket and consider
1619 * removing it in lieu of the new peer.
1621 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1625 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1626 return GNUNET_NO; /* We already know this peer (are connected even!) */
1627 bucket = find_current_bucket(&peer->hashPubKey);
1628 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1635 * Main function that handles whether or not to route a result
1636 * message to other peers, or to send to our local client.
1638 * @param msg the result message to be routed
1639 * @return the number of peers the message was routed to,
1640 * GNUNET_SYSERR on failure
1642 static int route_result_message(void *cls,
1643 struct GNUNET_MessageHeader *msg,
1644 struct DHT_MessageContext *message_context)
1646 struct GNUNET_PeerIdentity new_peer;
1647 struct DHTQueryRecord *record;
1648 struct DHTRouteSource *pos;
1649 struct PeerInfo *peer_info;
1650 const struct GNUNET_MessageHeader *hello_msg;
1652 increment_stats(STAT_RESULTS);
1654 * If a find peer result message is received and contains a valid
1655 * HELLO for another peer, offer it to the transport service.
1657 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1659 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1662 hello_msg = &msg[1];
1663 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1665 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1668 else /* We have a valid hello, and peer id stored in new_peer */
1670 increment_stats(STAT_FIND_PEER_REPLY);
1671 if (GNUNET_YES == consider_peer(&new_peer))
1673 increment_stats(STAT_HELLOS_PROVIDED);
1674 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1675 /* GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_UNIT_FOREVER_REL, &new_peer, NULL, NULL); */
1676 /* peer_request_connect call causes service to segfault */
1677 /* FIXME: Do we need this (peer_request_connect call)??? */
1682 if (malicious_dropper == GNUNET_YES)
1685 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, message_context->key);
1687 if (record == NULL) /* No record of this message! */
1690 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1691 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1692 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1694 #if DEBUG_DHT_ROUTING
1696 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1698 dhtlog_handle->insert_route (NULL,
1699 message_context->unique_id,
1701 message_context->hop_count,
1704 message_context->key,
1705 message_context->peer, NULL);
1708 if (message_context->bloom != NULL)
1710 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1711 message_context->bloom = NULL;
1719 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1722 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1723 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
1724 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1726 #if DEBUG_DHT_ROUTING
1727 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1729 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
1730 message_context->hop_count,
1731 GNUNET_YES, &my_identity, message_context->key,
1732 message_context->peer, NULL);
1735 increment_stats(STAT_RESULTS_TO_CLIENT);
1736 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
1737 increment_stats(STAT_GET_REPLY);
1739 send_reply_to_client(pos->client, msg, message_context->unique_id);
1741 else /* Send to peer */
1743 peer_info = find_peer_by_id(&pos->source);
1744 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
1750 if (message_context->bloom == NULL)
1751 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1752 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
1753 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey))
1756 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1757 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
1758 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1760 #if DEBUG_DHT_ROUTING
1761 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1763 dhtlog_handle->insert_route (NULL, message_context->unique_id,
1765 message_context->hop_count,
1766 GNUNET_NO, &my_identity, message_context->key,
1767 message_context->peer, &pos->source);
1770 forward_result_message(cls, msg, peer_info, message_context);
1775 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1776 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
1777 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1783 if (message_context->bloom != NULL)
1784 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1789 * Iterator for local get request results,
1791 * @param cls closure for iterator, a DatacacheGetContext
1792 * @param exp when does this value expire?
1793 * @param key the key this data is stored under
1794 * @param size the size of the data identified by key
1795 * @param data the actual data
1796 * @param type the type of the data
1798 * @return GNUNET_OK to continue iteration, anything else
1799 * to stop iteration.
1802 datacache_get_iterator (void *cls,
1803 struct GNUNET_TIME_Absolute exp,
1804 const GNUNET_HashCode * key,
1805 uint32_t size, const char *data, uint32_t type)
1807 struct DHT_MessageContext *msg_ctx = cls;
1808 struct DHT_MessageContext *new_msg_ctx;
1809 struct GNUNET_DHT_GetResultMessage *get_result;
1811 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1812 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
1814 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
1815 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
1817 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
1818 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
1819 get_result->header.size =
1820 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
1821 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
1822 get_result->type = htons (type);
1823 memcpy (&get_result[1], data, size);
1824 new_msg_ctx->peer = &my_identity;
1825 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1826 new_msg_ctx->hop_count = 0;
1827 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
1828 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
1829 increment_stats(STAT_GET_RESPONSE_START);
1830 route_result_message(cls, &get_result->header, new_msg_ctx);
1831 GNUNET_free(new_msg_ctx);
1832 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
1833 // datacache_get_ctx->unique_id);
1834 GNUNET_free (get_result);
1840 * Server handler for all dht get requests, look for data,
1841 * if found, send response either to clients or other peers.
1843 * @param cls closure for service
1844 * @param msg the actual get message
1845 * @param message_context struct containing pertinent information about the get request
1847 * @return number of items found for GET request
1850 handle_dht_get (void *cls,
1851 const struct GNUNET_MessageHeader *msg,
1852 struct DHT_MessageContext *message_context)
1854 const struct GNUNET_DHT_GetMessage *get_msg;
1856 unsigned int results;
1858 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
1859 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
1865 get_type = ntohs (get_msg->type);
1867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1868 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
1869 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
1870 message_context->unique_id);
1872 increment_stats(STAT_GETS);
1874 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
1877 if (datacache != NULL)
1879 GNUNET_DATACACHE_get (datacache, message_context->key, get_type,
1880 &datacache_get_iterator, message_context);
1885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1886 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
1887 results, "GET", message_context->unique_id);
1889 #if DEBUG_DHT_ROUTING
1890 if ((debug_routes) && (dhtlog_handle != NULL))
1892 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
1893 message_context->hop_count, GNUNET_YES, &my_identity,
1894 message_context->key);
1897 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1899 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
1900 message_context->hop_count, GNUNET_YES,
1901 &my_identity, message_context->key, message_context->peer,
1907 if (message_context->hop_count == 0) /* Locally initiated request */
1909 #if DEBUG_DHT_ROUTING
1910 if ((debug_routes) && (dhtlog_handle != NULL))
1912 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
1913 message_context->hop_count, GNUNET_NO, &my_identity,
1914 message_context->key);
1924 * Server handler for initiating local dht find peer requests
1926 * @param cls closure for service
1927 * @param find_msg the actual find peer message
1928 * @param message_context struct containing pertinent information about the request
1932 handle_dht_find_peer (void *cls,
1933 const struct GNUNET_MessageHeader *find_msg,
1934 struct DHT_MessageContext *message_context)
1936 struct GNUNET_MessageHeader *find_peer_result;
1937 struct GNUNET_DHT_FindPeerMessage *find_peer_message;
1938 struct DHT_MessageContext *new_msg_ctx;
1939 struct GNUNET_CONTAINER_BloomFilter *incoming_bloom;
1942 find_peer_message = (struct GNUNET_DHT_FindPeerMessage *)find_msg;
1944 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1945 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
1946 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
1947 ntohs (find_msg->size),
1948 sizeof (struct GNUNET_MessageHeader));
1950 if (my_hello == NULL)
1953 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1954 "`%s': Our HELLO is null, can't return.\n",
1960 incoming_bloom = GNUNET_CONTAINER_bloomfilter_init(find_peer_message->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1961 if (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test(incoming_bloom, &my_identity.hashPubKey))
1963 increment_stats(STAT_BLOOM_FIND_PEER);
1964 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
1965 return; /* We match the bloomfilter, do not send a response to this peer (they likely already know us!)*/
1967 GNUNET_CONTAINER_bloomfilter_free(incoming_bloom);
1969 /* Simplistic find_peer functionality, always return our hello */
1970 hello_size = ntohs(my_hello->size);
1971 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
1973 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1975 GNUNET_break_op (0);
1979 find_peer_result = GNUNET_malloc (tsize);
1980 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
1981 find_peer_result->size = htons (tsize);
1982 memcpy (&find_peer_result[1], my_hello, hello_size);
1984 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1985 "`%s': Sending hello size %d to requesting peer.\n",
1988 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
1989 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
1990 new_msg_ctx->peer = &my_identity;
1991 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1992 new_msg_ctx->hop_count = 0;
1993 new_msg_ctx->importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make find peer requests a higher priority */
1994 new_msg_ctx->timeout = DHT_DEFAULT_P2P_TIMEOUT;
1995 increment_stats(STAT_FIND_PEER_ANSWER);
1996 route_result_message(cls, find_peer_result, new_msg_ctx);
1997 GNUNET_free(new_msg_ctx);
1998 #if DEBUG_DHT_ROUTING
1999 if ((debug_routes) && (dhtlog_handle != NULL))
2001 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2002 message_context->hop_count, GNUNET_YES, &my_identity,
2003 message_context->key);
2006 GNUNET_free(find_peer_result);
2011 * Server handler for initiating local dht put requests
2013 * @param cls closure for service
2014 * @param msg the actual put message
2015 * @param message_context struct containing pertinent information about the request
2018 handle_dht_put (void *cls,
2019 const struct GNUNET_MessageHeader *msg,
2020 struct DHT_MessageContext *message_context)
2022 struct GNUNET_DHT_PutMessage *put_msg;
2026 GNUNET_assert (ntohs (msg->size) >=
2027 sizeof (struct GNUNET_DHT_PutMessage));
2030 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
2031 put_type = ntohs (put_msg->type);
2033 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
2036 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
2038 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2039 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
2040 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
2042 #if DEBUG_DHT_ROUTING
2043 if (message_context->hop_count == 0) /* Locally initiated request */
2045 if ((debug_routes) && (dhtlog_handle != NULL))
2047 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2048 message_context->hop_count, GNUNET_NO, &my_identity,
2049 message_context->key);
2054 if (message_context->closest != GNUNET_YES)
2057 #if DEBUG_DHT_ROUTING
2058 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2060 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2061 message_context->hop_count, GNUNET_YES,
2062 &my_identity, message_context->key, message_context->peer,
2066 if ((debug_routes) && (dhtlog_handle != NULL))
2068 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
2069 message_context->hop_count, GNUNET_YES, &my_identity,
2070 message_context->key);
2074 increment_stats(STAT_PUTS_INSERTED);
2075 if (datacache != NULL)
2076 GNUNET_DATACACHE_put (datacache, message_context->key, data_size,
2077 (char *) &put_msg[1], put_type,
2078 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
2080 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2081 "`%s:%s': %s request received, but have no datacache!\n",
2082 my_short_id, "DHT", "PUT");
2086 * Estimate the diameter of the network based
2087 * on how many buckets are currently in use.
2088 * Concept here is that the diameter of the network
2089 * is roughly the distance a message must travel in
2090 * order to reach its intended destination. Since
2091 * at each hop we expect to get one bit closer, and
2092 * we have one bit per bucket, the number of buckets
2093 * in use should be the largest number of hops for
2094 * a sucessful message. (of course, this assumes we
2095 * know all peers in the network!)
2097 * @return ballpark diameter figure
2099 static unsigned int estimate_diameter()
2101 return MAX_BUCKETS - lowest_bucket;
2105 * To how many peers should we (on average)
2106 * forward the request to obtain the desired
2107 * target_replication count (on average).
2109 * Always 0, 1 or 2 (don't send, send once, split)
2112 get_forward_count (unsigned int hop_count, size_t target_replication)
2114 double target_count;
2115 unsigned int target_value;
2116 unsigned int diameter;
2119 * If we are behaving in strict kademlia mode, send multiple initial requests,
2120 * but then only send to 1 or 0 peers.
2122 if (strict_kademlia == GNUNET_YES)
2125 return DHT_KADEMLIA_REPLICATION;
2126 else if (hop_count < MAX_HOPS)
2132 /* FIXME: the smaller we think the network is the more lenient we should be for
2133 * routing right? The estimation below only works if we think we have reasonably
2134 * full routing tables, which for our RR topologies may not be the case!
2136 diameter = estimate_diameter ();
2137 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
2140 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2141 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
2142 "DHT", estimate_diameter(), lowest_bucket);
2146 else if (hop_count > MAX_HOPS)
2149 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2150 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
2155 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
2156 target_replication / (target_replication * (hop_count + 1) + diameter);
2160 while (target_value < target_count)
2161 target_value++; /* target_value is ALWAYS 1 after this "loop" */
2165 if ((target_count + 1 - target_value) >
2166 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
2167 RAND_MAX) / RAND_MAX)
2169 return target_value;
2173 * Check whether my identity is closer than any known peers.
2175 * @param target hash code to check closeness to
2177 * Return GNUNET_YES if node location is closest, GNUNET_NO
2181 am_closest_peer (const GNUNET_HashCode * target)
2187 struct PeerInfo *pos;
2188 unsigned int my_distance;
2190 bucket_num = find_current_bucket(target);
2191 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2194 bits = matching_bits(&my_identity.hashPubKey, target);
2195 my_distance = distance(&my_identity.hashPubKey, target);
2197 pos = k_buckets[bucket_num].head;
2199 while ((pos != NULL) && (count < bucket_size))
2201 other_bits = matching_bits(&pos->id.hashPubKey, target);
2202 if (other_bits > bits)
2204 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2207 /* FIXME: why not just return GNUNET_YES here? We are certainly close. */
2208 /*if (distance(&pos->id.hashPubKey, target) < my_distance)
2215 GNUNET_GE_LOG (coreAPI->ectx,
2216 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2217 GNUNET_GE_BULK, "closest peer\n");
2218 printPeerBits (&closest);
2219 GNUNET_GE_LOG (coreAPI->ectx,
2220 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2221 GNUNET_GE_BULK, "me\n");
2222 printPeerBits (coreAPI->my_identity);
2223 GNUNET_GE_LOG (coreAPI->ectx,
2224 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2225 GNUNET_GE_BULK, "key\n");
2226 printKeyBits (target);
2227 GNUNET_GE_LOG (coreAPI->ectx,
2228 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2230 "closest peer inverse distance is %u, mine is %u\n",
2231 inverse_distance (target, &closest.hashPubKey),
2232 inverse_distance (target,
2233 &coreAPI->my_identity->hashPubKey));
2236 /* No peers closer, we are the closest! */
2242 * Select a peer from the routing table that would be a good routing
2243 * destination for sending a message for "target". The resulting peer
2244 * must not be in the set of blocked peers.<p>
2246 * Note that we should not ALWAYS select the closest peer to the
2247 * target, peers further away from the target should be chosen with
2248 * exponentially declining probability.
2250 * @param target the key we are selecting a peer to route to
2251 * @param bloom a bloomfilter containing entries this request has seen already
2253 * @return Peer to route to, or NULL on error
2255 static struct PeerInfo *
2256 select_peer (const GNUNET_HashCode * target,
2257 struct GNUNET_CONTAINER_BloomFilter *bloom)
2259 unsigned int distance;
2262 struct PeerInfo *pos;
2263 struct PeerInfo *chosen;
2264 unsigned long long largest_distance;
2265 unsigned long long total_distance;
2266 unsigned long long selected;
2268 if (strict_kademlia == GNUNET_YES)
2270 largest_distance = 0;
2272 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2274 pos = k_buckets[bc].head;
2276 while ((pos != NULL) && (count < bucket_size))
2278 /* If we are doing strict Kademlia like routing, then checking the bloomfilter is basically cheating! */
2279 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2281 distance = inverse_distance (target, &pos->id.hashPubKey);
2282 if (distance > largest_distance)
2285 largest_distance = distance;
2293 if ((largest_distance > 0) && (chosen != NULL))
2295 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2307 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2309 pos = k_buckets[bc].head;
2311 while ((pos != NULL) && (count < bucket_size))
2313 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2314 total_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2316 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2317 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2318 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2324 if (total_distance == 0)
2329 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2330 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2332 pos = k_buckets[bc].head;
2334 while ((pos != NULL) && (count < bucket_size))
2336 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2338 distance = inverse_distance (target, &pos->id.hashPubKey);
2339 if (distance > selected)
2341 selected -= distance;
2346 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2347 "`%s:%s': peer %s matches bloomfilter.\n",
2348 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2357 "`%s:%s': peer %s matches bloomfilter.\n",
2358 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2366 * Task used to remove forwarding entries, either
2367 * after timeout, when full, or on shutdown.
2369 * @param cls the entry to remove
2370 * @param tc context, reason, etc.
2373 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2375 struct DHTRouteSource *source_info = cls;
2376 struct DHTQueryRecord *record;
2377 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2378 record = source_info->record;
2379 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2381 if (record->head == NULL) /* No more entries in DLL */
2383 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2384 GNUNET_free(record);
2386 GNUNET_free(source_info);
2390 * Remember this routing request so that if a reply is
2391 * received we can either forward it to the correct peer
2392 * or return the result locally.
2394 * @param cls DHT service closure
2395 * @param msg_ctx Context of the route request
2397 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2399 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2401 struct DHTQueryRecord *record;
2402 struct DHTRouteSource *source_info;
2403 struct DHTRouteSource *pos;
2404 struct GNUNET_TIME_Absolute now;
2405 unsigned int current_size;
2407 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2408 while (current_size >= MAX_OUTSTANDING_FORWARDS)
2410 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2411 record = source_info->record;
2412 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2413 if (record->head == NULL) /* No more entries in DLL */
2415 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2416 GNUNET_free(record);
2418 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2419 GNUNET_free(source_info);
2420 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2422 now = GNUNET_TIME_absolute_get();
2423 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, msg_ctx->key);
2424 if (record != NULL) /* Already know this request! */
2429 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
2430 break; /* Already have this peer in reply list! */
2433 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
2435 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
2441 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
2442 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2443 memcpy(&record->key, msg_ctx->key, sizeof(GNUNET_HashCode));
2446 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
2447 source_info->record = record;
2448 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
2449 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
2450 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
2451 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
2453 source_info->client = msg_ctx->client;
2454 now = GNUNET_TIME_absolute_get_forever();
2456 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
2458 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2459 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
2460 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
2467 * Main function that handles whether or not to route a message to other
2470 * @param cls closure for dht service (NULL)
2471 * @param msg the message to be routed
2472 * @param message_context the context containing all pertinent information about the message
2474 * @return the number of peers the message was routed to,
2475 * GNUNET_SYSERR on failure
2477 static int route_message(void *cls,
2478 const struct GNUNET_MessageHeader *msg,
2479 struct DHT_MessageContext *message_context)
2482 struct PeerInfo *selected;
2483 struct PeerInfo *nearest;
2484 unsigned int forward_count;
2488 #if DEBUG_DHT_ROUTING
2492 if (malicious_dropper == GNUNET_YES)
2494 #if DEBUG_DHT_ROUTING
2495 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2497 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2498 message_context->hop_count, GNUNET_SYSERR,
2499 &my_identity, message_context->key, message_context->peer,
2503 if (message_context->bloom != NULL)
2504 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2508 increment_stats(STAT_ROUTES);
2509 message_context->closest = am_closest_peer(message_context->key);
2510 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
2511 nearest = find_closest_peer(message_context->key);
2513 if (message_context->bloom == NULL)
2514 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2516 if ((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
2517 /* || ((strict_kademlia == GNUNET_YES) && (message_context->closest == GNUNET_YES))) */
2520 #if DEBUG_DHT_ROUTING
2521 if (forward_count == 0)
2522 ret = GNUNET_SYSERR;
2526 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2528 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2529 message_context->hop_count, ret,
2530 &my_identity, message_context->key, message_context->peer,
2535 switch (ntohs(msg->type))
2537 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
2538 cache_response (cls, message_context);
2539 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
2542 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
2543 increment_stats(STAT_PUTS);
2544 handle_dht_put (cls, msg, message_context);
2546 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
2547 increment_stats(STAT_FIND_PEER);
2548 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
2550 cache_response (cls, message_context);
2551 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
2552 handle_dht_find_peer (cls, msg, message_context);
2554 #if DEBUG_DHT_ROUTING
2555 if (message_context->hop_count == 0) /* Locally initiated request */
2557 if ((debug_routes) && (dhtlog_handle != NULL))
2559 dhtlog_handle->insert_dhtkey(NULL, message_context->key);
2560 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2561 message_context->hop_count, GNUNET_NO, &my_identity,
2562 message_context->key);
2568 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2569 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
2572 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2574 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent->hashmap, message_context->key))
2576 if (GNUNET_SYSERR = GNUNET_CONTAINER_multihashmap_get_multiple (recent->hashmap, message_context->key, &find_matching_recent, &message_context)) /* Have too recently seen this request! */
2580 else /* Exact match not found, but same key found */
2582 recent_req = GNUNET_CONTAINER_multihashmap_get(recent->hashmap, message_context->key);
2587 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
2588 recent_req->uid = message_context->unique_id;
2589 memcmp(&recent_req->key, message_context->key, sizeof(GNUNET_HashCode));
2590 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
2591 GNUNET_CONTAINER_heap_insert(recent->minHeap, recent_req, GNUNET_TIME_absolute_get());
2592 GNUNET_CONTAINER_multihashmap_put(recent->hashmap, message_context->key, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2595 if (GNUNET_CONTAINER_multihashmap_size(recent->hashmap) > DHT_MAX_RECENT)
2597 remove_oldest_recent();
2601 for (i = 0; i < forward_count; i++)
2603 selected = select_peer(message_context->key, message_context->bloom);
2605 if (selected != NULL)
2607 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
2608 #if DEBUG_DHT_ROUTING > 1
2609 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
2610 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2611 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
2612 "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));
2613 GNUNET_free(nearest_buf);
2615 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2617 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2618 message_context->hop_count, GNUNET_NO,
2619 &my_identity, message_context->key, message_context->peer,
2622 forward_message(cls, msg, selected, message_context);
2627 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2628 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
2633 #if DEBUG_DHT_ROUTING > 1
2634 if (forward_count == 0)
2636 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2637 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
2638 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2642 if (message_context->bloom != NULL)
2643 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2645 return forward_count;
2649 * Find a client if it exists, add it otherwise.
2651 * @param client the server handle to the client
2653 * @return the client if found, a new client otherwise
2655 static struct ClientList *
2656 find_active_client (struct GNUNET_SERVER_Client *client)
2658 struct ClientList *pos = client_list;
2659 struct ClientList *ret;
2663 if (pos->client_handle == client)
2668 ret = GNUNET_malloc (sizeof (struct ClientList));
2669 ret->client_handle = client;
2670 ret->next = client_list;
2676 * Task to send a malicious put message across the network.
2678 * @param cls closure for this task
2679 * @param tc the context under which the task is running
2682 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2684 static struct GNUNET_DHT_PutMessage put_message;
2685 static struct DHT_MessageContext message_context;
2686 static GNUNET_HashCode key;
2687 unsigned int mcsize;
2688 uint32_t random_key;
2690 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2693 put_message.header.size = htons(sizeof(struct GNUNET_DHT_PutMessage));
2694 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
2695 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2696 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
2697 mcsize = sizeof(struct DHT_MessageContext) + sizeof(GNUNET_HashCode);
2698 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2699 message_context.client = NULL;
2700 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2701 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2702 message_context.key = &key;
2703 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2704 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2705 message_context.msg_options = ntohl (0);
2706 message_context.network_size = estimate_diameter();
2707 message_context.peer = &my_identity;
2708 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
2709 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
2710 if (dhtlog_handle != NULL)
2711 dhtlog_handle->insert_dhtkey(NULL, &key);
2712 increment_stats(STAT_PUT_START);
2713 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2714 route_message(NULL, &put_message.header, &message_context);
2715 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
2720 * Task to send a malicious put message across the network.
2722 * @param cls closure for this task
2723 * @param tc the context under which the task is running
2726 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2728 static struct GNUNET_DHT_GetMessage get_message;
2729 static struct DHT_MessageContext message_context;
2730 static GNUNET_HashCode key;
2731 unsigned int mcsize;
2732 uint32_t random_key;
2734 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2737 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
2738 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
2739 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2740 mcsize = sizeof(struct DHT_MessageContext) + sizeof(GNUNET_HashCode);
2741 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2742 message_context.client = NULL;
2743 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2744 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2745 message_context.key = &key;
2746 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2747 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2748 message_context.msg_options = ntohl (0);
2749 message_context.network_size = estimate_diameter();
2750 message_context.peer = &my_identity;
2751 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE; /* Make result routing a higher priority */
2752 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
2753 if (dhtlog_handle != NULL)
2754 dhtlog_handle->insert_dhtkey(NULL, &key);
2755 increment_stats(STAT_GET_START);
2756 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2757 route_message(NULL, &get_message.header, &message_context);
2758 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
2765 * Iterator over hash map entries.
2767 * @param cls closure
2768 * @param key current key code
2769 * @param value value in the hash map
2770 * @return GNUNET_YES if we should continue to
2775 add_known_to_bloom (void *cls,
2776 const GNUNET_HashCode * key,
2779 struct GNUNET_CONTAINER_BloomFilter *bloom = cls;
2780 GNUNET_CONTAINER_bloomfilter_add (bloom, key);
2785 * Task to send a find peer message for our own peer identifier
2786 * so that we can find the closest peers in the network to ourselves
2787 * and attempt to connect to them.
2789 * @param cls closure for this task
2790 * @param tc the context under which the task is running
2793 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2795 struct GNUNET_DHT_FindPeerMessage *find_peer_msg;
2796 struct DHT_MessageContext message_context;
2798 struct GNUNET_TIME_Relative next_send_time;
2799 struct GNUNET_CONTAINER_BloomFilter *temp_bloom;
2801 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2804 increment_stats(STAT_FIND_PEER_START);
2806 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_DHT_FindPeerMessage));
2807 find_peer_msg->header.size = htons(sizeof(struct GNUNET_DHT_FindPeerMessage));
2808 find_peer_msg->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
2809 temp_bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2810 GNUNET_CONTAINER_multihashmap_iterate(all_known_peers, &add_known_to_bloom, temp_bloom);
2811 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(temp_bloom, find_peer_msg->bloomfilter, DHT_BLOOM_SIZE));
2812 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2813 message_context.key = &my_identity.hashPubKey;
2814 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
2815 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2816 message_context.msg_options = ntohl (DHT_DEFAULT_FIND_PEER_OPTIONS);
2817 message_context.network_size = estimate_diameter();
2818 message_context.peer = &my_identity;
2819 message_context.importance = DHT_DEFAULT_FIND_PEER_IMPORTANCE;
2820 message_context.timeout = DHT_DEFAULT_FIND_PEER_TIMEOUT;
2822 ret = route_message(NULL, &find_peer_msg->header, &message_context);
2823 GNUNET_free(find_peer_msg);
2824 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2825 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
2827 if (newly_found_peers < bucket_size)
2829 next_send_time.value = (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) +
2830 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
2831 DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2);
2835 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
2836 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
2837 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
2839 newly_found_peers = 0;
2840 GNUNET_SCHEDULER_add_delayed (sched,
2842 &send_find_peer_message, NULL);
2847 * Handler for any generic DHT messages, calls the appropriate handler
2848 * depending on message type, sends confirmation if responses aren't otherwise
2851 * @param cls closure for the service
2852 * @param client the client we received this message from
2853 * @param message the actual message received
2856 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
2857 const struct GNUNET_MessageHeader *message)
2859 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
2860 const struct GNUNET_MessageHeader *enc_msg;
2861 struct DHT_MessageContext message_context;
2864 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
2865 enc_type = ntohs (enc_msg->type);
2868 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2869 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
2870 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
2871 GNUNET_ntohll (dht_msg->unique_id));
2873 #if DEBUG_DHT_ROUTING
2874 if (dhtlog_handle != NULL)
2875 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
2877 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2878 message_context.client = find_active_client (client);
2879 message_context.key = &dht_msg->key;
2880 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
2881 message_context.replication = ntohl (dht_msg->desired_replication_level);
2882 message_context.msg_options = ntohl (dht_msg->options);
2883 message_context.network_size = estimate_diameter();
2884 message_context.peer = &my_identity;
2885 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 4; /* Make local routing a higher priority */
2886 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
2887 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
2888 increment_stats(STAT_GET_START);
2889 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
2890 increment_stats(STAT_PUT_START);
2891 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
2892 increment_stats(STAT_FIND_PEER_START);
2894 route_message(cls, enc_msg, &message_context);
2896 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2901 * Handler for any locally received DHT control messages,
2902 * sets malicious flags mostly for now.
2904 * @param cls closure for the service
2905 * @param client the client we received this message from
2906 * @param message the actual message received
2910 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
2911 const struct GNUNET_MessageHeader *message)
2913 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
2914 (const struct GNUNET_DHT_ControlMessage *) message;
2916 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2917 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
2918 "CONTROL", ntohs(dht_control_msg->command));
2921 switch (ntohs(dht_control_msg->command))
2923 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
2924 if (ntohs(dht_control_msg->variable) > 0)
2925 malicious_get_frequency = ntohs(dht_control_msg->variable);
2926 if (malicious_get_frequency == 0)
2927 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
2928 if (malicious_getter != GNUNET_YES)
2929 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
2930 malicious_getter = GNUNET_YES;
2931 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
2933 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
2934 if (ntohs(dht_control_msg->variable) > 0)
2935 malicious_put_frequency = ntohs(dht_control_msg->variable);
2936 if (malicious_put_frequency == 0)
2937 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
2938 if (malicious_putter != GNUNET_YES)
2939 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
2940 malicious_putter = GNUNET_YES;
2941 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
2943 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
2944 if ((malicious_dropper != GNUNET_YES) && (dhtlog_handle != NULL))
2945 dhtlog_handle->set_malicious(&my_identity);
2946 malicious_dropper = GNUNET_YES;
2947 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
2950 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
2953 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2957 * Handler for any generic DHT stop messages, calls the appropriate handler
2958 * depending on message type (if processed locally)
2960 * @param cls closure for the service
2961 * @param client the client we received this message from
2962 * @param message the actual message received
2966 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
2967 const struct GNUNET_MessageHeader *message)
2970 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
2971 (const struct GNUNET_DHT_StopMessage *) message;
2972 struct DHTQueryRecord *record;
2973 struct DHTRouteSource *pos;
2976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2977 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
2978 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
2981 uid = GNUNET_ntohll(dht_stop_msg->unique_id);
2983 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
2990 if ((pos->client != NULL) && (pos->client->client_handle == client))
2992 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
2993 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
2999 GNUNET_SERVER_receive_done (client, GNUNET_OK);
3004 * Core handler for p2p route requests.
3007 handle_dht_p2p_route_request (void *cls,
3008 const struct GNUNET_PeerIdentity *peer,
3009 const struct GNUNET_MessageHeader *message,
3010 struct GNUNET_TIME_Relative latency, uint32_t distance)
3013 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3014 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3016 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
3017 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3018 struct DHT_MessageContext *message_context;
3020 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
3023 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
3028 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3033 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
3034 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3035 GNUNET_assert(message_context->bloom != NULL);
3036 message_context->hop_count = ntohl(incoming->hop_count);
3037 message_context->key = &incoming->key;
3038 message_context->replication = ntohl(incoming->desired_replication_level);
3039 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
3040 message_context->msg_options = ntohl(incoming->options);
3041 message_context->network_size = ntohl(incoming->network_size);
3042 message_context->peer = peer;
3043 message_context->importance = DHT_DEFAULT_P2P_IMPORTANCE;
3044 message_context->timeout = DHT_DEFAULT_P2P_TIMEOUT;
3045 route_message(cls, enc_msg, message_context);
3046 GNUNET_free(message_context);
3052 * Core handler for p2p route results.
3055 handle_dht_p2p_route_result (void *cls,
3056 const struct GNUNET_PeerIdentity *peer,
3057 const struct GNUNET_MessageHeader *message,
3058 struct GNUNET_TIME_Relative latency, uint32_t distance)
3061 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3062 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
3064 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
3065 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
3066 struct DHT_MessageContext message_context;
3068 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
3074 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
3075 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
3076 GNUNET_assert(message_context.bloom != NULL);
3077 message_context.key = &incoming->key;
3078 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
3079 message_context.msg_options = ntohl(incoming->options);
3080 message_context.hop_count = ntohl(incoming->hop_count);
3081 message_context.peer = peer;
3082 message_context.importance = DHT_DEFAULT_P2P_IMPORTANCE * 2; /* Make result routing a higher priority */
3083 message_context.timeout = DHT_DEFAULT_P2P_TIMEOUT;
3084 route_result_message(cls, enc_msg, &message_context);
3090 * Receive the HELLO from transport service,
3091 * free current and replace if necessary.
3094 * @param message HELLO message of peer
3097 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
3100 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3101 "Received our `%s' from transport service\n",
3105 GNUNET_assert (message != NULL);
3106 GNUNET_free_non_null(my_hello);
3107 my_hello = GNUNET_malloc(ntohs(message->size));
3108 memcpy(my_hello, message, ntohs(message->size));
3113 * Task run during shutdown.
3119 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
3122 struct PeerInfo *pos;
3123 if (transport_handle != NULL)
3125 GNUNET_free_non_null(my_hello);
3126 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
3127 GNUNET_TRANSPORT_disconnect(transport_handle);
3130 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
3132 while (k_buckets[bucket_count].head != NULL)
3134 pos = k_buckets[bucket_count].head;
3136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3137 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
3139 delete_peer(pos, bucket_count);
3142 if (coreAPI != NULL)
3145 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3146 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
3148 GNUNET_CORE_disconnect (coreAPI);
3150 if (datacache != NULL)
3153 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3154 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
3156 GNUNET_DATACACHE_destroy (datacache);
3161 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
3164 if (dhtlog_handle != NULL)
3165 GNUNET_DHTLOG_disconnect(dhtlog_handle);
3167 GNUNET_free_non_null(my_short_id);
3172 * To be called on core init/fail.
3174 * @param cls service closure
3175 * @param server handle to the server for this service
3176 * @param identity the public identity of this peer
3177 * @param publicKey the public key of this peer
3180 core_init (void *cls,
3181 struct GNUNET_CORE_Handle *server,
3182 const struct GNUNET_PeerIdentity *identity,
3183 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
3189 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3190 "%s: Connection to core FAILED!\n", "dht",
3191 GNUNET_i2s (identity));
3193 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
3194 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3198 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3199 "%s: Core connection initialized, I am peer: %s\n", "dht",
3200 GNUNET_i2s (identity));
3203 /* Copy our identity so we can use it */
3204 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3205 if (my_short_id != NULL)
3206 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3207 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3208 /* Set the server to local variable */
3211 if (dhtlog_handle != NULL)
3212 dhtlog_handle->insert_node (NULL, &my_identity);
3216 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3217 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3218 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3219 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
3224 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3225 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
3226 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
3231 * Method called whenever a peer connects.
3233 * @param cls closure
3234 * @param peer peer identity this notification is about
3235 * @param latency reported latency of the connection with peer
3236 * @param distance reported distance (DV) to peer
3238 void handle_core_connect (void *cls,
3239 const struct GNUNET_PeerIdentity * peer,
3240 struct GNUNET_TIME_Relative latency,
3243 struct PeerInfo *ret;
3246 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3247 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
3250 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3252 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));
3256 if (datacache != NULL)
3257 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
3258 ret = try_add_peer(peer,
3259 find_current_bucket(&peer->hashPubKey),
3264 newly_found_peers++;
3265 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3268 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3269 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
3274 * Method called whenever a peer disconnects.
3276 * @param cls closure
3277 * @param peer peer identity this notification is about
3279 void handle_core_disconnect (void *cls,
3281 GNUNET_PeerIdentity * peer)
3283 struct PeerInfo *to_remove;
3286 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");
3288 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3290 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));
3293 increment_stats(STAT_DISCONNECTS);
3294 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
3295 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
3296 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
3297 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
3298 delete_peer(to_remove, current_bucket);
3302 * Process dht requests.
3304 * @param cls closure
3305 * @param scheduler scheduler to use
3306 * @param server the initialized server
3307 * @param c configuration to use
3311 struct GNUNET_SCHEDULER_Handle *scheduler,
3312 struct GNUNET_SERVER_Handle *server,
3313 const struct GNUNET_CONFIGURATION_Handle *c)
3316 struct GNUNET_TIME_Relative next_send_time;
3320 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
3321 GNUNET_SERVER_add_handlers (server, plugin_handlers);
3322 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
3323 cfg, /* Main configuration */
3324 GNUNET_TIME_UNIT_FOREVER_REL,
3325 NULL, /* Closure passed to DHT functionas around? */
3326 &core_init, /* Call core_init once connected */
3327 &handle_core_connect, /* Handle connects */
3328 &handle_core_disconnect, /* remove peers on disconnects */
3329 NULL, /* Do we care about "status" updates? */
3330 NULL, /* Don't want notified about all incoming messages */
3331 GNUNET_NO, /* For header only inbound notification */
3332 NULL, /* Don't want notified about all outbound messages */
3333 GNUNET_NO, /* For header only outbound notification */
3334 core_handlers); /* Register these handlers */
3336 if (coreAPI == NULL)
3338 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
3339 NULL, NULL, NULL, NULL, NULL);
3340 if (transport_handle != NULL)
3341 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
3343 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
3345 lowest_bucket = MAX_BUCKETS - 1;
3346 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
3347 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3348 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
3349 GNUNET_assert(all_known_peers != NULL);
3350 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
3352 debug_routes = GNUNET_YES;
3356 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3359 strict_kademlia = GNUNET_YES;
3363 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3366 stop_on_closest = GNUNET_YES;
3370 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3373 stop_on_found = GNUNET_YES;
3377 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3378 "malicious_getter"))
3380 malicious_getter = GNUNET_YES;
3381 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3382 "MALICIOUS_GET_FREQUENCY",
3383 &malicious_get_frequency))
3384 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3388 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3389 "malicious_putter"))
3391 malicious_putter = GNUNET_YES;
3392 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3393 "MALICIOUS_PUT_FREQUENCY",
3394 &malicious_put_frequency))
3395 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3399 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3400 "malicious_dropper"))
3402 malicious_dropper = GNUNET_YES;
3406 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
3407 "mysql_logging_extended"))
3409 debug_routes = GNUNET_YES;
3410 debug_routes_extended = GNUNET_YES;
3413 if (GNUNET_YES == debug_routes)
3415 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
3416 if (dhtlog_handle == NULL)
3418 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3419 "Could not connect to mysql logging server, logging will not happen!");
3423 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
3427 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
3428 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
3429 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS_CLOSEST, 0, GNUNET_NO);
3430 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
3431 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
3432 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
3433 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
3434 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
3435 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
3436 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
3437 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
3438 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
3439 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
3440 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
3441 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
3442 GNUNET_STATISTICS_set(stats, STAT_BLOOM_FIND_PEER, 0, GNUNET_NO);
3443 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
3444 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
3445 GNUNET_STATISTICS_set(stats, STAT_HELLOS_PROVIDED, 0, GNUNET_NO);
3446 GNUNET_STATISTICS_set(stats, STAT_DISCONNECTS, 0, GNUNET_NO);
3449 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
3450 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
3451 (DHT_MAXIMUM_FIND_PEER_INTERVAL.value / 2) - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
3452 GNUNET_SCHEDULER_add_delayed (sched,
3454 &send_find_peer_message, NULL);
3457 /* Scheduled the task to clean up when shutdown is called */
3458 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
3459 GNUNET_TIME_UNIT_FOREVER_REL,
3460 &shutdown_task, NULL);
3464 * The main function for the dht service.
3466 * @param argc number of arguments from the command line
3467 * @param argv command line arguments
3468 * @return 0 ok, 1 on error
3471 main (int argc, char *const *argv)
3473 return (GNUNET_OK ==
3474 GNUNET_SERVICE_run (argc,
3477 GNUNET_SERVICE_OPTION_NONE,
3478 &run, NULL)) ? 0 : 1;