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_core_service.h"
36 #include "gnunet_datacache_lib.h"
37 #include "gnunet_transport_service.h"
38 #include "gnunet_hello_lib.h"
39 #include "gnunet_dht_service.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet-service-dht.h"
42 #include "gnunet-service-dht_clients.h"
43 #include "gnunet-service-dht_datacache.h"
44 #include "gnunet-service-dht_hello.h"
45 #include "gnunet-service-dht_neighbours.h"
46 #include "gnunet-service-dht_nse.h"
47 #include "gnunet-service-dht_routing.h"
52 * How many buckets will we allow total.
54 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
57 * What is the maximum number of peers in a given bucket.
59 #define DEFAULT_BUCKET_SIZE 8
62 * Desired replication level for FIND PEER requests
64 #define FIND_PEER_REPLICATION_LEVEL 4
67 * Maximum allowed replication level for all requests.
69 #define MAXIMUM_REPLICATION_LEVEL 16
72 * How often to update our preference levels for peers in our routing tables.
74 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
77 * How long at least to wait before sending another find peer request.
79 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
82 * How long at most to wait before sending another find peer request.
84 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10)
87 * How long at most to wait for transmission of a GET request to another peer?
89 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
98 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
100 struct GNUNET_MessageHeader header;
105 uint32_t options GNUNET_PACKED;
110 uint32_t type GNUNET_PACKED;
115 uint32_t hop_count GNUNET_PACKED;
118 * Replication level for this message
120 uint32_t desired_replication_level GNUNET_PACKED;
123 * Length of the PUT path that follows (if tracked).
125 uint32_t put_path_length GNUNET_PACKED;
128 * When does the content expire?
130 struct GNUNET_TIME_AbsoluteNBO expiration_time;
133 * Bloomfilter (for peer identities) to stop circular routes
135 char bloomfilter[DHT_BLOOM_SIZE];
138 * The key we are storing under.
142 /* put path (if tracked) */
152 struct PeerResultMessage
155 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
157 struct GNUNET_MessageHeader header;
162 uint32_t type GNUNET_PACKED;
165 * Length of the PUT path that follows (if tracked).
167 uint32_t put_path_length GNUNET_PACKED;
170 * Length of the GET path that follows (if tracked).
172 uint32_t get_path_length GNUNET_PACKED;
175 * When does the content expire?
177 struct GNUNET_TIME_AbsoluteNBO expiration_time;
180 * The key of the corresponding GET request.
184 /* put path (if tracked) */
186 /* get path (if tracked) */
196 struct PeerGetMessage
199 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_GET
201 struct GNUNET_MessageHeader header;
206 uint32_t options GNUNET_PACKED;
209 * Desired content type.
211 uint32_t type GNUNET_PACKED;
216 uint32_t hop_count GNUNET_PACKED;
219 * Desired replication level for this request.
221 uint32_t desired_replication_level GNUNET_PACKED;
224 * Size of the extended query.
226 uint32_t xquery_size;
229 * Bloomfilter mutator.
234 * Bloomfilter (for peer identities) to stop circular routes
236 char bloomfilter[DHT_BLOOM_SIZE];
239 * The key we are looking for.
245 /* result bloomfilter */
251 * Linked list of messages to send to a particular other peer.
253 struct P2PPendingMessage
256 * Pointer to next item in the list
258 struct P2PPendingMessage *next;
261 * Pointer to previous item in the list
263 struct P2PPendingMessage *prev;
266 * Message importance level. FIXME: used? useful?
268 unsigned int importance;
271 * When does this message time out?
273 struct GNUNET_TIME_Absolute timeout;
276 * Actual message to be sent, allocated at the end of the struct:
277 * // msg = (cast) &pm[1];
278 * // memcpy (&pm[1], data, len);
280 const struct GNUNET_MessageHeader *msg;
286 * Entry for a peer in a bucket.
291 * Next peer entry (DLL)
293 struct PeerInfo *next;
296 * Prev peer entry (DLL)
298 struct PeerInfo *prev;
301 * Count of outstanding messages for peer. FIXME: NEEDED?
302 * FIXME: bound queue size!?
304 unsigned int pending_count;
307 * Head of pending messages to be sent to this peer.
309 struct P2PPendingMessage *head;
312 * Tail of pending messages to be sent to this peer.
314 struct P2PPendingMessage *tail;
317 * Core handle for sending messages to this peer.
319 struct GNUNET_CORE_TransmitHandle *th;
322 * Preference update context
324 struct GNUNET_CORE_InformationRequestContext *info_ctx;
327 * Task for scheduling preference updates
329 GNUNET_SCHEDULER_TaskIdentifier preference_task;
332 * What is the identity of the peer?
334 struct GNUNET_PeerIdentity id;
338 * What is the average latency for replies received?
340 struct GNUNET_TIME_Relative latency;
343 * Transport level distance to peer.
345 unsigned int distance;
352 * Peers are grouped into buckets.
359 struct PeerInfo *head;
364 struct PeerInfo *tail;
367 * Number of peers in the bucket.
369 unsigned int peers_size;
374 * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
376 static unsigned int closest_bucket;
379 * How many peers have we added since we sent out our last
382 static unsigned int newly_found_peers;
385 * The buckets. Array of size MAX_BUCKET_SIZE. Offset 0 means 0 bits matching.
387 static struct PeerBucket k_buckets[MAX_BUCKETS];
390 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
392 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
395 * Maximum size for each bucket.
397 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
400 * Task that sends FIND PEER requests.
402 static GNUNET_SCHEDULER_TaskIdentifier find_peer_task;
405 * Identity of this peer.
407 static struct GNUNET_PeerIdentity my_identity;
410 * Handle to GNUnet core.
412 static struct GNUNET_CORE_Handle *coreAPI;
417 * Find the optimal bucket for this key.
419 * @param hc the hashcode to compare our identity to
420 * @return the proper bucket index, or GNUNET_SYSERR
421 * on error (same hashcode)
424 find_bucket (const GNUNET_HashCode * hc)
428 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
429 if (bits == MAX_BUCKETS)
431 /* How can all bits match? Got my own ID? */
433 return GNUNET_SYSERR;
435 return MAX_BUCKETS - bits - 1;
440 * Let GNUnet core know that we like the given peer.
442 * @param cls the 'struct PeerInfo' of the peer
443 * @param tc scheduler context.
446 update_core_preference (void *cls,
447 const struct GNUNET_SCHEDULER_TaskContext *tc);
451 * Function called with statistics about the given peer.
454 * @param peer identifies the peer
455 * @param bpm_out set to the current bandwidth limit (sending) for this peer
456 * @param amount set to the amount that was actually reserved or unreserved;
457 * either the full requested amount or zero (no partial reservations)
458 * @param res_delay if the reservation could not be satisfied (amount was 0), how
459 * long should the client wait until re-trying?
460 * @param preference current traffic preference for the given peer
463 update_core_preference_finish (void *cls,
464 const struct GNUNET_PeerIdentity *peer,
465 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
467 struct GNUNET_TIME_Relative res_delay,
470 struct PeerInfo *peer_info = cls;
472 peer_info->info_ctx = NULL;
473 peer_info->preference_task
474 = GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
475 &update_core_preference, peer_info);
480 * Let GNUnet core know that we like the given peer.
482 * @param cls the 'struct PeerInfo' of the peer
483 * @param tc scheduler context.
486 update_core_preference (void *cls,
487 const struct GNUNET_SCHEDULER_TaskContext *tc)
489 struct PeerInfo *peer = cls;
491 unsigned int matching;
494 peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
495 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
498 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
499 &peer->id.hashPubKey);
502 bucket = find_bucket (&peer->id.hashPubKey);
503 if (bucket == GNUNET_SYSERR)
507 GNUNET_assert (k_buckets[bucket].peers_size != 0);
508 preference = (1LL << matching) / k_buckets[bucket].peers_size;
512 peer->preference_task
513 = GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
514 &update_core_preference, peer);
517 GNUNET_STATISTICS_update (GDS_stats,
518 gettext_noop ("# Preference updates given to core"), 1,
521 GNUNET_CORE_peer_change_preference (coreAPI, &peer->id,
522 GNUNET_TIME_UNIT_FOREVER_REL,
523 GNUNET_BANDWIDTH_VALUE_MAX, 0,
525 &update_core_preference_finish, peer);
530 * Closure for 'add_known_to_bloom'.
532 struct BloomConstructorContext
535 * Bloom filter under construction.
537 struct GNUNET_CONTAINER_BloomFilter *bloom;
547 * Add each of the peers we already know to the bloom filter of
548 * the request so that we don't get duplicate HELLOs.
550 * @param cls the 'struct BloomConstructorContext'.
551 * @param key peer identity to add to the bloom filter
552 * @param value value the peer information (unused)
553 * @return GNUNET_YES (we should continue to iterate)
556 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
558 struct BloomConstructorContext *ctx = cls;
561 GNUNET_BLOCK_mingle_hash (key, ctx->bf_mutator, &mh);
562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
563 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
566 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
572 * Task to send a find peer message for our own peer identifier
573 * so that we can find the closest peers in the network to ourselves
574 * and attempt to connect to them.
576 * @param cls closure for this task
577 * @param tc the context under which the task is running
580 send_find_peer_message (void *cls,
581 const struct GNUNET_SCHEDULER_TaskContext *tc)
583 struct GNUNET_TIME_Relative next_send_time;
584 struct BloomConstructorContext bcc;
585 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
587 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
588 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
590 if (newly_found_peers > bucket_size)
592 /* If we are finding many peers already, no need to send out our request right now! */
593 find_peer_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
594 &send_find_peer_message, NULL);
595 newly_found_peers = 0;
598 bcc.bf_mutator = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
600 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, GNUNET_CONSTANTS_BLOOMFILTER_K);
601 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers,
604 GNUNET_STATISTICS_update (GDS_stats,
605 gettext_noop ("# FIND PEER messages initiated"), 1,
607 peer_bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
609 GNUNET_CONSTANTS_BLOOMFILTER_K);
610 // FIXME: pass priority!?
611 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
612 GNUNET_DHT_RO_FIND_PEER,
613 FIND_PEER_REPLICATION_LEVEL,
615 &my_identity.hashPubKey,
617 bcc.bloom, bcc.bf_mutator,
619 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
620 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
621 /* schedule next round */
622 next_send_time.rel_value =
623 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
624 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
625 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / (newly_found_peers+1));
626 newly_found_peers = 0;
627 find_peer_task = GNUNET_SCHEDULER_add_delayed (next_send_time,
628 &send_find_peer_message,
634 * Method called whenever a peer connects.
637 * @param peer peer identity this notification is about
638 * @param atsi performance data
641 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
642 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
644 struct PeerInfo *ret;
647 /* Check for connect to self message */
648 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
650 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
651 "Connected %s to %s\n",
652 GNUNET_i2s (&my_identity),
653 GNUNET_h2s (&peer->hashPubKey));
655 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
661 GNUNET_STATISTICS_update (GDS_stats,
662 gettext_noop ("# Peers connected"), 1,
664 peer_bucket = find_bucket (&peer->hashPubKey);
665 GNUNET_assert ( (peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS) );
666 ret = GNUNET_malloc (sizeof (struct PeerInfo));
668 ret->latency = latency;
669 ret->distance = distance;
672 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
673 k_buckets[peer_bucket].tail, ret);
674 k_buckets[peer_bucket].peers_size++;
675 closest_bucket = GNUNET_MAX (closest_bucket,
677 if ( (peer_bucket > 0) &&
678 (k_buckets[peer_bucket].peers_size <= bucket_size) )
680 ret->preference_task = GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
683 GNUNET_assert (GNUNET_OK ==
684 GNUNET_CONTAINER_multihashmap_put (all_known_peers,
685 &peer->hashPubKey, ret,
686 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
687 if (1 == GNUNET_CONTAINER_multihashmap_size (all_known_peers))
689 /* got a first connection, good time to start with FIND PEER requests... */
690 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message,
697 * Method called whenever a peer disconnects.
700 * @param peer peer identity this notification is about
703 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
705 struct PeerInfo *to_remove;
707 struct P2PPendingMessage *pos;
709 /* Check for disconnect from self message */
710 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
712 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
713 "Disconnected %s from %s\n",
714 GNUNET_i2s (&my_identity),
715 GNUNET_h2s (&peer->hashPubKey));
717 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
718 if (NULL == to_remove)
723 GNUNET_STATISTICS_update (GDS_stats,
724 gettext_noop ("# Peers connected"), -1,
726 GNUNET_assert (GNUNET_YES ==
727 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
730 if (NULL != to_remove->info_ctx)
732 GNUNET_CORE_peer_change_preference_cancel (to_remove->info_ctx);
733 to_remove->info_ctx = NULL;
735 if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
737 GNUNET_SCHEDULER_cancel (to_remove->preference_task);
738 to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
740 current_bucket = find_bucket (&to_remove->id.hashPubKey);
741 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
742 k_buckets[current_bucket].tail,
744 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
745 k_buckets[current_bucket].peers_size--;
746 while ( (closest_bucket > 0) &&
747 (k_buckets[closest_bucket].peers_size == 0) )
750 if (to_remove->th != NULL)
752 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
753 to_remove->th = NULL;
755 while (NULL != (pos = to_remove->head))
757 GNUNET_CONTAINER_DLL_remove (to_remove->head,
766 * Called when core is ready to send a message we asked for
767 * out to the destination.
769 * @param cls the 'struct PeerInfo' of the target peer
770 * @param size number of bytes available in buf
771 * @param buf where the callee should write the message
772 * @return number of bytes written to buf
775 core_transmit_notify (void *cls, size_t size, void *buf)
777 struct PeerInfo *peer = cls;
779 struct P2PPendingMessage *pending;
784 while ( (NULL != (pending = peer->head)) &&
785 (GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value == 0) )
787 peer->pending_count--;
788 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
789 GNUNET_free (pending);
793 /* no messages pending */
799 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
801 GNUNET_TIME_absolute_get_remaining (pending->timeout),
802 &peer->id, ntohs (pending->msg->size),
803 &core_transmit_notify, peer);
807 while ( (NULL != (pending = peer->head)) &&
808 (size - off >= (msize = ntohs (pending->msg->size))) )
810 GNUNET_STATISTICS_update (GDS_stats,
811 gettext_noop ("# Bytes transmitted to other peers"), msize,
813 memcpy (&cbuf[off], pending->msg, msize);
815 peer->pending_count--;
816 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
817 GNUNET_free (pending);
819 if (peer->head != NULL)
822 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
824 GNUNET_TIME_absolute_get_remaining (pending->timeout),
826 &core_transmit_notify, peer);
833 * Transmit all messages in the peer's message queue.
835 * @param peer message queue to process
838 process_peer_queue (struct PeerInfo *peer)
840 struct P2PPendingMessage *pending;
842 if (NULL == (pending = peer->head))
844 if (NULL != peer->th)
846 GNUNET_STATISTICS_update (GDS_stats,
847 gettext_noop ("# Bytes of bandwdith requested from core"),
848 ntohs (pending->msg->size),
851 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
853 GNUNET_TIME_absolute_get_remaining (pending->timeout),
855 ntohs (pending->msg->size),
856 &core_transmit_notify, peer);
861 * To how many peers should we (on average) forward the request to
862 * obtain the desired target_replication count (on average).
864 * @param hop_count number of hops the message has traversed
865 * @param target_replication the number of total paths desired
866 * @return Some number of peers to forward the message to
869 get_forward_count (uint32_t hop_count,
870 uint32_t target_replication)
872 uint32_t random_value;
873 uint32_t forward_count;
876 if (hop_count > GDS_NSE_get () * 6.0)
878 /* forcefully terminate */
881 if (hop_count > GDS_NSE_get () * 4.0)
883 /* Once we have reached our ideal number of hops, only forward to 1 peer */
886 /* bound by system-wide maximum */
887 target_replication = GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL,
890 1 + (target_replication - 1.0) / (GDS_NSE_get () +
891 ((float) (target_replication - 1.0) *
893 /* Set forward count to floor of target_value */
894 forward_count = (uint32_t) target_value;
895 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
896 target_value = target_value - forward_count;
898 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
899 if (random_value < (target_value * UINT32_MAX))
901 return forward_count;
906 * Compute the distance between have and target as a 32-bit value.
907 * Differences in the lower bits must count stronger than differences
908 * in the higher bits.
910 * @return 0 if have==target, otherwise a number
911 * that is larger as the distance between
912 * the two hash codes increases
915 get_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
922 /* We have to represent the distance between two 2^9 (=512)-bit
923 * numbers as a 2^5 (=32)-bit number with "0" being used for the
924 * two numbers being identical; furthermore, we need to
925 * guarantee that a difference in the number of matching
926 * bits is always represented in the result.
928 * We use 2^32/2^9 numerical values to distinguish between
929 * hash codes that have the same LSB bit distance and
930 * use the highest 2^9 bits of the result to signify the
931 * number of (mis)matching LSB bits; if we have 0 matching
932 * and hence 512 mismatching LSB bits we return -1 (since
933 * 512 itself cannot be represented with 9 bits) */
935 /* first, calculate the most significant 9 bits of our
936 * result, aka the number of LSBs */
937 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
938 /* bucket is now a value between 0 and 512 */
940 return 0; /* perfect match */
942 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
943 * below, we'd end up with max+1 (overflow)) */
945 /* calculate the most significant bits of the final result */
946 msb = (512 - bucket) << (32 - 9);
947 /* calculate the 32-9 least significant bits of the final result by
948 * looking at the differences in the 32-9 bits following the
949 * mismatching bit at 'bucket' */
952 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
954 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
955 GNUNET_CRYPTO_hash_get_bit (have, i))
956 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
957 * last bit set will be 31 -- if
958 * i does not reach 512 first... */
965 * Check whether my identity is closer than any known peers. If a
966 * non-null bloomfilter is given, check if this is the closest peer
967 * that hasn't already been routed to.
969 * @param key hash code to check closeness to
970 * @param bloom bloomfilter, exclude these entries from the decision
971 * @return GNUNET_YES if node location is closest,
972 * GNUNET_NO otherwise.
975 am_closest_peer (const GNUNET_HashCode *key,
976 const struct GNUNET_CONTAINER_BloomFilter *bloom)
982 struct PeerInfo *pos;
984 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
986 bucket_num = find_bucket (key);
987 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
988 pos = k_buckets[bucket_num].head;
990 while ((pos != NULL) && (count < bucket_size))
992 if ((bloom != NULL) &&
994 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
997 continue; /* Skip already checked entries */
999 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
1000 if (other_bits > bits)
1002 if (other_bits == bits) /* We match the same number of bits */
1006 /* No peers closer, we are the closest! */
1012 * Select a peer from the routing table that would be a good routing
1013 * destination for sending a message for "key". The resulting peer
1014 * must not be in the set of blocked peers.<p>
1016 * Note that we should not ALWAYS select the closest peer to the
1017 * target, peers further away from the target should be chosen with
1018 * exponentially declining probability.
1020 * FIXME: double-check that this is fine
1023 * @param key the key we are selecting a peer to route to
1024 * @param bloom a bloomfilter containing entries this request has seen already
1025 * @param hops how many hops has this message traversed thus far
1026 * @return Peer to route to, or NULL on error
1028 static struct PeerInfo *
1029 select_peer (const GNUNET_HashCode *key,
1030 const struct GNUNET_CONTAINER_BloomFilter *bloom,
1035 unsigned int selected;
1036 struct PeerInfo *pos;
1038 unsigned int smallest_distance;
1039 struct PeerInfo *chosen;
1041 if (hops >= GDS_NSE_get ())
1043 /* greedy selection (closest peer that is not in bloomfilter) */
1044 smallest_distance = UINT_MAX;
1046 for (bc = 0; bc < closest_bucket; bc++)
1048 pos = k_buckets[bc].head;
1050 while ((pos != NULL) && (count < bucket_size))
1052 if ( (bloom == NULL) ||
1054 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1056 dist = get_distance (key, &pos->id.hashPubKey);
1057 if (dist < smallest_distance)
1060 smallest_distance = dist;
1065 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1066 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1067 GNUNET_i2s (&pos->id),
1069 GNUNET_STATISTICS_update (GDS_stats,
1070 gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1078 GNUNET_STATISTICS_update (GDS_stats,
1079 gettext_noop ("# Peer selection failed"), 1,
1084 /* select "random" peer */
1085 /* count number of peers that are available and not filtered */
1087 for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1089 pos = k_buckets[bc].head;
1090 while ((pos != NULL) && (count < bucket_size))
1092 if ( (bloom != NULL) &&
1094 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1096 GNUNET_STATISTICS_update (GDS_stats,
1097 gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100 "Excluded peer `%s' due to BF match in random routing for %s\n",
1101 GNUNET_i2s (&pos->id),
1104 continue; /* Ignore bloomfiltered peers */
1110 if (count == 0) /* No peers to select from! */
1112 GNUNET_STATISTICS_update (GDS_stats,
1113 gettext_noop ("# Peer selection failed"), 1,
1117 /* Now actually choose a peer */
1118 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1120 for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1122 pos = k_buckets[bc].head;
1123 while ((pos != NULL) && (count < bucket_size))
1125 if ( (bloom != NULL) &&
1127 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1130 continue; /* Ignore bloomfiltered peers */
1132 if (0 == selected--)
1143 * Compute the set of peers that the given request should be
1146 * @param key routing key
1147 * @param bloom bloom filter excluding peers as targets, all selected
1148 * peers will be added to the bloom filter
1149 * @param hop_count number of hops the request has traversed so far
1150 * @param target_replication desired number of replicas
1151 * @param targets where to store an array of target peers (to be
1152 * free'd by the caller)
1153 * @return number of peers returned in 'targets'.
1156 get_target_peers (const GNUNET_HashCode *key,
1157 struct GNUNET_CONTAINER_BloomFilter *bloom,
1159 uint32_t target_replication,
1160 struct PeerInfo ***targets)
1164 struct PeerInfo **rtargets;
1165 struct PeerInfo *nxt;
1167 GNUNET_assert (NULL != bloom);
1168 ret = get_forward_count (hop_count, target_replication);
1174 rtargets = GNUNET_malloc (sizeof (struct PeerInfo*) * ret);
1175 for (off = 0; off < ret; off++)
1177 nxt = select_peer (key, bloom, hop_count);
1180 rtargets[off] = nxt;
1181 GNUNET_break (GNUNET_NO ==
1182 GNUNET_CONTAINER_bloomfilter_test (bloom, &nxt->id.hashPubKey));
1183 GNUNET_CONTAINER_bloomfilter_add (bloom, &rtargets[off]->id.hashPubKey);
1185 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1186 "Selected %u/%u peers at hop %u for %s (target was %u)\n",
1188 GNUNET_CONTAINER_multihashmap_size (all_known_peers),
1189 (unsigned int) hop_count,
1194 GNUNET_free (rtargets);
1198 *targets = rtargets;
1204 * Perform a PUT operation. Forwards the given request to other
1205 * peers. Does not store the data locally. Does not give the
1206 * data to local clients. May do nothing if this is the only
1207 * peer in the network (or if we are the closest peer in the
1210 * @param type type of the block
1211 * @param options routing options
1212 * @param desired_replication_level desired replication count
1213 * @param expiration_time when does the content expire
1214 * @param hop_count how many hops has this message traversed so far
1215 * @param bf Bloom filter of peers this PUT has already traversed
1216 * @param key key for the content
1217 * @param put_path_length number of entries in put_path
1218 * @param put_path peers this request has traversed so far (if tracked)
1219 * @param data payload to store
1220 * @param data_size number of bytes in data
1223 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1224 enum GNUNET_DHT_RouteOption options,
1225 uint32_t desired_replication_level,
1226 struct GNUNET_TIME_Absolute expiration_time,
1228 struct GNUNET_CONTAINER_BloomFilter *bf,
1229 const GNUNET_HashCode *key,
1230 unsigned int put_path_length,
1231 struct GNUNET_PeerIdentity *put_path,
1235 unsigned int target_count;
1237 struct PeerInfo **targets;
1238 struct PeerInfo *target;
1239 struct P2PPendingMessage *pending;
1241 struct PeerPutMessage *ppm;
1242 struct GNUNET_PeerIdentity *pp;
1244 GNUNET_assert (NULL != bf);
1245 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1246 "Adding myself (%s) to PUT bloomfilter for %s\n",
1247 GNUNET_i2s (&my_identity),
1249 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1250 GNUNET_STATISTICS_update (GDS_stats,
1251 gettext_noop ("# PUT requests routed"), 1,
1253 target_count = get_target_peers (key, bf, hop_count,
1254 desired_replication_level,
1256 if (0 == target_count)
1258 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1259 "Routing PUT for %s terminates after %u hops at %s\n",
1261 (unsigned int) hop_count,
1262 GNUNET_i2s (&my_identity));
1265 msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size + sizeof (struct PeerPutMessage);
1266 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1268 put_path_length = 0;
1269 msize = data_size + sizeof (struct PeerPutMessage);
1271 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1276 GNUNET_STATISTICS_update (GDS_stats,
1277 gettext_noop ("# PUT messages queued for transmission"), target_count,
1279 for (i=0;i<target_count;i++)
1281 target = targets[i];
1282 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1283 "Routing PUT for %s after %u hops to %s\n",
1285 (unsigned int) hop_count,
1286 GNUNET_i2s (&target->id));
1287 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1288 pending->importance = 0; /* FIXME */
1289 pending->timeout = expiration_time;
1290 ppm = (struct PeerPutMessage*) &pending[1];
1291 pending->msg = &ppm->header;
1292 ppm->header.size = htons (msize);
1293 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1294 ppm->options = htonl (options);
1295 ppm->type = htonl (type);
1296 ppm->hop_count = htonl (hop_count + 1);
1297 ppm->desired_replication_level = htonl (desired_replication_level);
1298 ppm->put_path_length = htonl (put_path_length);
1299 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1300 GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &target->id.hashPubKey));
1301 GNUNET_assert (GNUNET_OK ==
1302 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1306 pp = (struct GNUNET_PeerIdentity*) &ppm[1];
1307 memcpy (pp, put_path, sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1308 memcpy (&pp[put_path_length], data, data_size);
1309 GNUNET_CONTAINER_DLL_insert_tail (target->head,
1312 target->pending_count++;
1313 process_peer_queue (target);
1315 GNUNET_free (targets);
1320 * Perform a GET operation. Forwards the given request to other
1321 * peers. Does not lookup the key locally. May do nothing if this is
1322 * the only peer in the network (or if we are the closest peer in the
1325 * @param type type of the block
1326 * @param options routing options
1327 * @param desired_replication_level desired replication count
1328 * @param hop_count how many hops did this request traverse so far?
1329 * @param key key for the content
1330 * @param xquery extended query
1331 * @param xquery_size number of bytes in xquery
1332 * @param reply_bf bloomfilter to filter duplicates
1333 * @param reply_bf_mutator mutator for reply_bf
1334 * @param peer_bf filter for peers not to select (again)
1337 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1338 enum GNUNET_DHT_RouteOption options,
1339 uint32_t desired_replication_level,
1341 const GNUNET_HashCode *key,
1344 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1345 uint32_t reply_bf_mutator,
1346 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1348 unsigned int target_count;
1350 struct PeerInfo **targets;
1351 struct PeerInfo *target;
1352 struct P2PPendingMessage *pending;
1354 struct PeerGetMessage *pgm;
1356 size_t reply_bf_size;
1358 GNUNET_assert (NULL != peer_bf);
1359 GNUNET_STATISTICS_update (GDS_stats,
1360 gettext_noop ("# GET requests routed"), 1,
1362 target_count = get_target_peers (key, peer_bf, hop_count,
1363 desired_replication_level,
1365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1366 "Adding myself (%s) to GET bloomfilter for %s\n",
1367 GNUNET_i2s (&my_identity),
1369 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity.hashPubKey);
1370 if (0 == target_count)
1372 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1373 "Routing GET for %s terminates after %u hops at %s\n",
1375 (unsigned int) hop_count,
1376 GNUNET_i2s (&my_identity));
1379 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1380 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1381 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1386 GNUNET_STATISTICS_update (GDS_stats,
1387 gettext_noop ("# GET messages queued for transmission"), target_count,
1389 /* forward request */
1390 for (i=0;i<target_count;i++)
1392 target = targets[i];
1393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1394 "Routing GET for %s after %u hops to %s\n",
1396 (unsigned int) hop_count,
1397 GNUNET_i2s (&target->id));
1398 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1399 pending->importance = 0; /* FIXME */
1400 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1401 pgm = (struct PeerGetMessage*) &pending[1];
1402 pending->msg = &pgm->header;
1403 pgm->header.size = htons (msize);
1404 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1405 pgm->options = htonl (options);
1406 pgm->type = htonl (type);
1407 pgm->hop_count = htonl (hop_count + 1);
1408 pgm->desired_replication_level = htonl (desired_replication_level);
1409 pgm->xquery_size = htonl (xquery_size);
1410 pgm->bf_mutator = reply_bf_mutator;
1411 GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &target->id.hashPubKey));
1412 GNUNET_assert (GNUNET_OK ==
1413 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1417 xq = (char *) &pgm[1];
1418 memcpy (xq, xquery, xquery_size);
1419 if (NULL != reply_bf)
1420 GNUNET_assert (GNUNET_OK ==
1421 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1424 GNUNET_CONTAINER_DLL_insert_tail (target->head,
1427 target->pending_count++;
1428 process_peer_queue (target);
1430 GNUNET_free (targets);
1435 * Handle a reply (route to origin). Only forwards the reply back to
1436 * the given peer. Does not do local caching or forwarding to local
1439 * @param target neighbour that should receive the block (if still connected)
1440 * @param type type of the block
1441 * @param expiration_time when does the content expire
1442 * @param key key for the content
1443 * @param put_path_length number of entries in put_path
1444 * @param put_path peers the original PUT traversed (if tracked)
1445 * @param get_path_length number of entries in put_path
1446 * @param get_path peers this reply has traversed so far (if tracked)
1447 * @param data payload of the reply
1448 * @param data_size number of bytes in data
1451 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1452 enum GNUNET_BLOCK_Type type,
1453 struct GNUNET_TIME_Absolute expiration_time,
1454 const GNUNET_HashCode *key,
1455 unsigned int put_path_length,
1456 const struct GNUNET_PeerIdentity *put_path,
1457 unsigned int get_path_length,
1458 const struct GNUNET_PeerIdentity *get_path,
1462 struct PeerInfo *pi;
1463 struct P2PPendingMessage *pending;
1465 struct PeerResultMessage *prm;
1466 struct GNUNET_PeerIdentity *paths;
1468 msize = data_size + sizeof (struct PeerResultMessage) +
1469 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity);
1470 if ( (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1471 (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1472 (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1473 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE) )
1478 pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers,
1479 &target->hashPubKey);
1482 /* peer disconnected in the meantime, drop reply */
1485 GNUNET_STATISTICS_update (GDS_stats,
1486 gettext_noop ("# RESULT messages queued for transmission"), 1,
1488 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1489 pending->importance = 0; /* FIXME */
1490 pending->timeout = expiration_time;
1491 prm = (struct PeerResultMessage*) &pending[1];
1492 pending->msg = &prm->header;
1493 prm->header.size = htons (msize);
1494 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1495 prm->type = htonl (type);
1496 prm->put_path_length = htonl (put_path_length);
1497 prm->get_path_length = htonl (get_path_length);
1498 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1500 paths = (struct GNUNET_PeerIdentity*) &prm[1];
1501 memcpy (paths, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
1502 memcpy (&paths[put_path_length],
1503 get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1504 memcpy (&paths[put_path_length + get_path_length],
1506 GNUNET_CONTAINER_DLL_insert (pi->head,
1509 pi->pending_count++;
1510 process_peer_queue (pi);
1515 * To be called on core init/fail.
1517 * @param cls service closure
1518 * @param server handle to the server for this service
1519 * @param identity the public identity of this peer
1520 * @param publicKey the public key of this peer
1523 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1524 const struct GNUNET_PeerIdentity *identity,
1525 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1527 GNUNET_assert (server != NULL);
1528 my_identity = *identity;
1533 * Core handler for p2p put requests.
1535 * @param cls closure
1536 * @param peer sender of the request
1537 * @param message message
1538 * @param peer peer identity this notification is about
1539 * @param atsi performance data
1540 * @return GNUNET_OK to keep the connection open,
1541 * GNUNET_SYSERR to close it (signal serious error)
1544 handle_dht_p2p_put (void *cls,
1545 const struct GNUNET_PeerIdentity *peer,
1546 const struct GNUNET_MessageHeader *message,
1547 const struct GNUNET_TRANSPORT_ATS_Information
1550 const struct PeerPutMessage *put;
1551 const struct GNUNET_PeerIdentity *put_path;
1552 const void *payload;
1555 size_t payload_size;
1556 enum GNUNET_DHT_RouteOption options;
1557 struct GNUNET_CONTAINER_BloomFilter *bf;
1558 GNUNET_HashCode test_key;
1560 msize = ntohs (message->size);
1561 if (msize < sizeof (struct PeerPutMessage))
1563 GNUNET_break_op (0);
1566 put = (const struct PeerPutMessage*) message;
1567 putlen = ntohl (put->put_path_length);
1568 if ( (msize < sizeof (struct PeerPutMessage) + putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1569 (putlen > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1571 GNUNET_break_op (0);
1574 GNUNET_STATISTICS_update (GDS_stats,
1575 gettext_noop ("# P2P PUT requests received"), 1,
1577 put_path = (const struct GNUNET_PeerIdentity*) &put[1];
1578 payload = &put_path[putlen];
1579 options = ntohl (put->options);
1580 payload_size = msize - (sizeof (struct PeerPutMessage) +
1581 putlen * sizeof (struct GNUNET_PeerIdentity));
1582 switch (GNUNET_BLOCK_get_key (GDS_block_context,
1584 payload, payload_size,
1588 if (0 != memcmp (&test_key, &put->key, sizeof (GNUNET_HashCode)))
1590 GNUNET_break_op (0);
1595 GNUNET_break_op (0);
1598 /* cannot verify, good luck */
1601 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1602 "PUT for %s at %s\n",
1603 GNUNET_h2s (&put->key),
1604 GNUNET_i2s (&my_identity));
1605 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter,
1607 GNUNET_CONSTANTS_BLOOMFILTER_K);
1608 GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1610 struct GNUNET_PeerIdentity pp[putlen+1];
1612 /* extend 'put path' by sender */
1613 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1615 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1622 /* give to local clients */
1623 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1632 if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1633 (am_closest_peer (&put->key,
1635 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1641 /* route to other peers */
1642 GDS_NEIGHBOURS_handle_put (ntohl (put->type),
1644 ntohl (put->desired_replication_level),
1645 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1646 ntohl (put->hop_count),
1653 GNUNET_CONTAINER_bloomfilter_free (bf);
1659 * We have received a FIND PEER request. Send matching
1662 * @param sender sender of the FIND PEER request
1663 * @param key peers close to this key are desired
1664 * @param bf peers matching this bf are excluded
1665 * @param bf_mutator mutator for bf
1668 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1669 const GNUNET_HashCode *key,
1670 struct GNUNET_CONTAINER_BloomFilter *bf,
1671 uint32_t bf_mutator)
1674 struct PeerBucket *bucket;
1675 struct PeerInfo *peer;
1676 unsigned int choice;
1677 GNUNET_HashCode mhash;
1678 const struct GNUNET_HELLO_Message *hello;
1680 /* first, check about our own HELLO */
1681 if (NULL != GDS_my_hello)
1683 GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1684 if ( (NULL == bf) ||
1685 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) )
1687 GDS_NEIGHBOURS_handle_reply (sender,
1688 GNUNET_BLOCK_TYPE_DHT_HELLO,
1689 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1694 GNUNET_HELLO_size ((const struct GNUNET_HELLO_Message*) GDS_my_hello));
1698 GNUNET_STATISTICS_update (GDS_stats,
1699 gettext_noop ("# FIND PEER requests ignored due to Bloomfilter"), 1,
1705 GNUNET_STATISTICS_update (GDS_stats,
1706 gettext_noop ("# FIND PEER requests ignored due to lack of HELLO"), 1,
1710 /* then, also consider sending a random HELLO from the closest bucket */
1711 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
1712 bucket_idx = closest_bucket;
1714 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1715 if (bucket_idx == GNUNET_SYSERR)
1717 bucket = &k_buckets[bucket_idx];
1718 if (bucket->peers_size == 0)
1720 choice = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1721 bucket->peers_size);
1722 peer = bucket->head;
1725 GNUNET_assert (peer != NULL);
1729 choice = bucket->peers_size;
1734 return; /* no non-masked peer available */
1736 peer = bucket->head;
1737 GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1738 hello = GDS_HELLO_get (&peer->id);
1740 while ( (hello == NULL) ||
1741 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) );
1742 GDS_NEIGHBOURS_handle_reply (sender,
1743 GNUNET_BLOCK_TYPE_DHT_HELLO,
1744 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1749 GNUNET_HELLO_size (hello));
1754 * Core handler for p2p get requests.
1756 * @param cls closure
1757 * @param peer sender of the request
1758 * @param message message
1759 * @param peer peer identity this notification is about
1760 * @param atsi performance data
1761 * @return GNUNET_OK to keep the connection open,
1762 * GNUNET_SYSERR to close it (signal serious error)
1765 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1766 const struct GNUNET_MessageHeader *message,
1767 const struct GNUNET_TRANSPORT_ATS_Information
1770 struct PeerGetMessage *get;
1771 uint32_t xquery_size;
1772 size_t reply_bf_size;
1774 enum GNUNET_BLOCK_Type type;
1775 enum GNUNET_DHT_RouteOption options;
1776 enum GNUNET_BLOCK_EvaluationResult eval;
1777 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1778 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1781 GNUNET_break (0 != memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)));
1782 /* parse and validate message */
1783 msize = ntohs (message->size);
1784 if (msize < sizeof (struct PeerGetMessage))
1786 GNUNET_break_op (0);
1789 get = (struct PeerGetMessage *) message;
1790 xquery_size = ntohl (get->xquery_size);
1791 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1793 GNUNET_break_op (0);
1796 GNUNET_STATISTICS_update (GDS_stats,
1797 gettext_noop ("# P2P GET requests received"), 1,
1799 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1800 type = ntohl (get->type);
1801 options = ntohl (get->options);
1802 xquery = (const char*) &get[1];
1804 if (reply_bf_size > 0)
1805 reply_bf = GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size],
1807 GNUNET_CONSTANTS_BLOOMFILTER_K);
1808 eval = GNUNET_BLOCK_evaluate (GDS_block_context,
1813 xquery, xquery_size,
1815 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1817 /* request invalid or block type not supported */
1818 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1819 if (NULL != reply_bf)
1820 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1824 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter,
1826 GNUNET_CONSTANTS_BLOOMFILTER_K);
1827 GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &peer->hashPubKey));
1828 /* remember request for routing replies */
1829 GDS_ROUTING_add (peer,
1833 xquery, xquery_size,
1834 reply_bf, get->bf_mutator);
1835 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1836 "GET for %s at %s after %u hops\n",
1837 GNUNET_h2s (&get->key),
1838 GNUNET_i2s (&my_identity),
1839 (unsigned int) ntohl (get->hop_count));
1840 /* local lookup (this may update the reply_bf) */
1841 if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1842 (am_closest_peer (&get->key,
1845 if ( (0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1847 GNUNET_STATISTICS_update (GDS_stats,
1848 gettext_noop ("# P2P FIND PEER requests processed"), 1,
1850 handle_find_peer (peer,
1857 eval = GDS_DATACACHE_handle_get (&get->key,
1859 xquery, xquery_size,
1866 GNUNET_STATISTICS_update (GDS_stats,
1867 gettext_noop ("# P2P GET requests ONLY routed"), 1,
1871 /* P2P forwarding */
1872 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1873 GDS_NEIGHBOURS_handle_get (type,
1875 ntohl (get->desired_replication_level),
1876 ntohl (get->hop_count),
1878 xquery, xquery_size,
1883 if (NULL != reply_bf)
1884 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1885 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
1891 * Core handler for p2p result messages.
1893 * @param cls closure
1894 * @param message message
1895 * @param peer peer identity this notification is about
1896 * @param atsi performance data
1897 * @return GNUNET_YES (do not cut p2p connection)
1900 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1901 const struct GNUNET_MessageHeader *message,
1902 const struct GNUNET_TRANSPORT_ATS_Information
1905 const struct PeerResultMessage *prm;
1906 const struct GNUNET_PeerIdentity *put_path;
1907 const struct GNUNET_PeerIdentity *get_path;
1909 uint32_t get_path_length;
1910 uint32_t put_path_length;
1913 enum GNUNET_BLOCK_Type type;
1915 /* parse and validate message */
1916 msize = ntohs (message->size);
1917 if (msize < sizeof (struct PeerResultMessage))
1919 GNUNET_break_op (0);
1922 prm = (struct PeerResultMessage *) message;
1923 put_path_length = ntohl (prm->put_path_length);
1924 get_path_length = ntohl (prm->get_path_length);
1925 if ( (msize < sizeof (struct PeerResultMessage) +
1926 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity)) ||
1927 (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1928 (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1930 GNUNET_break_op (0);
1933 GNUNET_STATISTICS_update (GDS_stats,
1934 gettext_noop ("# P2P RESULTS received"), 1,
1936 put_path = (const struct GNUNET_PeerIdentity*) &prm[1];
1937 get_path = &put_path[put_path_length];
1938 type = ntohl (prm->type);
1939 data = (const void*) &get_path[get_path_length];
1940 data_size = msize - (sizeof (struct PeerResultMessage) +
1941 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1943 /* if we got a HELLO, consider it for our own routing table */
1944 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
1946 const struct GNUNET_MessageHeader *h;
1947 struct GNUNET_PeerIdentity pid;
1950 /* Should be a HELLO, validate and consider using it! */
1951 if (data_size < sizeof (struct GNUNET_MessageHeader))
1953 GNUNET_break_op (0);
1957 if (data_size != ntohs (h->size))
1959 GNUNET_break_op (0);
1963 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message*) h,
1966 GNUNET_break_op (0);
1969 if (0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
1971 bucket = find_bucket (&pid.hashPubKey);
1972 if ( (bucket >= 0) &&
1973 (k_buckets[bucket].peers_size < bucket_size) )
1975 if (NULL != GDS_transport_handle)
1976 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle,
1978 (void) GNUNET_CORE_peer_request_connect (coreAPI,
1985 /* append 'peer' to 'get_path' */
1987 struct GNUNET_PeerIdentity xget_path[get_path_length+1];
1989 memcpy (xget_path, get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1990 xget_path[get_path_length] = *peer;
1993 /* forward to local clients */
1994 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2004 /* forward to other peers */
2005 GDS_ROUTING_process (type,
2006 GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2020 * Initialize neighbours subsystem.
2022 * @return GNUNET_OK on success, GNUNET_SYSERR on error
2025 GDS_NEIGHBOURS_init ()
2027 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2028 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2029 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2030 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2033 unsigned long long temp_config_num;
2036 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2038 bucket_size = (unsigned int) temp_config_num;
2039 coreAPI = GNUNET_CORE_connect (GDS_cfg,
2043 &handle_core_connect,
2044 &handle_core_disconnect,
2045 NULL, /* Do we care about "status" updates? */
2049 if (coreAPI == NULL)
2050 return GNUNET_SYSERR;
2051 all_known_peers = GNUNET_CONTAINER_multihashmap_create (256);
2057 * Shutdown neighbours subsystem.
2060 GDS_NEIGHBOURS_done ()
2062 if (coreAPI == NULL)
2064 GNUNET_CORE_disconnect (coreAPI);
2066 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2067 GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2068 all_known_peers = NULL;
2069 if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2071 GNUNET_SCHEDULER_cancel (find_peer_task);
2072 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2077 /* end of gnunet-service-dht_neighbours.c */