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 * Default frequency for sending malicious put messages
93 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
96 * Type for a malicious request, so we can ignore it during testing
98 #define DHT_MALICIOUS_MESSAGE_TYPE 42
100 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
103 * Real maximum number of hops, at which point we refuse
104 * to forward the message.
109 * Linked list of messages to send to clients.
111 struct P2PPendingMessage
114 * Pointer to next item in the list
116 struct P2PPendingMessage *next;
119 * Pointer to previous item in the list
121 struct P2PPendingMessage *prev;
124 * Message importance level.
126 unsigned int importance;
129 * How long to wait before sending message.
131 struct GNUNET_TIME_Relative timeout;
134 * Actual message to be sent; // avoid allocation
136 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
142 * Per-peer information.
147 * Next peer entry (DLL)
149 struct PeerInfo *next;
152 * Prev peer entry (DLL)
154 struct PeerInfo *prev;
157 * Head of pending messages to be sent to this peer.
159 struct P2PPendingMessage *head;
162 * Tail of pending messages to be sent to this peer.
164 struct P2PPendingMessage *tail;
167 * Core handle for sending messages to this peer.
169 struct GNUNET_CORE_TransmitHandle *th;
172 * Task for scheduling message sends.
174 GNUNET_SCHEDULER_TaskIdentifier send_task;
177 * What is the average latency for replies received?
179 struct GNUNET_TIME_Relative latency;
182 * Number of responses received
184 unsigned long long response_count;
187 * Number of requests sent
189 unsigned long long request_count;
192 * What is the identity of the peer?
194 struct GNUNET_PeerIdentity id;
197 * Transport level distance to peer.
199 unsigned int distance;
202 * Task for scheduling periodic ping messages for this peer.
204 GNUNET_SCHEDULER_TaskIdentifier ping_task;
209 * Peers are grouped into buckets.
216 struct PeerInfo *head;
221 struct PeerInfo *tail;
224 * Number of peers in the bucket.
226 unsigned int peers_size;
230 * Linked list of messages to send to clients.
232 struct PendingMessage
235 * Pointer to next item in the list
237 struct PendingMessage *next;
240 * Pointer to previous item in the list
242 struct PendingMessage *prev;
245 * Actual message to be sent; // avoid allocation
247 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
252 * Struct containing information about a client,
253 * handle to connect to it, and any pending messages
254 * that need to be sent to it.
259 * Linked list of active clients
261 struct ClientList *next;
264 * The handle to this client
266 struct GNUNET_SERVER_Client *client_handle;
269 * Handle to the current transmission request, NULL
272 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
275 * Linked list of pending messages for this client
277 struct PendingMessage *pending_head;
280 * Tail of linked list of pending messages for this client
282 struct PendingMessage *pending_tail;
288 * Context containing information about a DHT message received.
290 struct DHT_MessageContext
293 * The client this request was received from.
294 * (NULL if received from another peer)
296 struct ClientList *client;
299 * The peer this request was received from.
300 * (NULL if received from local client)
302 const struct GNUNET_PeerIdentity *peer;
305 * The key this request was about
307 const GNUNET_HashCode *key;
310 * The unique identifier of this request
315 * Desired replication level
317 uint32_t replication;
320 * Network size estimate, either ours or the sum of
321 * those routed to thus far. =~ Log of number of peers
322 * chosen from for this request.
324 uint32_t network_size;
327 * Any message options for this request
329 uint32_t msg_options;
332 * How many hops has the message already traversed?
337 * Bloomfilter for this routing request.
339 struct GNUNET_CONTAINER_BloomFilter *bloom;
342 * Did we forward this message? (may need to remember it!)
347 * Are we the closest known peer to this key (out of our neighbors?)
353 * Record used for remembering what peers are waiting for what
354 * responses (based on search key).
356 struct DHTRouteSource
361 struct DHTRouteSource *next;
366 struct DHTRouteSource *prev;
369 * Source of the request. Replies should be forwarded to
372 struct GNUNET_PeerIdentity source;
375 * If this was a local request, remember the client; otherwise NULL.
377 struct ClientList *client;
380 * Pointer to this nodes heap location (for removal)
382 struct GNUNET_CONTAINER_HeapNode *hnode;
385 * Back pointer to the record storing this information.
387 struct DHTQueryRecord *record;
390 * Task to remove this entry on timeout.
392 GNUNET_SCHEDULER_TaskIdentifier delete_task;
396 * Entry in the DHT routing table.
398 struct DHTQueryRecord
401 * Head of DLL for result forwarding.
403 struct DHTRouteSource *head;
406 * Tail of DLL for result forwarding.
408 struct DHTRouteSource *tail;
411 * Key that the record concerns.
416 * GET message of this record (what we already forwarded?).
418 //DV_DHT_MESSAGE get; Try to get away with not saving this.
421 * Bloomfilter of the peers we've replied to so far
423 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
428 * DHT Routing results structure
433 * Min heap for removal upon reaching limit
435 struct GNUNET_CONTAINER_Heap *minHeap;
438 * Hashmap for fast key based lookup
440 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
445 * DHT structure for recent requests.
447 struct RecentRequests
450 * Min heap for removal upon reaching limit
452 struct GNUNET_CONTAINER_Heap *minHeap;
455 * Hashmap for key based lookup
457 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
469 * Recent requests by hash/uid and by time inserted.
471 static struct RecentRequests recent;
474 * Don't use our routing algorithm, always route
475 * to closest peer; initially send requests to 3
478 static int strict_kademlia;
481 * Routing option to end routing when closest peer found.
483 static int stop_on_closest;
486 * Routing option to end routing when data is found.
488 static int stop_on_found;
491 * Container of active queries we should remember
493 static struct DHTResults forward_list;
496 * Handle to the datacache service (for inserting/retrieving data)
498 static struct GNUNET_DATACACHE_Handle *datacache;
501 * Handle for the statistics service.
503 struct GNUNET_STATISTICS_Handle *stats;
506 * The main scheduler to use for the DHT service
508 static struct GNUNET_SCHEDULER_Handle *sched;
511 * The configuration the DHT service is running with
513 static const struct GNUNET_CONFIGURATION_Handle *cfg;
516 * Handle to the core service
518 static struct GNUNET_CORE_Handle *coreAPI;
521 * Handle to the transport service, for getting our hello
523 static struct GNUNET_TRANSPORT_Handle *transport_handle;
526 * The identity of our peer.
528 static struct GNUNET_PeerIdentity my_identity;
531 * Short id of the peer, for printing
533 static char *my_short_id;
538 static struct GNUNET_MessageHeader *my_hello;
541 * Task to run when we shut down, cleaning up all our trash
543 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
546 * The lowest currently used bucket.
548 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
551 * The buckets (Kademlia routing table, complete with growth).
552 * Array of size MAX_BUCKET_SIZE.
554 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
557 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
559 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
562 * Maximum size for each bucket.
564 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
567 * List of active clients.
569 static struct ClientList *client_list;
572 * Handle to the DHT logger.
574 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
577 * Whether or not to send routing debugging information
578 * to the dht logging server
580 static unsigned int debug_routes;
583 * Whether or not to send FULL route information to
586 static unsigned int debug_routes_extended;
589 * GNUNET_YES or GNUNET_NO, whether or not to act as
590 * a malicious node which drops all messages
592 static unsigned int malicious_dropper;
595 * GNUNET_YES or GNUNET_NO, whether or not to act as
596 * a malicious node which sends out lots of GETS
598 static unsigned int malicious_getter;
601 * GNUNET_YES or GNUNET_NO, whether or not to act as
602 * a malicious node which sends out lots of PUTS
604 static unsigned int malicious_putter;
606 static unsigned long long malicious_get_frequency;
608 static unsigned long long malicious_put_frequency;
611 * Forward declaration.
613 static size_t send_generic_reply (void *cls, size_t size, void *buf);
615 /* Declare here so retry_core_send is aware of it */
616 size_t core_transmit_notify (void *cls,
617 size_t size, void *buf);
620 increment_stats(const char *value)
624 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
629 * Try to send another message from our core send list
632 try_core_send (void *cls,
633 const struct GNUNET_SCHEDULER_TaskContext *tc)
635 struct PeerInfo *peer = cls;
636 struct P2PPendingMessage *pending;
639 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
641 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
644 if (peer->th != NULL)
645 return; /* Message send already in progress */
647 pending = peer->head;
650 ssize = ntohs(pending->msg->size);
652 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
653 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
654 "DHT", ssize, GNUNET_i2s(&peer->id));
656 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
657 pending->timeout, &peer->id,
658 ssize, &core_transmit_notify, peer);
663 * Function called to send a request out to another peer.
664 * Called both for locally initiated requests and those
665 * received from other peers.
667 * @param cls DHT service closure argument
668 * @param msg the encapsulated message
669 * @param peer the peer to forward the message to
670 * @param msg_ctx the context of the message (hop count, bloom, etc.)
672 static void forward_result_message (void *cls,
673 const struct GNUNET_MessageHeader *msg,
674 struct PeerInfo *peer,
675 struct DHT_MessageContext *msg_ctx)
677 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
678 struct P2PPendingMessage *pending;
682 increment_stats(STAT_RESULT_FORWARDS);
683 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
684 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
685 psize = sizeof(struct P2PPendingMessage) + msize;
686 pending = GNUNET_malloc(psize);
687 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
688 pending->importance = DHT_SEND_PRIORITY;
689 pending->timeout = GNUNET_TIME_relative_get_forever();
690 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
691 result_message->header.size = htons(msize);
692 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
693 result_message->options = htonl(msg_ctx->msg_options);
694 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
695 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
696 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
697 memcpy(&result_message->key, msg_ctx->key, sizeof(GNUNET_HashCode));
698 memcpy(&result_message[1], msg, ntohs(msg->size));
700 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));
702 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
703 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
704 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
707 * Called when core is ready to send a message we asked for
708 * out to the destination.
710 * @param cls closure (NULL)
711 * @param size number of bytes available in buf
712 * @param buf where the callee should write the message
713 * @return number of bytes written to buf
715 size_t core_transmit_notify (void *cls,
716 size_t size, void *buf)
718 struct PeerInfo *peer = cls;
720 struct P2PPendingMessage *pending;
727 /* client disconnected */
729 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
734 if (peer->head == NULL)
739 pending = peer->head;
740 msize = ntohs(pending->msg->size);
744 memcpy (cbuf, pending->msg, msize);
745 GNUNET_CONTAINER_DLL_remove (peer->head,
749 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));
751 GNUNET_free (pending);
754 while (NULL != pending &&
755 (size - off >= (msize = ntohs (pending->msg->size))))
757 #if DEBUG_DHT_ROUTING
758 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);
760 memcpy (&cbuf[off], pending->msg, msize);
762 GNUNET_CONTAINER_DLL_remove (peer->head,
765 GNUNET_free (pending);
766 pending = peer->head;
769 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
770 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
772 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);
778 * Determine how many low order bits match in two
779 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
780 * the first two lowest order bits, and therefore the
781 * return value is two (NOT XOR distance, nor how many
782 * bits match absolutely!).
784 * @param first the first hashcode
785 * @param second the hashcode to compare first to
787 * @return the number of bits that match
789 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
793 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
794 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
796 return sizeof (GNUNET_HashCode) * 8;
800 * Compute the distance between have and target as a 32-bit value.
801 * Differences in the lower bits must count stronger than differences
802 * in the higher bits.
804 * @return 0 if have==target, otherwise a number
805 * that is larger as the distance between
806 * the two hash codes increases
809 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
816 /* We have to represent the distance between two 2^9 (=512)-bit
817 numbers as a 2^5 (=32)-bit number with "0" being used for the
818 two numbers being identical; furthermore, we need to
819 guarantee that a difference in the number of matching
820 bits is always represented in the result.
822 We use 2^32/2^9 numerical values to distinguish between
823 hash codes that have the same LSB bit distance and
824 use the highest 2^9 bits of the result to signify the
825 number of (mis)matching LSB bits; if we have 0 matching
826 and hence 512 mismatching LSB bits we return -1 (since
827 512 itself cannot be represented with 9 bits) */
829 /* first, calculate the most significant 9 bits of our
830 result, aka the number of LSBs */
831 bucket = matching_bits (target, have);
832 /* bucket is now a value between 0 and 512 */
834 return 0; /* perfect match */
836 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
837 below, we'd end up with max+1 (overflow)) */
839 /* calculate the most significant bits of the final result */
840 msb = (512 - bucket) << (32 - 9);
841 /* calculate the 32-9 least significant bits of the final result by
842 looking at the differences in the 32-9 bits following the
843 mismatching bit at 'bucket' */
846 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
848 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
849 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
850 last bit set will be 31 -- if
851 i does not reach 512 first... */
857 * Return a number that is larger the closer the
858 * "have" GNUNET_hash code is to the "target".
860 * @return inverse distance metric, non-zero.
861 * Must fudge the value if NO bits match.
864 inverse_distance (const GNUNET_HashCode * target,
865 const GNUNET_HashCode * have)
867 if (matching_bits(target, have) == 0)
868 return 1; /* Never return 0! */
869 return ((unsigned int) -1) - distance (target, have);
873 * Find the optimal bucket for this key, regardless
874 * of the current number of buckets in use.
876 * @param hc the hashcode to compare our identity to
878 * @return the proper bucket index, or GNUNET_SYSERR
879 * on error (same hashcode)
881 static int find_bucket(const GNUNET_HashCode *hc)
885 bits = matching_bits(&my_identity.hashPubKey, hc);
886 if (bits == MAX_BUCKETS)
887 return GNUNET_SYSERR;
888 return MAX_BUCKETS - bits - 1;
892 * Find which k-bucket this peer should go into,
893 * taking into account the size of the k-bucket
894 * array. This means that if more bits match than
895 * there are currently buckets, lowest_bucket will
898 * @param hc GNUNET_HashCode we are finding the bucket for.
900 * @return the proper bucket index for this key,
901 * or GNUNET_SYSERR on error (same hashcode)
903 static int find_current_bucket(const GNUNET_HashCode *hc)
906 actual_bucket = find_bucket(hc);
908 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
909 return GNUNET_SYSERR;
910 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
911 return lowest_bucket;
913 return actual_bucket;
917 * Find a routing table entry from a peer identity
919 * @param peer the peer to look up
921 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
924 find_bucket_by_peer(const struct PeerInfo *peer)
927 struct PeerInfo *pos;
929 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
931 pos = k_buckets[bucket].head;
940 return GNUNET_SYSERR; /* No such peer. */
945 * Print the complete routing table for this peer.
948 print_routing_table ()
951 struct PeerInfo *pos;
952 char char_buf[30000];
954 memset(char_buf, 0, sizeof(char_buf));
956 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
957 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
958 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
960 pos = k_buckets[bucket].head;
961 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
962 //fprintf(stderr, "Bucket %d:\n", bucket);
965 //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));
966 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));
970 fprintf(stderr, "%s", char_buf);
976 * Find a routing table entry from a peer identity
978 * @param peer the peer identity to look up
980 * @return the routing table entry, or NULL if not found
982 static struct PeerInfo *
983 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
986 struct PeerInfo *pos;
987 bucket = find_current_bucket(&peer->hashPubKey);
989 if (bucket == GNUNET_SYSERR)
992 pos = k_buckets[bucket].head;
995 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
999 return NULL; /* No such peer. */
1003 * Really add a peer to a bucket (only do assertions
1006 * @param peer GNUNET_PeerIdentity of the peer to add
1007 * @param bucket the already figured out bucket to add
1009 * @param latency the core reported latency of this peer
1010 * @param distance the transport level distance to this peer
1012 * @return the newly added PeerInfo
1014 static struct PeerInfo *
1015 add_peer(const struct GNUNET_PeerIdentity *peer,
1016 unsigned int bucket,
1017 struct GNUNET_TIME_Relative latency,
1018 unsigned int distance)
1020 struct PeerInfo *new_peer;
1021 GNUNET_assert(bucket < MAX_BUCKETS);
1022 GNUNET_assert(peer != NULL);
1023 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
1024 new_peer->latency = latency;
1025 new_peer->distance = distance;
1026 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
1028 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
1029 k_buckets[bucket].tail,
1030 k_buckets[bucket].tail,
1032 k_buckets[bucket].peers_size++;
1038 * Given a peer and its corresponding bucket,
1039 * remove it from that bucket. Does not free
1040 * the PeerInfo struct, nor cancel messages
1041 * or free messages waiting to be sent to this
1044 * @param peer the peer to remove
1045 * @param bucket the bucket the peer belongs to
1047 static void remove_peer (struct PeerInfo *peer,
1048 unsigned int bucket)
1050 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1051 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1052 k_buckets[bucket].tail,
1054 k_buckets[bucket].peers_size--;
1055 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1060 * Removes peer from a bucket, then frees associated
1061 * resources and frees peer.
1063 * @param peer peer to be removed and freed
1064 * @param bucket which bucket this peer belongs to
1066 static void delete_peer (struct PeerInfo *peer,
1067 unsigned int bucket)
1069 struct P2PPendingMessage *pos;
1070 struct P2PPendingMessage *next;
1072 struct PeerInfo *peer_pos;
1074 peer_pos = k_buckets[bucket].head;
1075 while ((peer_pos != NULL) && (peer_pos != peer))
1076 peer_pos = peer_pos->next;
1077 if (peer_pos == NULL)
1079 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1080 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));
1082 GNUNET_assert(peer_pos != NULL);
1084 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1086 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1087 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1088 if (peer->th != NULL)
1089 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1092 while (pos != NULL) /* Remove any pending messages for this peer */
1099 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1100 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1106 * Iterator over hash map entries.
1108 * @param cls closure
1109 * @param key current key code
1110 * @param value PeerInfo of the peer to move to new lowest bucket
1111 * @return GNUNET_YES if we should continue to
1115 static int move_lowest_bucket (void *cls,
1116 const GNUNET_HashCode * key,
1119 struct PeerInfo *peer = value;
1122 new_bucket = lowest_bucket - 1;
1123 remove_peer(peer, lowest_bucket);
1124 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1125 k_buckets[new_bucket].tail,
1126 k_buckets[new_bucket].tail,
1128 k_buckets[new_bucket].peers_size++;
1134 * The current lowest bucket is full, so change the lowest
1135 * bucket to the next lower down, and move any appropriate
1136 * entries in the current lowest bucket to the new bucket.
1138 static void enable_next_bucket()
1140 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1141 struct PeerInfo *pos;
1142 GNUNET_assert(lowest_bucket > 0);
1143 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1144 pos = k_buckets[lowest_bucket].head;
1147 fprintf(stderr, "Printing RT before new bucket\n");
1148 print_routing_table();
1150 /* Populate the array of peers which should be in the next lowest bucket */
1153 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1154 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1158 /* Remove peers from lowest bucket, insert into next lowest bucket */
1159 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1160 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1161 lowest_bucket = lowest_bucket - 1;
1163 fprintf(stderr, "Printing RT after new bucket\n");
1164 print_routing_table();
1169 * Function called to send a request out to another peer.
1170 * Called both for locally initiated requests and those
1171 * received from other peers.
1173 * @param cls DHT service closure argument (unused)
1174 * @param msg the encapsulated message
1175 * @param peer the peer to forward the message to
1176 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1178 static void forward_message (void *cls,
1179 const struct GNUNET_MessageHeader *msg,
1180 struct PeerInfo *peer,
1181 struct DHT_MessageContext *msg_ctx)
1183 struct GNUNET_DHT_P2PRouteMessage *route_message;
1184 struct P2PPendingMessage *pending;
1188 increment_stats(STAT_ROUTE_FORWARDS);
1189 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1190 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1191 psize = sizeof(struct P2PPendingMessage) + msize;
1192 pending = GNUNET_malloc(psize);
1193 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1194 pending->importance = DHT_SEND_PRIORITY;
1195 pending->timeout = GNUNET_TIME_relative_get_forever();
1196 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1197 route_message->header.size = htons(msize);
1198 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1199 route_message->options = htonl(msg_ctx->msg_options);
1200 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1201 route_message->network_size = htonl(msg_ctx->network_size);
1202 route_message->desired_replication_level = htonl(msg_ctx->replication);
1203 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1204 if (msg_ctx->bloom != NULL)
1205 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1206 if (msg_ctx->key != NULL)
1207 memcpy(&route_message->key, msg_ctx->key, sizeof(GNUNET_HashCode));
1208 memcpy(&route_message[1], msg, ntohs(msg->size));
1210 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));
1212 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1213 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1214 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1219 * Task used to send ping messages to peers so that
1220 * they don't get disconnected.
1222 * @param cls the peer to send a ping message to
1223 * @param tc context, reason, etc.
1226 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1228 struct PeerInfo *peer = cls;
1229 struct GNUNET_MessageHeader ping_message;
1230 struct DHT_MessageContext message_context;
1232 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1235 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1236 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1238 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1240 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1242 forward_message(NULL, &ping_message, peer, &message_context);
1243 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1247 * Schedule PING messages for the top X peers in each
1248 * bucket of the routing table (so core won't disconnect them!)
1250 void schedule_ping_messages()
1252 unsigned int bucket;
1254 struct PeerInfo *pos;
1255 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1257 pos = k_buckets[bucket].head;
1261 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1262 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1263 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1265 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1266 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1276 * Attempt to add a peer to our k-buckets.
1278 * @param peer, the peer identity of the peer being added
1280 * @return NULL if the peer was not added,
1281 * pointer to PeerInfo for new peer otherwise
1283 static struct PeerInfo *
1284 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1285 unsigned int bucket,
1286 struct GNUNET_TIME_Relative latency,
1287 unsigned int distance)
1290 struct PeerInfo *new_peer;
1291 peer_bucket = find_current_bucket(&peer->hashPubKey);
1292 if (peer_bucket == GNUNET_SYSERR)
1295 GNUNET_assert(peer_bucket >= lowest_bucket);
1296 new_peer = add_peer(peer, peer_bucket, latency, distance);
1298 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1299 enable_next_bucket();
1301 schedule_ping_messages();
1308 * Task run to check for messages that need to be sent to a client.
1310 * @param client a ClientList, containing the client and any messages to be sent to it
1313 process_pending_messages (struct ClientList *client)
1315 if (client->pending_head == NULL)
1317 if (client->transmit_handle != NULL)
1319 client->transmit_handle =
1320 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1321 ntohs (client->pending_head->msg->
1323 GNUNET_TIME_UNIT_FOREVER_REL,
1324 &send_generic_reply, client);
1328 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1329 * request. A ClientList is passed as closure, take the head of the list
1330 * and copy it into buf, which has the result of sending the message to the
1333 * @param cls closure to this call
1334 * @param size maximum number of bytes available to send
1335 * @param buf where to copy the actual message to
1337 * @return the number of bytes actually copied, 0 indicates failure
1340 send_generic_reply (void *cls, size_t size, void *buf)
1342 struct ClientList *client = cls;
1344 struct PendingMessage *reply;
1348 client->transmit_handle = NULL;
1351 /* client disconnected */
1355 while ( (NULL != (reply = client->pending_head)) &&
1356 (size >= off + (msize = ntohs (reply->msg->size))))
1358 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1359 client->pending_tail,
1361 memcpy (&cbuf[off], reply->msg, msize);
1362 GNUNET_free (reply);
1365 process_pending_messages (client);
1371 * Add a PendingMessage to the clients list of messages to be sent
1373 * @param client the active client to send the message to
1374 * @param pending_message the actual message to send
1377 add_pending_message (struct ClientList *client,
1378 struct PendingMessage *pending_message)
1380 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1381 client->pending_tail,
1382 client->pending_tail,
1384 process_pending_messages (client);
1391 * Called when a reply needs to be sent to a client, as
1392 * a result it found to a GET or FIND PEER request.
1394 * @param client the client to send the reply to
1395 * @param message the encapsulated message to send
1396 * @param uid the unique identifier of this request
1399 send_reply_to_client (struct ClientList *client,
1400 const struct GNUNET_MessageHeader *message,
1401 unsigned long long uid)
1403 struct GNUNET_DHT_RouteResultMessage *reply;
1404 struct PendingMessage *pending_message;
1408 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1409 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1411 msize = ntohs (message->size);
1412 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1413 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1415 GNUNET_break_op (0);
1419 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1420 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1421 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1422 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1423 reply->header.size = htons (tsize);
1424 reply->unique_id = GNUNET_htonll (uid);
1425 memcpy (&reply[1], message, msize);
1427 add_pending_message (client, pending_message);
1431 * Consider whether or not we would like to have this peer added to
1432 * our routing table. Check whether bucket for this peer is full,
1433 * if so return negative; if not return positive. Since peers are
1434 * only added on CORE level connect, this doesn't actually add the
1435 * peer to the routing table.
1437 * @param peer the peer we are considering adding
1439 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1442 * FIXME: Think about making a context for this call so that we can
1443 * ping the oldest peer in the current bucket and consider
1444 * removing it in lieu of the new peer.
1446 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1450 if (GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1451 return GNUNET_NO; /* We already know this peer (are connected even!) */
1452 bucket = find_current_bucket(&peer->hashPubKey);
1453 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1460 * Main function that handles whether or not to route a result
1461 * message to other peers, or to send to our local client.
1463 * @param msg the result message to be routed
1464 * @return the number of peers the message was routed to,
1465 * GNUNET_SYSERR on failure
1467 static int route_result_message(void *cls,
1468 struct GNUNET_MessageHeader *msg,
1469 struct DHT_MessageContext *message_context)
1471 struct GNUNET_PeerIdentity new_peer;
1472 struct DHTQueryRecord *record;
1473 struct DHTRouteSource *pos;
1474 struct PeerInfo *peer_info;
1475 const struct GNUNET_MessageHeader *hello_msg;
1477 increment_stats(STAT_RESULTS);
1479 * If a find peer result message is received and contains a valid
1480 * HELLO for another peer, offer it to the transport service.
1482 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1484 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1487 hello_msg = &msg[1];
1488 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1490 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1493 else /* We have a valid hello, and peer id stored in new_peer */
1495 increment_stats(STAT_FIND_PEER_REPLY);
1496 if (GNUNET_YES == consider_peer(&new_peer))
1498 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1499 /* GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_UNIT_FOREVER_REL, &new_peer, NULL, NULL); */
1500 /* peer_request_connect call causes service to segfault */
1501 /* FIXME: Do we need this (peer_request_connect call)??? */
1506 if (malicious_dropper == GNUNET_YES)
1509 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, message_context->key);
1511 if (record == NULL) /* No record of this message! */
1514 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1515 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1516 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1518 #if DEBUG_DHT_ROUTING
1520 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1522 dhtlog_handle->insert_route (NULL,
1523 message_context->unique_id,
1525 message_context->hop_count,
1528 message_context->key,
1529 message_context->peer, NULL);
1532 if (message_context->bloom != NULL)
1534 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1535 message_context->bloom = NULL;
1543 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1546 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1547 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
1548 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1550 #if DEBUG_DHT_ROUTING
1551 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1553 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
1554 message_context->hop_count,
1555 GNUNET_YES, &my_identity, message_context->key,
1556 message_context->peer, NULL);
1559 increment_stats(STAT_RESULTS_TO_CLIENT);
1560 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
1561 increment_stats(STAT_GET_REPLY);
1563 send_reply_to_client(pos->client, msg, message_context->unique_id);
1565 else /* Send to peer */
1567 peer_info = find_peer_by_id(&pos->source);
1568 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
1574 if (message_context->bloom == NULL)
1575 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1576 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
1577 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey))
1580 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1581 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
1582 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1584 #if DEBUG_DHT_ROUTING
1585 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1587 dhtlog_handle->insert_route (NULL, message_context->unique_id,
1589 message_context->hop_count,
1590 GNUNET_NO, &my_identity, message_context->key,
1591 message_context->peer, &pos->source);
1594 forward_result_message(cls, msg, peer_info, message_context);
1599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1600 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
1601 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1607 if (message_context->bloom != NULL)
1608 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1613 * Iterator for local get request results,
1615 * @param cls closure for iterator, a DatacacheGetContext
1616 * @param exp when does this value expire?
1617 * @param key the key this data is stored under
1618 * @param size the size of the data identified by key
1619 * @param data the actual data
1620 * @param type the type of the data
1622 * @return GNUNET_OK to continue iteration, anything else
1623 * to stop iteration.
1626 datacache_get_iterator (void *cls,
1627 struct GNUNET_TIME_Absolute exp,
1628 const GNUNET_HashCode * key,
1629 uint32_t size, const char *data, uint32_t type)
1631 struct DHT_MessageContext *msg_ctx = cls;
1632 struct DHT_MessageContext *new_msg_ctx;
1633 struct GNUNET_DHT_GetResultMessage *get_result;
1635 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1636 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
1638 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
1639 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
1641 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
1642 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
1643 get_result->header.size =
1644 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
1645 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
1646 get_result->type = htons (type);
1647 memcpy (&get_result[1], data, size);
1648 new_msg_ctx->peer = &my_identity;
1649 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1650 new_msg_ctx->hop_count = 0;
1651 increment_stats(STAT_GET_RESPONSE_START);
1652 route_result_message(cls, &get_result->header, new_msg_ctx);
1653 GNUNET_free(new_msg_ctx);
1654 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
1655 // datacache_get_ctx->unique_id);
1656 GNUNET_free (get_result);
1662 * Server handler for all dht get requests, look for data,
1663 * if found, send response either to clients or other peers.
1665 * @param cls closure for service
1666 * @param msg the actual get message
1667 * @param message_context struct containing pertinent information about the get request
1669 * @return number of items found for GET request
1672 handle_dht_get (void *cls,
1673 const struct GNUNET_MessageHeader *msg,
1674 struct DHT_MessageContext *message_context)
1676 const struct GNUNET_DHT_GetMessage *get_msg;
1678 unsigned int results;
1680 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
1681 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
1687 get_type = ntohs (get_msg->type);
1689 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1690 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
1691 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
1692 message_context->unique_id);
1694 increment_stats(STAT_GETS);
1696 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
1699 if (datacache != NULL)
1701 GNUNET_DATACACHE_get (datacache, message_context->key, get_type,
1702 &datacache_get_iterator, message_context);
1707 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1708 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
1709 results, "GET", message_context->unique_id);
1711 #if DEBUG_DHT_ROUTING
1712 if ((debug_routes) && (dhtlog_handle != NULL))
1714 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
1715 message_context->hop_count, GNUNET_YES, &my_identity,
1716 message_context->key);
1719 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1721 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
1722 message_context->hop_count, GNUNET_YES,
1723 &my_identity, message_context->key, message_context->peer,
1729 if (message_context->hop_count == 0) /* Locally initiated request */
1731 #if DEBUG_DHT_ROUTING
1732 if ((debug_routes) && (dhtlog_handle != NULL))
1734 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
1735 message_context->hop_count, GNUNET_NO, &my_identity,
1736 message_context->key);
1746 * Server handler for initiating local dht find peer requests
1748 * @param cls closure for service
1749 * @param find_msg the actual find peer message
1750 * @param message_context struct containing pertinent information about the request
1754 handle_dht_find_peer (void *cls,
1755 const struct GNUNET_MessageHeader *find_msg,
1756 struct DHT_MessageContext *message_context)
1758 struct GNUNET_MessageHeader *find_peer_result;
1759 struct DHT_MessageContext *new_msg_ctx;
1764 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1765 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
1766 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
1767 ntohs (find_msg->size),
1768 sizeof (struct GNUNET_MessageHeader));
1770 if (my_hello == NULL)
1773 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1774 "`%s': Our HELLO is null, can't return.\n",
1779 /* Simplistic find_peer functionality, always return our hello */
1780 hello_size = ntohs(my_hello->size);
1781 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
1783 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1785 GNUNET_break_op (0);
1789 find_peer_result = GNUNET_malloc (tsize);
1790 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
1791 find_peer_result->size = htons (tsize);
1792 memcpy (&find_peer_result[1], my_hello, hello_size);
1794 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1795 "`%s': Sending hello size %d to requesting peer.\n",
1798 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
1799 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
1800 new_msg_ctx->peer = &my_identity;
1801 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1802 new_msg_ctx->hop_count = 0;
1803 increment_stats(STAT_FIND_PEER_ANSWER);
1804 route_result_message(cls, find_peer_result, new_msg_ctx);
1805 GNUNET_free(new_msg_ctx);
1806 #if DEBUG_DHT_ROUTING
1807 if ((debug_routes) && (dhtlog_handle != NULL))
1809 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
1810 message_context->hop_count, GNUNET_YES, &my_identity,
1811 message_context->key);
1814 //send_reply_to_client(message_context->client, find_peer_result, message_context->unique_id);
1815 GNUNET_free(find_peer_result);
1820 * Server handler for initiating local dht put requests
1822 * @param cls closure for service
1823 * @param msg the actual put message
1824 * @param message_context struct containing pertinent information about the request
1827 handle_dht_put (void *cls,
1828 const struct GNUNET_MessageHeader *msg,
1829 struct DHT_MessageContext *message_context)
1831 struct GNUNET_DHT_PutMessage *put_msg;
1835 GNUNET_assert (ntohs (msg->size) >=
1836 sizeof (struct GNUNET_DHT_PutMessage));
1839 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
1840 put_type = ntohs (put_msg->type);
1842 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
1845 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
1847 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1848 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
1849 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
1851 #if DEBUG_DHT_ROUTING
1852 if (message_context->hop_count == 0) /* Locally initiated request */
1854 if ((debug_routes) && (dhtlog_handle != NULL))
1856 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
1857 message_context->hop_count, GNUNET_NO, &my_identity,
1858 message_context->key);
1863 if (message_context->closest != GNUNET_YES)
1866 #if DEBUG_DHT_ROUTING
1867 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1869 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
1870 message_context->hop_count, GNUNET_YES,
1871 &my_identity, message_context->key, message_context->peer,
1875 if ((debug_routes) && (dhtlog_handle != NULL))
1877 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
1878 message_context->hop_count, GNUNET_YES, &my_identity,
1879 message_context->key);
1883 increment_stats(STAT_PUTS_INSERTED);
1884 if (datacache != NULL)
1885 GNUNET_DATACACHE_put (datacache, message_context->key, data_size,
1886 (char *) &put_msg[1], put_type,
1887 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
1889 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1890 "`%s:%s': %s request received, but have no datacache!\n",
1891 my_short_id, "DHT", "PUT");
1895 * Estimate the diameter of the network based
1896 * on how many buckets are currently in use.
1897 * Concept here is that the diameter of the network
1898 * is roughly the distance a message must travel in
1899 * order to reach its intended destination. Since
1900 * at each hop we expect to get one bit closer, and
1901 * we have one bit per bucket, the number of buckets
1902 * in use should be the largest number of hops for
1903 * a sucessful message. (of course, this assumes we
1904 * know all peers in the network!)
1906 * @return ballpark diameter figure
1908 static unsigned int estimate_diameter()
1910 return MAX_BUCKETS - lowest_bucket;
1914 * To how many peers should we (on average)
1915 * forward the request to obtain the desired
1916 * target_replication count (on average).
1918 * Always 0, 1 or 2 (don't send, send once, split)
1921 get_forward_count (unsigned int hop_count, size_t target_replication)
1923 double target_count;
1924 unsigned int target_value;
1925 unsigned int diameter;
1928 * If we are behaving in strict kademlia mode, send multiple initial requests,
1929 * but then only send to 1 or 0 peers.
1931 if (strict_kademlia == GNUNET_YES)
1934 return DHT_KADEMLIA_REPLICATION;
1935 else if (hop_count < MAX_HOPS)
1941 /* FIXME: the smaller we think the network is the more lenient we should be for
1942 * routing right? The estimation below only works if we think we have reasonably
1943 * full routing tables, which for our RR topologies may not be the case!
1945 diameter = estimate_diameter ();
1946 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
1949 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1950 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
1951 "DHT", estimate_diameter(), lowest_bucket);
1955 else if (hop_count > MAX_HOPS)
1958 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1959 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
1964 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
1965 target_replication / (target_replication * (hop_count + 1) + diameter);
1969 while (target_value < target_count)
1970 target_value++; /* target_value is ALWAYS 1 after this "loop" */
1974 if ((target_count + 1 - target_value) >
1975 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1976 RAND_MAX) / RAND_MAX)
1978 return target_value;
1982 * Find the closest peer in our routing table to the
1985 * @return The closest peer in our routing table to the
1986 * key, or NULL on error.
1988 static struct PeerInfo *
1989 find_closest_peer (const GNUNET_HashCode *hc)
1991 struct PeerInfo *pos;
1992 struct PeerInfo *current_closest;
1993 unsigned int lowest_distance;
1994 unsigned int temp_distance;
1998 lowest_distance = -1;
2000 if (k_buckets[lowest_bucket].peers_size == 0)
2003 current_closest = NULL;
2004 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
2006 pos = k_buckets[bucket].head;
2008 while ((pos != NULL) && (count < bucket_size))
2010 temp_distance = distance(&pos->id.hashPubKey, hc);
2011 if (temp_distance <= lowest_distance)
2013 lowest_distance = temp_distance;
2014 current_closest = pos;
2020 GNUNET_assert(current_closest != NULL);
2021 return current_closest;
2025 * Check whether my identity is closer than any known peers.
2027 * @param target hash code to check closeness to
2029 * Return GNUNET_YES if node location is closest, GNUNET_NO
2033 am_closest_peer (const GNUNET_HashCode * target)
2039 struct PeerInfo *pos;
2040 unsigned int my_distance;
2042 bucket_num = find_current_bucket(target);
2043 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2046 bits = matching_bits(&my_identity.hashPubKey, target);
2047 my_distance = distance(&my_identity.hashPubKey, target);
2049 pos = k_buckets[bucket_num].head;
2051 while ((pos != NULL) && (count < bucket_size))
2053 other_bits = matching_bits(&pos->id.hashPubKey, target);
2054 if (other_bits > bits)
2056 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2059 /* FIXME: why not just return GNUNET_YES here? We are certainly close. */
2060 /*if (distance(&pos->id.hashPubKey, target) < my_distance)
2067 GNUNET_GE_LOG (coreAPI->ectx,
2068 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2069 GNUNET_GE_BULK, "closest peer\n");
2070 printPeerBits (&closest);
2071 GNUNET_GE_LOG (coreAPI->ectx,
2072 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2073 GNUNET_GE_BULK, "me\n");
2074 printPeerBits (coreAPI->my_identity);
2075 GNUNET_GE_LOG (coreAPI->ectx,
2076 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2077 GNUNET_GE_BULK, "key\n");
2078 printKeyBits (target);
2079 GNUNET_GE_LOG (coreAPI->ectx,
2080 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2082 "closest peer inverse distance is %u, mine is %u\n",
2083 inverse_distance (target, &closest.hashPubKey),
2084 inverse_distance (target,
2085 &coreAPI->my_identity->hashPubKey));
2088 /* No peers closer, we are the closest! */
2095 * Select a peer from the routing table that would be a good routing
2096 * destination for sending a message for "target". The resulting peer
2097 * must not be in the set of blocked peers.<p>
2099 * Note that we should not ALWAYS select the closest peer to the
2100 * target, peers further away from the target should be chosen with
2101 * exponentially declining probability.
2103 * @param target the key we are selecting a peer to route to
2104 * @param bloom a bloomfilter containing entries this request has seen already
2106 * @return Peer to route to, or NULL on error
2108 static struct PeerInfo *
2109 select_peer (const GNUNET_HashCode * target,
2110 struct GNUNET_CONTAINER_BloomFilter *bloom)
2112 unsigned int distance;
2115 struct PeerInfo *pos;
2116 struct PeerInfo *chosen;
2117 unsigned long long largest_distance;
2118 unsigned long long total_distance;
2119 unsigned long long selected;
2121 if (strict_kademlia == GNUNET_YES)
2123 largest_distance = 0;
2125 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2127 pos = k_buckets[bc].head;
2129 while ((pos != NULL) && (count < bucket_size))
2131 /* If we are doing strict Kademlia like routing, then checking the bloomfilter is basically cheating! */
2133 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2135 distance = inverse_distance (target, &pos->id.hashPubKey);
2136 if (distance > largest_distance)
2139 largest_distance = distance;
2147 if ((largest_distance > 0) && (chosen != NULL))
2149 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2161 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2163 pos = k_buckets[bc].head;
2165 while ((pos != NULL) && (count < bucket_size))
2167 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2168 total_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2170 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2171 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2172 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2178 if (total_distance == 0)
2183 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2184 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2186 pos = k_buckets[bc].head;
2188 while ((pos != NULL) && (count < bucket_size))
2190 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2192 distance = inverse_distance (target, &pos->id.hashPubKey);
2193 if (distance > selected)
2195 selected -= distance;
2200 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2201 "`%s:%s': peer %s matches bloomfilter.\n",
2202 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2210 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2211 "`%s:%s': peer %s matches bloomfilter.\n",
2212 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2220 * Task used to remove forwarding entries, either
2221 * after timeout, when full, or on shutdown.
2223 * @param cls the entry to remove
2224 * @param tc context, reason, etc.
2227 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2229 struct DHTRouteSource *source_info = cls;
2230 struct DHTQueryRecord *record;
2231 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2232 record = source_info->record;
2233 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2235 if (record->head == NULL) /* No more entries in DLL */
2237 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2238 GNUNET_free(record);
2240 GNUNET_free(source_info);
2244 * Remember this routing request so that if a reply is
2245 * received we can either forward it to the correct peer
2246 * or return the result locally.
2248 * @param cls DHT service closure
2249 * @param msg_ctx Context of the route request
2251 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2253 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2255 struct DHTQueryRecord *record;
2256 struct DHTRouteSource *source_info;
2257 struct DHTRouteSource *pos;
2258 struct GNUNET_TIME_Absolute now;
2259 unsigned int current_size;
2261 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2262 while (current_size >= MAX_OUTSTANDING_FORWARDS)
2264 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2265 record = source_info->record;
2266 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2267 if (record->head == NULL) /* No more entries in DLL */
2269 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2270 GNUNET_free(record);
2272 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2273 GNUNET_free(source_info);
2274 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2276 now = GNUNET_TIME_absolute_get();
2277 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, msg_ctx->key);
2278 if (record != NULL) /* Already know this request! */
2283 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
2284 break; /* Already have this peer in reply list! */
2287 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
2289 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
2295 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
2296 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2297 memcpy(&record->key, msg_ctx->key, sizeof(GNUNET_HashCode));
2300 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
2301 source_info->record = record;
2302 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
2303 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
2304 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
2305 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
2307 source_info->client = msg_ctx->client;
2308 now = GNUNET_TIME_absolute_get_forever();
2310 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
2312 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2313 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
2314 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
2321 * Main function that handles whether or not to route a message to other
2324 * @param msg the message to be routed
2326 * @return the number of peers the message was routed to,
2327 * GNUNET_SYSERR on failure
2329 static int route_message(void *cls,
2330 const struct GNUNET_MessageHeader *msg,
2331 struct DHT_MessageContext *message_context)
2334 struct PeerInfo *selected;
2335 struct PeerInfo *nearest;
2336 unsigned int forward_count;
2340 #if DEBUG_DHT_ROUTING
2344 if (malicious_dropper == GNUNET_YES)
2346 #if DEBUG_DHT_ROUTING
2347 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2349 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2350 message_context->hop_count, GNUNET_SYSERR,
2351 &my_identity, message_context->key, message_context->peer,
2355 if (message_context->bloom != NULL)
2356 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2362 increment_stats(STAT_ROUTES);
2363 message_context->closest = am_closest_peer(message_context->key);
2364 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
2365 nearest = find_closest_peer(message_context->key);
2367 if (message_context->bloom == NULL)
2368 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2369 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2371 if (((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
2372 || ((strict_kademlia == GNUNET_YES) && (message_context->closest == GNUNET_YES)))
2375 #if DEBUG_DHT_ROUTING
2376 if (forward_count == 0)
2377 ret = GNUNET_SYSERR;
2381 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2383 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2384 message_context->hop_count, ret,
2385 &my_identity, message_context->key, message_context->peer,
2390 switch (ntohs(msg->type))
2392 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
2393 cache_response (cls, message_context);
2394 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
2397 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
2398 increment_stats(STAT_PUTS);
2399 handle_dht_put (cls, msg, message_context);
2401 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
2402 increment_stats(STAT_FIND_PEER);
2403 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
2405 cache_response (cls, message_context);
2406 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
2407 handle_dht_find_peer (cls, msg, message_context);
2409 #if DEBUG_DHT_ROUTING
2410 if (message_context->hop_count == 0) /* Locally initiated request */
2412 if ((debug_routes) && (dhtlog_handle != NULL))
2414 dhtlog_handle->insert_dhtkey(NULL, message_context->key);
2415 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2416 message_context->hop_count, GNUNET_NO, &my_identity,
2417 message_context->key);
2423 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2424 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
2427 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(recent->hashmap, message_context->key))
2429 if (GNUNET_SYSERR = GNUNET_CONTAINER_multihashmap_get_multiple (recent->hashmap, message_context->key, &find_matching_recent, &message_context)) /* Have too recently seen this request! */
2433 else /* Exact match not found, but same key found */
2435 recent_req = GNUNET_CONTAINER_multihashmap_get(recent->hashmap, message_context->key);
2440 recent_req = GNUNET_malloc(sizeof(struct RecentRequest));
2441 recent_req->uid = message_context->unique_id;
2442 memcmp(&recent_req->key, message_context->key, sizeof(GNUNET_HashCode));
2443 recent_req->remove_task = GNUNET_SCHEDULER_add_delayed(sched, DEFAULT_RECENT_REMOVAL, &remove_recent, recent_req);
2444 GNUNET_CONTAINER_heap_insert(recent->minHeap, recent_req, GNUNET_TIME_absolute_get());
2445 GNUNET_CONTAINER_multihashmap_put(recent->hashmap, message_context->key, recent_req, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2448 if (GNUNET_CONTAINER_multihashmap_size(recent->hashmap) > DHT_MAX_RECENT)
2450 remove_oldest_recent();
2453 for (i = 0; i < forward_count; i++)
2455 selected = select_peer(message_context->key, message_context->bloom);
2457 if (selected != NULL)
2459 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
2460 #if DEBUG_DHT_ROUTING > 1
2461 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
2462 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2463 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
2464 "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));
2465 GNUNET_free(nearest_buf);
2467 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2469 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2470 message_context->hop_count, GNUNET_NO,
2471 &my_identity, message_context->key, message_context->peer,
2474 forward_message(cls, msg, selected, message_context);
2479 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2480 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
2485 #if DEBUG_DHT_ROUTING > 1
2486 if (forward_count == 0)
2488 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2489 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
2490 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2494 if (message_context->bloom != NULL)
2495 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2497 return forward_count;
2501 * Find a client if it exists, add it otherwise.
2503 * @param client the server handle to the client
2505 * @return the client if found, a new client otherwise
2507 static struct ClientList *
2508 find_active_client (struct GNUNET_SERVER_Client *client)
2510 struct ClientList *pos = client_list;
2511 struct ClientList *ret;
2515 if (pos->client_handle == client)
2520 ret = GNUNET_malloc (sizeof (struct ClientList));
2521 ret->client_handle = client;
2522 ret->next = client_list;
2528 * Task to send a malicious put message across the network.
2530 * @param cls closure for this task
2531 * @param tc the context under which the task is running
2534 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2536 static struct GNUNET_DHT_PutMessage put_message;
2537 static struct DHT_MessageContext message_context;
2538 static GNUNET_HashCode key;
2539 unsigned int mcsize;
2540 uint32_t random_key;
2542 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2545 put_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
2546 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
2547 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2548 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
2549 mcsize = sizeof(struct DHT_MessageContext) + sizeof(GNUNET_HashCode);
2550 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2551 message_context.client = NULL;
2552 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2553 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2554 message_context.key = &key;
2555 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2556 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2557 message_context.msg_options = ntohl (0);
2558 message_context.network_size = estimate_diameter();
2559 message_context.peer = &my_identity;
2561 if (dhtlog_handle != NULL)
2562 dhtlog_handle->insert_dhtkey(NULL, &key);
2563 increment_stats(STAT_PUT_START);
2564 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2565 route_message(NULL, &put_message.header, &message_context);
2566 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
2571 * Task to send a malicious put message across the network.
2573 * @param cls closure for this task
2574 * @param tc the context under which the task is running
2577 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2579 static struct GNUNET_DHT_GetMessage get_message;
2580 static struct DHT_MessageContext message_context;
2581 static GNUNET_HashCode key;
2582 unsigned int mcsize;
2583 uint32_t random_key;
2585 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2588 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
2589 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
2590 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2591 mcsize = sizeof(struct DHT_MessageContext) + sizeof(GNUNET_HashCode);
2592 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2593 message_context.client = NULL;
2594 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2595 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2596 message_context.key = &key;
2597 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2598 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2599 message_context.msg_options = ntohl (0);
2600 message_context.network_size = estimate_diameter();
2601 message_context.peer = &my_identity;
2603 if (dhtlog_handle != NULL)
2604 dhtlog_handle->insert_dhtkey(NULL, &key);
2605 increment_stats(STAT_GET_START);
2606 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2607 route_message(NULL, &get_message.header, &message_context);
2608 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
2612 * Task to send a find peer message for our own peer identifier
2613 * so that we can find the closest peers in the network to ourselves
2614 * and attempt to connect to them.
2616 * @param cls closure for this task
2617 * @param tc the context under which the task is running
2620 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2622 struct GNUNET_MessageHeader *find_peer_msg;
2623 struct DHT_MessageContext message_context;
2625 struct GNUNET_TIME_Relative next_send_time;
2627 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2630 increment_stats(STAT_FIND_PEER_START);
2632 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_MessageHeader));
2633 find_peer_msg->size = htons(sizeof(struct GNUNET_MessageHeader));
2634 find_peer_msg->type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
2635 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2636 message_context.key = &my_identity.hashPubKey;
2637 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
2638 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2639 message_context.msg_options = ntohl (DHT_DEFAULT_FIND_PEER_OPTIONS);
2640 message_context.network_size = estimate_diameter();
2641 message_context.peer = &my_identity;
2643 ret = route_message(NULL, find_peer_msg, &message_context);
2644 GNUNET_free(find_peer_msg);
2645 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2646 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
2648 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
2649 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
2650 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
2651 GNUNET_SCHEDULER_add_delayed (sched,
2653 &send_find_peer_message, NULL);
2657 * Handler for any generic DHT messages, calls the appropriate handler
2658 * depending on message type, sends confirmation if responses aren't otherwise
2661 * @param cls closure for the service
2662 * @param client the client we received this message from
2663 * @param message the actual message received
2666 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
2667 const struct GNUNET_MessageHeader *message)
2669 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
2670 const struct GNUNET_MessageHeader *enc_msg;
2671 struct DHT_MessageContext message_context;
2674 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
2675 enc_type = ntohs (enc_msg->type);
2678 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2679 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
2680 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
2681 GNUNET_ntohll (dht_msg->unique_id));
2683 #if DEBUG_DHT_ROUTING
2684 if (dhtlog_handle != NULL)
2685 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
2687 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2688 message_context.client = find_active_client (client);
2689 message_context.key = &dht_msg->key;
2690 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
2691 message_context.replication = ntohl (dht_msg->desired_replication_level);
2692 message_context.msg_options = ntohl (dht_msg->options);
2693 message_context.network_size = estimate_diameter();
2694 message_context.peer = &my_identity;
2696 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
2697 increment_stats(STAT_GET_START);
2698 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
2699 increment_stats(STAT_PUT_START);
2700 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
2701 increment_stats(STAT_FIND_PEER_START);
2703 route_message(cls, enc_msg, &message_context);
2705 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2710 * Handler for any locally received DHT control messages,
2711 * sets malicious flags mostly for now.
2713 * @param cls closure for the service
2714 * @param client the client we received this message from
2715 * @param message the actual message received
2719 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
2720 const struct GNUNET_MessageHeader *message)
2722 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
2723 (const struct GNUNET_DHT_ControlMessage *) message;
2725 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2726 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
2727 "CONTROL", ntohs(dht_control_msg->command));
2730 switch (ntohs(dht_control_msg->command))
2732 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
2733 if (ntohs(dht_control_msg->variable) > 0)
2734 malicious_get_frequency = ntohs(dht_control_msg->variable);
2735 if (malicious_get_frequency == 0)
2736 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
2737 if (malicious_getter != GNUNET_YES)
2738 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
2739 malicious_getter = GNUNET_YES;
2740 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
2742 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
2743 if (ntohs(dht_control_msg->variable) > 0)
2744 malicious_put_frequency = ntohs(dht_control_msg->variable);
2745 if (malicious_put_frequency == 0)
2746 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
2747 if (malicious_putter != GNUNET_YES)
2748 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
2749 malicious_putter = GNUNET_YES;
2750 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
2752 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
2753 malicious_dropper = GNUNET_YES;
2754 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
2757 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
2760 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2764 * Handler for any generic DHT stop messages, calls the appropriate handler
2765 * depending on message type (if processed locally)
2767 * @param cls closure for the service
2768 * @param client the client we received this message from
2769 * @param message the actual message received
2773 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
2774 const struct GNUNET_MessageHeader *message)
2777 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
2778 (const struct GNUNET_DHT_StopMessage *) message;
2779 struct DHTQueryRecord *record;
2780 struct DHTRouteSource *pos;
2783 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2784 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
2785 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
2788 uid = GNUNET_ntohll(dht_stop_msg->unique_id);
2790 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
2797 if ((pos->client != NULL) && (pos->client->client_handle == client))
2799 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
2800 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
2806 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2811 * Core handler for p2p route requests.
2814 handle_dht_p2p_route_request (void *cls,
2815 const struct GNUNET_PeerIdentity *peer,
2816 const struct GNUNET_MessageHeader *message,
2817 struct GNUNET_TIME_Relative latency, uint32_t distance)
2820 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2821 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
2823 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
2824 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
2825 struct DHT_MessageContext *message_context;
2827 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
2830 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
2835 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2840 //memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2841 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
2842 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2843 GNUNET_assert(message_context->bloom != NULL);
2844 message_context->hop_count = ntohl(incoming->hop_count);
2845 message_context->key = &incoming->key;
2846 message_context->replication = ntohl(incoming->desired_replication_level);
2847 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
2848 message_context->msg_options = ntohl(incoming->options);
2849 message_context->network_size = ntohl(incoming->network_size);
2850 message_context->peer = peer;
2851 route_message(cls, enc_msg, message_context);
2852 GNUNET_free(message_context);
2858 * Core handler for p2p route results.
2861 handle_dht_p2p_route_result (void *cls,
2862 const struct GNUNET_PeerIdentity *peer,
2863 const struct GNUNET_MessageHeader *message,
2864 struct GNUNET_TIME_Relative latency, uint32_t distance)
2867 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2868 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
2870 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
2871 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
2872 struct DHT_MessageContext message_context;
2874 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2880 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2881 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2882 GNUNET_assert(message_context.bloom != NULL);
2883 message_context.key = &incoming->key;
2884 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
2885 message_context.msg_options = ntohl(incoming->options);
2886 message_context.hop_count = ntohl(incoming->hop_count);
2887 message_context.peer = peer;
2888 route_result_message(cls, enc_msg, &message_context);
2894 * Receive the HELLO from transport service,
2895 * free current and replace if necessary.
2898 * @param message HELLO message of peer
2901 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
2904 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2905 "Received our `%s' from transport service\n",
2909 GNUNET_assert (message != NULL);
2910 GNUNET_free_non_null(my_hello);
2911 my_hello = GNUNET_malloc(ntohs(message->size));
2912 memcpy(my_hello, message, ntohs(message->size));
2917 * Task run during shutdown.
2923 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2926 struct PeerInfo *pos;
2927 if (transport_handle != NULL)
2929 GNUNET_free_non_null(my_hello);
2930 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
2931 GNUNET_TRANSPORT_disconnect(transport_handle);
2934 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
2936 while (k_buckets[bucket_count].head != NULL)
2938 pos = k_buckets[bucket_count].head;
2940 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2941 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
2943 delete_peer(pos, bucket_count);
2946 if (coreAPI != NULL)
2949 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2950 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
2952 GNUNET_CORE_disconnect (coreAPI);
2954 if (datacache != NULL)
2957 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2958 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
2960 GNUNET_DATACACHE_destroy (datacache);
2965 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
2968 if (dhtlog_handle != NULL)
2969 GNUNET_DHTLOG_disconnect(dhtlog_handle);
2971 GNUNET_free_non_null(my_short_id);
2976 * To be called on core init/fail.
2978 * @param cls service closure
2979 * @param server handle to the server for this service
2980 * @param identity the public identity of this peer
2981 * @param publicKey the public key of this peer
2984 core_init (void *cls,
2985 struct GNUNET_CORE_Handle *server,
2986 const struct GNUNET_PeerIdentity *identity,
2987 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
2993 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2994 "%s: Connection to core FAILED!\n", "dht",
2995 GNUNET_i2s (identity));
2997 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
2998 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
3002 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3003 "%s: Core connection initialized, I am peer: %s\n", "dht",
3004 GNUNET_i2s (identity));
3007 /* Copy our identity so we can use it */
3008 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
3009 if (my_short_id != NULL)
3010 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
3011 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
3012 /* Set the server to local variable */
3015 if (dhtlog_handle != NULL)
3016 dhtlog_handle->insert_node (NULL, &my_identity);
3020 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
3021 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
3022 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
3023 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
3028 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
3029 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
3030 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
3035 * Method called whenever a peer connects.
3037 * @param cls closure
3038 * @param peer peer identity this notification is about
3039 * @param latency reported latency of the connection with peer
3040 * @param distance reported distance (DV) to peer
3042 void handle_core_connect (void *cls,
3043 const struct GNUNET_PeerIdentity * peer,
3044 struct GNUNET_TIME_Relative latency,
3047 struct PeerInfo *ret;
3050 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3051 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
3054 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3056 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));
3060 if (datacache != NULL)
3061 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
3062 ret = try_add_peer(peer,
3063 find_current_bucket(&peer->hashPubKey),
3068 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
3071 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
3072 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
3077 * Method called whenever a peer disconnects.
3079 * @param cls closure
3080 * @param peer peer identity this notification is about
3082 void handle_core_disconnect (void *cls,
3084 GNUNET_PeerIdentity * peer)
3086 struct PeerInfo *to_remove;
3089 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");
3091 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3093 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));
3096 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
3097 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
3098 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
3099 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
3100 delete_peer(to_remove, current_bucket);
3104 * Process dht requests.
3106 * @param cls closure
3107 * @param scheduler scheduler to use
3108 * @param server the initialized server
3109 * @param c configuration to use
3113 struct GNUNET_SCHEDULER_Handle *scheduler,
3114 struct GNUNET_SERVER_Handle *server,
3115 const struct GNUNET_CONFIGURATION_Handle *c)
3120 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
3121 GNUNET_SERVER_add_handlers (server, plugin_handlers);
3122 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
3123 cfg, /* Main configuration */
3124 GNUNET_TIME_UNIT_FOREVER_REL,
3125 NULL, /* Closure passed to DHT functionas around? */
3126 &core_init, /* Call core_init once connected */
3127 &handle_core_connect, /* Handle connects */
3128 &handle_core_disconnect, /* remove peers on disconnects */
3129 NULL, /* Do we care about "status" updates? */
3130 NULL, /* Don't want notified about all incoming messages */
3131 GNUNET_NO, /* For header only inbound notification */
3132 NULL, /* Don't want notified about all outbound messages */
3133 GNUNET_NO, /* For header only outbound notification */
3134 core_handlers); /* Register these handlers */
3136 if (coreAPI == NULL)
3138 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
3139 NULL, NULL, NULL, NULL, NULL);
3140 if (transport_handle != NULL)
3141 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
3143 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
3145 lowest_bucket = MAX_BUCKETS - 1;
3146 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
3147 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3148 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
3149 GNUNET_assert(all_known_peers != NULL);
3150 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
3152 debug_routes = GNUNET_YES;
3156 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3159 strict_kademlia = GNUNET_YES;
3163 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3166 stop_on_closest = GNUNET_YES;
3170 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3173 stop_on_found = GNUNET_YES;
3177 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3178 "malicious_getter"))
3180 malicious_getter = GNUNET_YES;
3181 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3182 "MALICIOUS_GET_FREQUENCY",
3183 &malicious_get_frequency))
3184 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3188 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3189 "malicious_putter"))
3191 malicious_putter = GNUNET_YES;
3192 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3193 "MALICIOUS_PUT_FREQUENCY",
3194 &malicious_put_frequency))
3195 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3199 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3200 "malicious_dropper"))
3202 malicious_dropper = GNUNET_YES;
3206 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
3207 "mysql_logging_extended"))
3209 debug_routes = GNUNET_YES;
3210 debug_routes_extended = GNUNET_YES;
3213 if (GNUNET_YES == debug_routes)
3215 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
3216 if (dhtlog_handle == NULL)
3218 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3219 "Could not connect to mysql logging server, logging will not happen!");
3223 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
3227 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
3228 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
3229 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
3230 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
3231 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
3232 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
3233 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
3234 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
3235 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
3236 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
3237 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
3238 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
3239 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
3240 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
3241 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
3242 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
3245 random_seconds = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 180);
3246 GNUNET_SCHEDULER_add_delayed (sched,
3247 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, random_seconds),
3248 &send_find_peer_message, NULL);
3251 /* Scheduled the task to clean up when shutdown is called */
3252 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
3253 GNUNET_TIME_UNIT_FOREVER_REL,
3254 &shutdown_task, NULL);
3258 * The main function for the dht service.
3260 * @param argc number of arguments from the command line
3261 * @param argv command line arguments
3262 * @return 0 ok, 1 on error
3265 main (int argc, char *const *argv)
3267 return (GNUNET_OK ==
3268 GNUNET_SERVICE_run (argc,
3271 GNUNET_SERVICE_OPTION_NONE,
3272 &run, NULL)) ? 0 : 1;