2 This file is part of GNUnet.
3 (C) 2009, 2010, 2011 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_neighbours.c
23 * @brief GNUnet DHT service's bucket and neighbour management code
24 * @author Christian Grothoff
25 * @author Nathan Evans
29 #include "gnunet_block_lib.h"
30 #include "gnunet_util_lib.h"
31 #include "gnunet_hello_lib.h"
32 #include "gnunet_constants.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_nse_service.h"
35 #include "gnunet_ats_service.h"
36 #include "gnunet_core_service.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"
42 #include "gnunet-service-dht.h"
43 #include "gnunet-service-dht_clients.h"
44 #include "gnunet-service-dht_datacache.h"
45 #include "gnunet-service-dht_hello.h"
46 #include "gnunet-service-dht_neighbours.h"
47 #include "gnunet-service-dht_nse.h"
48 #include "gnunet-service-dht_routing.h"
52 #include "../regex/regex_block_lib.h"
55 #define LOG_TRAFFIC(kind,...) GNUNET_log_from (kind, "dht-traffic",__VA_ARGS__)
58 * How many buckets will we allow total.
60 #define MAX_BUCKETS sizeof (struct GNUNET_HashCode) * 8
63 * What is the maximum number of peers in a given bucket.
65 #define DEFAULT_BUCKET_SIZE 8
68 * Desired replication level for FIND PEER requests
70 #define FIND_PEER_REPLICATION_LEVEL 4
73 * Maximum allowed replication level for all requests.
75 #define MAXIMUM_REPLICATION_LEVEL 16
78 * Maximum allowed number of pending messages per peer.
80 #define MAXIMUM_PENDING_PER_PEER 64
83 * How often to update our preference levels for peers in our routing tables.
85 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
88 * How long at least to wait before sending another find peer request.
90 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
93 * How long at most to wait before sending another find peer request.
95 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10)
98 * How long at most to wait for transmission of a GET request to another peer?
100 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
103 * Hello address expiration
105 extern struct GNUNET_TIME_Relative hello_expiration;
108 GNUNET_NETWORK_STRUCT_BEGIN
113 struct PeerPutMessage
116 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
118 struct GNUNET_MessageHeader header;
123 uint32_t options GNUNET_PACKED;
128 uint32_t type GNUNET_PACKED;
133 uint32_t hop_count GNUNET_PACKED;
136 * Replication level for this message
138 uint32_t desired_replication_level GNUNET_PACKED;
141 * Length of the PUT path that follows (if tracked).
143 uint32_t put_path_length GNUNET_PACKED;
146 * When does the content expire?
148 struct GNUNET_TIME_AbsoluteNBO expiration_time;
151 * Bloomfilter (for peer identities) to stop circular routes
153 char bloomfilter[DHT_BLOOM_SIZE];
156 * The key we are storing under.
158 struct GNUNET_HashCode key;
160 /* put path (if tracked) */
170 struct PeerResultMessage
173 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
175 struct GNUNET_MessageHeader header;
180 uint32_t type GNUNET_PACKED;
183 * Length of the PUT path that follows (if tracked).
185 uint32_t put_path_length GNUNET_PACKED;
188 * Length of the GET path that follows (if tracked).
190 uint32_t get_path_length GNUNET_PACKED;
193 * When does the content expire?
195 struct GNUNET_TIME_AbsoluteNBO expiration_time;
198 * The key of the corresponding GET request.
200 struct GNUNET_HashCode key;
202 /* put path (if tracked) */
204 /* get path (if tracked) */
214 struct PeerGetMessage
217 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_GET
219 struct GNUNET_MessageHeader header;
224 uint32_t options GNUNET_PACKED;
227 * Desired content type.
229 uint32_t type GNUNET_PACKED;
234 uint32_t hop_count GNUNET_PACKED;
237 * Desired replication level for this request.
239 uint32_t desired_replication_level GNUNET_PACKED;
242 * Size of the extended query.
244 uint32_t xquery_size;
247 * Bloomfilter mutator.
252 * Bloomfilter (for peer identities) to stop circular routes
254 char bloomfilter[DHT_BLOOM_SIZE];
257 * The key we are looking for.
259 struct GNUNET_HashCode key;
263 /* result bloomfilter */
266 GNUNET_NETWORK_STRUCT_END
269 * Linked list of messages to send to a particular other peer.
271 struct P2PPendingMessage
274 * Pointer to next item in the list
276 struct P2PPendingMessage *next;
279 * Pointer to previous item in the list
281 struct P2PPendingMessage *prev;
284 * Message importance level. FIXME: used? useful?
286 unsigned int importance;
289 * When does this message time out?
291 struct GNUNET_TIME_Absolute timeout;
294 * Actual message to be sent, allocated at the end of the struct:
295 * // msg = (cast) &pm[1];
296 * // memcpy (&pm[1], data, len);
298 const struct GNUNET_MessageHeader *msg;
304 * Entry for a peer in a bucket.
309 * Next peer entry (DLL)
311 struct PeerInfo *next;
314 * Prev peer entry (DLL)
316 struct PeerInfo *prev;
319 * Count of outstanding messages for peer.
321 unsigned int pending_count;
324 * Head of pending messages to be sent to this peer.
326 struct P2PPendingMessage *head;
329 * Tail of pending messages to be sent to this peer.
331 struct P2PPendingMessage *tail;
334 * Core handle for sending messages to this peer.
336 struct GNUNET_CORE_TransmitHandle *th;
339 * Task for scheduling preference updates
341 GNUNET_SCHEDULER_TaskIdentifier preference_task;
344 * What is the identity of the peer?
346 struct GNUNET_PeerIdentity id;
350 * What is the average latency for replies received?
352 struct GNUNET_TIME_Relative latency;
355 * Transport level distance to peer.
357 unsigned int distance;
364 * Peers are grouped into buckets.
371 struct PeerInfo *head;
376 struct PeerInfo *tail;
379 * Number of peers in the bucket.
381 unsigned int peers_size;
385 * Should routing details be logged to stderr (for debugging)?
387 static int log_route_details_stderr;
390 * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
392 static unsigned int closest_bucket;
395 * How many peers have we added since we sent out our last
398 static unsigned int newly_found_peers;
401 * Option for testing that disables the 'connect' function of the DHT.
403 static int disable_try_connect;
406 * The buckets. Array of size MAX_BUCKET_SIZE. Offset 0 means 0 bits matching.
408 static struct PeerBucket k_buckets[MAX_BUCKETS];
411 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
413 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
416 * Maximum size for each bucket.
418 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
421 * Task that sends FIND PEER requests.
423 static GNUNET_SCHEDULER_TaskIdentifier find_peer_task;
426 * Identity of this peer.
428 static struct GNUNET_PeerIdentity my_identity;
433 static struct GNUNET_CORE_Handle *coreAPI;
438 static struct GNUNET_ATS_PerformanceHandle *atsAPI;
443 * Find the optimal bucket for this key.
445 * @param hc the hashcode to compare our identity to
446 * @return the proper bucket index, or GNUNET_SYSERR
447 * on error (same hashcode)
450 find_bucket (const struct GNUNET_HashCode * hc)
454 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
455 if (bits == MAX_BUCKETS)
457 /* How can all bits match? Got my own ID? */
459 return GNUNET_SYSERR;
461 return MAX_BUCKETS - bits - 1;
466 * Let GNUnet core know that we like the given peer.
468 * @param cls the 'struct PeerInfo' of the peer
469 * @param tc scheduler context.
472 update_core_preference (void *cls,
473 const struct GNUNET_SCHEDULER_TaskContext *tc)
475 struct PeerInfo *peer = cls;
477 unsigned int matching;
480 peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
481 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
484 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
485 &peer->id.hashPubKey);
488 bucket = find_bucket (&peer->id.hashPubKey);
489 if (bucket == GNUNET_SYSERR)
493 GNUNET_assert (k_buckets[bucket].peers_size != 0);
494 preference = (1LL << matching) / k_buckets[bucket].peers_size;
498 peer->preference_task =
499 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
500 &update_core_preference, peer);
503 GNUNET_STATISTICS_update (GDS_stats,
504 gettext_noop ("# Preference updates given to core"),
506 GNUNET_ATS_change_preference (atsAPI, &peer->id,
507 GNUNET_ATS_PREFERENCE_BANDWIDTH,
508 (double) preference, GNUNET_ATS_PREFERENCE_END);
509 peer->preference_task =
510 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
511 &update_core_preference, peer);
518 * Closure for 'add_known_to_bloom'.
520 struct BloomConstructorContext
523 * Bloom filter under construction.
525 struct GNUNET_CONTAINER_BloomFilter *bloom;
535 * Add each of the peers we already know to the bloom filter of
536 * the request so that we don't get duplicate HELLOs.
538 * @param cls the 'struct BloomConstructorContext'.
539 * @param key peer identity to add to the bloom filter
540 * @param value value the peer information (unused)
541 * @return GNUNET_YES (we should continue to iterate)
544 add_known_to_bloom (void *cls, const struct GNUNET_HashCode * key, void *value)
546 struct BloomConstructorContext *ctx = cls;
547 struct GNUNET_HashCode mh;
549 GNUNET_BLOCK_mingle_hash (key, ctx->bf_mutator, &mh);
550 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
551 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
552 GNUNET_h2s (key), ctx->bf_mutator);
553 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
559 * Task to send a find peer message for our own peer identifier
560 * so that we can find the closest peers in the network to ourselves
561 * and attempt to connect to them.
563 * @param cls closure for this task
564 * @param tc the context under which the task is running
567 send_find_peer_message (void *cls,
568 const struct GNUNET_SCHEDULER_TaskContext *tc)
570 struct GNUNET_TIME_Relative next_send_time;
571 struct BloomConstructorContext bcc;
572 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
574 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
575 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
577 if (newly_found_peers > bucket_size)
579 /* If we are finding many peers already, no need to send out our request right now! */
581 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
582 &send_find_peer_message, NULL);
583 newly_found_peers = 0;
587 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
589 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
590 GNUNET_CONSTANTS_BLOOMFILTER_K);
591 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
593 GNUNET_STATISTICS_update (GDS_stats,
594 gettext_noop ("# FIND PEER messages initiated"), 1,
597 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
598 GNUNET_CONSTANTS_BLOOMFILTER_K);
599 // FIXME: pass priority!?
600 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
601 GNUNET_DHT_RO_FIND_PEER,
602 FIND_PEER_REPLICATION_LEVEL, 0,
603 &my_identity.hashPubKey, NULL, 0, bcc.bloom,
604 bcc.bf_mutator, peer_bf);
605 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
606 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
607 /* schedule next round */
608 next_send_time.rel_value =
609 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
610 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
611 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value /
612 (newly_found_peers + 1));
613 newly_found_peers = 0;
615 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
621 * Method called whenever a peer connects.
624 * @param peer peer identity this notification is about
625 * @param atsi performance data
626 * @param atsi_count number of records in 'atsi'
629 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
630 const struct GNUNET_ATS_Information *atsi,
631 unsigned int atsi_count)
633 struct PeerInfo *ret;
636 /* Check for connect to self message */
637 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
639 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected %s to %s\n",
640 GNUNET_i2s (&my_identity), GNUNET_h2s (&peer->hashPubKey));
642 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
648 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), 1,
650 peer_bucket = find_bucket (&peer->hashPubKey);
651 GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
652 ret = GNUNET_malloc (sizeof (struct PeerInfo));
654 ret->latency = latency;
655 ret->distance = distance;
658 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
659 k_buckets[peer_bucket].tail, ret);
660 k_buckets[peer_bucket].peers_size++;
661 closest_bucket = GNUNET_MAX (closest_bucket, peer_bucket);
662 if ((peer_bucket > 0) && (k_buckets[peer_bucket].peers_size <= bucket_size))
664 ret->preference_task =
665 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
668 GNUNET_assert (GNUNET_OK ==
669 GNUNET_CONTAINER_multihashmap_put (all_known_peers,
670 &peer->hashPubKey, ret,
671 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
672 if (1 == GNUNET_CONTAINER_multihashmap_size (all_known_peers) &&
673 (GNUNET_YES != disable_try_connect))
675 /* got a first connection, good time to start with FIND PEER requests... */
676 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
682 * Method called whenever a peer disconnects.
685 * @param peer peer identity this notification is about
688 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
690 struct PeerInfo *to_remove;
692 struct P2PPendingMessage *pos;
693 unsigned int discarded;
695 /* Check for disconnect from self message */
696 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
698 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnected %s from %s\n",
699 GNUNET_i2s (&my_identity), GNUNET_h2s (&peer->hashPubKey));
701 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
702 if (NULL == to_remove)
707 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), -1,
709 GNUNET_assert (GNUNET_YES ==
710 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
713 if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
715 GNUNET_SCHEDULER_cancel (to_remove->preference_task);
716 to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
718 current_bucket = find_bucket (&to_remove->id.hashPubKey);
719 GNUNET_assert (current_bucket >= 0);
720 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
721 k_buckets[current_bucket].tail, to_remove);
722 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
723 k_buckets[current_bucket].peers_size--;
724 while ((closest_bucket > 0) && (k_buckets[closest_bucket].peers_size == 0))
727 if (to_remove->th != NULL)
729 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
730 to_remove->th = NULL;
733 while (NULL != (pos = to_remove->head))
735 GNUNET_CONTAINER_DLL_remove (to_remove->head, to_remove->tail, pos);
739 GNUNET_STATISTICS_update (GDS_stats,
741 ("# Queued messages discarded (peer disconnected)"),
742 discarded, GNUNET_NO);
743 GNUNET_free (to_remove);
748 * Called when core is ready to send a message we asked for
749 * out to the destination.
751 * @param cls the 'struct PeerInfo' of the target peer
752 * @param size number of bytes available in buf
753 * @param buf where the callee should write the message
754 * @return number of bytes written to buf
757 core_transmit_notify (void *cls, size_t size, void *buf)
759 struct PeerInfo *peer = cls;
761 struct P2PPendingMessage *pending;
766 while ((NULL != (pending = peer->head)) &&
767 (GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value == 0))
769 peer->pending_count--;
770 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
771 GNUNET_free (pending);
775 /* no messages pending */
781 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO,
783 GNUNET_TIME_absolute_get_remaining
784 (pending->timeout), &peer->id,
785 ntohs (pending->msg->size),
786 &core_transmit_notify, peer);
787 GNUNET_break (NULL != peer->th);
791 while ((NULL != (pending = peer->head)) &&
792 (size - off >= (msize = ntohs (pending->msg->size))))
794 GNUNET_STATISTICS_update (GDS_stats,
796 ("# Bytes transmitted to other peers"), msize,
798 memcpy (&cbuf[off], pending->msg, msize);
800 peer->pending_count--;
801 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
802 GNUNET_free (pending);
804 if (peer->head != NULL)
807 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO,
809 GNUNET_TIME_absolute_get_remaining
810 (pending->timeout), &peer->id, msize,
811 &core_transmit_notify, peer);
812 GNUNET_break (NULL != peer->th);
819 * Transmit all messages in the peer's message queue.
821 * @param peer message queue to process
824 process_peer_queue (struct PeerInfo *peer)
826 struct P2PPendingMessage *pending;
828 if (NULL == (pending = peer->head))
830 if (NULL != peer->th)
832 GNUNET_STATISTICS_update (GDS_stats,
834 ("# Bytes of bandwidth requested from core"),
835 ntohs (pending->msg->size), GNUNET_NO);
837 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO,
839 GNUNET_TIME_absolute_get_remaining
840 (pending->timeout), &peer->id,
841 ntohs (pending->msg->size),
842 &core_transmit_notify, peer);
843 GNUNET_break (NULL != peer->th);
848 * To how many peers should we (on average) forward the request to
849 * obtain the desired target_replication count (on average).
851 * @param hop_count number of hops the message has traversed
852 * @param target_replication the number of total paths desired
853 * @return Some number of peers to forward the message to
856 get_forward_count (uint32_t hop_count, uint32_t target_replication)
858 uint32_t random_value;
859 uint32_t forward_count;
862 if (hop_count > GDS_NSE_get () * 4.0)
864 /* forcefully terminate */
867 if (hop_count > GDS_NSE_get () * 2.0)
869 /* Once we have reached our ideal number of hops, only forward to 1 peer */
872 /* bound by system-wide maximum */
874 GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
876 1 + (target_replication - 1.0) / (GDS_NSE_get () +
877 ((float) (target_replication - 1.0) *
879 /* Set forward count to floor of target_value */
880 forward_count = (uint32_t) target_value;
881 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
882 target_value = target_value - forward_count;
884 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
885 if (random_value < (target_value * UINT32_MAX))
887 return forward_count;
892 * Compute the distance between have and target as a 32-bit value.
893 * Differences in the lower bits must count stronger than differences
894 * in the higher bits.
896 * @return 0 if have==target, otherwise a number
897 * that is larger as the distance between
898 * the two hash codes increases
901 get_distance (const struct GNUNET_HashCode * target, const struct GNUNET_HashCode * have)
908 /* We have to represent the distance between two 2^9 (=512)-bit
909 * numbers as a 2^5 (=32)-bit number with "0" being used for the
910 * two numbers being identical; furthermore, we need to
911 * guarantee that a difference in the number of matching
912 * bits is always represented in the result.
914 * We use 2^32/2^9 numerical values to distinguish between
915 * hash codes that have the same LSB bit distance and
916 * use the highest 2^9 bits of the result to signify the
917 * number of (mis)matching LSB bits; if we have 0 matching
918 * and hence 512 mismatching LSB bits we return -1 (since
919 * 512 itself cannot be represented with 9 bits) */
921 /* first, calculate the most significant 9 bits of our
922 * result, aka the number of LSBs */
923 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
924 /* bucket is now a value between 0 and 512 */
926 return 0; /* perfect match */
928 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
929 * below, we'd end up with max+1 (overflow)) */
931 /* calculate the most significant bits of the final result */
932 msb = (512 - bucket) << (32 - 9);
933 /* calculate the 32-9 least significant bits of the final result by
934 * looking at the differences in the 32-9 bits following the
935 * mismatching bit at 'bucket' */
938 (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
940 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
941 GNUNET_CRYPTO_hash_get_bit (have, i))
942 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
943 * last bit set will be 31 -- if
944 * i does not reach 512 first... */
951 * Check whether my identity is closer than any known peers. If a
952 * non-null bloomfilter is given, check if this is the closest peer
953 * that hasn't already been routed to.
955 * @param key hash code to check closeness to
956 * @param bloom bloomfilter, exclude these entries from the decision
957 * @return GNUNET_YES if node location is closest,
958 * GNUNET_NO otherwise.
961 am_closest_peer (const struct GNUNET_HashCode * key,
962 const struct GNUNET_CONTAINER_BloomFilter *bloom)
968 struct PeerInfo *pos;
970 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (struct GNUNET_HashCode)))
972 bucket_num = find_bucket (key);
973 GNUNET_assert (bucket_num >= 0);
974 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
975 pos = k_buckets[bucket_num].head;
977 while ((pos != NULL) && (count < bucket_size))
979 if ((bloom != NULL) &&
981 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
984 continue; /* Skip already checked entries */
986 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
987 if (other_bits > bits)
989 if (other_bits == bits) /* We match the same number of bits */
993 /* No peers closer, we are the closest! */
999 * Select a peer from the routing table that would be a good routing
1000 * destination for sending a message for "key". The resulting peer
1001 * must not be in the set of blocked peers.<p>
1003 * Note that we should not ALWAYS select the closest peer to the
1004 * target, peers further away from the target should be chosen with
1005 * exponentially declining probability.
1007 * FIXME: double-check that this is fine
1010 * @param key the key we are selecting a peer to route to
1011 * @param bloom a bloomfilter containing entries this request has seen already
1012 * @param hops how many hops has this message traversed thus far
1013 * @return Peer to route to, or NULL on error
1015 static struct PeerInfo *
1016 select_peer (const struct GNUNET_HashCode * key,
1017 const struct GNUNET_CONTAINER_BloomFilter *bloom, uint32_t hops)
1021 unsigned int selected;
1022 struct PeerInfo *pos;
1024 unsigned int smallest_distance;
1025 struct PeerInfo *chosen;
1027 if (hops >= GDS_NSE_get ())
1029 /* greedy selection (closest peer that is not in bloomfilter) */
1030 smallest_distance = UINT_MAX;
1032 for (bc = 0; bc <= closest_bucket; bc++)
1034 pos = k_buckets[bc].head;
1036 while ((pos != NULL) && (count < bucket_size))
1038 if ((bloom == NULL) ||
1040 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1042 dist = get_distance (key, &pos->id.hashPubKey);
1043 if (dist < smallest_distance)
1046 smallest_distance = dist;
1051 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1052 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1053 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1054 GNUNET_STATISTICS_update (GDS_stats,
1056 ("# Peers excluded from routing due to Bloomfilter"),
1058 dist = get_distance (key, &pos->id.hashPubKey);
1059 if (dist < smallest_distance)
1062 smallest_distance = dist;
1070 GNUNET_STATISTICS_update (GDS_stats,
1071 gettext_noop ("# Peer selection failed"), 1,
1076 /* select "random" peer */
1077 /* count number of peers that are available and not filtered */
1079 for (bc = 0; bc <= closest_bucket; bc++)
1081 pos = k_buckets[bc].head;
1082 while ((pos != NULL) && (count < bucket_size))
1084 if ((bloom != NULL) &&
1086 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1088 GNUNET_STATISTICS_update (GDS_stats,
1090 ("# Peers excluded from routing due to Bloomfilter"),
1092 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1093 "Excluded peer `%s' due to BF match in random routing for %s\n",
1094 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1096 continue; /* Ignore bloomfiltered peers */
1102 if (0 == count) /* No peers to select from! */
1104 GNUNET_STATISTICS_update (GDS_stats,
1105 gettext_noop ("# Peer selection failed"), 1,
1109 /* Now actually choose a peer */
1110 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1112 for (bc = 0; bc <= closest_bucket; bc++)
1114 for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next)
1116 if ((bloom != NULL) &&
1118 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1120 continue; /* Ignore bloomfiltered peers */
1122 if (0 == selected--)
1132 * Compute the set of peers that the given request should be
1135 * @param key routing key
1136 * @param bloom bloom filter excluding peers as targets, all selected
1137 * peers will be added to the bloom filter
1138 * @param hop_count number of hops the request has traversed so far
1139 * @param target_replication desired number of replicas
1140 * @param targets where to store an array of target peers (to be
1141 * free'd by the caller)
1142 * @return number of peers returned in 'targets'.
1145 get_target_peers (const struct GNUNET_HashCode *key,
1146 struct GNUNET_CONTAINER_BloomFilter *bloom,
1147 uint32_t hop_count, uint32_t target_replication,
1148 struct PeerInfo ***targets)
1152 struct PeerInfo **rtargets;
1153 struct PeerInfo *nxt;
1155 GNUNET_assert (NULL != bloom);
1156 ret = get_forward_count (hop_count, target_replication);
1162 rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1163 for (off = 0; off < ret; off++)
1165 nxt = select_peer (key, bloom, hop_count);
1168 rtargets[off] = nxt;
1169 GNUNET_break (GNUNET_NO ==
1170 GNUNET_CONTAINER_bloomfilter_test (bloom,
1171 &nxt->id.hashPubKey));
1172 GNUNET_CONTAINER_bloomfilter_add (bloom, &rtargets[off]->id.hashPubKey);
1174 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1175 "Selected %u/%u peers at hop %u for %s (target was %u)\n", off,
1176 GNUNET_CONTAINER_multihashmap_size (all_known_peers),
1177 (unsigned int) hop_count, GNUNET_h2s (key), ret);
1180 GNUNET_free (rtargets);
1184 *targets = rtargets;
1185 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1186 "Forwarding query `%s' to %u peers (goal was %u peers)\n",
1195 * Perform a PUT operation. Forwards the given request to other
1196 * peers. Does not store the data locally. Does not give the
1197 * data to local clients. May do nothing if this is the only
1198 * peer in the network (or if we are the closest peer in the
1201 * @param type type of the block
1202 * @param options routing options
1203 * @param desired_replication_level desired replication count
1204 * @param expiration_time when does the content expire
1205 * @param hop_count how many hops has this message traversed so far
1206 * @param bf Bloom filter of peers this PUT has already traversed
1207 * @param key key for the content
1208 * @param put_path_length number of entries in put_path
1209 * @param put_path peers this request has traversed so far (if tracked)
1210 * @param data payload to store
1211 * @param data_size number of bytes in data
1214 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1215 enum GNUNET_DHT_RouteOption options,
1216 uint32_t desired_replication_level,
1217 struct GNUNET_TIME_Absolute expiration_time,
1219 struct GNUNET_CONTAINER_BloomFilter *bf,
1220 const struct GNUNET_HashCode * key,
1221 unsigned int put_path_length,
1222 struct GNUNET_PeerIdentity *put_path,
1223 const void *data, size_t data_size)
1225 unsigned int target_count;
1227 struct PeerInfo **targets;
1228 struct PeerInfo *target;
1229 struct P2PPendingMessage *pending;
1231 struct PeerPutMessage *ppm;
1232 struct GNUNET_PeerIdentity *pp;
1234 GNUNET_assert (NULL != bf);
1235 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1236 "Adding myself (%s) to PUT bloomfilter for %s\n",
1237 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1238 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1239 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1242 get_target_peers (key, bf, hop_count, desired_replication_level,
1244 if (0 == target_count)
1246 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1247 "Routing PUT for %s terminates after %u hops at %s\n",
1248 GNUNET_h2s (key), (unsigned int) hop_count,
1249 GNUNET_i2s (&my_identity));
1253 put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1254 sizeof (struct PeerPutMessage);
1255 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1257 put_path_length = 0;
1258 msize = data_size + sizeof (struct PeerPutMessage);
1260 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1263 GNUNET_free (targets);
1266 GNUNET_STATISTICS_update (GDS_stats,
1268 ("# PUT messages queued for transmission"),
1269 target_count, GNUNET_NO);
1270 for (i = 0; i < target_count; i++)
1272 target = targets[i];
1273 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1275 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1277 continue; /* skip */
1279 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1280 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1281 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1282 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1283 pending->importance = 0; /* FIXME */
1284 pending->timeout = expiration_time;
1285 ppm = (struct PeerPutMessage *) &pending[1];
1286 pending->msg = &ppm->header;
1287 ppm->header.size = htons (msize);
1288 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1289 ppm->options = htonl (options);
1290 ppm->type = htonl (type);
1291 ppm->hop_count = htonl (hop_count + 1);
1292 ppm->desired_replication_level = htonl (desired_replication_level);
1293 ppm->put_path_length = htonl (put_path_length);
1294 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1295 GNUNET_break (GNUNET_YES ==
1296 GNUNET_CONTAINER_bloomfilter_test (bf,
1297 &target->id.hashPubKey));
1298 GNUNET_assert (GNUNET_OK ==
1299 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1303 pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1304 memcpy (pp, put_path,
1305 sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1306 memcpy (&pp[put_path_length], data, data_size);
1307 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1308 target->pending_count++;
1309 process_peer_queue (target);
1311 GNUNET_free (targets);
1316 * Perform a GET operation. Forwards the given request to other
1317 * peers. Does not lookup the key locally. May do nothing if this is
1318 * the only peer in the network (or if we are the closest peer in the
1321 * @param type type of the block
1322 * @param options routing options
1323 * @param desired_replication_level desired replication count
1324 * @param hop_count how many hops did this request traverse so far?
1325 * @param key key for the content
1326 * @param xquery extended query
1327 * @param xquery_size number of bytes in xquery
1328 * @param reply_bf bloomfilter to filter duplicates
1329 * @param reply_bf_mutator mutator for reply_bf
1330 * @param peer_bf filter for peers not to select (again)
1333 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1334 enum GNUNET_DHT_RouteOption options,
1335 uint32_t desired_replication_level,
1336 uint32_t hop_count, const struct GNUNET_HashCode * key,
1337 const void *xquery, size_t xquery_size,
1338 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1339 uint32_t reply_bf_mutator,
1340 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1342 unsigned int target_count;
1344 struct PeerInfo **targets;
1345 struct PeerInfo *target;
1346 struct P2PPendingMessage *pending;
1348 struct PeerGetMessage *pgm;
1350 size_t reply_bf_size;
1352 GNUNET_assert (NULL != peer_bf);
1353 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1356 get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1358 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1359 "Adding myself (%s) to GET bloomfilter for %s\n",
1360 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1361 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity.hashPubKey);
1362 if (0 == target_count)
1364 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1365 "Routing GET for %s terminates after %u hops at %s\n",
1366 GNUNET_h2s (key), (unsigned int) hop_count,
1367 GNUNET_i2s (&my_identity));
1370 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1371 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1372 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1375 GNUNET_free (targets);
1378 GNUNET_STATISTICS_update (GDS_stats,
1380 ("# GET messages queued for transmission"),
1381 target_count, GNUNET_NO);
1382 /* forward request */
1383 for (i = 0; i < target_count; i++)
1385 target = targets[i];
1386 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1388 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1390 continue; /* skip */
1392 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1393 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1394 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1395 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1396 pending->importance = 0; /* FIXME */
1397 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1398 pgm = (struct PeerGetMessage *) &pending[1];
1399 pending->msg = &pgm->header;
1400 pgm->header.size = htons (msize);
1401 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1402 pgm->options = htonl (options);
1403 pgm->type = htonl (type);
1404 pgm->hop_count = htonl (hop_count + 1);
1405 pgm->desired_replication_level = htonl (desired_replication_level);
1406 pgm->xquery_size = htonl (xquery_size);
1407 pgm->bf_mutator = reply_bf_mutator;
1408 GNUNET_break (GNUNET_YES ==
1409 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1410 &target->id.hashPubKey));
1411 GNUNET_assert (GNUNET_OK ==
1412 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1416 xq = (char *) &pgm[1];
1417 memcpy (xq, xquery, xquery_size);
1418 if (NULL != reply_bf)
1419 GNUNET_assert (GNUNET_OK ==
1420 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1424 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1425 target->pending_count++;
1426 process_peer_queue (target);
1428 GNUNET_free (targets);
1433 * Handle a reply (route to origin). Only forwards the reply back to
1434 * the given peer. Does not do local caching or forwarding to local
1437 * @param target neighbour that should receive the block (if still connected)
1438 * @param type type of the block
1439 * @param expiration_time when does the content expire
1440 * @param key key for the content
1441 * @param put_path_length number of entries in put_path
1442 * @param put_path peers the original PUT traversed (if tracked)
1443 * @param get_path_length number of entries in put_path
1444 * @param get_path peers this reply has traversed so far (if tracked)
1445 * @param data payload of the reply
1446 * @param data_size number of bytes in data
1449 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1450 enum GNUNET_BLOCK_Type type,
1451 struct GNUNET_TIME_Absolute expiration_time,
1452 const struct GNUNET_HashCode * key,
1453 unsigned int put_path_length,
1454 const struct GNUNET_PeerIdentity *put_path,
1455 unsigned int get_path_length,
1456 const struct GNUNET_PeerIdentity *get_path,
1457 const void *data, size_t data_size)
1459 struct PeerInfo *pi;
1460 struct P2PPendingMessage *pending;
1462 struct PeerResultMessage *prm;
1463 struct GNUNET_PeerIdentity *paths;
1466 data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1468 sizeof (struct GNUNET_PeerIdentity);
1469 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1471 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1473 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1474 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1479 pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers, &target->hashPubKey);
1482 /* peer disconnected in the meantime, drop reply */
1485 if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1488 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1493 GNUNET_STATISTICS_update (GDS_stats,
1495 ("# RESULT messages queued for transmission"), 1,
1497 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1498 pending->importance = 0; /* FIXME */
1499 pending->timeout = expiration_time;
1500 prm = (struct PeerResultMessage *) &pending[1];
1501 pending->msg = &prm->header;
1502 prm->header.size = htons (msize);
1503 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1504 prm->type = htonl (type);
1505 prm->put_path_length = htonl (put_path_length);
1506 prm->get_path_length = htonl (get_path_length);
1507 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1509 paths = (struct GNUNET_PeerIdentity *) &prm[1];
1510 memcpy (paths, put_path,
1511 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1512 memcpy (&paths[put_path_length], get_path,
1513 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1514 memcpy (&paths[put_path_length + get_path_length], data, data_size);
1515 GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1516 pi->pending_count++;
1517 process_peer_queue (pi);
1522 * To be called on core init/fail.
1524 * @param cls service closure
1525 * @param server handle to the server for this service
1526 * @param identity the public identity of this peer
1529 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1530 const struct GNUNET_PeerIdentity *identity)
1532 GNUNET_assert (server != NULL);
1533 my_identity = *identity;
1538 * Core handler for p2p put requests.
1540 * @param cls closure
1541 * @param peer sender of the request
1542 * @param message message
1543 * @param peer peer identity this notification is about
1544 * @param atsi performance data
1545 * @param atsi_count number of records in 'atsi'
1546 * @return GNUNET_OK to keep the connection open,
1547 * GNUNET_SYSERR to close it (signal serious error)
1550 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1551 const struct GNUNET_MessageHeader *message,
1552 const struct GNUNET_ATS_Information *atsi,
1553 unsigned int atsi_count)
1555 const struct PeerPutMessage *put;
1556 const struct GNUNET_PeerIdentity *put_path;
1557 const void *payload;
1560 size_t payload_size;
1561 enum GNUNET_DHT_RouteOption options;
1562 struct GNUNET_CONTAINER_BloomFilter *bf;
1563 struct GNUNET_HashCode test_key;
1565 msize = ntohs (message->size);
1566 if (msize < sizeof (struct PeerPutMessage))
1568 GNUNET_break_op (0);
1571 put = (const struct PeerPutMessage *) message;
1572 putlen = ntohl (put->put_path_length);
1574 sizeof (struct PeerPutMessage) +
1575 putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1577 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1579 GNUNET_break_op (0);
1582 GNUNET_STATISTICS_update (GDS_stats,
1583 gettext_noop ("# P2P PUT requests received"), 1,
1585 put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1586 payload = &put_path[putlen];
1587 options = ntohl (put->options);
1589 msize - (sizeof (struct PeerPutMessage) +
1590 putlen * sizeof (struct GNUNET_PeerIdentity));
1591 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1592 GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1593 if (GNUNET_YES == log_route_details_stderr)
1597 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1598 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, "XDHT PUT %s: %s->%s (%u, %u=>%u)\n",
1599 GNUNET_h2s (&put->key), GNUNET_i2s (peer), tmp,
1600 ntohl(put->hop_count),
1601 GNUNET_CRYPTO_hash_matching_bits (&peer->hashPubKey, &put->key),
1602 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, &put->key)
1606 switch (GNUNET_BLOCK_get_key
1607 (GDS_block_context, ntohl (put->type), payload, payload_size,
1611 if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1613 GNUNET_break_op (0);
1618 GNUNET_break_op (0);
1621 /* cannot verify, good luck */
1624 if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
1626 switch (GNUNET_BLOCK_evaluate (GDS_block_context,
1629 NULL, 0, /* bloom filer */
1630 NULL, 0, /* xquery */
1631 payload, payload_size))
1633 case GNUNET_BLOCK_EVALUATION_OK_MORE:
1634 case GNUNET_BLOCK_EVALUATION_OK_LAST:
1637 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1638 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1639 case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1640 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1641 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1642 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1644 GNUNET_break_op (0);
1649 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1650 GNUNET_CONSTANTS_BLOOMFILTER_K);
1651 GNUNET_break_op (GNUNET_YES ==
1652 GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1654 struct GNUNET_PeerIdentity pp[putlen + 1];
1656 /* extend 'put path' by sender */
1657 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1659 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1666 /* give to local clients */
1667 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1668 &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1669 payload_size, payload);
1671 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1672 (am_closest_peer (&put->key, bf)))
1673 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1674 (put->expiration_time), &put->key, putlen, pp,
1675 ntohl (put->type), payload_size, payload);
1676 /* route to other peers */
1677 GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1678 ntohl (put->desired_replication_level),
1679 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1680 ntohl (put->hop_count), bf, &put->key, putlen,
1681 pp, payload, payload_size);
1682 /* notify monitoring clients */
1683 GDS_CLIENTS_process_put (options,
1685 ntohl (put->hop_count),
1686 ntohl (put->desired_replication_level),
1688 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1693 GNUNET_CONTAINER_bloomfilter_free (bf);
1699 * We have received a FIND PEER request. Send matching
1702 * @param sender sender of the FIND PEER request
1703 * @param key peers close to this key are desired
1704 * @param bf peers matching this bf are excluded
1705 * @param bf_mutator mutator for bf
1708 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1709 const struct GNUNET_HashCode * key,
1710 struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1713 struct PeerBucket *bucket;
1714 struct PeerInfo *peer;
1715 unsigned int choice;
1716 struct GNUNET_HashCode mhash;
1717 const struct GNUNET_HELLO_Message *hello;
1719 /* first, check about our own HELLO */
1720 if (NULL != GDS_my_hello)
1722 GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1724 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1726 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1727 GNUNET_TIME_relative_to_absolute
1729 key, 0, NULL, 0, NULL, GDS_my_hello,
1730 GNUNET_HELLO_size ((const struct
1731 GNUNET_HELLO_Message *)
1736 GNUNET_STATISTICS_update (GDS_stats,
1738 ("# FIND PEER requests ignored due to Bloomfilter"),
1744 GNUNET_STATISTICS_update (GDS_stats,
1746 ("# FIND PEER requests ignored due to lack of HELLO"),
1750 /* then, also consider sending a random HELLO from the closest bucket */
1751 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (struct GNUNET_HashCode)))
1752 bucket_idx = closest_bucket;
1754 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1755 if (bucket_idx == GNUNET_SYSERR)
1757 bucket = &k_buckets[bucket_idx];
1758 if (bucket->peers_size == 0)
1761 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1762 peer = bucket->head;
1765 GNUNET_assert (peer != NULL);
1769 choice = bucket->peers_size;
1774 return; /* no non-masked peer available */
1776 peer = bucket->head;
1777 GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1778 hello = GDS_HELLO_get (&peer->id);
1780 while ((hello == NULL) ||
1781 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1782 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1783 GNUNET_TIME_relative_to_absolute
1784 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1785 0, NULL, 0, NULL, hello,
1786 GNUNET_HELLO_size (hello));
1791 * Core handler for p2p get requests.
1793 * @param cls closure
1794 * @param peer sender of the request
1795 * @param message message
1796 * @param peer peer identity this notification is about
1797 * @param atsi performance data
1798 * @param atsi_count number of records in 'atsi'
1799 * @return GNUNET_OK to keep the connection open,
1800 * GNUNET_SYSERR to close it (signal serious error)
1803 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1804 const struct GNUNET_MessageHeader *message,
1805 const struct GNUNET_ATS_Information *atsi,
1806 unsigned int atsi_count)
1808 struct PeerGetMessage *get;
1809 uint32_t xquery_size;
1810 size_t reply_bf_size;
1812 enum GNUNET_BLOCK_Type type;
1813 enum GNUNET_DHT_RouteOption options;
1814 enum GNUNET_BLOCK_EvaluationResult eval;
1815 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1816 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1820 memcmp (peer, &my_identity,
1821 sizeof (struct GNUNET_PeerIdentity)));
1822 /* parse and validate message */
1823 msize = ntohs (message->size);
1824 if (msize < sizeof (struct PeerGetMessage))
1826 GNUNET_break_op (0);
1829 get = (struct PeerGetMessage *) message;
1830 xquery_size = ntohl (get->xquery_size);
1831 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1833 GNUNET_break_op (0);
1836 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1837 type = ntohl (get->type);
1838 options = ntohl (get->options);
1839 xquery = (const char *) &get[1];
1841 GNUNET_STATISTICS_update (GDS_stats,
1842 gettext_noop ("# P2P GET requests received"), 1,
1844 if (GNUNET_YES == log_route_details_stderr)
1848 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1849 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1850 "XDHT GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n",
1851 GNUNET_h2s (&get->key), GNUNET_i2s (peer), tmp,
1852 ntohl(get->hop_count),
1853 GNUNET_CRYPTO_hash_matching_bits (&peer->hashPubKey, &get->key),
1854 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, &get->key),
1855 ntohl(get->xquery_size), xquery
1860 if (reply_bf_size > 0)
1862 GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1863 GNUNET_CONSTANTS_BLOOMFILTER_K);
1865 GNUNET_BLOCK_evaluate (GDS_block_context, type, &get->key, &reply_bf,
1866 get->bf_mutator, xquery, xquery_size, NULL, 0);
1867 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1869 /* request invalid or block type not supported */
1870 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1871 if (NULL != reply_bf)
1872 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1876 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1877 GNUNET_CONSTANTS_BLOOMFILTER_K);
1878 GNUNET_break_op (GNUNET_YES ==
1879 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1880 &peer->hashPubKey));
1881 /* remember request for routing replies */
1882 GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1883 reply_bf, get->bf_mutator);
1884 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GET for %s at %s after %u hops\n",
1885 GNUNET_h2s (&get->key), GNUNET_i2s (&my_identity),
1886 (unsigned int) ntohl (get->hop_count));
1887 /* local lookup (this may update the reply_bf) */
1888 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1889 (am_closest_peer (&get->key, peer_bf)))
1891 if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1893 GNUNET_STATISTICS_update (GDS_stats,
1895 ("# P2P FIND PEER requests processed"), 1,
1897 handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
1902 GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
1903 &reply_bf, get->bf_mutator);
1908 GNUNET_STATISTICS_update (GDS_stats,
1909 gettext_noop ("# P2P GET requests ONLY routed"),
1913 GDS_CLIENTS_process_get (options,
1915 ntohl(get->hop_count),
1916 ntohl(get->desired_replication_level),
1920 /* P2P forwarding */
1921 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1922 GDS_NEIGHBOURS_handle_get (type, options,
1923 ntohl (get->desired_replication_level),
1924 ntohl (get->hop_count), &get->key, xquery,
1925 xquery_size, reply_bf, get->bf_mutator, peer_bf);
1927 if (NULL != reply_bf)
1928 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1929 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
1935 * Core handler for p2p result messages.
1937 * @param cls closure
1938 * @param message message
1939 * @param peer peer identity this notification is about
1940 * @param atsi performance data
1941 * @param atsi_count number of records in 'atsi'
1942 * @return GNUNET_YES (do not cut p2p connection)
1945 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1946 const struct GNUNET_MessageHeader *message,
1947 const struct GNUNET_ATS_Information *atsi,
1948 unsigned int atsi_count)
1950 const struct PeerResultMessage *prm;
1951 const struct GNUNET_PeerIdentity *put_path;
1952 const struct GNUNET_PeerIdentity *get_path;
1954 uint32_t get_path_length;
1955 uint32_t put_path_length;
1958 enum GNUNET_BLOCK_Type type;
1960 /* parse and validate message */
1961 msize = ntohs (message->size);
1962 if (msize < sizeof (struct PeerResultMessage))
1964 GNUNET_break_op (0);
1967 prm = (struct PeerResultMessage *) message;
1968 put_path_length = ntohl (prm->put_path_length);
1969 get_path_length = ntohl (prm->get_path_length);
1971 sizeof (struct PeerResultMessage) + (get_path_length +
1973 sizeof (struct GNUNET_PeerIdentity)) ||
1975 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1977 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1979 GNUNET_break_op (0);
1982 put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
1983 get_path = &put_path[put_path_length];
1984 type = ntohl (prm->type);
1985 data = (const void *) &get_path[get_path_length];
1987 msize - (sizeof (struct PeerResultMessage) +
1989 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1990 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
1992 if (GNUNET_YES == log_route_details_stderr)
1996 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1997 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, "XDHT RESULT %s: %s->%s (%u)\n",
1998 GNUNET_h2s (&prm->key), GNUNET_i2s (peer), tmp,
1999 get_path_length + 1);
2002 /* if we got a HELLO, consider it for our own routing table */
2003 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
2005 const struct GNUNET_MessageHeader *h;
2006 struct GNUNET_PeerIdentity pid;
2009 /* Should be a HELLO, validate and consider using it! */
2010 if (data_size < sizeof (struct GNUNET_MessageHeader))
2012 GNUNET_break_op (0);
2016 if (data_size != ntohs (h->size))
2018 GNUNET_break_op (0);
2022 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
2024 GNUNET_break_op (0);
2027 if ((GNUNET_YES != disable_try_connect) &&
2028 0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
2030 bucket = find_bucket (&pid.hashPubKey);
2031 if ((bucket >= 0) &&
2032 (k_buckets[bucket].peers_size < bucket_size) &&
2033 (NULL != GDS_transport_handle))
2035 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
2036 GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid, NULL, NULL); /*FIXME TRY_CONNECT change */
2041 /* append 'peer' to 'get_path' */
2043 struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
2045 memcpy (xget_path, get_path,
2046 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2047 xget_path[get_path_length] = *peer;
2050 /* forward to local clients */
2051 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2052 &prm->key, get_path_length, xget_path,
2053 put_path_length, put_path, type, data_size, data);
2054 GDS_CLIENTS_process_get_resp (type,
2055 xget_path, get_path_length,
2056 put_path, put_path_length,
2057 GNUNET_TIME_absolute_ntoh (
2058 prm->expiration_time),
2063 /* forward to other peers */
2064 GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2065 &prm->key, put_path_length, put_path, get_path_length,
2066 xget_path, data, data_size);
2074 * Initialize neighbours subsystem.
2076 * @return GNUNET_OK on success, GNUNET_SYSERR on error
2079 GDS_NEIGHBOURS_init ()
2081 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2082 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2083 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2084 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2087 unsigned long long temp_config_num;
2090 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2092 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2094 bucket_size = (unsigned int) temp_config_num;
2095 log_route_details_stderr =
2096 (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO;
2097 atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2099 GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
2100 &handle_core_disconnect, NULL, GNUNET_NO, NULL,
2101 GNUNET_NO, core_handlers);
2102 if (coreAPI == NULL)
2103 return GNUNET_SYSERR;
2104 all_known_peers = GNUNET_CONTAINER_multihashmap_create (256, GNUNET_NO);
2110 * Shutdown neighbours subsystem.
2113 GDS_NEIGHBOURS_done ()
2115 if (coreAPI == NULL)
2117 GNUNET_CORE_disconnect (coreAPI);
2119 GNUNET_ATS_performance_done (atsAPI);
2121 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2122 GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2123 all_known_peers = NULL;
2124 if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2126 GNUNET_SCHEDULER_cancel (find_peer_task);
2127 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2132 * Get the ID of the local node.
2134 * @return identity of the local node
2136 struct GNUNET_PeerIdentity *
2137 GDS_NEIGHBOURS_get_id ()
2139 return &my_identity;
2143 /* end of gnunet-service-dht_neighbours.c */