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 amount set to the amount that was actually reserved or unreserved;
456 * either the full requested amount or zero (no partial reservations)
457 * @param res_delay if the reservation could not be satisfied (amount was 0), how
458 * long should the client wait until re-trying?
461 update_core_preference_finish (void *cls,
462 const struct GNUNET_PeerIdentity *peer,
464 struct GNUNET_TIME_Relative res_delay)
466 struct PeerInfo *peer_info = cls;
468 peer_info->info_ctx = NULL;
469 peer_info->preference_task
470 = GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
471 &update_core_preference, peer_info);
476 * Let GNUnet core know that we like the given peer.
478 * @param cls the 'struct PeerInfo' of the peer
479 * @param tc scheduler context.
482 update_core_preference (void *cls,
483 const struct GNUNET_SCHEDULER_TaskContext *tc)
485 struct PeerInfo *peer = cls;
487 unsigned int matching;
490 peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
491 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
494 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
495 &peer->id.hashPubKey);
498 bucket = find_bucket (&peer->id.hashPubKey);
499 if (bucket == GNUNET_SYSERR)
503 GNUNET_assert (k_buckets[bucket].peers_size != 0);
504 preference = (1LL << matching) / k_buckets[bucket].peers_size;
508 peer->preference_task
509 = GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
510 &update_core_preference, peer);
513 GNUNET_STATISTICS_update (GDS_stats,
514 gettext_noop ("# Preference updates given to core"), 1,
517 GNUNET_CORE_peer_change_preference (coreAPI, &peer->id,
520 &update_core_preference_finish, peer);
525 * Closure for 'add_known_to_bloom'.
527 struct BloomConstructorContext
530 * Bloom filter under construction.
532 struct GNUNET_CONTAINER_BloomFilter *bloom;
542 * Add each of the peers we already know to the bloom filter of
543 * the request so that we don't get duplicate HELLOs.
545 * @param cls the 'struct BloomConstructorContext'.
546 * @param key peer identity to add to the bloom filter
547 * @param value value the peer information (unused)
548 * @return GNUNET_YES (we should continue to iterate)
551 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
553 struct BloomConstructorContext *ctx = cls;
556 GNUNET_BLOCK_mingle_hash (key, ctx->bf_mutator, &mh);
557 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
558 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
561 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
567 * Task to send a find peer message for our own peer identifier
568 * so that we can find the closest peers in the network to ourselves
569 * and attempt to connect to them.
571 * @param cls closure for this task
572 * @param tc the context under which the task is running
575 send_find_peer_message (void *cls,
576 const struct GNUNET_SCHEDULER_TaskContext *tc)
578 struct GNUNET_TIME_Relative next_send_time;
579 struct BloomConstructorContext bcc;
580 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
582 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
583 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
585 if (newly_found_peers > bucket_size)
587 /* If we are finding many peers already, no need to send out our request right now! */
588 find_peer_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
589 &send_find_peer_message, NULL);
590 newly_found_peers = 0;
593 bcc.bf_mutator = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
595 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, GNUNET_CONSTANTS_BLOOMFILTER_K);
596 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers,
599 GNUNET_STATISTICS_update (GDS_stats,
600 gettext_noop ("# FIND PEER messages initiated"), 1,
602 peer_bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
604 GNUNET_CONSTANTS_BLOOMFILTER_K);
605 // FIXME: pass priority!?
606 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
607 GNUNET_DHT_RO_FIND_PEER,
608 FIND_PEER_REPLICATION_LEVEL,
610 &my_identity.hashPubKey,
612 bcc.bloom, bcc.bf_mutator,
614 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
615 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
616 /* schedule next round */
617 next_send_time.rel_value =
618 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
619 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
620 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / (newly_found_peers+1));
621 newly_found_peers = 0;
622 find_peer_task = GNUNET_SCHEDULER_add_delayed (next_send_time,
623 &send_find_peer_message,
629 * Method called whenever a peer connects.
632 * @param peer peer identity this notification is about
633 * @param atsi performance data
636 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
637 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
639 struct PeerInfo *ret;
642 /* Check for connect to self message */
643 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
645 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
646 "Connected %s to %s\n",
647 GNUNET_i2s (&my_identity),
648 GNUNET_h2s (&peer->hashPubKey));
650 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
656 GNUNET_STATISTICS_update (GDS_stats,
657 gettext_noop ("# Peers connected"), 1,
659 peer_bucket = find_bucket (&peer->hashPubKey);
660 GNUNET_assert ( (peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS) );
661 ret = GNUNET_malloc (sizeof (struct PeerInfo));
663 ret->latency = latency;
664 ret->distance = distance;
667 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
668 k_buckets[peer_bucket].tail, ret);
669 k_buckets[peer_bucket].peers_size++;
670 closest_bucket = GNUNET_MAX (closest_bucket,
672 if ( (peer_bucket > 0) &&
673 (k_buckets[peer_bucket].peers_size <= bucket_size) )
675 ret->preference_task = GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
678 GNUNET_assert (GNUNET_OK ==
679 GNUNET_CONTAINER_multihashmap_put (all_known_peers,
680 &peer->hashPubKey, ret,
681 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
682 if (1 == GNUNET_CONTAINER_multihashmap_size (all_known_peers))
684 /* got a first connection, good time to start with FIND PEER requests... */
685 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message,
692 * Method called whenever a peer disconnects.
695 * @param peer peer identity this notification is about
698 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
700 struct PeerInfo *to_remove;
702 struct P2PPendingMessage *pos;
703 unsigned int discarded;
705 /* Check for disconnect from self message */
706 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
708 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
709 "Disconnected %s from %s\n",
710 GNUNET_i2s (&my_identity),
711 GNUNET_h2s (&peer->hashPubKey));
713 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
714 if (NULL == to_remove)
719 GNUNET_STATISTICS_update (GDS_stats,
720 gettext_noop ("# Peers connected"), -1,
722 GNUNET_assert (GNUNET_YES ==
723 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
726 if (NULL != to_remove->info_ctx)
728 GNUNET_CORE_peer_change_preference_cancel (to_remove->info_ctx);
729 to_remove->info_ctx = NULL;
731 if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
733 GNUNET_SCHEDULER_cancel (to_remove->preference_task);
734 to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
736 current_bucket = find_bucket (&to_remove->id.hashPubKey);
737 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
738 k_buckets[current_bucket].tail,
740 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
741 k_buckets[current_bucket].peers_size--;
742 while ( (closest_bucket > 0) &&
743 (k_buckets[closest_bucket].peers_size == 0) )
746 if (to_remove->th != NULL)
748 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
749 to_remove->th = NULL;
752 while (NULL != (pos = to_remove->head))
754 GNUNET_CONTAINER_DLL_remove (to_remove->head,
760 GNUNET_STATISTICS_update (GDS_stats,
761 gettext_noop ("# Queued messages discarded (peer disconnected)"), discarded,
763 GNUNET_free (to_remove);
768 * Called when core is ready to send a message we asked for
769 * out to the destination.
771 * @param cls the 'struct PeerInfo' of the target peer
772 * @param size number of bytes available in buf
773 * @param buf where the callee should write the message
774 * @return number of bytes written to buf
777 core_transmit_notify (void *cls, size_t size, void *buf)
779 struct PeerInfo *peer = cls;
781 struct P2PPendingMessage *pending;
786 while ( (NULL != (pending = peer->head)) &&
787 (GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value == 0) )
789 peer->pending_count--;
790 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
791 GNUNET_free (pending);
795 /* no messages pending */
801 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
803 GNUNET_TIME_absolute_get_remaining (pending->timeout),
804 &peer->id, ntohs (pending->msg->size),
805 &core_transmit_notify, peer);
806 GNUNET_break (NULL != peer->th);
810 while ( (NULL != (pending = peer->head)) &&
811 (size - off >= (msize = ntohs (pending->msg->size))) )
813 GNUNET_STATISTICS_update (GDS_stats,
814 gettext_noop ("# Bytes transmitted to other peers"), msize,
816 memcpy (&cbuf[off], pending->msg, msize);
818 peer->pending_count--;
819 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
820 GNUNET_free (pending);
822 if (peer->head != NULL)
825 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
827 GNUNET_TIME_absolute_get_remaining (pending->timeout),
829 &core_transmit_notify, peer);
830 GNUNET_break (NULL != peer->th);
837 * Transmit all messages in the peer's message queue.
839 * @param peer message queue to process
842 process_peer_queue (struct PeerInfo *peer)
844 struct P2PPendingMessage *pending;
846 if (NULL == (pending = peer->head))
848 if (NULL != peer->th)
850 GNUNET_STATISTICS_update (GDS_stats,
851 gettext_noop ("# Bytes of bandwdith requested from core"),
852 ntohs (pending->msg->size),
855 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
857 GNUNET_TIME_absolute_get_remaining (pending->timeout),
859 ntohs (pending->msg->size),
860 &core_transmit_notify, peer);
861 GNUNET_break (NULL != peer->th);
866 * To how many peers should we (on average) forward the request to
867 * obtain the desired target_replication count (on average).
869 * @param hop_count number of hops the message has traversed
870 * @param target_replication the number of total paths desired
871 * @return Some number of peers to forward the message to
874 get_forward_count (uint32_t hop_count,
875 uint32_t target_replication)
877 uint32_t random_value;
878 uint32_t forward_count;
881 if (hop_count > GDS_NSE_get () * 6.0)
883 /* forcefully terminate */
886 if (hop_count > GDS_NSE_get () * 4.0)
888 /* Once we have reached our ideal number of hops, only forward to 1 peer */
891 /* bound by system-wide maximum */
892 target_replication = GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL,
895 1 + (target_replication - 1.0) / (GDS_NSE_get () +
896 ((float) (target_replication - 1.0) *
898 /* Set forward count to floor of target_value */
899 forward_count = (uint32_t) target_value;
900 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
901 target_value = target_value - forward_count;
903 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
904 if (random_value < (target_value * UINT32_MAX))
906 return forward_count;
911 * Compute the distance between have and target as a 32-bit value.
912 * Differences in the lower bits must count stronger than differences
913 * in the higher bits.
915 * @return 0 if have==target, otherwise a number
916 * that is larger as the distance between
917 * the two hash codes increases
920 get_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
927 /* We have to represent the distance between two 2^9 (=512)-bit
928 * numbers as a 2^5 (=32)-bit number with "0" being used for the
929 * two numbers being identical; furthermore, we need to
930 * guarantee that a difference in the number of matching
931 * bits is always represented in the result.
933 * We use 2^32/2^9 numerical values to distinguish between
934 * hash codes that have the same LSB bit distance and
935 * use the highest 2^9 bits of the result to signify the
936 * number of (mis)matching LSB bits; if we have 0 matching
937 * and hence 512 mismatching LSB bits we return -1 (since
938 * 512 itself cannot be represented with 9 bits) */
940 /* first, calculate the most significant 9 bits of our
941 * result, aka the number of LSBs */
942 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
943 /* bucket is now a value between 0 and 512 */
945 return 0; /* perfect match */
947 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
948 * below, we'd end up with max+1 (overflow)) */
950 /* calculate the most significant bits of the final result */
951 msb = (512 - bucket) << (32 - 9);
952 /* calculate the 32-9 least significant bits of the final result by
953 * looking at the differences in the 32-9 bits following the
954 * mismatching bit at 'bucket' */
957 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
959 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
960 GNUNET_CRYPTO_hash_get_bit (have, i))
961 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
962 * last bit set will be 31 -- if
963 * i does not reach 512 first... */
970 * Check whether my identity is closer than any known peers. If a
971 * non-null bloomfilter is given, check if this is the closest peer
972 * that hasn't already been routed to.
974 * @param key hash code to check closeness to
975 * @param bloom bloomfilter, exclude these entries from the decision
976 * @return GNUNET_YES if node location is closest,
977 * GNUNET_NO otherwise.
980 am_closest_peer (const GNUNET_HashCode *key,
981 const struct GNUNET_CONTAINER_BloomFilter *bloom)
987 struct PeerInfo *pos;
989 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
991 bucket_num = find_bucket (key);
992 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
993 pos = k_buckets[bucket_num].head;
995 while ((pos != NULL) && (count < bucket_size))
997 if ((bloom != NULL) &&
999 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1002 continue; /* Skip already checked entries */
1004 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
1005 if (other_bits > bits)
1007 if (other_bits == bits) /* We match the same number of bits */
1011 /* No peers closer, we are the closest! */
1017 * Select a peer from the routing table that would be a good routing
1018 * destination for sending a message for "key". The resulting peer
1019 * must not be in the set of blocked peers.<p>
1021 * Note that we should not ALWAYS select the closest peer to the
1022 * target, peers further away from the target should be chosen with
1023 * exponentially declining probability.
1025 * FIXME: double-check that this is fine
1028 * @param key the key we are selecting a peer to route to
1029 * @param bloom a bloomfilter containing entries this request has seen already
1030 * @param hops how many hops has this message traversed thus far
1031 * @return Peer to route to, or NULL on error
1033 static struct PeerInfo *
1034 select_peer (const GNUNET_HashCode *key,
1035 const struct GNUNET_CONTAINER_BloomFilter *bloom,
1040 unsigned int selected;
1041 struct PeerInfo *pos;
1043 unsigned int smallest_distance;
1044 struct PeerInfo *chosen;
1046 if (hops >= GDS_NSE_get ())
1048 /* greedy selection (closest peer that is not in bloomfilter) */
1049 smallest_distance = UINT_MAX;
1051 for (bc = 0; bc < closest_bucket; bc++)
1053 pos = k_buckets[bc].head;
1055 while ((pos != NULL) && (count < bucket_size))
1057 if ( (bloom == NULL) ||
1059 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1061 dist = get_distance (key, &pos->id.hashPubKey);
1062 if (dist < smallest_distance)
1065 smallest_distance = dist;
1070 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1071 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1072 GNUNET_i2s (&pos->id),
1074 GNUNET_STATISTICS_update (GDS_stats,
1075 gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1083 GNUNET_STATISTICS_update (GDS_stats,
1084 gettext_noop ("# Peer selection failed"), 1,
1089 /* select "random" peer */
1090 /* count number of peers that are available and not filtered */
1092 for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1094 pos = k_buckets[bc].head;
1095 while ((pos != NULL) && (count < bucket_size))
1097 if ( (bloom != NULL) &&
1099 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1101 GNUNET_STATISTICS_update (GDS_stats,
1102 gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1104 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1105 "Excluded peer `%s' due to BF match in random routing for %s\n",
1106 GNUNET_i2s (&pos->id),
1109 continue; /* Ignore bloomfiltered peers */
1115 if (count == 0) /* No peers to select from! */
1117 GNUNET_STATISTICS_update (GDS_stats,
1118 gettext_noop ("# Peer selection failed"), 1,
1122 /* Now actually choose a peer */
1123 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1125 for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1127 pos = k_buckets[bc].head;
1128 while ((pos != NULL) && (count < bucket_size))
1130 if ( (bloom != NULL) &&
1132 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1135 continue; /* Ignore bloomfiltered peers */
1137 if (0 == selected--)
1148 * Compute the set of peers that the given request should be
1151 * @param key routing key
1152 * @param bloom bloom filter excluding peers as targets, all selected
1153 * peers will be added to the bloom filter
1154 * @param hop_count number of hops the request has traversed so far
1155 * @param target_replication desired number of replicas
1156 * @param targets where to store an array of target peers (to be
1157 * free'd by the caller)
1158 * @return number of peers returned in 'targets'.
1161 get_target_peers (const GNUNET_HashCode *key,
1162 struct GNUNET_CONTAINER_BloomFilter *bloom,
1164 uint32_t target_replication,
1165 struct PeerInfo ***targets)
1169 struct PeerInfo **rtargets;
1170 struct PeerInfo *nxt;
1172 GNUNET_assert (NULL != bloom);
1173 ret = get_forward_count (hop_count, target_replication);
1179 rtargets = GNUNET_malloc (sizeof (struct PeerInfo*) * ret);
1180 for (off = 0; off < ret; off++)
1182 nxt = select_peer (key, bloom, hop_count);
1185 rtargets[off] = nxt;
1186 GNUNET_break (GNUNET_NO ==
1187 GNUNET_CONTAINER_bloomfilter_test (bloom, &nxt->id.hashPubKey));
1188 GNUNET_CONTAINER_bloomfilter_add (bloom, &rtargets[off]->id.hashPubKey);
1190 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1191 "Selected %u/%u peers at hop %u for %s (target was %u)\n",
1193 GNUNET_CONTAINER_multihashmap_size (all_known_peers),
1194 (unsigned int) hop_count,
1199 GNUNET_free (rtargets);
1203 *targets = rtargets;
1209 * Perform a PUT operation. Forwards the given request to other
1210 * peers. Does not store the data locally. Does not give the
1211 * data to local clients. May do nothing if this is the only
1212 * peer in the network (or if we are the closest peer in the
1215 * @param type type of the block
1216 * @param options routing options
1217 * @param desired_replication_level desired replication count
1218 * @param expiration_time when does the content expire
1219 * @param hop_count how many hops has this message traversed so far
1220 * @param bf Bloom filter of peers this PUT has already traversed
1221 * @param key key for the content
1222 * @param put_path_length number of entries in put_path
1223 * @param put_path peers this request has traversed so far (if tracked)
1224 * @param data payload to store
1225 * @param data_size number of bytes in data
1228 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1229 enum GNUNET_DHT_RouteOption options,
1230 uint32_t desired_replication_level,
1231 struct GNUNET_TIME_Absolute expiration_time,
1233 struct GNUNET_CONTAINER_BloomFilter *bf,
1234 const GNUNET_HashCode *key,
1235 unsigned int put_path_length,
1236 struct GNUNET_PeerIdentity *put_path,
1240 unsigned int target_count;
1242 struct PeerInfo **targets;
1243 struct PeerInfo *target;
1244 struct P2PPendingMessage *pending;
1246 struct PeerPutMessage *ppm;
1247 struct GNUNET_PeerIdentity *pp;
1249 GNUNET_assert (NULL != bf);
1250 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1251 "Adding myself (%s) to PUT bloomfilter for %s\n",
1252 GNUNET_i2s (&my_identity),
1254 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1255 GNUNET_STATISTICS_update (GDS_stats,
1256 gettext_noop ("# PUT requests routed"), 1,
1258 target_count = get_target_peers (key, bf, hop_count,
1259 desired_replication_level,
1261 if (0 == target_count)
1263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1264 "Routing PUT for %s terminates after %u hops at %s\n",
1266 (unsigned int) hop_count,
1267 GNUNET_i2s (&my_identity));
1270 msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size + sizeof (struct PeerPutMessage);
1271 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1273 put_path_length = 0;
1274 msize = data_size + sizeof (struct PeerPutMessage);
1276 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1281 GNUNET_STATISTICS_update (GDS_stats,
1282 gettext_noop ("# PUT messages queued for transmission"), target_count,
1284 for (i=0;i<target_count;i++)
1286 target = targets[i];
1287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1288 "Routing PUT for %s after %u hops to %s\n",
1290 (unsigned int) hop_count,
1291 GNUNET_i2s (&target->id));
1292 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1293 pending->importance = 0; /* FIXME */
1294 pending->timeout = expiration_time;
1295 ppm = (struct PeerPutMessage*) &pending[1];
1296 pending->msg = &ppm->header;
1297 ppm->header.size = htons (msize);
1298 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1299 ppm->options = htonl (options);
1300 ppm->type = htonl (type);
1301 ppm->hop_count = htonl (hop_count + 1);
1302 ppm->desired_replication_level = htonl (desired_replication_level);
1303 ppm->put_path_length = htonl (put_path_length);
1304 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1305 GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &target->id.hashPubKey));
1306 GNUNET_assert (GNUNET_OK ==
1307 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1311 pp = (struct GNUNET_PeerIdentity*) &ppm[1];
1312 memcpy (pp, put_path, sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1313 memcpy (&pp[put_path_length], data, data_size);
1314 GNUNET_CONTAINER_DLL_insert_tail (target->head,
1317 target->pending_count++;
1318 process_peer_queue (target);
1320 GNUNET_free (targets);
1325 * Perform a GET operation. Forwards the given request to other
1326 * peers. Does not lookup the key locally. May do nothing if this is
1327 * the only peer in the network (or if we are the closest peer in the
1330 * @param type type of the block
1331 * @param options routing options
1332 * @param desired_replication_level desired replication count
1333 * @param hop_count how many hops did this request traverse so far?
1334 * @param key key for the content
1335 * @param xquery extended query
1336 * @param xquery_size number of bytes in xquery
1337 * @param reply_bf bloomfilter to filter duplicates
1338 * @param reply_bf_mutator mutator for reply_bf
1339 * @param peer_bf filter for peers not to select (again)
1342 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1343 enum GNUNET_DHT_RouteOption options,
1344 uint32_t desired_replication_level,
1346 const GNUNET_HashCode *key,
1349 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1350 uint32_t reply_bf_mutator,
1351 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1353 unsigned int target_count;
1355 struct PeerInfo **targets;
1356 struct PeerInfo *target;
1357 struct P2PPendingMessage *pending;
1359 struct PeerGetMessage *pgm;
1361 size_t reply_bf_size;
1363 GNUNET_assert (NULL != peer_bf);
1364 GNUNET_STATISTICS_update (GDS_stats,
1365 gettext_noop ("# GET requests routed"), 1,
1367 target_count = get_target_peers (key, peer_bf, hop_count,
1368 desired_replication_level,
1370 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1371 "Adding myself (%s) to GET bloomfilter for %s\n",
1372 GNUNET_i2s (&my_identity),
1374 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity.hashPubKey);
1375 if (0 == target_count)
1377 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1378 "Routing GET for %s terminates after %u hops at %s\n",
1380 (unsigned int) hop_count,
1381 GNUNET_i2s (&my_identity));
1384 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1385 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1386 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1391 GNUNET_STATISTICS_update (GDS_stats,
1392 gettext_noop ("# GET messages queued for transmission"), target_count,
1394 /* forward request */
1395 for (i=0;i<target_count;i++)
1397 target = targets[i];
1398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1399 "Routing GET for %s after %u hops to %s\n",
1401 (unsigned int) hop_count,
1402 GNUNET_i2s (&target->id));
1403 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1404 pending->importance = 0; /* FIXME */
1405 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1406 pgm = (struct PeerGetMessage*) &pending[1];
1407 pending->msg = &pgm->header;
1408 pgm->header.size = htons (msize);
1409 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1410 pgm->options = htonl (options);
1411 pgm->type = htonl (type);
1412 pgm->hop_count = htonl (hop_count + 1);
1413 pgm->desired_replication_level = htonl (desired_replication_level);
1414 pgm->xquery_size = htonl (xquery_size);
1415 pgm->bf_mutator = reply_bf_mutator;
1416 GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &target->id.hashPubKey));
1417 GNUNET_assert (GNUNET_OK ==
1418 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1422 xq = (char *) &pgm[1];
1423 memcpy (xq, xquery, xquery_size);
1424 if (NULL != reply_bf)
1425 GNUNET_assert (GNUNET_OK ==
1426 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1429 GNUNET_CONTAINER_DLL_insert_tail (target->head,
1432 target->pending_count++;
1433 process_peer_queue (target);
1435 GNUNET_free (targets);
1440 * Handle a reply (route to origin). Only forwards the reply back to
1441 * the given peer. Does not do local caching or forwarding to local
1444 * @param target neighbour that should receive the block (if still connected)
1445 * @param type type of the block
1446 * @param expiration_time when does the content expire
1447 * @param key key for the content
1448 * @param put_path_length number of entries in put_path
1449 * @param put_path peers the original PUT traversed (if tracked)
1450 * @param get_path_length number of entries in put_path
1451 * @param get_path peers this reply has traversed so far (if tracked)
1452 * @param data payload of the reply
1453 * @param data_size number of bytes in data
1456 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1457 enum GNUNET_BLOCK_Type type,
1458 struct GNUNET_TIME_Absolute expiration_time,
1459 const GNUNET_HashCode *key,
1460 unsigned int put_path_length,
1461 const struct GNUNET_PeerIdentity *put_path,
1462 unsigned int get_path_length,
1463 const struct GNUNET_PeerIdentity *get_path,
1467 struct PeerInfo *pi;
1468 struct P2PPendingMessage *pending;
1470 struct PeerResultMessage *prm;
1471 struct GNUNET_PeerIdentity *paths;
1473 msize = data_size + sizeof (struct PeerResultMessage) +
1474 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity);
1475 if ( (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1476 (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1477 (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1478 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE) )
1483 pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers,
1484 &target->hashPubKey);
1487 /* peer disconnected in the meantime, drop reply */
1490 GNUNET_STATISTICS_update (GDS_stats,
1491 gettext_noop ("# RESULT messages queued for transmission"), 1,
1493 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1494 pending->importance = 0; /* FIXME */
1495 pending->timeout = expiration_time;
1496 prm = (struct PeerResultMessage*) &pending[1];
1497 pending->msg = &prm->header;
1498 prm->header.size = htons (msize);
1499 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1500 prm->type = htonl (type);
1501 prm->put_path_length = htonl (put_path_length);
1502 prm->get_path_length = htonl (get_path_length);
1503 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1505 paths = (struct GNUNET_PeerIdentity*) &prm[1];
1506 memcpy (paths, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
1507 memcpy (&paths[put_path_length],
1508 get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1509 memcpy (&paths[put_path_length + get_path_length],
1511 GNUNET_CONTAINER_DLL_insert (pi->head,
1514 pi->pending_count++;
1515 process_peer_queue (pi);
1520 * To be called on core init/fail.
1522 * @param cls service closure
1523 * @param server handle to the server for this service
1524 * @param identity the public identity of this peer
1527 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1528 const struct GNUNET_PeerIdentity *identity)
1530 GNUNET_assert (server != NULL);
1531 my_identity = *identity;
1536 * Core handler for p2p put requests.
1538 * @param cls closure
1539 * @param peer sender of the request
1540 * @param message message
1541 * @param peer peer identity this notification is about
1542 * @param atsi performance data
1543 * @return GNUNET_OK to keep the connection open,
1544 * GNUNET_SYSERR to close it (signal serious error)
1547 handle_dht_p2p_put (void *cls,
1548 const struct GNUNET_PeerIdentity *peer,
1549 const struct GNUNET_MessageHeader *message,
1550 const struct GNUNET_TRANSPORT_ATS_Information
1553 const struct PeerPutMessage *put;
1554 const struct GNUNET_PeerIdentity *put_path;
1555 const void *payload;
1558 size_t payload_size;
1559 enum GNUNET_DHT_RouteOption options;
1560 struct GNUNET_CONTAINER_BloomFilter *bf;
1561 GNUNET_HashCode test_key;
1563 msize = ntohs (message->size);
1564 if (msize < sizeof (struct PeerPutMessage))
1566 GNUNET_break_op (0);
1569 put = (const struct PeerPutMessage*) message;
1570 putlen = ntohl (put->put_path_length);
1571 if ( (msize < sizeof (struct PeerPutMessage) + putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1572 (putlen > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1574 GNUNET_break_op (0);
1577 GNUNET_STATISTICS_update (GDS_stats,
1578 gettext_noop ("# P2P PUT requests received"), 1,
1580 put_path = (const struct GNUNET_PeerIdentity*) &put[1];
1581 payload = &put_path[putlen];
1582 options = ntohl (put->options);
1583 payload_size = msize - (sizeof (struct PeerPutMessage) +
1584 putlen * sizeof (struct GNUNET_PeerIdentity));
1585 switch (GNUNET_BLOCK_get_key (GDS_block_context,
1587 payload, payload_size,
1591 if (0 != memcmp (&test_key, &put->key, sizeof (GNUNET_HashCode)))
1593 GNUNET_break_op (0);
1598 GNUNET_break_op (0);
1601 /* cannot verify, good luck */
1604 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1605 "PUT for %s at %s\n",
1606 GNUNET_h2s (&put->key),
1607 GNUNET_i2s (&my_identity));
1608 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter,
1610 GNUNET_CONSTANTS_BLOOMFILTER_K);
1611 GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1613 struct GNUNET_PeerIdentity pp[putlen+1];
1615 /* extend 'put path' by sender */
1616 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1618 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1625 /* give to local clients */
1626 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1635 if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1636 (am_closest_peer (&put->key,
1638 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1644 /* route to other peers */
1645 GDS_NEIGHBOURS_handle_put (ntohl (put->type),
1647 ntohl (put->desired_replication_level),
1648 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1649 ntohl (put->hop_count),
1656 GNUNET_CONTAINER_bloomfilter_free (bf);
1662 * We have received a FIND PEER request. Send matching
1665 * @param sender sender of the FIND PEER request
1666 * @param key peers close to this key are desired
1667 * @param bf peers matching this bf are excluded
1668 * @param bf_mutator mutator for bf
1671 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1672 const GNUNET_HashCode *key,
1673 struct GNUNET_CONTAINER_BloomFilter *bf,
1674 uint32_t bf_mutator)
1677 struct PeerBucket *bucket;
1678 struct PeerInfo *peer;
1679 unsigned int choice;
1680 GNUNET_HashCode mhash;
1681 const struct GNUNET_HELLO_Message *hello;
1683 /* first, check about our own HELLO */
1684 if (NULL != GDS_my_hello)
1686 GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1687 if ( (NULL == bf) ||
1688 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) )
1690 GDS_NEIGHBOURS_handle_reply (sender,
1691 GNUNET_BLOCK_TYPE_DHT_HELLO,
1692 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1697 GNUNET_HELLO_size ((const struct GNUNET_HELLO_Message*) GDS_my_hello));
1701 GNUNET_STATISTICS_update (GDS_stats,
1702 gettext_noop ("# FIND PEER requests ignored due to Bloomfilter"), 1,
1708 GNUNET_STATISTICS_update (GDS_stats,
1709 gettext_noop ("# FIND PEER requests ignored due to lack of HELLO"), 1,
1713 /* then, also consider sending a random HELLO from the closest bucket */
1714 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
1715 bucket_idx = closest_bucket;
1717 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1718 if (bucket_idx == GNUNET_SYSERR)
1720 bucket = &k_buckets[bucket_idx];
1721 if (bucket->peers_size == 0)
1723 choice = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1724 bucket->peers_size);
1725 peer = bucket->head;
1728 GNUNET_assert (peer != NULL);
1732 choice = bucket->peers_size;
1737 return; /* no non-masked peer available */
1739 peer = bucket->head;
1740 GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1741 hello = GDS_HELLO_get (&peer->id);
1743 while ( (hello == NULL) ||
1744 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) );
1745 GDS_NEIGHBOURS_handle_reply (sender,
1746 GNUNET_BLOCK_TYPE_DHT_HELLO,
1747 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1752 GNUNET_HELLO_size (hello));
1757 * Core handler for p2p get requests.
1759 * @param cls closure
1760 * @param peer sender of the request
1761 * @param message message
1762 * @param peer peer identity this notification is about
1763 * @param atsi performance data
1764 * @return GNUNET_OK to keep the connection open,
1765 * GNUNET_SYSERR to close it (signal serious error)
1768 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1769 const struct GNUNET_MessageHeader *message,
1770 const struct GNUNET_TRANSPORT_ATS_Information
1773 struct PeerGetMessage *get;
1774 uint32_t xquery_size;
1775 size_t reply_bf_size;
1777 enum GNUNET_BLOCK_Type type;
1778 enum GNUNET_DHT_RouteOption options;
1779 enum GNUNET_BLOCK_EvaluationResult eval;
1780 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1781 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1784 GNUNET_break (0 != memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)));
1785 /* parse and validate message */
1786 msize = ntohs (message->size);
1787 if (msize < sizeof (struct PeerGetMessage))
1789 GNUNET_break_op (0);
1792 get = (struct PeerGetMessage *) message;
1793 xquery_size = ntohl (get->xquery_size);
1794 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1796 GNUNET_break_op (0);
1799 GNUNET_STATISTICS_update (GDS_stats,
1800 gettext_noop ("# P2P GET requests received"), 1,
1802 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1803 type = ntohl (get->type);
1804 options = ntohl (get->options);
1805 xquery = (const char*) &get[1];
1807 if (reply_bf_size > 0)
1808 reply_bf = GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size],
1810 GNUNET_CONSTANTS_BLOOMFILTER_K);
1811 eval = GNUNET_BLOCK_evaluate (GDS_block_context,
1816 xquery, xquery_size,
1818 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1820 /* request invalid or block type not supported */
1821 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1822 if (NULL != reply_bf)
1823 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1827 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter,
1829 GNUNET_CONSTANTS_BLOOMFILTER_K);
1830 GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &peer->hashPubKey));
1831 /* remember request for routing replies */
1832 GDS_ROUTING_add (peer,
1836 xquery, xquery_size,
1837 reply_bf, get->bf_mutator);
1838 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1839 "GET for %s at %s after %u hops\n",
1840 GNUNET_h2s (&get->key),
1841 GNUNET_i2s (&my_identity),
1842 (unsigned int) ntohl (get->hop_count));
1843 /* local lookup (this may update the reply_bf) */
1844 if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1845 (am_closest_peer (&get->key,
1848 if ( (0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1850 GNUNET_STATISTICS_update (GDS_stats,
1851 gettext_noop ("# P2P FIND PEER requests processed"), 1,
1853 handle_find_peer (peer,
1860 eval = GDS_DATACACHE_handle_get (&get->key,
1862 xquery, xquery_size,
1869 GNUNET_STATISTICS_update (GDS_stats,
1870 gettext_noop ("# P2P GET requests ONLY routed"), 1,
1874 /* P2P forwarding */
1875 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1876 GDS_NEIGHBOURS_handle_get (type,
1878 ntohl (get->desired_replication_level),
1879 ntohl (get->hop_count),
1881 xquery, xquery_size,
1886 if (NULL != reply_bf)
1887 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1888 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
1894 * Core handler for p2p result messages.
1896 * @param cls closure
1897 * @param message message
1898 * @param peer peer identity this notification is about
1899 * @param atsi performance data
1900 * @return GNUNET_YES (do not cut p2p connection)
1903 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1904 const struct GNUNET_MessageHeader *message,
1905 const struct GNUNET_TRANSPORT_ATS_Information
1908 const struct PeerResultMessage *prm;
1909 const struct GNUNET_PeerIdentity *put_path;
1910 const struct GNUNET_PeerIdentity *get_path;
1912 uint32_t get_path_length;
1913 uint32_t put_path_length;
1916 enum GNUNET_BLOCK_Type type;
1918 /* parse and validate message */
1919 msize = ntohs (message->size);
1920 if (msize < sizeof (struct PeerResultMessage))
1922 GNUNET_break_op (0);
1925 prm = (struct PeerResultMessage *) message;
1926 put_path_length = ntohl (prm->put_path_length);
1927 get_path_length = ntohl (prm->get_path_length);
1928 if ( (msize < sizeof (struct PeerResultMessage) +
1929 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity)) ||
1930 (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1931 (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1933 GNUNET_break_op (0);
1936 GNUNET_STATISTICS_update (GDS_stats,
1937 gettext_noop ("# P2P RESULTS received"), 1,
1939 put_path = (const struct GNUNET_PeerIdentity*) &prm[1];
1940 get_path = &put_path[put_path_length];
1941 type = ntohl (prm->type);
1942 data = (const void*) &get_path[get_path_length];
1943 data_size = msize - (sizeof (struct PeerResultMessage) +
1944 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1946 /* if we got a HELLO, consider it for our own routing table */
1947 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
1949 const struct GNUNET_MessageHeader *h;
1950 struct GNUNET_PeerIdentity pid;
1953 /* Should be a HELLO, validate and consider using it! */
1954 if (data_size < sizeof (struct GNUNET_MessageHeader))
1956 GNUNET_break_op (0);
1960 if (data_size != ntohs (h->size))
1962 GNUNET_break_op (0);
1966 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message*) h,
1969 GNUNET_break_op (0);
1972 if (0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
1974 bucket = find_bucket (&pid.hashPubKey);
1975 if ( (bucket >= 0) &&
1976 (k_buckets[bucket].peers_size < bucket_size) )
1978 if (NULL != GDS_transport_handle)
1980 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle,
1982 GNUNET_TRANSPORT_try_connect (GDS_transport_handle,
1989 /* append 'peer' to 'get_path' */
1991 struct GNUNET_PeerIdentity xget_path[get_path_length+1];
1993 memcpy (xget_path, get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1994 xget_path[get_path_length] = *peer;
1997 /* forward to local clients */
1998 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2008 /* forward to other peers */
2009 GDS_ROUTING_process (type,
2010 GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2024 * Initialize neighbours subsystem.
2026 * @return GNUNET_OK on success, GNUNET_SYSERR on error
2029 GDS_NEIGHBOURS_init ()
2031 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2032 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2033 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2034 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2037 unsigned long long temp_config_num;
2040 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2042 bucket_size = (unsigned int) temp_config_num;
2043 coreAPI = GNUNET_CORE_connect (GDS_cfg,
2047 &handle_core_connect,
2048 &handle_core_disconnect,
2049 NULL, /* Do we care about "status" updates? */
2053 if (coreAPI == NULL)
2054 return GNUNET_SYSERR;
2055 all_known_peers = GNUNET_CONTAINER_multihashmap_create (256);
2061 * Shutdown neighbours subsystem.
2064 GDS_NEIGHBOURS_done ()
2066 if (coreAPI == NULL)
2068 GNUNET_CORE_disconnect (coreAPI);
2070 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2071 GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2072 all_known_peers = NULL;
2073 if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2075 GNUNET_SCHEDULER_cancel (find_peer_task);
2076 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2081 /* end of gnunet-service-dht_neighbours.c */