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 (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 * How often to update our preference levels for peers in our routing tables.
75 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
78 * How long at least to wait before sending another find peer request.
80 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
83 * How long at most to wait before sending another find peer request.
85 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10)
88 * How long at most to wait for transmission of a GET request to another peer?
90 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
93 GNUNET_NETWORK_STRUCT_BEGIN
101 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
103 struct GNUNET_MessageHeader header;
108 uint32_t options GNUNET_PACKED;
113 uint32_t type GNUNET_PACKED;
118 uint32_t hop_count GNUNET_PACKED;
121 * Replication level for this message
123 uint32_t desired_replication_level GNUNET_PACKED;
126 * Length of the PUT path that follows (if tracked).
128 uint32_t put_path_length GNUNET_PACKED;
131 * When does the content expire?
133 struct GNUNET_TIME_AbsoluteNBO expiration_time;
136 * Bloomfilter (for peer identities) to stop circular routes
138 char bloomfilter[DHT_BLOOM_SIZE];
141 * The key we are storing under.
145 /* put path (if tracked) */
155 struct PeerResultMessage
158 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
160 struct GNUNET_MessageHeader header;
165 uint32_t type GNUNET_PACKED;
168 * Length of the PUT path that follows (if tracked).
170 uint32_t put_path_length GNUNET_PACKED;
173 * Length of the GET path that follows (if tracked).
175 uint32_t get_path_length GNUNET_PACKED;
178 * When does the content expire?
180 struct GNUNET_TIME_AbsoluteNBO expiration_time;
183 * The key of the corresponding GET request.
187 /* put path (if tracked) */
189 /* get path (if tracked) */
199 struct PeerGetMessage
202 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_GET
204 struct GNUNET_MessageHeader header;
209 uint32_t options GNUNET_PACKED;
212 * Desired content type.
214 uint32_t type GNUNET_PACKED;
219 uint32_t hop_count GNUNET_PACKED;
222 * Desired replication level for this request.
224 uint32_t desired_replication_level GNUNET_PACKED;
227 * Size of the extended query.
229 uint32_t xquery_size;
232 * Bloomfilter mutator.
237 * Bloomfilter (for peer identities) to stop circular routes
239 char bloomfilter[DHT_BLOOM_SIZE];
242 * The key we are looking for.
248 /* result bloomfilter */
251 GNUNET_NETWORK_STRUCT_END
254 * Linked list of messages to send to a particular other peer.
256 struct P2PPendingMessage
259 * Pointer to next item in the list
261 struct P2PPendingMessage *next;
264 * Pointer to previous item in the list
266 struct P2PPendingMessage *prev;
269 * Message importance level. FIXME: used? useful?
271 unsigned int importance;
274 * When does this message time out?
276 struct GNUNET_TIME_Absolute timeout;
279 * Actual message to be sent, allocated at the end of the struct:
280 * // msg = (cast) &pm[1];
281 * // memcpy (&pm[1], data, len);
283 const struct GNUNET_MessageHeader *msg;
289 * Entry for a peer in a bucket.
294 * Next peer entry (DLL)
296 struct PeerInfo *next;
299 * Prev peer entry (DLL)
301 struct PeerInfo *prev;
304 * Count of outstanding messages for peer. FIXME: NEEDED?
305 * FIXME: bound queue size!?
307 unsigned int pending_count;
310 * Head of pending messages to be sent to this peer.
312 struct P2PPendingMessage *head;
315 * Tail of pending messages to be sent to this peer.
317 struct P2PPendingMessage *tail;
320 * Core handle for sending messages to this peer.
322 struct GNUNET_CORE_TransmitHandle *th;
325 * Task for scheduling preference updates
327 GNUNET_SCHEDULER_TaskIdentifier preference_task;
330 * What is the identity of the peer?
332 struct GNUNET_PeerIdentity id;
336 * What is the average latency for replies received?
338 struct GNUNET_TIME_Relative latency;
341 * Transport level distance to peer.
343 unsigned int distance;
350 * Peers are grouped into buckets.
357 struct PeerInfo *head;
362 struct PeerInfo *tail;
365 * Number of peers in the bucket.
367 unsigned int peers_size;
372 * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
374 static unsigned int closest_bucket;
377 * How many peers have we added since we sent out our last
380 static unsigned int newly_found_peers;
383 * The buckets. Array of size MAX_BUCKET_SIZE. Offset 0 means 0 bits matching.
385 static struct PeerBucket k_buckets[MAX_BUCKETS];
388 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
390 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
393 * Maximum size for each bucket.
395 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
398 * Task that sends FIND PEER requests.
400 static GNUNET_SCHEDULER_TaskIdentifier find_peer_task;
403 * Identity of this peer.
405 static struct GNUNET_PeerIdentity my_identity;
410 static struct GNUNET_CORE_Handle *coreAPI;
415 static struct GNUNET_ATS_PerformanceHandle *atsAPI;
420 * Find the optimal bucket for this key.
422 * @param hc the hashcode to compare our identity to
423 * @return the proper bucket index, or GNUNET_SYSERR
424 * on error (same hashcode)
427 find_bucket (const GNUNET_HashCode * hc)
431 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
432 if (bits == MAX_BUCKETS)
434 /* How can all bits match? Got my own ID? */
436 return GNUNET_SYSERR;
438 return MAX_BUCKETS - bits - 1;
443 * Let GNUnet core know that we like the given peer.
445 * @param cls the 'struct PeerInfo' of the peer
446 * @param tc scheduler context.
449 update_core_preference (void *cls,
450 const struct GNUNET_SCHEDULER_TaskContext *tc)
452 struct PeerInfo *peer = cls;
454 unsigned int matching;
457 peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
458 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
461 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
462 &peer->id.hashPubKey);
465 bucket = find_bucket (&peer->id.hashPubKey);
466 if (bucket == GNUNET_SYSERR)
470 GNUNET_assert (k_buckets[bucket].peers_size != 0);
471 preference = (1LL << matching) / k_buckets[bucket].peers_size;
475 peer->preference_task =
476 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
477 &update_core_preference, peer);
480 GNUNET_STATISTICS_update (GDS_stats,
481 gettext_noop ("# Preference updates given to core"),
483 GNUNET_ATS_change_preference (atsAPI, &peer->id,
484 GNUNET_ATS_PREFERENCE_BANDWIDTH,
485 (double) preference, GNUNET_ATS_PREFERENCE_END);
486 peer->preference_task =
487 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
488 &update_core_preference, peer);
495 * Closure for 'add_known_to_bloom'.
497 struct BloomConstructorContext
500 * Bloom filter under construction.
502 struct GNUNET_CONTAINER_BloomFilter *bloom;
512 * Add each of the peers we already know to the bloom filter of
513 * the request so that we don't get duplicate HELLOs.
515 * @param cls the 'struct BloomConstructorContext'.
516 * @param key peer identity to add to the bloom filter
517 * @param value value the peer information (unused)
518 * @return GNUNET_YES (we should continue to iterate)
521 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
523 struct BloomConstructorContext *ctx = cls;
526 GNUNET_BLOCK_mingle_hash (key, ctx->bf_mutator, &mh);
528 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
529 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
530 GNUNET_h2s (key), ctx->bf_mutator);
532 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
538 * Task to send a find peer message for our own peer identifier
539 * so that we can find the closest peers in the network to ourselves
540 * and attempt to connect to them.
542 * @param cls closure for this task
543 * @param tc the context under which the task is running
546 send_find_peer_message (void *cls,
547 const struct GNUNET_SCHEDULER_TaskContext *tc)
549 struct GNUNET_TIME_Relative next_send_time;
550 struct BloomConstructorContext bcc;
551 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
553 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
554 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
556 if (newly_found_peers > bucket_size)
558 /* If we are finding many peers already, no need to send out our request right now! */
560 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
561 &send_find_peer_message, NULL);
562 newly_found_peers = 0;
566 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
568 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
569 GNUNET_CONSTANTS_BLOOMFILTER_K);
570 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
572 GNUNET_STATISTICS_update (GDS_stats,
573 gettext_noop ("# FIND PEER messages initiated"), 1,
576 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
577 GNUNET_CONSTANTS_BLOOMFILTER_K);
578 // FIXME: pass priority!?
579 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
580 GNUNET_DHT_RO_FIND_PEER,
581 FIND_PEER_REPLICATION_LEVEL, 0,
582 &my_identity.hashPubKey, NULL, 0, bcc.bloom,
583 bcc.bf_mutator, peer_bf);
584 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
585 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
586 /* schedule next round */
587 next_send_time.rel_value =
588 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
589 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
590 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value /
591 (newly_found_peers + 1));
592 newly_found_peers = 0;
594 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
600 * Method called whenever a peer connects.
603 * @param peer peer identity this notification is about
604 * @param atsi performance data
605 * @param atsi_count number of records in 'atsi'
608 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
609 const struct GNUNET_ATS_Information *atsi,
610 unsigned int atsi_count)
612 struct PeerInfo *ret;
615 /* Check for connect to self message */
616 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
619 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected %s to %s\n",
620 GNUNET_i2s (&my_identity), GNUNET_h2s (&peer->hashPubKey));
623 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
629 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# Peers connected"), 1,
631 peer_bucket = find_bucket (&peer->hashPubKey);
632 GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
633 ret = GNUNET_malloc (sizeof (struct PeerInfo));
635 ret->latency = latency;
636 ret->distance = distance;
639 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
640 k_buckets[peer_bucket].tail, ret);
641 k_buckets[peer_bucket].peers_size++;
642 closest_bucket = GNUNET_MAX (closest_bucket, peer_bucket);
643 if ((peer_bucket > 0) && (k_buckets[peer_bucket].peers_size <= bucket_size))
645 ret->preference_task =
646 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
649 GNUNET_assert (GNUNET_OK ==
650 GNUNET_CONTAINER_multihashmap_put (all_known_peers,
651 &peer->hashPubKey, ret,
652 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
653 if (1 == GNUNET_CONTAINER_multihashmap_size (all_known_peers))
655 /* got a first connection, good time to start with FIND PEER requests... */
656 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
662 * Method called whenever a peer disconnects.
665 * @param peer peer identity this notification is about
668 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
670 struct PeerInfo *to_remove;
672 struct P2PPendingMessage *pos;
673 unsigned int discarded;
675 /* Check for disconnect from self message */
676 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
679 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnected %s from %s\n",
680 GNUNET_i2s (&my_identity), GNUNET_h2s (&peer->hashPubKey));
683 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
684 if (NULL == to_remove)
689 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# Peers connected"), -1,
691 GNUNET_assert (GNUNET_YES ==
692 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
695 if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
697 GNUNET_SCHEDULER_cancel (to_remove->preference_task);
698 to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
700 current_bucket = find_bucket (&to_remove->id.hashPubKey);
701 GNUNET_assert (current_bucket >= 0);
702 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
703 k_buckets[current_bucket].tail, to_remove);
704 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
705 k_buckets[current_bucket].peers_size--;
706 while ((closest_bucket > 0) && (k_buckets[closest_bucket].peers_size == 0))
709 if (to_remove->th != NULL)
711 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
712 to_remove->th = NULL;
715 while (NULL != (pos = to_remove->head))
717 GNUNET_CONTAINER_DLL_remove (to_remove->head, to_remove->tail, pos);
721 GNUNET_STATISTICS_update (GDS_stats,
723 ("# Queued messages discarded (peer disconnected)"),
724 discarded, GNUNET_NO);
725 GNUNET_free (to_remove);
730 * Called when core is ready to send a message we asked for
731 * out to the destination.
733 * @param cls the 'struct PeerInfo' of the target peer
734 * @param size number of bytes available in buf
735 * @param buf where the callee should write the message
736 * @return number of bytes written to buf
739 core_transmit_notify (void *cls, size_t size, void *buf)
741 struct PeerInfo *peer = cls;
743 struct P2PPendingMessage *pending;
748 while ((NULL != (pending = peer->head)) &&
749 (GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value == 0))
751 peer->pending_count--;
752 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
753 GNUNET_free (pending);
757 /* no messages pending */
763 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
765 GNUNET_TIME_absolute_get_remaining
766 (pending->timeout), &peer->id,
767 ntohs (pending->msg->size),
768 &core_transmit_notify, peer);
769 GNUNET_break (NULL != peer->th);
773 while ((NULL != (pending = peer->head)) &&
774 (size - off >= (msize = ntohs (pending->msg->size))))
776 GNUNET_STATISTICS_update (GDS_stats,
778 ("# Bytes transmitted to other peers"), msize,
780 memcpy (&cbuf[off], pending->msg, msize);
782 peer->pending_count--;
783 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
784 GNUNET_free (pending);
786 if (peer->head != NULL)
789 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
791 GNUNET_TIME_absolute_get_remaining
792 (pending->timeout), &peer->id, msize,
793 &core_transmit_notify, peer);
794 GNUNET_break (NULL != peer->th);
801 * Transmit all messages in the peer's message queue.
803 * @param peer message queue to process
806 process_peer_queue (struct PeerInfo *peer)
808 struct P2PPendingMessage *pending;
810 if (NULL == (pending = peer->head))
812 if (NULL != peer->th)
814 GNUNET_STATISTICS_update (GDS_stats,
816 ("# Bytes of bandwdith requested from core"),
817 ntohs (pending->msg->size), GNUNET_NO);
819 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
821 GNUNET_TIME_absolute_get_remaining
822 (pending->timeout), &peer->id,
823 ntohs (pending->msg->size),
824 &core_transmit_notify, peer);
825 GNUNET_break (NULL != peer->th);
830 * To how many peers should we (on average) forward the request to
831 * obtain the desired target_replication count (on average).
833 * @param hop_count number of hops the message has traversed
834 * @param target_replication the number of total paths desired
835 * @return Some number of peers to forward the message to
838 get_forward_count (uint32_t hop_count, uint32_t target_replication)
840 uint32_t random_value;
841 uint32_t forward_count;
844 if (hop_count > GDS_NSE_get () * 6.0)
846 /* forcefully terminate */
849 if (hop_count > GDS_NSE_get () * 4.0)
851 /* Once we have reached our ideal number of hops, only forward to 1 peer */
854 /* bound by system-wide maximum */
856 GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
858 1 + (target_replication - 1.0) / (GDS_NSE_get () +
859 ((float) (target_replication - 1.0) *
861 /* Set forward count to floor of target_value */
862 forward_count = (uint32_t) target_value;
863 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
864 target_value = target_value - forward_count;
866 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
867 if (random_value < (target_value * UINT32_MAX))
869 return forward_count;
874 * Compute the distance between have and target as a 32-bit value.
875 * Differences in the lower bits must count stronger than differences
876 * in the higher bits.
878 * @return 0 if have==target, otherwise a number
879 * that is larger as the distance between
880 * the two hash codes increases
883 get_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
890 /* We have to represent the distance between two 2^9 (=512)-bit
891 * numbers as a 2^5 (=32)-bit number with "0" being used for the
892 * two numbers being identical; furthermore, we need to
893 * guarantee that a difference in the number of matching
894 * bits is always represented in the result.
896 * We use 2^32/2^9 numerical values to distinguish between
897 * hash codes that have the same LSB bit distance and
898 * use the highest 2^9 bits of the result to signify the
899 * number of (mis)matching LSB bits; if we have 0 matching
900 * and hence 512 mismatching LSB bits we return -1 (since
901 * 512 itself cannot be represented with 9 bits) */
903 /* first, calculate the most significant 9 bits of our
904 * result, aka the number of LSBs */
905 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
906 /* bucket is now a value between 0 and 512 */
908 return 0; /* perfect match */
910 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
911 * below, we'd end up with max+1 (overflow)) */
913 /* calculate the most significant bits of the final result */
914 msb = (512 - bucket) << (32 - 9);
915 /* calculate the 32-9 least significant bits of the final result by
916 * looking at the differences in the 32-9 bits following the
917 * mismatching bit at 'bucket' */
920 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
922 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
923 GNUNET_CRYPTO_hash_get_bit (have, i))
924 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
925 * last bit set will be 31 -- if
926 * i does not reach 512 first... */
933 * Check whether my identity is closer than any known peers. If a
934 * non-null bloomfilter is given, check if this is the closest peer
935 * that hasn't already been routed to.
937 * @param key hash code to check closeness to
938 * @param bloom bloomfilter, exclude these entries from the decision
939 * @return GNUNET_YES if node location is closest,
940 * GNUNET_NO otherwise.
943 am_closest_peer (const GNUNET_HashCode * key,
944 const struct GNUNET_CONTAINER_BloomFilter *bloom)
950 struct PeerInfo *pos;
952 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
954 bucket_num = find_bucket (key);
955 GNUNET_assert (bucket_num >= 0);
956 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
957 pos = k_buckets[bucket_num].head;
959 while ((pos != NULL) && (count < bucket_size))
961 if ((bloom != NULL) &&
963 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
966 continue; /* Skip already checked entries */
968 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
969 if (other_bits > bits)
971 if (other_bits == bits) /* We match the same number of bits */
975 /* No peers closer, we are the closest! */
981 * Select a peer from the routing table that would be a good routing
982 * destination for sending a message for "key". The resulting peer
983 * must not be in the set of blocked peers.<p>
985 * Note that we should not ALWAYS select the closest peer to the
986 * target, peers further away from the target should be chosen with
987 * exponentially declining probability.
989 * FIXME: double-check that this is fine
992 * @param key the key we are selecting a peer to route to
993 * @param bloom a bloomfilter containing entries this request has seen already
994 * @param hops how many hops has this message traversed thus far
995 * @return Peer to route to, or NULL on error
997 static struct PeerInfo *
998 select_peer (const GNUNET_HashCode * key,
999 const struct GNUNET_CONTAINER_BloomFilter *bloom, uint32_t hops)
1003 unsigned int selected;
1004 struct PeerInfo *pos;
1006 unsigned int smallest_distance;
1007 struct PeerInfo *chosen;
1009 if (hops >= GDS_NSE_get ())
1011 /* greedy selection (closest peer that is not in bloomfilter) */
1012 smallest_distance = UINT_MAX;
1014 for (bc = 0; bc <= closest_bucket; bc++)
1016 pos = k_buckets[bc].head;
1018 while ((pos != NULL) && (count < bucket_size))
1020 if ((bloom == NULL) ||
1022 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1024 dist = get_distance (key, &pos->id.hashPubKey);
1025 if (dist < smallest_distance)
1028 smallest_distance = dist;
1034 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1035 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1036 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1038 GNUNET_STATISTICS_update (GDS_stats,
1040 ("# Peers excluded from routing due to Bloomfilter"),
1048 GNUNET_STATISTICS_update (GDS_stats,
1049 gettext_noop ("# Peer selection failed"), 1,
1054 /* select "random" peer */
1055 /* count number of peers that are available and not filtered */
1057 for (bc = 0; bc <= closest_bucket; bc++)
1059 pos = k_buckets[bc].head;
1060 while ((pos != NULL) && (count < bucket_size))
1062 if ((bloom != NULL) &&
1064 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1066 GNUNET_STATISTICS_update (GDS_stats,
1068 ("# 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));
1076 continue; /* Ignore bloomfiltered peers */
1082 if (count == 0) /* No peers to select from! */
1084 GNUNET_STATISTICS_update (GDS_stats,
1085 gettext_noop ("# Peer selection failed"), 1,
1089 /* Now actually choose a peer */
1090 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1092 for (bc = 0; bc <= closest_bucket; bc++)
1094 pos = k_buckets[bc].head;
1095 while ((pos != NULL) && (count < bucket_size))
1097 if ((bloom != NULL) &&
1099 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1102 continue; /* Ignore bloomfiltered peers */
1104 if (0 == selected--)
1115 * Compute the set of peers that the given request should be
1118 * @param key routing key
1119 * @param bloom bloom filter excluding peers as targets, all selected
1120 * peers will be added to the bloom filter
1121 * @param hop_count number of hops the request has traversed so far
1122 * @param target_replication desired number of replicas
1123 * @param targets where to store an array of target peers (to be
1124 * free'd by the caller)
1125 * @return number of peers returned in 'targets'.
1128 get_target_peers (const GNUNET_HashCode * key,
1129 struct GNUNET_CONTAINER_BloomFilter *bloom,
1130 uint32_t hop_count, uint32_t target_replication,
1131 struct PeerInfo ***targets)
1135 struct PeerInfo **rtargets;
1136 struct PeerInfo *nxt;
1138 GNUNET_assert (NULL != bloom);
1139 ret = get_forward_count (hop_count, target_replication);
1145 rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1146 for (off = 0; off < ret; off++)
1148 nxt = select_peer (key, bloom, hop_count);
1151 rtargets[off] = nxt;
1152 GNUNET_break (GNUNET_NO ==
1153 GNUNET_CONTAINER_bloomfilter_test (bloom,
1154 &nxt->id.hashPubKey));
1155 GNUNET_CONTAINER_bloomfilter_add (bloom, &rtargets[off]->id.hashPubKey);
1158 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1159 "Selected %u/%u peers at hop %u for %s (target was %u)\n", off,
1160 GNUNET_CONTAINER_multihashmap_size (all_known_peers),
1161 (unsigned int) hop_count, GNUNET_h2s (key), ret);
1165 GNUNET_free (rtargets);
1169 *targets = rtargets;
1175 * Perform a PUT operation. Forwards the given request to other
1176 * peers. Does not store the data locally. Does not give the
1177 * data to local clients. May do nothing if this is the only
1178 * peer in the network (or if we are the closest peer in the
1181 * @param type type of the block
1182 * @param options routing options
1183 * @param desired_replication_level desired replication count
1184 * @param expiration_time when does the content expire
1185 * @param hop_count how many hops has this message traversed so far
1186 * @param bf Bloom filter of peers this PUT has already traversed
1187 * @param key key for the content
1188 * @param put_path_length number of entries in put_path
1189 * @param put_path peers this request has traversed so far (if tracked)
1190 * @param data payload to store
1191 * @param data_size number of bytes in data
1194 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1195 enum GNUNET_DHT_RouteOption options,
1196 uint32_t desired_replication_level,
1197 struct GNUNET_TIME_Absolute expiration_time,
1199 struct GNUNET_CONTAINER_BloomFilter *bf,
1200 const GNUNET_HashCode * key,
1201 unsigned int put_path_length,
1202 struct GNUNET_PeerIdentity *put_path,
1203 const void *data, size_t data_size)
1205 unsigned int target_count;
1207 struct PeerInfo **targets;
1208 struct PeerInfo *target;
1209 struct P2PPendingMessage *pending;
1211 struct PeerPutMessage *ppm;
1212 struct GNUNET_PeerIdentity *pp;
1214 GNUNET_assert (NULL != bf);
1216 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1217 "Adding myself (%s) to PUT bloomfilter for %s\n",
1218 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1220 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1221 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1224 get_target_peers (key, bf, hop_count, desired_replication_level,
1226 if (0 == target_count)
1229 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1230 "Routing PUT for %s terminates after %u hops at %s\n",
1231 GNUNET_h2s (key), (unsigned int) hop_count,
1232 GNUNET_i2s (&my_identity));
1237 put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1238 sizeof (struct PeerPutMessage);
1239 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1241 put_path_length = 0;
1242 msize = data_size + sizeof (struct PeerPutMessage);
1244 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1247 GNUNET_free (targets);
1250 GNUNET_STATISTICS_update (GDS_stats,
1252 ("# PUT messages queued for transmission"),
1253 target_count, GNUNET_NO);
1254 for (i = 0; i < target_count; i++)
1256 target = targets[i];
1258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1259 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1260 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1262 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1263 pending->importance = 0; /* FIXME */
1264 pending->timeout = expiration_time;
1265 ppm = (struct PeerPutMessage *) &pending[1];
1266 pending->msg = &ppm->header;
1267 ppm->header.size = htons (msize);
1268 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1269 ppm->options = htonl (options);
1270 ppm->type = htonl (type);
1271 ppm->hop_count = htonl (hop_count + 1);
1272 ppm->desired_replication_level = htonl (desired_replication_level);
1273 ppm->put_path_length = htonl (put_path_length);
1274 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1275 GNUNET_break (GNUNET_YES ==
1276 GNUNET_CONTAINER_bloomfilter_test (bf,
1277 &target->id.hashPubKey));
1278 GNUNET_assert (GNUNET_OK ==
1279 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1283 pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1284 memcpy (pp, put_path,
1285 sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1286 memcpy (&pp[put_path_length], data, data_size);
1287 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1288 target->pending_count++;
1289 process_peer_queue (target);
1291 GNUNET_free (targets);
1296 * Perform a GET operation. Forwards the given request to other
1297 * peers. Does not lookup the key locally. May do nothing if this is
1298 * the only peer in the network (or if we are the closest peer in the
1301 * @param type type of the block
1302 * @param options routing options
1303 * @param desired_replication_level desired replication count
1304 * @param hop_count how many hops did this request traverse so far?
1305 * @param key key for the content
1306 * @param xquery extended query
1307 * @param xquery_size number of bytes in xquery
1308 * @param reply_bf bloomfilter to filter duplicates
1309 * @param reply_bf_mutator mutator for reply_bf
1310 * @param peer_bf filter for peers not to select (again)
1313 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1314 enum GNUNET_DHT_RouteOption options,
1315 uint32_t desired_replication_level,
1316 uint32_t hop_count, const GNUNET_HashCode * key,
1317 const void *xquery, size_t xquery_size,
1318 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1319 uint32_t reply_bf_mutator,
1320 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1322 unsigned int target_count;
1324 struct PeerInfo **targets;
1325 struct PeerInfo *target;
1326 struct P2PPendingMessage *pending;
1328 struct PeerGetMessage *pgm;
1330 size_t reply_bf_size;
1332 GNUNET_assert (NULL != peer_bf);
1333 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1336 get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1339 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1340 "Adding myself (%s) to GET bloomfilter for %s\n",
1341 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1343 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity.hashPubKey);
1344 if (0 == target_count)
1347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1348 "Routing GET for %s terminates after %u hops at %s\n",
1349 GNUNET_h2s (key), (unsigned int) hop_count,
1350 GNUNET_i2s (&my_identity));
1354 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1355 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1356 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1359 GNUNET_free (targets);
1362 GNUNET_STATISTICS_update (GDS_stats,
1364 ("# GET messages queued for transmission"),
1365 target_count, GNUNET_NO);
1366 /* forward request */
1367 for (i = 0; i < target_count; i++)
1369 target = targets[i];
1371 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1372 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1373 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1375 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1376 pending->importance = 0; /* FIXME */
1377 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1378 pgm = (struct PeerGetMessage *) &pending[1];
1379 pending->msg = &pgm->header;
1380 pgm->header.size = htons (msize);
1381 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1382 pgm->options = htonl (options);
1383 pgm->type = htonl (type);
1384 pgm->hop_count = htonl (hop_count + 1);
1385 pgm->desired_replication_level = htonl (desired_replication_level);
1386 pgm->xquery_size = htonl (xquery_size);
1387 pgm->bf_mutator = reply_bf_mutator;
1388 GNUNET_break (GNUNET_YES ==
1389 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1390 &target->id.hashPubKey));
1391 GNUNET_assert (GNUNET_OK ==
1392 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1396 xq = (char *) &pgm[1];
1397 memcpy (xq, xquery, xquery_size);
1398 if (NULL != reply_bf)
1399 GNUNET_assert (GNUNET_OK ==
1400 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1404 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1405 target->pending_count++;
1406 process_peer_queue (target);
1408 GNUNET_free (targets);
1413 * Handle a reply (route to origin). Only forwards the reply back to
1414 * the given peer. Does not do local caching or forwarding to local
1417 * @param target neighbour that should receive the block (if still connected)
1418 * @param type type of the block
1419 * @param expiration_time when does the content expire
1420 * @param key key for the content
1421 * @param put_path_length number of entries in put_path
1422 * @param put_path peers the original PUT traversed (if tracked)
1423 * @param get_path_length number of entries in put_path
1424 * @param get_path peers this reply has traversed so far (if tracked)
1425 * @param data payload of the reply
1426 * @param data_size number of bytes in data
1429 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1430 enum GNUNET_BLOCK_Type type,
1431 struct GNUNET_TIME_Absolute expiration_time,
1432 const GNUNET_HashCode * key,
1433 unsigned int put_path_length,
1434 const struct GNUNET_PeerIdentity *put_path,
1435 unsigned int get_path_length,
1436 const struct GNUNET_PeerIdentity *get_path,
1437 const void *data, size_t data_size)
1439 struct PeerInfo *pi;
1440 struct P2PPendingMessage *pending;
1442 struct PeerResultMessage *prm;
1443 struct GNUNET_PeerIdentity *paths;
1446 data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1448 sizeof (struct GNUNET_PeerIdentity);
1449 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1451 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1453 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1454 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1459 pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers, &target->hashPubKey);
1462 /* peer disconnected in the meantime, drop reply */
1465 GNUNET_STATISTICS_update (GDS_stats,
1467 ("# RESULT messages queued for transmission"), 1,
1469 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1470 pending->importance = 0; /* FIXME */
1471 pending->timeout = expiration_time;
1472 prm = (struct PeerResultMessage *) &pending[1];
1473 pending->msg = &prm->header;
1474 prm->header.size = htons (msize);
1475 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1476 prm->type = htonl (type);
1477 prm->put_path_length = htonl (put_path_length);
1478 prm->get_path_length = htonl (get_path_length);
1479 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1481 paths = (struct GNUNET_PeerIdentity *) &prm[1];
1482 memcpy (paths, put_path,
1483 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1484 memcpy (&paths[put_path_length], get_path,
1485 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1486 memcpy (&paths[put_path_length + get_path_length], data, data_size);
1487 GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1488 pi->pending_count++;
1489 process_peer_queue (pi);
1494 * To be called on core init/fail.
1496 * @param cls service closure
1497 * @param server handle to the server for this service
1498 * @param identity the public identity of this peer
1501 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1502 const struct GNUNET_PeerIdentity *identity)
1504 GNUNET_assert (server != NULL);
1505 my_identity = *identity;
1510 * Core handler for p2p put requests.
1512 * @param cls closure
1513 * @param peer sender of the request
1514 * @param message message
1515 * @param peer peer identity this notification is about
1516 * @param atsi performance data
1517 * @param atsi_count number of records in 'atsi'
1518 * @return GNUNET_OK to keep the connection open,
1519 * GNUNET_SYSERR to close it (signal serious error)
1522 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1523 const struct GNUNET_MessageHeader *message,
1524 const struct GNUNET_ATS_Information *atsi,
1525 unsigned int atsi_count)
1527 const struct PeerPutMessage *put;
1528 const struct GNUNET_PeerIdentity *put_path;
1529 const void *payload;
1532 size_t payload_size;
1533 enum GNUNET_DHT_RouteOption options;
1534 struct GNUNET_CONTAINER_BloomFilter *bf;
1535 GNUNET_HashCode test_key;
1537 msize = ntohs (message->size);
1538 if (msize < sizeof (struct PeerPutMessage))
1540 GNUNET_break_op (0);
1543 put = (const struct PeerPutMessage *) message;
1544 putlen = ntohl (put->put_path_length);
1546 sizeof (struct PeerPutMessage) +
1547 putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1549 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1551 GNUNET_break_op (0);
1554 GNUNET_STATISTICS_update (GDS_stats,
1555 gettext_noop ("# P2P PUT requests received"), 1,
1557 put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1558 payload = &put_path[putlen];
1559 options = ntohl (put->options);
1561 msize - (sizeof (struct PeerPutMessage) +
1562 putlen * sizeof (struct GNUNET_PeerIdentity));
1563 switch (GNUNET_BLOCK_get_key
1564 (GDS_block_context, ntohl (put->type), payload, payload_size,
1568 if (0 != memcmp (&test_key, &put->key, sizeof (GNUNET_HashCode)))
1570 GNUNET_break_op (0);
1575 GNUNET_break_op (0);
1578 /* cannot verify, good luck */
1582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for %s at %s\n",
1583 GNUNET_h2s (&put->key), GNUNET_i2s (&my_identity));
1585 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1586 GNUNET_CONSTANTS_BLOOMFILTER_K);
1587 GNUNET_break_op (GNUNET_YES ==
1588 GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1590 struct GNUNET_PeerIdentity pp[putlen + 1];
1592 /* extend 'put path' by sender */
1593 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1595 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1602 /* give to local clients */
1603 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1604 &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1605 payload_size, payload);
1607 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1608 (am_closest_peer (&put->key, bf)))
1609 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1610 (put->expiration_time), &put->key, putlen, pp,
1611 ntohl (put->type), payload_size, payload);
1612 /* route to other peers */
1613 GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1614 ntohl (put->desired_replication_level),
1615 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1616 ntohl (put->hop_count), bf, &put->key, putlen,
1617 pp, payload, payload_size);
1619 GNUNET_CONTAINER_bloomfilter_free (bf);
1620 GDS_CLIENTS_process_monitor (GNUNET_MESSAGE_TYPE_DHT_MONITOR_PUT,
1621 GNUNET_TIME_absolute_ntoh (put->expiration_time), &put->key,
1622 putlen, put_path, 0, NULL, ntohl(put->desired_replication_level),
1623 ntohl (put->type), payload, payload_size);
1629 * We have received a FIND PEER request. Send matching
1632 * @param sender sender of the FIND PEER request
1633 * @param key peers close to this key are desired
1634 * @param bf peers matching this bf are excluded
1635 * @param bf_mutator mutator for bf
1638 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1639 const GNUNET_HashCode * key,
1640 struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1643 struct PeerBucket *bucket;
1644 struct PeerInfo *peer;
1645 unsigned int choice;
1646 GNUNET_HashCode mhash;
1647 const struct GNUNET_HELLO_Message *hello;
1649 /* first, check about our own HELLO */
1650 if (NULL != GDS_my_hello)
1652 GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1654 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1656 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1657 GNUNET_TIME_relative_to_absolute
1658 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1659 key, 0, NULL, 0, NULL, GDS_my_hello,
1660 GNUNET_HELLO_size ((const struct
1661 GNUNET_HELLO_Message *)
1666 GNUNET_STATISTICS_update (GDS_stats,
1668 ("# FIND PEER requests ignored due to Bloomfilter"),
1674 GNUNET_STATISTICS_update (GDS_stats,
1676 ("# FIND PEER requests ignored due to lack of HELLO"),
1680 /* then, also consider sending a random HELLO from the closest bucket */
1681 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
1682 bucket_idx = closest_bucket;
1684 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1685 if (bucket_idx == GNUNET_SYSERR)
1687 bucket = &k_buckets[bucket_idx];
1688 if (bucket->peers_size == 0)
1691 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1692 peer = bucket->head;
1695 GNUNET_assert (peer != NULL);
1699 choice = bucket->peers_size;
1704 return; /* no non-masked peer available */
1706 peer = bucket->head;
1707 GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1708 hello = GDS_HELLO_get (&peer->id);
1710 while ((hello == NULL) ||
1711 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1712 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1713 GNUNET_TIME_relative_to_absolute
1714 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1715 0, NULL, 0, NULL, hello,
1716 GNUNET_HELLO_size (hello));
1721 * Core handler for p2p get requests.
1723 * @param cls closure
1724 * @param peer sender of the request
1725 * @param message message
1726 * @param peer peer identity this notification is about
1727 * @param atsi performance data
1728 * @param atsi_count number of records in 'atsi'
1729 * @return GNUNET_OK to keep the connection open,
1730 * GNUNET_SYSERR to close it (signal serious error)
1733 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1734 const struct GNUNET_MessageHeader *message,
1735 const struct GNUNET_ATS_Information *atsi,
1736 unsigned int atsi_count)
1738 struct PeerGetMessage *get;
1739 uint32_t xquery_size;
1740 size_t reply_bf_size;
1742 enum GNUNET_BLOCK_Type type;
1743 enum GNUNET_DHT_RouteOption options;
1744 enum GNUNET_BLOCK_EvaluationResult eval;
1745 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1746 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1750 memcmp (peer, &my_identity,
1751 sizeof (struct GNUNET_PeerIdentity)));
1752 /* parse and validate message */
1753 msize = ntohs (message->size);
1754 if (msize < sizeof (struct PeerGetMessage))
1756 GNUNET_break_op (0);
1759 get = (struct PeerGetMessage *) message;
1760 xquery_size = ntohl (get->xquery_size);
1761 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1763 GNUNET_break_op (0);
1766 GNUNET_STATISTICS_update (GDS_stats,
1767 gettext_noop ("# P2P GET requests received"), 1,
1769 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1770 type = ntohl (get->type);
1771 options = ntohl (get->options);
1772 xquery = (const char *) &get[1];
1774 if (reply_bf_size > 0)
1776 GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1777 GNUNET_CONSTANTS_BLOOMFILTER_K);
1779 GNUNET_BLOCK_evaluate (GDS_block_context, type, &get->key, &reply_bf,
1780 get->bf_mutator, xquery, xquery_size, NULL, 0);
1781 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1783 /* request invalid or block type not supported */
1784 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1785 if (NULL != reply_bf)
1786 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1790 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1791 GNUNET_CONSTANTS_BLOOMFILTER_K);
1792 GNUNET_break_op (GNUNET_YES ==
1793 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1794 &peer->hashPubKey));
1795 /* remember request for routing replies */
1796 GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1797 reply_bf, get->bf_mutator);
1799 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GET for %s at %s after %u hops\n",
1800 GNUNET_h2s (&get->key), GNUNET_i2s (&my_identity),
1801 (unsigned int) ntohl (get->hop_count));
1803 /* local lookup (this may update the reply_bf) */
1804 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1805 (am_closest_peer (&get->key, peer_bf)))
1807 if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1809 GNUNET_STATISTICS_update (GDS_stats,
1811 ("# P2P FIND PEER requests processed"), 1,
1813 handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
1818 GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
1819 &reply_bf, get->bf_mutator);
1824 GNUNET_STATISTICS_update (GDS_stats,
1825 gettext_noop ("# P2P GET requests ONLY routed"),
1829 GDS_CLIENTS_process_monitor (GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET,
1830 GNUNET_TIME_UNIT_FOREVER_ABS, &get->key, 0, NULL, 0, NULL,
1831 ntohl (get->desired_replication_level), type, NULL, 0);
1833 /* P2P forwarding */
1834 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1835 GDS_NEIGHBOURS_handle_get (type, options,
1836 ntohl (get->desired_replication_level),
1837 ntohl (get->hop_count), &get->key, xquery,
1838 xquery_size, reply_bf, get->bf_mutator, peer_bf);
1840 if (NULL != reply_bf)
1841 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1842 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
1848 * Core handler for p2p result messages.
1850 * @param cls closure
1851 * @param message message
1852 * @param peer peer identity this notification is about
1853 * @param atsi performance data
1854 * @param atsi_count number of records in 'atsi'
1855 * @return GNUNET_YES (do not cut p2p connection)
1858 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1859 const struct GNUNET_MessageHeader *message,
1860 const struct GNUNET_ATS_Information *atsi,
1861 unsigned int atsi_count)
1863 const struct PeerResultMessage *prm;
1864 const struct GNUNET_PeerIdentity *put_path;
1865 const struct GNUNET_PeerIdentity *get_path;
1867 uint32_t get_path_length;
1868 uint32_t put_path_length;
1871 enum GNUNET_BLOCK_Type type;
1873 /* parse and validate message */
1874 msize = ntohs (message->size);
1875 if (msize < sizeof (struct PeerResultMessage))
1877 GNUNET_break_op (0);
1880 prm = (struct PeerResultMessage *) message;
1881 put_path_length = ntohl (prm->put_path_length);
1882 get_path_length = ntohl (prm->get_path_length);
1884 sizeof (struct PeerResultMessage) + (get_path_length +
1886 sizeof (struct GNUNET_PeerIdentity)) ||
1888 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1890 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1892 GNUNET_break_op (0);
1895 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
1897 put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
1898 get_path = &put_path[put_path_length];
1899 type = ntohl (prm->type);
1900 data = (const void *) &get_path[get_path_length];
1902 msize - (sizeof (struct PeerResultMessage) +
1904 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1906 /* if we got a HELLO, consider it for our own routing table */
1907 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
1909 const struct GNUNET_MessageHeader *h;
1910 struct GNUNET_PeerIdentity pid;
1913 /* Should be a HELLO, validate and consider using it! */
1914 if (data_size < sizeof (struct GNUNET_MessageHeader))
1916 GNUNET_break_op (0);
1920 if (data_size != ntohs (h->size))
1922 GNUNET_break_op (0);
1926 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
1928 GNUNET_break_op (0);
1931 if (0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
1933 bucket = find_bucket (&pid.hashPubKey);
1934 if ((bucket >= 0) && (k_buckets[bucket].peers_size < bucket_size))
1936 if (NULL != GDS_transport_handle)
1938 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
1939 GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid);
1945 /* append 'peer' to 'get_path' */
1947 struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
1949 memcpy (xget_path, get_path,
1950 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1951 xget_path[get_path_length] = *peer;
1954 /* forward to local clients */
1955 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
1956 &prm->key, get_path_length, xget_path,
1957 put_path_length, put_path, type, data_size, data);
1959 /* forward to other peers */
1960 GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
1961 &prm->key, put_path_length, put_path, get_path_length,
1962 xget_path, data, data_size);
1965 GDS_CLIENTS_process_monitor (GNUNET_MESSAGE_TYPE_DHT_MONITOR_GET_RESP,
1966 GNUNET_TIME_absolute_ntoh (prm->expiration_time), &prm->key,
1967 put_path_length, put_path, get_path_length, get_path,
1968 0, type, data, data_size);
1975 * Initialize neighbours subsystem.
1977 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1980 GDS_NEIGHBOURS_init ()
1982 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1983 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
1984 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
1985 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
1988 unsigned long long temp_config_num;
1991 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
1993 bucket_size = (unsigned int) temp_config_num;
1994 atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
1996 GNUNET_CORE_connect (GDS_cfg, 1, NULL, &core_init, &handle_core_connect,
1997 &handle_core_disconnect, NULL, GNUNET_NO, NULL,
1998 GNUNET_NO, core_handlers);
1999 if (coreAPI == NULL)
2000 return GNUNET_SYSERR;
2001 all_known_peers = GNUNET_CONTAINER_multihashmap_create (256);
2007 * Shutdown neighbours subsystem.
2010 GDS_NEIGHBOURS_done ()
2012 if (coreAPI == NULL)
2014 GNUNET_CORE_disconnect (coreAPI);
2016 GNUNET_ATS_performance_done (atsAPI);
2018 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2019 GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2020 all_known_peers = NULL;
2021 if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2023 GNUNET_SCHEDULER_cancel (find_peer_task);
2024 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2029 /* end of gnunet-service-dht_neighbours.c */