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
28 #include "gnunet_util_lib.h"
29 #include "gnunet_block_lib.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_constants.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_nse_service.h"
34 #include "gnunet_ats_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"
51 #define LOG_TRAFFIC(kind,...) GNUNET_log_from (kind, "dht-traffic",__VA_ARGS__)
54 * How many buckets will we allow total.
56 #define MAX_BUCKETS sizeof (struct GNUNET_HashCode) * 8
59 * What is the maximum number of peers in a given bucket.
61 #define DEFAULT_BUCKET_SIZE 8
64 * Desired replication level for FIND PEER requests
66 #define FIND_PEER_REPLICATION_LEVEL 4
69 * Maximum allowed replication level for all requests.
71 #define MAXIMUM_REPLICATION_LEVEL 16
74 * Maximum allowed number of pending messages per peer.
76 #define MAXIMUM_PENDING_PER_PEER 64
79 * How often to update our preference levels for peers in our routing tables.
81 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
84 * How long at least to wait before sending another find peer request.
86 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
89 * How long at most to wait before sending another find peer request.
91 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10)
94 * How long at most to wait for transmission of a GET request to another peer?
96 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
99 * Hello address expiration
101 extern struct GNUNET_TIME_Relative hello_expiration;
104 GNUNET_NETWORK_STRUCT_BEGIN
109 struct PeerPutMessage
112 * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
114 struct GNUNET_MessageHeader header;
119 uint32_t options GNUNET_PACKED;
124 uint32_t type GNUNET_PACKED;
129 uint32_t hop_count GNUNET_PACKED;
132 * Replication level for this message
134 uint32_t desired_replication_level GNUNET_PACKED;
137 * Length of the PUT path that follows (if tracked).
139 uint32_t put_path_length GNUNET_PACKED;
142 * When does the content expire?
144 struct GNUNET_TIME_AbsoluteNBO expiration_time;
147 * Bloomfilter (for peer identities) to stop circular routes
149 char bloomfilter[DHT_BLOOM_SIZE];
152 * The key we are storing under.
154 struct GNUNET_HashCode key;
156 /* put path (if tracked) */
166 struct PeerResultMessage
169 * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
171 struct GNUNET_MessageHeader header;
176 uint32_t type GNUNET_PACKED;
179 * Length of the PUT path that follows (if tracked).
181 uint32_t put_path_length GNUNET_PACKED;
184 * Length of the GET path that follows (if tracked).
186 uint32_t get_path_length GNUNET_PACKED;
189 * When does the content expire?
191 struct GNUNET_TIME_AbsoluteNBO expiration_time;
194 * The key of the corresponding GET request.
196 struct GNUNET_HashCode key;
198 /* put path (if tracked) */
200 /* get path (if tracked) */
210 struct PeerGetMessage
213 * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_GET
215 struct GNUNET_MessageHeader header;
220 uint32_t options GNUNET_PACKED;
223 * Desired content type.
225 uint32_t type GNUNET_PACKED;
230 uint32_t hop_count GNUNET_PACKED;
233 * Desired replication level for this request.
235 uint32_t desired_replication_level GNUNET_PACKED;
238 * Size of the extended query.
240 uint32_t xquery_size;
243 * Bloomfilter mutator.
248 * Bloomfilter (for peer identities) to stop circular routes
250 char bloomfilter[DHT_BLOOM_SIZE];
253 * The key we are looking for.
255 struct GNUNET_HashCode key;
259 /* result bloomfilter */
262 GNUNET_NETWORK_STRUCT_END
265 * Linked list of messages to send to a particular other peer.
267 struct P2PPendingMessage
270 * Pointer to next item in the list
272 struct P2PPendingMessage *next;
275 * Pointer to previous item in the list
277 struct P2PPendingMessage *prev;
280 * Message importance level. FIXME: used? useful?
282 unsigned int importance;
285 * When does this message time out?
287 struct GNUNET_TIME_Absolute timeout;
290 * Actual message to be sent, allocated at the end of the struct:
291 * // msg = (cast) &pm[1];
292 * // memcpy (&pm[1], data, len);
294 const struct GNUNET_MessageHeader *msg;
300 * Entry for a peer in a bucket.
305 * Next peer entry (DLL)
307 struct PeerInfo *next;
310 * Prev peer entry (DLL)
312 struct PeerInfo *prev;
315 * Count of outstanding messages for peer.
317 unsigned int pending_count;
320 * Head of pending messages to be sent to this peer.
322 struct P2PPendingMessage *head;
325 * Tail of pending messages to be sent to this peer.
327 struct P2PPendingMessage *tail;
330 * Core handle for sending messages to this peer.
332 struct GNUNET_CORE_TransmitHandle *th;
335 * Task for scheduling preference updates
337 struct GNUNET_SCHEDULER_Task * preference_task;
340 * What is the identity of the peer?
342 struct GNUNET_PeerIdentity id;
346 * What is the average latency for replies received?
348 struct GNUNET_TIME_Relative latency;
351 * Transport level distance to peer.
353 unsigned int distance;
360 * Peers are grouped into buckets.
367 struct PeerInfo *head;
372 struct PeerInfo *tail;
375 * Number of peers in the bucket.
377 unsigned int peers_size;
382 * Do we cache all results that we are routing in the local datacache?
384 static int cache_results;
387 * Should routing details be logged to stderr (for debugging)?
389 static int log_route_details_stderr;
392 * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
394 static unsigned int closest_bucket;
397 * How many peers have we added since we sent out our last
400 static unsigned int newly_found_peers;
403 * Option for testing that disables the 'connect' function of the DHT.
405 static int disable_try_connect;
408 * The buckets. Array of size MAX_BUCKET_SIZE. Offset 0 means 0 bits matching.
410 static struct PeerBucket k_buckets[MAX_BUCKETS];
413 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
415 static struct GNUNET_CONTAINER_MultiPeerMap *all_known_peers;
418 * Maximum size for each bucket.
420 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
423 * Task that sends FIND PEER requests.
425 static struct GNUNET_SCHEDULER_Task * find_peer_task;
428 * Identity of this peer.
430 static struct GNUNET_PeerIdentity my_identity;
433 * Hash of the identity of this peer.
435 static struct GNUNET_HashCode my_identity_hash;
440 static struct GNUNET_CORE_Handle *core_api;
445 static struct GNUNET_ATS_PerformanceHandle *atsAPI;
450 * Find the optimal bucket for this key.
452 * @param hc the hashcode to compare our identity to
453 * @return the proper bucket index, or GNUNET_SYSERR
454 * on error (same hashcode)
457 find_bucket (const struct GNUNET_HashCode *hc)
461 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, hc);
462 if (bits == MAX_BUCKETS)
464 /* How can all bits match? Got my own ID? */
466 return GNUNET_SYSERR;
468 return MAX_BUCKETS - bits - 1;
473 * Let GNUnet core know that we like the given peer.
475 * @param cls the `struct PeerInfo` of the peer
476 * @param tc scheduler context.
479 update_core_preference (void *cls,
480 const struct GNUNET_SCHEDULER_TaskContext *tc)
482 struct PeerInfo *peer = cls;
484 unsigned int matching;
486 struct GNUNET_HashCode phash;
488 peer->preference_task = NULL;
489 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
491 GNUNET_CRYPTO_hash (&peer->id,
492 sizeof (struct GNUNET_PeerIdentity),
495 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash,
499 bucket = find_bucket (&phash);
500 if (bucket == GNUNET_SYSERR)
504 GNUNET_assert (k_buckets[bucket].peers_size != 0);
505 preference = (1LL << matching) / k_buckets[bucket].peers_size;
509 peer->preference_task =
510 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
511 &update_core_preference, peer);
514 GNUNET_STATISTICS_update (GDS_stats,
515 gettext_noop ("# Preference updates given to core"),
517 GNUNET_ATS_performance_change_preference (atsAPI, &peer->id,
518 GNUNET_ATS_PREFERENCE_BANDWIDTH,
519 (double) preference, GNUNET_ATS_PREFERENCE_END);
520 peer->preference_task =
521 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
522 &update_core_preference, peer);
529 * Closure for 'add_known_to_bloom'.
531 struct BloomConstructorContext
534 * Bloom filter under construction.
536 struct GNUNET_CONTAINER_BloomFilter *bloom;
546 * Add each of the peers we already know to the bloom filter of
547 * the request so that we don't get duplicate HELLOs.
549 * @param cls the 'struct BloomConstructorContext'.
550 * @param key peer identity to add to the bloom filter
551 * @param value value the peer information (unused)
552 * @return #GNUNET_YES (we should continue to iterate)
555 add_known_to_bloom (void *cls,
556 const struct GNUNET_PeerIdentity *key,
559 struct BloomConstructorContext *ctx = cls;
560 struct GNUNET_HashCode key_hash;
561 struct GNUNET_HashCode mh;
563 GNUNET_CRYPTO_hash (key, sizeof (struct GNUNET_PeerIdentity), &key_hash);
564 GNUNET_BLOCK_mingle_hash (&key_hash, ctx->bf_mutator, &mh);
565 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
566 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
567 GNUNET_i2s (key), ctx->bf_mutator);
568 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
574 * Task to send a find peer message for our own peer identifier
575 * so that we can find the closest peers in the network to ourselves
576 * and attempt to connect to them.
578 * @param cls closure for this task
579 * @param tc the context under which the task is running
582 send_find_peer_message (void *cls,
583 const struct GNUNET_SCHEDULER_TaskContext *tc)
585 struct GNUNET_TIME_Relative next_send_time;
586 struct BloomConstructorContext bcc;
587 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
589 find_peer_task = NULL;
590 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
592 if (newly_found_peers > bucket_size)
594 /* If we are finding many peers already, no need to send out our request right now! */
596 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
597 &send_find_peer_message, NULL);
598 newly_found_peers = 0;
602 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
604 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
605 GNUNET_CONSTANTS_BLOOMFILTER_K);
606 GNUNET_CONTAINER_multipeermap_iterate (all_known_peers, &add_known_to_bloom,
608 GNUNET_STATISTICS_update (GDS_stats,
609 gettext_noop ("# FIND PEER messages initiated"), 1,
612 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
613 GNUNET_CONSTANTS_BLOOMFILTER_K);
614 // FIXME: pass priority!?
615 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
616 GNUNET_DHT_RO_FIND_PEER,
617 FIND_PEER_REPLICATION_LEVEL, 0,
618 &my_identity_hash, NULL, 0, bcc.bloom,
619 bcc.bf_mutator, peer_bf);
620 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
621 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
622 /* schedule next round */
623 next_send_time.rel_value_us =
624 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value_us +
625 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
626 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value_us /
627 (newly_found_peers + 1));
628 newly_found_peers = 0;
630 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
636 * Method called whenever a peer connects.
639 * @param peer peer identity this notification is about
642 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
644 struct PeerInfo *ret;
645 struct GNUNET_HashCode phash;
648 /* Check for connect to self message */
649 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
651 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
655 GNUNET_CONTAINER_multipeermap_contains (all_known_peers,
661 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), 1,
663 GNUNET_CRYPTO_hash (peer,
664 sizeof (struct GNUNET_PeerIdentity),
666 peer_bucket = find_bucket (&phash);
667 GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
668 ret = GNUNET_new (struct PeerInfo);
670 ret->latency = latency;
671 ret->distance = distance;
674 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
675 k_buckets[peer_bucket].tail, ret);
676 k_buckets[peer_bucket].peers_size++;
677 closest_bucket = GNUNET_MAX (closest_bucket, peer_bucket);
678 if ((peer_bucket > 0) && (k_buckets[peer_bucket].peers_size <= bucket_size))
680 ret->preference_task =
681 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
684 GNUNET_assert (GNUNET_OK ==
685 GNUNET_CONTAINER_multipeermap_put (all_known_peers,
687 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
688 if (1 == GNUNET_CONTAINER_multipeermap_size (all_known_peers) &&
689 (GNUNET_YES != disable_try_connect))
691 /* got a first connection, good time to start with FIND PEER requests... */
692 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
698 * Method called whenever a peer disconnects.
701 * @param peer peer identity this notification is about
704 handle_core_disconnect (void *cls,
705 const struct GNUNET_PeerIdentity *peer)
707 struct PeerInfo *to_remove;
709 struct P2PPendingMessage *pos;
710 unsigned int discarded;
711 struct GNUNET_HashCode phash;
713 /* Check for disconnect from self message */
714 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
716 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
720 GNUNET_CONTAINER_multipeermap_get (all_known_peers, peer);
721 if (NULL == to_remove)
726 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), -1,
728 GNUNET_assert (GNUNET_YES ==
729 GNUNET_CONTAINER_multipeermap_remove (all_known_peers,
732 if (NULL != to_remove->preference_task)
734 GNUNET_SCHEDULER_cancel (to_remove->preference_task);
735 to_remove->preference_task = NULL;
737 GNUNET_CRYPTO_hash (peer,
738 sizeof (struct GNUNET_PeerIdentity),
740 current_bucket = find_bucket (&phash);
741 GNUNET_assert (current_bucket >= 0);
742 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
743 k_buckets[current_bucket].tail, to_remove);
744 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
745 k_buckets[current_bucket].peers_size--;
746 while ((closest_bucket > 0) && (k_buckets[closest_bucket].peers_size == 0))
749 if (to_remove->th != NULL)
751 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
752 to_remove->th = NULL;
755 while (NULL != (pos = to_remove->head))
757 GNUNET_CONTAINER_DLL_remove (to_remove->head, to_remove->tail, pos);
761 GNUNET_STATISTICS_update (GDS_stats,
763 ("# Queued messages discarded (peer disconnected)"),
764 discarded, GNUNET_NO);
765 GNUNET_free (to_remove);
770 * Called when core is ready to send a message we asked for
771 * out to the destination.
773 * @param cls the 'struct PeerInfo' of the target peer
774 * @param size number of bytes available in buf
775 * @param buf where the callee should write the message
776 * @return number of bytes written to buf
779 core_transmit_notify (void *cls, size_t size, void *buf)
781 struct PeerInfo *peer = cls;
783 struct P2PPendingMessage *pending;
788 while ((NULL != (pending = peer->head)) &&
789 (0 == GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value_us))
791 GNUNET_STATISTICS_update (GDS_stats,
793 ("# Messages dropped (CORE timeout)"),
796 peer->pending_count--;
797 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
798 GNUNET_free (pending);
802 /* no messages pending */
808 GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
809 GNUNET_CORE_PRIO_BEST_EFFORT,
810 GNUNET_TIME_absolute_get_remaining
811 (pending->timeout), &peer->id,
812 ntohs (pending->msg->size),
813 &core_transmit_notify, peer);
814 GNUNET_break (NULL != peer->th);
818 while ((NULL != (pending = peer->head)) &&
819 (size - off >= (msize = ntohs (pending->msg->size))))
821 GNUNET_STATISTICS_update (GDS_stats,
823 ("# Bytes transmitted to other peers"), msize,
825 memcpy (&cbuf[off], pending->msg, msize);
827 peer->pending_count--;
828 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
829 GNUNET_free (pending);
831 if (peer->head != NULL)
834 GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
835 GNUNET_CORE_PRIO_BEST_EFFORT,
836 GNUNET_TIME_absolute_get_remaining
837 (pending->timeout), &peer->id, msize,
838 &core_transmit_notify, peer);
839 GNUNET_break (NULL != peer->th);
846 * Transmit all messages in the peer's message queue.
848 * @param peer message queue to process
851 process_peer_queue (struct PeerInfo *peer)
853 struct P2PPendingMessage *pending;
855 if (NULL == (pending = peer->head))
857 if (NULL != peer->th)
859 GNUNET_STATISTICS_update (GDS_stats,
861 ("# Bytes of bandwidth requested from core"),
862 ntohs (pending->msg->size), GNUNET_NO);
864 GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
865 GNUNET_CORE_PRIO_BEST_EFFORT,
866 GNUNET_TIME_absolute_get_remaining
867 (pending->timeout), &peer->id,
868 ntohs (pending->msg->size),
869 &core_transmit_notify, peer);
870 GNUNET_break (NULL != peer->th);
875 * To how many peers should we (on average) forward the request to
876 * obtain the desired target_replication count (on average).
878 * @param hop_count number of hops the message has traversed
879 * @param target_replication the number of total paths desired
880 * @return Some number of peers to forward the message to
883 get_forward_count (uint32_t hop_count, uint32_t target_replication)
885 uint32_t random_value;
886 uint32_t forward_count;
889 if (hop_count > GDS_NSE_get () * 4.0)
891 /* forcefully terminate */
892 GNUNET_STATISTICS_update (GDS_stats,
893 gettext_noop ("# requests TTL-dropped"),
897 if (hop_count > GDS_NSE_get () * 2.0)
899 /* Once we have reached our ideal number of hops, only forward to 1 peer */
902 /* bound by system-wide maximum */
904 GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
906 1 + (target_replication - 1.0) / (GDS_NSE_get () +
907 ((float) (target_replication - 1.0) *
909 /* Set forward count to floor of target_value */
910 forward_count = (uint32_t) target_value;
911 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
912 target_value = target_value - forward_count;
914 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
915 if (random_value < (target_value * UINT32_MAX))
917 return forward_count;
922 * Compute the distance between have and target as a 32-bit value.
923 * Differences in the lower bits must count stronger than differences
924 * in the higher bits.
928 * @return 0 if have==target, otherwise a number
929 * that is larger as the distance between
930 * the two hash codes increases
933 get_distance (const struct GNUNET_HashCode *target,
934 const struct GNUNET_HashCode *have)
941 /* We have to represent the distance between two 2^9 (=512)-bit
942 * numbers as a 2^5 (=32)-bit number with "0" being used for the
943 * two numbers being identical; furthermore, we need to
944 * guarantee that a difference in the number of matching
945 * bits is always represented in the result.
947 * We use 2^32/2^9 numerical values to distinguish between
948 * hash codes that have the same LSB bit distance and
949 * use the highest 2^9 bits of the result to signify the
950 * number of (mis)matching LSB bits; if we have 0 matching
951 * and hence 512 mismatching LSB bits we return -1 (since
952 * 512 itself cannot be represented with 9 bits) */
954 /* first, calculate the most significant 9 bits of our
955 * result, aka the number of LSBs */
956 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
957 /* bucket is now a value between 0 and 512 */
959 return 0; /* perfect match */
961 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
962 * below, we'd end up with max+1 (overflow)) */
964 /* calculate the most significant bits of the final result */
965 msb = (512 - bucket) << (32 - 9);
966 /* calculate the 32-9 least significant bits of the final result by
967 * looking at the differences in the 32-9 bits following the
968 * mismatching bit at 'bucket' */
971 (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
973 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
974 GNUNET_CRYPTO_hash_get_bit (have, i))
975 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
976 * last bit set will be 31 -- if
977 * i does not reach 512 first... */
984 * Check whether my identity is closer than any known peers. If a
985 * non-null bloomfilter is given, check if this is the closest peer
986 * that hasn't already been routed to.
988 * @param key hash code to check closeness to
989 * @param bloom bloomfilter, exclude these entries from the decision
990 * @return #GNUNET_YES if node location is closest,
991 * #GNUNET_NO otherwise.
994 am_closest_peer (const struct GNUNET_HashCode *key,
995 const struct GNUNET_CONTAINER_BloomFilter *bloom)
1001 struct PeerInfo *pos;
1002 struct GNUNET_HashCode phash;
1004 if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1006 bucket_num = find_bucket (key);
1007 GNUNET_assert (bucket_num >= 0);
1008 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, key);
1009 pos = k_buckets[bucket_num].head;
1011 while ((pos != NULL) && (count < bucket_size))
1013 GNUNET_CRYPTO_hash (&pos->id,
1014 sizeof (struct GNUNET_PeerIdentity),
1016 if ((bloom != NULL) &&
1018 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1021 continue; /* Skip already checked entries */
1023 other_bits = GNUNET_CRYPTO_hash_matching_bits (&phash, key);
1024 if (other_bits > bits)
1026 if (other_bits == bits) /* We match the same number of bits */
1030 /* No peers closer, we are the closest! */
1036 * Select a peer from the routing table that would be a good routing
1037 * destination for sending a message for "key". The resulting peer
1038 * must not be in the set of blocked peers.<p>
1040 * Note that we should not ALWAYS select the closest peer to the
1041 * target, peers further away from the target should be chosen with
1042 * exponentially declining probability.
1044 * FIXME: double-check that this is fine
1047 * @param key the key we are selecting a peer to route to
1048 * @param bloom a bloomfilter containing entries this request has seen already
1049 * @param hops how many hops has this message traversed thus far
1050 * @return Peer to route to, or NULL on error
1052 static struct PeerInfo *
1053 select_peer (const struct GNUNET_HashCode * key,
1054 const struct GNUNET_CONTAINER_BloomFilter *bloom, uint32_t hops)
1058 unsigned int selected;
1059 struct PeerInfo *pos;
1061 unsigned int smallest_distance;
1062 struct PeerInfo *chosen;
1063 struct GNUNET_HashCode phash;
1065 if (hops >= GDS_NSE_get ())
1067 /* greedy selection (closest peer that is not in bloomfilter) */
1068 smallest_distance = UINT_MAX;
1070 for (bc = 0; bc <= closest_bucket; bc++)
1072 pos = k_buckets[bc].head;
1074 while ((pos != NULL) && (count < bucket_size))
1076 GNUNET_CRYPTO_hash (&pos->id,
1077 sizeof (struct GNUNET_PeerIdentity),
1079 if ((bloom == NULL) ||
1081 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1083 dist = get_distance (key, &phash);
1084 if (dist < smallest_distance)
1087 smallest_distance = dist;
1092 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1093 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1094 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1095 GNUNET_STATISTICS_update (GDS_stats,
1097 ("# Peers excluded from routing due to Bloomfilter"),
1099 dist = get_distance (key, &phash);
1100 if (dist < smallest_distance)
1103 smallest_distance = dist;
1111 GNUNET_STATISTICS_update (GDS_stats,
1112 gettext_noop ("# Peer selection failed"), 1,
1117 /* select "random" peer */
1118 /* count number of peers that are available and not filtered */
1120 for (bc = 0; bc <= closest_bucket; bc++)
1122 pos = k_buckets[bc].head;
1123 while ((pos != NULL) && (count < bucket_size))
1125 GNUNET_CRYPTO_hash (&pos->id,
1126 sizeof (struct GNUNET_PeerIdentity),
1128 if ((bloom != NULL) &&
1130 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1132 GNUNET_STATISTICS_update (GDS_stats,
1134 ("# Peers excluded from routing due to Bloomfilter"),
1136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1137 "Excluded peer `%s' due to BF match in random routing for %s\n",
1138 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1140 continue; /* Ignore bloomfiltered peers */
1146 if (0 == count) /* No peers to select from! */
1148 GNUNET_STATISTICS_update (GDS_stats,
1149 gettext_noop ("# Peer selection failed"), 1,
1153 /* Now actually choose a peer */
1154 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1156 for (bc = 0; bc <= closest_bucket; bc++)
1158 for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next)
1160 GNUNET_CRYPTO_hash (&pos->id,
1161 sizeof (struct GNUNET_PeerIdentity),
1163 if ((bloom != NULL) &&
1165 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1167 continue; /* Ignore bloomfiltered peers */
1169 if (0 == selected--)
1179 * Compute the set of peers that the given request should be
1182 * @param key routing key
1183 * @param bloom bloom filter excluding peers as targets, all selected
1184 * peers will be added to the bloom filter
1185 * @param hop_count number of hops the request has traversed so far
1186 * @param target_replication desired number of replicas
1187 * @param targets where to store an array of target peers (to be
1188 * free'd by the caller)
1189 * @return number of peers returned in 'targets'.
1192 get_target_peers (const struct GNUNET_HashCode *key,
1193 struct GNUNET_CONTAINER_BloomFilter *bloom,
1194 uint32_t hop_count, uint32_t target_replication,
1195 struct PeerInfo ***targets)
1199 struct PeerInfo **rtargets;
1200 struct PeerInfo *nxt;
1201 struct GNUNET_HashCode nhash;
1203 GNUNET_assert (NULL != bloom);
1204 ret = get_forward_count (hop_count, target_replication);
1210 rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1211 for (off = 0; off < ret; off++)
1213 nxt = select_peer (key, bloom, hop_count);
1216 rtargets[off] = nxt;
1217 GNUNET_CRYPTO_hash (&nxt->id,
1218 sizeof (struct GNUNET_PeerIdentity),
1220 GNUNET_break (GNUNET_NO ==
1221 GNUNET_CONTAINER_bloomfilter_test (bloom,
1223 GNUNET_CONTAINER_bloomfilter_add (bloom, &nhash);
1225 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1226 "Selected %u/%u peers at hop %u for %s (target was %u)\n", off,
1227 GNUNET_CONTAINER_multipeermap_size (all_known_peers),
1228 (unsigned int) hop_count, GNUNET_h2s (key), ret);
1231 GNUNET_free (rtargets);
1235 *targets = rtargets;
1236 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1237 "Forwarding query `%s' to %u peers (goal was %u peers)\n",
1246 * Perform a PUT operation. Forwards the given request to other
1247 * peers. Does not store the data locally. Does not give the
1248 * data to local clients. May do nothing if this is the only
1249 * peer in the network (or if we are the closest peer in the
1252 * @param type type of the block
1253 * @param options routing options
1254 * @param desired_replication_level desired replication count
1255 * @param expiration_time when does the content expire
1256 * @param hop_count how many hops has this message traversed so far
1257 * @param bf Bloom filter of peers this PUT has already traversed
1258 * @param key key for the content
1259 * @param put_path_length number of entries in @a put_path
1260 * @param put_path peers this request has traversed so far (if tracked)
1261 * @param data payload to store
1262 * @param data_size number of bytes in @a data
1263 * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1266 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1267 enum GNUNET_DHT_RouteOption options,
1268 uint32_t desired_replication_level,
1269 struct GNUNET_TIME_Absolute expiration_time,
1271 struct GNUNET_CONTAINER_BloomFilter *bf,
1272 const struct GNUNET_HashCode *key,
1273 unsigned int put_path_length,
1274 struct GNUNET_PeerIdentity *put_path,
1275 const void *data, size_t data_size)
1277 unsigned int target_count;
1279 struct PeerInfo **targets;
1280 struct PeerInfo *target;
1281 struct P2PPendingMessage *pending;
1283 struct PeerPutMessage *ppm;
1284 struct GNUNET_PeerIdentity *pp;
1285 struct GNUNET_HashCode thash;
1286 unsigned int skip_count;
1288 GNUNET_assert (NULL != bf);
1289 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1290 "Adding myself (%s) to PUT bloomfilter for %s\n",
1291 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1292 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity_hash);
1293 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1296 get_target_peers (key, bf, hop_count, desired_replication_level,
1298 if (0 == target_count)
1300 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1301 "Routing PUT for %s terminates after %u hops at %s\n",
1302 GNUNET_h2s (key), (unsigned int) hop_count,
1303 GNUNET_i2s (&my_identity));
1307 put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1308 sizeof (struct PeerPutMessage);
1309 if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1311 put_path_length = 0;
1312 msize = data_size + sizeof (struct PeerPutMessage);
1314 if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1317 GNUNET_free (targets);
1320 GNUNET_STATISTICS_update (GDS_stats,
1322 ("# PUT messages queued for transmission"),
1323 target_count, GNUNET_NO);
1325 for (i = 0; i < target_count; i++)
1327 target = targets[i];
1328 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1331 GNUNET_STATISTICS_update (GDS_stats,
1332 gettext_noop ("# P2P messages dropped due to full queue"),
1337 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1338 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1339 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1340 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1341 pending->importance = 0; /* FIXME */
1342 pending->timeout = expiration_time;
1343 ppm = (struct PeerPutMessage *) &pending[1];
1344 pending->msg = &ppm->header;
1345 ppm->header.size = htons (msize);
1346 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1347 ppm->options = htonl (options);
1348 ppm->type = htonl (type);
1349 ppm->hop_count = htonl (hop_count + 1);
1350 ppm->desired_replication_level = htonl (desired_replication_level);
1351 ppm->put_path_length = htonl (put_path_length);
1352 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1353 GNUNET_CRYPTO_hash (&target->id,
1354 sizeof (struct GNUNET_PeerIdentity),
1356 GNUNET_break (GNUNET_YES ==
1357 GNUNET_CONTAINER_bloomfilter_test (bf,
1359 GNUNET_assert (GNUNET_OK ==
1360 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1364 pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1365 memcpy (pp, put_path,
1366 sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1367 memcpy (&pp[put_path_length], data, data_size);
1368 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1369 target->pending_count++;
1370 process_peer_queue (target);
1372 GNUNET_free (targets);
1373 return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1378 * Perform a GET operation. Forwards the given request to other
1379 * peers. Does not lookup the key locally. May do nothing if this is
1380 * the only peer in the network (or if we are the closest peer in the
1383 * @param type type of the block
1384 * @param options routing options
1385 * @param desired_replication_level desired replication count
1386 * @param hop_count how many hops did this request traverse so far?
1387 * @param key key for the content
1388 * @param xquery extended query
1389 * @param xquery_size number of bytes in @a xquery
1390 * @param reply_bf bloomfilter to filter duplicates
1391 * @param reply_bf_mutator mutator for @a reply_bf
1392 * @param peer_bf filter for peers not to select (again)
1393 * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1396 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1397 enum GNUNET_DHT_RouteOption options,
1398 uint32_t desired_replication_level,
1399 uint32_t hop_count, const struct GNUNET_HashCode * key,
1400 const void *xquery, size_t xquery_size,
1401 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1402 uint32_t reply_bf_mutator,
1403 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1405 unsigned int target_count;
1407 struct PeerInfo **targets;
1408 struct PeerInfo *target;
1409 struct P2PPendingMessage *pending;
1411 struct PeerGetMessage *pgm;
1413 size_t reply_bf_size;
1414 struct GNUNET_HashCode thash;
1415 unsigned int skip_count;
1417 GNUNET_assert (NULL != peer_bf);
1418 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1421 get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1423 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1424 "Adding myself (%s) to GET bloomfilter for %s\n",
1425 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1426 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity_hash);
1427 if (0 == target_count)
1429 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1430 "Routing GET for %s terminates after %u hops at %s\n",
1431 GNUNET_h2s (key), (unsigned int) hop_count,
1432 GNUNET_i2s (&my_identity));
1435 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1436 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1437 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1440 GNUNET_free (targets);
1443 GNUNET_STATISTICS_update (GDS_stats,
1445 ("# GET messages queued for transmission"),
1446 target_count, GNUNET_NO);
1447 /* forward request */
1449 for (i = 0; i < target_count; i++)
1451 target = targets[i];
1452 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1455 GNUNET_STATISTICS_update (GDS_stats,
1456 gettext_noop ("# P2P messages dropped due to full queue"),
1461 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1462 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1463 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1464 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1465 pending->importance = 0; /* FIXME */
1466 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1467 pgm = (struct PeerGetMessage *) &pending[1];
1468 pending->msg = &pgm->header;
1469 pgm->header.size = htons (msize);
1470 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1471 pgm->options = htonl (options);
1472 pgm->type = htonl (type);
1473 pgm->hop_count = htonl (hop_count + 1);
1474 pgm->desired_replication_level = htonl (desired_replication_level);
1475 pgm->xquery_size = htonl (xquery_size);
1476 pgm->bf_mutator = reply_bf_mutator;
1477 GNUNET_CRYPTO_hash (&target->id,
1478 sizeof (struct GNUNET_PeerIdentity),
1480 GNUNET_break (GNUNET_YES ==
1481 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1483 GNUNET_assert (GNUNET_OK ==
1484 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1488 xq = (char *) &pgm[1];
1489 memcpy (xq, xquery, xquery_size);
1490 if (NULL != reply_bf)
1491 GNUNET_assert (GNUNET_OK ==
1492 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1496 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1497 target->pending_count++;
1498 process_peer_queue (target);
1500 GNUNET_free (targets);
1501 return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1506 * Handle a reply (route to origin). Only forwards the reply back to
1507 * the given peer. Does not do local caching or forwarding to local
1510 * @param target neighbour that should receive the block (if still connected)
1511 * @param type type of the block
1512 * @param expiration_time when does the content expire
1513 * @param key key for the content
1514 * @param put_path_length number of entries in @a put_path
1515 * @param put_path peers the original PUT traversed (if tracked)
1516 * @param get_path_length number of entries in @a get_path
1517 * @param get_path peers this reply has traversed so far (if tracked)
1518 * @param data payload of the reply
1519 * @param data_size number of bytes in @a data
1522 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1523 enum GNUNET_BLOCK_Type type,
1524 struct GNUNET_TIME_Absolute expiration_time,
1525 const struct GNUNET_HashCode * key,
1526 unsigned int put_path_length,
1527 const struct GNUNET_PeerIdentity *put_path,
1528 unsigned int get_path_length,
1529 const struct GNUNET_PeerIdentity *get_path,
1530 const void *data, size_t data_size)
1532 struct PeerInfo *pi;
1533 struct P2PPendingMessage *pending;
1535 struct PeerResultMessage *prm;
1536 struct GNUNET_PeerIdentity *paths;
1539 data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1541 sizeof (struct GNUNET_PeerIdentity);
1542 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1544 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1546 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1547 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1552 pi = GNUNET_CONTAINER_multipeermap_get (all_known_peers, target);
1555 /* peer disconnected in the meantime, drop reply */
1558 if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1561 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1566 GNUNET_STATISTICS_update (GDS_stats,
1568 ("# RESULT messages queued for transmission"), 1,
1570 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1571 pending->importance = 0; /* FIXME */
1572 pending->timeout = expiration_time;
1573 prm = (struct PeerResultMessage *) &pending[1];
1574 pending->msg = &prm->header;
1575 prm->header.size = htons (msize);
1576 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1577 prm->type = htonl (type);
1578 prm->put_path_length = htonl (put_path_length);
1579 prm->get_path_length = htonl (get_path_length);
1580 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1582 paths = (struct GNUNET_PeerIdentity *) &prm[1];
1583 memcpy (paths, put_path,
1584 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1585 memcpy (&paths[put_path_length], get_path,
1586 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1587 memcpy (&paths[put_path_length + get_path_length], data, data_size);
1588 GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1589 pi->pending_count++;
1590 process_peer_queue (pi);
1595 * To be called on core init/fail.
1597 * @param cls service closure
1598 * @param identity the public identity of this peer
1601 core_init (void *cls,
1602 const struct GNUNET_PeerIdentity *identity)
1604 my_identity = *identity;
1605 GNUNET_CRYPTO_hash (identity,
1606 sizeof (struct GNUNET_PeerIdentity),
1612 * Core handler for p2p put requests.
1614 * @param cls closure
1615 * @param peer sender of the request
1616 * @param message message
1617 * @param peer peer identity this notification is about
1618 * @return #GNUNET_OK to keep the connection open,
1619 * #GNUNET_SYSERR to close it (signal serious error)
1622 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1623 const struct GNUNET_MessageHeader *message)
1625 const struct PeerPutMessage *put;
1626 const struct GNUNET_PeerIdentity *put_path;
1627 const void *payload;
1630 size_t payload_size;
1631 enum GNUNET_DHT_RouteOption options;
1632 struct GNUNET_CONTAINER_BloomFilter *bf;
1633 struct GNUNET_HashCode test_key;
1634 struct GNUNET_HashCode phash;
1637 msize = ntohs (message->size);
1638 if (msize < sizeof (struct PeerPutMessage))
1640 GNUNET_break_op (0);
1643 put = (const struct PeerPutMessage *) message;
1644 putlen = ntohl (put->put_path_length);
1646 sizeof (struct PeerPutMessage) +
1647 putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1649 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1651 GNUNET_break_op (0);
1654 GNUNET_STATISTICS_update (GDS_stats,
1655 gettext_noop ("# P2P PUT requests received"), 1,
1657 GNUNET_STATISTICS_update (GDS_stats,
1658 gettext_noop ("# P2P PUT bytes received"), msize,
1660 put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1661 payload = &put_path[putlen];
1662 options = ntohl (put->options);
1664 msize - (sizeof (struct PeerPutMessage) +
1665 putlen * sizeof (struct GNUNET_PeerIdentity));
1667 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1668 GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1669 GNUNET_CRYPTO_hash (peer, sizeof (struct GNUNET_PeerIdentity), &phash);
1670 if (GNUNET_YES == log_route_details_stderr)
1674 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1675 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1676 "R5N PUT %s: %s->%s (%u, %u=>%u)\n",
1677 GNUNET_h2s (&put->key), GNUNET_i2s (peer), tmp,
1678 ntohl(put->hop_count),
1679 GNUNET_CRYPTO_hash_matching_bits (&phash, &put->key),
1680 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &put->key)
1684 switch (GNUNET_BLOCK_get_key
1685 (GDS_block_context, ntohl (put->type), payload, payload_size,
1689 if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1691 char *put_s = GNUNET_strdup (GNUNET_h2s_full (&put->key));
1692 GNUNET_break_op (0);
1693 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1694 "PUT with key `%s' for block with key %s\n",
1695 put_s, GNUNET_h2s_full (&test_key));
1696 GNUNET_free (put_s);
1701 GNUNET_break_op (0);
1704 /* cannot verify, good luck */
1707 if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
1709 switch (GNUNET_BLOCK_evaluate (GDS_block_context,
1712 NULL, 0, /* bloom filer */
1713 NULL, 0, /* xquery */
1714 payload, payload_size))
1716 case GNUNET_BLOCK_EVALUATION_OK_MORE:
1717 case GNUNET_BLOCK_EVALUATION_OK_LAST:
1720 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1721 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1722 case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1723 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1724 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1725 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1727 GNUNET_break_op (0);
1732 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1733 GNUNET_CONSTANTS_BLOOMFILTER_K);
1734 GNUNET_break_op (GNUNET_YES ==
1735 GNUNET_CONTAINER_bloomfilter_test (bf, &phash));
1737 struct GNUNET_PeerIdentity pp[putlen + 1];
1739 /* extend 'put path' by sender */
1740 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1742 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1749 /* give to local clients */
1750 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1751 &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1752 payload_size, payload);
1754 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1755 (am_closest_peer (&put->key, bf)))
1756 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1757 (put->expiration_time), &put->key, putlen, pp,
1758 ntohl (put->type), payload_size, payload);
1759 /* route to other peers */
1760 forwarded = GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1761 ntohl (put->desired_replication_level),
1762 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1763 ntohl (put->hop_count), bf,
1765 pp, payload, payload_size);
1766 /* notify monitoring clients */
1767 GDS_CLIENTS_process_put (options
1768 | (GNUNET_OK == forwarded)
1769 ? GNUNET_DHT_RO_LAST_HOP : 0,
1771 ntohl (put->hop_count),
1772 ntohl (put->desired_replication_level),
1774 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1779 GNUNET_CONTAINER_bloomfilter_free (bf);
1785 * We have received a FIND PEER request. Send matching
1788 * @param sender sender of the FIND PEER request
1789 * @param key peers close to this key are desired
1790 * @param bf peers matching this bf are excluded
1791 * @param bf_mutator mutator for bf
1794 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1795 const struct GNUNET_HashCode * key,
1796 struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1799 struct PeerBucket *bucket;
1800 struct PeerInfo *peer;
1801 unsigned int choice;
1802 struct GNUNET_HashCode phash;
1803 struct GNUNET_HashCode mhash;
1804 const struct GNUNET_HELLO_Message *hello;
1806 /* first, check about our own HELLO */
1807 if (NULL != GDS_my_hello)
1809 GNUNET_BLOCK_mingle_hash (&my_identity_hash, bf_mutator, &mhash);
1811 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1813 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1814 GNUNET_TIME_relative_to_absolute
1816 key, 0, NULL, 0, NULL, GDS_my_hello,
1817 GNUNET_HELLO_size ((const struct
1818 GNUNET_HELLO_Message *)
1823 GNUNET_STATISTICS_update (GDS_stats,
1825 ("# FIND PEER requests ignored due to Bloomfilter"),
1831 GNUNET_STATISTICS_update (GDS_stats,
1833 ("# FIND PEER requests ignored due to lack of HELLO"),
1837 /* then, also consider sending a random HELLO from the closest bucket */
1838 if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1839 bucket_idx = closest_bucket;
1841 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1842 if (bucket_idx == GNUNET_SYSERR)
1844 bucket = &k_buckets[bucket_idx];
1845 if (bucket->peers_size == 0)
1848 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1849 peer = bucket->head;
1852 GNUNET_assert (NULL != peer);
1856 choice = bucket->peers_size;
1861 return; /* no non-masked peer available */
1863 peer = bucket->head;
1864 GNUNET_CRYPTO_hash (&peer->id, sizeof (struct GNUNET_PeerIdentity), &phash);
1865 GNUNET_BLOCK_mingle_hash (&phash, bf_mutator, &mhash);
1866 hello = GDS_HELLO_get (&peer->id);
1868 while ((hello == NULL) ||
1869 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1870 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1871 GNUNET_TIME_relative_to_absolute
1872 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1873 0, NULL, 0, NULL, hello,
1874 GNUNET_HELLO_size (hello));
1879 * Core handler for p2p get requests.
1881 * @param cls closure
1882 * @param peer sender of the request
1883 * @param message message
1884 * @return #GNUNET_OK to keep the connection open,
1885 * #GNUNET_SYSERR to close it (signal serious error)
1888 handle_dht_p2p_get (void *cls,
1889 const struct GNUNET_PeerIdentity *peer,
1890 const struct GNUNET_MessageHeader *message)
1892 struct PeerGetMessage *get;
1893 uint32_t xquery_size;
1894 size_t reply_bf_size;
1896 enum GNUNET_BLOCK_Type type;
1897 enum GNUNET_DHT_RouteOption options;
1898 enum GNUNET_BLOCK_EvaluationResult eval;
1899 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1900 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1902 struct GNUNET_HashCode phash;
1906 memcmp (peer, &my_identity,
1907 sizeof (struct GNUNET_PeerIdentity)));
1908 /* parse and validate message */
1909 msize = ntohs (message->size);
1910 if (msize < sizeof (struct PeerGetMessage))
1912 GNUNET_break_op (0);
1915 get = (struct PeerGetMessage *) message;
1916 xquery_size = ntohl (get->xquery_size);
1917 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1919 GNUNET_break_op (0);
1922 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1923 type = ntohl (get->type);
1924 options = ntohl (get->options);
1925 xquery = (const char *) &get[1];
1927 GNUNET_STATISTICS_update (GDS_stats,
1928 gettext_noop ("# P2P GET requests received"), 1,
1930 GNUNET_STATISTICS_update (GDS_stats,
1931 gettext_noop ("# P2P GET bytes received"), msize,
1933 GNUNET_CRYPTO_hash (peer,
1934 sizeof (struct GNUNET_PeerIdentity),
1936 if (GNUNET_YES == log_route_details_stderr)
1940 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1941 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1942 "R5N GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n",
1943 GNUNET_h2s (&get->key), GNUNET_i2s (peer), tmp,
1944 ntohl(get->hop_count),
1945 GNUNET_CRYPTO_hash_matching_bits (&phash, &get->key),
1946 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &get->key),
1947 ntohl(get->xquery_size), xquery);
1951 if (reply_bf_size > 0)
1953 GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1954 GNUNET_CONSTANTS_BLOOMFILTER_K);
1956 GNUNET_BLOCK_evaluate (GDS_block_context, type, &get->key, &reply_bf,
1957 get->bf_mutator, xquery, xquery_size, NULL, 0);
1958 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1960 /* request invalid or block type not supported */
1961 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1962 if (NULL != reply_bf)
1963 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1967 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1968 GNUNET_CONSTANTS_BLOOMFILTER_K);
1969 GNUNET_break_op (GNUNET_YES ==
1970 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1972 /* remember request for routing replies */
1973 GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1974 reply_bf, get->bf_mutator);
1975 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1976 "GET for %s at %s after %u hops\n",
1977 GNUNET_h2s (&get->key),
1978 GNUNET_i2s (&my_identity),
1979 (unsigned int) ntohl (get->hop_count));
1980 /* local lookup (this may update the reply_bf) */
1981 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1982 (am_closest_peer (&get->key, peer_bf)))
1984 if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1986 GNUNET_STATISTICS_update (GDS_stats,
1988 ("# P2P FIND PEER requests processed"), 1,
1990 handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
1995 GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
1996 &reply_bf, get->bf_mutator);
2001 GNUNET_STATISTICS_update (GDS_stats,
2002 gettext_noop ("# P2P GET requests ONLY routed"),
2006 /* P2P forwarding */
2007 forwarded = GNUNET_NO;
2008 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
2009 forwarded = GDS_NEIGHBOURS_handle_get (type, options,
2010 ntohl (get->desired_replication_level),
2011 ntohl (get->hop_count),
2016 get->bf_mutator, peer_bf);
2017 GDS_CLIENTS_process_get (options
2018 | (GNUNET_OK == forwarded)
2019 ? GNUNET_DHT_RO_LAST_HOP : 0,
2021 ntohl (get->hop_count),
2022 ntohl (get->desired_replication_level),
2028 if (NULL != reply_bf)
2029 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
2030 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
2036 * Core handler for p2p result messages.
2038 * @param cls closure
2039 * @param message message
2040 * @param peer peer identity this notification is about
2041 * @return #GNUNET_YES (do not cut p2p connection)
2044 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
2045 const struct GNUNET_MessageHeader *message)
2047 const struct PeerResultMessage *prm;
2048 const struct GNUNET_PeerIdentity *put_path;
2049 const struct GNUNET_PeerIdentity *get_path;
2051 uint32_t get_path_length;
2052 uint32_t put_path_length;
2055 enum GNUNET_BLOCK_Type type;
2057 /* parse and validate message */
2058 msize = ntohs (message->size);
2059 if (msize < sizeof (struct PeerResultMessage))
2061 GNUNET_break_op (0);
2064 prm = (struct PeerResultMessage *) message;
2065 put_path_length = ntohl (prm->put_path_length);
2066 get_path_length = ntohl (prm->get_path_length);
2068 sizeof (struct PeerResultMessage) + (get_path_length +
2070 sizeof (struct GNUNET_PeerIdentity)) ||
2072 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
2074 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
2076 GNUNET_break_op (0);
2079 put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
2080 get_path = &put_path[put_path_length];
2081 type = ntohl (prm->type);
2082 data = (const void *) &get_path[get_path_length];
2084 msize - (sizeof (struct PeerResultMessage) +
2086 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
2087 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
2089 GNUNET_STATISTICS_update (GDS_stats,
2090 gettext_noop ("# P2P RESULT bytes received"),
2092 if (GNUNET_YES == log_route_details_stderr)
2096 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
2097 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, "R5N RESULT %s: %s->%s (%u)\n",
2098 GNUNET_h2s (&prm->key), GNUNET_i2s (peer), tmp,
2099 get_path_length + 1);
2102 /* if we got a HELLO, consider it for our own routing table */
2103 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
2105 const struct GNUNET_MessageHeader *h;
2106 struct GNUNET_PeerIdentity pid;
2109 /* Should be a HELLO, validate and consider using it! */
2110 if (data_size < sizeof (struct GNUNET_MessageHeader))
2112 GNUNET_break_op (0);
2116 if (data_size != ntohs (h->size))
2118 GNUNET_break_op (0);
2122 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
2124 GNUNET_break_op (0);
2127 if ((GNUNET_YES != disable_try_connect) &&
2128 0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
2130 struct GNUNET_HashCode pid_hash;
2132 GNUNET_CRYPTO_hash (&pid, sizeof (struct GNUNET_PeerIdentity), &pid_hash);
2133 bucket = find_bucket (&pid_hash);
2134 if ((bucket >= 0) &&
2135 (k_buckets[bucket].peers_size < bucket_size) &&
2136 (NULL != GDS_transport_handle))
2138 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
2139 GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid, NULL, NULL); /*FIXME TRY_CONNECT change */
2144 /* append 'peer' to 'get_path' */
2146 struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
2148 memcpy (xget_path, get_path,
2149 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2150 xget_path[get_path_length] = *peer;
2153 /* forward to local clients */
2154 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2155 &prm->key, get_path_length, xget_path,
2156 put_path_length, put_path, type, data_size, data);
2157 GDS_CLIENTS_process_get_resp (type,
2158 xget_path, get_path_length,
2159 put_path, put_path_length,
2160 GNUNET_TIME_absolute_ntoh (
2161 prm->expiration_time),
2165 if (GNUNET_YES == cache_results)
2167 struct GNUNET_PeerIdentity xput_path[get_path_length + 1 + put_path_length];
2169 memcpy (xput_path, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
2170 memcpy (&xput_path[put_path_length],
2172 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2174 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2176 get_path_length + put_path_length, xput_path,
2177 type, data_size, data);
2179 /* forward to other peers */
2180 GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2181 &prm->key, put_path_length, put_path, get_path_length,
2182 xget_path, data, data_size);
2190 * Initialize neighbours subsystem.
2192 * @return GNUNET_OK on success, GNUNET_SYSERR on error
2195 GDS_NEIGHBOURS_init ()
2197 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2198 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2199 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2200 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2203 unsigned long long temp_config_num;
2206 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2208 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2210 bucket_size = (unsigned int) temp_config_num;
2212 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "CACHE_RESULTS");
2214 log_route_details_stderr =
2215 (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO;
2216 atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2218 GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
2219 &handle_core_disconnect, NULL, GNUNET_NO, NULL,
2220 GNUNET_NO, core_handlers);
2221 if (core_api == NULL)
2222 return GNUNET_SYSERR;
2223 all_known_peers = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
2229 * Shutdown neighbours subsystem.
2232 GDS_NEIGHBOURS_done ()
2234 if (NULL == core_api)
2236 GNUNET_CORE_disconnect (core_api);
2238 GNUNET_ATS_performance_done (atsAPI);
2240 GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (all_known_peers));
2241 GNUNET_CONTAINER_multipeermap_destroy (all_known_peers);
2242 all_known_peers = NULL;
2243 if (NULL != find_peer_task)
2245 GNUNET_SCHEDULER_cancel (find_peer_task);
2246 find_peer_task = NULL;
2251 * Get the ID of the local node.
2253 * @return identity of the local node
2255 struct GNUNET_PeerIdentity *
2256 GDS_NEIGHBOURS_get_id ()
2258 return &my_identity;
2262 /* end of gnunet-service-dht_neighbours.c */