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)
99 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
101 struct GNUNET_MessageHeader header;
106 uint32_t options GNUNET_PACKED;
111 uint32_t type GNUNET_PACKED;
116 uint32_t hop_count GNUNET_PACKED;
119 * Replication level for this message
121 uint32_t desired_replication_level GNUNET_PACKED;
124 * Length of the PUT path that follows (if tracked).
126 uint32_t put_path_length GNUNET_PACKED;
129 * When does the content expire?
131 struct GNUNET_TIME_AbsoluteNBO expiration_time;
134 * Bloomfilter (for peer identities) to stop circular routes
136 char bloomfilter[DHT_BLOOM_SIZE];
139 * The key we are storing under.
143 /* put path (if tracked) */
153 struct PeerResultMessage
156 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
158 struct GNUNET_MessageHeader header;
163 uint32_t type GNUNET_PACKED;
166 * Length of the PUT path that follows (if tracked).
168 uint32_t put_path_length GNUNET_PACKED;
171 * Length of the GET path that follows (if tracked).
173 uint32_t get_path_length GNUNET_PACKED;
176 * When does the content expire?
178 struct GNUNET_TIME_AbsoluteNBO expiration_time;
181 * The key of the corresponding GET request.
185 /* put path (if tracked) */
187 /* get path (if tracked) */
197 struct PeerGetMessage
200 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_GET
202 struct GNUNET_MessageHeader header;
207 uint32_t options GNUNET_PACKED;
210 * Desired content type.
212 uint32_t type GNUNET_PACKED;
217 uint32_t hop_count GNUNET_PACKED;
220 * Desired replication level for this request.
222 uint32_t desired_replication_level GNUNET_PACKED;
225 * Size of the extended query.
227 uint32_t xquery_size;
230 * Bloomfilter mutator.
235 * Bloomfilter (for peer identities) to stop circular routes
237 char bloomfilter[DHT_BLOOM_SIZE];
240 * The key we are looking for.
246 /* result bloomfilter */
252 * Linked list of messages to send to a particular other peer.
254 struct P2PPendingMessage
257 * Pointer to next item in the list
259 struct P2PPendingMessage *next;
262 * Pointer to previous item in the list
264 struct P2PPendingMessage *prev;
267 * Message importance level. FIXME: used? useful?
269 unsigned int importance;
272 * When does this message time out?
274 struct GNUNET_TIME_Absolute timeout;
277 * Actual message to be sent, allocated at the end of the struct:
278 * // msg = (cast) &pm[1];
279 * // memcpy (&pm[1], data, len);
281 const struct GNUNET_MessageHeader *msg;
287 * Entry for a peer in a bucket.
292 * Next peer entry (DLL)
294 struct PeerInfo *next;
297 * Prev peer entry (DLL)
299 struct PeerInfo *prev;
302 * Count of outstanding messages for peer. FIXME: NEEDED?
303 * FIXME: bound queue size!?
305 unsigned int pending_count;
308 * Head of pending messages to be sent to this peer.
310 struct P2PPendingMessage *head;
313 * Tail of pending messages to be sent to this peer.
315 struct P2PPendingMessage *tail;
318 * Core handle for sending messages to this peer.
320 struct GNUNET_CORE_TransmitHandle *th;
323 * Task for scheduling preference updates
325 GNUNET_SCHEDULER_TaskIdentifier preference_task;
328 * What is the identity of the peer?
330 struct GNUNET_PeerIdentity id;
334 * What is the average latency for replies received?
336 struct GNUNET_TIME_Relative latency;
339 * Transport level distance to peer.
341 unsigned int distance;
348 * Peers are grouped into buckets.
355 struct PeerInfo *head;
360 struct PeerInfo *tail;
363 * Number of peers in the bucket.
365 unsigned int peers_size;
370 * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
372 static unsigned int closest_bucket;
375 * How many peers have we added since we sent out our last
378 static unsigned int newly_found_peers;
381 * The buckets. Array of size MAX_BUCKET_SIZE. Offset 0 means 0 bits matching.
383 static struct PeerBucket k_buckets[MAX_BUCKETS];
386 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
388 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
391 * Maximum size for each bucket.
393 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
396 * Task that sends FIND PEER requests.
398 static GNUNET_SCHEDULER_TaskIdentifier find_peer_task;
401 * Identity of this peer.
403 static struct GNUNET_PeerIdentity my_identity;
408 static struct GNUNET_CORE_Handle *coreAPI;
413 static struct GNUNET_ATS_PerformanceHandle *atsAPI;
418 * Find the optimal bucket for this key.
420 * @param hc the hashcode to compare our identity to
421 * @return the proper bucket index, or GNUNET_SYSERR
422 * on error (same hashcode)
425 find_bucket (const GNUNET_HashCode * hc)
429 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
430 if (bits == MAX_BUCKETS)
432 /* How can all bits match? Got my own ID? */
434 return GNUNET_SYSERR;
436 return MAX_BUCKETS - bits - 1;
441 * Let GNUnet core know that we like the given peer.
443 * @param cls the 'struct PeerInfo' of the peer
444 * @param tc scheduler context.
447 update_core_preference (void *cls,
448 const struct GNUNET_SCHEDULER_TaskContext *tc)
450 struct PeerInfo *peer = cls;
452 unsigned int matching;
455 peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
456 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
459 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
460 &peer->id.hashPubKey);
463 bucket = find_bucket (&peer->id.hashPubKey);
464 if (bucket == GNUNET_SYSERR)
468 GNUNET_assert (k_buckets[bucket].peers_size != 0);
469 preference = (1LL << matching) / k_buckets[bucket].peers_size;
473 peer->preference_task
474 = GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
475 &update_core_preference, peer);
478 GNUNET_STATISTICS_update (GDS_stats,
479 gettext_noop ("# Preference updates given to core"), 1,
481 GNUNET_ATS_change_preference (atsAPI, &peer->id,
482 GNUNET_ATS_PREFERENCE_BANDWIDTH,
484 GNUNET_ATS_PREFERENCE_END);
485 peer->preference_task
486 = GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
487 &update_core_preference, peer);
494 * Closure for 'add_known_to_bloom'.
496 struct BloomConstructorContext
499 * Bloom filter under construction.
501 struct GNUNET_CONTAINER_BloomFilter *bloom;
511 * Add each of the peers we already know to the bloom filter of
512 * the request so that we don't get duplicate HELLOs.
514 * @param cls the 'struct BloomConstructorContext'.
515 * @param key peer identity to add to the bloom filter
516 * @param value value the peer information (unused)
517 * @return GNUNET_YES (we should continue to iterate)
520 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
522 struct BloomConstructorContext *ctx = cls;
525 GNUNET_BLOCK_mingle_hash (key, ctx->bf_mutator, &mh);
526 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
527 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
530 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
536 * Task to send a find peer message for our own peer identifier
537 * so that we can find the closest peers in the network to ourselves
538 * and attempt to connect to them.
540 * @param cls closure for this task
541 * @param tc the context under which the task is running
544 send_find_peer_message (void *cls,
545 const struct GNUNET_SCHEDULER_TaskContext *tc)
547 struct GNUNET_TIME_Relative next_send_time;
548 struct BloomConstructorContext bcc;
549 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
551 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
552 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
554 if (newly_found_peers > bucket_size)
556 /* If we are finding many peers already, no need to send out our request right now! */
557 find_peer_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
558 &send_find_peer_message, NULL);
559 newly_found_peers = 0;
562 bcc.bf_mutator = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
564 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, GNUNET_CONSTANTS_BLOOMFILTER_K);
565 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers,
568 GNUNET_STATISTICS_update (GDS_stats,
569 gettext_noop ("# FIND PEER messages initiated"), 1,
571 peer_bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
573 GNUNET_CONSTANTS_BLOOMFILTER_K);
574 // FIXME: pass priority!?
575 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
576 GNUNET_DHT_RO_FIND_PEER,
577 FIND_PEER_REPLICATION_LEVEL,
579 &my_identity.hashPubKey,
581 bcc.bloom, bcc.bf_mutator,
583 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
584 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
585 /* schedule next round */
586 next_send_time.rel_value =
587 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
588 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
589 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / (newly_found_peers+1));
590 newly_found_peers = 0;
591 find_peer_task = GNUNET_SCHEDULER_add_delayed (next_send_time,
592 &send_find_peer_message,
598 * Method called whenever a peer connects.
601 * @param peer peer identity this notification is about
602 * @param atsi performance data
605 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
606 const struct GNUNET_ATS_Information *atsi)
608 struct PeerInfo *ret;
611 /* Check for connect to self message */
612 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
614 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
615 "Connected %s to %s\n",
616 GNUNET_i2s (&my_identity),
617 GNUNET_h2s (&peer->hashPubKey));
619 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
625 GNUNET_STATISTICS_update (GDS_stats,
626 gettext_noop ("# Peers connected"), 1,
628 peer_bucket = find_bucket (&peer->hashPubKey);
629 GNUNET_assert ( (peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS) );
630 ret = GNUNET_malloc (sizeof (struct PeerInfo));
632 ret->latency = latency;
633 ret->distance = distance;
636 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
637 k_buckets[peer_bucket].tail, ret);
638 k_buckets[peer_bucket].peers_size++;
639 closest_bucket = GNUNET_MAX (closest_bucket,
641 if ( (peer_bucket > 0) &&
642 (k_buckets[peer_bucket].peers_size <= bucket_size) )
644 ret->preference_task = GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
647 GNUNET_assert (GNUNET_OK ==
648 GNUNET_CONTAINER_multihashmap_put (all_known_peers,
649 &peer->hashPubKey, ret,
650 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
651 if (1 == GNUNET_CONTAINER_multihashmap_size (all_known_peers))
653 /* got a first connection, good time to start with FIND PEER requests... */
654 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message,
661 * Method called whenever a peer disconnects.
664 * @param peer peer identity this notification is about
667 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
669 struct PeerInfo *to_remove;
671 struct P2PPendingMessage *pos;
672 unsigned int discarded;
674 /* Check for disconnect from self message */
675 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
677 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
678 "Disconnected %s from %s\n",
679 GNUNET_i2s (&my_identity),
680 GNUNET_h2s (&peer->hashPubKey));
682 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
683 if (NULL == to_remove)
688 GNUNET_STATISTICS_update (GDS_stats,
689 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,
705 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
706 k_buckets[current_bucket].peers_size--;
707 while ( (closest_bucket > 0) &&
708 (k_buckets[closest_bucket].peers_size == 0) )
711 if (to_remove->th != NULL)
713 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
714 to_remove->th = NULL;
717 while (NULL != (pos = to_remove->head))
719 GNUNET_CONTAINER_DLL_remove (to_remove->head,
725 GNUNET_STATISTICS_update (GDS_stats,
726 gettext_noop ("# Queued messages discarded (peer disconnected)"), discarded,
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 (pending->timeout),
769 &peer->id, ntohs (pending->msg->size),
770 &core_transmit_notify, peer);
771 GNUNET_break (NULL != peer->th);
775 while ( (NULL != (pending = peer->head)) &&
776 (size - off >= (msize = ntohs (pending->msg->size))) )
778 GNUNET_STATISTICS_update (GDS_stats,
779 gettext_noop ("# Bytes transmitted to other peers"), msize,
781 memcpy (&cbuf[off], pending->msg, msize);
783 peer->pending_count--;
784 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
785 GNUNET_free (pending);
787 if (peer->head != NULL)
790 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
792 GNUNET_TIME_absolute_get_remaining (pending->timeout),
794 &core_transmit_notify, peer);
795 GNUNET_break (NULL != peer->th);
802 * Transmit all messages in the peer's message queue.
804 * @param peer message queue to process
807 process_peer_queue (struct PeerInfo *peer)
809 struct P2PPendingMessage *pending;
811 if (NULL == (pending = peer->head))
813 if (NULL != peer->th)
815 GNUNET_STATISTICS_update (GDS_stats,
816 gettext_noop ("# Bytes of bandwdith requested from core"),
817 ntohs (pending->msg->size),
820 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
822 GNUNET_TIME_absolute_get_remaining (pending->timeout),
824 ntohs (pending->msg->size),
825 &core_transmit_notify, peer);
826 GNUNET_break (NULL != peer->th);
831 * To how many peers should we (on average) forward the request to
832 * obtain the desired target_replication count (on average).
834 * @param hop_count number of hops the message has traversed
835 * @param target_replication the number of total paths desired
836 * @return Some number of peers to forward the message to
839 get_forward_count (uint32_t hop_count,
840 uint32_t target_replication)
842 uint32_t random_value;
843 uint32_t forward_count;
846 if (hop_count > GDS_NSE_get () * 6.0)
848 /* forcefully terminate */
851 if (hop_count > GDS_NSE_get () * 4.0)
853 /* Once we have reached our ideal number of hops, only forward to 1 peer */
856 /* bound by system-wide maximum */
857 target_replication = GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL,
860 1 + (target_replication - 1.0) / (GDS_NSE_get () +
861 ((float) (target_replication - 1.0) *
863 /* Set forward count to floor of target_value */
864 forward_count = (uint32_t) target_value;
865 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
866 target_value = target_value - forward_count;
868 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
869 if (random_value < (target_value * UINT32_MAX))
871 return forward_count;
876 * Compute the distance between have and target as a 32-bit value.
877 * Differences in the lower bits must count stronger than differences
878 * in the higher bits.
880 * @return 0 if have==target, otherwise a number
881 * that is larger as the distance between
882 * the two hash codes increases
885 get_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
892 /* We have to represent the distance between two 2^9 (=512)-bit
893 * numbers as a 2^5 (=32)-bit number with "0" being used for the
894 * two numbers being identical; furthermore, we need to
895 * guarantee that a difference in the number of matching
896 * bits is always represented in the result.
898 * We use 2^32/2^9 numerical values to distinguish between
899 * hash codes that have the same LSB bit distance and
900 * use the highest 2^9 bits of the result to signify the
901 * number of (mis)matching LSB bits; if we have 0 matching
902 * and hence 512 mismatching LSB bits we return -1 (since
903 * 512 itself cannot be represented with 9 bits) */
905 /* first, calculate the most significant 9 bits of our
906 * result, aka the number of LSBs */
907 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
908 /* bucket is now a value between 0 and 512 */
910 return 0; /* perfect match */
912 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
913 * below, we'd end up with max+1 (overflow)) */
915 /* calculate the most significant bits of the final result */
916 msb = (512 - bucket) << (32 - 9);
917 /* calculate the 32-9 least significant bits of the final result by
918 * looking at the differences in the 32-9 bits following the
919 * mismatching bit at 'bucket' */
922 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
924 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
925 GNUNET_CRYPTO_hash_get_bit (have, i))
926 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
927 * last bit set will be 31 -- if
928 * i does not reach 512 first... */
935 * Check whether my identity is closer than any known peers. If a
936 * non-null bloomfilter is given, check if this is the closest peer
937 * that hasn't already been routed to.
939 * @param key hash code to check closeness to
940 * @param bloom bloomfilter, exclude these entries from the decision
941 * @return GNUNET_YES if node location is closest,
942 * GNUNET_NO otherwise.
945 am_closest_peer (const GNUNET_HashCode *key,
946 const struct GNUNET_CONTAINER_BloomFilter *bloom)
952 struct PeerInfo *pos;
954 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
956 bucket_num = find_bucket (key);
957 GNUNET_assert (bucket_num >= 0);
958 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
959 pos = k_buckets[bucket_num].head;
961 while ((pos != NULL) && (count < bucket_size))
963 if ((bloom != NULL) &&
965 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
968 continue; /* Skip already checked entries */
970 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
971 if (other_bits > bits)
973 if (other_bits == bits) /* We match the same number of bits */
977 /* No peers closer, we are the closest! */
983 * Select a peer from the routing table that would be a good routing
984 * destination for sending a message for "key". The resulting peer
985 * must not be in the set of blocked peers.<p>
987 * Note that we should not ALWAYS select the closest peer to the
988 * target, peers further away from the target should be chosen with
989 * exponentially declining probability.
991 * FIXME: double-check that this is fine
994 * @param key the key we are selecting a peer to route to
995 * @param bloom a bloomfilter containing entries this request has seen already
996 * @param hops how many hops has this message traversed thus far
997 * @return Peer to route to, or NULL on error
999 static struct PeerInfo *
1000 select_peer (const GNUNET_HashCode *key,
1001 const struct GNUNET_CONTAINER_BloomFilter *bloom,
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),
1040 GNUNET_STATISTICS_update (GDS_stats,
1041 gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
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 = closest_bucket; bc < MAX_BUCKETS; 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,
1068 gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1070 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1071 "Excluded peer `%s' due to BF match in random routing for %s\n",
1072 GNUNET_i2s (&pos->id),
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 = closest_bucket; bc < MAX_BUCKETS; 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 GNUNET_HashCode *key,
1128 struct GNUNET_CONTAINER_BloomFilter *bloom,
1130 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, &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",
1159 GNUNET_CONTAINER_multihashmap_size (all_known_peers),
1160 (unsigned int) hop_count,
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,
1206 unsigned int target_count;
1208 struct PeerInfo **targets;
1209 struct PeerInfo *target;
1210 struct P2PPendingMessage *pending;
1212 struct PeerPutMessage *ppm;
1213 struct GNUNET_PeerIdentity *pp;
1215 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),
1220 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1221 GNUNET_STATISTICS_update (GDS_stats,
1222 gettext_noop ("# PUT requests routed"), 1,
1224 target_count = get_target_peers (key, bf, hop_count,
1225 desired_replication_level,
1227 if (0 == target_count)
1229 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1230 "Routing PUT for %s terminates after %u hops at %s\n",
1232 (unsigned int) hop_count,
1233 GNUNET_i2s (&my_identity));
1236 msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size + sizeof (struct PeerPutMessage);
1237 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1239 put_path_length = 0;
1240 msize = data_size + sizeof (struct PeerPutMessage);
1242 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1245 GNUNET_free (targets);
1248 GNUNET_STATISTICS_update (GDS_stats,
1249 gettext_noop ("# PUT messages queued for transmission"), target_count,
1251 for (i=0;i<target_count;i++)
1253 target = targets[i];
1254 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1255 "Routing PUT for %s after %u hops to %s\n",
1257 (unsigned int) hop_count,
1258 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 == GNUNET_CONTAINER_bloomfilter_test (bf, &target->id.hashPubKey));
1273 GNUNET_assert (GNUNET_OK ==
1274 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1278 pp = (struct GNUNET_PeerIdentity*) &ppm[1];
1279 memcpy (pp, put_path, sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1280 memcpy (&pp[put_path_length], data, data_size);
1281 GNUNET_CONTAINER_DLL_insert_tail (target->head,
1284 target->pending_count++;
1285 process_peer_queue (target);
1287 GNUNET_free (targets);
1292 * Perform a GET operation. Forwards the given request to other
1293 * peers. Does not lookup the key locally. May do nothing if this is
1294 * the only peer in the network (or if we are the closest peer in the
1297 * @param type type of the block
1298 * @param options routing options
1299 * @param desired_replication_level desired replication count
1300 * @param hop_count how many hops did this request traverse so far?
1301 * @param key key for the content
1302 * @param xquery extended query
1303 * @param xquery_size number of bytes in xquery
1304 * @param reply_bf bloomfilter to filter duplicates
1305 * @param reply_bf_mutator mutator for reply_bf
1306 * @param peer_bf filter for peers not to select (again)
1309 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1310 enum GNUNET_DHT_RouteOption options,
1311 uint32_t desired_replication_level,
1313 const GNUNET_HashCode *key,
1316 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1317 uint32_t reply_bf_mutator,
1318 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1320 unsigned int target_count;
1322 struct PeerInfo **targets;
1323 struct PeerInfo *target;
1324 struct P2PPendingMessage *pending;
1326 struct PeerGetMessage *pgm;
1328 size_t reply_bf_size;
1330 GNUNET_assert (NULL != peer_bf);
1331 GNUNET_STATISTICS_update (GDS_stats,
1332 gettext_noop ("# GET requests routed"), 1,
1334 target_count = get_target_peers (key, peer_bf, hop_count,
1335 desired_replication_level,
1337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1338 "Adding myself (%s) to GET bloomfilter for %s\n",
1339 GNUNET_i2s (&my_identity),
1341 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity.hashPubKey);
1342 if (0 == target_count)
1344 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1345 "Routing GET for %s terminates after %u hops at %s\n",
1347 (unsigned int) hop_count,
1348 GNUNET_i2s (&my_identity));
1351 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1352 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1353 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1356 GNUNET_free (targets);
1359 GNUNET_STATISTICS_update (GDS_stats,
1360 gettext_noop ("# GET messages queued for transmission"), target_count,
1362 /* forward request */
1363 for (i=0;i<target_count;i++)
1365 target = targets[i];
1366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1367 "Routing GET for %s after %u hops to %s\n",
1369 (unsigned int) hop_count,
1370 GNUNET_i2s (&target->id));
1371 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1372 pending->importance = 0; /* FIXME */
1373 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1374 pgm = (struct PeerGetMessage*) &pending[1];
1375 pending->msg = &pgm->header;
1376 pgm->header.size = htons (msize);
1377 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1378 pgm->options = htonl (options);
1379 pgm->type = htonl (type);
1380 pgm->hop_count = htonl (hop_count + 1);
1381 pgm->desired_replication_level = htonl (desired_replication_level);
1382 pgm->xquery_size = htonl (xquery_size);
1383 pgm->bf_mutator = reply_bf_mutator;
1384 GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &target->id.hashPubKey));
1385 GNUNET_assert (GNUNET_OK ==
1386 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1390 xq = (char *) &pgm[1];
1391 memcpy (xq, xquery, xquery_size);
1392 if (NULL != reply_bf)
1393 GNUNET_assert (GNUNET_OK ==
1394 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1397 GNUNET_CONTAINER_DLL_insert_tail (target->head,
1400 target->pending_count++;
1401 process_peer_queue (target);
1403 GNUNET_free (targets);
1408 * Handle a reply (route to origin). Only forwards the reply back to
1409 * the given peer. Does not do local caching or forwarding to local
1412 * @param target neighbour that should receive the block (if still connected)
1413 * @param type type of the block
1414 * @param expiration_time when does the content expire
1415 * @param key key for the content
1416 * @param put_path_length number of entries in put_path
1417 * @param put_path peers the original PUT traversed (if tracked)
1418 * @param get_path_length number of entries in put_path
1419 * @param get_path peers this reply has traversed so far (if tracked)
1420 * @param data payload of the reply
1421 * @param data_size number of bytes in data
1424 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1425 enum GNUNET_BLOCK_Type type,
1426 struct GNUNET_TIME_Absolute expiration_time,
1427 const GNUNET_HashCode *key,
1428 unsigned int put_path_length,
1429 const struct GNUNET_PeerIdentity *put_path,
1430 unsigned int get_path_length,
1431 const struct GNUNET_PeerIdentity *get_path,
1435 struct PeerInfo *pi;
1436 struct P2PPendingMessage *pending;
1438 struct PeerResultMessage *prm;
1439 struct GNUNET_PeerIdentity *paths;
1441 msize = data_size + sizeof (struct PeerResultMessage) +
1442 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity);
1443 if ( (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1444 (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1445 (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1446 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE) )
1451 pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers,
1452 &target->hashPubKey);
1455 /* peer disconnected in the meantime, drop reply */
1458 GNUNET_STATISTICS_update (GDS_stats,
1459 gettext_noop ("# RESULT messages queued for transmission"), 1,
1461 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1462 pending->importance = 0; /* FIXME */
1463 pending->timeout = expiration_time;
1464 prm = (struct PeerResultMessage*) &pending[1];
1465 pending->msg = &prm->header;
1466 prm->header.size = htons (msize);
1467 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1468 prm->type = htonl (type);
1469 prm->put_path_length = htonl (put_path_length);
1470 prm->get_path_length = htonl (get_path_length);
1471 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1473 paths = (struct GNUNET_PeerIdentity*) &prm[1];
1474 memcpy (paths, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
1475 memcpy (&paths[put_path_length],
1476 get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1477 memcpy (&paths[put_path_length + get_path_length],
1479 GNUNET_CONTAINER_DLL_insert (pi->head,
1482 pi->pending_count++;
1483 process_peer_queue (pi);
1488 * To be called on core init/fail.
1490 * @param cls service closure
1491 * @param server handle to the server for this service
1492 * @param identity the public identity of this peer
1495 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1496 const struct GNUNET_PeerIdentity *identity)
1498 GNUNET_assert (server != NULL);
1499 my_identity = *identity;
1504 * Core handler for p2p put requests.
1506 * @param cls closure
1507 * @param peer sender of the request
1508 * @param message message
1509 * @param peer peer identity this notification is about
1510 * @param atsi performance data
1511 * @return GNUNET_OK to keep the connection open,
1512 * GNUNET_SYSERR to close it (signal serious error)
1515 handle_dht_p2p_put (void *cls,
1516 const struct GNUNET_PeerIdentity *peer,
1517 const struct GNUNET_MessageHeader *message,
1518 const struct GNUNET_ATS_Information
1521 const struct PeerPutMessage *put;
1522 const struct GNUNET_PeerIdentity *put_path;
1523 const void *payload;
1526 size_t payload_size;
1527 enum GNUNET_DHT_RouteOption options;
1528 struct GNUNET_CONTAINER_BloomFilter *bf;
1529 GNUNET_HashCode test_key;
1531 msize = ntohs (message->size);
1532 if (msize < sizeof (struct PeerPutMessage))
1534 GNUNET_break_op (0);
1537 put = (const struct PeerPutMessage*) message;
1538 putlen = ntohl (put->put_path_length);
1539 if ( (msize < sizeof (struct PeerPutMessage) + putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1540 (putlen > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1542 GNUNET_break_op (0);
1545 GNUNET_STATISTICS_update (GDS_stats,
1546 gettext_noop ("# P2P PUT requests received"), 1,
1548 put_path = (const struct GNUNET_PeerIdentity*) &put[1];
1549 payload = &put_path[putlen];
1550 options = ntohl (put->options);
1551 payload_size = msize - (sizeof (struct PeerPutMessage) +
1552 putlen * sizeof (struct GNUNET_PeerIdentity));
1553 switch (GNUNET_BLOCK_get_key (GDS_block_context,
1555 payload, payload_size,
1559 if (0 != memcmp (&test_key, &put->key, sizeof (GNUNET_HashCode)))
1561 GNUNET_break_op (0);
1566 GNUNET_break_op (0);
1569 /* cannot verify, good luck */
1572 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1573 "PUT for %s at %s\n",
1574 GNUNET_h2s (&put->key),
1575 GNUNET_i2s (&my_identity));
1576 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter,
1578 GNUNET_CONSTANTS_BLOOMFILTER_K);
1579 GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1581 struct GNUNET_PeerIdentity pp[putlen+1];
1583 /* extend 'put path' by sender */
1584 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1586 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1593 /* give to local clients */
1594 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1603 if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1604 (am_closest_peer (&put->key,
1606 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1612 /* route to other peers */
1613 GDS_NEIGHBOURS_handle_put (ntohl (put->type),
1615 ntohl (put->desired_replication_level),
1616 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1617 ntohl (put->hop_count),
1624 GNUNET_CONTAINER_bloomfilter_free (bf);
1630 * We have received a FIND PEER request. Send matching
1633 * @param sender sender of the FIND PEER request
1634 * @param key peers close to this key are desired
1635 * @param bf peers matching this bf are excluded
1636 * @param bf_mutator mutator for bf
1639 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1640 const GNUNET_HashCode *key,
1641 struct GNUNET_CONTAINER_BloomFilter *bf,
1642 uint32_t bf_mutator)
1645 struct PeerBucket *bucket;
1646 struct PeerInfo *peer;
1647 unsigned int choice;
1648 GNUNET_HashCode mhash;
1649 const struct GNUNET_HELLO_Message *hello;
1651 /* first, check about our own HELLO */
1652 if (NULL != GDS_my_hello)
1654 GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1655 if ( (NULL == bf) ||
1656 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) )
1658 GDS_NEIGHBOURS_handle_reply (sender,
1659 GNUNET_BLOCK_TYPE_DHT_HELLO,
1660 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1665 GNUNET_HELLO_size ((const struct GNUNET_HELLO_Message*) GDS_my_hello));
1669 GNUNET_STATISTICS_update (GDS_stats,
1670 gettext_noop ("# FIND PEER requests ignored due to Bloomfilter"), 1,
1676 GNUNET_STATISTICS_update (GDS_stats,
1677 gettext_noop ("# FIND PEER requests ignored due to lack of HELLO"), 1,
1681 /* then, also consider sending a random HELLO from the closest bucket */
1682 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
1683 bucket_idx = closest_bucket;
1685 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1686 if (bucket_idx == GNUNET_SYSERR)
1688 bucket = &k_buckets[bucket_idx];
1689 if (bucket->peers_size == 0)
1691 choice = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1692 bucket->peers_size);
1693 peer = bucket->head;
1696 GNUNET_assert (peer != NULL);
1700 choice = bucket->peers_size;
1705 return; /* no non-masked peer available */
1707 peer = bucket->head;
1708 GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1709 hello = GDS_HELLO_get (&peer->id);
1711 while ( (hello == NULL) ||
1712 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) );
1713 GDS_NEIGHBOURS_handle_reply (sender,
1714 GNUNET_BLOCK_TYPE_DHT_HELLO,
1715 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1720 GNUNET_HELLO_size (hello));
1725 * Core handler for p2p get requests.
1727 * @param cls closure
1728 * @param peer sender of the request
1729 * @param message message
1730 * @param peer peer identity this notification is about
1731 * @param atsi performance data
1732 * @return GNUNET_OK to keep the connection open,
1733 * GNUNET_SYSERR to close it (signal serious error)
1736 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1737 const struct GNUNET_MessageHeader *message,
1738 const struct GNUNET_ATS_Information
1741 struct PeerGetMessage *get;
1742 uint32_t xquery_size;
1743 size_t reply_bf_size;
1745 enum GNUNET_BLOCK_Type type;
1746 enum GNUNET_DHT_RouteOption options;
1747 enum GNUNET_BLOCK_EvaluationResult eval;
1748 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1749 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1752 GNUNET_break (0 != memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)));
1753 /* parse and validate message */
1754 msize = ntohs (message->size);
1755 if (msize < sizeof (struct PeerGetMessage))
1757 GNUNET_break_op (0);
1760 get = (struct PeerGetMessage *) message;
1761 xquery_size = ntohl (get->xquery_size);
1762 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1764 GNUNET_break_op (0);
1767 GNUNET_STATISTICS_update (GDS_stats,
1768 gettext_noop ("# P2P GET requests received"), 1,
1770 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1771 type = ntohl (get->type);
1772 options = ntohl (get->options);
1773 xquery = (const char*) &get[1];
1775 if (reply_bf_size > 0)
1776 reply_bf = GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size],
1778 GNUNET_CONSTANTS_BLOOMFILTER_K);
1779 eval = GNUNET_BLOCK_evaluate (GDS_block_context,
1784 xquery, xquery_size,
1786 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1788 /* request invalid or block type not supported */
1789 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1790 if (NULL != reply_bf)
1791 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1795 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter,
1797 GNUNET_CONSTANTS_BLOOMFILTER_K);
1798 GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &peer->hashPubKey));
1799 /* remember request for routing replies */
1800 GDS_ROUTING_add (peer,
1804 xquery, xquery_size,
1805 reply_bf, get->bf_mutator);
1806 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1807 "GET for %s at %s after %u hops\n",
1808 GNUNET_h2s (&get->key),
1809 GNUNET_i2s (&my_identity),
1810 (unsigned int) ntohl (get->hop_count));
1811 /* local lookup (this may update the reply_bf) */
1812 if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1813 (am_closest_peer (&get->key,
1816 if ( (0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1818 GNUNET_STATISTICS_update (GDS_stats,
1819 gettext_noop ("# P2P FIND PEER requests processed"), 1,
1821 handle_find_peer (peer,
1828 eval = GDS_DATACACHE_handle_get (&get->key,
1830 xquery, xquery_size,
1837 GNUNET_STATISTICS_update (GDS_stats,
1838 gettext_noop ("# P2P GET requests ONLY routed"), 1,
1842 /* P2P forwarding */
1843 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1844 GDS_NEIGHBOURS_handle_get (type,
1846 ntohl (get->desired_replication_level),
1847 ntohl (get->hop_count),
1849 xquery, xquery_size,
1854 if (NULL != reply_bf)
1855 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1856 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
1862 * Core handler for p2p result messages.
1864 * @param cls closure
1865 * @param message message
1866 * @param peer peer identity this notification is about
1867 * @param atsi performance data
1868 * @return GNUNET_YES (do not cut p2p connection)
1871 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1872 const struct GNUNET_MessageHeader *message,
1873 const struct GNUNET_ATS_Information
1876 const struct PeerResultMessage *prm;
1877 const struct GNUNET_PeerIdentity *put_path;
1878 const struct GNUNET_PeerIdentity *get_path;
1880 uint32_t get_path_length;
1881 uint32_t put_path_length;
1884 enum GNUNET_BLOCK_Type type;
1886 /* parse and validate message */
1887 msize = ntohs (message->size);
1888 if (msize < sizeof (struct PeerResultMessage))
1890 GNUNET_break_op (0);
1893 prm = (struct PeerResultMessage *) message;
1894 put_path_length = ntohl (prm->put_path_length);
1895 get_path_length = ntohl (prm->get_path_length);
1896 if ( (msize < sizeof (struct PeerResultMessage) +
1897 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity)) ||
1898 (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1899 (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1901 GNUNET_break_op (0);
1904 GNUNET_STATISTICS_update (GDS_stats,
1905 gettext_noop ("# P2P RESULTS received"), 1,
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];
1911 data_size = msize - (sizeof (struct PeerResultMessage) +
1912 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1914 /* if we got a HELLO, consider it for our own routing table */
1915 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
1917 const struct GNUNET_MessageHeader *h;
1918 struct GNUNET_PeerIdentity pid;
1921 /* Should be a HELLO, validate and consider using it! */
1922 if (data_size < sizeof (struct GNUNET_MessageHeader))
1924 GNUNET_break_op (0);
1928 if (data_size != ntohs (h->size))
1930 GNUNET_break_op (0);
1934 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message*) h,
1937 GNUNET_break_op (0);
1940 if (0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
1942 bucket = find_bucket (&pid.hashPubKey);
1943 if ( (bucket >= 0) &&
1944 (k_buckets[bucket].peers_size < bucket_size) )
1946 if (NULL != GDS_transport_handle)
1948 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle,
1950 GNUNET_TRANSPORT_try_connect (GDS_transport_handle,
1957 /* append 'peer' to 'get_path' */
1959 struct GNUNET_PeerIdentity xget_path[get_path_length+1];
1961 memcpy (xget_path, get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1962 xget_path[get_path_length] = *peer;
1965 /* forward to local clients */
1966 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
1976 /* forward to other peers */
1977 GDS_ROUTING_process (type,
1978 GNUNET_TIME_absolute_ntoh (prm->expiration_time),
1992 * Initialize neighbours subsystem.
1994 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1997 GDS_NEIGHBOURS_init ()
1999 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2000 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2001 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2002 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2005 unsigned long long temp_config_num;
2008 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2010 bucket_size = (unsigned int) temp_config_num;
2011 atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2012 coreAPI = GNUNET_CORE_connect (GDS_cfg,
2016 &handle_core_connect,
2017 &handle_core_disconnect,
2021 if (coreAPI == NULL)
2022 return GNUNET_SYSERR;
2023 all_known_peers = GNUNET_CONTAINER_multihashmap_create (256);
2029 * Shutdown neighbours subsystem.
2032 GDS_NEIGHBOURS_done ()
2034 if (coreAPI == NULL)
2036 GNUNET_CORE_disconnect (coreAPI);
2038 GNUNET_ATS_performance_done (atsAPI);
2040 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2041 GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2042 all_known_peers = NULL;
2043 if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2045 GNUNET_SCHEDULER_cancel (find_peer_task);
2046 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2051 /* end of gnunet-service-dht_neighbours.c */