2 This file is part of GNUnet.
3 Copyright (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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
22 * @file dht/gnunet-service-dht_neighbours.c
23 * @brief GNUnet DHT service's bucket and neighbour management code
24 * @author Christian Grothoff
25 * @author Nathan Evans
28 #include "gnunet_util_lib.h"
29 #include "gnunet_block_lib.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_constants.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_nse_service.h"
34 #include "gnunet_ats_service.h"
35 #include "gnunet_core_service.h"
36 #include "gnunet_datacache_lib.h"
37 #include "gnunet_transport_service.h"
38 #include "gnunet_hello_lib.h"
39 #include "gnunet_dht_service.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet-service-dht.h"
42 #include "gnunet-service-dht_clients.h"
43 #include "gnunet-service-dht_datacache.h"
44 #include "gnunet-service-dht_hello.h"
45 #include "gnunet-service-dht_neighbours.h"
46 #include "gnunet-service-dht_nse.h"
47 #include "gnunet-service-dht_routing.h"
50 #define LOG_TRAFFIC(kind,...) GNUNET_log_from (kind, "dht-traffic",__VA_ARGS__)
53 * How many buckets will we allow total.
55 #define MAX_BUCKETS sizeof (struct GNUNET_HashCode) * 8
58 * What is the maximum number of peers in a given bucket.
60 #define DEFAULT_BUCKET_SIZE 8
63 * Desired replication level for FIND PEER requests
65 #define FIND_PEER_REPLICATION_LEVEL 4
68 * Maximum allowed replication level for all requests.
70 #define MAXIMUM_REPLICATION_LEVEL 16
73 * Maximum allowed number of pending messages per peer.
75 #define MAXIMUM_PENDING_PER_PEER 64
78 * How often to update our preference levels for peers in our routing tables.
80 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
83 * How long at least to wait before sending another find peer request.
85 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
88 * How long at most to wait before sending another find peer request.
90 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10)
93 * How long at most to wait for transmission of a GET request to another peer?
95 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
98 * Hello address expiration
100 extern struct GNUNET_TIME_Relative hello_expiration;
103 GNUNET_NETWORK_STRUCT_BEGIN
108 struct PeerPutMessage
111 * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
113 struct GNUNET_MessageHeader header;
118 uint32_t options GNUNET_PACKED;
123 uint32_t type GNUNET_PACKED;
128 uint32_t hop_count GNUNET_PACKED;
131 * Replication level for this message
133 uint32_t desired_replication_level GNUNET_PACKED;
136 * Length of the PUT path that follows (if tracked).
138 uint32_t put_path_length GNUNET_PACKED;
141 * When does the content expire?
143 struct GNUNET_TIME_AbsoluteNBO expiration_time;
146 * Bloomfilter (for peer identities) to stop circular routes
148 char bloomfilter[DHT_BLOOM_SIZE];
151 * The key we are storing under.
153 struct GNUNET_HashCode key;
155 /* put path (if tracked) */
165 struct PeerResultMessage
168 * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
170 struct GNUNET_MessageHeader header;
175 uint32_t type GNUNET_PACKED;
178 * Length of the PUT path that follows (if tracked).
180 uint32_t put_path_length GNUNET_PACKED;
183 * Length of the GET path that follows (if tracked).
185 uint32_t get_path_length GNUNET_PACKED;
188 * When does the content expire?
190 struct GNUNET_TIME_AbsoluteNBO expiration_time;
193 * The key of the corresponding GET request.
195 struct GNUNET_HashCode key;
197 /* put path (if tracked) */
199 /* get path (if tracked) */
209 struct PeerGetMessage
212 * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_GET
214 struct GNUNET_MessageHeader header;
219 uint32_t options GNUNET_PACKED;
222 * Desired content type.
224 uint32_t type GNUNET_PACKED;
229 uint32_t hop_count GNUNET_PACKED;
232 * Desired replication level for this request.
234 uint32_t desired_replication_level GNUNET_PACKED;
237 * Size of the extended query.
239 uint32_t xquery_size;
242 * Bloomfilter mutator.
247 * Bloomfilter (for peer identities) to stop circular routes
249 char bloomfilter[DHT_BLOOM_SIZE];
252 * The key we are looking for.
254 struct GNUNET_HashCode key;
258 /* result bloomfilter */
261 GNUNET_NETWORK_STRUCT_END
264 * Linked list of messages to send to a particular other peer.
266 struct P2PPendingMessage
269 * Pointer to next item in the list
271 struct P2PPendingMessage *next;
274 * Pointer to previous item in the list
276 struct P2PPendingMessage *prev;
279 * Message importance level. FIXME: used? useful?
281 unsigned int importance;
284 * When does this message time out?
286 struct GNUNET_TIME_Absolute timeout;
289 * Actual message to be sent, allocated at the end of the struct:
290 * // msg = (cast) &pm[1];
291 * // memcpy (&pm[1], data, len);
293 const struct GNUNET_MessageHeader *msg;
299 * Entry for a peer in a bucket.
304 * Next peer entry (DLL)
306 struct PeerInfo *next;
309 * Prev peer entry (DLL)
311 struct PeerInfo *prev;
314 * Count of outstanding messages for peer.
316 unsigned int pending_count;
319 * Head of pending messages to be sent to this peer.
321 struct P2PPendingMessage *head;
324 * Tail of pending messages to be sent to this peer.
326 struct P2PPendingMessage *tail;
329 * Core handle for sending messages to this peer.
331 struct GNUNET_CORE_TransmitHandle *th;
334 * Task for scheduling preference updates
336 struct GNUNET_SCHEDULER_Task * preference_task;
339 * What is the identity of the peer?
341 struct GNUNET_PeerIdentity id;
345 * What is the average latency for replies received?
347 struct GNUNET_TIME_Relative latency;
350 * Transport level distance to peer.
352 unsigned int distance;
359 * Peers are grouped into buckets.
366 struct PeerInfo *head;
371 struct PeerInfo *tail;
374 * Number of peers in the bucket.
376 unsigned int peers_size;
381 * Do we cache all results that we are routing in the local datacache?
383 static int cache_results;
386 * Should routing details be logged to stderr (for debugging)?
388 static int log_route_details_stderr;
391 * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
393 static unsigned int closest_bucket;
396 * How many peers have we added since we sent out our last
399 static unsigned int newly_found_peers;
402 * Option for testing that disables the 'connect' function of the DHT.
404 static int disable_try_connect;
407 * The buckets. Array of size MAX_BUCKET_SIZE. Offset 0 means 0 bits matching.
409 static struct PeerBucket k_buckets[MAX_BUCKETS];
412 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
414 static struct GNUNET_CONTAINER_MultiPeerMap *all_known_peers;
417 * Maximum size for each bucket.
419 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
422 * Task that sends FIND PEER requests.
424 static struct GNUNET_SCHEDULER_Task * find_peer_task;
427 * Identity of this peer.
429 static struct GNUNET_PeerIdentity my_identity;
432 * Hash of the identity of this peer.
434 static struct GNUNET_HashCode my_identity_hash;
439 static struct GNUNET_CORE_Handle *core_api;
444 static struct GNUNET_ATS_PerformanceHandle *atsAPI;
449 * Find the optimal bucket for this key.
451 * @param hc the hashcode to compare our identity to
452 * @return the proper bucket index, or GNUNET_SYSERR
453 * on error (same hashcode)
456 find_bucket (const struct GNUNET_HashCode *hc)
460 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, hc);
461 if (bits == MAX_BUCKETS)
463 /* How can all bits match? Got my own ID? */
465 return GNUNET_SYSERR;
467 return MAX_BUCKETS - bits - 1;
472 * Let GNUnet core know that we like the given peer.
474 * @param cls the `struct PeerInfo` of the peer
475 * @param tc scheduler context.
478 update_core_preference (void *cls,
479 const struct GNUNET_SCHEDULER_TaskContext *tc)
481 struct PeerInfo *peer = cls;
483 unsigned int matching;
485 struct GNUNET_HashCode phash;
487 peer->preference_task = NULL;
488 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
490 GNUNET_CRYPTO_hash (&peer->id,
491 sizeof (struct GNUNET_PeerIdentity),
494 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash,
498 bucket = find_bucket (&phash);
499 if (bucket == GNUNET_SYSERR)
503 GNUNET_assert (k_buckets[bucket].peers_size != 0);
504 preference = (1LL << matching) / k_buckets[bucket].peers_size;
508 peer->preference_task =
509 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
510 &update_core_preference, peer);
513 GNUNET_STATISTICS_update (GDS_stats,
514 gettext_noop ("# Preference updates given to core"),
516 GNUNET_ATS_performance_change_preference (atsAPI, &peer->id,
517 GNUNET_ATS_PREFERENCE_BANDWIDTH,
518 (double) preference, GNUNET_ATS_PREFERENCE_END);
519 peer->preference_task =
520 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
521 &update_core_preference, peer);
528 * Closure for 'add_known_to_bloom'.
530 struct BloomConstructorContext
533 * Bloom filter under construction.
535 struct GNUNET_CONTAINER_BloomFilter *bloom;
545 * Add each of the peers we already know to the bloom filter of
546 * the request so that we don't get duplicate HELLOs.
548 * @param cls the 'struct BloomConstructorContext'.
549 * @param key peer identity to add to the bloom filter
550 * @param value value the peer information (unused)
551 * @return #GNUNET_YES (we should continue to iterate)
554 add_known_to_bloom (void *cls,
555 const struct GNUNET_PeerIdentity *key,
558 struct BloomConstructorContext *ctx = cls;
559 struct GNUNET_HashCode key_hash;
560 struct GNUNET_HashCode mh;
562 GNUNET_CRYPTO_hash (key, sizeof (struct GNUNET_PeerIdentity), &key_hash);
563 GNUNET_BLOCK_mingle_hash (&key_hash, ctx->bf_mutator, &mh);
564 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
565 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
566 GNUNET_i2s (key), ctx->bf_mutator);
567 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
573 * Task to send a find peer message for our own peer identifier
574 * so that we can find the closest peers in the network to ourselves
575 * and attempt to connect to them.
577 * @param cls closure for this task
578 * @param tc the context under which the task is running
581 send_find_peer_message (void *cls,
582 const struct GNUNET_SCHEDULER_TaskContext *tc)
584 struct GNUNET_TIME_Relative next_send_time;
585 struct BloomConstructorContext bcc;
586 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
588 find_peer_task = NULL;
589 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
591 if (newly_found_peers > bucket_size)
593 /* If we are finding many peers already, no need to send out our request right now! */
595 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
596 &send_find_peer_message, NULL);
597 newly_found_peers = 0;
601 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
603 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
604 GNUNET_CONSTANTS_BLOOMFILTER_K);
605 GNUNET_CONTAINER_multipeermap_iterate (all_known_peers, &add_known_to_bloom,
607 GNUNET_STATISTICS_update (GDS_stats,
608 gettext_noop ("# FIND PEER messages initiated"), 1,
611 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
612 GNUNET_CONSTANTS_BLOOMFILTER_K);
613 // FIXME: pass priority!?
614 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
615 GNUNET_DHT_RO_FIND_PEER,
616 FIND_PEER_REPLICATION_LEVEL, 0,
617 &my_identity_hash, NULL, 0, bcc.bloom,
618 bcc.bf_mutator, peer_bf);
619 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
620 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
621 /* schedule next round */
622 next_send_time.rel_value_us =
623 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value_us +
624 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
625 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value_us /
626 (newly_found_peers + 1));
627 newly_found_peers = 0;
629 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
635 * Method called whenever a peer connects.
638 * @param peer peer identity this notification is about
641 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer)
643 struct PeerInfo *ret;
644 struct GNUNET_HashCode phash;
647 /* Check for connect to self message */
648 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
650 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
654 GNUNET_CONTAINER_multipeermap_contains (all_known_peers,
660 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), 1,
662 GNUNET_CRYPTO_hash (peer,
663 sizeof (struct GNUNET_PeerIdentity),
665 peer_bucket = find_bucket (&phash);
666 GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
667 ret = GNUNET_new (struct PeerInfo);
669 ret->latency = latency;
670 ret->distance = distance;
673 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
674 k_buckets[peer_bucket].tail, ret);
675 k_buckets[peer_bucket].peers_size++;
676 closest_bucket = GNUNET_MAX (closest_bucket, peer_bucket);
677 if ((peer_bucket > 0) && (k_buckets[peer_bucket].peers_size <= bucket_size))
679 ret->preference_task =
680 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
683 GNUNET_assert (GNUNET_OK ==
684 GNUNET_CONTAINER_multipeermap_put (all_known_peers,
686 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
687 if (1 == GNUNET_CONTAINER_multipeermap_size (all_known_peers) &&
688 (GNUNET_YES != disable_try_connect))
690 /* got a first connection, good time to start with FIND PEER requests... */
691 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
697 * Method called whenever a peer disconnects.
700 * @param peer peer identity this notification is about
703 handle_core_disconnect (void *cls,
704 const struct GNUNET_PeerIdentity *peer)
706 struct PeerInfo *to_remove;
708 struct P2PPendingMessage *pos;
709 unsigned int discarded;
710 struct GNUNET_HashCode phash;
712 /* Check for disconnect from self message */
713 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
715 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
719 GNUNET_CONTAINER_multipeermap_get (all_known_peers, peer);
720 if (NULL == to_remove)
725 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# peers connected"), -1,
727 GNUNET_assert (GNUNET_YES ==
728 GNUNET_CONTAINER_multipeermap_remove (all_known_peers,
731 if (NULL != to_remove->preference_task)
733 GNUNET_SCHEDULER_cancel (to_remove->preference_task);
734 to_remove->preference_task = NULL;
736 GNUNET_CRYPTO_hash (peer,
737 sizeof (struct GNUNET_PeerIdentity),
739 current_bucket = find_bucket (&phash);
740 GNUNET_assert (current_bucket >= 0);
741 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
742 k_buckets[current_bucket].tail, to_remove);
743 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
744 k_buckets[current_bucket].peers_size--;
745 while ((closest_bucket > 0) && (k_buckets[closest_bucket].peers_size == 0))
748 if (to_remove->th != NULL)
750 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
751 to_remove->th = NULL;
754 while (NULL != (pos = to_remove->head))
756 GNUNET_CONTAINER_DLL_remove (to_remove->head, to_remove->tail, pos);
760 GNUNET_STATISTICS_update (GDS_stats,
762 ("# Queued messages discarded (peer disconnected)"),
763 discarded, GNUNET_NO);
764 GNUNET_free (to_remove);
769 * Called when core is ready to send a message we asked for
770 * out to the destination.
772 * @param cls the 'struct PeerInfo' of the target peer
773 * @param size number of bytes available in buf
774 * @param buf where the callee should write the message
775 * @return number of bytes written to buf
778 core_transmit_notify (void *cls, size_t size, void *buf)
780 struct PeerInfo *peer = cls;
782 struct P2PPendingMessage *pending;
787 while ((NULL != (pending = peer->head)) &&
788 (0 == GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value_us))
790 GNUNET_STATISTICS_update (GDS_stats,
792 ("# Messages dropped (CORE timeout)"),
795 peer->pending_count--;
796 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
797 GNUNET_free (pending);
801 /* no messages pending */
807 GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
808 GNUNET_CORE_PRIO_BEST_EFFORT,
809 GNUNET_TIME_absolute_get_remaining
810 (pending->timeout), &peer->id,
811 ntohs (pending->msg->size),
812 &core_transmit_notify, peer);
813 GNUNET_break (NULL != peer->th);
817 while ((NULL != (pending = peer->head)) &&
818 (size - off >= (msize = ntohs (pending->msg->size))))
820 GNUNET_STATISTICS_update (GDS_stats,
822 ("# Bytes transmitted to other peers"), msize,
824 memcpy (&cbuf[off], pending->msg, msize);
826 peer->pending_count--;
827 GNUNET_CONTAINER_DLL_remove (peer->head,
830 GNUNET_free (pending);
832 if (NULL != (pending = peer->head))
834 /* technically redundant, but easier to read and
835 avoids bogus gcc warning... */
836 msize = ntohs (pending->msg->size);
838 GNUNET_CORE_notify_transmit_ready (core_api,
840 GNUNET_CORE_PRIO_BEST_EFFORT,
841 GNUNET_TIME_absolute_get_remaining (pending->timeout),
844 &core_transmit_notify,
846 GNUNET_break (NULL != peer->th);
853 * Transmit all messages in the peer's message queue.
855 * @param peer message queue to process
858 process_peer_queue (struct PeerInfo *peer)
860 struct P2PPendingMessage *pending;
862 if (NULL == (pending = peer->head))
864 if (NULL != peer->th)
866 GNUNET_STATISTICS_update (GDS_stats,
868 ("# Bytes of bandwidth requested from core"),
869 ntohs (pending->msg->size), GNUNET_NO);
871 GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
872 GNUNET_CORE_PRIO_BEST_EFFORT,
873 GNUNET_TIME_absolute_get_remaining
874 (pending->timeout), &peer->id,
875 ntohs (pending->msg->size),
876 &core_transmit_notify, peer);
877 GNUNET_break (NULL != peer->th);
882 * To how many peers should we (on average) forward the request to
883 * obtain the desired target_replication count (on average).
885 * @param hop_count number of hops the message has traversed
886 * @param target_replication the number of total paths desired
887 * @return Some number of peers to forward the message to
890 get_forward_count (uint32_t hop_count, uint32_t target_replication)
892 uint32_t random_value;
893 uint32_t forward_count;
896 if (hop_count > GDS_NSE_get () * 4.0)
898 /* forcefully terminate */
899 GNUNET_STATISTICS_update (GDS_stats,
900 gettext_noop ("# requests TTL-dropped"),
904 if (hop_count > GDS_NSE_get () * 2.0)
906 /* Once we have reached our ideal number of hops, only forward to 1 peer */
909 /* bound by system-wide maximum */
911 GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
913 1 + (target_replication - 1.0) / (GDS_NSE_get () +
914 ((float) (target_replication - 1.0) *
916 /* Set forward count to floor of target_value */
917 forward_count = (uint32_t) target_value;
918 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
919 target_value = target_value - forward_count;
921 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
922 if (random_value < (target_value * UINT32_MAX))
924 return forward_count;
929 * Compute the distance between have and target as a 32-bit value.
930 * Differences in the lower bits must count stronger than differences
931 * in the higher bits.
935 * @return 0 if have==target, otherwise a number
936 * that is larger as the distance between
937 * the two hash codes increases
940 get_distance (const struct GNUNET_HashCode *target,
941 const struct GNUNET_HashCode *have)
948 /* We have to represent the distance between two 2^9 (=512)-bit
949 * numbers as a 2^5 (=32)-bit number with "0" being used for the
950 * two numbers being identical; furthermore, we need to
951 * guarantee that a difference in the number of matching
952 * bits is always represented in the result.
954 * We use 2^32/2^9 numerical values to distinguish between
955 * hash codes that have the same LSB bit distance and
956 * use the highest 2^9 bits of the result to signify the
957 * number of (mis)matching LSB bits; if we have 0 matching
958 * and hence 512 mismatching LSB bits we return -1 (since
959 * 512 itself cannot be represented with 9 bits) */
961 /* first, calculate the most significant 9 bits of our
962 * result, aka the number of LSBs */
963 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
964 /* bucket is now a value between 0 and 512 */
966 return 0; /* perfect match */
968 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
969 * below, we'd end up with max+1 (overflow)) */
971 /* calculate the most significant bits of the final result */
972 msb = (512 - bucket) << (32 - 9);
973 /* calculate the 32-9 least significant bits of the final result by
974 * looking at the differences in the 32-9 bits following the
975 * mismatching bit at 'bucket' */
978 (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
980 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
981 GNUNET_CRYPTO_hash_get_bit (have, i))
982 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
983 * last bit set will be 31 -- if
984 * i does not reach 512 first... */
991 * Check whether my identity is closer than any known peers. If a
992 * non-null bloomfilter is given, check if this is the closest peer
993 * that hasn't already been routed to.
995 * @param key hash code to check closeness to
996 * @param bloom bloomfilter, exclude these entries from the decision
997 * @return #GNUNET_YES if node location is closest,
998 * #GNUNET_NO otherwise.
1001 am_closest_peer (const struct GNUNET_HashCode *key,
1002 const struct GNUNET_CONTAINER_BloomFilter *bloom)
1008 struct PeerInfo *pos;
1009 struct GNUNET_HashCode phash;
1011 if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1013 bucket_num = find_bucket (key);
1014 GNUNET_assert (bucket_num >= 0);
1015 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, key);
1016 pos = k_buckets[bucket_num].head;
1018 while ((pos != NULL) && (count < bucket_size))
1020 GNUNET_CRYPTO_hash (&pos->id,
1021 sizeof (struct GNUNET_PeerIdentity),
1023 if ((bloom != NULL) &&
1025 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1028 continue; /* Skip already checked entries */
1030 other_bits = GNUNET_CRYPTO_hash_matching_bits (&phash, key);
1031 if (other_bits > bits)
1033 if (other_bits == bits) /* We match the same number of bits */
1037 /* No peers closer, we are the closest! */
1043 * Select a peer from the routing table that would be a good routing
1044 * destination for sending a message for "key". The resulting peer
1045 * must not be in the set of blocked peers.<p>
1047 * Note that we should not ALWAYS select the closest peer to the
1048 * target, peers further away from the target should be chosen with
1049 * exponentially declining probability.
1051 * FIXME: double-check that this is fine
1054 * @param key the key we are selecting a peer to route to
1055 * @param bloom a bloomfilter containing entries this request has seen already
1056 * @param hops how many hops has this message traversed thus far
1057 * @return Peer to route to, or NULL on error
1059 static struct PeerInfo *
1060 select_peer (const struct GNUNET_HashCode * key,
1061 const struct GNUNET_CONTAINER_BloomFilter *bloom, uint32_t hops)
1065 unsigned int selected;
1066 struct PeerInfo *pos;
1068 unsigned int smallest_distance;
1069 struct PeerInfo *chosen;
1070 struct GNUNET_HashCode phash;
1072 if (hops >= GDS_NSE_get ())
1074 /* greedy selection (closest peer that is not in bloomfilter) */
1075 smallest_distance = UINT_MAX;
1077 for (bc = 0; bc <= closest_bucket; bc++)
1079 pos = k_buckets[bc].head;
1081 while ((pos != NULL) && (count < bucket_size))
1083 GNUNET_CRYPTO_hash (&pos->id,
1084 sizeof (struct GNUNET_PeerIdentity),
1086 if ((bloom == NULL) ||
1088 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1090 dist = get_distance (key, &phash);
1091 if (dist < smallest_distance)
1094 smallest_distance = dist;
1099 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1100 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1101 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1102 GNUNET_STATISTICS_update (GDS_stats,
1104 ("# Peers excluded from routing due to Bloomfilter"),
1106 dist = get_distance (key, &phash);
1107 if (dist < smallest_distance)
1110 smallest_distance = dist;
1118 GNUNET_STATISTICS_update (GDS_stats,
1119 gettext_noop ("# Peer selection failed"), 1,
1124 /* select "random" peer */
1125 /* count number of peers that are available and not filtered */
1127 for (bc = 0; bc <= closest_bucket; bc++)
1129 pos = k_buckets[bc].head;
1130 while ((pos != NULL) && (count < bucket_size))
1132 GNUNET_CRYPTO_hash (&pos->id,
1133 sizeof (struct GNUNET_PeerIdentity),
1135 if ((bloom != NULL) &&
1137 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1139 GNUNET_STATISTICS_update (GDS_stats,
1141 ("# Peers excluded from routing due to Bloomfilter"),
1143 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1144 "Excluded peer `%s' due to BF match in random routing for %s\n",
1145 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1147 continue; /* Ignore bloomfiltered peers */
1153 if (0 == count) /* No peers to select from! */
1155 GNUNET_STATISTICS_update (GDS_stats,
1156 gettext_noop ("# Peer selection failed"), 1,
1160 /* Now actually choose a peer */
1161 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1163 for (bc = 0; bc <= closest_bucket; bc++)
1165 for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next)
1167 GNUNET_CRYPTO_hash (&pos->id,
1168 sizeof (struct GNUNET_PeerIdentity),
1170 if ((bloom != NULL) &&
1172 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1174 continue; /* Ignore bloomfiltered peers */
1176 if (0 == selected--)
1186 * Compute the set of peers that the given request should be
1189 * @param key routing key
1190 * @param bloom bloom filter excluding peers as targets, all selected
1191 * peers will be added to the bloom filter
1192 * @param hop_count number of hops the request has traversed so far
1193 * @param target_replication desired number of replicas
1194 * @param targets where to store an array of target peers (to be
1195 * free'd by the caller)
1196 * @return number of peers returned in 'targets'.
1199 get_target_peers (const struct GNUNET_HashCode *key,
1200 struct GNUNET_CONTAINER_BloomFilter *bloom,
1201 uint32_t hop_count, uint32_t target_replication,
1202 struct PeerInfo ***targets)
1206 struct PeerInfo **rtargets;
1207 struct PeerInfo *nxt;
1208 struct GNUNET_HashCode nhash;
1210 GNUNET_assert (NULL != bloom);
1211 ret = get_forward_count (hop_count, target_replication);
1217 rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1218 for (off = 0; off < ret; off++)
1220 nxt = select_peer (key, bloom, hop_count);
1223 rtargets[off] = nxt;
1224 GNUNET_CRYPTO_hash (&nxt->id,
1225 sizeof (struct GNUNET_PeerIdentity),
1227 GNUNET_break (GNUNET_NO ==
1228 GNUNET_CONTAINER_bloomfilter_test (bloom,
1230 GNUNET_CONTAINER_bloomfilter_add (bloom, &nhash);
1232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1233 "Selected %u/%u peers at hop %u for %s (target was %u)\n", off,
1234 GNUNET_CONTAINER_multipeermap_size (all_known_peers),
1235 (unsigned int) hop_count, GNUNET_h2s (key), ret);
1238 GNUNET_free (rtargets);
1242 *targets = rtargets;
1243 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1244 "Forwarding query `%s' to %u peers (goal was %u peers)\n",
1253 * Perform a PUT operation. Forwards the given request to other
1254 * peers. Does not store the data locally. Does not give the
1255 * data to local clients. May do nothing if this is the only
1256 * peer in the network (or if we are the closest peer in the
1259 * @param type type of the block
1260 * @param options routing options
1261 * @param desired_replication_level desired replication count
1262 * @param expiration_time when does the content expire
1263 * @param hop_count how many hops has this message traversed so far
1264 * @param bf Bloom filter of peers this PUT has already traversed
1265 * @param key key for the content
1266 * @param put_path_length number of entries in @a put_path
1267 * @param put_path peers this request has traversed so far (if tracked)
1268 * @param data payload to store
1269 * @param data_size number of bytes in @a data
1270 * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1273 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1274 enum GNUNET_DHT_RouteOption options,
1275 uint32_t desired_replication_level,
1276 struct GNUNET_TIME_Absolute expiration_time,
1278 struct GNUNET_CONTAINER_BloomFilter *bf,
1279 const struct GNUNET_HashCode *key,
1280 unsigned int put_path_length,
1281 struct GNUNET_PeerIdentity *put_path,
1282 const void *data, size_t data_size)
1284 unsigned int target_count;
1286 struct PeerInfo **targets;
1287 struct PeerInfo *target;
1288 struct P2PPendingMessage *pending;
1290 struct PeerPutMessage *ppm;
1291 struct GNUNET_PeerIdentity *pp;
1292 struct GNUNET_HashCode thash;
1293 unsigned int skip_count;
1295 GNUNET_assert (NULL != bf);
1296 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1297 "Adding myself (%s) to PUT bloomfilter for %s\n",
1298 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1299 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity_hash);
1300 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1303 get_target_peers (key, bf, hop_count, desired_replication_level,
1305 if (0 == target_count)
1307 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1308 "Routing PUT for %s terminates after %u hops at %s\n",
1309 GNUNET_h2s (key), (unsigned int) hop_count,
1310 GNUNET_i2s (&my_identity));
1314 put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1315 sizeof (struct PeerPutMessage);
1316 if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1318 put_path_length = 0;
1319 msize = data_size + sizeof (struct PeerPutMessage);
1321 if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1324 GNUNET_free (targets);
1327 GNUNET_STATISTICS_update (GDS_stats,
1329 ("# PUT messages queued for transmission"),
1330 target_count, GNUNET_NO);
1332 for (i = 0; i < target_count; i++)
1334 target = targets[i];
1335 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1338 GNUNET_STATISTICS_update (GDS_stats,
1339 gettext_noop ("# P2P messages dropped due to full queue"),
1344 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1345 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1346 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1347 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1348 pending->importance = 0; /* FIXME */
1349 pending->timeout = expiration_time;
1350 ppm = (struct PeerPutMessage *) &pending[1];
1351 pending->msg = &ppm->header;
1352 ppm->header.size = htons (msize);
1353 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1354 ppm->options = htonl (options);
1355 ppm->type = htonl (type);
1356 ppm->hop_count = htonl (hop_count + 1);
1357 ppm->desired_replication_level = htonl (desired_replication_level);
1358 ppm->put_path_length = htonl (put_path_length);
1359 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1360 GNUNET_CRYPTO_hash (&target->id,
1361 sizeof (struct GNUNET_PeerIdentity),
1363 GNUNET_break (GNUNET_YES ==
1364 GNUNET_CONTAINER_bloomfilter_test (bf,
1366 GNUNET_assert (GNUNET_OK ==
1367 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1371 pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1372 memcpy (pp, put_path,
1373 sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1374 memcpy (&pp[put_path_length], data, data_size);
1375 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1376 target->pending_count++;
1377 process_peer_queue (target);
1379 GNUNET_free (targets);
1380 return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1385 * Perform a GET operation. Forwards the given request to other
1386 * peers. Does not lookup the key locally. May do nothing if this is
1387 * the only peer in the network (or if we are the closest peer in the
1390 * @param type type of the block
1391 * @param options routing options
1392 * @param desired_replication_level desired replication count
1393 * @param hop_count how many hops did this request traverse so far?
1394 * @param key key for the content
1395 * @param xquery extended query
1396 * @param xquery_size number of bytes in @a xquery
1397 * @param reply_bf bloomfilter to filter duplicates
1398 * @param reply_bf_mutator mutator for @a reply_bf
1399 * @param peer_bf filter for peers not to select (again)
1400 * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1403 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1404 enum GNUNET_DHT_RouteOption options,
1405 uint32_t desired_replication_level,
1406 uint32_t hop_count, const struct GNUNET_HashCode * key,
1407 const void *xquery, size_t xquery_size,
1408 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1409 uint32_t reply_bf_mutator,
1410 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1412 unsigned int target_count;
1414 struct PeerInfo **targets;
1415 struct PeerInfo *target;
1416 struct P2PPendingMessage *pending;
1418 struct PeerGetMessage *pgm;
1420 size_t reply_bf_size;
1421 struct GNUNET_HashCode thash;
1422 unsigned int skip_count;
1424 GNUNET_assert (NULL != peer_bf);
1425 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1428 get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1430 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1431 "Adding myself (%s) to GET bloomfilter for %s\n",
1432 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1433 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity_hash);
1434 if (0 == target_count)
1436 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1437 "Routing GET for %s terminates after %u hops at %s\n",
1438 GNUNET_h2s (key), (unsigned int) hop_count,
1439 GNUNET_i2s (&my_identity));
1442 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1443 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1444 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1447 GNUNET_free (targets);
1450 GNUNET_STATISTICS_update (GDS_stats,
1452 ("# GET messages queued for transmission"),
1453 target_count, GNUNET_NO);
1454 /* forward request */
1456 for (i = 0; i < target_count; i++)
1458 target = targets[i];
1459 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1462 GNUNET_STATISTICS_update (GDS_stats,
1463 gettext_noop ("# P2P messages dropped due to full queue"),
1468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1469 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1470 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1471 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1472 pending->importance = 0; /* FIXME */
1473 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1474 pgm = (struct PeerGetMessage *) &pending[1];
1475 pending->msg = &pgm->header;
1476 pgm->header.size = htons (msize);
1477 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1478 pgm->options = htonl (options);
1479 pgm->type = htonl (type);
1480 pgm->hop_count = htonl (hop_count + 1);
1481 pgm->desired_replication_level = htonl (desired_replication_level);
1482 pgm->xquery_size = htonl (xquery_size);
1483 pgm->bf_mutator = reply_bf_mutator;
1484 GNUNET_CRYPTO_hash (&target->id,
1485 sizeof (struct GNUNET_PeerIdentity),
1487 GNUNET_break (GNUNET_YES ==
1488 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1490 GNUNET_assert (GNUNET_OK ==
1491 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1495 xq = (char *) &pgm[1];
1496 memcpy (xq, xquery, xquery_size);
1497 if (NULL != reply_bf)
1498 GNUNET_assert (GNUNET_OK ==
1499 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1503 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1504 target->pending_count++;
1505 process_peer_queue (target);
1507 GNUNET_free (targets);
1508 return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1513 * Handle a reply (route to origin). Only forwards the reply back to
1514 * the given peer. Does not do local caching or forwarding to local
1517 * @param target neighbour that should receive the block (if still connected)
1518 * @param type type of the block
1519 * @param expiration_time when does the content expire
1520 * @param key key for the content
1521 * @param put_path_length number of entries in @a put_path
1522 * @param put_path peers the original PUT traversed (if tracked)
1523 * @param get_path_length number of entries in @a get_path
1524 * @param get_path peers this reply has traversed so far (if tracked)
1525 * @param data payload of the reply
1526 * @param data_size number of bytes in @a data
1529 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1530 enum GNUNET_BLOCK_Type type,
1531 struct GNUNET_TIME_Absolute expiration_time,
1532 const struct GNUNET_HashCode * key,
1533 unsigned int put_path_length,
1534 const struct GNUNET_PeerIdentity *put_path,
1535 unsigned int get_path_length,
1536 const struct GNUNET_PeerIdentity *get_path,
1537 const void *data, size_t data_size)
1539 struct PeerInfo *pi;
1540 struct P2PPendingMessage *pending;
1542 struct PeerResultMessage *prm;
1543 struct GNUNET_PeerIdentity *paths;
1546 data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1548 sizeof (struct GNUNET_PeerIdentity);
1549 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1551 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1553 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1554 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1559 pi = GNUNET_CONTAINER_multipeermap_get (all_known_peers, target);
1562 /* peer disconnected in the meantime, drop reply */
1565 if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1568 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1573 GNUNET_STATISTICS_update (GDS_stats,
1575 ("# RESULT messages queued for transmission"), 1,
1577 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1578 pending->importance = 0; /* FIXME */
1579 pending->timeout = expiration_time;
1580 prm = (struct PeerResultMessage *) &pending[1];
1581 pending->msg = &prm->header;
1582 prm->header.size = htons (msize);
1583 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1584 prm->type = htonl (type);
1585 prm->put_path_length = htonl (put_path_length);
1586 prm->get_path_length = htonl (get_path_length);
1587 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1589 paths = (struct GNUNET_PeerIdentity *) &prm[1];
1590 memcpy (paths, put_path,
1591 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1592 memcpy (&paths[put_path_length], get_path,
1593 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1594 memcpy (&paths[put_path_length + get_path_length], data, data_size);
1595 GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1596 pi->pending_count++;
1597 process_peer_queue (pi);
1602 * To be called on core init/fail.
1604 * @param cls service closure
1605 * @param identity the public identity of this peer
1608 core_init (void *cls,
1609 const struct GNUNET_PeerIdentity *identity)
1611 my_identity = *identity;
1612 GNUNET_CRYPTO_hash (identity,
1613 sizeof (struct GNUNET_PeerIdentity),
1619 * Core handler for p2p put requests.
1621 * @param cls closure
1622 * @param peer sender of the request
1623 * @param message message
1624 * @param peer peer identity this notification is about
1625 * @return #GNUNET_OK to keep the connection open,
1626 * #GNUNET_SYSERR to close it (signal serious error)
1629 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1630 const struct GNUNET_MessageHeader *message)
1632 const struct PeerPutMessage *put;
1633 const struct GNUNET_PeerIdentity *put_path;
1634 const void *payload;
1637 size_t payload_size;
1638 enum GNUNET_DHT_RouteOption options;
1639 struct GNUNET_CONTAINER_BloomFilter *bf;
1640 struct GNUNET_HashCode test_key;
1641 struct GNUNET_HashCode phash;
1644 msize = ntohs (message->size);
1645 if (msize < sizeof (struct PeerPutMessage))
1647 GNUNET_break_op (0);
1650 put = (const struct PeerPutMessage *) message;
1651 putlen = ntohl (put->put_path_length);
1653 sizeof (struct PeerPutMessage) +
1654 putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1656 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1658 GNUNET_break_op (0);
1661 GNUNET_STATISTICS_update (GDS_stats,
1662 gettext_noop ("# P2P PUT requests received"), 1,
1664 GNUNET_STATISTICS_update (GDS_stats,
1665 gettext_noop ("# P2P PUT bytes received"), msize,
1667 put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1668 payload = &put_path[putlen];
1669 options = ntohl (put->options);
1671 msize - (sizeof (struct PeerPutMessage) +
1672 putlen * sizeof (struct GNUNET_PeerIdentity));
1674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1675 GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1676 GNUNET_CRYPTO_hash (peer, sizeof (struct GNUNET_PeerIdentity), &phash);
1677 if (GNUNET_YES == log_route_details_stderr)
1681 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1682 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1683 "R5N PUT %s: %s->%s (%u, %u=>%u)\n",
1684 GNUNET_h2s (&put->key), GNUNET_i2s (peer), tmp,
1685 ntohl(put->hop_count),
1686 GNUNET_CRYPTO_hash_matching_bits (&phash, &put->key),
1687 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &put->key)
1691 switch (GNUNET_BLOCK_get_key
1692 (GDS_block_context, ntohl (put->type), payload, payload_size,
1696 if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1698 char *put_s = GNUNET_strdup (GNUNET_h2s_full (&put->key));
1699 GNUNET_break_op (0);
1700 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1701 "PUT with key `%s' for block with key %s\n",
1702 put_s, GNUNET_h2s_full (&test_key));
1703 GNUNET_free (put_s);
1708 GNUNET_break_op (0);
1711 /* cannot verify, good luck */
1714 if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
1716 switch (GNUNET_BLOCK_evaluate (GDS_block_context,
1718 GNUNET_BLOCK_EO_NONE,
1720 NULL, 0, /* bloom filer */
1721 NULL, 0, /* xquery */
1722 payload, payload_size))
1724 case GNUNET_BLOCK_EVALUATION_OK_MORE:
1725 case GNUNET_BLOCK_EVALUATION_OK_LAST:
1728 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1729 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1730 case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1731 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1732 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1733 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1735 GNUNET_break_op (0);
1740 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1741 GNUNET_CONSTANTS_BLOOMFILTER_K);
1742 GNUNET_break_op (GNUNET_YES ==
1743 GNUNET_CONTAINER_bloomfilter_test (bf, &phash));
1745 struct GNUNET_PeerIdentity pp[putlen + 1];
1747 /* extend 'put path' by sender */
1748 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1750 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1757 /* give to local clients */
1758 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1759 &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1760 payload_size, payload);
1762 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1763 (am_closest_peer (&put->key, bf)))
1764 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1765 (put->expiration_time), &put->key, putlen, pp,
1766 ntohl (put->type), payload_size, payload);
1767 /* route to other peers */
1768 forwarded = GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1769 ntohl (put->desired_replication_level),
1770 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1771 ntohl (put->hop_count), bf,
1773 pp, payload, payload_size);
1774 /* notify monitoring clients */
1775 GDS_CLIENTS_process_put (options
1776 | (GNUNET_OK == forwarded)
1777 ? GNUNET_DHT_RO_LAST_HOP : 0,
1779 ntohl (put->hop_count),
1780 ntohl (put->desired_replication_level),
1782 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1787 GNUNET_CONTAINER_bloomfilter_free (bf);
1793 * We have received a FIND PEER request. Send matching
1796 * @param sender sender of the FIND PEER request
1797 * @param key peers close to this key are desired
1798 * @param bf peers matching this bf are excluded
1799 * @param bf_mutator mutator for bf
1802 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1803 const struct GNUNET_HashCode * key,
1804 struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1807 struct PeerBucket *bucket;
1808 struct PeerInfo *peer;
1809 unsigned int choice;
1810 struct GNUNET_HashCode phash;
1811 struct GNUNET_HashCode mhash;
1812 const struct GNUNET_HELLO_Message *hello;
1814 /* first, check about our own HELLO */
1815 if (NULL != GDS_my_hello)
1817 GNUNET_BLOCK_mingle_hash (&my_identity_hash, bf_mutator, &mhash);
1819 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1821 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1822 GNUNET_TIME_relative_to_absolute
1824 key, 0, NULL, 0, NULL, GDS_my_hello,
1825 GNUNET_HELLO_size ((const struct
1826 GNUNET_HELLO_Message *)
1831 GNUNET_STATISTICS_update (GDS_stats,
1833 ("# FIND PEER requests ignored due to Bloomfilter"),
1839 GNUNET_STATISTICS_update (GDS_stats,
1841 ("# FIND PEER requests ignored due to lack of HELLO"),
1845 /* then, also consider sending a random HELLO from the closest bucket */
1846 if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1847 bucket_idx = closest_bucket;
1849 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1850 if (bucket_idx == GNUNET_SYSERR)
1852 bucket = &k_buckets[bucket_idx];
1853 if (bucket->peers_size == 0)
1856 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1857 peer = bucket->head;
1860 GNUNET_assert (NULL != peer);
1864 choice = bucket->peers_size;
1869 return; /* no non-masked peer available */
1871 peer = bucket->head;
1872 GNUNET_CRYPTO_hash (&peer->id, sizeof (struct GNUNET_PeerIdentity), &phash);
1873 GNUNET_BLOCK_mingle_hash (&phash, bf_mutator, &mhash);
1874 hello = GDS_HELLO_get (&peer->id);
1876 while ((hello == NULL) ||
1877 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1878 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1879 GNUNET_TIME_relative_to_absolute
1880 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1881 0, NULL, 0, NULL, hello,
1882 GNUNET_HELLO_size (hello));
1887 * Core handler for p2p get requests.
1889 * @param cls closure
1890 * @param peer sender of the request
1891 * @param message message
1892 * @return #GNUNET_OK to keep the connection open,
1893 * #GNUNET_SYSERR to close it (signal serious error)
1896 handle_dht_p2p_get (void *cls,
1897 const struct GNUNET_PeerIdentity *peer,
1898 const struct GNUNET_MessageHeader *message)
1900 struct PeerGetMessage *get;
1901 uint32_t xquery_size;
1902 size_t reply_bf_size;
1904 enum GNUNET_BLOCK_Type type;
1905 enum GNUNET_DHT_RouteOption options;
1906 enum GNUNET_BLOCK_EvaluationResult eval;
1907 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1908 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1910 struct GNUNET_HashCode phash;
1914 memcmp (peer, &my_identity,
1915 sizeof (struct GNUNET_PeerIdentity)));
1916 /* parse and validate message */
1917 msize = ntohs (message->size);
1918 if (msize < sizeof (struct PeerGetMessage))
1920 GNUNET_break_op (0);
1923 get = (struct PeerGetMessage *) message;
1924 xquery_size = ntohl (get->xquery_size);
1925 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1927 GNUNET_break_op (0);
1930 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1931 type = ntohl (get->type);
1932 options = ntohl (get->options);
1933 xquery = (const char *) &get[1];
1935 GNUNET_STATISTICS_update (GDS_stats,
1936 gettext_noop ("# P2P GET requests received"), 1,
1938 GNUNET_STATISTICS_update (GDS_stats,
1939 gettext_noop ("# P2P GET bytes received"), msize,
1941 GNUNET_CRYPTO_hash (peer,
1942 sizeof (struct GNUNET_PeerIdentity),
1944 if (GNUNET_YES == log_route_details_stderr)
1948 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1949 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1950 "R5N GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n",
1951 GNUNET_h2s (&get->key), GNUNET_i2s (peer), tmp,
1952 ntohl(get->hop_count),
1953 GNUNET_CRYPTO_hash_matching_bits (&phash, &get->key),
1954 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &get->key),
1955 ntohl(get->xquery_size), xquery);
1959 if (reply_bf_size > 0)
1961 GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1962 GNUNET_CONSTANTS_BLOOMFILTER_K);
1964 GNUNET_BLOCK_evaluate (GDS_block_context,
1966 GNUNET_BLOCK_EO_NONE,
1974 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1976 /* request invalid or block type not supported */
1977 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1978 if (NULL != reply_bf)
1979 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1983 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1984 GNUNET_CONSTANTS_BLOOMFILTER_K);
1985 GNUNET_break_op (GNUNET_YES ==
1986 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1988 /* remember request for routing replies */
1989 GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1990 reply_bf, get->bf_mutator);
1991 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1992 "GET for %s at %s after %u hops\n",
1993 GNUNET_h2s (&get->key),
1994 GNUNET_i2s (&my_identity),
1995 (unsigned int) ntohl (get->hop_count));
1996 /* local lookup (this may update the reply_bf) */
1997 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1998 (am_closest_peer (&get->key, peer_bf)))
2000 if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
2002 GNUNET_STATISTICS_update (GDS_stats,
2004 ("# P2P FIND PEER requests processed"), 1,
2006 handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
2011 GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
2012 &reply_bf, get->bf_mutator);
2017 GNUNET_STATISTICS_update (GDS_stats,
2018 gettext_noop ("# P2P GET requests ONLY routed"),
2022 /* P2P forwarding */
2023 forwarded = GNUNET_NO;
2024 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
2025 forwarded = GDS_NEIGHBOURS_handle_get (type, options,
2026 ntohl (get->desired_replication_level),
2027 ntohl (get->hop_count),
2032 get->bf_mutator, peer_bf);
2033 GDS_CLIENTS_process_get (options
2034 | (GNUNET_OK == forwarded)
2035 ? GNUNET_DHT_RO_LAST_HOP : 0,
2037 ntohl (get->hop_count),
2038 ntohl (get->desired_replication_level),
2044 if (NULL != reply_bf)
2045 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
2046 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
2052 * Core handler for p2p result messages.
2054 * @param cls closure
2055 * @param message message
2056 * @param peer peer identity this notification is about
2057 * @return #GNUNET_YES (do not cut p2p connection)
2060 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
2061 const struct GNUNET_MessageHeader *message)
2063 const struct PeerResultMessage *prm;
2064 const struct GNUNET_PeerIdentity *put_path;
2065 const struct GNUNET_PeerIdentity *get_path;
2067 uint32_t get_path_length;
2068 uint32_t put_path_length;
2071 enum GNUNET_BLOCK_Type type;
2073 /* parse and validate message */
2074 msize = ntohs (message->size);
2075 if (msize < sizeof (struct PeerResultMessage))
2077 GNUNET_break_op (0);
2080 prm = (struct PeerResultMessage *) message;
2081 put_path_length = ntohl (prm->put_path_length);
2082 get_path_length = ntohl (prm->get_path_length);
2084 sizeof (struct PeerResultMessage) + (get_path_length +
2086 sizeof (struct GNUNET_PeerIdentity)) ||
2088 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
2090 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
2092 GNUNET_break_op (0);
2095 put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
2096 get_path = &put_path[put_path_length];
2097 type = ntohl (prm->type);
2098 data = (const void *) &get_path[get_path_length];
2100 msize - (sizeof (struct PeerResultMessage) +
2102 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
2103 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
2105 GNUNET_STATISTICS_update (GDS_stats,
2106 gettext_noop ("# P2P RESULT bytes received"),
2108 if (GNUNET_YES == log_route_details_stderr)
2112 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
2113 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG, "R5N RESULT %s: %s->%s (%u)\n",
2114 GNUNET_h2s (&prm->key), GNUNET_i2s (peer), tmp,
2115 get_path_length + 1);
2118 /* if we got a HELLO, consider it for our own routing table */
2119 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
2121 const struct GNUNET_MessageHeader *h;
2122 struct GNUNET_PeerIdentity pid;
2125 /* Should be a HELLO, validate and consider using it! */
2126 if (data_size < sizeof (struct GNUNET_MessageHeader))
2128 GNUNET_break_op (0);
2132 if (data_size != ntohs (h->size))
2134 GNUNET_break_op (0);
2138 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
2140 GNUNET_break_op (0);
2143 if ((GNUNET_YES != disable_try_connect) &&
2144 0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
2146 struct GNUNET_HashCode pid_hash;
2148 GNUNET_CRYPTO_hash (&pid, sizeof (struct GNUNET_PeerIdentity), &pid_hash);
2149 bucket = find_bucket (&pid_hash);
2150 if ((bucket >= 0) &&
2151 (k_buckets[bucket].peers_size < bucket_size) &&
2152 (NULL != GDS_transport_handle))
2154 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
2155 GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid, NULL, NULL); /*FIXME TRY_CONNECT change */
2160 /* append 'peer' to 'get_path' */
2162 struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
2164 memcpy (xget_path, get_path,
2165 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2166 xget_path[get_path_length] = *peer;
2169 /* forward to local clients */
2170 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2171 &prm->key, get_path_length, xget_path,
2172 put_path_length, put_path, type, data_size, data);
2173 GDS_CLIENTS_process_get_resp (type,
2174 xget_path, get_path_length,
2175 put_path, put_path_length,
2176 GNUNET_TIME_absolute_ntoh (
2177 prm->expiration_time),
2181 if (GNUNET_YES == cache_results)
2183 struct GNUNET_PeerIdentity xput_path[get_path_length + 1 + put_path_length];
2185 memcpy (xput_path, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
2186 memcpy (&xput_path[put_path_length],
2188 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2190 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2192 get_path_length + put_path_length, xput_path,
2193 type, data_size, data);
2195 /* forward to other peers */
2196 GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2197 &prm->key, put_path_length, put_path, get_path_length,
2198 xget_path, data, data_size);
2206 * Initialize neighbours subsystem.
2208 * @return GNUNET_OK on success, GNUNET_SYSERR on error
2211 GDS_NEIGHBOURS_init ()
2213 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2214 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2215 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2216 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2219 unsigned long long temp_config_num;
2222 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2224 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2226 bucket_size = (unsigned int) temp_config_num;
2228 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "CACHE_RESULTS");
2230 log_route_details_stderr =
2231 (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO;
2232 atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
2234 GNUNET_CORE_connect (GDS_cfg, NULL, &core_init, &handle_core_connect,
2235 &handle_core_disconnect, NULL, GNUNET_NO, NULL,
2236 GNUNET_NO, core_handlers);
2237 if (core_api == NULL)
2238 return GNUNET_SYSERR;
2239 all_known_peers = GNUNET_CONTAINER_multipeermap_create (256, GNUNET_NO);
2245 * Shutdown neighbours subsystem.
2248 GDS_NEIGHBOURS_done ()
2250 if (NULL == core_api)
2252 GNUNET_CORE_disconnect (core_api);
2254 GNUNET_ATS_performance_done (atsAPI);
2256 GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (all_known_peers));
2257 GNUNET_CONTAINER_multipeermap_destroy (all_known_peers);
2258 all_known_peers = NULL;
2259 if (NULL != find_peer_task)
2261 GNUNET_SCHEDULER_cancel (find_peer_task);
2262 find_peer_task = NULL;
2267 * Get the ID of the local node.
2269 * @return identity of the local node
2271 struct GNUNET_PeerIdentity *
2272 GDS_NEIGHBOURS_get_id ()
2274 return &my_identity;
2278 /* end of gnunet-service-dht_neighbours.c */