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_malloc (sizeof (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,
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,
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,
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
1261 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1262 enum GNUNET_DHT_RouteOption options,
1263 uint32_t desired_replication_level,
1264 struct GNUNET_TIME_Absolute expiration_time,
1266 struct GNUNET_CONTAINER_BloomFilter *bf,
1267 const struct GNUNET_HashCode *key,
1268 unsigned int put_path_length,
1269 struct GNUNET_PeerIdentity *put_path,
1270 const void *data, size_t data_size)
1272 unsigned int target_count;
1274 struct PeerInfo **targets;
1275 struct PeerInfo *target;
1276 struct P2PPendingMessage *pending;
1278 struct PeerPutMessage *ppm;
1279 struct GNUNET_PeerIdentity *pp;
1280 struct GNUNET_HashCode thash;
1282 GNUNET_assert (NULL != bf);
1283 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1284 "Adding myself (%s) to PUT bloomfilter for %s\n",
1285 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1286 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity_hash);
1287 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1290 get_target_peers (key, bf, hop_count, desired_replication_level,
1292 if (0 == target_count)
1294 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1295 "Routing PUT for %s terminates after %u hops at %s\n",
1296 GNUNET_h2s (key), (unsigned int) hop_count,
1297 GNUNET_i2s (&my_identity));
1301 put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1302 sizeof (struct PeerPutMessage);
1303 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1305 put_path_length = 0;
1306 msize = data_size + sizeof (struct PeerPutMessage);
1308 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1311 GNUNET_free (targets);
1314 GNUNET_STATISTICS_update (GDS_stats,
1316 ("# PUT messages queued for transmission"),
1317 target_count, GNUNET_NO);
1318 for (i = 0; i < target_count; i++)
1320 target = targets[i];
1321 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1323 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1325 continue; /* skip */
1327 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1328 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1329 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1330 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1331 pending->importance = 0; /* FIXME */
1332 pending->timeout = expiration_time;
1333 ppm = (struct PeerPutMessage *) &pending[1];
1334 pending->msg = &ppm->header;
1335 ppm->header.size = htons (msize);
1336 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1337 ppm->options = htonl (options);
1338 ppm->type = htonl (type);
1339 ppm->hop_count = htonl (hop_count + 1);
1340 ppm->desired_replication_level = htonl (desired_replication_level);
1341 ppm->put_path_length = htonl (put_path_length);
1342 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1343 GNUNET_CRYPTO_hash (&target->id,
1344 sizeof (struct GNUNET_PeerIdentity),
1346 GNUNET_break (GNUNET_YES ==
1347 GNUNET_CONTAINER_bloomfilter_test (bf,
1349 GNUNET_assert (GNUNET_OK ==
1350 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1354 pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1355 memcpy (pp, put_path,
1356 sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1357 memcpy (&pp[put_path_length], data, data_size);
1358 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1359 target->pending_count++;
1360 process_peer_queue (target);
1362 GNUNET_free (targets);
1367 * Perform a GET operation. Forwards the given request to other
1368 * peers. Does not lookup the key locally. May do nothing if this is
1369 * the only peer in the network (or if we are the closest peer in the
1372 * @param type type of the block
1373 * @param options routing options
1374 * @param desired_replication_level desired replication count
1375 * @param hop_count how many hops did this request traverse so far?
1376 * @param key key for the content
1377 * @param xquery extended query
1378 * @param xquery_size number of bytes in @a xquery
1379 * @param reply_bf bloomfilter to filter duplicates
1380 * @param reply_bf_mutator mutator for @a reply_bf
1381 * @param peer_bf filter for peers not to select (again)
1384 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1385 enum GNUNET_DHT_RouteOption options,
1386 uint32_t desired_replication_level,
1387 uint32_t hop_count, const struct GNUNET_HashCode * key,
1388 const void *xquery, size_t xquery_size,
1389 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1390 uint32_t reply_bf_mutator,
1391 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1393 unsigned int target_count;
1395 struct PeerInfo **targets;
1396 struct PeerInfo *target;
1397 struct P2PPendingMessage *pending;
1399 struct PeerGetMessage *pgm;
1401 size_t reply_bf_size;
1402 struct GNUNET_HashCode thash;
1404 GNUNET_assert (NULL != peer_bf);
1405 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1408 get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1410 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1411 "Adding myself (%s) to GET bloomfilter for %s\n",
1412 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1413 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity_hash);
1414 if (0 == target_count)
1416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1417 "Routing GET for %s terminates after %u hops at %s\n",
1418 GNUNET_h2s (key), (unsigned int) hop_count,
1419 GNUNET_i2s (&my_identity));
1422 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1423 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1424 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1427 GNUNET_free (targets);
1430 GNUNET_STATISTICS_update (GDS_stats,
1432 ("# GET messages queued for transmission"),
1433 target_count, GNUNET_NO);
1434 /* forward request */
1435 for (i = 0; i < target_count; i++)
1437 target = targets[i];
1438 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1440 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1442 continue; /* skip */
1444 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1445 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1446 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1447 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1448 pending->importance = 0; /* FIXME */
1449 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1450 pgm = (struct PeerGetMessage *) &pending[1];
1451 pending->msg = &pgm->header;
1452 pgm->header.size = htons (msize);
1453 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1454 pgm->options = htonl (options);
1455 pgm->type = htonl (type);
1456 pgm->hop_count = htonl (hop_count + 1);
1457 pgm->desired_replication_level = htonl (desired_replication_level);
1458 pgm->xquery_size = htonl (xquery_size);
1459 pgm->bf_mutator = reply_bf_mutator;
1460 GNUNET_CRYPTO_hash (&target->id,
1461 sizeof (struct GNUNET_PeerIdentity),
1463 GNUNET_break (GNUNET_YES ==
1464 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1466 GNUNET_assert (GNUNET_OK ==
1467 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1471 xq = (char *) &pgm[1];
1472 memcpy (xq, xquery, xquery_size);
1473 if (NULL != reply_bf)
1474 GNUNET_assert (GNUNET_OK ==
1475 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1479 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1480 target->pending_count++;
1481 process_peer_queue (target);
1483 GNUNET_free (targets);
1488 * Handle a reply (route to origin). Only forwards the reply back to
1489 * the given peer. Does not do local caching or forwarding to local
1492 * @param target neighbour that should receive the block (if still connected)
1493 * @param type type of the block
1494 * @param expiration_time when does the content expire
1495 * @param key key for the content
1496 * @param put_path_length number of entries in @a put_path
1497 * @param put_path peers the original PUT traversed (if tracked)
1498 * @param get_path_length number of entries in @a get_path
1499 * @param get_path peers this reply has traversed so far (if tracked)
1500 * @param data payload of the reply
1501 * @param data_size number of bytes in @a data
1504 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1505 enum GNUNET_BLOCK_Type type,
1506 struct GNUNET_TIME_Absolute expiration_time,
1507 const struct GNUNET_HashCode * key,
1508 unsigned int put_path_length,
1509 const struct GNUNET_PeerIdentity *put_path,
1510 unsigned int get_path_length,
1511 const struct GNUNET_PeerIdentity *get_path,
1512 const void *data, size_t data_size)
1514 struct PeerInfo *pi;
1515 struct P2PPendingMessage *pending;
1517 struct PeerResultMessage *prm;
1518 struct GNUNET_PeerIdentity *paths;
1521 data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1523 sizeof (struct GNUNET_PeerIdentity);
1524 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1526 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1528 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1529 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1534 pi = GNUNET_CONTAINER_multipeermap_get (all_known_peers, target);
1537 /* peer disconnected in the meantime, drop reply */
1540 if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1543 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1548 GNUNET_STATISTICS_update (GDS_stats,
1550 ("# RESULT messages queued for transmission"), 1,
1552 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1553 pending->importance = 0; /* FIXME */
1554 pending->timeout = expiration_time;
1555 prm = (struct PeerResultMessage *) &pending[1];
1556 pending->msg = &prm->header;
1557 prm->header.size = htons (msize);
1558 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1559 prm->type = htonl (type);
1560 prm->put_path_length = htonl (put_path_length);
1561 prm->get_path_length = htonl (get_path_length);
1562 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1564 paths = (struct GNUNET_PeerIdentity *) &prm[1];
1565 memcpy (paths, put_path,
1566 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1567 memcpy (&paths[put_path_length], get_path,
1568 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1569 memcpy (&paths[put_path_length + get_path_length], data, data_size);
1570 GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1571 pi->pending_count++;
1572 process_peer_queue (pi);
1577 * To be called on core init/fail.
1579 * @param cls service closure
1580 * @param identity the public identity of this peer
1583 core_init (void *cls,
1584 const struct GNUNET_PeerIdentity *identity)
1586 my_identity = *identity;
1587 GNUNET_CRYPTO_hash (identity,
1588 sizeof (struct GNUNET_PeerIdentity),
1594 * Core handler for p2p put requests.
1596 * @param cls closure
1597 * @param peer sender of the request
1598 * @param message message
1599 * @param peer peer identity this notification is about
1600 * @return #GNUNET_OK to keep the connection open,
1601 * #GNUNET_SYSERR to close it (signal serious error)
1604 handle_dht_p2p_put (void *cls,
1605 const struct GNUNET_PeerIdentity *peer,
1606 const struct GNUNET_MessageHeader *message)
1608 const struct PeerPutMessage *put;
1609 const struct GNUNET_PeerIdentity *put_path;
1610 const void *payload;
1613 size_t payload_size;
1614 enum GNUNET_DHT_RouteOption options;
1615 struct GNUNET_CONTAINER_BloomFilter *bf;
1616 struct GNUNET_HashCode test_key;
1617 struct GNUNET_HashCode phash;
1619 msize = ntohs (message->size);
1620 if (msize < sizeof (struct PeerPutMessage))
1622 GNUNET_break_op (0);
1625 put = (const struct PeerPutMessage *) message;
1626 putlen = ntohl (put->put_path_length);
1628 sizeof (struct PeerPutMessage) +
1629 putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1631 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1633 GNUNET_break_op (0);
1636 GNUNET_STATISTICS_update (GDS_stats,
1637 gettext_noop ("# P2P PUT requests received"), 1,
1639 GNUNET_STATISTICS_update (GDS_stats,
1640 gettext_noop ("# P2P PUT bytes received"), msize,
1642 put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1643 payload = &put_path[putlen];
1644 options = ntohl (put->options);
1646 msize - (sizeof (struct PeerPutMessage) +
1647 putlen * sizeof (struct GNUNET_PeerIdentity));
1648 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1649 GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1650 GNUNET_CRYPTO_hash (peer, sizeof (struct GNUNET_PeerIdentity), &phash);
1651 if (GNUNET_YES == log_route_details_stderr)
1655 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1656 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1657 "XDHT PUT %s: %s->%s (%u, %u=>%u)\n",
1658 GNUNET_h2s (&put->key), GNUNET_i2s (peer), tmp,
1659 ntohl(put->hop_count),
1660 GNUNET_CRYPTO_hash_matching_bits (&phash, &put->key),
1661 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &put->key)
1665 switch (GNUNET_BLOCK_get_key
1666 (GDS_block_context, ntohl (put->type), payload, payload_size,
1670 if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1672 char *put_s = GNUNET_strdup (GNUNET_h2s (&put->key));
1673 GNUNET_break_op (0);
1674 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1675 "PUT with key `%s' for block with key %s\n",
1676 put_s, GNUNET_h2s (&test_key));
1677 GNUNET_free (put_s);
1682 GNUNET_break_op (0);
1685 /* cannot verify, good luck */
1688 if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
1690 switch (GNUNET_BLOCK_evaluate (GDS_block_context,
1693 NULL, 0, /* bloom filer */
1694 NULL, 0, /* xquery */
1695 payload, payload_size))
1697 case GNUNET_BLOCK_EVALUATION_OK_MORE:
1698 case GNUNET_BLOCK_EVALUATION_OK_LAST:
1701 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1702 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1703 case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1704 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1705 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1706 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1708 GNUNET_break_op (0);
1713 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1714 GNUNET_CONSTANTS_BLOOMFILTER_K);
1715 GNUNET_break_op (GNUNET_YES ==
1716 GNUNET_CONTAINER_bloomfilter_test (bf, &phash));
1718 struct GNUNET_PeerIdentity pp[putlen + 1];
1720 /* extend 'put path' by sender */
1721 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1723 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1730 /* give to local clients */
1731 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1732 &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1733 payload_size, payload);
1735 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1736 (am_closest_peer (&put->key, bf)))
1737 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1738 (put->expiration_time), &put->key, putlen, pp,
1739 ntohl (put->type), payload_size, payload);
1740 /* route to other peers */
1741 GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1742 ntohl (put->desired_replication_level),
1743 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1744 ntohl (put->hop_count), bf, &put->key, putlen,
1745 pp, payload, payload_size);
1746 /* notify monitoring clients */
1747 GDS_CLIENTS_process_put (options,
1749 ntohl (put->hop_count),
1750 ntohl (put->desired_replication_level),
1752 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1757 GNUNET_CONTAINER_bloomfilter_free (bf);
1763 * We have received a FIND PEER request. Send matching
1766 * @param sender sender of the FIND PEER request
1767 * @param key peers close to this key are desired
1768 * @param bf peers matching this bf are excluded
1769 * @param bf_mutator mutator for bf
1772 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1773 const struct GNUNET_HashCode * key,
1774 struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1777 struct PeerBucket *bucket;
1778 struct PeerInfo *peer;
1779 unsigned int choice;
1780 struct GNUNET_HashCode phash;
1781 struct GNUNET_HashCode mhash;
1782 const struct GNUNET_HELLO_Message *hello;
1784 /* first, check about our own HELLO */
1785 if (NULL != GDS_my_hello)
1787 GNUNET_BLOCK_mingle_hash (&my_identity_hash, bf_mutator, &mhash);
1789 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1791 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1792 GNUNET_TIME_relative_to_absolute
1794 key, 0, NULL, 0, NULL, GDS_my_hello,
1795 GNUNET_HELLO_size ((const struct
1796 GNUNET_HELLO_Message *)
1801 GNUNET_STATISTICS_update (GDS_stats,
1803 ("# FIND PEER requests ignored due to Bloomfilter"),
1809 GNUNET_STATISTICS_update (GDS_stats,
1811 ("# FIND PEER requests ignored due to lack of HELLO"),
1815 /* then, also consider sending a random HELLO from the closest bucket */
1816 if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1817 bucket_idx = closest_bucket;
1819 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1820 if (bucket_idx == GNUNET_SYSERR)
1822 bucket = &k_buckets[bucket_idx];
1823 if (bucket->peers_size == 0)
1826 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1827 peer = bucket->head;
1830 GNUNET_assert (NULL != peer);
1834 choice = bucket->peers_size;
1839 return; /* no non-masked peer available */
1841 peer = bucket->head;
1842 GNUNET_CRYPTO_hash (&peer->id, sizeof (struct GNUNET_PeerIdentity), &phash);
1843 GNUNET_BLOCK_mingle_hash (&phash, bf_mutator, &mhash);
1844 hello = GDS_HELLO_get (&peer->id);
1846 while ((hello == NULL) ||
1847 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1848 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1849 GNUNET_TIME_relative_to_absolute
1850 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1851 0, NULL, 0, NULL, hello,
1852 GNUNET_HELLO_size (hello));
1857 * Core handler for p2p get requests.
1859 * @param cls closure
1860 * @param peer sender of the request
1861 * @param message message
1862 * @return #GNUNET_OK to keep the connection open,
1863 * #GNUNET_SYSERR to close it (signal serious error)
1866 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1867 const struct GNUNET_MessageHeader *message)
1869 struct PeerGetMessage *get;
1870 uint32_t xquery_size;
1871 size_t reply_bf_size;
1873 enum GNUNET_BLOCK_Type type;
1874 enum GNUNET_DHT_RouteOption options;
1875 enum GNUNET_BLOCK_EvaluationResult eval;
1876 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1877 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1879 struct GNUNET_HashCode phash;
1882 memcmp (peer, &my_identity,
1883 sizeof (struct GNUNET_PeerIdentity)));
1884 /* parse and validate message */
1885 msize = ntohs (message->size);
1886 if (msize < sizeof (struct PeerGetMessage))
1888 GNUNET_break_op (0);
1891 get = (struct PeerGetMessage *) message;
1892 xquery_size = ntohl (get->xquery_size);
1893 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1895 GNUNET_break_op (0);
1898 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1899 type = ntohl (get->type);
1900 options = ntohl (get->options);
1901 xquery = (const char *) &get[1];
1903 GNUNET_STATISTICS_update (GDS_stats,
1904 gettext_noop ("# P2P GET requests received"), 1,
1906 GNUNET_STATISTICS_update (GDS_stats,
1907 gettext_noop ("# P2P GET bytes received"), msize,
1909 GNUNET_CRYPTO_hash (peer, sizeof (struct GNUNET_PeerIdentity), &phash);
1910 if (GNUNET_YES == log_route_details_stderr)
1914 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1915 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1916 "XDHT GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n",
1917 GNUNET_h2s (&get->key), GNUNET_i2s (peer), tmp,
1918 ntohl(get->hop_count),
1919 GNUNET_CRYPTO_hash_matching_bits (&phash, &get->key),
1920 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &get->key),
1921 ntohl(get->xquery_size), xquery
1926 if (reply_bf_size > 0)
1928 GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1929 GNUNET_CONSTANTS_BLOOMFILTER_K);
1931 GNUNET_BLOCK_evaluate (GDS_block_context, type, &get->key, &reply_bf,
1932 get->bf_mutator, xquery, xquery_size, NULL, 0);
1933 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1935 /* request invalid or block type not supported */
1936 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1937 if (NULL != reply_bf)
1938 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1942 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1943 GNUNET_CONSTANTS_BLOOMFILTER_K);
1944 GNUNET_break_op (GNUNET_YES ==
1945 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1947 /* remember request for routing replies */
1948 GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1949 reply_bf, get->bf_mutator);
1950 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GET for %s at %s after %u hops\n",
1951 GNUNET_h2s (&get->key), GNUNET_i2s (&my_identity),
1952 (unsigned int) ntohl (get->hop_count));
1953 /* local lookup (this may update the reply_bf) */
1954 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1955 (am_closest_peer (&get->key, peer_bf)))
1957 if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1959 GNUNET_STATISTICS_update (GDS_stats,
1961 ("# P2P FIND PEER requests processed"), 1,
1963 handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
1968 GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
1969 &reply_bf, get->bf_mutator);
1974 GNUNET_STATISTICS_update (GDS_stats,
1975 gettext_noop ("# P2P GET requests ONLY routed"),
1979 GDS_CLIENTS_process_get (options,
1981 ntohl(get->hop_count),
1982 ntohl(get->desired_replication_level),
1986 /* P2P forwarding */
1987 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1988 GDS_NEIGHBOURS_handle_get (type, options,
1989 ntohl (get->desired_replication_level),
1990 ntohl (get->hop_count), &get->key, xquery,
1991 xquery_size, reply_bf, get->bf_mutator, peer_bf);
1993 if (NULL != reply_bf)
1994 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1995 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
2001 * Core handler for p2p result messages.
2003 * @param cls closure
2004 * @param message message
2005 * @param peer peer identity this notification is about
2006 * @return #GNUNET_YES (do not cut p2p connection)
2009 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
2010 const struct GNUNET_MessageHeader *message)
2012 const struct PeerResultMessage *prm;
2013 const struct GNUNET_PeerIdentity *put_path;
2014 const struct GNUNET_PeerIdentity *get_path;
2016 uint32_t get_path_length;
2017 uint32_t put_path_length;
2020 enum GNUNET_BLOCK_Type type;
2022 /* parse and validate message */
2023 msize = ntohs (message->size);
2024 if (msize < sizeof (struct PeerResultMessage))
2026 GNUNET_break_op (0);
2029 prm = (struct PeerResultMessage *) message;
2030 put_path_length = ntohl (prm->put_path_length);
2031 get_path_length = ntohl (prm->get_path_length);
2033 sizeof (struct PeerResultMessage) + (get_path_length +
2035 sizeof (struct GNUNET_PeerIdentity)) ||
2037 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
2039 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
2041 GNUNET_break_op (0);
2044 put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
2045 get_path = &put_path[put_path_length];
2046 type = ntohl (prm->type);
2047 data = (const void *) &get_path[get_path_length];
2049 msize - (sizeof (struct PeerResultMessage) +
2051 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
2052 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
2054 GNUNET_STATISTICS_update (GDS_stats,
2055 gettext_noop ("# P2P RESULT bytes received"),
2057 if (GNUNET_YES == log_route_details_stderr)
2061 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
2062 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, "XDHT RESULT %s: %s->%s (%u)\n",
2063 GNUNET_h2s (&prm->key), GNUNET_i2s (peer), tmp,
2064 get_path_length + 1);
2067 /* if we got a HELLO, consider it for our own routing table */
2068 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
2070 const struct GNUNET_MessageHeader *h;
2071 struct GNUNET_PeerIdentity pid;
2074 /* Should be a HELLO, validate and consider using it! */
2075 if (data_size < sizeof (struct GNUNET_MessageHeader))
2077 GNUNET_break_op (0);
2081 if (data_size != ntohs (h->size))
2083 GNUNET_break_op (0);
2087 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
2089 GNUNET_break_op (0);
2092 if ((GNUNET_YES != disable_try_connect) &&
2093 0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
2095 struct GNUNET_HashCode pid_hash;
2097 GNUNET_CRYPTO_hash (&pid, sizeof (struct GNUNET_PeerIdentity), &pid_hash);
2098 bucket = find_bucket (&pid_hash);
2099 if ((bucket >= 0) &&
2100 (k_buckets[bucket].peers_size < bucket_size) &&
2101 (NULL != GDS_transport_handle))
2103 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
2104 GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid, NULL, NULL); /*FIXME TRY_CONNECT change */
2109 /* append 'peer' to 'get_path' */
2111 struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
2113 memcpy (xget_path, get_path,
2114 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2115 xget_path[get_path_length] = *peer;
2118 /* forward to local clients */
2119 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2120 &prm->key, get_path_length, xget_path,
2121 put_path_length, put_path, type, data_size, data);
2122 GDS_CLIENTS_process_get_resp (type,
2123 xget_path, get_path_length,
2124 put_path, put_path_length,
2125 GNUNET_TIME_absolute_ntoh (
2126 prm->expiration_time),
2130 if (GNUNET_YES == cache_results)
2132 struct GNUNET_PeerIdentity xput_path[get_path_length + 1 + put_path_length];
2134 memcpy (xput_path, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
2135 memcpy (&xput_path[put_path_length],
2137 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2139 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2141 get_path_length + put_path_length, xput_path,
2142 type, data_size, data);
2144 /* forward to other peers */
2145 GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2146 &prm->key, put_path_length, put_path, get_path_length,
2147 xget_path, data, data_size);
2155 * Initialize neighbours subsystem.
2157 * @return GNUNET_OK on success, GNUNET_SYSERR on error
2160 GDS_NEIGHBOURS_init ()
2162 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2163 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2164 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2165 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2168 unsigned long long temp_config_num;
2171 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2173 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2175 bucket_size = (unsigned int) temp_config_num;
2177 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "CACHE_RESULTS");
2179 log_route_details_stderr =
2180 (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO;
2181 atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2183 GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
2184 &handle_core_disconnect, NULL, GNUNET_NO, NULL,
2185 GNUNET_NO, core_handlers);
2186 if (core_api == NULL)
2187 return GNUNET_SYSERR;
2188 all_known_peers = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
2194 * Shutdown neighbours subsystem.
2197 GDS_NEIGHBOURS_done ()
2199 if (NULL == core_api)
2201 GNUNET_CORE_disconnect (core_api);
2203 GNUNET_ATS_performance_done (atsAPI);
2205 GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (all_known_peers));
2206 GNUNET_CONTAINER_multipeermap_destroy (all_known_peers);
2207 all_known_peers = NULL;
2208 if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2210 GNUNET_SCHEDULER_cancel (find_peer_task);
2211 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2216 * Get the ID of the local node.
2218 * @return identity of the local node
2220 struct GNUNET_PeerIdentity *
2221 GDS_NEIGHBOURS_get_id ()
2223 return &my_identity;
2227 /* end of gnunet-service-dht_neighbours.c */