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_YES
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 8
64 * Minimum number of peers we need for "good" routing,
65 * any less than this and we will allow messages to
66 * travel much further through the network!
68 #define MINIMUM_PEER_THRESHOLD 20
70 #define DHT_DEFAULT_FIND_PEER_REPLICATION 10
72 #define DHT_MAX_RECENT 100
74 #define DHT_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
76 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
78 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
81 * How many initial requests to send out (in true Kademlia fashion)
83 #define DHT_KADEMLIA_REPLICATION 3
86 * Default frequency for sending malicious get messages
88 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
91 * Type for a malicious request, so we can ignore it during testing
93 #define DHT_MALICIOUS_MESSAGE_TYPE 42
95 * Default frequency for sending malicious put messages
97 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
99 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
102 * Real maximum number of hops, at which point we refuse
103 * to forward the message.
108 * Linked list of messages to send to clients.
110 struct P2PPendingMessage
113 * Pointer to next item in the list
115 struct P2PPendingMessage *next;
118 * Pointer to previous item in the list
120 struct P2PPendingMessage *prev;
123 * Message importance level.
125 unsigned int importance;
128 * How long to wait before sending message.
130 struct GNUNET_TIME_Relative timeout;
133 * Actual message to be sent; // avoid allocation
135 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
141 * Per-peer information.
146 * Next peer entry (DLL)
148 struct PeerInfo *next;
151 * Prev peer entry (DLL)
153 struct PeerInfo *prev;
156 * Head of pending messages to be sent to this peer.
158 struct P2PPendingMessage *head;
161 * Tail of pending messages to be sent to this peer.
163 struct P2PPendingMessage *tail;
166 * Core handle for sending messages to this peer.
168 struct GNUNET_CORE_TransmitHandle *th;
171 * Task for scheduling message sends.
173 GNUNET_SCHEDULER_TaskIdentifier send_task;
176 * What is the average latency for replies received?
178 struct GNUNET_TIME_Relative latency;
181 * Number of responses received
183 unsigned long long response_count;
186 * Number of requests sent
188 unsigned long long request_count;
191 * What is the identity of the peer?
193 struct GNUNET_PeerIdentity id;
196 * Transport level distance to peer.
198 unsigned int distance;
201 * Task for scheduling periodic ping messages for this peer.
203 GNUNET_SCHEDULER_TaskIdentifier ping_task;
208 * Peers are grouped into buckets.
215 struct PeerInfo *head;
220 struct PeerInfo *tail;
223 * Number of peers in the bucket.
225 unsigned int peers_size;
229 * Linked list of messages to send to clients.
231 struct PendingMessage
234 * Pointer to next item in the list
236 struct PendingMessage *next;
239 * Pointer to previous item in the list
241 struct PendingMessage *prev;
244 * Actual message to be sent; // avoid allocation
246 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
251 * Struct containing information about a client,
252 * handle to connect to it, and any pending messages
253 * that need to be sent to it.
258 * Linked list of active clients
260 struct ClientList *next;
263 * The handle to this client
265 struct GNUNET_SERVER_Client *client_handle;
268 * Handle to the current transmission request, NULL
271 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
274 * Linked list of pending messages for this client
276 struct PendingMessage *pending_head;
279 * Tail of linked list of pending messages for this client
281 struct PendingMessage *pending_tail;
287 * Context containing information about a DHT message received.
289 struct DHT_MessageContext
292 * The client this request was received from.
293 * (NULL if received from another peer)
295 struct ClientList *client;
298 * The peer this request was received from.
299 * (NULL if received from local client)
301 const struct GNUNET_PeerIdentity *peer;
304 * The key this request was about
306 const GNUNET_HashCode *key;
309 * The unique identifier of this request
314 * Desired replication level
316 uint32_t replication;
319 * Network size estimate, either ours or the sum of
320 * those routed to thus far. =~ Log of number of peers
321 * chosen from for this request.
323 uint32_t network_size;
326 * Any message options for this request
328 uint32_t msg_options;
331 * How many hops has the message already traversed?
336 * Bloomfilter for this routing request.
338 struct GNUNET_CONTAINER_BloomFilter *bloom;
341 * Did we forward this message? (may need to remember it!)
346 * Are we the closest known peer to this key (out of our neighbors?)
352 * Record used for remembering what peers are waiting for what
353 * responses (based on search key).
355 struct DHTRouteSource
360 struct DHTRouteSource *next;
365 struct DHTRouteSource *prev;
368 * Source of the request. Replies should be forwarded to
371 struct GNUNET_PeerIdentity source;
374 * If this was a local request, remember the client; otherwise NULL.
376 struct ClientList *client;
379 * Pointer to this nodes heap location (for removal)
381 struct GNUNET_CONTAINER_HeapNode *hnode;
384 * Back pointer to the record storing this information.
386 struct DHTQueryRecord *record;
389 * Task to remove this entry on timeout.
391 GNUNET_SCHEDULER_TaskIdentifier delete_task;
395 * Entry in the DHT routing table.
397 struct DHTQueryRecord
400 * Head of DLL for result forwarding.
402 struct DHTRouteSource *head;
405 * Tail of DLL for result forwarding.
407 struct DHTRouteSource *tail;
410 * Key that the record concerns.
415 * GET message of this record (what we already forwarded?).
417 //DV_DHT_MESSAGE get; Try to get away with not saving this.
420 * Bloomfilter of the peers we've replied to so far
422 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
427 * DHT Routing results structure
432 * Min heap for removal upon reaching limit
434 struct GNUNET_CONTAINER_Heap *minHeap;
437 * Hashmap for fast key based lookup
439 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
444 * DHT structure for recent requests.
446 struct RecentRequests
449 * Min heap for removal upon reaching limit
451 struct GNUNET_CONTAINER_Heap *minHeap;
454 * Hashmap for key based lookup
456 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
468 * Recent requests by hash/uid and by time inserted.
470 static struct RecentRequests recent;
473 * Don't use our routing algorithm, always route
474 * to closest peer; initially send requests to 3
477 static int strict_kademlia;
480 * Routing option to end routing when closest peer found.
482 static int stop_on_closest;
485 * Routing option to end routing when data is found.
487 static int stop_on_found;
490 * Container of active queries we should remember
492 static struct DHTResults forward_list;
495 * Handle to the datacache service (for inserting/retrieving data)
497 static struct GNUNET_DATACACHE_Handle *datacache;
500 * Handle for the statistics service.
502 struct GNUNET_STATISTICS_Handle *stats;
505 * The main scheduler to use for the DHT service
507 static struct GNUNET_SCHEDULER_Handle *sched;
510 * The configuration the DHT service is running with
512 static const struct GNUNET_CONFIGURATION_Handle *cfg;
515 * Handle to the core service
517 static struct GNUNET_CORE_Handle *coreAPI;
520 * Handle to the transport service, for getting our hello
522 static struct GNUNET_TRANSPORT_Handle *transport_handle;
525 * The identity of our peer.
527 static struct GNUNET_PeerIdentity my_identity;
530 * Short id of the peer, for printing
532 static char *my_short_id;
537 static struct GNUNET_MessageHeader *my_hello;
540 * Task to run when we shut down, cleaning up all our trash
542 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
545 * The lowest currently used bucket.
547 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
550 * The buckets (Kademlia routing table, complete with growth).
551 * Array of size MAX_BUCKET_SIZE.
553 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
556 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
558 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
561 * Maximum size for each bucket.
563 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
566 * List of active clients.
568 static struct ClientList *client_list;
571 * Handle to the DHT logger.
573 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
576 * Whether or not to send routing debugging information
577 * to the dht logging server
579 static unsigned int debug_routes;
582 * Whether or not to send FULL route information to
585 static unsigned int debug_routes_extended;
588 * GNUNET_YES or GNUNET_NO, whether or not to act as
589 * a malicious node which drops all messages
591 static unsigned int malicious_dropper;
594 * GNUNET_YES or GNUNET_NO, whether or not to act as
595 * a malicious node which sends out lots of GETS
597 static unsigned int malicious_getter;
600 * GNUNET_YES or GNUNET_NO, whether or not to act as
601 * a malicious node which sends out lots of PUTS
603 static unsigned int malicious_putter;
605 static unsigned long long malicious_get_frequency;
607 static unsigned long long malicious_put_frequency;
610 * Forward declaration.
612 static size_t send_generic_reply (void *cls, size_t size, void *buf);
614 /* Declare here so retry_core_send is aware of it */
615 size_t core_transmit_notify (void *cls,
616 size_t size, void *buf);
619 increment_stats(const char *value)
623 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
628 * Try to send another message from our core send list
631 try_core_send (void *cls,
632 const struct GNUNET_SCHEDULER_TaskContext *tc)
634 struct PeerInfo *peer = cls;
635 struct P2PPendingMessage *pending;
638 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
640 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
643 if (peer->th != NULL)
644 return; /* Message send already in progress */
646 pending = peer->head;
649 ssize = ntohs(pending->msg->size);
651 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
652 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
653 "DHT", ssize, GNUNET_i2s(&peer->id));
655 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
656 pending->timeout, &peer->id,
657 ssize, &core_transmit_notify, peer);
662 * Function called to send a request out to another peer.
663 * Called both for locally initiated requests and those
664 * received from other peers.
666 * @param cls DHT service closure argument
667 * @param msg the encapsulated message
668 * @param peer the peer to forward the message to
669 * @param msg_ctx the context of the message (hop count, bloom, etc.)
671 static void forward_result_message (void *cls,
672 const struct GNUNET_MessageHeader *msg,
673 struct PeerInfo *peer,
674 struct DHT_MessageContext *msg_ctx)
676 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
677 struct P2PPendingMessage *pending;
681 increment_stats(STAT_RESULT_FORWARDS);
682 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
683 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
684 psize = sizeof(struct P2PPendingMessage) + msize;
685 pending = GNUNET_malloc(psize);
686 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
687 pending->importance = DHT_SEND_PRIORITY;
688 pending->timeout = GNUNET_TIME_relative_get_forever();
689 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
690 result_message->header.size = htons(msize);
691 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
692 result_message->options = htonl(msg_ctx->msg_options);
693 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
694 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
695 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
696 memcpy(&result_message->key, msg_ctx->key, sizeof(GNUNET_HashCode));
697 memcpy(&result_message[1], msg, ntohs(msg->size));
699 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));
701 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
702 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
703 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
706 * Called when core is ready to send a message we asked for
707 * out to the destination.
709 * @param cls closure (NULL)
710 * @param size number of bytes available in buf
711 * @param buf where the callee should write the message
712 * @return number of bytes written to buf
714 size_t core_transmit_notify (void *cls,
715 size_t size, void *buf)
717 struct PeerInfo *peer = cls;
719 struct P2PPendingMessage *pending;
726 /* client disconnected */
728 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
733 if (peer->head == NULL)
738 pending = peer->head;
739 msize = ntohs(pending->msg->size);
743 memcpy (cbuf, pending->msg, msize);
744 GNUNET_CONTAINER_DLL_remove (peer->head,
748 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));
750 GNUNET_free (pending);
753 while (NULL != pending &&
754 (size - off >= (msize = ntohs (pending->msg->size))))
756 #if DEBUG_DHT_ROUTING
757 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);
759 memcpy (&cbuf[off], pending->msg, msize);
761 GNUNET_CONTAINER_DLL_remove (peer->head,
764 GNUNET_free (pending);
765 pending = peer->head;
768 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
769 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
771 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);
777 * Determine how many low order bits match in two
778 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
779 * the first two lowest order bits, and therefore the
780 * return value is two (NOT XOR distance, nor how many
781 * bits match absolutely!).
783 * @param first the first hashcode
784 * @param second the hashcode to compare first to
786 * @return the number of bits that match
788 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
792 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
793 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
795 return sizeof (GNUNET_HashCode) * 8;
799 * Compute the distance between have and target as a 32-bit value.
800 * Differences in the lower bits must count stronger than differences
801 * in the higher bits.
803 * @return 0 if have==target, otherwise a number
804 * that is larger as the distance between
805 * the two hash codes increases
808 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
815 /* We have to represent the distance between two 2^9 (=512)-bit
816 numbers as a 2^5 (=32)-bit number with "0" being used for the
817 two numbers being identical; furthermore, we need to
818 guarantee that a difference in the number of matching
819 bits is always represented in the result.
821 We use 2^32/2^9 numerical values to distinguish between
822 hash codes that have the same LSB bit distance and
823 use the highest 2^9 bits of the result to signify the
824 number of (mis)matching LSB bits; if we have 0 matching
825 and hence 512 mismatching LSB bits we return -1 (since
826 512 itself cannot be represented with 9 bits) */
828 /* first, calculate the most significant 9 bits of our
829 result, aka the number of LSBs */
830 bucket = matching_bits (target, have);
831 /* bucket is now a value between 0 and 512 */
833 return 0; /* perfect match */
835 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
836 below, we'd end up with max+1 (overflow)) */
838 /* calculate the most significant bits of the final result */
839 msb = (512 - bucket) << (32 - 9);
840 /* calculate the 32-9 least significant bits of the final result by
841 looking at the differences in the 32-9 bits following the
842 mismatching bit at 'bucket' */
845 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
847 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
848 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
849 last bit set will be 31 -- if
850 i does not reach 512 first... */
856 * Return a number that is larger the closer the
857 * "have" GNUNET_hash code is to the "target".
859 * @return inverse distance metric, non-zero.
860 * Must fudge the value if NO bits match.
863 inverse_distance (const GNUNET_HashCode * target,
864 const GNUNET_HashCode * have)
866 if (matching_bits(target, have) == 0)
867 return 1; /* Never return 0! */
868 return ((unsigned int) -1) - distance (target, have);
872 * Find the optimal bucket for this key, regardless
873 * of the current number of buckets in use.
875 * @param hc the hashcode to compare our identity to
877 * @return the proper bucket index, or GNUNET_SYSERR
878 * on error (same hashcode)
880 static int find_bucket(const GNUNET_HashCode *hc)
884 bits = matching_bits(&my_identity.hashPubKey, hc);
885 if (bits == MAX_BUCKETS)
886 return GNUNET_SYSERR;
887 return MAX_BUCKETS - bits - 1;
891 * Find which k-bucket this peer should go into,
892 * taking into account the size of the k-bucket
893 * array. This means that if more bits match than
894 * there are currently buckets, lowest_bucket will
897 * @param hc GNUNET_HashCode we are finding the bucket for.
899 * @return the proper bucket index for this key,
900 * or GNUNET_SYSERR on error (same hashcode)
902 static int find_current_bucket(const GNUNET_HashCode *hc)
905 actual_bucket = find_bucket(hc);
907 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
908 return GNUNET_SYSERR;
909 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
910 return lowest_bucket;
912 return actual_bucket;
916 * Find a routing table entry from a peer identity
918 * @param peer the peer to look up
920 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
923 find_bucket_by_peer(const struct PeerInfo *peer)
926 struct PeerInfo *pos;
928 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
930 pos = k_buckets[bucket].head;
939 return GNUNET_SYSERR; /* No such peer. */
944 * Print the complete routing table for this peer.
947 print_routing_table ()
950 struct PeerInfo *pos;
951 char char_buf[30000];
953 memset(char_buf, 0, sizeof(char_buf));
955 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
956 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
957 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
959 pos = k_buckets[bucket].head;
960 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
961 //fprintf(stderr, "Bucket %d:\n", bucket);
964 //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));
965 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));
969 fprintf(stderr, "%s", char_buf);
975 * Find a routing table entry from a peer identity
977 * @param peer the peer identity to look up
979 * @return the routing table entry, or NULL if not found
981 static struct PeerInfo *
982 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
985 struct PeerInfo *pos;
986 bucket = find_current_bucket(&peer->hashPubKey);
988 if (bucket == GNUNET_SYSERR)
991 pos = k_buckets[bucket].head;
994 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
998 return NULL; /* No such peer. */
1002 * Really add a peer to a bucket (only do assertions
1005 * @param peer GNUNET_PeerIdentity of the peer to add
1006 * @param bucket the already figured out bucket to add
1008 * @param latency the core reported latency of this peer
1009 * @param distance the transport level distance to this peer
1011 * @return the newly added PeerInfo
1013 static struct PeerInfo *
1014 add_peer(const struct GNUNET_PeerIdentity *peer,
1015 unsigned int bucket,
1016 struct GNUNET_TIME_Relative latency,
1017 unsigned int distance)
1019 struct PeerInfo *new_peer;
1020 GNUNET_assert(bucket < MAX_BUCKETS);
1021 GNUNET_assert(peer != NULL);
1022 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1023 new_peer->latency = latency;
1024 new_peer->distance = distance;
1025 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1027 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1028 k_buckets[bucket].tail,
1029 k_buckets[bucket].tail,
1031 k_buckets[bucket].peers_size++;
1037 * Given a peer and its corresponding bucket,
1038 * remove it from that bucket. Does not free
1039 * the PeerInfo struct, nor cancel messages
1040 * or free messages waiting to be sent to this
1043 * @param peer the peer to remove
1044 * @param bucket the bucket the peer belongs to
1046 static void remove_peer (struct PeerInfo *peer,
1047 unsigned int bucket)
1049 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1050 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1051 k_buckets[bucket].tail,
1053 k_buckets[bucket].peers_size--;
1054 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1059 * Removes peer from a bucket, then frees associated
1060 * resources and frees peer.
1062 * @param peer peer to be removed and freed
1063 * @param bucket which bucket this peer belongs to
1065 static void delete_peer (struct PeerInfo *peer,
1066 unsigned int bucket)
1068 struct P2PPendingMessage *pos;
1069 struct P2PPendingMessage *next;
1071 struct PeerInfo *peer_pos;
1073 peer_pos = k_buckets[bucket].head;
1074 while ((peer_pos != NULL) && (peer_pos != peer))
1075 peer_pos = peer_pos->next;
1076 if (peer_pos == NULL)
1078 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1079 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));
1081 GNUNET_assert(peer_pos != NULL);
1083 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1085 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1086 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1087 if (peer->th != NULL)
1088 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1091 while (pos != NULL) /* Remove any pending messages for this peer */
1098 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1099 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1105 * Iterator over hash map entries.
1107 * @param cls closure
1108 * @param key current key code
1109 * @param value PeerInfo of the peer to move to new lowest bucket
1110 * @return GNUNET_YES if we should continue to
1114 static int move_lowest_bucket (void *cls,
1115 const GNUNET_HashCode * key,
1118 struct PeerInfo *peer = value;
1121 new_bucket = lowest_bucket - 1;
1122 remove_peer(peer, lowest_bucket);
1123 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1124 k_buckets[new_bucket].tail,
1125 k_buckets[new_bucket].tail,
1127 k_buckets[new_bucket].peers_size++;
1133 * The current lowest bucket is full, so change the lowest
1134 * bucket to the next lower down, and move any appropriate
1135 * entries in the current lowest bucket to the new bucket.
1137 static void enable_next_bucket()
1139 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1140 struct PeerInfo *pos;
1141 GNUNET_assert(lowest_bucket > 0);
1142 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1143 pos = k_buckets[lowest_bucket].head;
1146 fprintf(stderr, "Printing RT before new bucket\n");
1147 print_routing_table();
1149 /* Populate the array of peers which should be in the next lowest bucket */
1152 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1153 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1157 /* Remove peers from lowest bucket, insert into next lowest bucket */
1158 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1159 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1160 lowest_bucket = lowest_bucket - 1;
1162 fprintf(stderr, "Printing RT after new bucket\n");
1163 print_routing_table();
1168 * Function called to send a request out to another peer.
1169 * Called both for locally initiated requests and those
1170 * received from other peers.
1172 * @param cls DHT service closure argument (unused)
1173 * @param msg the encapsulated message
1174 * @param peer the peer to forward the message to
1175 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1177 static void forward_message (void *cls,
1178 const struct GNUNET_MessageHeader *msg,
1179 struct PeerInfo *peer,
1180 struct DHT_MessageContext *msg_ctx)
1182 struct GNUNET_DHT_P2PRouteMessage *route_message;
1183 struct P2PPendingMessage *pending;
1187 increment_stats(STAT_ROUTE_FORWARDS);
1188 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1189 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1190 psize = sizeof(struct P2PPendingMessage) + msize;
1191 pending = GNUNET_malloc(psize);
1192 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1193 pending->importance = DHT_SEND_PRIORITY;
1194 pending->timeout = GNUNET_TIME_relative_get_forever();
1195 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1196 route_message->header.size = htons(msize);
1197 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1198 route_message->options = htonl(msg_ctx->msg_options);
1199 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1200 route_message->network_size = htonl(msg_ctx->network_size);
1201 route_message->desired_replication_level = htonl(msg_ctx->replication);
1202 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1203 if (msg_ctx->bloom != NULL)
1204 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1205 if (msg_ctx->key != NULL)
1206 memcpy(&route_message->key, msg_ctx->key, sizeof(GNUNET_HashCode));
1207 memcpy(&route_message[1], msg, ntohs(msg->size));
1209 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));
1211 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1212 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1213 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1218 * Task used to send ping messages to peers so that
1219 * they don't get disconnected.
1221 * @param cls the peer to send a ping message to
1222 * @param tc context, reason, etc.
1225 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1227 struct PeerInfo *peer = cls;
1228 struct GNUNET_MessageHeader ping_message;
1229 struct DHT_MessageContext message_context;
1231 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1234 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1235 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1237 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1239 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1241 forward_message(NULL, &ping_message, peer, &message_context);
1242 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1246 * Schedule PING messages for the top X peers in each
1247 * bucket of the routing table (so core won't disconnect them!)
1249 void schedule_ping_messages()
1251 unsigned int bucket;
1253 struct PeerInfo *pos;
1254 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1256 pos = k_buckets[bucket].head;
1260 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1261 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1262 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1264 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1265 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1275 * Attempt to add a peer to our k-buckets.
1277 * @param peer, the peer identity of the peer being added
1279 * @return NULL if the peer was not added,
1280 * pointer to PeerInfo for new peer otherwise
1282 static struct PeerInfo *
1283 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1284 unsigned int bucket,
1285 struct GNUNET_TIME_Relative latency,
1286 unsigned int distance)
1289 struct PeerInfo *new_peer;
1290 peer_bucket = find_current_bucket(&peer->hashPubKey);
1291 if (peer_bucket == GNUNET_SYSERR)
1294 GNUNET_assert(peer_bucket >= lowest_bucket);
1295 new_peer = add_peer(peer, peer_bucket, latency, distance);
1297 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1298 enable_next_bucket();
1300 schedule_ping_messages();
1307 * Task run to check for messages that need to be sent to a client.
1309 * @param client a ClientList, containing the client and any messages to be sent to it
1312 process_pending_messages (struct ClientList *client)
1314 if (client->pending_head == NULL)
1316 if (client->transmit_handle != NULL)
1318 client->transmit_handle =
1319 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1320 ntohs (client->pending_head->msg->
1322 GNUNET_TIME_UNIT_FOREVER_REL,
1323 &send_generic_reply, client);
1327 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1328 * request. A ClientList is passed as closure, take the head of the list
1329 * and copy it into buf, which has the result of sending the message to the
1332 * @param cls closure to this call
1333 * @param size maximum number of bytes available to send
1334 * @param buf where to copy the actual message to
1336 * @return the number of bytes actually copied, 0 indicates failure
1339 send_generic_reply (void *cls, size_t size, void *buf)
1341 struct ClientList *client = cls;
1343 struct PendingMessage *reply;
1347 client->transmit_handle = NULL;
1350 /* client disconnected */
1354 while ( (NULL != (reply = client->pending_head)) &&
1355 (size >= off + (msize = ntohs (reply->msg->size))))
1357 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1358 client->pending_tail,
1360 memcpy (&cbuf[off], reply->msg, msize);
1361 GNUNET_free (reply);
1364 process_pending_messages (client);
1370 * Add a PendingMessage to the clients list of messages to be sent
1372 * @param client the active client to send the message to
1373 * @param pending_message the actual message to send
1376 add_pending_message (struct ClientList *client,
1377 struct PendingMessage *pending_message)
1379 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1380 client->pending_tail,
1381 client->pending_tail,
1383 process_pending_messages (client);
1390 * Called when a reply needs to be sent to a client, as
1391 * a result it found to a GET or FIND PEER request.
1393 * @param client the client to send the reply to
1394 * @param message the encapsulated message to send
1395 * @param uid the unique identifier of this request
1398 send_reply_to_client (struct ClientList *client,
1399 const struct GNUNET_MessageHeader *message,
1400 unsigned long long uid)
1402 struct GNUNET_DHT_RouteResultMessage *reply;
1403 struct PendingMessage *pending_message;
1407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1408 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1410 msize = ntohs (message->size);
1411 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1412 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1414 GNUNET_break_op (0);
1418 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1419 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1420 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1421 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1422 reply->header.size = htons (tsize);
1423 reply->unique_id = GNUNET_htonll (uid);
1424 memcpy (&reply[1], message, msize);
1426 add_pending_message (client, pending_message);
1430 * Consider whether or not we would like to have this peer added to
1431 * our routing table. Check whether bucket for this peer is full,
1432 * if so return negative; if not return positive. Since peers are
1433 * only added on CORE level connect, this doesn't actually add the
1434 * peer to the routing table.
1436 * @param peer the peer we are considering adding
1438 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1441 * FIXME: Think about making a context for this call so that we can
1442 * ping the oldest peer in the current bucket and consider
1443 * removing it in lieu of the new peer.
1445 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1449 if (GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1450 return GNUNET_NO; /* We already know this peer (are connected even!) */
1451 bucket = find_current_bucket(&peer->hashPubKey);
1452 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1459 * Main function that handles whether or not to route a result
1460 * message to other peers, or to send to our local client.
1462 * @param msg the result message to be routed
1463 * @return the number of peers the message was routed to,
1464 * GNUNET_SYSERR on failure
1466 static int route_result_message(void *cls,
1467 struct GNUNET_MessageHeader *msg,
1468 struct DHT_MessageContext *message_context)
1470 struct GNUNET_PeerIdentity new_peer;
1471 struct DHTQueryRecord *record;
1472 struct DHTRouteSource *pos;
1473 struct PeerInfo *peer_info;
1474 const struct GNUNET_MessageHeader *hello_msg;
1476 increment_stats(STAT_RESULTS);
1478 * If a find peer result message is received and contains a valid
1479 * HELLO for another peer, offer it to the transport service.
1481 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1483 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1486 hello_msg = &msg[1];
1487 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1489 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1492 else /* We have a valid hello, and peer id stored in new_peer */
1494 increment_stats(STAT_FIND_PEER_REPLY);
1495 if (GNUNET_YES == consider_peer(&new_peer))
1497 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1498 /* GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_UNIT_FOREVER_REL, &new_peer, NULL, NULL); */
1499 /* peer_request_connect call causes service to segfault */
1500 /* FIXME: Do we need this (peer_request_connect call)??? */
1505 if (malicious_dropper == GNUNET_YES)
1508 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, message_context->key);
1510 if (record == NULL) /* No record of this message! */
1513 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1514 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1515 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1517 #if DEBUG_DHT_ROUTING
1519 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1521 dhtlog_handle->insert_route (NULL,
1522 message_context->unique_id,
1524 message_context->hop_count,
1527 message_context->key,
1528 message_context->peer, NULL);
1531 if (message_context->bloom != NULL)
1533 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1534 message_context->bloom = NULL;
1542 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1545 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1546 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
1547 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1549 #if DEBUG_DHT_ROUTING
1550 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1552 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
1553 message_context->hop_count,
1554 GNUNET_YES, &my_identity, message_context->key,
1555 message_context->peer, NULL);
1558 increment_stats(STAT_RESULTS_TO_CLIENT);
1559 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
1560 increment_stats(STAT_GET_REPLY);
1562 send_reply_to_client(pos->client, msg, message_context->unique_id);
1564 else /* Send to peer */
1566 peer_info = find_peer_by_id(&pos->source);
1567 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
1573 if (message_context->bloom == NULL)
1574 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1575 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
1576 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey))
1579 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1580 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
1581 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1583 #if DEBUG_DHT_ROUTING
1584 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1586 dhtlog_handle->insert_route (NULL, message_context->unique_id,
1588 message_context->hop_count,
1589 GNUNET_NO, &my_identity, message_context->key,
1590 message_context->peer, &pos->source);
1593 forward_result_message(cls, msg, peer_info, message_context);
1598 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1599 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
1600 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1606 if (message_context->bloom != NULL)
1607 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1612 * Iterator for local get request results,
1614 * @param cls closure for iterator, a DatacacheGetContext
1615 * @param exp when does this value expire?
1616 * @param key the key this data is stored under
1617 * @param size the size of the data identified by key
1618 * @param data the actual data
1619 * @param type the type of the data
1621 * @return GNUNET_OK to continue iteration, anything else
1622 * to stop iteration.
1625 datacache_get_iterator (void *cls,
1626 struct GNUNET_TIME_Absolute exp,
1627 const GNUNET_HashCode * key,
1628 uint32_t size, const char *data, uint32_t type)
1630 struct DHT_MessageContext *msg_ctx = cls;
1631 struct DHT_MessageContext *new_msg_ctx;
1632 struct GNUNET_DHT_GetResultMessage *get_result;
1634 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1635 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
1637 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
1638 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
1640 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
1641 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
1642 get_result->header.size =
1643 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
1644 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
1645 get_result->type = htons (type);
1646 memcpy (&get_result[1], data, size);
1647 new_msg_ctx->peer = &my_identity;
1648 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1649 new_msg_ctx->hop_count = 0;
1650 increment_stats(STAT_GET_RESPONSE_START);
1651 route_result_message(cls, &get_result->header, new_msg_ctx);
1652 GNUNET_free(new_msg_ctx);
1653 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
1654 // datacache_get_ctx->unique_id);
1655 GNUNET_free (get_result);
1661 * Server handler for all dht get requests, look for data,
1662 * if found, send response either to clients or other peers.
1664 * @param cls closure for service
1665 * @param msg the actual get message
1666 * @param message_context struct containing pertinent information about the get request
1668 * @return number of items found for GET request
1671 handle_dht_get (void *cls,
1672 const struct GNUNET_MessageHeader *msg,
1673 struct DHT_MessageContext *message_context)
1675 const struct GNUNET_DHT_GetMessage *get_msg;
1677 unsigned int results;
1679 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
1680 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
1686 get_type = ntohs (get_msg->type);
1688 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1689 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
1690 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
1691 message_context->unique_id);
1693 increment_stats(STAT_GETS);
1695 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
1698 if (datacache != NULL)
1700 GNUNET_DATACACHE_get (datacache, message_context->key, get_type,
1701 &datacache_get_iterator, message_context);
1706 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1707 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
1708 results, "GET", message_context->unique_id);
1710 #if DEBUG_DHT_ROUTING
1711 if ((debug_routes) && (dhtlog_handle != NULL))
1713 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
1714 message_context->hop_count, GNUNET_YES, &my_identity,
1715 message_context->key);
1718 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1720 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
1721 message_context->hop_count, GNUNET_YES,
1722 &my_identity, message_context->key, message_context->peer,
1728 if (message_context->hop_count == 0) /* Locally initiated request */
1730 #if DEBUG_DHT_ROUTING
1731 if ((debug_routes) && (dhtlog_handle != NULL))
1733 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
1734 message_context->hop_count, GNUNET_NO, &my_identity,
1735 message_context->key);
1745 * Server handler for initiating local dht find peer requests
1747 * @param cls closure for service
1748 * @param find_msg the actual find peer message
1749 * @param message_context struct containing pertinent information about the request
1753 handle_dht_find_peer (void *cls,
1754 const struct GNUNET_MessageHeader *find_msg,
1755 struct DHT_MessageContext *message_context)
1757 struct GNUNET_MessageHeader *find_peer_result;
1758 struct DHT_MessageContext *new_msg_ctx;
1763 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1764 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
1765 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
1766 ntohs (find_msg->size),
1767 sizeof (struct GNUNET_MessageHeader));
1769 if (my_hello == NULL)
1772 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1773 "`%s': Our HELLO is null, can't return.\n",
1778 /* Simplistic find_peer functionality, always return our hello */
1779 hello_size = ntohs(my_hello->size);
1780 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
1782 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1784 GNUNET_break_op (0);
1788 find_peer_result = GNUNET_malloc (tsize);
1789 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
1790 find_peer_result->size = htons (tsize);
1791 memcpy (&find_peer_result[1], my_hello, hello_size);
1793 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1794 "`%s': Sending hello size %d to requesting peer.\n",
1797 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
1798 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
1799 new_msg_ctx->peer = &my_identity;
1800 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1801 new_msg_ctx->hop_count = 0;
1802 increment_stats(STAT_FIND_PEER_ANSWER);
1803 route_result_message(cls, find_peer_result, new_msg_ctx);
1804 GNUNET_free(new_msg_ctx);
1805 #if DEBUG_DHT_ROUTING
1806 if ((debug_routes) && (dhtlog_handle != NULL))
1808 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
1809 message_context->hop_count, GNUNET_YES, &my_identity,
1810 message_context->key);
1813 //send_reply_to_client(message_context->client, find_peer_result, message_context->unique_id);
1814 GNUNET_free(find_peer_result);
1819 * Server handler for initiating local dht put requests
1821 * @param cls closure for service
1822 * @param msg the actual put message
1823 * @param message_context struct containing pertinent information about the request
1826 handle_dht_put (void *cls,
1827 const struct GNUNET_MessageHeader *msg,
1828 struct DHT_MessageContext *message_context)
1830 struct GNUNET_DHT_PutMessage *put_msg;
1834 GNUNET_assert (ntohs (msg->size) >=
1835 sizeof (struct GNUNET_DHT_PutMessage));
1838 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
1839 put_type = ntohs (put_msg->type);
1841 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
1844 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
1846 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1847 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
1848 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
1850 #if DEBUG_DHT_ROUTING
1851 if (message_context->hop_count == 0) /* Locally initiated request */
1853 if ((debug_routes) && (dhtlog_handle != NULL))
1855 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
1856 message_context->hop_count, GNUNET_NO, &my_identity,
1857 message_context->key);
1862 if (message_context->closest != GNUNET_YES)
1865 #if DEBUG_DHT_ROUTING
1866 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1868 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
1869 message_context->hop_count, GNUNET_YES,
1870 &my_identity, message_context->key, message_context->peer,
1874 if ((debug_routes) && (dhtlog_handle != NULL))
1876 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
1877 message_context->hop_count, GNUNET_YES, &my_identity,
1878 message_context->key);
1882 increment_stats(STAT_PUTS_INSERTED);
1883 if (datacache != NULL)
1884 GNUNET_DATACACHE_put (datacache, message_context->key, data_size,
1885 (char *) &put_msg[1], put_type,
1886 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
1888 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1889 "`%s:%s': %s request received, but have no datacache!\n",
1890 my_short_id, "DHT", "PUT");
1894 * Estimate the diameter of the network based
1895 * on how many buckets are currently in use.
1896 * Concept here is that the diameter of the network
1897 * is roughly the distance a message must travel in
1898 * order to reach its intended destination. Since
1899 * at each hop we expect to get one bit closer, and
1900 * we have one bit per bucket, the number of buckets
1901 * in use should be the largest number of hops for
1902 * a sucessful message. (of course, this assumes we
1903 * know all peers in the network!)
1905 * @return ballpark diameter figure
1907 static unsigned int estimate_diameter()
1909 return MAX_BUCKETS - lowest_bucket;
1913 * To how many peers should we (on average)
1914 * forward the request to obtain the desired
1915 * target_replication count (on average).
1917 * Always 0, 1 or 2 (don't send, send once, split)
1920 get_forward_count (unsigned int hop_count, size_t target_replication)
1922 double target_count;
1923 unsigned int target_value;
1924 unsigned int diameter;
1927 * If we are behaving in strict kademlia mode, send multiple initial requests,
1928 * but then only send to 1 or 0 peers.
1930 if (strict_kademlia == GNUNET_YES)
1933 return DHT_KADEMLIA_REPLICATION;
1934 else if (hop_count < MAX_HOPS)
1940 /* FIXME: the smaller we think the network is the more lenient we should be for
1941 * routing right? The estimation below only works if we think we have reasonably
1942 * full routing tables, which for our RR topologies may not be the case!
1944 diameter = estimate_diameter ();
1945 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
1948 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1949 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
1950 "DHT", estimate_diameter(), lowest_bucket);
1954 else if (hop_count > MAX_HOPS)
1957 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1958 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
1963 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
1964 target_replication / (target_replication * (hop_count + 1) + diameter);
1968 while (target_value < target_count)
1969 target_value++; /* target_value is ALWAYS 1 after this "loop" */
1973 if ((target_count + 1 - target_value) >
1974 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1975 RAND_MAX) / RAND_MAX)
1977 return target_value;
1981 * Find the closest peer in our routing table to the
1984 * @return The closest peer in our routing table to the
1985 * key, or NULL on error.
1987 static struct PeerInfo *
1988 find_closest_peer (const GNUNET_HashCode *hc)
1990 struct PeerInfo *pos;
1991 struct PeerInfo *current_closest;
1992 unsigned int lowest_distance;
1993 unsigned int temp_distance;
1997 lowest_distance = -1;
1999 if (k_buckets[lowest_bucket].peers_size == 0)
2002 current_closest = NULL;
2003 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
2005 pos = k_buckets[bucket].head;
2007 while ((pos != NULL) && (count < bucket_size))
2009 temp_distance = distance(&pos->id.hashPubKey, hc);
2010 if (temp_distance <= lowest_distance)
2012 lowest_distance = temp_distance;
2013 current_closest = pos;
2019 GNUNET_assert(current_closest != NULL);
2020 return current_closest;
2024 * Check whether my identity is closer than any known peers.
2026 * @param target hash code to check closeness to
2028 * Return GNUNET_YES if node location is closest, GNUNET_NO
2032 am_closest_peer (const GNUNET_HashCode * target)
2038 struct PeerInfo *pos;
2039 unsigned int my_distance;
2041 bucket_num = find_current_bucket(target);
2042 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2045 bits = matching_bits(&my_identity.hashPubKey, target);
2046 my_distance = distance(&my_identity.hashPubKey, target);
2048 pos = k_buckets[bucket_num].head;
2050 while ((pos != NULL) && (count < bucket_size))
2052 other_bits = matching_bits(&pos->id.hashPubKey, target);
2053 if (other_bits > bits)
2055 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2058 /* FIXME: why not just return GNUNET_YES here? We are certainly close. */
2059 /*if (distance(&pos->id.hashPubKey, target) < my_distance)
2066 GNUNET_GE_LOG (coreAPI->ectx,
2067 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2068 GNUNET_GE_BULK, "closest peer\n");
2069 printPeerBits (&closest);
2070 GNUNET_GE_LOG (coreAPI->ectx,
2071 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2072 GNUNET_GE_BULK, "me\n");
2073 printPeerBits (coreAPI->my_identity);
2074 GNUNET_GE_LOG (coreAPI->ectx,
2075 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2076 GNUNET_GE_BULK, "key\n");
2077 printKeyBits (target);
2078 GNUNET_GE_LOG (coreAPI->ectx,
2079 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2081 "closest peer inverse distance is %u, mine is %u\n",
2082 inverse_distance (target, &closest.hashPubKey),
2083 inverse_distance (target,
2084 &coreAPI->my_identity->hashPubKey));
2087 /* No peers closer, we are the closest! */
2094 * Select a peer from the routing table that would be a good routing
2095 * destination for sending a message for "target". The resulting peer
2096 * must not be in the set of blocked peers.<p>
2098 * Note that we should not ALWAYS select the closest peer to the
2099 * target, peers further away from the target should be chosen with
2100 * exponentially declining probability.
2102 * @param target the key we are selecting a peer to route to
2103 * @param bloom a bloomfilter containing entries this request has seen already
2105 * @return Peer to route to, or NULL on error
2107 static struct PeerInfo *
2108 select_peer (const GNUNET_HashCode * target,
2109 struct GNUNET_CONTAINER_BloomFilter *bloom)
2111 unsigned int distance;
2114 struct PeerInfo *pos;
2115 struct PeerInfo *chosen;
2116 unsigned long long largest_distance;
2117 unsigned long long total_distance;
2118 unsigned long long selected;
2120 if (strict_kademlia == GNUNET_YES)
2122 largest_distance = 0;
2124 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2126 pos = k_buckets[bc].head;
2128 while ((pos != NULL) && (count < bucket_size))
2130 /* If we are doing strict Kademlia like routing, then checking the bloomfilter is basically cheating! */
2132 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2134 distance = inverse_distance (target, &pos->id.hashPubKey);
2135 if (distance > largest_distance)
2138 largest_distance = distance;
2146 if ((largest_distance > 0) && (chosen != NULL))
2148 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2160 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2162 pos = k_buckets[bc].head;
2164 while ((pos != NULL) && (count < bucket_size))
2166 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2167 total_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2169 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2170 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2171 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2177 if (total_distance == 0)
2182 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2183 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2185 pos = k_buckets[bc].head;
2187 while ((pos != NULL) && (count < bucket_size))
2189 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2191 distance = inverse_distance (target, &pos->id.hashPubKey);
2192 if (distance > selected)
2194 selected -= distance;
2199 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2200 "`%s:%s': peer %s matches bloomfilter.\n",
2201 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2209 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2210 "`%s:%s': peer %s matches bloomfilter.\n",
2211 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2219 * Task used to remove forwarding entries, either
2220 * after timeout, when full, or on shutdown.
2222 * @param cls the entry to remove
2223 * @param tc context, reason, etc.
2226 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2228 struct DHTRouteSource *source_info = cls;
2229 struct DHTQueryRecord *record;
2230 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2231 record = source_info->record;
2232 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2234 if (record->head == NULL) /* No more entries in DLL */
2236 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2237 GNUNET_free(record);
2239 GNUNET_free(source_info);
2243 * Remember this routing request so that if a reply is
2244 * received we can either forward it to the correct peer
2245 * or return the result locally.
2247 * @param cls DHT service closure
2248 * @param msg_ctx Context of the route request
2250 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2252 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2254 struct DHTQueryRecord *record;
2255 struct DHTRouteSource *source_info;
2256 struct DHTRouteSource *pos;
2257 struct GNUNET_TIME_Absolute now;
2258 unsigned int current_size;
2260 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2261 while (current_size >= MAX_OUTSTANDING_FORWARDS)
2263 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2264 record = source_info->record;
2265 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2266 if (record->head == NULL) /* No more entries in DLL */
2268 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2269 GNUNET_free(record);
2271 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2272 GNUNET_free(source_info);
2273 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2275 now = GNUNET_TIME_absolute_get();
2276 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, msg_ctx->key);
2277 if (record != NULL) /* Already know this request! */
2282 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
2283 break; /* Already have this peer in reply list! */
2286 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
2288 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
2294 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
2295 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2296 memcpy(&record->key, msg_ctx->key, sizeof(GNUNET_HashCode));
2299 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
2300 source_info->record = record;
2301 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
2302 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
2303 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
2304 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
2306 source_info->client = msg_ctx->client;
2307 now = GNUNET_TIME_absolute_get_forever();
2309 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
2311 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2312 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
2313 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
2320 * Main function that handles whether or not to route a message to other
2323 * @param msg the message to be routed
2325 * @return the number of peers the message was routed to,
2326 * GNUNET_SYSERR on failure
2328 static int route_message(void *cls,
2329 const struct GNUNET_MessageHeader *msg,
2330 struct DHT_MessageContext *message_context)
2333 struct PeerInfo *selected;
2334 struct PeerInfo *nearest;
2335 unsigned int forward_count;
2339 #if DEBUG_DHT_ROUTING
2343 if (malicious_dropper == GNUNET_YES)
2345 #if DEBUG_DHT_ROUTING
2346 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2348 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2349 message_context->hop_count, GNUNET_SYSERR,
2350 &my_identity, message_context->key, message_context->peer,
2354 if (message_context->bloom != NULL)
2355 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2361 increment_stats(STAT_ROUTES);
2362 message_context->closest = am_closest_peer(message_context->key);
2363 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
2364 nearest = find_closest_peer(message_context->key);
2366 if (message_context->bloom == NULL)
2367 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2368 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2370 if (((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
2371 || ((strict_kademlia == GNUNET_YES) && (message_context->closest == GNUNET_YES)))
2374 #if DEBUG_DHT_ROUTING
2375 if (forward_count == 0)
2376 ret = GNUNET_SYSERR;
2380 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2382 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2383 message_context->hop_count, ret,
2384 &my_identity, message_context->key, message_context->peer,
2389 switch (ntohs(msg->type))
2391 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
2392 cache_response (cls, message_context);
2393 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
2396 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
2397 increment_stats(STAT_PUTS);
2398 handle_dht_put (cls, msg, message_context);
2400 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
2401 increment_stats(STAT_FIND_PEER);
2402 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
2404 cache_response (cls, message_context);
2405 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
2406 handle_dht_find_peer (cls, msg, message_context);
2408 #if DEBUG_DHT_ROUTING
2409 if (message_context->hop_count == 0) /* Locally initiated request */
2411 if ((debug_routes) && (dhtlog_handle != NULL))
2413 dhtlog_handle->insert_dhtkey(NULL, message_context->key);
2414 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2415 message_context->hop_count, GNUNET_NO, &my_identity,
2416 message_context->key);
2422 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2423 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
2426 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent->hashmap, message_context->key))
2428 if (GNUNET_SYSERR = GNUNET_CONTAINER_multihashmap_get_multiple (recent->hashmap, message_context->key, &find_matching_recent, &message_context)) /* Have too recently seen this request! */
2432 else /* Exact match not found, but same key found */
2434 recent_req = GNUNET_CONTAINER_multihashmap_get(recent->hashmap, message_context->key);
2439 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
2440 recent_req->uid = message_context->unique_id;
2441 memcmp(&recent_req->key, message_context->key, sizeof(GNUNET_HashCode));
2442 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
2443 GNUNET_CONTAINER_heap_insert(recent->minHeap, recent_req, GNUNET_TIME_absolute_get());
2444 GNUNET_CONTAINER_multihashmap_put(recent->hashmap, message_context->key, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2447 if (GNUNET_CONTAINER_multihashmap_size(recent->hashmap) > DHT_MAX_RECENT)
2449 remove_oldest_recent();
2452 for (i = 0; i < forward_count; i++)
2454 selected = select_peer(message_context->key, message_context->bloom);
2456 if (selected != NULL)
2458 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
2459 #if DEBUG_DHT_ROUTING > 1
2460 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
2461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2462 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
2463 "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));
2464 GNUNET_free(nearest_buf);
2466 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2468 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2469 message_context->hop_count, GNUNET_NO,
2470 &my_identity, message_context->key, message_context->peer,
2473 forward_message(cls, msg, selected, message_context);
2478 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2479 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
2484 #if DEBUG_DHT_ROUTING > 1
2485 if (forward_count == 0)
2487 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2488 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
2489 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2493 if (message_context->bloom != NULL)
2494 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2496 return forward_count;
2500 * Find a client if it exists, add it otherwise.
2502 * @param client the server handle to the client
2504 * @return the client if found, a new client otherwise
2506 static struct ClientList *
2507 find_active_client (struct GNUNET_SERVER_Client *client)
2509 struct ClientList *pos = client_list;
2510 struct ClientList *ret;
2514 if (pos->client_handle == client)
2519 ret = GNUNET_malloc (sizeof (struct ClientList));
2520 ret->client_handle = client;
2521 ret->next = client_list;
2527 * Task to send a malicious put message across the network.
2529 * @param cls closure for this task
2530 * @param tc the context under which the task is running
2533 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2535 static struct GNUNET_DHT_PutMessage put_message;
2536 static struct DHT_MessageContext message_context;
2537 static GNUNET_HashCode key;
2538 unsigned int mcsize;
2539 uint32_t random_key;
2540 put_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
2541 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
2542 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2543 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
2544 mcsize = sizeof(struct DHT_MessageContext) + sizeof(GNUNET_HashCode);
2545 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2546 message_context.client = NULL;
2547 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2548 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2549 message_context.key = &key;
2550 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2551 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2552 message_context.msg_options = ntohl (0);
2553 message_context.network_size = estimate_diameter();
2554 message_context.peer = &my_identity;
2555 increment_stats(STAT_PUT_START);
2556 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2557 route_message(NULL, &put_message.header, &message_context);
2558 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
2563 * Task to send a malicious put message across the network.
2565 * @param cls closure for this task
2566 * @param tc the context under which the task is running
2569 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2571 static struct GNUNET_DHT_GetMessage get_message;
2572 static struct DHT_MessageContext message_context;
2573 static GNUNET_HashCode key;
2574 unsigned int mcsize;
2575 uint32_t random_key;
2576 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
2577 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
2578 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2579 mcsize = sizeof(struct DHT_MessageContext) + sizeof(GNUNET_HashCode);
2580 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2581 message_context.client = NULL;
2582 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2583 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2584 message_context.key = &key;
2585 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2586 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2587 message_context.msg_options = ntohl (0);
2588 message_context.network_size = estimate_diameter();
2589 message_context.peer = &my_identity;
2590 increment_stats(STAT_GET_START);
2591 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2592 route_message(NULL, &get_message.header, &message_context);
2593 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
2597 * Task to send a find peer message for our own peer identifier
2598 * so that we can find the closest peers in the network to ourselves
2599 * and attempt to connect to them.
2601 * @param cls closure for this task
2602 * @param tc the context under which the task is running
2605 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2607 struct GNUNET_MessageHeader *find_peer_msg;
2608 struct DHT_MessageContext message_context;
2610 struct GNUNET_TIME_Relative next_send_time;
2612 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2615 increment_stats(STAT_FIND_PEER_START);
2617 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_MessageHeader));
2618 find_peer_msg->size = htons(sizeof(struct GNUNET_MessageHeader));
2619 find_peer_msg->type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
2620 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2621 message_context.key = &my_identity.hashPubKey;
2622 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
2623 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2624 message_context.msg_options = ntohl (DHT_DEFAULT_FIND_PEER_OPTIONS);
2625 message_context.network_size = estimate_diameter();
2626 message_context.peer = &my_identity;
2628 ret = route_message(NULL, find_peer_msg, &message_context);
2629 GNUNET_free(find_peer_msg);
2630 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2631 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
2633 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
2634 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
2635 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
2636 GNUNET_SCHEDULER_add_delayed (sched,
2638 &send_find_peer_message, NULL);
2642 * Handler for any generic DHT messages, calls the appropriate handler
2643 * depending on message type, sends confirmation if responses aren't otherwise
2646 * @param cls closure for the service
2647 * @param client the client we received this message from
2648 * @param message the actual message received
2651 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
2652 const struct GNUNET_MessageHeader *message)
2654 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
2655 const struct GNUNET_MessageHeader *enc_msg;
2656 struct DHT_MessageContext message_context;
2659 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
2660 enc_type = ntohs (enc_msg->type);
2663 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2664 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
2665 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
2666 GNUNET_ntohll (dht_msg->unique_id));
2668 #if DEBUG_DHT_ROUTING
2669 if (dhtlog_handle != NULL)
2670 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
2672 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2673 message_context.client = find_active_client (client);
2674 message_context.key = &dht_msg->key;
2675 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
2676 message_context.replication = ntohl (dht_msg->desired_replication_level);
2677 message_context.msg_options = ntohl (dht_msg->options);
2678 message_context.network_size = estimate_diameter();
2679 message_context.peer = &my_identity;
2681 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
2682 increment_stats(STAT_GET_START);
2683 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
2684 increment_stats(STAT_PUT_START);
2685 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
2686 increment_stats(STAT_FIND_PEER_START);
2688 route_message(cls, enc_msg, &message_context);
2690 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2695 * Handler for any locally received DHT control messages,
2696 * sets malicious flags mostly for now.
2698 * @param cls closure for the service
2699 * @param client the client we received this message from
2700 * @param message the actual message received
2704 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
2705 const struct GNUNET_MessageHeader *message)
2707 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
2708 (const struct GNUNET_DHT_ControlMessage *) message;
2710 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2711 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
2712 "CONTROL", ntohs(dht_control_msg->command));
2715 switch (ntohs(dht_control_msg->command))
2717 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
2718 if (ntohs(dht_control_msg->variable) > 0)
2719 malicious_get_frequency = ntohs(dht_control_msg->variable);
2720 if (malicious_getter != GNUNET_YES)
2721 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
2722 malicious_getter = GNUNET_YES;
2723 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
2725 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
2726 if (ntohs(dht_control_msg->variable) > 0)
2727 malicious_put_frequency = ntohs(dht_control_msg->variable);
2728 if (malicious_putter != GNUNET_YES)
2729 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
2730 malicious_putter = GNUNET_YES;
2731 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
2733 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
2734 malicious_dropper = GNUNET_YES;
2735 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
2738 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
2741 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2745 * Handler for any generic DHT stop messages, calls the appropriate handler
2746 * depending on message type (if processed locally)
2748 * @param cls closure for the service
2749 * @param client the client we received this message from
2750 * @param message the actual message received
2754 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
2755 const struct GNUNET_MessageHeader *message)
2758 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
2759 (const struct GNUNET_DHT_StopMessage *) message;
2760 struct DHTQueryRecord *record;
2761 struct DHTRouteSource *pos;
2764 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2765 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
2766 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
2769 uid = GNUNET_ntohll(dht_stop_msg->unique_id);
2771 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
2778 if ((pos->client != NULL) && (pos->client->client_handle == client))
2780 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
2781 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
2787 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2792 * Core handler for p2p route requests.
2795 handle_dht_p2p_route_request (void *cls,
2796 const struct GNUNET_PeerIdentity *peer,
2797 const struct GNUNET_MessageHeader *message,
2798 struct GNUNET_TIME_Relative latency, uint32_t distance)
2801 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2802 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
2804 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
2805 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
2806 struct DHT_MessageContext *message_context;
2808 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
2811 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
2816 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2821 //memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2822 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
2823 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2824 GNUNET_assert(message_context->bloom != NULL);
2825 message_context->hop_count = ntohl(incoming->hop_count);
2826 message_context->key = &incoming->key;
2827 message_context->replication = ntohl(incoming->desired_replication_level);
2828 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
2829 message_context->msg_options = ntohl(incoming->options);
2830 message_context->network_size = ntohl(incoming->network_size);
2831 message_context->peer = peer;
2832 route_message(cls, enc_msg, message_context);
2833 GNUNET_free(message_context);
2839 * Core handler for p2p route results.
2842 handle_dht_p2p_route_result (void *cls,
2843 const struct GNUNET_PeerIdentity *peer,
2844 const struct GNUNET_MessageHeader *message,
2845 struct GNUNET_TIME_Relative latency, uint32_t distance)
2848 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2849 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
2851 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
2852 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
2853 struct DHT_MessageContext message_context;
2855 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2861 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2862 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2863 GNUNET_assert(message_context.bloom != NULL);
2864 message_context.key = &incoming->key;
2865 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
2866 message_context.msg_options = ntohl(incoming->options);
2867 message_context.hop_count = ntohl(incoming->hop_count);
2868 message_context.peer = peer;
2869 route_result_message(cls, enc_msg, &message_context);
2875 * Receive the HELLO from transport service,
2876 * free current and replace if necessary.
2879 * @param message HELLO message of peer
2882 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
2885 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2886 "Received our `%s' from transport service\n",
2890 GNUNET_assert (message != NULL);
2891 GNUNET_free_non_null(my_hello);
2892 my_hello = GNUNET_malloc(ntohs(message->size));
2893 memcpy(my_hello, message, ntohs(message->size));
2898 * Task run during shutdown.
2904 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2907 struct PeerInfo *pos;
2908 if (transport_handle != NULL)
2910 GNUNET_free_non_null(my_hello);
2911 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
2912 GNUNET_TRANSPORT_disconnect(transport_handle);
2915 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
2917 while (k_buckets[bucket_count].head != NULL)
2919 pos = k_buckets[bucket_count].head;
2921 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2922 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
2924 delete_peer(pos, bucket_count);
2927 if (coreAPI != NULL)
2930 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2931 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
2933 GNUNET_CORE_disconnect (coreAPI);
2935 if (datacache != NULL)
2938 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2939 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
2941 GNUNET_DATACACHE_destroy (datacache);
2946 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
2949 if (dhtlog_handle != NULL)
2950 GNUNET_DHTLOG_disconnect(dhtlog_handle);
2952 GNUNET_free_non_null(my_short_id);
2957 * To be called on core init/fail.
2959 * @param cls service closure
2960 * @param server handle to the server for this service
2961 * @param identity the public identity of this peer
2962 * @param publicKey the public key of this peer
2965 core_init (void *cls,
2966 struct GNUNET_CORE_Handle *server,
2967 const struct GNUNET_PeerIdentity *identity,
2968 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
2974 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2975 "%s: Connection to core FAILED!\n", "dht",
2976 GNUNET_i2s (identity));
2978 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
2979 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
2983 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2984 "%s: Core connection initialized, I am peer: %s\n", "dht",
2985 GNUNET_i2s (identity));
2988 /* Copy our identity so we can use it */
2989 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
2990 if (my_short_id != NULL)
2991 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
2992 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
2993 /* Set the server to local variable */
2996 if (dhtlog_handle != NULL)
2997 dhtlog_handle->insert_node (NULL, &my_identity);
3001 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3002 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3003 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3004 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
3009 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3010 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
3011 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
3016 * Method called whenever a peer connects.
3018 * @param cls closure
3019 * @param peer peer identity this notification is about
3020 * @param latency reported latency of the connection with peer
3021 * @param distance reported distance (DV) to peer
3023 void handle_core_connect (void *cls,
3024 const struct GNUNET_PeerIdentity * peer,
3025 struct GNUNET_TIME_Relative latency,
3028 struct PeerInfo *ret;
3031 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3032 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
3035 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3037 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));
3041 if (datacache != NULL)
3042 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
3043 ret = try_add_peer(peer,
3044 find_current_bucket(&peer->hashPubKey),
3049 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3052 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3053 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
3058 * Method called whenever a peer disconnects.
3060 * @param cls closure
3061 * @param peer peer identity this notification is about
3063 void handle_core_disconnect (void *cls,
3065 GNUNET_PeerIdentity * peer)
3067 struct PeerInfo *to_remove;
3070 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");
3072 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3074 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));
3077 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
3078 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
3079 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
3080 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
3081 delete_peer(to_remove, current_bucket);
3085 * Process dht requests.
3087 * @param cls closure
3088 * @param scheduler scheduler to use
3089 * @param server the initialized server
3090 * @param c configuration to use
3094 struct GNUNET_SCHEDULER_Handle *scheduler,
3095 struct GNUNET_SERVER_Handle *server,
3096 const struct GNUNET_CONFIGURATION_Handle *c)
3101 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
3102 GNUNET_SERVER_add_handlers (server, plugin_handlers);
3103 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
3104 cfg, /* Main configuration */
3105 GNUNET_TIME_UNIT_FOREVER_REL,
3106 NULL, /* Closure passed to DHT functionas around? */
3107 &core_init, /* Call core_init once connected */
3108 &handle_core_connect, /* Handle connects */
3109 &handle_core_disconnect, /* remove peers on disconnects */
3110 NULL, /* Do we care about "status" updates? */
3111 NULL, /* Don't want notified about all incoming messages */
3112 GNUNET_NO, /* For header only inbound notification */
3113 NULL, /* Don't want notified about all outbound messages */
3114 GNUNET_NO, /* For header only outbound notification */
3115 core_handlers); /* Register these handlers */
3117 if (coreAPI == NULL)
3119 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
3120 NULL, NULL, NULL, NULL, NULL);
3121 if (transport_handle != NULL)
3122 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
3124 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
3126 lowest_bucket = MAX_BUCKETS - 1;
3127 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
3128 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3129 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
3130 GNUNET_assert(all_known_peers != NULL);
3131 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
3133 debug_routes = GNUNET_YES;
3137 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3140 strict_kademlia = GNUNET_YES;
3144 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3147 stop_on_closest = GNUNET_YES;
3151 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3154 stop_on_found = GNUNET_YES;
3158 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3159 "malicious_getter"))
3161 malicious_getter = GNUNET_YES;
3162 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3163 "MALICIOUS_GET_FREQUENCY",
3164 &malicious_get_frequency))
3165 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3169 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3170 "malicious_putter"))
3172 malicious_putter = GNUNET_YES;
3173 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3174 "MALICIOUS_PUT_FREQUENCY",
3175 &malicious_put_frequency))
3176 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3180 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3181 "malicious_dropper"))
3183 malicious_dropper = GNUNET_YES;
3187 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
3188 "mysql_logging_extended"))
3190 debug_routes = GNUNET_YES;
3191 debug_routes_extended = GNUNET_YES;
3194 if (GNUNET_YES == debug_routes)
3196 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
3197 if (dhtlog_handle == NULL)
3199 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3200 "Could not connect to mysql logging server, logging will not happen!");
3204 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
3208 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
3209 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
3210 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
3211 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
3212 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
3213 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
3214 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
3215 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
3216 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
3217 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
3218 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
3219 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
3220 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
3221 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
3222 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
3223 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
3226 random_seconds = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 180);
3227 GNUNET_SCHEDULER_add_delayed (sched,
3228 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, random_seconds),
3229 &send_find_peer_message, NULL);
3232 /* Scheduled the task to clean up when shutdown is called */
3233 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
3234 GNUNET_TIME_UNIT_FOREVER_REL,
3235 &shutdown_task, NULL);
3239 * The main function for the dht service.
3241 * @param argc number of arguments from the command line
3242 * @param argv command line arguments
3243 * @return 0 ok, 1 on error
3246 main (int argc, char *const *argv)
3248 return (GNUNET_OK ==
3249 GNUNET_SERVICE_run (argc,
3252 GNUNET_SERVICE_OPTION_NONE,
3253 &run, NULL)) ? 0 : 1;