2 This file is part of GNUnet.
3 (C) 2009-2013 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_util_lib.h"
30 #include "gnunet_block_lib.h"
31 #include "gnunet_hello_lib.h"
32 #include "gnunet_constants.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_nse_service.h"
35 #include "gnunet_ats_service.h"
36 #include "gnunet_core_service.h"
37 #include "gnunet_datacache_lib.h"
38 #include "gnunet_transport_service.h"
39 #include "gnunet_hello_lib.h"
40 #include "gnunet_dht_service.h"
41 #include "gnunet_statistics_service.h"
42 #include "gnunet-service-dht.h"
43 #include "gnunet-service-dht_clients.h"
44 #include "gnunet-service-dht_datacache.h"
45 #include "gnunet-service-dht_hello.h"
46 #include "gnunet-service-dht_neighbours.h"
47 #include "gnunet-service-dht_nse.h"
48 #include "gnunet-service-dht_routing.h"
52 #define LOG_TRAFFIC(kind,...) GNUNET_log_from (kind, "dht-traffic",__VA_ARGS__)
55 * How many buckets will we allow total.
57 #define MAX_BUCKETS sizeof (struct GNUNET_HashCode) * 8
60 * What is the maximum number of peers in a given bucket.
62 #define DEFAULT_BUCKET_SIZE 8
65 * Desired replication level for FIND PEER requests
67 #define FIND_PEER_REPLICATION_LEVEL 4
70 * Maximum allowed replication level for all requests.
72 #define MAXIMUM_REPLICATION_LEVEL 16
75 * Maximum allowed number of pending messages per peer.
77 #define MAXIMUM_PENDING_PER_PEER 64
80 * How often to update our preference levels for peers in our routing tables.
82 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
85 * How long at least to wait before sending another find peer request.
87 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
90 * How long at most to wait before sending another find peer request.
92 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10)
95 * How long at most to wait for transmission of a GET request to another peer?
97 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
100 * Hello address expiration
102 extern struct GNUNET_TIME_Relative hello_expiration;
105 GNUNET_NETWORK_STRUCT_BEGIN
110 struct PeerPutMessage
113 * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
115 struct GNUNET_MessageHeader header;
120 uint32_t options GNUNET_PACKED;
125 uint32_t type GNUNET_PACKED;
130 uint32_t hop_count GNUNET_PACKED;
133 * Replication level for this message
135 uint32_t desired_replication_level GNUNET_PACKED;
138 * Length of the PUT path that follows (if tracked).
140 uint32_t put_path_length GNUNET_PACKED;
143 * When does the content expire?
145 struct GNUNET_TIME_AbsoluteNBO expiration_time;
148 * Bloomfilter (for peer identities) to stop circular routes
150 char bloomfilter[DHT_BLOOM_SIZE];
153 * The key we are storing under.
155 struct GNUNET_HashCode key;
157 /* put path (if tracked) */
167 struct PeerResultMessage
170 * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
172 struct GNUNET_MessageHeader header;
177 uint32_t type GNUNET_PACKED;
180 * Length of the PUT path that follows (if tracked).
182 uint32_t put_path_length GNUNET_PACKED;
185 * Length of the GET path that follows (if tracked).
187 uint32_t get_path_length GNUNET_PACKED;
190 * When does the content expire?
192 struct GNUNET_TIME_AbsoluteNBO expiration_time;
195 * The key of the corresponding GET request.
197 struct GNUNET_HashCode key;
199 /* put path (if tracked) */
201 /* get path (if tracked) */
211 struct PeerGetMessage
214 * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_GET
216 struct GNUNET_MessageHeader header;
221 uint32_t options GNUNET_PACKED;
224 * Desired content type.
226 uint32_t type GNUNET_PACKED;
231 uint32_t hop_count GNUNET_PACKED;
234 * Desired replication level for this request.
236 uint32_t desired_replication_level GNUNET_PACKED;
239 * Size of the extended query.
241 uint32_t xquery_size;
244 * Bloomfilter mutator.
249 * Bloomfilter (for peer identities) to stop circular routes
251 char bloomfilter[DHT_BLOOM_SIZE];
254 * The key we are looking for.
256 struct GNUNET_HashCode key;
260 /* result bloomfilter */
263 GNUNET_NETWORK_STRUCT_END
266 * Linked list of messages to send to a particular other peer.
268 struct P2PPendingMessage
271 * Pointer to next item in the list
273 struct P2PPendingMessage *next;
276 * Pointer to previous item in the list
278 struct P2PPendingMessage *prev;
281 * Message importance level. FIXME: used? useful?
283 unsigned int importance;
286 * When does this message time out?
288 struct GNUNET_TIME_Absolute timeout;
291 * Actual message to be sent, allocated at the end of the struct:
292 * // msg = (cast) &pm[1];
293 * // memcpy (&pm[1], data, len);
295 const struct GNUNET_MessageHeader *msg;
301 * Entry for a peer in a bucket.
306 * Next peer entry (DLL)
308 struct PeerInfo *next;
311 * Prev peer entry (DLL)
313 struct PeerInfo *prev;
316 * Count of outstanding messages for peer.
318 unsigned int pending_count;
321 * Head of pending messages to be sent to this peer.
323 struct P2PPendingMessage *head;
326 * Tail of pending messages to be sent to this peer.
328 struct P2PPendingMessage *tail;
331 * Core handle for sending messages to this peer.
333 struct GNUNET_CORE_TransmitHandle *th;
336 * Task for scheduling preference updates
338 GNUNET_SCHEDULER_TaskIdentifier preference_task;
341 * What is the identity of the peer?
343 struct GNUNET_PeerIdentity id;
347 * What is the average latency for replies received?
349 struct GNUNET_TIME_Relative latency;
352 * Transport level distance to peer.
354 unsigned int distance;
361 * Peers are grouped into buckets.
368 struct PeerInfo *head;
373 struct PeerInfo *tail;
376 * Number of peers in the bucket.
378 unsigned int peers_size;
383 * Do we cache all results that we are routing in the local datacache?
385 static int cache_results;
388 * Should routing details be logged to stderr (for debugging)?
390 static int log_route_details_stderr;
393 * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
395 static unsigned int closest_bucket;
398 * How many peers have we added since we sent out our last
401 static unsigned int newly_found_peers;
404 * Option for testing that disables the 'connect' function of the DHT.
406 static int disable_try_connect;
409 * The buckets. Array of size MAX_BUCKET_SIZE. Offset 0 means 0 bits matching.
411 static struct PeerBucket k_buckets[MAX_BUCKETS];
414 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
416 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
419 * Maximum size for each bucket.
421 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
424 * Task that sends FIND PEER requests.
426 static GNUNET_SCHEDULER_TaskIdentifier find_peer_task;
429 * Identity of this peer.
431 static struct GNUNET_PeerIdentity my_identity;
436 static struct GNUNET_CORE_Handle *coreAPI;
441 static struct GNUNET_ATS_PerformanceHandle *atsAPI;
446 * Find the optimal bucket for this key.
448 * @param hc the hashcode to compare our identity to
449 * @return the proper bucket index, or GNUNET_SYSERR
450 * on error (same hashcode)
453 find_bucket (const struct GNUNET_HashCode *hc)
457 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
458 if (bits == MAX_BUCKETS)
460 /* How can all bits match? Got my own ID? */
462 return GNUNET_SYSERR;
464 return MAX_BUCKETS - bits - 1;
469 * Let GNUnet core know that we like the given peer.
471 * @param cls the `struct PeerInfo` of the peer
472 * @param tc scheduler context.
475 update_core_preference (void *cls,
476 const struct GNUNET_SCHEDULER_TaskContext *tc)
478 struct PeerInfo *peer = cls;
480 unsigned int matching;
483 peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
484 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
487 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
488 &peer->id.hashPubKey);
491 bucket = find_bucket (&peer->id.hashPubKey);
492 if (bucket == GNUNET_SYSERR)
496 GNUNET_assert (k_buckets[bucket].peers_size != 0);
497 preference = (1LL << matching) / k_buckets[bucket].peers_size;
501 peer->preference_task =
502 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
503 &update_core_preference, peer);
506 GNUNET_STATISTICS_update (GDS_stats,
507 gettext_noop ("# Preference updates given to core"),
509 GNUNET_ATS_performance_change_preference (atsAPI, &peer->id,
510 GNUNET_ATS_PREFERENCE_BANDWIDTH,
511 (double) preference, GNUNET_ATS_PREFERENCE_END);
512 peer->preference_task =
513 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
514 &update_core_preference, peer);
521 * Closure for 'add_known_to_bloom'.
523 struct BloomConstructorContext
526 * Bloom filter under construction.
528 struct GNUNET_CONTAINER_BloomFilter *bloom;
538 * Add each of the peers we already know to the bloom filter of
539 * the request so that we don't get duplicate HELLOs.
541 * @param cls the 'struct BloomConstructorContext'.
542 * @param key peer identity to add to the bloom filter
543 * @param value value the peer information (unused)
544 * @return #GNUNET_YES (we should continue to iterate)
547 add_known_to_bloom (void *cls,
548 const struct GNUNET_HashCode *key,
551 struct BloomConstructorContext *ctx = cls;
552 struct GNUNET_HashCode mh;
554 GNUNET_BLOCK_mingle_hash (key, ctx->bf_mutator, &mh);
555 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
556 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
557 GNUNET_h2s (key), ctx->bf_mutator);
558 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
564 * Task to send a find peer message for our own peer identifier
565 * so that we can find the closest peers in the network to ourselves
566 * and attempt to connect to them.
568 * @param cls closure for this task
569 * @param tc the context under which the task is running
572 send_find_peer_message (void *cls,
573 const struct GNUNET_SCHEDULER_TaskContext *tc)
575 struct GNUNET_TIME_Relative next_send_time;
576 struct BloomConstructorContext bcc;
577 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
579 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
580 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
582 if (newly_found_peers > bucket_size)
584 /* If we are finding many peers already, no need to send out our request right now! */
586 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
587 &send_find_peer_message, NULL);
588 newly_found_peers = 0;
592 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
594 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
595 GNUNET_CONSTANTS_BLOOMFILTER_K);
596 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
598 GNUNET_STATISTICS_update (GDS_stats,
599 gettext_noop ("# FIND PEER messages initiated"), 1,
602 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
603 GNUNET_CONSTANTS_BLOOMFILTER_K);
604 // FIXME: pass priority!?
605 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
606 GNUNET_DHT_RO_FIND_PEER,
607 FIND_PEER_REPLICATION_LEVEL, 0,
608 &my_identity.hashPubKey, NULL, 0, bcc.bloom,
609 bcc.bf_mutator, peer_bf);
610 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
611 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
612 /* schedule next round */
613 next_send_time.rel_value_us =
614 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value_us +
615 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
616 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value_us /
617 (newly_found_peers + 1));
618 newly_found_peers = 0;
620 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
626 * Method called whenever a peer connects.
629 * @param peer peer identity this notification is about
632 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
634 struct PeerInfo *ret;
637 /* Check for connect to self message */
638 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
640 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected %s to %s\n",
641 GNUNET_i2s (&my_identity), GNUNET_h2s (&peer->hashPubKey));
643 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
649 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), 1,
651 peer_bucket = find_bucket (&peer->hashPubKey);
652 GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
653 ret = GNUNET_malloc (sizeof (struct PeerInfo));
655 ret->latency = latency;
656 ret->distance = distance;
659 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
660 k_buckets[peer_bucket].tail, ret);
661 k_buckets[peer_bucket].peers_size++;
662 closest_bucket = GNUNET_MAX (closest_bucket, peer_bucket);
663 if ((peer_bucket > 0) && (k_buckets[peer_bucket].peers_size <= bucket_size))
665 ret->preference_task =
666 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
669 GNUNET_assert (GNUNET_OK ==
670 GNUNET_CONTAINER_multihashmap_put (all_known_peers,
671 &peer->hashPubKey, ret,
672 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
673 if (1 == GNUNET_CONTAINER_multihashmap_size (all_known_peers) &&
674 (GNUNET_YES != disable_try_connect))
676 /* got a first connection, good time to start with FIND PEER requests... */
677 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
683 * Method called whenever a peer disconnects.
686 * @param peer peer identity this notification is about
689 handle_core_disconnect (void *cls,
690 const struct GNUNET_PeerIdentity *peer)
692 struct PeerInfo *to_remove;
694 struct P2PPendingMessage *pos;
695 unsigned int discarded;
697 /* Check for disconnect from self message */
698 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
700 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnected %s from %s\n",
701 GNUNET_i2s (&my_identity), GNUNET_h2s (&peer->hashPubKey));
703 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
704 if (NULL == to_remove)
709 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), -1,
711 GNUNET_assert (GNUNET_YES ==
712 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
715 if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
717 GNUNET_SCHEDULER_cancel (to_remove->preference_task);
718 to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
720 current_bucket = find_bucket (&to_remove->id.hashPubKey);
721 GNUNET_assert (current_bucket >= 0);
722 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
723 k_buckets[current_bucket].tail, to_remove);
724 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
725 k_buckets[current_bucket].peers_size--;
726 while ((closest_bucket > 0) && (k_buckets[closest_bucket].peers_size == 0))
729 if (to_remove->th != NULL)
731 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
732 to_remove->th = NULL;
735 while (NULL != (pos = to_remove->head))
737 GNUNET_CONTAINER_DLL_remove (to_remove->head, to_remove->tail, pos);
741 GNUNET_STATISTICS_update (GDS_stats,
743 ("# Queued messages discarded (peer disconnected)"),
744 discarded, GNUNET_NO);
745 GNUNET_free (to_remove);
750 * Called when core is ready to send a message we asked for
751 * out to the destination.
753 * @param cls the 'struct PeerInfo' of the target peer
754 * @param size number of bytes available in buf
755 * @param buf where the callee should write the message
756 * @return number of bytes written to buf
759 core_transmit_notify (void *cls, size_t size, void *buf)
761 struct PeerInfo *peer = cls;
763 struct P2PPendingMessage *pending;
768 while ((NULL != (pending = peer->head)) &&
769 (0 == GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value_us))
771 peer->pending_count--;
772 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
773 GNUNET_free (pending);
777 /* no messages pending */
783 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO,
785 GNUNET_TIME_absolute_get_remaining
786 (pending->timeout), &peer->id,
787 ntohs (pending->msg->size),
788 &core_transmit_notify, peer);
789 GNUNET_break (NULL != peer->th);
793 while ((NULL != (pending = peer->head)) &&
794 (size - off >= (msize = ntohs (pending->msg->size))))
796 GNUNET_STATISTICS_update (GDS_stats,
798 ("# Bytes transmitted to other peers"), msize,
800 memcpy (&cbuf[off], pending->msg, msize);
802 peer->pending_count--;
803 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
804 GNUNET_free (pending);
806 if (peer->head != NULL)
809 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO,
811 GNUNET_TIME_absolute_get_remaining
812 (pending->timeout), &peer->id, msize,
813 &core_transmit_notify, peer);
814 GNUNET_break (NULL != peer->th);
821 * Transmit all messages in the peer's message queue.
823 * @param peer message queue to process
826 process_peer_queue (struct PeerInfo *peer)
828 struct P2PPendingMessage *pending;
830 if (NULL == (pending = peer->head))
832 if (NULL != peer->th)
834 GNUNET_STATISTICS_update (GDS_stats,
836 ("# Bytes of bandwidth requested from core"),
837 ntohs (pending->msg->size), GNUNET_NO);
839 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO,
841 GNUNET_TIME_absolute_get_remaining
842 (pending->timeout), &peer->id,
843 ntohs (pending->msg->size),
844 &core_transmit_notify, peer);
845 GNUNET_break (NULL != peer->th);
850 * To how many peers should we (on average) forward the request to
851 * obtain the desired target_replication count (on average).
853 * @param hop_count number of hops the message has traversed
854 * @param target_replication the number of total paths desired
855 * @return Some number of peers to forward the message to
858 get_forward_count (uint32_t hop_count, uint32_t target_replication)
860 uint32_t random_value;
861 uint32_t forward_count;
864 if (hop_count > GDS_NSE_get () * 4.0)
866 /* forcefully terminate */
867 GNUNET_STATISTICS_update (GDS_stats,
868 gettext_noop ("# requests TTL-dropped"),
872 if (hop_count > GDS_NSE_get () * 2.0)
874 /* Once we have reached our ideal number of hops, only forward to 1 peer */
877 /* bound by system-wide maximum */
879 GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
881 1 + (target_replication - 1.0) / (GDS_NSE_get () +
882 ((float) (target_replication - 1.0) *
884 /* Set forward count to floor of target_value */
885 forward_count = (uint32_t) target_value;
886 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
887 target_value = target_value - forward_count;
889 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
890 if (random_value < (target_value * UINT32_MAX))
892 return forward_count;
897 * Compute the distance between have and target as a 32-bit value.
898 * Differences in the lower bits must count stronger than differences
899 * in the higher bits.
903 * @return 0 if have==target, otherwise a number
904 * that is larger as the distance between
905 * the two hash codes increases
908 get_distance (const struct GNUNET_HashCode *target,
909 const struct GNUNET_HashCode *have)
916 /* We have to represent the distance between two 2^9 (=512)-bit
917 * numbers as a 2^5 (=32)-bit number with "0" being used for the
918 * two numbers being identical; furthermore, we need to
919 * guarantee that a difference in the number of matching
920 * bits is always represented in the result.
922 * We use 2^32/2^9 numerical values to distinguish between
923 * hash codes that have the same LSB bit distance and
924 * use the highest 2^9 bits of the result to signify the
925 * number of (mis)matching LSB bits; if we have 0 matching
926 * and hence 512 mismatching LSB bits we return -1 (since
927 * 512 itself cannot be represented with 9 bits) */
929 /* first, calculate the most significant 9 bits of our
930 * result, aka the number of LSBs */
931 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
932 /* bucket is now a value between 0 and 512 */
934 return 0; /* perfect match */
936 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
937 * below, we'd end up with max+1 (overflow)) */
939 /* calculate the most significant bits of the final result */
940 msb = (512 - bucket) << (32 - 9);
941 /* calculate the 32-9 least significant bits of the final result by
942 * looking at the differences in the 32-9 bits following the
943 * mismatching bit at 'bucket' */
946 (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
948 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
949 GNUNET_CRYPTO_hash_get_bit (have, i))
950 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
951 * last bit set will be 31 -- if
952 * i does not reach 512 first... */
959 * Check whether my identity is closer than any known peers. If a
960 * non-null bloomfilter is given, check if this is the closest peer
961 * that hasn't already been routed to.
963 * @param key hash code to check closeness to
964 * @param bloom bloomfilter, exclude these entries from the decision
965 * @return GNUNET_YES if node location is closest,
966 * GNUNET_NO otherwise.
969 am_closest_peer (const struct GNUNET_HashCode * key,
970 const struct GNUNET_CONTAINER_BloomFilter *bloom)
976 struct PeerInfo *pos;
978 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (struct GNUNET_HashCode)))
980 bucket_num = find_bucket (key);
981 GNUNET_assert (bucket_num >= 0);
982 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
983 pos = k_buckets[bucket_num].head;
985 while ((pos != NULL) && (count < bucket_size))
987 if ((bloom != NULL) &&
989 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
992 continue; /* Skip already checked entries */
994 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
995 if (other_bits > bits)
997 if (other_bits == bits) /* We match the same number of bits */
1001 /* No peers closer, we are the closest! */
1007 * Select a peer from the routing table that would be a good routing
1008 * destination for sending a message for "key". The resulting peer
1009 * must not be in the set of blocked peers.<p>
1011 * Note that we should not ALWAYS select the closest peer to the
1012 * target, peers further away from the target should be chosen with
1013 * exponentially declining probability.
1015 * FIXME: double-check that this is fine
1018 * @param key the key we are selecting a peer to route to
1019 * @param bloom a bloomfilter containing entries this request has seen already
1020 * @param hops how many hops has this message traversed thus far
1021 * @return Peer to route to, or NULL on error
1023 static struct PeerInfo *
1024 select_peer (const struct GNUNET_HashCode * key,
1025 const struct GNUNET_CONTAINER_BloomFilter *bloom, uint32_t hops)
1029 unsigned int selected;
1030 struct PeerInfo *pos;
1032 unsigned int smallest_distance;
1033 struct PeerInfo *chosen;
1035 if (hops >= GDS_NSE_get ())
1037 /* greedy selection (closest peer that is not in bloomfilter) */
1038 smallest_distance = UINT_MAX;
1040 for (bc = 0; bc <= closest_bucket; bc++)
1042 pos = k_buckets[bc].head;
1044 while ((pos != NULL) && (count < bucket_size))
1046 if ((bloom == NULL) ||
1048 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1050 dist = get_distance (key, &pos->id.hashPubKey);
1051 if (dist < smallest_distance)
1054 smallest_distance = dist;
1059 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1060 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1061 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1062 GNUNET_STATISTICS_update (GDS_stats,
1064 ("# Peers excluded from routing due to Bloomfilter"),
1066 dist = get_distance (key, &pos->id.hashPubKey);
1067 if (dist < smallest_distance)
1070 smallest_distance = dist;
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 = 0; bc <= closest_bucket; 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,
1098 ("# Peers excluded from routing due to Bloomfilter"),
1100 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1101 "Excluded peer `%s' due to BF match in random routing for %s\n",
1102 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1104 continue; /* Ignore bloomfiltered peers */
1110 if (0 == count) /* 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 = 0; bc <= closest_bucket; bc++)
1122 for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next)
1124 if ((bloom != NULL) &&
1126 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1128 continue; /* Ignore bloomfiltered peers */
1130 if (0 == selected--)
1140 * Compute the set of peers that the given request should be
1143 * @param key routing key
1144 * @param bloom bloom filter excluding peers as targets, all selected
1145 * peers will be added to the bloom filter
1146 * @param hop_count number of hops the request has traversed so far
1147 * @param target_replication desired number of replicas
1148 * @param targets where to store an array of target peers (to be
1149 * free'd by the caller)
1150 * @return number of peers returned in 'targets'.
1153 get_target_peers (const struct GNUNET_HashCode *key,
1154 struct GNUNET_CONTAINER_BloomFilter *bloom,
1155 uint32_t hop_count, uint32_t target_replication,
1156 struct PeerInfo ***targets)
1160 struct PeerInfo **rtargets;
1161 struct PeerInfo *nxt;
1163 GNUNET_assert (NULL != bloom);
1164 ret = get_forward_count (hop_count, target_replication);
1170 rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1171 for (off = 0; off < ret; off++)
1173 nxt = select_peer (key, bloom, hop_count);
1176 rtargets[off] = nxt;
1177 GNUNET_break (GNUNET_NO ==
1178 GNUNET_CONTAINER_bloomfilter_test (bloom,
1179 &nxt->id.hashPubKey));
1180 GNUNET_CONTAINER_bloomfilter_add (bloom, &rtargets[off]->id.hashPubKey);
1182 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1183 "Selected %u/%u peers at hop %u for %s (target was %u)\n", off,
1184 GNUNET_CONTAINER_multihashmap_size (all_known_peers),
1185 (unsigned int) hop_count, GNUNET_h2s (key), ret);
1188 GNUNET_free (rtargets);
1192 *targets = rtargets;
1193 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1194 "Forwarding query `%s' to %u peers (goal was %u peers)\n",
1203 * Perform a PUT operation. Forwards the given request to other
1204 * peers. Does not store the data locally. Does not give the
1205 * data to local clients. May do nothing if this is the only
1206 * peer in the network (or if we are the closest peer in the
1209 * @param type type of the block
1210 * @param options routing options
1211 * @param desired_replication_level desired replication count
1212 * @param expiration_time when does the content expire
1213 * @param hop_count how many hops has this message traversed so far
1214 * @param bf Bloom filter of peers this PUT has already traversed
1215 * @param key key for the content
1216 * @param put_path_length number of entries in @a put_path
1217 * @param put_path peers this request has traversed so far (if tracked)
1218 * @param data payload to store
1219 * @param data_size number of bytes in @a data
1222 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1223 enum GNUNET_DHT_RouteOption options,
1224 uint32_t desired_replication_level,
1225 struct GNUNET_TIME_Absolute expiration_time,
1227 struct GNUNET_CONTAINER_BloomFilter *bf,
1228 const struct GNUNET_HashCode *key,
1229 unsigned int put_path_length,
1230 struct GNUNET_PeerIdentity *put_path,
1231 const void *data, size_t data_size)
1233 unsigned int target_count;
1235 struct PeerInfo **targets;
1236 struct PeerInfo *target;
1237 struct P2PPendingMessage *pending;
1239 struct PeerPutMessage *ppm;
1240 struct GNUNET_PeerIdentity *pp;
1242 GNUNET_assert (NULL != bf);
1243 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1244 "Adding myself (%s) to PUT bloomfilter for %s\n",
1245 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1246 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1247 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1250 get_target_peers (key, bf, hop_count, desired_replication_level,
1252 if (0 == target_count)
1254 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1255 "Routing PUT for %s terminates after %u hops at %s\n",
1256 GNUNET_h2s (key), (unsigned int) hop_count,
1257 GNUNET_i2s (&my_identity));
1261 put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1262 sizeof (struct PeerPutMessage);
1263 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1265 put_path_length = 0;
1266 msize = data_size + sizeof (struct PeerPutMessage);
1268 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1271 GNUNET_free (targets);
1274 GNUNET_STATISTICS_update (GDS_stats,
1276 ("# PUT messages queued for transmission"),
1277 target_count, GNUNET_NO);
1278 for (i = 0; i < target_count; i++)
1280 target = targets[i];
1281 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1283 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1285 continue; /* skip */
1287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1288 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1289 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1290 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1291 pending->importance = 0; /* FIXME */
1292 pending->timeout = expiration_time;
1293 ppm = (struct PeerPutMessage *) &pending[1];
1294 pending->msg = &ppm->header;
1295 ppm->header.size = htons (msize);
1296 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1297 ppm->options = htonl (options);
1298 ppm->type = htonl (type);
1299 ppm->hop_count = htonl (hop_count + 1);
1300 ppm->desired_replication_level = htonl (desired_replication_level);
1301 ppm->put_path_length = htonl (put_path_length);
1302 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1303 GNUNET_break (GNUNET_YES ==
1304 GNUNET_CONTAINER_bloomfilter_test (bf,
1305 &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,
1313 sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1314 memcpy (&pp[put_path_length], data, data_size);
1315 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1316 target->pending_count++;
1317 process_peer_queue (target);
1319 GNUNET_free (targets);
1324 * Perform a GET operation. Forwards the given request to other
1325 * peers. Does not lookup the key locally. May do nothing if this is
1326 * the only peer in the network (or if we are the closest peer in the
1329 * @param type type of the block
1330 * @param options routing options
1331 * @param desired_replication_level desired replication count
1332 * @param hop_count how many hops did this request traverse so far?
1333 * @param key key for the content
1334 * @param xquery extended query
1335 * @param xquery_size number of bytes in @a xquery
1336 * @param reply_bf bloomfilter to filter duplicates
1337 * @param reply_bf_mutator mutator for @a reply_bf
1338 * @param peer_bf filter for peers not to select (again)
1341 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1342 enum GNUNET_DHT_RouteOption options,
1343 uint32_t desired_replication_level,
1344 uint32_t hop_count, const struct GNUNET_HashCode * key,
1345 const void *xquery, size_t xquery_size,
1346 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1347 uint32_t reply_bf_mutator,
1348 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1350 unsigned int target_count;
1352 struct PeerInfo **targets;
1353 struct PeerInfo *target;
1354 struct P2PPendingMessage *pending;
1356 struct PeerGetMessage *pgm;
1358 size_t reply_bf_size;
1360 GNUNET_assert (NULL != peer_bf);
1361 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1364 get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1366 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1367 "Adding myself (%s) to GET bloomfilter for %s\n",
1368 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
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",
1374 GNUNET_h2s (key), (unsigned int) hop_count,
1375 GNUNET_i2s (&my_identity));
1378 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1379 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1380 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1383 GNUNET_free (targets);
1386 GNUNET_STATISTICS_update (GDS_stats,
1388 ("# GET messages queued for transmission"),
1389 target_count, GNUNET_NO);
1390 /* forward request */
1391 for (i = 0; i < target_count; i++)
1393 target = targets[i];
1394 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1396 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1398 continue; /* skip */
1400 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1401 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1402 (unsigned int) hop_count, 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 ==
1417 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1418 &target->id.hashPubKey));
1419 GNUNET_assert (GNUNET_OK ==
1420 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1424 xq = (char *) &pgm[1];
1425 memcpy (xq, xquery, xquery_size);
1426 if (NULL != reply_bf)
1427 GNUNET_assert (GNUNET_OK ==
1428 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1432 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1433 target->pending_count++;
1434 process_peer_queue (target);
1436 GNUNET_free (targets);
1441 * Handle a reply (route to origin). Only forwards the reply back to
1442 * the given peer. Does not do local caching or forwarding to local
1445 * @param target neighbour that should receive the block (if still connected)
1446 * @param type type of the block
1447 * @param expiration_time when does the content expire
1448 * @param key key for the content
1449 * @param put_path_length number of entries in @a put_path
1450 * @param put_path peers the original PUT traversed (if tracked)
1451 * @param get_path_length number of entries in @a get_path
1452 * @param get_path peers this reply has traversed so far (if tracked)
1453 * @param data payload of the reply
1454 * @param data_size number of bytes in @a data
1457 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1458 enum GNUNET_BLOCK_Type type,
1459 struct GNUNET_TIME_Absolute expiration_time,
1460 const struct GNUNET_HashCode * key,
1461 unsigned int put_path_length,
1462 const struct GNUNET_PeerIdentity *put_path,
1463 unsigned int get_path_length,
1464 const struct GNUNET_PeerIdentity *get_path,
1465 const void *data, size_t data_size)
1467 struct PeerInfo *pi;
1468 struct P2PPendingMessage *pending;
1470 struct PeerResultMessage *prm;
1471 struct GNUNET_PeerIdentity *paths;
1474 data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1476 sizeof (struct GNUNET_PeerIdentity);
1477 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1479 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1481 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1482 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1487 pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers, &target->hashPubKey);
1490 /* peer disconnected in the meantime, drop reply */
1493 if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1496 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1501 GNUNET_STATISTICS_update (GDS_stats,
1503 ("# RESULT messages queued for transmission"), 1,
1505 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1506 pending->importance = 0; /* FIXME */
1507 pending->timeout = expiration_time;
1508 prm = (struct PeerResultMessage *) &pending[1];
1509 pending->msg = &prm->header;
1510 prm->header.size = htons (msize);
1511 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1512 prm->type = htonl (type);
1513 prm->put_path_length = htonl (put_path_length);
1514 prm->get_path_length = htonl (get_path_length);
1515 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1517 paths = (struct GNUNET_PeerIdentity *) &prm[1];
1518 memcpy (paths, put_path,
1519 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1520 memcpy (&paths[put_path_length], get_path,
1521 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1522 memcpy (&paths[put_path_length + get_path_length], data, data_size);
1523 GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1524 pi->pending_count++;
1525 process_peer_queue (pi);
1530 * To be called on core init/fail.
1532 * @param cls service closure
1533 * @param identity the public identity of this peer
1536 core_init (void *cls,
1537 const struct GNUNET_PeerIdentity *identity)
1539 my_identity = *identity;
1544 * Core handler for p2p put requests.
1546 * @param cls closure
1547 * @param peer sender of the request
1548 * @param message message
1549 * @param peer peer identity this notification is about
1550 * @return #GNUNET_OK to keep the connection open,
1551 * #GNUNET_SYSERR to close it (signal serious error)
1554 handle_dht_p2p_put (void *cls,
1555 const struct GNUNET_PeerIdentity *peer,
1556 const struct GNUNET_MessageHeader *message)
1558 const struct PeerPutMessage *put;
1559 const struct GNUNET_PeerIdentity *put_path;
1560 const void *payload;
1563 size_t payload_size;
1564 enum GNUNET_DHT_RouteOption options;
1565 struct GNUNET_CONTAINER_BloomFilter *bf;
1566 struct GNUNET_HashCode test_key;
1568 msize = ntohs (message->size);
1569 if (msize < sizeof (struct PeerPutMessage))
1571 GNUNET_break_op (0);
1574 put = (const struct PeerPutMessage *) message;
1575 putlen = ntohl (put->put_path_length);
1577 sizeof (struct PeerPutMessage) +
1578 putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1580 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1582 GNUNET_break_op (0);
1585 GNUNET_STATISTICS_update (GDS_stats,
1586 gettext_noop ("# P2P PUT requests received"), 1,
1588 GNUNET_STATISTICS_update (GDS_stats,
1589 gettext_noop ("# P2P PUT bytes received"), msize,
1591 put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1592 payload = &put_path[putlen];
1593 options = ntohl (put->options);
1595 msize - (sizeof (struct PeerPutMessage) +
1596 putlen * sizeof (struct GNUNET_PeerIdentity));
1597 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1598 GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1599 if (GNUNET_YES == log_route_details_stderr)
1603 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1604 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1605 "XDHT PUT %s: %s->%s (%u, %u=>%u)\n",
1606 GNUNET_h2s (&put->key), GNUNET_i2s (peer), tmp,
1607 ntohl(put->hop_count),
1608 GNUNET_CRYPTO_hash_matching_bits (&peer->hashPubKey, &put->key),
1609 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, &put->key)
1613 switch (GNUNET_BLOCK_get_key
1614 (GDS_block_context, ntohl (put->type), payload, payload_size,
1618 if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1620 char *put_s = GNUNET_strdup (GNUNET_h2s (&put->key));
1621 GNUNET_break_op (0);
1622 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1623 "PUT with key `%s' for block with key %s\n",
1624 put_s, GNUNET_h2s (&test_key));
1625 GNUNET_free (put_s);
1630 GNUNET_break_op (0);
1633 /* cannot verify, good luck */
1636 if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
1638 switch (GNUNET_BLOCK_evaluate (GDS_block_context,
1641 NULL, 0, /* bloom filer */
1642 NULL, 0, /* xquery */
1643 payload, payload_size))
1645 case GNUNET_BLOCK_EVALUATION_OK_MORE:
1646 case GNUNET_BLOCK_EVALUATION_OK_LAST:
1649 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1650 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1651 case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1652 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1653 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1654 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1656 GNUNET_break_op (0);
1661 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1662 GNUNET_CONSTANTS_BLOOMFILTER_K);
1663 GNUNET_break_op (GNUNET_YES ==
1664 GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1666 struct GNUNET_PeerIdentity pp[putlen + 1];
1668 /* extend 'put path' by sender */
1669 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1671 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1678 /* give to local clients */
1679 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1680 &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1681 payload_size, payload);
1683 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1684 (am_closest_peer (&put->key, bf)))
1685 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1686 (put->expiration_time), &put->key, putlen, pp,
1687 ntohl (put->type), payload_size, payload);
1688 /* route to other peers */
1689 GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1690 ntohl (put->desired_replication_level),
1691 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1692 ntohl (put->hop_count), bf, &put->key, putlen,
1693 pp, payload, payload_size);
1694 /* notify monitoring clients */
1695 GDS_CLIENTS_process_put (options,
1697 ntohl (put->hop_count),
1698 ntohl (put->desired_replication_level),
1700 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1705 GNUNET_CONTAINER_bloomfilter_free (bf);
1711 * We have received a FIND PEER request. Send matching
1714 * @param sender sender of the FIND PEER request
1715 * @param key peers close to this key are desired
1716 * @param bf peers matching this bf are excluded
1717 * @param bf_mutator mutator for bf
1720 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1721 const struct GNUNET_HashCode * key,
1722 struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1725 struct PeerBucket *bucket;
1726 struct PeerInfo *peer;
1727 unsigned int choice;
1728 struct GNUNET_HashCode mhash;
1729 const struct GNUNET_HELLO_Message *hello;
1731 /* first, check about our own HELLO */
1732 if (NULL != GDS_my_hello)
1734 GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1736 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1738 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1739 GNUNET_TIME_relative_to_absolute
1741 key, 0, NULL, 0, NULL, GDS_my_hello,
1742 GNUNET_HELLO_size ((const struct
1743 GNUNET_HELLO_Message *)
1748 GNUNET_STATISTICS_update (GDS_stats,
1750 ("# FIND PEER requests ignored due to Bloomfilter"),
1756 GNUNET_STATISTICS_update (GDS_stats,
1758 ("# FIND PEER requests ignored due to lack of HELLO"),
1762 /* then, also consider sending a random HELLO from the closest bucket */
1763 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (struct GNUNET_HashCode)))
1764 bucket_idx = closest_bucket;
1766 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1767 if (bucket_idx == GNUNET_SYSERR)
1769 bucket = &k_buckets[bucket_idx];
1770 if (bucket->peers_size == 0)
1773 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1774 peer = bucket->head;
1777 GNUNET_assert (NULL != peer);
1781 choice = bucket->peers_size;
1786 return; /* no non-masked peer available */
1788 peer = bucket->head;
1789 GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1790 hello = GDS_HELLO_get (&peer->id);
1792 while ((hello == NULL) ||
1793 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1794 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1795 GNUNET_TIME_relative_to_absolute
1796 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1797 0, NULL, 0, NULL, hello,
1798 GNUNET_HELLO_size (hello));
1803 * Core handler for p2p get requests.
1805 * @param cls closure
1806 * @param peer sender of the request
1807 * @param message message
1808 * @return #GNUNET_OK to keep the connection open,
1809 * #GNUNET_SYSERR to close it (signal serious error)
1812 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1813 const struct GNUNET_MessageHeader *message)
1815 struct PeerGetMessage *get;
1816 uint32_t xquery_size;
1817 size_t reply_bf_size;
1819 enum GNUNET_BLOCK_Type type;
1820 enum GNUNET_DHT_RouteOption options;
1821 enum GNUNET_BLOCK_EvaluationResult eval;
1822 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1823 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1827 memcmp (peer, &my_identity,
1828 sizeof (struct GNUNET_PeerIdentity)));
1829 /* parse and validate message */
1830 msize = ntohs (message->size);
1831 if (msize < sizeof (struct PeerGetMessage))
1833 GNUNET_break_op (0);
1836 get = (struct PeerGetMessage *) message;
1837 xquery_size = ntohl (get->xquery_size);
1838 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1840 GNUNET_break_op (0);
1843 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1844 type = ntohl (get->type);
1845 options = ntohl (get->options);
1846 xquery = (const char *) &get[1];
1848 GNUNET_STATISTICS_update (GDS_stats,
1849 gettext_noop ("# P2P GET requests received"), 1,
1851 GNUNET_STATISTICS_update (GDS_stats,
1852 gettext_noop ("# P2P GET bytes received"), msize,
1854 if (GNUNET_YES == log_route_details_stderr)
1858 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1859 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1860 "XDHT GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n",
1861 GNUNET_h2s (&get->key), GNUNET_i2s (peer), tmp,
1862 ntohl(get->hop_count),
1863 GNUNET_CRYPTO_hash_matching_bits (&peer->hashPubKey, &get->key),
1864 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, &get->key),
1865 ntohl(get->xquery_size), xquery
1870 if (reply_bf_size > 0)
1872 GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1873 GNUNET_CONSTANTS_BLOOMFILTER_K);
1875 GNUNET_BLOCK_evaluate (GDS_block_context, type, &get->key, &reply_bf,
1876 get->bf_mutator, xquery, xquery_size, NULL, 0);
1877 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1879 /* request invalid or block type not supported */
1880 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1881 if (NULL != reply_bf)
1882 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1886 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1887 GNUNET_CONSTANTS_BLOOMFILTER_K);
1888 GNUNET_break_op (GNUNET_YES ==
1889 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1890 &peer->hashPubKey));
1891 /* remember request for routing replies */
1892 GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1893 reply_bf, get->bf_mutator);
1894 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GET for %s at %s after %u hops\n",
1895 GNUNET_h2s (&get->key), GNUNET_i2s (&my_identity),
1896 (unsigned int) ntohl (get->hop_count));
1897 /* local lookup (this may update the reply_bf) */
1898 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1899 (am_closest_peer (&get->key, peer_bf)))
1901 if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1903 GNUNET_STATISTICS_update (GDS_stats,
1905 ("# P2P FIND PEER requests processed"), 1,
1907 handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
1912 GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
1913 &reply_bf, get->bf_mutator);
1918 GNUNET_STATISTICS_update (GDS_stats,
1919 gettext_noop ("# P2P GET requests ONLY routed"),
1923 GDS_CLIENTS_process_get (options,
1925 ntohl(get->hop_count),
1926 ntohl(get->desired_replication_level),
1930 /* P2P forwarding */
1931 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1932 GDS_NEIGHBOURS_handle_get (type, options,
1933 ntohl (get->desired_replication_level),
1934 ntohl (get->hop_count), &get->key, xquery,
1935 xquery_size, reply_bf, get->bf_mutator, peer_bf);
1937 if (NULL != reply_bf)
1938 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1939 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
1945 * Core handler for p2p result messages.
1947 * @param cls closure
1948 * @param message message
1949 * @param peer peer identity this notification is about
1950 * @return #GNUNET_YES (do not cut p2p connection)
1953 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1954 const struct GNUNET_MessageHeader *message)
1956 const struct PeerResultMessage *prm;
1957 const struct GNUNET_PeerIdentity *put_path;
1958 const struct GNUNET_PeerIdentity *get_path;
1960 uint32_t get_path_length;
1961 uint32_t put_path_length;
1964 enum GNUNET_BLOCK_Type type;
1966 /* parse and validate message */
1967 msize = ntohs (message->size);
1968 if (msize < sizeof (struct PeerResultMessage))
1970 GNUNET_break_op (0);
1973 prm = (struct PeerResultMessage *) message;
1974 put_path_length = ntohl (prm->put_path_length);
1975 get_path_length = ntohl (prm->get_path_length);
1977 sizeof (struct PeerResultMessage) + (get_path_length +
1979 sizeof (struct GNUNET_PeerIdentity)) ||
1981 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1983 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1985 GNUNET_break_op (0);
1988 put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
1989 get_path = &put_path[put_path_length];
1990 type = ntohl (prm->type);
1991 data = (const void *) &get_path[get_path_length];
1993 msize - (sizeof (struct PeerResultMessage) +
1995 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1996 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
1998 GNUNET_STATISTICS_update (GDS_stats,
1999 gettext_noop ("# P2P RESULT bytes received"),
2001 if (GNUNET_YES == log_route_details_stderr)
2005 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
2006 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, "XDHT RESULT %s: %s->%s (%u)\n",
2007 GNUNET_h2s (&prm->key), GNUNET_i2s (peer), tmp,
2008 get_path_length + 1);
2011 /* if we got a HELLO, consider it for our own routing table */
2012 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
2014 const struct GNUNET_MessageHeader *h;
2015 struct GNUNET_PeerIdentity pid;
2018 /* Should be a HELLO, validate and consider using it! */
2019 if (data_size < sizeof (struct GNUNET_MessageHeader))
2021 GNUNET_break_op (0);
2025 if (data_size != ntohs (h->size))
2027 GNUNET_break_op (0);
2031 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
2033 GNUNET_break_op (0);
2036 if ((GNUNET_YES != disable_try_connect) &&
2037 0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
2039 bucket = find_bucket (&pid.hashPubKey);
2040 if ((bucket >= 0) &&
2041 (k_buckets[bucket].peers_size < bucket_size) &&
2042 (NULL != GDS_transport_handle))
2044 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
2045 GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid, NULL, NULL); /*FIXME TRY_CONNECT change */
2050 /* append 'peer' to 'get_path' */
2052 struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
2054 memcpy (xget_path, get_path,
2055 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2056 xget_path[get_path_length] = *peer;
2059 /* forward to local clients */
2060 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2061 &prm->key, get_path_length, xget_path,
2062 put_path_length, put_path, type, data_size, data);
2063 GDS_CLIENTS_process_get_resp (type,
2064 xget_path, get_path_length,
2065 put_path, put_path_length,
2066 GNUNET_TIME_absolute_ntoh (
2067 prm->expiration_time),
2071 if (GNUNET_YES == cache_results)
2073 struct GNUNET_PeerIdentity xput_path[get_path_length + 1 + put_path_length];
2075 memcpy (xput_path, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
2076 memcpy (&xput_path[put_path_length],
2078 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2080 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2082 get_path_length + put_path_length, xput_path,
2083 type, data_size, data);
2085 /* forward to other peers */
2086 GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2087 &prm->key, put_path_length, put_path, get_path_length,
2088 xget_path, data, data_size);
2096 * Initialize neighbours subsystem.
2098 * @return GNUNET_OK on success, GNUNET_SYSERR on error
2101 GDS_NEIGHBOURS_init ()
2103 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2104 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2105 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2106 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2109 unsigned long long temp_config_num;
2112 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2114 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2116 bucket_size = (unsigned int) temp_config_num;
2118 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "CACHE_RESULTS");
2120 log_route_details_stderr =
2121 (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO;
2122 atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2124 GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
2125 &handle_core_disconnect, NULL, GNUNET_NO, NULL,
2126 GNUNET_NO, core_handlers);
2127 if (coreAPI == NULL)
2128 return GNUNET_SYSERR;
2129 all_known_peers = GNUNET_CONTAINER_multihashmap_create (256, GNUNET_NO);
2135 * Shutdown neighbours subsystem.
2138 GDS_NEIGHBOURS_done ()
2140 if (NULL == coreAPI)
2142 GNUNET_CORE_disconnect (coreAPI);
2144 GNUNET_ATS_performance_done (atsAPI);
2146 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2147 GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2148 all_known_peers = NULL;
2149 if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2151 GNUNET_SCHEDULER_cancel (find_peer_task);
2152 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2157 * Get the ID of the local node.
2159 * @return identity of the local node
2161 struct GNUNET_PeerIdentity *
2162 GDS_NEIGHBOURS_get_id ()
2164 return &my_identity;
2168 /* end of gnunet-service-dht_neighbours.c */