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_MultiPeerMap *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;
434 * Hash of the identity of this peer.
436 static struct GNUNET_HashCode my_identity_hash;
441 static struct GNUNET_CORE_Handle *core_api;
446 static struct GNUNET_ATS_PerformanceHandle *atsAPI;
451 * Find the optimal bucket for this key.
453 * @param hc the hashcode to compare our identity to
454 * @return the proper bucket index, or GNUNET_SYSERR
455 * on error (same hashcode)
458 find_bucket (const struct GNUNET_HashCode *hc)
462 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, hc);
463 if (bits == MAX_BUCKETS)
465 /* How can all bits match? Got my own ID? */
467 return GNUNET_SYSERR;
469 return MAX_BUCKETS - bits - 1;
474 * Let GNUnet core know that we like the given peer.
476 * @param cls the `struct PeerInfo` of the peer
477 * @param tc scheduler context.
480 update_core_preference (void *cls,
481 const struct GNUNET_SCHEDULER_TaskContext *tc)
483 struct PeerInfo *peer = cls;
485 unsigned int matching;
487 struct GNUNET_HashCode phash;
489 peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
490 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
492 GNUNET_CRYPTO_hash (&peer->id,
493 sizeof (struct GNUNET_PeerIdentity),
496 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash,
500 bucket = find_bucket (&phash);
501 if (bucket == GNUNET_SYSERR)
505 GNUNET_assert (k_buckets[bucket].peers_size != 0);
506 preference = (1LL << matching) / k_buckets[bucket].peers_size;
510 peer->preference_task =
511 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
512 &update_core_preference, peer);
515 GNUNET_STATISTICS_update (GDS_stats,
516 gettext_noop ("# Preference updates given to core"),
518 GNUNET_ATS_performance_change_preference (atsAPI, &peer->id,
519 GNUNET_ATS_PREFERENCE_BANDWIDTH,
520 (double) preference, GNUNET_ATS_PREFERENCE_END);
521 peer->preference_task =
522 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
523 &update_core_preference, peer);
530 * Closure for 'add_known_to_bloom'.
532 struct BloomConstructorContext
535 * Bloom filter under construction.
537 struct GNUNET_CONTAINER_BloomFilter *bloom;
547 * Add each of the peers we already know to the bloom filter of
548 * the request so that we don't get duplicate HELLOs.
550 * @param cls the 'struct BloomConstructorContext'.
551 * @param key peer identity to add to the bloom filter
552 * @param value value the peer information (unused)
553 * @return #GNUNET_YES (we should continue to iterate)
556 add_known_to_bloom (void *cls,
557 const struct GNUNET_PeerIdentity *key,
560 struct BloomConstructorContext *ctx = cls;
561 struct GNUNET_HashCode key_hash;
562 struct GNUNET_HashCode mh;
564 GNUNET_CRYPTO_hash (key, sizeof (struct GNUNET_PeerIdentity), &key_hash);
565 GNUNET_BLOCK_mingle_hash (&key_hash, ctx->bf_mutator, &mh);
566 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
567 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
568 GNUNET_i2s (key), ctx->bf_mutator);
569 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
575 * Task to send a find peer message for our own peer identifier
576 * so that we can find the closest peers in the network to ourselves
577 * and attempt to connect to them.
579 * @param cls closure for this task
580 * @param tc the context under which the task is running
583 send_find_peer_message (void *cls,
584 const struct GNUNET_SCHEDULER_TaskContext *tc)
586 struct GNUNET_TIME_Relative next_send_time;
587 struct BloomConstructorContext bcc;
588 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
590 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
591 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
593 if (newly_found_peers > bucket_size)
595 /* If we are finding many peers already, no need to send out our request right now! */
597 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
598 &send_find_peer_message, NULL);
599 newly_found_peers = 0;
603 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
605 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
606 GNUNET_CONSTANTS_BLOOMFILTER_K);
607 GNUNET_CONTAINER_multipeermap_iterate (all_known_peers, &add_known_to_bloom,
609 GNUNET_STATISTICS_update (GDS_stats,
610 gettext_noop ("# FIND PEER messages initiated"), 1,
613 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
614 GNUNET_CONSTANTS_BLOOMFILTER_K);
615 // FIXME: pass priority!?
616 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
617 GNUNET_DHT_RO_FIND_PEER,
618 FIND_PEER_REPLICATION_LEVEL, 0,
619 &my_identity_hash, NULL, 0, bcc.bloom,
620 bcc.bf_mutator, peer_bf);
621 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
622 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
623 /* schedule next round */
624 next_send_time.rel_value_us =
625 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value_us +
626 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
627 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value_us /
628 (newly_found_peers + 1));
629 newly_found_peers = 0;
631 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
637 * Method called whenever a peer connects.
640 * @param peer peer identity this notification is about
643 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
645 struct PeerInfo *ret;
646 struct GNUNET_HashCode phash;
649 /* Check for connect to self message */
650 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
652 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
656 GNUNET_CONTAINER_multipeermap_contains (all_known_peers,
662 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), 1,
664 GNUNET_CRYPTO_hash (peer,
665 sizeof (struct GNUNET_PeerIdentity),
667 peer_bucket = find_bucket (&phash);
668 GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
669 ret = GNUNET_new (struct PeerInfo);
671 ret->latency = latency;
672 ret->distance = distance;
675 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
676 k_buckets[peer_bucket].tail, ret);
677 k_buckets[peer_bucket].peers_size++;
678 closest_bucket = GNUNET_MAX (closest_bucket, peer_bucket);
679 if ((peer_bucket > 0) && (k_buckets[peer_bucket].peers_size <= bucket_size))
681 ret->preference_task =
682 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
685 GNUNET_assert (GNUNET_OK ==
686 GNUNET_CONTAINER_multipeermap_put (all_known_peers,
688 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
689 if (1 == GNUNET_CONTAINER_multipeermap_size (all_known_peers) &&
690 (GNUNET_YES != disable_try_connect))
692 /* got a first connection, good time to start with FIND PEER requests... */
693 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
699 * Method called whenever a peer disconnects.
702 * @param peer peer identity this notification is about
705 handle_core_disconnect (void *cls,
706 const struct GNUNET_PeerIdentity *peer)
708 struct PeerInfo *to_remove;
710 struct P2PPendingMessage *pos;
711 unsigned int discarded;
712 struct GNUNET_HashCode phash;
714 /* Check for disconnect from self message */
715 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
717 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
721 GNUNET_CONTAINER_multipeermap_get (all_known_peers, peer);
722 if (NULL == to_remove)
727 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), -1,
729 GNUNET_assert (GNUNET_YES ==
730 GNUNET_CONTAINER_multipeermap_remove (all_known_peers,
733 if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
735 GNUNET_SCHEDULER_cancel (to_remove->preference_task);
736 to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
738 GNUNET_CRYPTO_hash (peer,
739 sizeof (struct GNUNET_PeerIdentity),
741 current_bucket = find_bucket (&phash);
742 GNUNET_assert (current_bucket >= 0);
743 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
744 k_buckets[current_bucket].tail, to_remove);
745 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
746 k_buckets[current_bucket].peers_size--;
747 while ((closest_bucket > 0) && (k_buckets[closest_bucket].peers_size == 0))
750 if (to_remove->th != NULL)
752 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
753 to_remove->th = NULL;
756 while (NULL != (pos = to_remove->head))
758 GNUNET_CONTAINER_DLL_remove (to_remove->head, to_remove->tail, pos);
762 GNUNET_STATISTICS_update (GDS_stats,
764 ("# Queued messages discarded (peer disconnected)"),
765 discarded, GNUNET_NO);
766 GNUNET_free (to_remove);
771 * Called when core is ready to send a message we asked for
772 * out to the destination.
774 * @param cls the 'struct PeerInfo' of the target peer
775 * @param size number of bytes available in buf
776 * @param buf where the callee should write the message
777 * @return number of bytes written to buf
780 core_transmit_notify (void *cls, size_t size, void *buf)
782 struct PeerInfo *peer = cls;
784 struct P2PPendingMessage *pending;
789 while ((NULL != (pending = peer->head)) &&
790 (0 == GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value_us))
792 peer->pending_count--;
793 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
794 GNUNET_free (pending);
798 /* no messages pending */
804 GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
805 GNUNET_CORE_PRIO_BEST_EFFORT,
806 GNUNET_TIME_absolute_get_remaining
807 (pending->timeout), &peer->id,
808 ntohs (pending->msg->size),
809 &core_transmit_notify, peer);
810 GNUNET_break (NULL != peer->th);
814 while ((NULL != (pending = peer->head)) &&
815 (size - off >= (msize = ntohs (pending->msg->size))))
817 GNUNET_STATISTICS_update (GDS_stats,
819 ("# Bytes transmitted to other peers"), msize,
821 memcpy (&cbuf[off], pending->msg, msize);
823 peer->pending_count--;
824 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
825 GNUNET_free (pending);
827 if (peer->head != NULL)
830 GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
831 GNUNET_CORE_PRIO_BEST_EFFORT,
832 GNUNET_TIME_absolute_get_remaining
833 (pending->timeout), &peer->id, msize,
834 &core_transmit_notify, peer);
835 GNUNET_break (NULL != peer->th);
842 * Transmit all messages in the peer's message queue.
844 * @param peer message queue to process
847 process_peer_queue (struct PeerInfo *peer)
849 struct P2PPendingMessage *pending;
851 if (NULL == (pending = peer->head))
853 if (NULL != peer->th)
855 GNUNET_STATISTICS_update (GDS_stats,
857 ("# Bytes of bandwidth requested from core"),
858 ntohs (pending->msg->size), GNUNET_NO);
860 GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
861 GNUNET_CORE_PRIO_BEST_EFFORT,
862 GNUNET_TIME_absolute_get_remaining
863 (pending->timeout), &peer->id,
864 ntohs (pending->msg->size),
865 &core_transmit_notify, peer);
866 GNUNET_break (NULL != peer->th);
871 * To how many peers should we (on average) forward the request to
872 * obtain the desired target_replication count (on average).
874 * @param hop_count number of hops the message has traversed
875 * @param target_replication the number of total paths desired
876 * @return Some number of peers to forward the message to
879 get_forward_count (uint32_t hop_count, uint32_t target_replication)
881 uint32_t random_value;
882 uint32_t forward_count;
885 if (hop_count > GDS_NSE_get () * 4.0)
887 /* forcefully terminate */
888 GNUNET_STATISTICS_update (GDS_stats,
889 gettext_noop ("# requests TTL-dropped"),
893 if (hop_count > GDS_NSE_get () * 2.0)
895 /* Once we have reached our ideal number of hops, only forward to 1 peer */
898 /* bound by system-wide maximum */
900 GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
902 1 + (target_replication - 1.0) / (GDS_NSE_get () +
903 ((float) (target_replication - 1.0) *
905 /* Set forward count to floor of target_value */
906 forward_count = (uint32_t) target_value;
907 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
908 target_value = target_value - forward_count;
910 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
911 if (random_value < (target_value * UINT32_MAX))
913 return forward_count;
918 * Compute the distance between have and target as a 32-bit value.
919 * Differences in the lower bits must count stronger than differences
920 * in the higher bits.
924 * @return 0 if have==target, otherwise a number
925 * that is larger as the distance between
926 * the two hash codes increases
929 get_distance (const struct GNUNET_HashCode *target,
930 const struct GNUNET_HashCode *have)
937 /* We have to represent the distance between two 2^9 (=512)-bit
938 * numbers as a 2^5 (=32)-bit number with "0" being used for the
939 * two numbers being identical; furthermore, we need to
940 * guarantee that a difference in the number of matching
941 * bits is always represented in the result.
943 * We use 2^32/2^9 numerical values to distinguish between
944 * hash codes that have the same LSB bit distance and
945 * use the highest 2^9 bits of the result to signify the
946 * number of (mis)matching LSB bits; if we have 0 matching
947 * and hence 512 mismatching LSB bits we return -1 (since
948 * 512 itself cannot be represented with 9 bits) */
950 /* first, calculate the most significant 9 bits of our
951 * result, aka the number of LSBs */
952 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
953 /* bucket is now a value between 0 and 512 */
955 return 0; /* perfect match */
957 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
958 * below, we'd end up with max+1 (overflow)) */
960 /* calculate the most significant bits of the final result */
961 msb = (512 - bucket) << (32 - 9);
962 /* calculate the 32-9 least significant bits of the final result by
963 * looking at the differences in the 32-9 bits following the
964 * mismatching bit at 'bucket' */
967 (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
969 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
970 GNUNET_CRYPTO_hash_get_bit (have, i))
971 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
972 * last bit set will be 31 -- if
973 * i does not reach 512 first... */
980 * Check whether my identity is closer than any known peers. If a
981 * non-null bloomfilter is given, check if this is the closest peer
982 * that hasn't already been routed to.
984 * @param key hash code to check closeness to
985 * @param bloom bloomfilter, exclude these entries from the decision
986 * @return #GNUNET_YES if node location is closest,
987 * #GNUNET_NO otherwise.
990 am_closest_peer (const struct GNUNET_HashCode *key,
991 const struct GNUNET_CONTAINER_BloomFilter *bloom)
997 struct PeerInfo *pos;
998 struct GNUNET_HashCode phash;
1000 if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1002 bucket_num = find_bucket (key);
1003 GNUNET_assert (bucket_num >= 0);
1004 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, key);
1005 pos = k_buckets[bucket_num].head;
1007 while ((pos != NULL) && (count < bucket_size))
1009 GNUNET_CRYPTO_hash (&pos->id,
1010 sizeof (struct GNUNET_PeerIdentity),
1012 if ((bloom != NULL) &&
1014 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1017 continue; /* Skip already checked entries */
1019 other_bits = GNUNET_CRYPTO_hash_matching_bits (&phash, key);
1020 if (other_bits > bits)
1022 if (other_bits == bits) /* We match the same number of bits */
1026 /* No peers closer, we are the closest! */
1032 * Select a peer from the routing table that would be a good routing
1033 * destination for sending a message for "key". The resulting peer
1034 * must not be in the set of blocked peers.<p>
1036 * Note that we should not ALWAYS select the closest peer to the
1037 * target, peers further away from the target should be chosen with
1038 * exponentially declining probability.
1040 * FIXME: double-check that this is fine
1043 * @param key the key we are selecting a peer to route to
1044 * @param bloom a bloomfilter containing entries this request has seen already
1045 * @param hops how many hops has this message traversed thus far
1046 * @return Peer to route to, or NULL on error
1048 static struct PeerInfo *
1049 select_peer (const struct GNUNET_HashCode * key,
1050 const struct GNUNET_CONTAINER_BloomFilter *bloom, uint32_t hops)
1054 unsigned int selected;
1055 struct PeerInfo *pos;
1057 unsigned int smallest_distance;
1058 struct PeerInfo *chosen;
1059 struct GNUNET_HashCode phash;
1061 if (hops >= GDS_NSE_get ())
1063 /* greedy selection (closest peer that is not in bloomfilter) */
1064 smallest_distance = UINT_MAX;
1066 for (bc = 0; bc <= closest_bucket; bc++)
1068 pos = k_buckets[bc].head;
1070 while ((pos != NULL) && (count < bucket_size))
1072 GNUNET_CRYPTO_hash (&pos->id,
1073 sizeof (struct GNUNET_PeerIdentity),
1075 if ((bloom == NULL) ||
1077 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1079 dist = get_distance (key, &phash);
1080 if (dist < smallest_distance)
1083 smallest_distance = dist;
1088 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1089 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1090 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1091 GNUNET_STATISTICS_update (GDS_stats,
1093 ("# Peers excluded from routing due to Bloomfilter"),
1095 dist = get_distance (key, &phash);
1096 if (dist < smallest_distance)
1099 smallest_distance = dist;
1107 GNUNET_STATISTICS_update (GDS_stats,
1108 gettext_noop ("# Peer selection failed"), 1,
1113 /* select "random" peer */
1114 /* count number of peers that are available and not filtered */
1116 for (bc = 0; bc <= closest_bucket; bc++)
1118 pos = k_buckets[bc].head;
1119 while ((pos != NULL) && (count < bucket_size))
1121 GNUNET_CRYPTO_hash (&pos->id,
1122 sizeof (struct GNUNET_PeerIdentity),
1124 if ((bloom != NULL) &&
1126 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1128 GNUNET_STATISTICS_update (GDS_stats,
1130 ("# Peers excluded from routing due to Bloomfilter"),
1132 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1133 "Excluded peer `%s' due to BF match in random routing for %s\n",
1134 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1136 continue; /* Ignore bloomfiltered peers */
1142 if (0 == count) /* No peers to select from! */
1144 GNUNET_STATISTICS_update (GDS_stats,
1145 gettext_noop ("# Peer selection failed"), 1,
1149 /* Now actually choose a peer */
1150 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1152 for (bc = 0; bc <= closest_bucket; bc++)
1154 for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next)
1156 GNUNET_CRYPTO_hash (&pos->id,
1157 sizeof (struct GNUNET_PeerIdentity),
1159 if ((bloom != NULL) &&
1161 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1163 continue; /* Ignore bloomfiltered peers */
1165 if (0 == selected--)
1175 * Compute the set of peers that the given request should be
1178 * @param key routing key
1179 * @param bloom bloom filter excluding peers as targets, all selected
1180 * peers will be added to the bloom filter
1181 * @param hop_count number of hops the request has traversed so far
1182 * @param target_replication desired number of replicas
1183 * @param targets where to store an array of target peers (to be
1184 * free'd by the caller)
1185 * @return number of peers returned in 'targets'.
1188 get_target_peers (const struct GNUNET_HashCode *key,
1189 struct GNUNET_CONTAINER_BloomFilter *bloom,
1190 uint32_t hop_count, uint32_t target_replication,
1191 struct PeerInfo ***targets)
1195 struct PeerInfo **rtargets;
1196 struct PeerInfo *nxt;
1197 struct GNUNET_HashCode nhash;
1199 GNUNET_assert (NULL != bloom);
1200 ret = get_forward_count (hop_count, target_replication);
1206 rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1207 for (off = 0; off < ret; off++)
1209 nxt = select_peer (key, bloom, hop_count);
1212 rtargets[off] = nxt;
1213 GNUNET_CRYPTO_hash (&nxt->id,
1214 sizeof (struct GNUNET_PeerIdentity),
1216 GNUNET_break (GNUNET_NO ==
1217 GNUNET_CONTAINER_bloomfilter_test (bloom,
1219 GNUNET_CONTAINER_bloomfilter_add (bloom, &nhash);
1221 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1222 "Selected %u/%u peers at hop %u for %s (target was %u)\n", off,
1223 GNUNET_CONTAINER_multipeermap_size (all_known_peers),
1224 (unsigned int) hop_count, GNUNET_h2s (key), ret);
1227 GNUNET_free (rtargets);
1231 *targets = rtargets;
1232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1233 "Forwarding query `%s' to %u peers (goal was %u peers)\n",
1242 * Perform a PUT operation. Forwards the given request to other
1243 * peers. Does not store the data locally. Does not give the
1244 * data to local clients. May do nothing if this is the only
1245 * peer in the network (or if we are the closest peer in the
1248 * @param type type of the block
1249 * @param options routing options
1250 * @param desired_replication_level desired replication count
1251 * @param expiration_time when does the content expire
1252 * @param hop_count how many hops has this message traversed so far
1253 * @param bf Bloom filter of peers this PUT has already traversed
1254 * @param key key for the content
1255 * @param put_path_length number of entries in @a put_path
1256 * @param put_path peers this request has traversed so far (if tracked)
1257 * @param data payload to store
1258 * @param data_size number of bytes in @a data
1259 * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1262 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1263 enum GNUNET_DHT_RouteOption options,
1264 uint32_t desired_replication_level,
1265 struct GNUNET_TIME_Absolute expiration_time,
1267 struct GNUNET_CONTAINER_BloomFilter *bf,
1268 const struct GNUNET_HashCode *key,
1269 unsigned int put_path_length,
1270 struct GNUNET_PeerIdentity *put_path,
1271 const void *data, size_t data_size)
1273 unsigned int target_count;
1275 struct PeerInfo **targets;
1276 struct PeerInfo *target;
1277 struct P2PPendingMessage *pending;
1279 struct PeerPutMessage *ppm;
1280 struct GNUNET_PeerIdentity *pp;
1281 struct GNUNET_HashCode thash;
1282 unsigned int skip_count;
1284 GNUNET_assert (NULL != bf);
1285 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1286 "Adding myself (%s) to PUT bloomfilter for %s\n",
1287 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1288 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity_hash);
1289 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1292 get_target_peers (key, bf, hop_count, desired_replication_level,
1294 if (0 == target_count)
1296 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1297 "Routing PUT for %s terminates after %u hops at %s\n",
1298 GNUNET_h2s (key), (unsigned int) hop_count,
1299 GNUNET_i2s (&my_identity));
1303 put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1304 sizeof (struct PeerPutMessage);
1305 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1307 put_path_length = 0;
1308 msize = data_size + sizeof (struct PeerPutMessage);
1310 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1313 GNUNET_free (targets);
1316 GNUNET_STATISTICS_update (GDS_stats,
1318 ("# PUT messages queued for transmission"),
1319 target_count, GNUNET_NO);
1321 for (i = 0; i < target_count; i++)
1323 target = targets[i];
1324 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1327 GNUNET_STATISTICS_update (GDS_stats,
1328 gettext_noop ("# P2P messages dropped due to full queue"),
1333 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1334 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1335 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1336 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1337 pending->importance = 0; /* FIXME */
1338 pending->timeout = expiration_time;
1339 ppm = (struct PeerPutMessage *) &pending[1];
1340 pending->msg = &ppm->header;
1341 ppm->header.size = htons (msize);
1342 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1343 ppm->options = htonl (options);
1344 ppm->type = htonl (type);
1345 ppm->hop_count = htonl (hop_count + 1);
1346 ppm->desired_replication_level = htonl (desired_replication_level);
1347 ppm->put_path_length = htonl (put_path_length);
1348 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1349 GNUNET_CRYPTO_hash (&target->id,
1350 sizeof (struct GNUNET_PeerIdentity),
1352 GNUNET_break (GNUNET_YES ==
1353 GNUNET_CONTAINER_bloomfilter_test (bf,
1355 GNUNET_assert (GNUNET_OK ==
1356 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1360 pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1361 memcpy (pp, put_path,
1362 sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1363 memcpy (&pp[put_path_length], data, data_size);
1364 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1365 target->pending_count++;
1366 process_peer_queue (target);
1368 GNUNET_free (targets);
1369 return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1374 * Perform a GET operation. Forwards the given request to other
1375 * peers. Does not lookup the key locally. May do nothing if this is
1376 * the only peer in the network (or if we are the closest peer in the
1379 * @param type type of the block
1380 * @param options routing options
1381 * @param desired_replication_level desired replication count
1382 * @param hop_count how many hops did this request traverse so far?
1383 * @param key key for the content
1384 * @param xquery extended query
1385 * @param xquery_size number of bytes in @a xquery
1386 * @param reply_bf bloomfilter to filter duplicates
1387 * @param reply_bf_mutator mutator for @a reply_bf
1388 * @param peer_bf filter for peers not to select (again)
1389 * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1392 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1393 enum GNUNET_DHT_RouteOption options,
1394 uint32_t desired_replication_level,
1395 uint32_t hop_count, const struct GNUNET_HashCode * key,
1396 const void *xquery, size_t xquery_size,
1397 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1398 uint32_t reply_bf_mutator,
1399 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1401 unsigned int target_count;
1403 struct PeerInfo **targets;
1404 struct PeerInfo *target;
1405 struct P2PPendingMessage *pending;
1407 struct PeerGetMessage *pgm;
1409 size_t reply_bf_size;
1410 struct GNUNET_HashCode thash;
1411 unsigned int skip_count;
1413 GNUNET_assert (NULL != peer_bf);
1414 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1417 get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1419 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1420 "Adding myself (%s) to GET bloomfilter for %s\n",
1421 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1422 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity_hash);
1423 if (0 == target_count)
1425 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1426 "Routing GET for %s terminates after %u hops at %s\n",
1427 GNUNET_h2s (key), (unsigned int) hop_count,
1428 GNUNET_i2s (&my_identity));
1431 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1432 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1433 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1436 GNUNET_free (targets);
1439 GNUNET_STATISTICS_update (GDS_stats,
1441 ("# GET messages queued for transmission"),
1442 target_count, GNUNET_NO);
1443 /* forward request */
1445 for (i = 0; i < target_count; i++)
1447 target = targets[i];
1448 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1451 GNUNET_STATISTICS_update (GDS_stats,
1452 gettext_noop ("# P2P messages dropped due to full queue"),
1457 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1458 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1459 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1460 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1461 pending->importance = 0; /* FIXME */
1462 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1463 pgm = (struct PeerGetMessage *) &pending[1];
1464 pending->msg = &pgm->header;
1465 pgm->header.size = htons (msize);
1466 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1467 pgm->options = htonl (options);
1468 pgm->type = htonl (type);
1469 pgm->hop_count = htonl (hop_count + 1);
1470 pgm->desired_replication_level = htonl (desired_replication_level);
1471 pgm->xquery_size = htonl (xquery_size);
1472 pgm->bf_mutator = reply_bf_mutator;
1473 GNUNET_CRYPTO_hash (&target->id,
1474 sizeof (struct GNUNET_PeerIdentity),
1476 GNUNET_break (GNUNET_YES ==
1477 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1479 GNUNET_assert (GNUNET_OK ==
1480 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1484 xq = (char *) &pgm[1];
1485 memcpy (xq, xquery, xquery_size);
1486 if (NULL != reply_bf)
1487 GNUNET_assert (GNUNET_OK ==
1488 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1492 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1493 target->pending_count++;
1494 process_peer_queue (target);
1496 GNUNET_free (targets);
1497 return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1502 * Handle a reply (route to origin). Only forwards the reply back to
1503 * the given peer. Does not do local caching or forwarding to local
1506 * @param target neighbour that should receive the block (if still connected)
1507 * @param type type of the block
1508 * @param expiration_time when does the content expire
1509 * @param key key for the content
1510 * @param put_path_length number of entries in @a put_path
1511 * @param put_path peers the original PUT traversed (if tracked)
1512 * @param get_path_length number of entries in @a get_path
1513 * @param get_path peers this reply has traversed so far (if tracked)
1514 * @param data payload of the reply
1515 * @param data_size number of bytes in @a data
1518 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1519 enum GNUNET_BLOCK_Type type,
1520 struct GNUNET_TIME_Absolute expiration_time,
1521 const struct GNUNET_HashCode * key,
1522 unsigned int put_path_length,
1523 const struct GNUNET_PeerIdentity *put_path,
1524 unsigned int get_path_length,
1525 const struct GNUNET_PeerIdentity *get_path,
1526 const void *data, size_t data_size)
1528 struct PeerInfo *pi;
1529 struct P2PPendingMessage *pending;
1531 struct PeerResultMessage *prm;
1532 struct GNUNET_PeerIdentity *paths;
1535 data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1537 sizeof (struct GNUNET_PeerIdentity);
1538 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1540 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1542 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1543 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1548 pi = GNUNET_CONTAINER_multipeermap_get (all_known_peers, target);
1551 /* peer disconnected in the meantime, drop reply */
1554 if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1557 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1562 GNUNET_STATISTICS_update (GDS_stats,
1564 ("# RESULT messages queued for transmission"), 1,
1566 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1567 pending->importance = 0; /* FIXME */
1568 pending->timeout = expiration_time;
1569 prm = (struct PeerResultMessage *) &pending[1];
1570 pending->msg = &prm->header;
1571 prm->header.size = htons (msize);
1572 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1573 prm->type = htonl (type);
1574 prm->put_path_length = htonl (put_path_length);
1575 prm->get_path_length = htonl (get_path_length);
1576 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1578 paths = (struct GNUNET_PeerIdentity *) &prm[1];
1579 memcpy (paths, put_path,
1580 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1581 memcpy (&paths[put_path_length], get_path,
1582 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1583 memcpy (&paths[put_path_length + get_path_length], data, data_size);
1584 GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1585 pi->pending_count++;
1586 process_peer_queue (pi);
1591 * To be called on core init/fail.
1593 * @param cls service closure
1594 * @param identity the public identity of this peer
1597 core_init (void *cls,
1598 const struct GNUNET_PeerIdentity *identity)
1600 my_identity = *identity;
1601 GNUNET_CRYPTO_hash (identity,
1602 sizeof (struct GNUNET_PeerIdentity),
1608 * Core handler for p2p put requests.
1610 * @param cls closure
1611 * @param peer sender of the request
1612 * @param message message
1613 * @param peer peer identity this notification is about
1614 * @return #GNUNET_OK to keep the connection open,
1615 * #GNUNET_SYSERR to close it (signal serious error)
1618 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1619 const struct GNUNET_MessageHeader *message)
1621 const struct PeerPutMessage *put;
1622 const struct GNUNET_PeerIdentity *put_path;
1623 const void *payload;
1626 size_t payload_size;
1627 enum GNUNET_DHT_RouteOption options;
1628 struct GNUNET_CONTAINER_BloomFilter *bf;
1629 struct GNUNET_HashCode test_key;
1630 struct GNUNET_HashCode phash;
1633 msize = ntohs (message->size);
1634 if (msize < sizeof (struct PeerPutMessage))
1636 GNUNET_break_op (0);
1639 put = (const struct PeerPutMessage *) message;
1640 putlen = ntohl (put->put_path_length);
1642 sizeof (struct PeerPutMessage) +
1643 putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1645 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1647 GNUNET_break_op (0);
1650 GNUNET_STATISTICS_update (GDS_stats,
1651 gettext_noop ("# P2P PUT requests received"), 1,
1653 GNUNET_STATISTICS_update (GDS_stats,
1654 gettext_noop ("# P2P PUT bytes received"), msize,
1656 put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1657 payload = &put_path[putlen];
1658 options = ntohl (put->options);
1660 msize - (sizeof (struct PeerPutMessage) +
1661 putlen * sizeof (struct GNUNET_PeerIdentity));
1663 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1664 GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1665 GNUNET_CRYPTO_hash (peer, sizeof (struct GNUNET_PeerIdentity), &phash);
1666 if (GNUNET_YES == log_route_details_stderr)
1670 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1671 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1672 "R5N PUT %s: %s->%s (%u, %u=>%u)\n",
1673 GNUNET_h2s (&put->key), GNUNET_i2s (peer), tmp,
1674 ntohl(put->hop_count),
1675 GNUNET_CRYPTO_hash_matching_bits (&phash, &put->key),
1676 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &put->key)
1680 switch (GNUNET_BLOCK_get_key
1681 (GDS_block_context, ntohl (put->type), payload, payload_size,
1685 if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1687 char *put_s = GNUNET_strdup (GNUNET_h2s_full (&put->key));
1688 GNUNET_break_op (0);
1689 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1690 "PUT with key `%s' for block with key %s\n",
1691 put_s, GNUNET_h2s_full (&test_key));
1692 GNUNET_free (put_s);
1697 GNUNET_break_op (0);
1700 /* cannot verify, good luck */
1703 if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
1705 switch (GNUNET_BLOCK_evaluate (GDS_block_context,
1708 NULL, 0, /* bloom filer */
1709 NULL, 0, /* xquery */
1710 payload, payload_size))
1712 case GNUNET_BLOCK_EVALUATION_OK_MORE:
1713 case GNUNET_BLOCK_EVALUATION_OK_LAST:
1716 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1717 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1718 case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1719 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1720 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1721 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1723 GNUNET_break_op (0);
1728 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1729 GNUNET_CONSTANTS_BLOOMFILTER_K);
1730 GNUNET_break_op (GNUNET_YES ==
1731 GNUNET_CONTAINER_bloomfilter_test (bf, &phash));
1733 struct GNUNET_PeerIdentity pp[putlen + 1];
1735 /* extend 'put path' by sender */
1736 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1738 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1745 /* give to local clients */
1746 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1747 &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1748 payload_size, payload);
1750 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1751 (am_closest_peer (&put->key, bf)))
1752 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1753 (put->expiration_time), &put->key, putlen, pp,
1754 ntohl (put->type), payload_size, payload);
1755 /* route to other peers */
1756 forwarded = GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1757 ntohl (put->desired_replication_level),
1758 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1759 ntohl (put->hop_count), bf,
1761 pp, payload, payload_size);
1762 /* notify monitoring clients */
1763 GDS_CLIENTS_process_put (options
1764 | (GNUNET_OK == forwarded)
1765 ? GNUNET_DHT_RO_LAST_HOP : 0,
1767 ntohl (put->hop_count),
1768 ntohl (put->desired_replication_level),
1770 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1775 GNUNET_CONTAINER_bloomfilter_free (bf);
1781 * We have received a FIND PEER request. Send matching
1784 * @param sender sender of the FIND PEER request
1785 * @param key peers close to this key are desired
1786 * @param bf peers matching this bf are excluded
1787 * @param bf_mutator mutator for bf
1790 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1791 const struct GNUNET_HashCode * key,
1792 struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1795 struct PeerBucket *bucket;
1796 struct PeerInfo *peer;
1797 unsigned int choice;
1798 struct GNUNET_HashCode phash;
1799 struct GNUNET_HashCode mhash;
1800 const struct GNUNET_HELLO_Message *hello;
1802 /* first, check about our own HELLO */
1803 if (NULL != GDS_my_hello)
1805 GNUNET_BLOCK_mingle_hash (&my_identity_hash, bf_mutator, &mhash);
1807 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1809 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1810 GNUNET_TIME_relative_to_absolute
1812 key, 0, NULL, 0, NULL, GDS_my_hello,
1813 GNUNET_HELLO_size ((const struct
1814 GNUNET_HELLO_Message *)
1819 GNUNET_STATISTICS_update (GDS_stats,
1821 ("# FIND PEER requests ignored due to Bloomfilter"),
1827 GNUNET_STATISTICS_update (GDS_stats,
1829 ("# FIND PEER requests ignored due to lack of HELLO"),
1833 /* then, also consider sending a random HELLO from the closest bucket */
1834 if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1835 bucket_idx = closest_bucket;
1837 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1838 if (bucket_idx == GNUNET_SYSERR)
1840 bucket = &k_buckets[bucket_idx];
1841 if (bucket->peers_size == 0)
1844 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1845 peer = bucket->head;
1848 GNUNET_assert (NULL != peer);
1852 choice = bucket->peers_size;
1857 return; /* no non-masked peer available */
1859 peer = bucket->head;
1860 GNUNET_CRYPTO_hash (&peer->id, sizeof (struct GNUNET_PeerIdentity), &phash);
1861 GNUNET_BLOCK_mingle_hash (&phash, bf_mutator, &mhash);
1862 hello = GDS_HELLO_get (&peer->id);
1864 while ((hello == NULL) ||
1865 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1866 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1867 GNUNET_TIME_relative_to_absolute
1868 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1869 0, NULL, 0, NULL, hello,
1870 GNUNET_HELLO_size (hello));
1875 * Core handler for p2p get requests.
1877 * @param cls closure
1878 * @param peer sender of the request
1879 * @param message message
1880 * @return #GNUNET_OK to keep the connection open,
1881 * #GNUNET_SYSERR to close it (signal serious error)
1884 handle_dht_p2p_get (void *cls,
1885 const struct GNUNET_PeerIdentity *peer,
1886 const struct GNUNET_MessageHeader *message)
1888 struct PeerGetMessage *get;
1889 uint32_t xquery_size;
1890 size_t reply_bf_size;
1892 enum GNUNET_BLOCK_Type type;
1893 enum GNUNET_DHT_RouteOption options;
1894 enum GNUNET_BLOCK_EvaluationResult eval;
1895 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1896 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1898 struct GNUNET_HashCode phash;
1902 memcmp (peer, &my_identity,
1903 sizeof (struct GNUNET_PeerIdentity)));
1904 /* parse and validate message */
1905 msize = ntohs (message->size);
1906 if (msize < sizeof (struct PeerGetMessage))
1908 GNUNET_break_op (0);
1911 get = (struct PeerGetMessage *) message;
1912 xquery_size = ntohl (get->xquery_size);
1913 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1915 GNUNET_break_op (0);
1918 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1919 type = ntohl (get->type);
1920 options = ntohl (get->options);
1921 xquery = (const char *) &get[1];
1923 GNUNET_STATISTICS_update (GDS_stats,
1924 gettext_noop ("# P2P GET requests received"), 1,
1926 GNUNET_STATISTICS_update (GDS_stats,
1927 gettext_noop ("# P2P GET bytes received"), msize,
1929 GNUNET_CRYPTO_hash (peer,
1930 sizeof (struct GNUNET_PeerIdentity),
1932 if (GNUNET_YES == log_route_details_stderr)
1936 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1937 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1938 "R5N GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n",
1939 GNUNET_h2s (&get->key), GNUNET_i2s (peer), tmp,
1940 ntohl(get->hop_count),
1941 GNUNET_CRYPTO_hash_matching_bits (&phash, &get->key),
1942 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &get->key),
1943 ntohl(get->xquery_size), xquery);
1947 if (reply_bf_size > 0)
1949 GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1950 GNUNET_CONSTANTS_BLOOMFILTER_K);
1952 GNUNET_BLOCK_evaluate (GDS_block_context, type, &get->key, &reply_bf,
1953 get->bf_mutator, xquery, xquery_size, NULL, 0);
1954 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1956 /* request invalid or block type not supported */
1957 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1958 if (NULL != reply_bf)
1959 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1963 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1964 GNUNET_CONSTANTS_BLOOMFILTER_K);
1965 GNUNET_break_op (GNUNET_YES ==
1966 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1968 /* remember request for routing replies */
1969 GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1970 reply_bf, get->bf_mutator);
1971 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1972 "GET for %s at %s after %u hops\n",
1973 GNUNET_h2s (&get->key),
1974 GNUNET_i2s (&my_identity),
1975 (unsigned int) ntohl (get->hop_count));
1976 /* local lookup (this may update the reply_bf) */
1977 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1978 (am_closest_peer (&get->key, peer_bf)))
1980 if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1982 GNUNET_STATISTICS_update (GDS_stats,
1984 ("# P2P FIND PEER requests processed"), 1,
1986 handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
1991 GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
1992 &reply_bf, get->bf_mutator);
1997 GNUNET_STATISTICS_update (GDS_stats,
1998 gettext_noop ("# P2P GET requests ONLY routed"),
2002 /* P2P forwarding */
2003 forwarded = GNUNET_NO;
2004 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
2005 forwarded = GDS_NEIGHBOURS_handle_get (type, options,
2006 ntohl (get->desired_replication_level),
2007 ntohl (get->hop_count),
2012 get->bf_mutator, peer_bf);
2013 GDS_CLIENTS_process_get (options
2014 | (GNUNET_OK == forwarded)
2015 ? GNUNET_DHT_RO_LAST_HOP : 0,
2017 ntohl (get->hop_count),
2018 ntohl (get->desired_replication_level),
2024 if (NULL != reply_bf)
2025 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
2026 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
2032 * Core handler for p2p result messages.
2034 * @param cls closure
2035 * @param message message
2036 * @param peer peer identity this notification is about
2037 * @return #GNUNET_YES (do not cut p2p connection)
2040 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
2041 const struct GNUNET_MessageHeader *message)
2043 const struct PeerResultMessage *prm;
2044 const struct GNUNET_PeerIdentity *put_path;
2045 const struct GNUNET_PeerIdentity *get_path;
2047 uint32_t get_path_length;
2048 uint32_t put_path_length;
2051 enum GNUNET_BLOCK_Type type;
2053 /* parse and validate message */
2054 msize = ntohs (message->size);
2055 if (msize < sizeof (struct PeerResultMessage))
2057 GNUNET_break_op (0);
2060 prm = (struct PeerResultMessage *) message;
2061 put_path_length = ntohl (prm->put_path_length);
2062 get_path_length = ntohl (prm->get_path_length);
2064 sizeof (struct PeerResultMessage) + (get_path_length +
2066 sizeof (struct GNUNET_PeerIdentity)) ||
2068 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
2070 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
2072 GNUNET_break_op (0);
2075 put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
2076 get_path = &put_path[put_path_length];
2077 type = ntohl (prm->type);
2078 data = (const void *) &get_path[get_path_length];
2080 msize - (sizeof (struct PeerResultMessage) +
2082 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
2083 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
2085 GNUNET_STATISTICS_update (GDS_stats,
2086 gettext_noop ("# P2P RESULT bytes received"),
2088 if (GNUNET_YES == log_route_details_stderr)
2092 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
2093 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, "R5N RESULT %s: %s->%s (%u)\n",
2094 GNUNET_h2s (&prm->key), GNUNET_i2s (peer), tmp,
2095 get_path_length + 1);
2098 /* if we got a HELLO, consider it for our own routing table */
2099 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
2101 const struct GNUNET_MessageHeader *h;
2102 struct GNUNET_PeerIdentity pid;
2105 /* Should be a HELLO, validate and consider using it! */
2106 if (data_size < sizeof (struct GNUNET_MessageHeader))
2108 GNUNET_break_op (0);
2112 if (data_size != ntohs (h->size))
2114 GNUNET_break_op (0);
2118 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
2120 GNUNET_break_op (0);
2123 if ((GNUNET_YES != disable_try_connect) &&
2124 0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
2126 struct GNUNET_HashCode pid_hash;
2128 GNUNET_CRYPTO_hash (&pid, sizeof (struct GNUNET_PeerIdentity), &pid_hash);
2129 bucket = find_bucket (&pid_hash);
2130 if ((bucket >= 0) &&
2131 (k_buckets[bucket].peers_size < bucket_size) &&
2132 (NULL != GDS_transport_handle))
2134 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
2135 GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid, NULL, NULL); /*FIXME TRY_CONNECT change */
2140 /* append 'peer' to 'get_path' */
2142 struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
2144 memcpy (xget_path, get_path,
2145 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2146 xget_path[get_path_length] = *peer;
2149 /* forward to local clients */
2150 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2151 &prm->key, get_path_length, xget_path,
2152 put_path_length, put_path, type, data_size, data);
2153 GDS_CLIENTS_process_get_resp (type,
2154 xget_path, get_path_length,
2155 put_path, put_path_length,
2156 GNUNET_TIME_absolute_ntoh (
2157 prm->expiration_time),
2161 if (GNUNET_YES == cache_results)
2163 struct GNUNET_PeerIdentity xput_path[get_path_length + 1 + put_path_length];
2165 memcpy (xput_path, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
2166 memcpy (&xput_path[put_path_length],
2168 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2170 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2172 get_path_length + put_path_length, xput_path,
2173 type, data_size, data);
2175 /* forward to other peers */
2176 GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2177 &prm->key, put_path_length, put_path, get_path_length,
2178 xget_path, data, data_size);
2186 * Initialize neighbours subsystem.
2188 * @return GNUNET_OK on success, GNUNET_SYSERR on error
2191 GDS_NEIGHBOURS_init ()
2193 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2194 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2195 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2196 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2199 unsigned long long temp_config_num;
2202 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2204 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2206 bucket_size = (unsigned int) temp_config_num;
2208 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "CACHE_RESULTS");
2210 log_route_details_stderr =
2211 (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO;
2212 atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2214 GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
2215 &handle_core_disconnect, NULL, GNUNET_NO, NULL,
2216 GNUNET_NO, core_handlers);
2217 if (core_api == NULL)
2218 return GNUNET_SYSERR;
2219 all_known_peers = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
2225 * Shutdown neighbours subsystem.
2228 GDS_NEIGHBOURS_done ()
2230 if (NULL == core_api)
2232 GNUNET_CORE_disconnect (core_api);
2234 GNUNET_ATS_performance_done (atsAPI);
2236 GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (all_known_peers));
2237 GNUNET_CONTAINER_multipeermap_destroy (all_known_peers);
2238 all_known_peers = NULL;
2239 if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2241 GNUNET_SCHEDULER_cancel (find_peer_task);
2242 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2247 * Get the ID of the local node.
2249 * @return identity of the local node
2251 struct GNUNET_PeerIdentity *
2252 GDS_NEIGHBOURS_get_id ()
2254 return &my_identity;
2258 /* end of gnunet-service-dht_neighbours.c */