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_DEFAULT_FIND_PEER_OPTIONS GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE
74 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
75 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 5)
78 * How many initial requests to send out (in true Kademlia fashion)
80 #define DHT_KADEMLIA_REPLICATION 3
83 * Default frequency for sending malicious get messages
85 #define DEFAULT_MALICIOUS_GET_FREQUENCY 1000 /* Number of milliseconds */
88 * Type for a malicious request, so we can ignore it during testing
90 #define DHT_MALICIOUS_MESSAGE_TYPE 42
92 * Default frequency for sending malicious put messages
94 #define DEFAULT_MALICIOUS_PUT_FREQUENCY 1000 /* Default is in milliseconds */
96 #define DHT_DEFAULT_PING_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 1)
99 * Real maximum number of hops, at which point we refuse
100 * to forward the message.
105 * Linked list of messages to send to clients.
107 struct P2PPendingMessage
110 * Pointer to next item in the list
112 struct P2PPendingMessage *next;
115 * Pointer to previous item in the list
117 struct P2PPendingMessage *prev;
120 * Message importance level.
122 unsigned int importance;
125 * How long to wait before sending message.
127 struct GNUNET_TIME_Relative timeout;
130 * Actual message to be sent; // avoid allocation
132 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
138 * Per-peer information.
143 * Next peer entry (DLL)
145 struct PeerInfo *next;
148 * Prev peer entry (DLL)
150 struct PeerInfo *prev;
153 * Head of pending messages to be sent to this peer.
155 struct P2PPendingMessage *head;
158 * Tail of pending messages to be sent to this peer.
160 struct P2PPendingMessage *tail;
163 * Core handle for sending messages to this peer.
165 struct GNUNET_CORE_TransmitHandle *th;
168 * Task for scheduling message sends.
170 GNUNET_SCHEDULER_TaskIdentifier send_task;
173 * What is the average latency for replies received?
175 struct GNUNET_TIME_Relative latency;
178 * Number of responses received
180 unsigned long long response_count;
183 * Number of requests sent
185 unsigned long long request_count;
188 * What is the identity of the peer?
190 struct GNUNET_PeerIdentity id;
193 * Transport level distance to peer.
195 unsigned int distance;
198 * Task for scheduling periodic ping messages for this peer.
200 GNUNET_SCHEDULER_TaskIdentifier ping_task;
205 * Peers are grouped into buckets.
212 struct PeerInfo *head;
217 struct PeerInfo *tail;
220 * Number of peers in the bucket.
222 unsigned int peers_size;
226 * Linked list of messages to send to clients.
228 struct PendingMessage
231 * Pointer to next item in the list
233 struct PendingMessage *next;
236 * Pointer to previous item in the list
238 struct PendingMessage *prev;
241 * Actual message to be sent; // avoid allocation
243 const struct GNUNET_MessageHeader *msg; // msg = (cast) &pm[1]; // memcpy (&pm[1], data, len);
248 * Struct containing information about a client,
249 * handle to connect to it, and any pending messages
250 * that need to be sent to it.
255 * Linked list of active clients
257 struct ClientList *next;
260 * The handle to this client
262 struct GNUNET_SERVER_Client *client_handle;
265 * Handle to the current transmission request, NULL
268 struct GNUNET_CONNECTION_TransmitHandle *transmit_handle;
271 * Linked list of pending messages for this client
273 struct PendingMessage *pending_head;
276 * Tail of linked list of pending messages for this client
278 struct PendingMessage *pending_tail;
284 * Context containing information about a DHT message received.
286 struct DHT_MessageContext
289 * The client this request was received from.
290 * (NULL if received from another peer)
292 struct ClientList *client;
295 * The peer this request was received from.
296 * (NULL if received from local client)
298 const struct GNUNET_PeerIdentity *peer;
301 * The key this request was about
303 const GNUNET_HashCode *key;
306 * The unique identifier of this request
311 * Desired replication level
313 uint32_t replication;
316 * Network size estimate, either ours or the sum of
317 * those routed to thus far. =~ Log of number of peers
318 * chosen from for this request.
320 uint32_t network_size;
323 * Any message options for this request
325 uint32_t msg_options;
328 * How many hops has the message already traversed?
333 * Bloomfilter for this routing request.
335 struct GNUNET_CONTAINER_BloomFilter *bloom;
338 * Did we forward this message? (may need to remember it!)
343 * Are we the closest known peer to this key (out of our neighbors?)
349 * Record used for remembering what peers are waiting for what
350 * responses (based on search key).
352 struct DHTRouteSource
358 struct DHTRouteSource *next;
363 struct DHTRouteSource *prev;
366 * Source of the request. Replies should be forwarded to
369 struct GNUNET_PeerIdentity source;
372 * If this was a local request, remember the client; otherwise NULL.
374 struct ClientList *client;
377 * Pointer to this nodes heap location (for removal)
379 struct GNUNET_CONTAINER_HeapNode *hnode;
382 * Back pointer to the record storing this information.
384 struct DHTQueryRecord *record;
387 * Task to remove this entry on timeout.
389 GNUNET_SCHEDULER_TaskIdentifier delete_task;
393 * Entry in the DHT routing table.
395 struct DHTQueryRecord
398 * Head of DLL for result forwarding.
400 struct DHTRouteSource *head;
403 * Tail of DLL for result forwarding.
405 struct DHTRouteSource *tail;
408 * Key that the record concerns.
413 * GET message of this record (what we already forwarded?).
415 //DV_DHT_MESSAGE get; Try to get away with not saving this.
418 * Bloomfilter of the peers we've replied to so far
420 //struct GNUNET_BloomFilter *bloom_results; Don't think we need this, just remove from DLL on response.
425 * DHT Routing results structure
430 * Min heap for removal upon reaching limit
432 struct GNUNET_CONTAINER_Heap *minHeap;
435 * Hashmap for fast key based lookup
437 struct GNUNET_CONTAINER_MultiHashMap *hashmap;
442 * Don't use our routing algorithm, always route
443 * to closest peer; initially send requests to 3
446 static int strict_kademlia;
449 * Routing option to end routing when closest peer found.
451 static int stop_on_closest;
454 * Routing option to end routing when data is found.
456 static int stop_on_found;
459 * Container of active queries we should remember
461 static struct DHTResults forward_list;
464 * Handle to the datacache service (for inserting/retrieving data)
466 static struct GNUNET_DATACACHE_Handle *datacache;
469 * Handle for the statistics service.
471 struct GNUNET_STATISTICS_Handle *stats;
474 * The main scheduler to use for the DHT service
476 static struct GNUNET_SCHEDULER_Handle *sched;
479 * The configuration the DHT service is running with
481 static const struct GNUNET_CONFIGURATION_Handle *cfg;
484 * Handle to the core service
486 static struct GNUNET_CORE_Handle *coreAPI;
489 * Handle to the transport service, for getting our hello
491 static struct GNUNET_TRANSPORT_Handle *transport_handle;
494 * The identity of our peer.
496 static struct GNUNET_PeerIdentity my_identity;
499 * Short id of the peer, for printing
501 static char *my_short_id;
506 static struct GNUNET_MessageHeader *my_hello;
509 * Task to run when we shut down, cleaning up all our trash
511 static GNUNET_SCHEDULER_TaskIdentifier cleanup_task;
514 * The lowest currently used bucket.
516 static unsigned int lowest_bucket; /* Initially equal to MAX_BUCKETS - 1 */
519 * The buckets (Kademlia routing table, complete with growth).
520 * Array of size MAX_BUCKET_SIZE.
522 static struct PeerBucket k_buckets[MAX_BUCKETS]; /* From 0 to MAX_BUCKETS - 1 */
525 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
527 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
530 * Maximum size for each bucket.
532 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE; /* Initially equal to DEFAULT_BUCKET_SIZE */
535 * List of active clients.
537 static struct ClientList *client_list;
540 * Handle to the DHT logger.
542 static struct GNUNET_DHTLOG_Handle *dhtlog_handle;
545 * Whether or not to send routing debugging information
546 * to the dht logging server
548 static unsigned int debug_routes;
551 * Whether or not to send FULL route information to
554 static unsigned int debug_routes_extended;
557 * GNUNET_YES or GNUNET_NO, whether or not to act as
558 * a malicious node which drops all messages
560 static unsigned int malicious_dropper;
563 * GNUNET_YES or GNUNET_NO, whether or not to act as
564 * a malicious node which sends out lots of GETS
566 static unsigned int malicious_getter;
569 * GNUNET_YES or GNUNET_NO, whether or not to act as
570 * a malicious node which sends out lots of PUTS
572 static unsigned int malicious_putter;
574 static unsigned long long malicious_get_frequency;
576 static unsigned long long malicious_put_frequency;
579 * Forward declaration.
581 static size_t send_generic_reply (void *cls, size_t size, void *buf);
583 /* Declare here so retry_core_send is aware of it */
584 size_t core_transmit_notify (void *cls,
585 size_t size, void *buf);
588 increment_stats(const char *value)
592 GNUNET_STATISTICS_update (stats, value, 1, GNUNET_NO);
597 * Try to send another message from our core send list
600 try_core_send (void *cls,
601 const struct GNUNET_SCHEDULER_TaskContext *tc)
603 struct PeerInfo *peer = cls;
604 struct P2PPendingMessage *pending;
607 peer->send_task = GNUNET_SCHEDULER_NO_TASK;
609 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
612 if (peer->th != NULL)
613 return; /* Message send already in progress */
615 pending = peer->head;
618 ssize = ntohs(pending->msg->size);
620 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
621 "`%s:%s': Calling notify_transmit_ready with size %d for peer %s\n", my_short_id,
622 "DHT", ssize, GNUNET_i2s(&peer->id));
624 peer->th = GNUNET_CORE_notify_transmit_ready(coreAPI, pending->importance,
625 pending->timeout, &peer->id,
626 ssize, &core_transmit_notify, peer);
631 * Function called to send a request out to another peer.
632 * Called both for locally initiated requests and those
633 * received from other peers.
635 * @param cls DHT service closure argument
636 * @param msg the encapsulated message
637 * @param peer the peer to forward the message to
638 * @param msg_ctx the context of the message (hop count, bloom, etc.)
640 static void forward_result_message (void *cls,
641 const struct GNUNET_MessageHeader *msg,
642 struct PeerInfo *peer,
643 struct DHT_MessageContext *msg_ctx)
645 struct GNUNET_DHT_P2PRouteResultMessage *result_message;
646 struct P2PPendingMessage *pending;
650 increment_stats(STAT_RESULT_FORWARDS);
651 msize = sizeof (struct GNUNET_DHT_P2PRouteResultMessage) + ntohs(msg->size);
652 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
653 psize = sizeof(struct P2PPendingMessage) + msize;
654 pending = GNUNET_malloc(psize);
655 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
656 pending->importance = DHT_SEND_PRIORITY;
657 pending->timeout = GNUNET_TIME_relative_get_forever();
658 result_message = (struct GNUNET_DHT_P2PRouteResultMessage *)pending->msg;
659 result_message->header.size = htons(msize);
660 result_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT);
661 result_message->options = htonl(msg_ctx->msg_options);
662 result_message->hop_count = htonl(msg_ctx->hop_count + 1);
663 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, result_message->bloomfilter, DHT_BLOOM_SIZE));
664 result_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
665 memcpy(&result_message->key, msg_ctx->key, sizeof(GNUNET_HashCode));
666 memcpy(&result_message[1], msg, ntohs(msg->size));
668 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));
670 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
671 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
672 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
675 * Called when core is ready to send a message we asked for
676 * out to the destination.
678 * @param cls closure (NULL)
679 * @param size number of bytes available in buf
680 * @param buf where the callee should write the message
681 * @return number of bytes written to buf
683 size_t core_transmit_notify (void *cls,
684 size_t size, void *buf)
686 struct PeerInfo *peer = cls;
688 struct P2PPendingMessage *pending;
695 /* client disconnected */
697 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s:%s': buffer was NULL\n", my_short_id, "DHT");
702 if (peer->head == NULL)
707 pending = peer->head;
708 msize = ntohs(pending->msg->size);
712 memcpy (cbuf, pending->msg, msize);
713 GNUNET_CONTAINER_DLL_remove (peer->head,
717 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));
719 GNUNET_free (pending);
722 while (NULL != pending &&
723 (size - off >= (msize = ntohs (pending->msg->size))))
725 #if DEBUG_DHT_ROUTING
726 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);
728 memcpy (&cbuf[off], pending->msg, msize);
730 GNUNET_CONTAINER_DLL_remove (peer->head,
733 GNUNET_free (pending);
734 pending = peer->head;
737 if ((peer->head != NULL) && (peer->send_task == GNUNET_SCHEDULER_NO_TASK))
738 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
740 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);
746 * Determine how many low order bits match in two
747 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
748 * the first two lowest order bits, and therefore the
749 * return value is two (NOT XOR distance, nor how many
750 * bits match absolutely!).
752 * @param first the first hashcode
753 * @param second the hashcode to compare first to
755 * @return the number of bits that match
757 static unsigned int matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second)
761 for (i = 0; i < sizeof (GNUNET_HashCode) * 8; i++)
762 if (GNUNET_CRYPTO_hash_get_bit (first, i) != GNUNET_CRYPTO_hash_get_bit (second, i))
764 return sizeof (GNUNET_HashCode) * 8;
768 * Compute the distance between have and target as a 32-bit value.
769 * Differences in the lower bits must count stronger than differences
770 * in the higher bits.
772 * @return 0 if have==target, otherwise a number
773 * that is larger as the distance between
774 * the two hash codes increases
777 distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
784 /* We have to represent the distance between two 2^9 (=512)-bit
785 numbers as a 2^5 (=32)-bit number with "0" being used for the
786 two numbers being identical; furthermore, we need to
787 guarantee that a difference in the number of matching
788 bits is always represented in the result.
790 We use 2^32/2^9 numerical values to distinguish between
791 hash codes that have the same LSB bit distance and
792 use the highest 2^9 bits of the result to signify the
793 number of (mis)matching LSB bits; if we have 0 matching
794 and hence 512 mismatching LSB bits we return -1 (since
795 512 itself cannot be represented with 9 bits) */
797 /* first, calculate the most significant 9 bits of our
798 result, aka the number of LSBs */
799 bucket = matching_bits (target, have);
800 /* bucket is now a value between 0 and 512 */
802 return 0; /* perfect match */
804 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
805 below, we'd end up with max+1 (overflow)) */
807 /* calculate the most significant bits of the final result */
808 msb = (512 - bucket) << (32 - 9);
809 /* calculate the 32-9 least significant bits of the final result by
810 looking at the differences in the 32-9 bits following the
811 mismatching bit at 'bucket' */
814 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
816 if (GNUNET_CRYPTO_hash_get_bit (target, i) != GNUNET_CRYPTO_hash_get_bit (have, i))
817 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
818 last bit set will be 31 -- if
819 i does not reach 512 first... */
825 * Return a number that is larger the closer the
826 * "have" GNUNET_hash code is to the "target".
828 * @return inverse distance metric, non-zero.
829 * Must fudge the value if NO bits match.
832 inverse_distance (const GNUNET_HashCode * target,
833 const GNUNET_HashCode * have)
835 if (matching_bits(target, have) == 0)
836 return 1; /* Never return 0! */
837 return ((unsigned int) -1) - distance (target, have);
841 * Find the optimal bucket for this key, regardless
842 * of the current number of buckets in use.
844 * @param hc the hashcode to compare our identity to
846 * @return the proper bucket index, or GNUNET_SYSERR
847 * on error (same hashcode)
849 static int find_bucket(const GNUNET_HashCode *hc)
853 bits = matching_bits(&my_identity.hashPubKey, hc);
854 if (bits == MAX_BUCKETS)
855 return GNUNET_SYSERR;
856 return MAX_BUCKETS - bits - 1;
860 * Find which k-bucket this peer should go into,
861 * taking into account the size of the k-bucket
862 * array. This means that if more bits match than
863 * there are currently buckets, lowest_bucket will
866 * @param hc GNUNET_HashCode we are finding the bucket for.
868 * @return the proper bucket index for this key,
869 * or GNUNET_SYSERR on error (same hashcode)
871 static int find_current_bucket(const GNUNET_HashCode *hc)
874 actual_bucket = find_bucket(hc);
876 if (actual_bucket == GNUNET_SYSERR) /* hc and our peer identity match! */
877 return GNUNET_SYSERR;
878 else if (actual_bucket < lowest_bucket) /* actual_bucket not yet used */
879 return lowest_bucket;
881 return actual_bucket;
885 * Find a routing table entry from a peer identity
887 * @param peer the peer to look up
889 * @return the bucket number holding the peer, GNUNET_SYSERR if not found
892 find_bucket_by_peer(const struct PeerInfo *peer)
895 struct PeerInfo *pos;
897 for (bucket = lowest_bucket; bucket < MAX_BUCKETS - 1; bucket++)
899 pos = k_buckets[bucket].head;
908 return GNUNET_SYSERR; /* No such peer. */
913 * Print the complete routing table for this peer.
916 print_routing_table ()
919 struct PeerInfo *pos;
920 char char_buf[30000];
922 memset(char_buf, 0, sizeof(char_buf));
924 char_pos += sprintf(&char_buf[char_pos], "Printing routing table for peer %s\n", my_short_id);
925 //fprintf(stderr, "Printing routing table for peer %s\n", my_short_id);
926 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
928 pos = k_buckets[bucket].head;
929 char_pos += sprintf(&char_buf[char_pos], "Bucket %d:\n", bucket);
930 //fprintf(stderr, "Bucket %d:\n", bucket);
933 //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));
934 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));
938 fprintf(stderr, "%s", char_buf);
944 * Find a routing table entry from a peer identity
946 * @param peer the peer identity to look up
948 * @return the routing table entry, or NULL if not found
950 static struct PeerInfo *
951 find_peer_by_id(const struct GNUNET_PeerIdentity *peer)
954 struct PeerInfo *pos;
955 bucket = find_current_bucket(&peer->hashPubKey);
957 if (bucket == GNUNET_SYSERR)
960 pos = k_buckets[bucket].head;
963 if (0 == memcmp(&pos->id, peer, sizeof(struct GNUNET_PeerIdentity)))
967 return NULL; /* No such peer. */
971 * Really add a peer to a bucket (only do assertions
974 * @param peer GNUNET_PeerIdentity of the peer to add
975 * @param bucket the already figured out bucket to add
977 * @param latency the core reported latency of this peer
978 * @param distance the transport level distance to this peer
980 * @return the newly added PeerInfo
982 static struct PeerInfo *
983 add_peer(const struct GNUNET_PeerIdentity *peer,
985 struct GNUNET_TIME_Relative latency,
986 unsigned int distance)
988 struct PeerInfo *new_peer;
989 GNUNET_assert(bucket < MAX_BUCKETS);
990 GNUNET_assert(peer != NULL);
991 new_peer = GNUNET_malloc(sizeof(struct PeerInfo));
992 new_peer->latency = latency;
993 new_peer->distance = distance;
994 memcpy(&new_peer->id, peer, sizeof(struct GNUNET_PeerIdentity));
996 GNUNET_CONTAINER_DLL_insert_after(k_buckets[bucket].head,
997 k_buckets[bucket].tail,
998 k_buckets[bucket].tail,
1000 k_buckets[bucket].peers_size++;
1006 * Given a peer and its corresponding bucket,
1007 * remove it from that bucket. Does not free
1008 * the PeerInfo struct, nor cancel messages
1009 * or free messages waiting to be sent to this
1012 * @param peer the peer to remove
1013 * @param bucket the bucket the peer belongs to
1015 static void remove_peer (struct PeerInfo *peer,
1016 unsigned int bucket)
1018 GNUNET_assert(k_buckets[bucket].peers_size > 0);
1019 GNUNET_CONTAINER_DLL_remove(k_buckets[bucket].head,
1020 k_buckets[bucket].tail,
1022 k_buckets[bucket].peers_size--;
1023 if ((bucket == lowest_bucket) && (k_buckets[lowest_bucket].peers_size == 0) && (lowest_bucket < MAX_BUCKETS - 1))
1028 * Removes peer from a bucket, then frees associated
1029 * resources and frees peer.
1031 * @param peer peer to be removed and freed
1032 * @param bucket which bucket this peer belongs to
1034 static void delete_peer (struct PeerInfo *peer,
1035 unsigned int bucket)
1037 struct P2PPendingMessage *pos;
1038 struct P2PPendingMessage *next;
1040 struct PeerInfo *peer_pos;
1042 peer_pos = k_buckets[bucket].head;
1043 while ((peer_pos != NULL) && (peer_pos != peer))
1044 peer_pos = peer_pos->next;
1045 if (peer_pos == NULL)
1047 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: Expected peer `%s' in bucket %d\n", my_short_id, "DHT", GNUNET_i2s(&peer->id), bucket);
1048 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));
1050 GNUNET_assert(peer_pos != NULL);
1052 remove_peer(peer, bucket); /* First remove the peer from its bucket */
1054 if (peer->send_task != GNUNET_SCHEDULER_NO_TASK)
1055 GNUNET_SCHEDULER_cancel(sched, peer->send_task);
1056 if (peer->th != NULL)
1057 GNUNET_CORE_notify_transmit_ready_cancel(peer->th);
1060 while (pos != NULL) /* Remove any pending messages for this peer */
1067 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->id.hashPubKey));
1068 GNUNET_CONTAINER_multihashmap_remove (all_known_peers, &peer->id.hashPubKey, peer);
1074 * Iterator over hash map entries.
1076 * @param cls closure
1077 * @param key current key code
1078 * @param value PeerInfo of the peer to move to new lowest bucket
1079 * @return GNUNET_YES if we should continue to
1083 static int move_lowest_bucket (void *cls,
1084 const GNUNET_HashCode * key,
1087 struct PeerInfo *peer = value;
1090 new_bucket = lowest_bucket - 1;
1091 remove_peer(peer, lowest_bucket);
1092 GNUNET_CONTAINER_DLL_insert_after(k_buckets[new_bucket].head,
1093 k_buckets[new_bucket].tail,
1094 k_buckets[new_bucket].tail,
1096 k_buckets[new_bucket].peers_size++;
1102 * The current lowest bucket is full, so change the lowest
1103 * bucket to the next lower down, and move any appropriate
1104 * entries in the current lowest bucket to the new bucket.
1106 static void enable_next_bucket()
1108 struct GNUNET_CONTAINER_MultiHashMap *to_remove;
1109 struct PeerInfo *pos;
1110 GNUNET_assert(lowest_bucket > 0);
1111 to_remove = GNUNET_CONTAINER_multihashmap_create(bucket_size);
1112 pos = k_buckets[lowest_bucket].head;
1115 fprintf(stderr, "Printing RT before new bucket\n");
1116 print_routing_table();
1118 /* Populate the array of peers which should be in the next lowest bucket */
1121 if (find_bucket(&pos->id.hashPubKey) < lowest_bucket)
1122 GNUNET_CONTAINER_multihashmap_put(to_remove, &pos->id.hashPubKey, pos, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1126 /* Remove peers from lowest bucket, insert into next lowest bucket */
1127 GNUNET_CONTAINER_multihashmap_iterate(to_remove, &move_lowest_bucket, NULL);
1128 GNUNET_CONTAINER_multihashmap_destroy(to_remove);
1129 lowest_bucket = lowest_bucket - 1;
1131 fprintf(stderr, "Printing RT after new bucket\n");
1132 print_routing_table();
1137 * Function called to send a request out to another peer.
1138 * Called both for locally initiated requests and those
1139 * received from other peers.
1141 * @param cls DHT service closure argument (unused)
1142 * @param msg the encapsulated message
1143 * @param peer the peer to forward the message to
1144 * @param msg_ctx the context of the message (hop count, bloom, etc.)
1146 static void forward_message (void *cls,
1147 const struct GNUNET_MessageHeader *msg,
1148 struct PeerInfo *peer,
1149 struct DHT_MessageContext *msg_ctx)
1151 struct GNUNET_DHT_P2PRouteMessage *route_message;
1152 struct P2PPendingMessage *pending;
1156 increment_stats(STAT_ROUTE_FORWARDS);
1157 msize = sizeof (struct GNUNET_DHT_P2PRouteMessage) + ntohs(msg->size);
1158 GNUNET_assert(msize <= GNUNET_SERVER_MAX_MESSAGE_SIZE);
1159 psize = sizeof(struct P2PPendingMessage) + msize;
1160 pending = GNUNET_malloc(psize);
1161 pending->msg = (struct GNUNET_MessageHeader *)&pending[1];
1162 pending->importance = DHT_SEND_PRIORITY;
1163 pending->timeout = GNUNET_TIME_relative_get_forever();
1164 route_message = (struct GNUNET_DHT_P2PRouteMessage *)pending->msg;
1165 route_message->header.size = htons(msize);
1166 route_message->header.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE);
1167 route_message->options = htonl(msg_ctx->msg_options);
1168 route_message->hop_count = htonl(msg_ctx->hop_count + 1);
1169 route_message->network_size = htonl(msg_ctx->network_size);
1170 route_message->desired_replication_level = htonl(msg_ctx->replication);
1171 route_message->unique_id = GNUNET_htonll(msg_ctx->unique_id);
1172 if (msg_ctx->bloom != NULL)
1173 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_bloomfilter_get_raw_data(msg_ctx->bloom, route_message->bloomfilter, DHT_BLOOM_SIZE));
1174 if (msg_ctx->key != NULL)
1175 memcpy(&route_message->key, msg_ctx->key, sizeof(GNUNET_HashCode));
1176 memcpy(&route_message[1], msg, ntohs(msg->size));
1178 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));
1180 GNUNET_CONTAINER_DLL_insert_after(peer->head, peer->tail, peer->tail, pending);
1181 if (peer->send_task == GNUNET_SCHEDULER_NO_TASK)
1182 peer->send_task = GNUNET_SCHEDULER_add_now(sched, &try_core_send, peer);
1187 * Task used to send ping messages to peers so that
1188 * they don't get disconnected.
1190 * @param cls the peer to send a ping message to
1191 * @param tc context, reason, etc.
1194 periodic_ping_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1196 struct PeerInfo *peer = cls;
1197 struct GNUNET_MessageHeader ping_message;
1198 struct DHT_MessageContext message_context;
1200 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
1203 ping_message.size = htons(sizeof(struct GNUNET_MessageHeader));
1204 ping_message.type = htons(GNUNET_MESSAGE_TYPE_DHT_P2P_PING);
1206 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
1208 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Sending periodic ping to %s\n", my_short_id, "DHT", GNUNET_i2s(&peer->id));
1210 forward_message(NULL, &ping_message, peer, &message_context);
1211 peer->ping_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_DEFAULT_PING_DELAY, &periodic_ping_task, peer);
1215 * Schedule PING messages for the top X peers in each
1216 * bucket of the routing table (so core won't disconnect them!)
1218 void schedule_ping_messages()
1220 unsigned int bucket;
1222 struct PeerInfo *pos;
1223 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1225 pos = k_buckets[bucket].head;
1229 if ((count < bucket_size) && (pos->ping_task == GNUNET_SCHEDULER_NO_TASK))
1230 GNUNET_SCHEDULER_add_now(sched, &periodic_ping_task, pos);
1231 else if ((count >= bucket_size) && (pos->ping_task != GNUNET_SCHEDULER_NO_TASK))
1233 GNUNET_SCHEDULER_cancel(sched, pos->ping_task);
1234 pos->ping_task = GNUNET_SCHEDULER_NO_TASK;
1244 * Attempt to add a peer to our k-buckets.
1246 * @param peer, the peer identity of the peer being added
1248 * @return NULL if the peer was not added,
1249 * pointer to PeerInfo for new peer otherwise
1251 static struct PeerInfo *
1252 try_add_peer(const struct GNUNET_PeerIdentity *peer,
1253 unsigned int bucket,
1254 struct GNUNET_TIME_Relative latency,
1255 unsigned int distance)
1258 struct PeerInfo *new_peer;
1259 peer_bucket = find_current_bucket(&peer->hashPubKey);
1260 if (peer_bucket == GNUNET_SYSERR)
1263 GNUNET_assert(peer_bucket >= lowest_bucket);
1264 new_peer = add_peer(peer, peer_bucket, latency, distance);
1266 if ((k_buckets[lowest_bucket].peers_size) >= bucket_size)
1267 enable_next_bucket();
1269 schedule_ping_messages();
1276 * Task run to check for messages that need to be sent to a client.
1278 * @param client a ClientList, containing the client and any messages to be sent to it
1281 process_pending_messages (struct ClientList *client)
1283 if (client->pending_head == NULL)
1285 if (client->transmit_handle != NULL)
1287 client->transmit_handle =
1288 GNUNET_SERVER_notify_transmit_ready (client->client_handle,
1289 ntohs (client->pending_head->msg->
1291 GNUNET_TIME_UNIT_FOREVER_REL,
1292 &send_generic_reply, client);
1296 * Callback called as a result of issuing a GNUNET_SERVER_notify_transmit_ready
1297 * request. A ClientList is passed as closure, take the head of the list
1298 * and copy it into buf, which has the result of sending the message to the
1301 * @param cls closure to this call
1302 * @param size maximum number of bytes available to send
1303 * @param buf where to copy the actual message to
1305 * @return the number of bytes actually copied, 0 indicates failure
1308 send_generic_reply (void *cls, size_t size, void *buf)
1310 struct ClientList *client = cls;
1312 struct PendingMessage *reply;
1316 client->transmit_handle = NULL;
1319 /* client disconnected */
1323 while ( (NULL != (reply = client->pending_head)) &&
1324 (size >= off + (msize = ntohs (reply->msg->size))))
1326 GNUNET_CONTAINER_DLL_remove (client->pending_head,
1327 client->pending_tail,
1329 memcpy (&cbuf[off], reply->msg, msize);
1330 GNUNET_free (reply);
1333 process_pending_messages (client);
1339 * Add a PendingMessage to the clients list of messages to be sent
1341 * @param client the active client to send the message to
1342 * @param pending_message the actual message to send
1345 add_pending_message (struct ClientList *client,
1346 struct PendingMessage *pending_message)
1348 GNUNET_CONTAINER_DLL_insert_after (client->pending_head,
1349 client->pending_tail,
1350 client->pending_tail,
1352 process_pending_messages (client);
1359 * Called when a reply needs to be sent to a client, as
1360 * a result it found to a GET or FIND PEER request.
1362 * @param client the client to send the reply to
1363 * @param message the encapsulated message to send
1364 * @param uid the unique identifier of this request
1367 send_reply_to_client (struct ClientList *client,
1368 const struct GNUNET_MessageHeader *message,
1369 unsigned long long uid)
1371 struct GNUNET_DHT_RouteResultMessage *reply;
1372 struct PendingMessage *pending_message;
1376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1377 "`%s:%s': Sending reply to client.\n", my_short_id, "DHT");
1379 msize = ntohs (message->size);
1380 tsize = sizeof (struct GNUNET_DHT_RouteResultMessage) + msize;
1381 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1383 GNUNET_break_op (0);
1387 pending_message = GNUNET_malloc (sizeof (struct PendingMessage) + tsize);
1388 pending_message->msg = (struct GNUNET_MessageHeader *)&pending_message[1];
1389 reply = (struct GNUNET_DHT_RouteResultMessage *)&pending_message[1];
1390 reply->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_RESULT);
1391 reply->header.size = htons (tsize);
1392 reply->unique_id = GNUNET_htonll (uid);
1393 memcpy (&reply[1], message, msize);
1395 add_pending_message (client, pending_message);
1399 * Consider whether or not we would like to have this peer added to
1400 * our routing table. Check whether bucket for this peer is full,
1401 * if so return negative; if not return positive. Since peers are
1402 * only added on CORE level connect, this doesn't actually add the
1403 * peer to the routing table.
1405 * @param peer the peer we are considering adding
1407 * @return GNUNET_YES if we want this peer, GNUNET_NO if not (bucket
1410 * FIXME: Think about making a context for this call so that we can
1411 * ping the oldest peer in the current bucket and consider
1412 * removing it in lieu of the new peer.
1414 static int consider_peer (struct GNUNET_PeerIdentity *peer)
1418 if (GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
1419 return GNUNET_NO; /* We already know this peer (are connected even!) */
1420 bucket = find_current_bucket(&peer->hashPubKey);
1421 if ((k_buckets[bucket].peers_size < bucket_size) || ((bucket == lowest_bucket) && (lowest_bucket > 0)))
1428 * Main function that handles whether or not to route a result
1429 * message to other peers, or to send to our local client.
1431 * @param msg the result message to be routed
1432 * @return the number of peers the message was routed to,
1433 * GNUNET_SYSERR on failure
1435 static int route_result_message(void *cls,
1436 struct GNUNET_MessageHeader *msg,
1437 struct DHT_MessageContext *message_context)
1439 struct GNUNET_PeerIdentity new_peer;
1440 struct DHTQueryRecord *record;
1441 struct DHTRouteSource *pos;
1442 struct PeerInfo *peer_info;
1443 const struct GNUNET_MessageHeader *hello_msg;
1445 increment_stats(STAT_RESULTS);
1447 * If a find peer result message is received and contains a valid
1448 * HELLO for another peer, offer it to the transport service.
1450 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT)
1452 if (ntohs(msg->size) <= sizeof(struct GNUNET_MessageHeader))
1455 hello_msg = &msg[1];
1456 if ((ntohs(hello_msg->type) != GNUNET_MESSAGE_TYPE_HELLO) || (GNUNET_SYSERR == GNUNET_HELLO_get_id((const struct GNUNET_HELLO_Message *)hello_msg, &new_peer)))
1458 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Received non-HELLO message type in find peer result message!\n", my_short_id, "DHT");
1461 else /* We have a valid hello, and peer id stored in new_peer */
1463 increment_stats(STAT_FIND_PEER_REPLY);
1464 if (GNUNET_YES == consider_peer(&new_peer))
1466 GNUNET_TRANSPORT_offer_hello(transport_handle, hello_msg);
1467 /* GNUNET_CORE_peer_request_connect(sched, cfg, GNUNET_TIME_UNIT_FOREVER_REL, &new_peer, NULL, NULL); */
1468 /* peer_request_connect call causes service to segfault */
1469 /* FIXME: Do we need this (peer_request_connect call)??? */
1474 if (malicious_dropper == GNUNET_YES)
1477 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, message_context->key);
1479 if (record == NULL) /* No record of this message! */
1482 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1483 "`%s:%s': Have no record of response key %s uid %llu\n", my_short_id,
1484 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1486 #if DEBUG_DHT_ROUTING
1488 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1490 dhtlog_handle->insert_route (NULL,
1491 message_context->unique_id,
1493 message_context->hop_count,
1496 message_context->key,
1497 message_context->peer, NULL);
1500 if (message_context->bloom != NULL)
1502 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1503 message_context->bloom = NULL;
1511 if (0 == memcmp(&pos->source, &my_identity, sizeof(struct GNUNET_PeerIdentity))) /* Local client (or DHT) initiated request! */
1514 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1515 "`%s:%s': Sending response key %s uid %llu to client\n", my_short_id,
1516 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
1518 #if DEBUG_DHT_ROUTING
1519 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1521 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_RESULT,
1522 message_context->hop_count,
1523 GNUNET_YES, &my_identity, message_context->key,
1524 message_context->peer, NULL);
1527 increment_stats(STAT_RESULTS_TO_CLIENT);
1528 if (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET_RESULT)
1529 increment_stats(STAT_GET_REPLY);
1531 send_reply_to_client(pos->client, msg, message_context->unique_id);
1533 else /* Send to peer */
1535 peer_info = find_peer_by_id(&pos->source);
1536 if (peer_info == NULL) /* Didn't find the peer in our routing table, perhaps peer disconnected! */
1542 if (message_context->bloom == NULL)
1543 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1544 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
1545 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (message_context->bloom, &peer_info->id.hashPubKey))
1548 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1549 "`%s:%s': Forwarding response key %s uid %llu to peer %s\n", my_short_id,
1550 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1552 #if DEBUG_DHT_ROUTING
1553 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1555 dhtlog_handle->insert_route (NULL, message_context->unique_id,
1557 message_context->hop_count,
1558 GNUNET_NO, &my_identity, message_context->key,
1559 message_context->peer, &pos->source);
1562 forward_result_message(cls, msg, peer_info, message_context);
1567 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1568 "`%s:%s': NOT Forwarding response (bloom match) key %s uid %llu to peer %s\n", my_short_id,
1569 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id, GNUNET_i2s(&peer_info->id));
1575 if (message_context->bloom != NULL)
1576 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
1581 * Iterator for local get request results,
1583 * @param cls closure for iterator, a DatacacheGetContext
1584 * @param exp when does this value expire?
1585 * @param key the key this data is stored under
1586 * @param size the size of the data identified by key
1587 * @param data the actual data
1588 * @param type the type of the data
1590 * @return GNUNET_OK to continue iteration, anything else
1591 * to stop iteration.
1594 datacache_get_iterator (void *cls,
1595 struct GNUNET_TIME_Absolute exp,
1596 const GNUNET_HashCode * key,
1597 uint32_t size, const char *data, uint32_t type)
1599 struct DHT_MessageContext *msg_ctx = cls;
1600 struct DHT_MessageContext *new_msg_ctx;
1601 struct GNUNET_DHT_GetResultMessage *get_result;
1603 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1604 "`%s:%s': Received `%s' response from datacache\n", my_short_id, "DHT", "GET");
1606 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
1607 memcpy(new_msg_ctx, msg_ctx, sizeof(struct DHT_MessageContext));
1609 GNUNET_malloc (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
1610 get_result->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_GET_RESULT);
1611 get_result->header.size =
1612 htons (sizeof (struct GNUNET_DHT_GetResultMessage) + size);
1613 get_result->expiration = GNUNET_TIME_absolute_hton(exp);
1614 get_result->type = htons (type);
1615 memcpy (&get_result[1], data, size);
1616 new_msg_ctx->peer = &my_identity;
1617 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1618 new_msg_ctx->hop_count = 0;
1619 increment_stats(STAT_GET_RESPONSE_START);
1620 route_result_message(cls, &get_result->header, new_msg_ctx);
1621 GNUNET_free(new_msg_ctx);
1622 //send_reply_to_client (datacache_get_ctx->client, &get_result->header,
1623 // datacache_get_ctx->unique_id);
1624 GNUNET_free (get_result);
1630 * Server handler for all dht get requests, look for data,
1631 * if found, send response either to clients or other peers.
1633 * @param cls closure for service
1634 * @param msg the actual get message
1635 * @param message_context struct containing pertinent information about the get request
1637 * @return number of items found for GET request
1640 handle_dht_get (void *cls,
1641 const struct GNUNET_MessageHeader *msg,
1642 struct DHT_MessageContext *message_context)
1644 const struct GNUNET_DHT_GetMessage *get_msg;
1646 unsigned int results;
1648 get_msg = (const struct GNUNET_DHT_GetMessage *) msg;
1649 if (ntohs (get_msg->header.size) != sizeof (struct GNUNET_DHT_GetMessage))
1655 get_type = ntohs (get_msg->type);
1657 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1658 "`%s:%s': Received `%s' request, message type %u, key %s, uid %llu\n", my_short_id,
1659 "DHT", "GET", get_type, GNUNET_h2s (message_context->key),
1660 message_context->unique_id);
1662 increment_stats(STAT_GETS);
1664 if (get_type == DHT_MALICIOUS_MESSAGE_TYPE)
1667 if (datacache != NULL)
1669 GNUNET_DATACACHE_get (datacache, message_context->key, get_type,
1670 &datacache_get_iterator, message_context);
1675 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1676 "`%s:%s': Found %d results for `%s' request uid %llu\n", my_short_id, "DHT",
1677 results, "GET", message_context->unique_id);
1679 #if DEBUG_DHT_ROUTING
1680 if ((debug_routes) && (dhtlog_handle != NULL))
1682 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
1683 message_context->hop_count, GNUNET_YES, &my_identity,
1684 message_context->key);
1687 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1689 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
1690 message_context->hop_count, GNUNET_YES,
1691 &my_identity, message_context->key, message_context->peer,
1697 if (message_context->hop_count == 0) /* Locally initiated request */
1699 #if DEBUG_DHT_ROUTING
1700 if ((debug_routes) && (dhtlog_handle != NULL))
1702 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_GET,
1703 message_context->hop_count, GNUNET_NO, &my_identity,
1704 message_context->key);
1714 * Server handler for initiating local dht find peer requests
1716 * @param cls closure for service
1717 * @param find_msg the actual find peer message
1718 * @param message_context struct containing pertinent information about the request
1722 handle_dht_find_peer (void *cls,
1723 const struct GNUNET_MessageHeader *find_msg,
1724 struct DHT_MessageContext *message_context)
1726 struct GNUNET_MessageHeader *find_peer_result;
1727 struct DHT_MessageContext *new_msg_ctx;
1732 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1733 "`%s:%s': Received `%s' request from client, key %s (msg size %d, we expected %d)\n",
1734 my_short_id, "DHT", "FIND PEER", GNUNET_h2s (message_context->key),
1735 ntohs (find_msg->size),
1736 sizeof (struct GNUNET_MessageHeader));
1738 if (my_hello == NULL)
1741 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1742 "`%s': Our HELLO is null, can't return.\n",
1747 /* Simplistic find_peer functionality, always return our hello */
1748 hello_size = ntohs(my_hello->size);
1749 tsize = hello_size + sizeof (struct GNUNET_MessageHeader);
1751 if (tsize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1753 GNUNET_break_op (0);
1757 find_peer_result = GNUNET_malloc (tsize);
1758 find_peer_result->type = htons (GNUNET_MESSAGE_TYPE_DHT_FIND_PEER_RESULT);
1759 find_peer_result->size = htons (tsize);
1760 memcpy (&find_peer_result[1], my_hello, hello_size);
1762 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1763 "`%s': Sending hello size %d to requesting peer.\n",
1766 new_msg_ctx = GNUNET_malloc(sizeof(struct DHT_MessageContext));
1767 memcpy(new_msg_ctx, message_context, sizeof(struct DHT_MessageContext));
1768 new_msg_ctx->peer = &my_identity;
1769 new_msg_ctx->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
1770 new_msg_ctx->hop_count = 0;
1771 increment_stats(STAT_FIND_PEER_ANSWER);
1772 route_result_message(cls, find_peer_result, new_msg_ctx);
1773 GNUNET_free(new_msg_ctx);
1774 #if DEBUG_DHT_ROUTING
1775 if ((debug_routes) && (dhtlog_handle != NULL))
1777 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
1778 message_context->hop_count, GNUNET_YES, &my_identity,
1779 message_context->key);
1782 //send_reply_to_client(message_context->client, find_peer_result, message_context->unique_id);
1783 GNUNET_free(find_peer_result);
1788 * Server handler for initiating local dht put requests
1790 * @param cls closure for service
1791 * @param msg the actual put message
1792 * @param message_context struct containing pertinent information about the request
1795 handle_dht_put (void *cls,
1796 const struct GNUNET_MessageHeader *msg,
1797 struct DHT_MessageContext *message_context)
1799 struct GNUNET_DHT_PutMessage *put_msg;
1803 GNUNET_assert (ntohs (msg->size) >=
1804 sizeof (struct GNUNET_DHT_PutMessage));
1807 put_msg = (struct GNUNET_DHT_PutMessage *)msg;
1808 put_type = ntohs (put_msg->type);
1810 if (put_type == DHT_MALICIOUS_MESSAGE_TYPE)
1813 data_size = ntohs (put_msg->header.size) - sizeof (struct GNUNET_DHT_PutMessage);
1815 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1816 "`%s:%s': Received `%s' request (inserting data!), message type %d, key %s, uid %llu\n",
1817 my_short_id, "DHT", "PUT", put_type, GNUNET_h2s (message_context->key), message_context->unique_id);
1819 #if DEBUG_DHT_ROUTING
1820 if (message_context->hop_count == 0) /* Locally initiated request */
1822 if ((debug_routes) && (dhtlog_handle != NULL))
1824 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
1825 message_context->hop_count, GNUNET_NO, &my_identity,
1826 message_context->key);
1831 if (message_context->closest != GNUNET_YES)
1834 #if DEBUG_DHT_ROUTING
1835 if ((debug_routes_extended) && (dhtlog_handle != NULL))
1837 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
1838 message_context->hop_count, GNUNET_YES,
1839 &my_identity, message_context->key, message_context->peer,
1843 if ((debug_routes) && (dhtlog_handle != NULL))
1845 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_PUT,
1846 message_context->hop_count, GNUNET_YES, &my_identity,
1847 message_context->key);
1851 increment_stats(STAT_PUTS_INSERTED);
1852 if (datacache != NULL)
1853 GNUNET_DATACACHE_put (datacache, message_context->key, data_size,
1854 (char *) &put_msg[1], put_type,
1855 GNUNET_TIME_absolute_ntoh(put_msg->expiration));
1857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1858 "`%s:%s': %s request received, but have no datacache!\n",
1859 my_short_id, "DHT", "PUT");
1863 * Estimate the diameter of the network based
1864 * on how many buckets are currently in use.
1865 * Concept here is that the diameter of the network
1866 * is roughly the distance a message must travel in
1867 * order to reach its intended destination. Since
1868 * at each hop we expect to get one bit closer, and
1869 * we have one bit per bucket, the number of buckets
1870 * in use should be the largest number of hops for
1871 * a sucessful message. (of course, this assumes we
1872 * know all peers in the network!)
1874 * @return ballpark diameter figure
1876 static unsigned int estimate_diameter()
1878 return MAX_BUCKETS - lowest_bucket;
1882 * To how many peers should we (on average)
1883 * forward the request to obtain the desired
1884 * target_replication count (on average).
1886 * Always 0, 1 or 2 (don't send, send once, split)
1889 get_forward_count (unsigned int hop_count, size_t target_replication)
1891 double target_count;
1892 unsigned int target_value;
1893 unsigned int diameter;
1896 * If we are behaving in strict kademlia mode, send multiple initial requests,
1897 * but then only send to 1 or 0 peers.
1899 if (strict_kademlia == GNUNET_YES)
1902 return DHT_KADEMLIA_REPLICATION;
1903 else if (hop_count < MAX_HOPS)
1909 /* FIXME: the smaller we think the network is the more lenient we should be for
1910 * routing right? The estimation below only works if we think we have reasonably
1911 * full routing tables, which for our RR topologies may not be the case!
1913 diameter = estimate_diameter ();
1914 if ((hop_count > (diameter + 1) * 2) && (MINIMUM_PEER_THRESHOLD < estimate_diameter() * bucket_size))
1917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1918 "`%s:%s': Hop count too high (est %d, lowest %d), NOT Forwarding request\n", my_short_id,
1919 "DHT", estimate_diameter(), lowest_bucket);
1923 else if (hop_count > MAX_HOPS)
1926 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1927 "`%s:%s': Hop count too high (greater than max)\n", my_short_id,
1932 target_count = /* target_count is ALWAYS < 1 unless replication is < 1 */
1933 target_replication / (target_replication * (hop_count + 1) + diameter);
1937 while (target_value < target_count)
1938 target_value++; /* target_value is ALWAYS 1 after this "loop" */
1942 if ((target_count + 1 - target_value) >
1943 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1944 RAND_MAX) / RAND_MAX)
1946 return target_value;
1950 * Find the closest peer in our routing table to the
1953 * @return The closest peer in our routing table to the
1954 * key, or NULL on error.
1956 static struct PeerInfo *
1957 find_closest_peer (const GNUNET_HashCode *hc)
1959 struct PeerInfo *pos;
1960 struct PeerInfo *current_closest;
1961 unsigned int lowest_distance;
1962 unsigned int temp_distance;
1966 lowest_distance = -1;
1968 if (k_buckets[lowest_bucket].peers_size == 0)
1971 current_closest = NULL;
1972 for (bucket = lowest_bucket; bucket < MAX_BUCKETS; bucket++)
1974 pos = k_buckets[bucket].head;
1976 while ((pos != NULL) && (count < bucket_size))
1978 temp_distance = distance(&pos->id.hashPubKey, hc);
1979 if (temp_distance <= lowest_distance)
1981 lowest_distance = temp_distance;
1982 current_closest = pos;
1988 GNUNET_assert(current_closest != NULL);
1989 return current_closest;
1993 * Check whether my identity is closer than any known peers.
1995 * @param target hash code to check closeness to
1997 * Return GNUNET_YES if node location is closest, GNUNET_NO
2001 am_closest_peer (const GNUNET_HashCode * target)
2007 struct PeerInfo *pos;
2008 unsigned int my_distance;
2010 bucket_num = find_current_bucket(target);
2011 if (bucket_num == GNUNET_SYSERR) /* Same key! */
2014 bits = matching_bits(&my_identity.hashPubKey, target);
2015 my_distance = distance(&my_identity.hashPubKey, target);
2017 pos = k_buckets[bucket_num].head;
2019 while ((pos != NULL) && (count < bucket_size))
2021 other_bits = matching_bits(&pos->id.hashPubKey, target);
2022 if (other_bits > bits)
2024 else if (other_bits == bits) /* We match the same number of bits, do distance comparison */
2027 /* FIXME: why not just return GNUNET_YES here? We are certainly close. */
2028 /*if (distance(&pos->id.hashPubKey, target) < my_distance)
2035 GNUNET_GE_LOG (coreAPI->ectx,
2036 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2037 GNUNET_GE_BULK, "closest peer\n");
2038 printPeerBits (&closest);
2039 GNUNET_GE_LOG (coreAPI->ectx,
2040 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2041 GNUNET_GE_BULK, "me\n");
2042 printPeerBits (coreAPI->my_identity);
2043 GNUNET_GE_LOG (coreAPI->ectx,
2044 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2045 GNUNET_GE_BULK, "key\n");
2046 printKeyBits (target);
2047 GNUNET_GE_LOG (coreAPI->ectx,
2048 GNUNET_GE_WARNING | GNUNET_GE_ADMIN | GNUNET_GE_USER |
2050 "closest peer inverse distance is %u, mine is %u\n",
2051 inverse_distance (target, &closest.hashPubKey),
2052 inverse_distance (target,
2053 &coreAPI->my_identity->hashPubKey));
2056 /* No peers closer, we are the closest! */
2063 * Select a peer from the routing table that would be a good routing
2064 * destination for sending a message for "target". The resulting peer
2065 * must not be in the set of blocked peers.<p>
2067 * Note that we should not ALWAYS select the closest peer to the
2068 * target, peers further away from the target should be chosen with
2069 * exponentially declining probability.
2071 * @param target the key we are selecting a peer to route to
2072 * @param bloom a bloomfilter containing entries this request has seen already
2074 * @return Peer to route to, or NULL on error
2076 static struct PeerInfo *
2077 select_peer (const GNUNET_HashCode * target,
2078 struct GNUNET_CONTAINER_BloomFilter *bloom)
2080 unsigned int distance;
2083 struct PeerInfo *pos;
2084 struct PeerInfo *chosen;
2085 unsigned long long largest_distance;
2086 unsigned long long total_distance;
2087 unsigned long long selected;
2089 if (strict_kademlia == GNUNET_YES)
2091 largest_distance = 0;
2093 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2095 pos = k_buckets[bc].head;
2096 while ((pos != NULL) && (count < bucket_size))
2098 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2100 distance = inverse_distance (target, &pos->id.hashPubKey);
2101 if (distance > largest_distance)
2104 largest_distance = distance;
2111 if ((largest_distance > 0) && (chosen != NULL))
2113 GNUNET_CONTAINER_bloomfilter_add(bloom, &chosen->id.hashPubKey);
2125 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2127 pos = k_buckets[bc].head;
2129 while ((pos != NULL) && (count < bucket_size))
2131 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2132 total_distance += (unsigned long long)inverse_distance (target, &pos->id.hashPubKey);
2134 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2135 "`%s:%s': Total distance is %llu, distance from %s to %s is %u\n",
2136 my_short_id, "DHT", total_distance, GNUNET_i2s(&pos->id), GNUNET_h2s(target) , inverse_distance(target, &pos->id.hashPubKey));
2142 if (total_distance == 0)
2147 selected = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, total_distance);
2148 for (bc = lowest_bucket; bc < MAX_BUCKETS; bc++)
2150 pos = k_buckets[bc].head;
2152 while ((pos != NULL) && (count < bucket_size))
2154 if (GNUNET_NO == GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
2156 distance = inverse_distance (target, &pos->id.hashPubKey);
2157 if (distance > selected)
2159 selected -= distance;
2164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2165 "`%s:%s': peer %s matches bloomfilter.\n",
2166 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2174 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2175 "`%s:%s': peer %s matches bloomfilter.\n",
2176 my_short_id, "DHT", GNUNET_i2s(&pos->id));
2184 * Task used to remove forwarding entries, either
2185 * after timeout, when full, or on shutdown.
2187 * @param cls the entry to remove
2188 * @param tc context, reason, etc.
2191 remove_forward_entry (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2193 struct DHTRouteSource *source_info = cls;
2194 struct DHTQueryRecord *record;
2195 source_info = GNUNET_CONTAINER_heap_remove_node(forward_list.minHeap, source_info->hnode);
2196 record = source_info->record;
2197 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2199 if (record->head == NULL) /* No more entries in DLL */
2201 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2202 GNUNET_free(record);
2204 GNUNET_free(source_info);
2208 * Remember this routing request so that if a reply is
2209 * received we can either forward it to the correct peer
2210 * or return the result locally.
2212 * @param cls DHT service closure
2213 * @param msg_ctx Context of the route request
2215 * @return GNUNET_YES if this response was cached, GNUNET_NO if not
2217 static int cache_response(void *cls, struct DHT_MessageContext *msg_ctx)
2219 struct DHTQueryRecord *record;
2220 struct DHTRouteSource *source_info;
2221 struct DHTRouteSource *pos;
2222 struct GNUNET_TIME_Absolute now;
2223 unsigned int current_size;
2225 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2226 while (current_size >= MAX_OUTSTANDING_FORWARDS)
2228 source_info = GNUNET_CONTAINER_heap_remove_root(forward_list.minHeap);
2229 record = source_info->record;
2230 GNUNET_CONTAINER_DLL_remove(record->head, record->tail, source_info);
2231 if (record->head == NULL) /* No more entries in DLL */
2233 GNUNET_assert(GNUNET_YES == GNUNET_CONTAINER_multihashmap_remove(forward_list.hashmap, &record->key, record));
2234 GNUNET_free(record);
2236 GNUNET_SCHEDULER_cancel(sched, source_info->delete_task);
2237 GNUNET_free(source_info);
2238 current_size = GNUNET_CONTAINER_multihashmap_size(forward_list.hashmap);
2240 now = GNUNET_TIME_absolute_get();
2241 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, msg_ctx->key);
2242 if (record != NULL) /* Already know this request! */
2247 if (0 == memcmp(msg_ctx->peer, &pos->source, sizeof(struct GNUNET_PeerIdentity)))
2248 break; /* Already have this peer in reply list! */
2251 if ((pos != NULL) && (pos->client == msg_ctx->client)) /* Seen this already */
2253 GNUNET_CONTAINER_heap_update_cost(forward_list.minHeap, pos->hnode, now.value);
2259 record = GNUNET_malloc(sizeof (struct DHTQueryRecord));
2260 GNUNET_assert(GNUNET_OK == GNUNET_CONTAINER_multihashmap_put(forward_list.hashmap, msg_ctx->key, record, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
2261 memcpy(&record->key, msg_ctx->key, sizeof(GNUNET_HashCode));
2264 source_info = GNUNET_malloc(sizeof(struct DHTRouteSource));
2265 source_info->record = record;
2266 source_info->delete_task = GNUNET_SCHEDULER_add_delayed(sched, DHT_FORWARD_TIMEOUT, &remove_forward_entry, source_info);
2267 memcpy(&source_info->source, msg_ctx->peer, sizeof(struct GNUNET_PeerIdentity));
2268 GNUNET_CONTAINER_DLL_insert_after(record->head, record->tail, record->tail, source_info);
2269 if (msg_ctx->client != NULL) /* For local request, set timeout so high it effectively never gets pushed out */
2271 source_info->client = msg_ctx->client;
2272 now = GNUNET_TIME_absolute_get_forever();
2274 source_info->hnode = GNUNET_CONTAINER_heap_insert(forward_list.minHeap, source_info, now.value);
2276 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2277 "`%s:%s': Created new forward source info for %s uid %llu\n", my_short_id,
2278 "DHT", GNUNET_h2s (msg_ctx->key), msg_ctx->unique_id);
2285 * Main function that handles whether or not to route a message to other
2288 * @param msg the message to be routed
2290 * @return the number of peers the message was routed to,
2291 * GNUNET_SYSERR on failure
2293 static int route_message(void *cls,
2294 const struct GNUNET_MessageHeader *msg,
2295 struct DHT_MessageContext *message_context)
2298 struct PeerInfo *selected;
2299 struct PeerInfo *nearest;
2300 unsigned int forward_count;
2304 #if DEBUG_DHT_ROUTING
2308 if (malicious_dropper == GNUNET_YES)
2310 #if DEBUG_DHT_ROUTING
2311 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2313 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2314 message_context->hop_count, GNUNET_SYSERR,
2315 &my_identity, message_context->key, message_context->peer,
2319 if (message_context->bloom != NULL)
2320 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2324 increment_stats(STAT_ROUTES);
2325 message_context->closest = am_closest_peer(message_context->key);
2326 forward_count = get_forward_count(message_context->hop_count, message_context->replication);
2327 nearest = find_closest_peer(message_context->key);
2329 if (message_context->bloom == NULL)
2330 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2331 GNUNET_CONTAINER_bloomfilter_add (message_context->bloom, &my_identity.hashPubKey);
2333 if ((stop_on_closest == GNUNET_YES) && (message_context->closest == GNUNET_YES) && (ntohs(msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT))
2336 #if DEBUG_DHT_ROUTING
2337 if (forward_count == 0)
2338 ret = GNUNET_SYSERR;
2342 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2344 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2345 message_context->hop_count, ret,
2346 &my_identity, message_context->key, message_context->peer,
2351 switch (ntohs(msg->type))
2353 case GNUNET_MESSAGE_TYPE_DHT_GET: /* Add to hashmap of requests seen, search for data (always) */
2354 cache_response (cls, message_context);
2355 if ((handle_dht_get (cls, msg, message_context) > 0) && (stop_on_found == GNUNET_YES))
2358 case GNUNET_MESSAGE_TYPE_DHT_PUT: /* Check if closest, if so insert data. FIXME: thresholding to reduce complexity?*/
2359 increment_stats(STAT_PUTS);
2360 handle_dht_put (cls, msg, message_context);
2362 case GNUNET_MESSAGE_TYPE_DHT_FIND_PEER: /* Check if closest and not started by us, check options, add to requests seen */
2363 increment_stats(STAT_FIND_PEER);
2364 if (((message_context->hop_count > 0) && (0 != memcmp(message_context->peer, &my_identity, sizeof(struct GNUNET_PeerIdentity)))) || (message_context->client != NULL))
2366 cache_response (cls, message_context);
2367 if ((message_context->closest == GNUNET_YES) || (message_context->msg_options == GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE))
2368 handle_dht_find_peer (cls, msg, message_context);
2370 #if DEBUG_DHT_ROUTING
2371 if (message_context->hop_count == 0) /* Locally initiated request */
2373 if ((debug_routes) && (dhtlog_handle != NULL))
2375 dhtlog_handle->insert_dhtkey(NULL, message_context->key);
2376 dhtlog_handle->insert_query (NULL, message_context->unique_id, DHTLOG_FIND_PEER,
2377 message_context->hop_count, GNUNET_NO, &my_identity,
2378 message_context->key);
2384 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2385 "`%s': Message type (%d) not handled\n", "DHT", ntohs(msg->type));
2388 for (i = 0; i < forward_count; i++)
2390 selected = select_peer(message_context->key, message_context->bloom);
2392 if (selected != NULL)
2394 GNUNET_CONTAINER_bloomfilter_add(message_context->bloom, &selected->id.hashPubKey);
2395 #if DEBUG_DHT_ROUTING > 1
2396 nearest_buf = GNUNET_strdup(GNUNET_i2s(&nearest->id));
2397 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2398 "`%s:%s': Forwarding request key %s uid %llu to peer %s (closest %s, bits %d, distance %u)\n", my_short_id,
2399 "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));
2400 GNUNET_free(nearest_buf);
2402 if ((debug_routes_extended) && (dhtlog_handle != NULL))
2404 dhtlog_handle->insert_route (NULL, message_context->unique_id, DHTLOG_ROUTE,
2405 message_context->hop_count, GNUNET_NO,
2406 &my_identity, message_context->key, message_context->peer,
2409 forward_message(cls, msg, selected, message_context);
2414 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2415 "`%s:%s': No peers selected for forwarding.\n", my_short_id,
2420 #if DEBUG_DHT_ROUTING > 1
2421 if (forward_count == 0)
2423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2424 "`%s:%s': NOT Forwarding request key %s uid %llu to any peers\n", my_short_id,
2425 "DHT", GNUNET_h2s (message_context->key), message_context->unique_id);
2429 if (message_context->bloom != NULL)
2430 GNUNET_CONTAINER_bloomfilter_free(message_context->bloom);
2432 return forward_count;
2436 * Find a client if it exists, add it otherwise.
2438 * @param client the server handle to the client
2440 * @return the client if found, a new client otherwise
2442 static struct ClientList *
2443 find_active_client (struct GNUNET_SERVER_Client *client)
2445 struct ClientList *pos = client_list;
2446 struct ClientList *ret;
2450 if (pos->client_handle == client)
2455 ret = GNUNET_malloc (sizeof (struct ClientList));
2456 ret->client_handle = client;
2457 ret->next = client_list;
2463 * Task to send a malicious put message across the network.
2465 * @param cls closure for this task
2466 * @param tc the context under which the task is running
2469 malicious_put_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2471 static struct GNUNET_DHT_PutMessage put_message;
2472 static struct DHT_MessageContext message_context;
2473 static GNUNET_HashCode key;
2474 unsigned int mcsize;
2475 uint32_t random_key;
2476 put_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
2477 put_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_PUT);
2478 put_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2479 put_message.expiration = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get_forever());
2480 mcsize = sizeof(struct DHT_MessageContext) + sizeof(GNUNET_HashCode);
2481 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2482 message_context.client = NULL;
2483 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2484 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2485 message_context.key = &key;
2486 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2487 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2488 message_context.msg_options = ntohl (0);
2489 message_context.network_size = estimate_diameter();
2490 message_context.peer = &my_identity;
2491 increment_stats(STAT_PUT_START);
2492 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious PUT message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2493 route_message(NULL, &put_message.header, &message_context);
2494 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_put_frequency), &malicious_put_task, NULL);
2499 * Task to send a malicious put message across the network.
2501 * @param cls closure for this task
2502 * @param tc the context under which the task is running
2505 malicious_get_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2507 static struct GNUNET_DHT_GetMessage get_message;
2508 static struct DHT_MessageContext message_context;
2509 static GNUNET_HashCode key;
2510 unsigned int mcsize;
2511 uint32_t random_key;
2512 get_message.header.size = htons(sizeof(struct GNUNET_DHT_GetMessage));
2513 get_message.header.type = htons(GNUNET_MESSAGE_TYPE_DHT_GET);
2514 get_message.type = htons(DHT_MALICIOUS_MESSAGE_TYPE);
2515 mcsize = sizeof(struct DHT_MessageContext) + sizeof(GNUNET_HashCode);
2516 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2517 message_context.client = NULL;
2518 random_key = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, (uint32_t)-1);
2519 GNUNET_CRYPTO_hash(&random_key, sizeof(uint32_t), &key);
2520 message_context.key = &key;
2521 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_WEAK, (uint64_t)-1));
2522 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2523 message_context.msg_options = ntohl (0);
2524 message_context.network_size = estimate_diameter();
2525 message_context.peer = &my_identity;
2526 increment_stats(STAT_GET_START);
2527 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Sending malicious GET message with hash %s", my_short_id, "DHT", GNUNET_h2s(&key));
2528 route_message(NULL, &get_message.header, &message_context);
2529 GNUNET_SCHEDULER_add_delayed(sched, GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, malicious_get_frequency), &malicious_get_task, NULL);
2533 * Task to send a find peer message for our own peer identifier
2534 * so that we can find the closest peers in the network to ourselves
2535 * and attempt to connect to them.
2537 * @param cls closure for this task
2538 * @param tc the context under which the task is running
2541 send_find_peer_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2543 struct GNUNET_MessageHeader *find_peer_msg;
2544 struct DHT_MessageContext message_context;
2546 struct GNUNET_TIME_Relative next_send_time;
2548 if (tc->reason == GNUNET_SCHEDULER_REASON_SHUTDOWN)
2551 increment_stats(STAT_FIND_PEER_START);
2553 find_peer_msg = GNUNET_malloc(sizeof(struct GNUNET_MessageHeader));
2554 find_peer_msg->size = htons(sizeof(struct GNUNET_MessageHeader));
2555 find_peer_msg->type = htons(GNUNET_MESSAGE_TYPE_DHT_FIND_PEER);
2556 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2557 message_context.key = &my_identity.hashPubKey;
2558 message_context.unique_id = GNUNET_ntohll (GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, (uint64_t)-1));
2559 message_context.replication = ntohl (DHT_DEFAULT_FIND_PEER_REPLICATION);
2560 message_context.msg_options = ntohl (DHT_DEFAULT_FIND_PEER_OPTIONS);
2561 message_context.network_size = estimate_diameter();
2562 message_context.peer = &my_identity;
2564 ret = route_message(NULL, find_peer_msg, &message_context);
2565 GNUNET_free(find_peer_msg);
2566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2567 "`%s:%s': Sent `%s' request to %d peers\n", my_short_id, "DHT",
2569 next_send_time.value = DHT_MINIMUM_FIND_PEER_INTERVAL.value +
2570 GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
2571 DHT_MAXIMUM_FIND_PEER_INTERVAL.value - DHT_MINIMUM_FIND_PEER_INTERVAL.value);
2572 GNUNET_SCHEDULER_add_delayed (sched,
2574 &send_find_peer_message, NULL);
2578 * Handler for any generic DHT messages, calls the appropriate handler
2579 * depending on message type, sends confirmation if responses aren't otherwise
2582 * @param cls closure for the service
2583 * @param client the client we received this message from
2584 * @param message the actual message received
2587 handle_dht_local_route_request (void *cls, struct GNUNET_SERVER_Client *client,
2588 const struct GNUNET_MessageHeader *message)
2590 const struct GNUNET_DHT_RouteMessage *dht_msg = (const struct GNUNET_DHT_RouteMessage *) message;
2591 const struct GNUNET_MessageHeader *enc_msg;
2592 struct DHT_MessageContext message_context;
2595 enc_msg = (const struct GNUNET_MessageHeader *) &dht_msg[1];
2596 enc_type = ntohs (enc_msg->type);
2599 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2600 "`%s:%s': Received `%s' request from client, message type %d, key %s, uid %llu\n",
2601 my_short_id, "DHT", "GENERIC", enc_type, GNUNET_h2s (&dht_msg->key),
2602 GNUNET_ntohll (dht_msg->unique_id));
2604 #if DEBUG_DHT_ROUTING
2605 if (dhtlog_handle != NULL)
2606 dhtlog_handle->insert_dhtkey (NULL, &dht_msg->key);
2608 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2609 message_context.client = find_active_client (client);
2610 message_context.key = &dht_msg->key;
2611 message_context.unique_id = GNUNET_ntohll (dht_msg->unique_id);
2612 message_context.replication = ntohl (dht_msg->desired_replication_level);
2613 message_context.msg_options = ntohl (dht_msg->options);
2614 message_context.network_size = estimate_diameter();
2615 message_context.peer = &my_identity;
2617 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_GET)
2618 increment_stats(STAT_GET_START);
2619 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_PUT)
2620 increment_stats(STAT_PUT_START);
2621 else if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_FIND_PEER)
2622 increment_stats(STAT_FIND_PEER_START);
2624 route_message(cls, enc_msg, &message_context);
2626 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2631 * Handler for any locally received DHT control messages,
2632 * sets malicious flags mostly for now.
2634 * @param cls closure for the service
2635 * @param client the client we received this message from
2636 * @param message the actual message received
2640 handle_dht_control_message (void *cls, struct GNUNET_SERVER_Client *client,
2641 const struct GNUNET_MessageHeader *message)
2643 const struct GNUNET_DHT_ControlMessage *dht_control_msg =
2644 (const struct GNUNET_DHT_ControlMessage *) message;
2646 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2647 "`%s:%s': Received `%s' request from client, command %d\n", my_short_id, "DHT",
2648 "CONTROL", ntohs(dht_control_msg->command));
2651 switch (ntohs(dht_control_msg->command))
2653 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_GET:
2654 if (ntohs(dht_control_msg->variable) > 0)
2655 malicious_get_frequency = ntohs(dht_control_msg->variable);
2656 if (malicious_getter != GNUNET_YES)
2657 GNUNET_SCHEDULER_add_now(sched, &malicious_get_task, NULL);
2658 malicious_getter = GNUNET_YES;
2659 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious GET behavior, frequency %d\n", my_short_id, "DHT", malicious_get_frequency);
2661 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_PUT:
2662 if (ntohs(dht_control_msg->variable) > 0)
2663 malicious_put_frequency = ntohs(dht_control_msg->variable);
2664 if (malicious_putter != GNUNET_YES)
2665 GNUNET_SCHEDULER_add_now(sched, &malicious_put_task, NULL);
2666 malicious_putter = GNUNET_YES;
2667 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious PUT behavior, frequency %d\n", my_short_id, "DHT", malicious_put_frequency);
2669 case GNUNET_MESSAGE_TYPE_DHT_MALICIOUS_DROP:
2670 malicious_dropper = GNUNET_YES;
2671 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Initiating malicious DROP behavior\n", my_short_id, "DHT");
2674 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s Unknown control command type `%d'!\n", ntohs(dht_control_msg->command));
2677 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2681 * Handler for any generic DHT stop messages, calls the appropriate handler
2682 * depending on message type (if processed locally)
2684 * @param cls closure for the service
2685 * @param client the client we received this message from
2686 * @param message the actual message received
2690 handle_dht_local_route_stop(void *cls, struct GNUNET_SERVER_Client *client,
2691 const struct GNUNET_MessageHeader *message)
2694 const struct GNUNET_DHT_StopMessage *dht_stop_msg =
2695 (const struct GNUNET_DHT_StopMessage *) message;
2696 struct DHTQueryRecord *record;
2697 struct DHTRouteSource *pos;
2700 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2701 "`%s:%s': Received `%s' request from client, uid %llu\n", my_short_id, "DHT",
2702 "GENERIC STOP", GNUNET_ntohll (dht_stop_msg->unique_id));
2705 uid = GNUNET_ntohll(dht_stop_msg->unique_id);
2707 record = GNUNET_CONTAINER_multihashmap_get(forward_list.hashmap, &dht_stop_msg->key);
2714 if ((pos->client != NULL) && (pos->client->client_handle == client))
2716 GNUNET_SCHEDULER_cancel(sched, pos->delete_task);
2717 GNUNET_SCHEDULER_add_now(sched, &remove_forward_entry, pos);
2723 GNUNET_SERVER_receive_done (client, GNUNET_OK);
2728 * Core handler for p2p route requests.
2731 handle_dht_p2p_route_request (void *cls,
2732 const struct GNUNET_PeerIdentity *peer,
2733 const struct GNUNET_MessageHeader *message,
2734 struct GNUNET_TIME_Relative latency, uint32_t distance)
2737 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2738 "`%s:%s': Received P2P request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
2740 struct GNUNET_DHT_P2PRouteMessage *incoming = (struct GNUNET_DHT_P2PRouteMessage *)message;
2741 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
2742 struct DHT_MessageContext *message_context;
2744 if (ntohs(enc_msg->type) == GNUNET_MESSAGE_TYPE_DHT_P2P_PING) /* Throw these away. FIXME: Don't throw these away? (reply)*/
2747 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "%s:%s Received P2P Ping message.\n", my_short_id, "DHT");
2752 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2757 //memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2758 message_context = GNUNET_malloc(sizeof (struct DHT_MessageContext));
2759 message_context->bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2760 GNUNET_assert(message_context->bloom != NULL);
2761 message_context->hop_count = ntohl(incoming->hop_count);
2762 message_context->key = &incoming->key;
2763 message_context->replication = ntohl(incoming->desired_replication_level);
2764 message_context->unique_id = GNUNET_ntohll(incoming->unique_id);
2765 message_context->msg_options = ntohl(incoming->options);
2766 message_context->network_size = ntohl(incoming->network_size);
2767 message_context->peer = peer;
2768 route_message(cls, enc_msg, message_context);
2769 GNUNET_free(message_context);
2775 * Core handler for p2p route results.
2778 handle_dht_p2p_route_result (void *cls,
2779 const struct GNUNET_PeerIdentity *peer,
2780 const struct GNUNET_MessageHeader *message,
2781 struct GNUNET_TIME_Relative latency, uint32_t distance)
2784 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2785 "`%s:%s': Received request from peer %s\n", my_short_id, "DHT", GNUNET_i2s(peer));
2787 struct GNUNET_DHT_P2PRouteResultMessage *incoming = (struct GNUNET_DHT_P2PRouteResultMessage *)message;
2788 struct GNUNET_MessageHeader *enc_msg = (struct GNUNET_MessageHeader *)&incoming[1];
2789 struct DHT_MessageContext message_context;
2791 if (ntohs(enc_msg->size) > GNUNET_SERVER_MAX_MESSAGE_SIZE)
2797 memset(&message_context, 0, sizeof(struct DHT_MessageContext));
2798 message_context.bloom = GNUNET_CONTAINER_bloomfilter_init(incoming->bloomfilter, DHT_BLOOM_SIZE, DHT_BLOOM_K);
2799 GNUNET_assert(message_context.bloom != NULL);
2800 message_context.key = &incoming->key;
2801 message_context.unique_id = GNUNET_ntohll(incoming->unique_id);
2802 message_context.msg_options = ntohl(incoming->options);
2803 message_context.hop_count = ntohl(incoming->hop_count);
2804 message_context.peer = peer;
2805 route_result_message(cls, enc_msg, &message_context);
2811 * Receive the HELLO from transport service,
2812 * free current and replace if necessary.
2815 * @param message HELLO message of peer
2818 process_hello (void *cls, const struct GNUNET_MessageHeader *message)
2821 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2822 "Received our `%s' from transport service\n",
2826 GNUNET_assert (message != NULL);
2827 GNUNET_free_non_null(my_hello);
2828 my_hello = GNUNET_malloc(ntohs(message->size));
2829 memcpy(my_hello, message, ntohs(message->size));
2834 * Task run during shutdown.
2840 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2843 struct PeerInfo *pos;
2844 if (transport_handle != NULL)
2846 GNUNET_free_non_null(my_hello);
2847 GNUNET_TRANSPORT_get_hello_cancel(transport_handle, &process_hello, NULL);
2848 GNUNET_TRANSPORT_disconnect(transport_handle);
2851 for (bucket_count = lowest_bucket; bucket_count < MAX_BUCKETS; bucket_count++)
2853 while (k_buckets[bucket_count].head != NULL)
2855 pos = k_buckets[bucket_count].head;
2857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2858 "%s:%s Removing peer %s from bucket %d!\n", my_short_id, "DHT", GNUNET_i2s(&pos->id), bucket_count);
2860 delete_peer(pos, bucket_count);
2863 if (coreAPI != NULL)
2866 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2867 "%s:%s Disconnecting core!\n", my_short_id, "DHT");
2869 GNUNET_CORE_disconnect (coreAPI);
2871 if (datacache != NULL)
2874 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2875 "%s:%s Destroying datacache!\n", my_short_id, "DHT");
2877 GNUNET_DATACACHE_destroy (datacache);
2882 GNUNET_STATISTICS_destroy (stats, GNUNET_YES);
2885 if (dhtlog_handle != NULL)
2886 GNUNET_DHTLOG_disconnect(dhtlog_handle);
2888 GNUNET_free_non_null(my_short_id);
2893 * To be called on core init/fail.
2895 * @param cls service closure
2896 * @param server handle to the server for this service
2897 * @param identity the public identity of this peer
2898 * @param publicKey the public key of this peer
2901 core_init (void *cls,
2902 struct GNUNET_CORE_Handle *server,
2903 const struct GNUNET_PeerIdentity *identity,
2904 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
2910 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2911 "%s: Connection to core FAILED!\n", "dht",
2912 GNUNET_i2s (identity));
2914 GNUNET_SCHEDULER_cancel (sched, cleanup_task);
2915 GNUNET_SCHEDULER_add_now (sched, &shutdown_task, NULL);
2919 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2920 "%s: Core connection initialized, I am peer: %s\n", "dht",
2921 GNUNET_i2s (identity));
2924 /* Copy our identity so we can use it */
2925 memcpy (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity));
2926 if (my_short_id != NULL)
2927 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s Receive CORE INIT message but have already been initialized! Did CORE fail?\n", "DHT SERVICE");
2928 my_short_id = GNUNET_strdup(GNUNET_i2s(&my_identity));
2929 /* Set the server to local variable */
2932 if (dhtlog_handle != NULL)
2933 dhtlog_handle->insert_node (NULL, &my_identity);
2937 static struct GNUNET_SERVER_MessageHandler plugin_handlers[] = {
2938 {&handle_dht_local_route_request, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE, 0},
2939 {&handle_dht_local_route_stop, NULL, GNUNET_MESSAGE_TYPE_DHT_LOCAL_ROUTE_STOP, 0},
2940 {&handle_dht_control_message, NULL, GNUNET_MESSAGE_TYPE_DHT_CONTROL, 0},
2945 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2946 {&handle_dht_p2p_route_request, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE, 0},
2947 {&handle_dht_p2p_route_result, GNUNET_MESSAGE_TYPE_DHT_P2P_ROUTE_RESULT, 0},
2952 * Method called whenever a peer connects.
2954 * @param cls closure
2955 * @param peer peer identity this notification is about
2956 * @param latency reported latency of the connection with peer
2957 * @param distance reported distance (DV) to peer
2959 void handle_core_connect (void *cls,
2960 const struct GNUNET_PeerIdentity * peer,
2961 struct GNUNET_TIME_Relative latency,
2964 struct PeerInfo *ret;
2967 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2968 "%s:%s Receives core connect message for peer %s distance %d!\n", my_short_id, "dht", GNUNET_i2s(peer), distance);
2971 if (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
2973 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "%s:%s Received %s message for peer %s, but already have peer in RT!", my_short_id, "DHT", "CORE CONNECT", GNUNET_i2s(peer));
2977 if (datacache != NULL)
2978 GNUNET_DATACACHE_put(datacache, &peer->hashPubKey, sizeof(struct GNUNET_PeerIdentity), (const char *)peer, 0, GNUNET_TIME_absolute_get_forever());
2979 ret = try_add_peer(peer,
2980 find_current_bucket(&peer->hashPubKey),
2985 GNUNET_CONTAINER_multihashmap_put(all_known_peers, &peer->hashPubKey, ret, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
2988 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2989 "%s:%s Adding peer to routing list: %s\n", my_short_id, "DHT", ret == NULL ? "NOT ADDED" : "PEER ADDED");
2994 * Method called whenever a peer disconnects.
2996 * @param cls closure
2997 * @param peer peer identity this notification is about
2999 void handle_core_disconnect (void *cls,
3001 GNUNET_PeerIdentity * peer)
3003 struct PeerInfo *to_remove;
3006 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");
3008 if (GNUNET_YES != GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey))
3010 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "%s:%s: do not have peer `%s' in RT, can't disconnect!\n", my_short_id, "DHT", GNUNET_i2s(peer));
3013 GNUNET_assert(GNUNET_CONTAINER_multihashmap_contains(all_known_peers, &peer->hashPubKey));
3014 to_remove = GNUNET_CONTAINER_multihashmap_get(all_known_peers, &peer->hashPubKey);
3015 GNUNET_assert(0 == memcmp(peer, &to_remove->id, sizeof(struct GNUNET_PeerIdentity)));
3016 current_bucket = find_current_bucket(&to_remove->id.hashPubKey);
3017 delete_peer(to_remove, current_bucket);
3021 * Process dht requests.
3023 * @param cls closure
3024 * @param scheduler scheduler to use
3025 * @param server the initialized server
3026 * @param c configuration to use
3030 struct GNUNET_SCHEDULER_Handle *scheduler,
3031 struct GNUNET_SERVER_Handle *server,
3032 const struct GNUNET_CONFIGURATION_Handle *c)
3037 datacache = GNUNET_DATACACHE_create (sched, cfg, "dhtcache");
3038 GNUNET_SERVER_add_handlers (server, plugin_handlers);
3039 coreAPI = GNUNET_CORE_connect (sched, /* Main scheduler */
3040 cfg, /* Main configuration */
3041 GNUNET_TIME_UNIT_FOREVER_REL,
3042 NULL, /* Closure passed to DHT functionas around? */
3043 &core_init, /* Call core_init once connected */
3044 &handle_core_connect, /* Handle connects */
3045 &handle_core_disconnect, /* remove peers on disconnects */
3046 NULL, /* Do we care about "status" updates? */
3047 NULL, /* Don't want notified about all incoming messages */
3048 GNUNET_NO, /* For header only inbound notification */
3049 NULL, /* Don't want notified about all outbound messages */
3050 GNUNET_NO, /* For header only outbound notification */
3051 core_handlers); /* Register these handlers */
3053 if (coreAPI == NULL)
3055 transport_handle = GNUNET_TRANSPORT_connect(sched, cfg,
3056 NULL, NULL, NULL, NULL, NULL);
3057 if (transport_handle != NULL)
3058 GNUNET_TRANSPORT_get_hello (transport_handle, &process_hello, NULL);
3060 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Failed to connect to transport service!\n");
3062 lowest_bucket = MAX_BUCKETS - 1;
3063 forward_list.hashmap = GNUNET_CONTAINER_multihashmap_create(MAX_OUTSTANDING_FORWARDS / 10);
3064 forward_list.minHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
3065 all_known_peers = GNUNET_CONTAINER_multihashmap_create(MAX_BUCKETS / 8);
3066 GNUNET_assert(all_known_peers != NULL);
3067 if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing", "mysql_logging"))
3069 debug_routes = GNUNET_YES;
3073 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3076 strict_kademlia = GNUNET_YES;
3080 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3083 stop_on_closest = GNUNET_YES;
3087 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3090 stop_on_found = GNUNET_YES;
3094 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3095 "malicious_getter"))
3097 malicious_getter = GNUNET_YES;
3098 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3099 "MALICIOUS_GET_FREQUENCY",
3100 &malicious_get_frequency))
3101 malicious_get_frequency = DEFAULT_MALICIOUS_GET_FREQUENCY;
3105 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3106 "malicious_putter"))
3108 malicious_putter = GNUNET_YES;
3109 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_number (cfg, "DHT",
3110 "MALICIOUS_PUT_FREQUENCY",
3111 &malicious_put_frequency))
3112 malicious_put_frequency = DEFAULT_MALICIOUS_PUT_FREQUENCY;
3116 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht",
3117 "malicious_dropper"))
3119 malicious_dropper = GNUNET_YES;
3123 GNUNET_CONFIGURATION_get_value_yesno(cfg, "dht_testing",
3124 "mysql_logging_extended"))
3126 debug_routes = GNUNET_YES;
3127 debug_routes_extended = GNUNET_YES;
3130 if (GNUNET_YES == debug_routes)
3132 dhtlog_handle = GNUNET_DHTLOG_connect(cfg);
3133 if (dhtlog_handle == NULL)
3135 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
3136 "Could not connect to mysql logging server, logging will not happen!");
3140 stats = GNUNET_STATISTICS_create(sched, "dht", cfg);
3144 GNUNET_STATISTICS_set(stats, STAT_ROUTES, 0, GNUNET_NO);
3145 GNUNET_STATISTICS_set(stats, STAT_ROUTE_FORWARDS, 0, GNUNET_NO);
3146 GNUNET_STATISTICS_set(stats, STAT_RESULTS, 0, GNUNET_NO);
3147 GNUNET_STATISTICS_set(stats, STAT_RESULTS_TO_CLIENT, 0, GNUNET_NO);
3148 GNUNET_STATISTICS_set(stats, STAT_RESULT_FORWARDS, 0, GNUNET_NO);
3149 GNUNET_STATISTICS_set(stats, STAT_GETS, 0, GNUNET_NO);
3150 GNUNET_STATISTICS_set(stats, STAT_PUTS, 0, GNUNET_NO);
3151 GNUNET_STATISTICS_set(stats, STAT_PUTS_INSERTED, 0, GNUNET_NO);
3152 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER, 0, GNUNET_NO);
3153 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_START, 0, GNUNET_NO);
3154 GNUNET_STATISTICS_set(stats, STAT_GET_START, 0, GNUNET_NO);
3155 GNUNET_STATISTICS_set(stats, STAT_PUT_START, 0, GNUNET_NO);
3156 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_REPLY, 0, GNUNET_NO);
3157 GNUNET_STATISTICS_set(stats, STAT_FIND_PEER_ANSWER, 0, GNUNET_NO);
3158 GNUNET_STATISTICS_set(stats, STAT_GET_REPLY, 0, GNUNET_NO);
3159 GNUNET_STATISTICS_set(stats, STAT_GET_RESPONSE_START, 0, GNUNET_NO);
3162 random_seconds = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 180);
3163 GNUNET_SCHEDULER_add_delayed (sched,
3164 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, random_seconds),
3165 &send_find_peer_message, NULL);
3168 /* Scheduled the task to clean up when shutdown is called */
3169 cleanup_task = GNUNET_SCHEDULER_add_delayed (sched,
3170 GNUNET_TIME_UNIT_FOREVER_REL,
3171 &shutdown_task, NULL);
3175 * The main function for the dht service.
3177 * @param argc number of arguments from the command line
3178 * @param argv command line arguments
3179 * @return 0 ok, 1 on error
3182 main (int argc, char *const *argv)
3184 return (GNUNET_OK ==
3185 GNUNET_SERVICE_run (argc,
3188 GNUNET_SERVICE_OPTION_NONE,
3189 &run, NULL)) ? 0 : 1;