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"
53 * How many buckets will we allow total.
55 #define MAX_BUCKETS sizeof (struct GNUNET_HashCode) * 8
58 * What is the maximum number of peers in a given bucket.
60 #define DEFAULT_BUCKET_SIZE 8
63 * Desired replication level for FIND PEER requests
65 #define FIND_PEER_REPLICATION_LEVEL 4
68 * Maximum allowed replication level for all requests.
70 #define MAXIMUM_REPLICATION_LEVEL 16
73 * Maximum allowed number of pending messages per peer.
75 #define MAXIMUM_PENDING_PER_PEER 64
78 * How often to update our preference levels for peers in our routing tables.
80 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
83 * How long at least to wait before sending another find peer request.
85 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
88 * How long at most to wait before sending another find peer request.
90 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10)
93 * How long at most to wait for transmission of a GET request to another peer?
95 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
98 GNUNET_NETWORK_STRUCT_BEGIN
103 struct PeerPutMessage
106 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
108 struct GNUNET_MessageHeader header;
113 uint32_t options GNUNET_PACKED;
118 uint32_t type GNUNET_PACKED;
123 uint32_t hop_count GNUNET_PACKED;
126 * Replication level for this message
128 uint32_t desired_replication_level GNUNET_PACKED;
131 * Length of the PUT path that follows (if tracked).
133 uint32_t put_path_length GNUNET_PACKED;
136 * When does the content expire?
138 struct GNUNET_TIME_AbsoluteNBO expiration_time;
141 * Bloomfilter (for peer identities) to stop circular routes
143 char bloomfilter[DHT_BLOOM_SIZE];
146 * The key we are storing under.
148 struct GNUNET_HashCode key;
150 /* put path (if tracked) */
160 struct PeerResultMessage
163 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
165 struct GNUNET_MessageHeader header;
170 uint32_t type GNUNET_PACKED;
173 * Length of the PUT path that follows (if tracked).
175 uint32_t put_path_length GNUNET_PACKED;
178 * Length of the GET path that follows (if tracked).
180 uint32_t get_path_length GNUNET_PACKED;
183 * When does the content expire?
185 struct GNUNET_TIME_AbsoluteNBO expiration_time;
188 * The key of the corresponding GET request.
190 struct GNUNET_HashCode key;
192 /* put path (if tracked) */
194 /* get path (if tracked) */
204 struct PeerGetMessage
207 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_GET
209 struct GNUNET_MessageHeader header;
214 uint32_t options GNUNET_PACKED;
217 * Desired content type.
219 uint32_t type GNUNET_PACKED;
224 uint32_t hop_count GNUNET_PACKED;
227 * Desired replication level for this request.
229 uint32_t desired_replication_level GNUNET_PACKED;
232 * Size of the extended query.
234 uint32_t xquery_size;
237 * Bloomfilter mutator.
242 * Bloomfilter (for peer identities) to stop circular routes
244 char bloomfilter[DHT_BLOOM_SIZE];
247 * The key we are looking for.
249 struct GNUNET_HashCode key;
253 /* result bloomfilter */
256 GNUNET_NETWORK_STRUCT_END
259 * Linked list of messages to send to a particular other peer.
261 struct P2PPendingMessage
264 * Pointer to next item in the list
266 struct P2PPendingMessage *next;
269 * Pointer to previous item in the list
271 struct P2PPendingMessage *prev;
274 * Message importance level. FIXME: used? useful?
276 unsigned int importance;
279 * When does this message time out?
281 struct GNUNET_TIME_Absolute timeout;
284 * Actual message to be sent, allocated at the end of the struct:
285 * // msg = (cast) &pm[1];
286 * // memcpy (&pm[1], data, len);
288 const struct GNUNET_MessageHeader *msg;
294 * Entry for a peer in a bucket.
299 * Next peer entry (DLL)
301 struct PeerInfo *next;
304 * Prev peer entry (DLL)
306 struct PeerInfo *prev;
309 * Count of outstanding messages for peer.
311 unsigned int pending_count;
314 * Head of pending messages to be sent to this peer.
316 struct P2PPendingMessage *head;
319 * Tail of pending messages to be sent to this peer.
321 struct P2PPendingMessage *tail;
324 * Core handle for sending messages to this peer.
326 struct GNUNET_CORE_TransmitHandle *th;
329 * Task for scheduling preference updates
331 GNUNET_SCHEDULER_TaskIdentifier preference_task;
334 * What is the identity of the peer?
336 struct GNUNET_PeerIdentity id;
340 * What is the average latency for replies received?
342 struct GNUNET_TIME_Relative latency;
345 * Transport level distance to peer.
347 unsigned int distance;
354 * Peers are grouped into buckets.
361 struct PeerInfo *head;
366 struct PeerInfo *tail;
369 * Number of peers in the bucket.
371 unsigned int peers_size;
376 * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
378 static unsigned int closest_bucket;
381 * How many peers have we added since we sent out our last
384 static unsigned int newly_found_peers;
387 * Option for testing that disables the 'connect' function of the DHT.
389 static int disable_try_connect;
392 * The buckets. Array of size MAX_BUCKET_SIZE. Offset 0 means 0 bits matching.
394 static struct PeerBucket k_buckets[MAX_BUCKETS];
397 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
399 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
402 * Maximum size for each bucket.
404 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
407 * Task that sends FIND PEER requests.
409 static GNUNET_SCHEDULER_TaskIdentifier find_peer_task;
412 * Identity of this peer.
414 static struct GNUNET_PeerIdentity my_identity;
419 static struct GNUNET_CORE_Handle *coreAPI;
424 static struct GNUNET_ATS_PerformanceHandle *atsAPI;
429 * Find the optimal bucket for this key.
431 * @param hc the hashcode to compare our identity to
432 * @return the proper bucket index, or GNUNET_SYSERR
433 * on error (same hashcode)
436 find_bucket (const struct GNUNET_HashCode * hc)
440 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
441 if (bits == MAX_BUCKETS)
443 /* How can all bits match? Got my own ID? */
445 return GNUNET_SYSERR;
447 return MAX_BUCKETS - bits - 1;
452 * Let GNUnet core know that we like the given peer.
454 * @param cls the 'struct PeerInfo' of the peer
455 * @param tc scheduler context.
458 update_core_preference (void *cls,
459 const struct GNUNET_SCHEDULER_TaskContext *tc)
461 struct PeerInfo *peer = cls;
463 unsigned int matching;
466 peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
467 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
470 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
471 &peer->id.hashPubKey);
474 bucket = find_bucket (&peer->id.hashPubKey);
475 if (bucket == GNUNET_SYSERR)
479 GNUNET_assert (k_buckets[bucket].peers_size != 0);
480 preference = (1LL << matching) / k_buckets[bucket].peers_size;
484 peer->preference_task =
485 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
486 &update_core_preference, peer);
489 GNUNET_STATISTICS_update (GDS_stats,
490 gettext_noop ("# Preference updates given to core"),
492 GNUNET_ATS_change_preference (atsAPI, &peer->id,
493 GNUNET_ATS_PREFERENCE_BANDWIDTH,
494 (double) preference, GNUNET_ATS_PREFERENCE_END);
495 peer->preference_task =
496 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
497 &update_core_preference, peer);
504 * Closure for 'add_known_to_bloom'.
506 struct BloomConstructorContext
509 * Bloom filter under construction.
511 struct GNUNET_CONTAINER_BloomFilter *bloom;
521 * Add each of the peers we already know to the bloom filter of
522 * the request so that we don't get duplicate HELLOs.
524 * @param cls the 'struct BloomConstructorContext'.
525 * @param key peer identity to add to the bloom filter
526 * @param value value the peer information (unused)
527 * @return GNUNET_YES (we should continue to iterate)
530 add_known_to_bloom (void *cls, const struct GNUNET_HashCode * key, void *value)
532 struct BloomConstructorContext *ctx = cls;
533 struct GNUNET_HashCode mh;
535 GNUNET_BLOCK_mingle_hash (key, ctx->bf_mutator, &mh);
536 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
537 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
538 GNUNET_h2s (key), ctx->bf_mutator);
539 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
545 * Task to send a find peer message for our own peer identifier
546 * so that we can find the closest peers in the network to ourselves
547 * and attempt to connect to them.
549 * @param cls closure for this task
550 * @param tc the context under which the task is running
553 send_find_peer_message (void *cls,
554 const struct GNUNET_SCHEDULER_TaskContext *tc)
556 struct GNUNET_TIME_Relative next_send_time;
557 struct BloomConstructorContext bcc;
558 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
560 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
561 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
563 if (newly_found_peers > bucket_size)
565 /* If we are finding many peers already, no need to send out our request right now! */
567 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
568 &send_find_peer_message, NULL);
569 newly_found_peers = 0;
573 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
575 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
576 GNUNET_CONSTANTS_BLOOMFILTER_K);
577 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
579 GNUNET_STATISTICS_update (GDS_stats,
580 gettext_noop ("# FIND PEER messages initiated"), 1,
583 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
584 GNUNET_CONSTANTS_BLOOMFILTER_K);
585 // FIXME: pass priority!?
586 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
587 GNUNET_DHT_RO_FIND_PEER,
588 FIND_PEER_REPLICATION_LEVEL, 0,
589 &my_identity.hashPubKey, NULL, 0, bcc.bloom,
590 bcc.bf_mutator, peer_bf);
591 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
592 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
593 /* schedule next round */
594 next_send_time.rel_value =
595 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
596 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
597 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value /
598 (newly_found_peers + 1));
599 newly_found_peers = 0;
601 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
607 * Method called whenever a peer connects.
610 * @param peer peer identity this notification is about
611 * @param atsi performance data
612 * @param atsi_count number of records in 'atsi'
615 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
616 const struct GNUNET_ATS_Information *atsi,
617 unsigned int atsi_count)
619 struct PeerInfo *ret;
622 /* Check for connect to self message */
623 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected %s to %s\n",
626 GNUNET_i2s (&my_identity), GNUNET_h2s (&peer->hashPubKey));
628 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
634 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), 1,
636 peer_bucket = find_bucket (&peer->hashPubKey);
637 GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
638 ret = GNUNET_malloc (sizeof (struct PeerInfo));
640 ret->latency = latency;
641 ret->distance = distance;
644 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
645 k_buckets[peer_bucket].tail, ret);
646 k_buckets[peer_bucket].peers_size++;
647 closest_bucket = GNUNET_MAX (closest_bucket, peer_bucket);
648 if ((peer_bucket > 0) && (k_buckets[peer_bucket].peers_size <= bucket_size))
650 ret->preference_task =
651 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
654 GNUNET_assert (GNUNET_OK ==
655 GNUNET_CONTAINER_multihashmap_put (all_known_peers,
656 &peer->hashPubKey, ret,
657 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
658 if (1 == GNUNET_CONTAINER_multihashmap_size (all_known_peers))
660 /* got a first connection, good time to start with FIND PEER requests... */
661 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
667 * Method called whenever a peer disconnects.
670 * @param peer peer identity this notification is about
673 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
675 struct PeerInfo *to_remove;
677 struct P2PPendingMessage *pos;
678 unsigned int discarded;
680 /* Check for disconnect from self message */
681 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
683 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnected %s from %s\n",
684 GNUNET_i2s (&my_identity), GNUNET_h2s (&peer->hashPubKey));
686 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
687 if (NULL == to_remove)
692 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), -1,
694 GNUNET_assert (GNUNET_YES ==
695 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
698 if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
700 GNUNET_SCHEDULER_cancel (to_remove->preference_task);
701 to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
703 current_bucket = find_bucket (&to_remove->id.hashPubKey);
704 GNUNET_assert (current_bucket >= 0);
705 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
706 k_buckets[current_bucket].tail, to_remove);
707 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
708 k_buckets[current_bucket].peers_size--;
709 while ((closest_bucket > 0) && (k_buckets[closest_bucket].peers_size == 0))
712 if (to_remove->th != NULL)
714 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
715 to_remove->th = NULL;
718 while (NULL != (pos = to_remove->head))
720 GNUNET_CONTAINER_DLL_remove (to_remove->head, to_remove->tail, pos);
724 GNUNET_STATISTICS_update (GDS_stats,
726 ("# Queued messages discarded (peer disconnected)"),
727 discarded, GNUNET_NO);
728 GNUNET_free (to_remove);
733 * Called when core is ready to send a message we asked for
734 * out to the destination.
736 * @param cls the 'struct PeerInfo' of the target peer
737 * @param size number of bytes available in buf
738 * @param buf where the callee should write the message
739 * @return number of bytes written to buf
742 core_transmit_notify (void *cls, size_t size, void *buf)
744 struct PeerInfo *peer = cls;
746 struct P2PPendingMessage *pending;
751 while ((NULL != (pending = peer->head)) &&
752 (GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value == 0))
754 peer->pending_count--;
755 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
756 GNUNET_free (pending);
760 /* no messages pending */
766 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
768 GNUNET_TIME_absolute_get_remaining
769 (pending->timeout), &peer->id,
770 ntohs (pending->msg->size),
771 &core_transmit_notify, peer);
772 GNUNET_break (NULL != peer->th);
776 while ((NULL != (pending = peer->head)) &&
777 (size - off >= (msize = ntohs (pending->msg->size))))
779 GNUNET_STATISTICS_update (GDS_stats,
781 ("# Bytes transmitted to other peers"), msize,
783 memcpy (&cbuf[off], pending->msg, msize);
785 peer->pending_count--;
786 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
787 GNUNET_free (pending);
789 if (peer->head != NULL)
792 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
794 GNUNET_TIME_absolute_get_remaining
795 (pending->timeout), &peer->id, msize,
796 &core_transmit_notify, peer);
797 GNUNET_break (NULL != peer->th);
804 * Transmit all messages in the peer's message queue.
806 * @param peer message queue to process
809 process_peer_queue (struct PeerInfo *peer)
811 struct P2PPendingMessage *pending;
813 if (NULL == (pending = peer->head))
815 if (NULL != peer->th)
817 GNUNET_STATISTICS_update (GDS_stats,
819 ("# Bytes of bandwdith requested from core"),
820 ntohs (pending->msg->size), GNUNET_NO);
822 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
824 GNUNET_TIME_absolute_get_remaining
825 (pending->timeout), &peer->id,
826 ntohs (pending->msg->size),
827 &core_transmit_notify, peer);
828 GNUNET_break (NULL != peer->th);
833 * To how many peers should we (on average) forward the request to
834 * obtain the desired target_replication count (on average).
836 * @param hop_count number of hops the message has traversed
837 * @param target_replication the number of total paths desired
838 * @return Some number of peers to forward the message to
841 get_forward_count (uint32_t hop_count, uint32_t target_replication)
843 uint32_t random_value;
844 uint32_t forward_count;
847 if (hop_count > GDS_NSE_get () * 6.0)
849 /* forcefully terminate */
852 if (hop_count > GDS_NSE_get () * 4.0)
854 /* Once we have reached our ideal number of hops, only forward to 1 peer */
857 /* bound by system-wide maximum */
859 GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
861 1 + (target_replication - 1.0) / (GDS_NSE_get () +
862 ((float) (target_replication - 1.0) *
864 /* Set forward count to floor of target_value */
865 forward_count = (uint32_t) target_value;
866 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
867 target_value = target_value - forward_count;
869 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
870 if (random_value < (target_value * UINT32_MAX))
872 return forward_count;
877 * Compute the distance between have and target as a 32-bit value.
878 * Differences in the lower bits must count stronger than differences
879 * in the higher bits.
881 * @return 0 if have==target, otherwise a number
882 * that is larger as the distance between
883 * the two hash codes increases
886 get_distance (const struct GNUNET_HashCode * target, const struct GNUNET_HashCode * have)
893 /* We have to represent the distance between two 2^9 (=512)-bit
894 * numbers as a 2^5 (=32)-bit number with "0" being used for the
895 * two numbers being identical; furthermore, we need to
896 * guarantee that a difference in the number of matching
897 * bits is always represented in the result.
899 * We use 2^32/2^9 numerical values to distinguish between
900 * hash codes that have the same LSB bit distance and
901 * use the highest 2^9 bits of the result to signify the
902 * number of (mis)matching LSB bits; if we have 0 matching
903 * and hence 512 mismatching LSB bits we return -1 (since
904 * 512 itself cannot be represented with 9 bits) */
906 /* first, calculate the most significant 9 bits of our
907 * result, aka the number of LSBs */
908 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
909 /* bucket is now a value between 0 and 512 */
911 return 0; /* perfect match */
913 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
914 * below, we'd end up with max+1 (overflow)) */
916 /* calculate the most significant bits of the final result */
917 msb = (512 - bucket) << (32 - 9);
918 /* calculate the 32-9 least significant bits of the final result by
919 * looking at the differences in the 32-9 bits following the
920 * mismatching bit at 'bucket' */
923 (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
925 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
926 GNUNET_CRYPTO_hash_get_bit (have, i))
927 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
928 * last bit set will be 31 -- if
929 * i does not reach 512 first... */
936 * Check whether my identity is closer than any known peers. If a
937 * non-null bloomfilter is given, check if this is the closest peer
938 * that hasn't already been routed to.
940 * @param key hash code to check closeness to
941 * @param bloom bloomfilter, exclude these entries from the decision
942 * @return GNUNET_YES if node location is closest,
943 * GNUNET_NO otherwise.
946 am_closest_peer (const struct GNUNET_HashCode * key,
947 const struct GNUNET_CONTAINER_BloomFilter *bloom)
953 struct PeerInfo *pos;
955 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (struct GNUNET_HashCode)))
957 bucket_num = find_bucket (key);
958 GNUNET_assert (bucket_num >= 0);
959 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
960 pos = k_buckets[bucket_num].head;
962 while ((pos != NULL) && (count < bucket_size))
964 if ((bloom != NULL) &&
966 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
969 continue; /* Skip already checked entries */
971 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
972 if (other_bits > bits)
974 if (other_bits == bits) /* We match the same number of bits */
978 /* No peers closer, we are the closest! */
984 * Select a peer from the routing table that would be a good routing
985 * destination for sending a message for "key". The resulting peer
986 * must not be in the set of blocked peers.<p>
988 * Note that we should not ALWAYS select the closest peer to the
989 * target, peers further away from the target should be chosen with
990 * exponentially declining probability.
992 * FIXME: double-check that this is fine
995 * @param key the key we are selecting a peer to route to
996 * @param bloom a bloomfilter containing entries this request has seen already
997 * @param hops how many hops has this message traversed thus far
998 * @return Peer to route to, or NULL on error
1000 static struct PeerInfo *
1001 select_peer (const struct GNUNET_HashCode * key,
1002 const struct GNUNET_CONTAINER_BloomFilter *bloom, uint32_t hops)
1006 unsigned int selected;
1007 struct PeerInfo *pos;
1009 unsigned int smallest_distance;
1010 struct PeerInfo *chosen;
1012 if (hops >= GDS_NSE_get ())
1014 /* greedy selection (closest peer that is not in bloomfilter) */
1015 smallest_distance = UINT_MAX;
1017 for (bc = 0; bc <= closest_bucket; bc++)
1019 pos = k_buckets[bc].head;
1021 while ((pos != NULL) && (count < bucket_size))
1023 if ((bloom == NULL) ||
1025 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1027 dist = get_distance (key, &pos->id.hashPubKey);
1028 if (dist < smallest_distance)
1031 smallest_distance = dist;
1036 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1037 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1038 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1039 GNUNET_STATISTICS_update (GDS_stats,
1041 ("# Peers excluded from routing due to Bloomfilter"),
1049 GNUNET_STATISTICS_update (GDS_stats,
1050 gettext_noop ("# Peer selection failed"), 1,
1055 /* select "random" peer */
1056 /* count number of peers that are available and not filtered */
1058 for (bc = 0; bc <= closest_bucket; bc++)
1060 pos = k_buckets[bc].head;
1061 while ((pos != NULL) && (count < bucket_size))
1063 if ((bloom != NULL) &&
1065 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1067 GNUNET_STATISTICS_update (GDS_stats,
1069 ("# Peers excluded from routing due to Bloomfilter"),
1071 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1072 "Excluded peer `%s' due to BF match in random routing for %s\n",
1073 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1075 continue; /* Ignore bloomfiltered peers */
1081 if (count == 0) /* No peers to select from! */
1083 GNUNET_STATISTICS_update (GDS_stats,
1084 gettext_noop ("# Peer selection failed"), 1,
1088 /* Now actually choose a peer */
1089 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1091 for (bc = 0; bc <= closest_bucket; bc++)
1093 pos = k_buckets[bc].head;
1094 while ((pos != NULL) && (count < bucket_size))
1096 if ((bloom != NULL) &&
1098 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1101 continue; /* Ignore bloomfiltered peers */
1103 if (0 == selected--)
1114 * Compute the set of peers that the given request should be
1117 * @param key routing key
1118 * @param bloom bloom filter excluding peers as targets, all selected
1119 * peers will be added to the bloom filter
1120 * @param hop_count number of hops the request has traversed so far
1121 * @param target_replication desired number of replicas
1122 * @param targets where to store an array of target peers (to be
1123 * free'd by the caller)
1124 * @return number of peers returned in 'targets'.
1127 get_target_peers (const struct GNUNET_HashCode * key,
1128 struct GNUNET_CONTAINER_BloomFilter *bloom,
1129 uint32_t hop_count, uint32_t target_replication,
1130 struct PeerInfo ***targets)
1134 struct PeerInfo **rtargets;
1135 struct PeerInfo *nxt;
1137 GNUNET_assert (NULL != bloom);
1138 ret = get_forward_count (hop_count, target_replication);
1144 rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1145 for (off = 0; off < ret; off++)
1147 nxt = select_peer (key, bloom, hop_count);
1150 rtargets[off] = nxt;
1151 GNUNET_break (GNUNET_NO ==
1152 GNUNET_CONTAINER_bloomfilter_test (bloom,
1153 &nxt->id.hashPubKey));
1154 GNUNET_CONTAINER_bloomfilter_add (bloom, &rtargets[off]->id.hashPubKey);
1156 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1157 "Selected %u/%u peers at hop %u for %s (target was %u)\n", off,
1158 GNUNET_CONTAINER_multihashmap_size (all_known_peers),
1159 (unsigned int) hop_count, GNUNET_h2s (key), ret);
1162 GNUNET_free (rtargets);
1166 *targets = rtargets;
1172 * Perform a PUT operation. Forwards the given request to other
1173 * peers. Does not store the data locally. Does not give the
1174 * data to local clients. May do nothing if this is the only
1175 * peer in the network (or if we are the closest peer in the
1178 * @param type type of the block
1179 * @param options routing options
1180 * @param desired_replication_level desired replication count
1181 * @param expiration_time when does the content expire
1182 * @param hop_count how many hops has this message traversed so far
1183 * @param bf Bloom filter of peers this PUT has already traversed
1184 * @param key key for the content
1185 * @param put_path_length number of entries in put_path
1186 * @param put_path peers this request has traversed so far (if tracked)
1187 * @param data payload to store
1188 * @param data_size number of bytes in data
1191 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1192 enum GNUNET_DHT_RouteOption options,
1193 uint32_t desired_replication_level,
1194 struct GNUNET_TIME_Absolute expiration_time,
1196 struct GNUNET_CONTAINER_BloomFilter *bf,
1197 const struct GNUNET_HashCode * key,
1198 unsigned int put_path_length,
1199 struct GNUNET_PeerIdentity *put_path,
1200 const void *data, size_t data_size)
1202 unsigned int target_count;
1204 struct PeerInfo **targets;
1205 struct PeerInfo *target;
1206 struct P2PPendingMessage *pending;
1208 struct PeerPutMessage *ppm;
1209 struct GNUNET_PeerIdentity *pp;
1211 GNUNET_assert (NULL != bf);
1212 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1213 "Adding myself (%s) to PUT bloomfilter for %s\n",
1214 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1215 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1216 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1219 get_target_peers (key, bf, hop_count, desired_replication_level,
1221 if (0 == target_count)
1223 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1224 "Routing PUT for %s terminates after %u hops at %s\n",
1225 GNUNET_h2s (key), (unsigned int) hop_count,
1226 GNUNET_i2s (&my_identity));
1230 put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1231 sizeof (struct PeerPutMessage);
1232 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1234 put_path_length = 0;
1235 msize = data_size + sizeof (struct PeerPutMessage);
1237 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1240 GNUNET_free (targets);
1243 GNUNET_STATISTICS_update (GDS_stats,
1245 ("# PUT messages queued for transmission"),
1246 target_count, GNUNET_NO);
1247 for (i = 0; i < target_count; i++)
1249 target = targets[i];
1250 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1252 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1254 continue; /* skip */
1256 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1257 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1258 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1259 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1260 pending->importance = 0; /* FIXME */
1261 pending->timeout = expiration_time;
1262 ppm = (struct PeerPutMessage *) &pending[1];
1263 pending->msg = &ppm->header;
1264 ppm->header.size = htons (msize);
1265 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1266 ppm->options = htonl (options);
1267 ppm->type = htonl (type);
1268 ppm->hop_count = htonl (hop_count + 1);
1269 ppm->desired_replication_level = htonl (desired_replication_level);
1270 ppm->put_path_length = htonl (put_path_length);
1271 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1272 GNUNET_break (GNUNET_YES ==
1273 GNUNET_CONTAINER_bloomfilter_test (bf,
1274 &target->id.hashPubKey));
1275 GNUNET_assert (GNUNET_OK ==
1276 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1280 pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1281 memcpy (pp, put_path,
1282 sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1283 memcpy (&pp[put_path_length], data, data_size);
1284 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1285 target->pending_count++;
1286 process_peer_queue (target);
1288 GNUNET_free (targets);
1293 * Perform a GET operation. Forwards the given request to other
1294 * peers. Does not lookup the key locally. May do nothing if this is
1295 * the only peer in the network (or if we are the closest peer in the
1298 * @param type type of the block
1299 * @param options routing options
1300 * @param desired_replication_level desired replication count
1301 * @param hop_count how many hops did this request traverse so far?
1302 * @param key key for the content
1303 * @param xquery extended query
1304 * @param xquery_size number of bytes in xquery
1305 * @param reply_bf bloomfilter to filter duplicates
1306 * @param reply_bf_mutator mutator for reply_bf
1307 * @param peer_bf filter for peers not to select (again)
1310 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1311 enum GNUNET_DHT_RouteOption options,
1312 uint32_t desired_replication_level,
1313 uint32_t hop_count, const struct GNUNET_HashCode * key,
1314 const void *xquery, size_t xquery_size,
1315 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1316 uint32_t reply_bf_mutator,
1317 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1319 unsigned int target_count;
1321 struct PeerInfo **targets;
1322 struct PeerInfo *target;
1323 struct P2PPendingMessage *pending;
1325 struct PeerGetMessage *pgm;
1327 size_t reply_bf_size;
1329 GNUNET_assert (NULL != peer_bf);
1330 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1333 get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1335 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1336 "Adding myself (%s) to GET bloomfilter for %s\n",
1337 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1338 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity.hashPubKey);
1339 if (0 == target_count)
1341 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1342 "Routing GET for %s terminates after %u hops at %s\n",
1343 GNUNET_h2s (key), (unsigned int) hop_count,
1344 GNUNET_i2s (&my_identity));
1347 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1348 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1349 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1352 GNUNET_free (targets);
1355 GNUNET_STATISTICS_update (GDS_stats,
1357 ("# GET messages queued for transmission"),
1358 target_count, GNUNET_NO);
1359 /* forward request */
1360 for (i = 0; i < target_count; i++)
1362 target = targets[i];
1363 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1365 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1367 continue; /* skip */
1369 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1370 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1371 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1372 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1373 pending->importance = 0; /* FIXME */
1374 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1375 pgm = (struct PeerGetMessage *) &pending[1];
1376 pending->msg = &pgm->header;
1377 pgm->header.size = htons (msize);
1378 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1379 pgm->options = htonl (options);
1380 pgm->type = htonl (type);
1381 pgm->hop_count = htonl (hop_count + 1);
1382 pgm->desired_replication_level = htonl (desired_replication_level);
1383 pgm->xquery_size = htonl (xquery_size);
1384 pgm->bf_mutator = reply_bf_mutator;
1385 GNUNET_break (GNUNET_YES ==
1386 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1387 &target->id.hashPubKey));
1388 GNUNET_assert (GNUNET_OK ==
1389 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1393 xq = (char *) &pgm[1];
1394 memcpy (xq, xquery, xquery_size);
1395 if (NULL != reply_bf)
1396 GNUNET_assert (GNUNET_OK ==
1397 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1401 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1402 target->pending_count++;
1403 process_peer_queue (target);
1405 GNUNET_free (targets);
1410 * Handle a reply (route to origin). Only forwards the reply back to
1411 * the given peer. Does not do local caching or forwarding to local
1414 * @param target neighbour that should receive the block (if still connected)
1415 * @param type type of the block
1416 * @param expiration_time when does the content expire
1417 * @param key key for the content
1418 * @param put_path_length number of entries in put_path
1419 * @param put_path peers the original PUT traversed (if tracked)
1420 * @param get_path_length number of entries in put_path
1421 * @param get_path peers this reply has traversed so far (if tracked)
1422 * @param data payload of the reply
1423 * @param data_size number of bytes in data
1426 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1427 enum GNUNET_BLOCK_Type type,
1428 struct GNUNET_TIME_Absolute expiration_time,
1429 const struct GNUNET_HashCode * key,
1430 unsigned int put_path_length,
1431 const struct GNUNET_PeerIdentity *put_path,
1432 unsigned int get_path_length,
1433 const struct GNUNET_PeerIdentity *get_path,
1434 const void *data, size_t data_size)
1436 struct PeerInfo *pi;
1437 struct P2PPendingMessage *pending;
1439 struct PeerResultMessage *prm;
1440 struct GNUNET_PeerIdentity *paths;
1443 data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1445 sizeof (struct GNUNET_PeerIdentity);
1446 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1448 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1450 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1451 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1456 pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers, &target->hashPubKey);
1459 /* peer disconnected in the meantime, drop reply */
1462 if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1465 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1470 GNUNET_STATISTICS_update (GDS_stats,
1472 ("# RESULT messages queued for transmission"), 1,
1474 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1475 pending->importance = 0; /* FIXME */
1476 pending->timeout = expiration_time;
1477 prm = (struct PeerResultMessage *) &pending[1];
1478 pending->msg = &prm->header;
1479 prm->header.size = htons (msize);
1480 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1481 prm->type = htonl (type);
1482 prm->put_path_length = htonl (put_path_length);
1483 prm->get_path_length = htonl (get_path_length);
1484 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1486 paths = (struct GNUNET_PeerIdentity *) &prm[1];
1487 memcpy (paths, put_path,
1488 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1489 memcpy (&paths[put_path_length], get_path,
1490 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1491 memcpy (&paths[put_path_length + get_path_length], data, data_size);
1492 GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1493 pi->pending_count++;
1494 process_peer_queue (pi);
1499 * To be called on core init/fail.
1501 * @param cls service closure
1502 * @param server handle to the server for this service
1503 * @param identity the public identity of this peer
1506 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1507 const struct GNUNET_PeerIdentity *identity)
1509 GNUNET_assert (server != NULL);
1510 my_identity = *identity;
1515 * Core handler for p2p put requests.
1517 * @param cls closure
1518 * @param peer sender of the request
1519 * @param message message
1520 * @param peer peer identity this notification is about
1521 * @param atsi performance data
1522 * @param atsi_count number of records in 'atsi'
1523 * @return GNUNET_OK to keep the connection open,
1524 * GNUNET_SYSERR to close it (signal serious error)
1527 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1528 const struct GNUNET_MessageHeader *message,
1529 const struct GNUNET_ATS_Information *atsi,
1530 unsigned int atsi_count)
1532 const struct PeerPutMessage *put;
1533 const struct GNUNET_PeerIdentity *put_path;
1534 const void *payload;
1537 size_t payload_size;
1538 enum GNUNET_DHT_RouteOption options;
1539 struct GNUNET_CONTAINER_BloomFilter *bf;
1540 struct GNUNET_HashCode test_key;
1542 msize = ntohs (message->size);
1543 if (msize < sizeof (struct PeerPutMessage))
1545 GNUNET_break_op (0);
1548 put = (const struct PeerPutMessage *) message;
1549 putlen = ntohl (put->put_path_length);
1551 sizeof (struct PeerPutMessage) +
1552 putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1554 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1556 GNUNET_break_op (0);
1559 GNUNET_STATISTICS_update (GDS_stats,
1560 gettext_noop ("# P2P PUT requests received"), 1,
1562 put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1563 payload = &put_path[putlen];
1564 options = ntohl (put->options);
1566 msize - (sizeof (struct PeerPutMessage) +
1567 putlen * sizeof (struct GNUNET_PeerIdentity));
1568 switch (GNUNET_BLOCK_get_key
1569 (GDS_block_context, ntohl (put->type), payload, payload_size,
1573 if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1575 GNUNET_break_op (0);
1580 GNUNET_break_op (0);
1583 /* cannot verify, good luck */
1586 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1587 GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1588 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1589 GNUNET_CONSTANTS_BLOOMFILTER_K);
1590 GNUNET_break_op (GNUNET_YES ==
1591 GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1593 struct GNUNET_PeerIdentity pp[putlen + 1];
1595 /* extend 'put path' by sender */
1596 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1598 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1605 /* give to local clients */
1606 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1607 &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1608 payload_size, payload);
1610 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1611 (am_closest_peer (&put->key, bf)))
1612 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1613 (put->expiration_time), &put->key, putlen, pp,
1614 ntohl (put->type), payload_size, payload);
1615 /* route to other peers */
1616 GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1617 ntohl (put->desired_replication_level),
1618 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1619 ntohl (put->hop_count), bf, &put->key, putlen,
1620 pp, payload, payload_size);
1622 GNUNET_CONTAINER_bloomfilter_free (bf);
1623 GDS_CLIENTS_process_put (options,
1625 ntohl (put->hop_count),
1626 ntohl (put->desired_replication_level),
1628 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1637 * We have received a FIND PEER request. Send matching
1640 * @param sender sender of the FIND PEER request
1641 * @param key peers close to this key are desired
1642 * @param bf peers matching this bf are excluded
1643 * @param bf_mutator mutator for bf
1646 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1647 const struct GNUNET_HashCode * key,
1648 struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1651 struct PeerBucket *bucket;
1652 struct PeerInfo *peer;
1653 unsigned int choice;
1654 struct GNUNET_HashCode mhash;
1655 const struct GNUNET_HELLO_Message *hello;
1657 /* first, check about our own HELLO */
1658 if (NULL != GDS_my_hello)
1660 GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1662 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1664 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1665 GNUNET_TIME_relative_to_absolute
1666 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1667 key, 0, NULL, 0, NULL, GDS_my_hello,
1668 GNUNET_HELLO_size ((const struct
1669 GNUNET_HELLO_Message *)
1674 GNUNET_STATISTICS_update (GDS_stats,
1676 ("# FIND PEER requests ignored due to Bloomfilter"),
1682 GNUNET_STATISTICS_update (GDS_stats,
1684 ("# FIND PEER requests ignored due to lack of HELLO"),
1688 /* then, also consider sending a random HELLO from the closest bucket */
1689 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (struct GNUNET_HashCode)))
1690 bucket_idx = closest_bucket;
1692 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1693 if (bucket_idx == GNUNET_SYSERR)
1695 bucket = &k_buckets[bucket_idx];
1696 if (bucket->peers_size == 0)
1699 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1700 peer = bucket->head;
1703 GNUNET_assert (peer != NULL);
1707 choice = bucket->peers_size;
1712 return; /* no non-masked peer available */
1714 peer = bucket->head;
1715 GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1716 hello = GDS_HELLO_get (&peer->id);
1718 while ((hello == NULL) ||
1719 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1720 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1721 GNUNET_TIME_relative_to_absolute
1722 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1723 0, NULL, 0, NULL, hello,
1724 GNUNET_HELLO_size (hello));
1729 * Core handler for p2p get requests.
1731 * @param cls closure
1732 * @param peer sender of the request
1733 * @param message message
1734 * @param peer peer identity this notification is about
1735 * @param atsi performance data
1736 * @param atsi_count number of records in 'atsi'
1737 * @return GNUNET_OK to keep the connection open,
1738 * GNUNET_SYSERR to close it (signal serious error)
1741 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1742 const struct GNUNET_MessageHeader *message,
1743 const struct GNUNET_ATS_Information *atsi,
1744 unsigned int atsi_count)
1746 struct PeerGetMessage *get;
1747 uint32_t xquery_size;
1748 size_t reply_bf_size;
1750 enum GNUNET_BLOCK_Type type;
1751 enum GNUNET_DHT_RouteOption options;
1752 enum GNUNET_BLOCK_EvaluationResult eval;
1753 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1754 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1758 memcmp (peer, &my_identity,
1759 sizeof (struct GNUNET_PeerIdentity)));
1760 /* parse and validate message */
1761 msize = ntohs (message->size);
1762 if (msize < sizeof (struct PeerGetMessage))
1764 GNUNET_break_op (0);
1767 get = (struct PeerGetMessage *) message;
1768 xquery_size = ntohl (get->xquery_size);
1769 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1771 GNUNET_break_op (0);
1774 GNUNET_STATISTICS_update (GDS_stats,
1775 gettext_noop ("# P2P GET requests received"), 1,
1777 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1778 type = ntohl (get->type);
1779 options = ntohl (get->options);
1780 xquery = (const char *) &get[1];
1782 if (reply_bf_size > 0)
1784 GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1785 GNUNET_CONSTANTS_BLOOMFILTER_K);
1787 GNUNET_BLOCK_evaluate (GDS_block_context, type, &get->key, &reply_bf,
1788 get->bf_mutator, xquery, xquery_size, NULL, 0);
1789 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1791 /* request invalid or block type not supported */
1792 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1793 if (NULL != reply_bf)
1794 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1798 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1799 GNUNET_CONSTANTS_BLOOMFILTER_K);
1800 GNUNET_break_op (GNUNET_YES ==
1801 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1802 &peer->hashPubKey));
1803 /* remember request for routing replies */
1804 GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1805 reply_bf, get->bf_mutator);
1806 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GET for %s at %s after %u hops\n",
1807 GNUNET_h2s (&get->key), GNUNET_i2s (&my_identity),
1808 (unsigned int) ntohl (get->hop_count));
1809 /* local lookup (this may update the reply_bf) */
1810 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1811 (am_closest_peer (&get->key, peer_bf)))
1813 if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1815 GNUNET_STATISTICS_update (GDS_stats,
1817 ("# P2P FIND PEER requests processed"), 1,
1819 handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
1824 GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
1825 &reply_bf, get->bf_mutator);
1830 GNUNET_STATISTICS_update (GDS_stats,
1831 gettext_noop ("# P2P GET requests ONLY routed"),
1836 GDS_CLIENTS_process_get (options,
1838 ntohl(get->hop_count),
1839 ntohl(get->desired_replication_level),
1843 /* P2P forwarding */
1844 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1845 GDS_NEIGHBOURS_handle_get (type, options,
1846 ntohl (get->desired_replication_level),
1847 ntohl (get->hop_count), &get->key, xquery,
1848 xquery_size, reply_bf, get->bf_mutator, peer_bf);
1850 if (NULL != reply_bf)
1851 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1852 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
1858 * Core handler for p2p result messages.
1860 * @param cls closure
1861 * @param message message
1862 * @param peer peer identity this notification is about
1863 * @param atsi performance data
1864 * @param atsi_count number of records in 'atsi'
1865 * @return GNUNET_YES (do not cut p2p connection)
1868 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1869 const struct GNUNET_MessageHeader *message,
1870 const struct GNUNET_ATS_Information *atsi,
1871 unsigned int atsi_count)
1873 const struct PeerResultMessage *prm;
1874 const struct GNUNET_PeerIdentity *put_path;
1875 const struct GNUNET_PeerIdentity *get_path;
1877 uint32_t get_path_length;
1878 uint32_t put_path_length;
1881 enum GNUNET_BLOCK_Type type;
1883 /* parse and validate message */
1884 msize = ntohs (message->size);
1885 if (msize < sizeof (struct PeerResultMessage))
1887 GNUNET_break_op (0);
1890 prm = (struct PeerResultMessage *) message;
1891 put_path_length = ntohl (prm->put_path_length);
1892 get_path_length = ntohl (prm->get_path_length);
1894 sizeof (struct PeerResultMessage) + (get_path_length +
1896 sizeof (struct GNUNET_PeerIdentity)) ||
1898 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1900 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1902 GNUNET_break_op (0);
1905 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
1907 put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
1908 get_path = &put_path[put_path_length];
1909 type = ntohl (prm->type);
1910 data = (const void *) &get_path[get_path_length];
1912 msize - (sizeof (struct PeerResultMessage) +
1914 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1916 /* if we got a HELLO, consider it for our own routing table */
1917 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
1919 const struct GNUNET_MessageHeader *h;
1920 struct GNUNET_PeerIdentity pid;
1923 /* Should be a HELLO, validate and consider using it! */
1924 if (data_size < sizeof (struct GNUNET_MessageHeader))
1926 GNUNET_break_op (0);
1930 if (data_size != ntohs (h->size))
1932 GNUNET_break_op (0);
1936 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
1938 GNUNET_break_op (0);
1941 if (0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
1943 bucket = find_bucket (&pid.hashPubKey);
1944 if ((bucket >= 0) && (k_buckets[bucket].peers_size < bucket_size))
1946 if (NULL != GDS_transport_handle)
1948 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
1950 disable_try_connect)
1951 GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid);
1957 /* append 'peer' to 'get_path' */
1959 struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
1961 memcpy (xget_path, get_path,
1962 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1963 xget_path[get_path_length] = *peer;
1966 /* forward to local clients */
1967 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
1968 &prm->key, get_path_length, xget_path,
1969 put_path_length, put_path, type, data_size, data);
1971 /* forward to other peers */
1972 GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
1973 &prm->key, put_path_length, put_path, get_path_length,
1974 xget_path, data, data_size);
1977 GDS_CLIENTS_process_get_resp (type,
1982 GNUNET_TIME_absolute_ntoh (
1983 prm->expiration_time),
1993 * Initialize neighbours subsystem.
1995 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1998 GDS_NEIGHBOURS_init ()
2000 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2001 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2002 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2003 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2006 unsigned long long temp_config_num;
2009 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2011 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2013 bucket_size = (unsigned int) temp_config_num;
2014 atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2016 GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
2017 &handle_core_disconnect, NULL, GNUNET_NO, NULL,
2018 GNUNET_NO, core_handlers);
2019 if (coreAPI == NULL)
2020 return GNUNET_SYSERR;
2021 all_known_peers = GNUNET_CONTAINER_multihashmap_create (256);
2027 * Shutdown neighbours subsystem.
2030 GDS_NEIGHBOURS_done ()
2032 if (coreAPI == NULL)
2034 GNUNET_CORE_disconnect (coreAPI);
2036 GNUNET_ATS_performance_done (atsAPI);
2038 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2039 GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2040 all_known_peers = NULL;
2041 if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2043 GNUNET_SCHEDULER_cancel (find_peer_task);
2044 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2049 * Get the ID of the local node.
2051 * @return identity of the local node
2053 struct GNUNET_PeerIdentity *
2054 GDS_NEIGHBOURS_get_id ()
2056 return &my_identity;
2060 /* end of gnunet-service-dht_neighbours.c */