2 This file is part of GNUnet.
3 (C) 2009, 2010, 2011 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_block_lib.h"
30 #include "gnunet_util_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"
53 * How many buckets will we allow total.
55 #define MAX_BUCKETS sizeof (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 * How often to update our preference levels for peers in our routing tables.
75 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
78 * How long at least to wait before sending another find peer request.
80 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
83 * How long at most to wait before sending another find peer request.
85 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10)
88 * How long at most to wait for transmission of a GET request to another peer?
90 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
93 GNUNET_NETWORK_STRUCT_BEGIN
101 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
103 struct GNUNET_MessageHeader header;
108 uint32_t options GNUNET_PACKED;
113 uint32_t type GNUNET_PACKED;
118 uint32_t hop_count GNUNET_PACKED;
121 * Replication level for this message
123 uint32_t desired_replication_level GNUNET_PACKED;
126 * Length of the PUT path that follows (if tracked).
128 uint32_t put_path_length GNUNET_PACKED;
131 * When does the content expire?
133 struct GNUNET_TIME_AbsoluteNBO expiration_time;
136 * Bloomfilter (for peer identities) to stop circular routes
138 char bloomfilter[DHT_BLOOM_SIZE];
141 * The key we are storing under.
145 /* put path (if tracked) */
155 struct PeerResultMessage
158 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
160 struct GNUNET_MessageHeader header;
165 uint32_t type GNUNET_PACKED;
168 * Length of the PUT path that follows (if tracked).
170 uint32_t put_path_length GNUNET_PACKED;
173 * Length of the GET path that follows (if tracked).
175 uint32_t get_path_length GNUNET_PACKED;
178 * When does the content expire?
180 struct GNUNET_TIME_AbsoluteNBO expiration_time;
183 * The key of the corresponding GET request.
187 /* put path (if tracked) */
189 /* get path (if tracked) */
199 struct PeerGetMessage
202 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_GET
204 struct GNUNET_MessageHeader header;
209 uint32_t options GNUNET_PACKED;
212 * Desired content type.
214 uint32_t type GNUNET_PACKED;
219 uint32_t hop_count GNUNET_PACKED;
222 * Desired replication level for this request.
224 uint32_t desired_replication_level GNUNET_PACKED;
227 * Size of the extended query.
229 uint32_t xquery_size;
232 * Bloomfilter mutator.
237 * Bloomfilter (for peer identities) to stop circular routes
239 char bloomfilter[DHT_BLOOM_SIZE];
242 * The key we are looking for.
248 /* result bloomfilter */
251 GNUNET_NETWORK_STRUCT_END
254 * Linked list of messages to send to a particular other peer.
256 struct P2PPendingMessage
259 * Pointer to next item in the list
261 struct P2PPendingMessage *next;
264 * Pointer to previous item in the list
266 struct P2PPendingMessage *prev;
269 * Message importance level. FIXME: used? useful?
271 unsigned int importance;
274 * When does this message time out?
276 struct GNUNET_TIME_Absolute timeout;
279 * Actual message to be sent, allocated at the end of the struct:
280 * // msg = (cast) &pm[1];
281 * // memcpy (&pm[1], data, len);
283 const struct GNUNET_MessageHeader *msg;
289 * Entry for a peer in a bucket.
294 * Next peer entry (DLL)
296 struct PeerInfo *next;
299 * Prev peer entry (DLL)
301 struct PeerInfo *prev;
304 * Count of outstanding messages for peer. FIXME: NEEDED?
305 * FIXME: bound queue size!?
307 unsigned int pending_count;
310 * Head of pending messages to be sent to this peer.
312 struct P2PPendingMessage *head;
315 * Tail of pending messages to be sent to this peer.
317 struct P2PPendingMessage *tail;
320 * Core handle for sending messages to this peer.
322 struct GNUNET_CORE_TransmitHandle *th;
325 * Task for scheduling preference updates
327 GNUNET_SCHEDULER_TaskIdentifier preference_task;
330 * What is the identity of the peer?
332 struct GNUNET_PeerIdentity id;
336 * What is the average latency for replies received?
338 struct GNUNET_TIME_Relative latency;
341 * Transport level distance to peer.
343 unsigned int distance;
350 * Peers are grouped into buckets.
357 struct PeerInfo *head;
362 struct PeerInfo *tail;
365 * Number of peers in the bucket.
367 unsigned int peers_size;
372 * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
374 static unsigned int closest_bucket;
377 * How many peers have we added since we sent out our last
380 static unsigned int newly_found_peers;
383 * The buckets. Array of size MAX_BUCKET_SIZE. Offset 0 means 0 bits matching.
385 static struct PeerBucket k_buckets[MAX_BUCKETS];
388 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
390 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
393 * Maximum size for each bucket.
395 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
398 * Task that sends FIND PEER requests.
400 static GNUNET_SCHEDULER_TaskIdentifier find_peer_task;
403 * Identity of this peer.
405 static struct GNUNET_PeerIdentity my_identity;
410 static struct GNUNET_CORE_Handle *coreAPI;
415 static struct GNUNET_ATS_PerformanceHandle *atsAPI;
420 * Find the optimal bucket for this key.
422 * @param hc the hashcode to compare our identity to
423 * @return the proper bucket index, or GNUNET_SYSERR
424 * on error (same hashcode)
427 find_bucket (const GNUNET_HashCode * hc)
431 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
432 if (bits == MAX_BUCKETS)
434 /* How can all bits match? Got my own ID? */
436 return GNUNET_SYSERR;
438 return MAX_BUCKETS - bits - 1;
443 * Let GNUnet core know that we like the given peer.
445 * @param cls the 'struct PeerInfo' of the peer
446 * @param tc scheduler context.
449 update_core_preference (void *cls,
450 const struct GNUNET_SCHEDULER_TaskContext *tc)
452 struct PeerInfo *peer = cls;
454 unsigned int matching;
457 peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
458 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
461 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
462 &peer->id.hashPubKey);
465 bucket = find_bucket (&peer->id.hashPubKey);
466 if (bucket == GNUNET_SYSERR)
470 GNUNET_assert (k_buckets[bucket].peers_size != 0);
471 preference = (1LL << matching) / k_buckets[bucket].peers_size;
475 peer->preference_task =
476 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
477 &update_core_preference, peer);
480 GNUNET_STATISTICS_update (GDS_stats,
481 gettext_noop ("# Preference updates given to core"),
483 GNUNET_ATS_change_preference (atsAPI, &peer->id,
484 GNUNET_ATS_PREFERENCE_BANDWIDTH,
485 (double) preference, GNUNET_ATS_PREFERENCE_END);
486 peer->preference_task =
487 GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
488 &update_core_preference, peer);
495 * Closure for 'add_known_to_bloom'.
497 struct BloomConstructorContext
500 * Bloom filter under construction.
502 struct GNUNET_CONTAINER_BloomFilter *bloom;
512 * Add each of the peers we already know to the bloom filter of
513 * the request so that we don't get duplicate HELLOs.
515 * @param cls the 'struct BloomConstructorContext'.
516 * @param key peer identity to add to the bloom filter
517 * @param value value the peer information (unused)
518 * @return GNUNET_YES (we should continue to iterate)
521 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
523 struct BloomConstructorContext *ctx = cls;
526 GNUNET_BLOCK_mingle_hash (key, ctx->bf_mutator, &mh);
527 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
528 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
529 GNUNET_h2s (key), ctx->bf_mutator);
530 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
536 * Task to send a find peer message for our own peer identifier
537 * so that we can find the closest peers in the network to ourselves
538 * and attempt to connect to them.
540 * @param cls closure for this task
541 * @param tc the context under which the task is running
544 send_find_peer_message (void *cls,
545 const struct GNUNET_SCHEDULER_TaskContext *tc)
547 struct GNUNET_TIME_Relative next_send_time;
548 struct BloomConstructorContext bcc;
549 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
551 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
552 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
554 if (newly_found_peers > bucket_size)
556 /* If we are finding many peers already, no need to send out our request right now! */
558 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
559 &send_find_peer_message, NULL);
560 newly_found_peers = 0;
564 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
566 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
567 GNUNET_CONSTANTS_BLOOMFILTER_K);
568 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers, &add_known_to_bloom,
570 GNUNET_STATISTICS_update (GDS_stats,
571 gettext_noop ("# FIND PEER messages initiated"), 1,
574 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
575 GNUNET_CONSTANTS_BLOOMFILTER_K);
576 // FIXME: pass priority!?
577 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
578 GNUNET_DHT_RO_FIND_PEER,
579 FIND_PEER_REPLICATION_LEVEL, 0,
580 &my_identity.hashPubKey, NULL, 0, bcc.bloom,
581 bcc.bf_mutator, peer_bf);
582 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
583 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
584 /* schedule next round */
585 next_send_time.rel_value =
586 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
587 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
588 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value /
589 (newly_found_peers + 1));
590 newly_found_peers = 0;
592 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
598 * Method called whenever a peer connects.
601 * @param peer peer identity this notification is about
602 * @param atsi performance data
603 * @param atsi_count number of records in 'atsi'
606 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
607 const struct GNUNET_ATS_Information *atsi,
608 unsigned int atsi_count)
610 struct PeerInfo *ret;
613 /* Check for connect to self message */
614 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
616 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connected %s to %s\n",
617 GNUNET_i2s (&my_identity), GNUNET_h2s (&peer->hashPubKey));
619 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
625 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# Peers connected"), 1,
627 peer_bucket = find_bucket (&peer->hashPubKey);
628 GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
629 ret = GNUNET_malloc (sizeof (struct PeerInfo));
631 ret->latency = latency;
632 ret->distance = distance;
635 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
636 k_buckets[peer_bucket].tail, ret);
637 k_buckets[peer_bucket].peers_size++;
638 closest_bucket = GNUNET_MAX (closest_bucket, peer_bucket);
639 if ((peer_bucket > 0) && (k_buckets[peer_bucket].peers_size <= bucket_size))
641 ret->preference_task =
642 GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
645 GNUNET_assert (GNUNET_OK ==
646 GNUNET_CONTAINER_multihashmap_put (all_known_peers,
647 &peer->hashPubKey, ret,
648 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
649 if (1 == GNUNET_CONTAINER_multihashmap_size (all_known_peers))
651 /* got a first connection, good time to start with FIND PEER requests... */
652 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message, NULL);
658 * Method called whenever a peer disconnects.
661 * @param peer peer identity this notification is about
664 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
666 struct PeerInfo *to_remove;
668 struct P2PPendingMessage *pos;
669 unsigned int discarded;
671 /* Check for disconnect from self message */
672 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
674 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Disconnected %s from %s\n",
675 GNUNET_i2s (&my_identity), GNUNET_h2s (&peer->hashPubKey));
677 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
678 if (NULL == to_remove)
683 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# Peers connected"), -1,
685 GNUNET_assert (GNUNET_YES ==
686 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
689 if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
691 GNUNET_SCHEDULER_cancel (to_remove->preference_task);
692 to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
694 current_bucket = find_bucket (&to_remove->id.hashPubKey);
695 GNUNET_assert (current_bucket >= 0);
696 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
697 k_buckets[current_bucket].tail, to_remove);
698 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
699 k_buckets[current_bucket].peers_size--;
700 while ((closest_bucket > 0) && (k_buckets[closest_bucket].peers_size == 0))
703 if (to_remove->th != NULL)
705 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
706 to_remove->th = NULL;
709 while (NULL != (pos = to_remove->head))
711 GNUNET_CONTAINER_DLL_remove (to_remove->head, to_remove->tail, pos);
715 GNUNET_STATISTICS_update (GDS_stats,
717 ("# Queued messages discarded (peer disconnected)"),
718 discarded, GNUNET_NO);
719 GNUNET_free (to_remove);
724 * Called when core is ready to send a message we asked for
725 * out to the destination.
727 * @param cls the 'struct PeerInfo' of the target peer
728 * @param size number of bytes available in buf
729 * @param buf where the callee should write the message
730 * @return number of bytes written to buf
733 core_transmit_notify (void *cls, size_t size, void *buf)
735 struct PeerInfo *peer = cls;
737 struct P2PPendingMessage *pending;
742 while ((NULL != (pending = peer->head)) &&
743 (GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value == 0))
745 peer->pending_count--;
746 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
747 GNUNET_free (pending);
751 /* no messages pending */
757 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
759 GNUNET_TIME_absolute_get_remaining
760 (pending->timeout), &peer->id,
761 ntohs (pending->msg->size),
762 &core_transmit_notify, peer);
763 GNUNET_break (NULL != peer->th);
767 while ((NULL != (pending = peer->head)) &&
768 (size - off >= (msize = ntohs (pending->msg->size))))
770 GNUNET_STATISTICS_update (GDS_stats,
772 ("# Bytes transmitted to other peers"), msize,
774 memcpy (&cbuf[off], pending->msg, msize);
776 peer->pending_count--;
777 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
778 GNUNET_free (pending);
780 if (peer->head != NULL)
783 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
785 GNUNET_TIME_absolute_get_remaining
786 (pending->timeout), &peer->id, msize,
787 &core_transmit_notify, peer);
788 GNUNET_break (NULL != peer->th);
795 * Transmit all messages in the peer's message queue.
797 * @param peer message queue to process
800 process_peer_queue (struct PeerInfo *peer)
802 struct P2PPendingMessage *pending;
804 if (NULL == (pending = peer->head))
806 if (NULL != peer->th)
808 GNUNET_STATISTICS_update (GDS_stats,
810 ("# Bytes of bandwdith requested from core"),
811 ntohs (pending->msg->size), GNUNET_NO);
813 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
815 GNUNET_TIME_absolute_get_remaining
816 (pending->timeout), &peer->id,
817 ntohs (pending->msg->size),
818 &core_transmit_notify, peer);
819 GNUNET_break (NULL != peer->th);
824 * To how many peers should we (on average) forward the request to
825 * obtain the desired target_replication count (on average).
827 * @param hop_count number of hops the message has traversed
828 * @param target_replication the number of total paths desired
829 * @return Some number of peers to forward the message to
832 get_forward_count (uint32_t hop_count, uint32_t target_replication)
834 uint32_t random_value;
835 uint32_t forward_count;
838 if (hop_count > GDS_NSE_get () * 6.0)
840 /* forcefully terminate */
843 if (hop_count > GDS_NSE_get () * 4.0)
845 /* Once we have reached our ideal number of hops, only forward to 1 peer */
848 /* bound by system-wide maximum */
850 GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
852 1 + (target_replication - 1.0) / (GDS_NSE_get () +
853 ((float) (target_replication - 1.0) *
855 /* Set forward count to floor of target_value */
856 forward_count = (uint32_t) target_value;
857 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
858 target_value = target_value - forward_count;
860 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
861 if (random_value < (target_value * UINT32_MAX))
863 return forward_count;
868 * Compute the distance between have and target as a 32-bit value.
869 * Differences in the lower bits must count stronger than differences
870 * in the higher bits.
872 * @return 0 if have==target, otherwise a number
873 * that is larger as the distance between
874 * the two hash codes increases
877 get_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
884 /* We have to represent the distance between two 2^9 (=512)-bit
885 * numbers as a 2^5 (=32)-bit number with "0" being used for the
886 * two numbers being identical; furthermore, we need to
887 * guarantee that a difference in the number of matching
888 * bits is always represented in the result.
890 * We use 2^32/2^9 numerical values to distinguish between
891 * hash codes that have the same LSB bit distance and
892 * use the highest 2^9 bits of the result to signify the
893 * number of (mis)matching LSB bits; if we have 0 matching
894 * and hence 512 mismatching LSB bits we return -1 (since
895 * 512 itself cannot be represented with 9 bits) */
897 /* first, calculate the most significant 9 bits of our
898 * result, aka the number of LSBs */
899 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
900 /* bucket is now a value between 0 and 512 */
902 return 0; /* perfect match */
904 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
905 * below, we'd end up with max+1 (overflow)) */
907 /* calculate the most significant bits of the final result */
908 msb = (512 - bucket) << (32 - 9);
909 /* calculate the 32-9 least significant bits of the final result by
910 * looking at the differences in the 32-9 bits following the
911 * mismatching bit at 'bucket' */
914 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
916 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
917 GNUNET_CRYPTO_hash_get_bit (have, i))
918 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
919 * last bit set will be 31 -- if
920 * i does not reach 512 first... */
927 * Check whether my identity is closer than any known peers. If a
928 * non-null bloomfilter is given, check if this is the closest peer
929 * that hasn't already been routed to.
931 * @param key hash code to check closeness to
932 * @param bloom bloomfilter, exclude these entries from the decision
933 * @return GNUNET_YES if node location is closest,
934 * GNUNET_NO otherwise.
937 am_closest_peer (const GNUNET_HashCode * key,
938 const struct GNUNET_CONTAINER_BloomFilter *bloom)
944 struct PeerInfo *pos;
946 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
948 bucket_num = find_bucket (key);
949 GNUNET_assert (bucket_num >= 0);
950 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
951 pos = k_buckets[bucket_num].head;
953 while ((pos != NULL) && (count < bucket_size))
955 if ((bloom != NULL) &&
957 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
960 continue; /* Skip already checked entries */
962 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
963 if (other_bits > bits)
965 if (other_bits == bits) /* We match the same number of bits */
969 /* No peers closer, we are the closest! */
975 * Select a peer from the routing table that would be a good routing
976 * destination for sending a message for "key". The resulting peer
977 * must not be in the set of blocked peers.<p>
979 * Note that we should not ALWAYS select the closest peer to the
980 * target, peers further away from the target should be chosen with
981 * exponentially declining probability.
983 * FIXME: double-check that this is fine
986 * @param key the key we are selecting a peer to route to
987 * @param bloom a bloomfilter containing entries this request has seen already
988 * @param hops how many hops has this message traversed thus far
989 * @return Peer to route to, or NULL on error
991 static struct PeerInfo *
992 select_peer (const GNUNET_HashCode * key,
993 const struct GNUNET_CONTAINER_BloomFilter *bloom, uint32_t hops)
997 unsigned int selected;
998 struct PeerInfo *pos;
1000 unsigned int smallest_distance;
1001 struct PeerInfo *chosen;
1003 if (hops >= GDS_NSE_get ())
1005 /* greedy selection (closest peer that is not in bloomfilter) */
1006 smallest_distance = UINT_MAX;
1008 for (bc = 0; bc <= closest_bucket; bc++)
1010 pos = k_buckets[bc].head;
1012 while ((pos != NULL) && (count < bucket_size))
1014 if ((bloom == NULL) ||
1016 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1018 dist = get_distance (key, &pos->id.hashPubKey);
1019 if (dist < smallest_distance)
1022 smallest_distance = dist;
1027 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1028 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1029 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1030 GNUNET_STATISTICS_update (GDS_stats,
1032 ("# Peers excluded from routing due to Bloomfilter"),
1040 GNUNET_STATISTICS_update (GDS_stats,
1041 gettext_noop ("# Peer selection failed"), 1,
1046 /* select "random" peer */
1047 /* count number of peers that are available and not filtered */
1049 for (bc = 0; bc <= closest_bucket; bc++)
1051 pos = k_buckets[bc].head;
1052 while ((pos != NULL) && (count < bucket_size))
1054 if ((bloom != NULL) &&
1056 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1058 GNUNET_STATISTICS_update (GDS_stats,
1060 ("# Peers excluded from routing due to Bloomfilter"),
1062 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1063 "Excluded peer `%s' due to BF match in random routing for %s\n",
1064 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1066 continue; /* Ignore bloomfiltered peers */
1072 if (count == 0) /* No peers to select from! */
1074 GNUNET_STATISTICS_update (GDS_stats,
1075 gettext_noop ("# Peer selection failed"), 1,
1079 /* Now actually choose a peer */
1080 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1082 for (bc = 0; bc <= closest_bucket; bc++)
1084 pos = k_buckets[bc].head;
1085 while ((pos != NULL) && (count < bucket_size))
1087 if ((bloom != NULL) &&
1089 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1092 continue; /* Ignore bloomfiltered peers */
1094 if (0 == selected--)
1105 * Compute the set of peers that the given request should be
1108 * @param key routing key
1109 * @param bloom bloom filter excluding peers as targets, all selected
1110 * peers will be added to the bloom filter
1111 * @param hop_count number of hops the request has traversed so far
1112 * @param target_replication desired number of replicas
1113 * @param targets where to store an array of target peers (to be
1114 * free'd by the caller)
1115 * @return number of peers returned in 'targets'.
1118 get_target_peers (const GNUNET_HashCode * key,
1119 struct GNUNET_CONTAINER_BloomFilter *bloom,
1120 uint32_t hop_count, uint32_t target_replication,
1121 struct PeerInfo ***targets)
1125 struct PeerInfo **rtargets;
1126 struct PeerInfo *nxt;
1128 GNUNET_assert (NULL != bloom);
1129 ret = get_forward_count (hop_count, target_replication);
1135 rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1136 for (off = 0; off < ret; off++)
1138 nxt = select_peer (key, bloom, hop_count);
1141 rtargets[off] = nxt;
1142 GNUNET_break (GNUNET_NO ==
1143 GNUNET_CONTAINER_bloomfilter_test (bloom,
1144 &nxt->id.hashPubKey));
1145 GNUNET_CONTAINER_bloomfilter_add (bloom, &rtargets[off]->id.hashPubKey);
1147 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1148 "Selected %u/%u peers at hop %u for %s (target was %u)\n", off,
1149 GNUNET_CONTAINER_multihashmap_size (all_known_peers),
1150 (unsigned int) hop_count, GNUNET_h2s (key), ret);
1153 GNUNET_free (rtargets);
1157 *targets = rtargets;
1163 * Perform a PUT operation. Forwards the given request to other
1164 * peers. Does not store the data locally. Does not give the
1165 * data to local clients. May do nothing if this is the only
1166 * peer in the network (or if we are the closest peer in the
1169 * @param type type of the block
1170 * @param options routing options
1171 * @param desired_replication_level desired replication count
1172 * @param expiration_time when does the content expire
1173 * @param hop_count how many hops has this message traversed so far
1174 * @param bf Bloom filter of peers this PUT has already traversed
1175 * @param key key for the content
1176 * @param put_path_length number of entries in put_path
1177 * @param put_path peers this request has traversed so far (if tracked)
1178 * @param data payload to store
1179 * @param data_size number of bytes in data
1182 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1183 enum GNUNET_DHT_RouteOption options,
1184 uint32_t desired_replication_level,
1185 struct GNUNET_TIME_Absolute expiration_time,
1187 struct GNUNET_CONTAINER_BloomFilter *bf,
1188 const GNUNET_HashCode * key,
1189 unsigned int put_path_length,
1190 struct GNUNET_PeerIdentity *put_path,
1191 const void *data, size_t data_size)
1193 unsigned int target_count;
1195 struct PeerInfo **targets;
1196 struct PeerInfo *target;
1197 struct P2PPendingMessage *pending;
1199 struct PeerPutMessage *ppm;
1200 struct GNUNET_PeerIdentity *pp;
1202 GNUNET_assert (NULL != bf);
1203 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1204 "Adding myself (%s) to PUT bloomfilter for %s\n",
1205 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1206 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1207 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1210 get_target_peers (key, bf, hop_count, desired_replication_level,
1212 if (0 == target_count)
1214 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1215 "Routing PUT for %s terminates after %u hops at %s\n",
1216 GNUNET_h2s (key), (unsigned int) hop_count,
1217 GNUNET_i2s (&my_identity));
1221 put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1222 sizeof (struct PeerPutMessage);
1223 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1225 put_path_length = 0;
1226 msize = data_size + sizeof (struct PeerPutMessage);
1228 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1231 GNUNET_free (targets);
1234 GNUNET_STATISTICS_update (GDS_stats,
1236 ("# PUT messages queued for transmission"),
1237 target_count, GNUNET_NO);
1238 for (i = 0; i < target_count; i++)
1240 target = targets[i];
1241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1242 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1243 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1244 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1245 pending->importance = 0; /* FIXME */
1246 pending->timeout = expiration_time;
1247 ppm = (struct PeerPutMessage *) &pending[1];
1248 pending->msg = &ppm->header;
1249 ppm->header.size = htons (msize);
1250 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1251 ppm->options = htonl (options);
1252 ppm->type = htonl (type);
1253 ppm->hop_count = htonl (hop_count + 1);
1254 ppm->desired_replication_level = htonl (desired_replication_level);
1255 ppm->put_path_length = htonl (put_path_length);
1256 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1257 GNUNET_break (GNUNET_YES ==
1258 GNUNET_CONTAINER_bloomfilter_test (bf,
1259 &target->id.hashPubKey));
1260 GNUNET_assert (GNUNET_OK ==
1261 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1265 pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1266 memcpy (pp, put_path,
1267 sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1268 memcpy (&pp[put_path_length], data, data_size);
1269 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1270 target->pending_count++;
1271 process_peer_queue (target);
1273 GNUNET_free (targets);
1278 * Perform a GET operation. Forwards the given request to other
1279 * peers. Does not lookup the key locally. May do nothing if this is
1280 * the only peer in the network (or if we are the closest peer in the
1283 * @param type type of the block
1284 * @param options routing options
1285 * @param desired_replication_level desired replication count
1286 * @param hop_count how many hops did this request traverse so far?
1287 * @param key key for the content
1288 * @param xquery extended query
1289 * @param xquery_size number of bytes in xquery
1290 * @param reply_bf bloomfilter to filter duplicates
1291 * @param reply_bf_mutator mutator for reply_bf
1292 * @param peer_bf filter for peers not to select (again)
1295 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1296 enum GNUNET_DHT_RouteOption options,
1297 uint32_t desired_replication_level,
1298 uint32_t hop_count, const GNUNET_HashCode * key,
1299 const void *xquery, size_t xquery_size,
1300 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1301 uint32_t reply_bf_mutator,
1302 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1304 unsigned int target_count;
1306 struct PeerInfo **targets;
1307 struct PeerInfo *target;
1308 struct P2PPendingMessage *pending;
1310 struct PeerGetMessage *pgm;
1312 size_t reply_bf_size;
1314 GNUNET_assert (NULL != peer_bf);
1315 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1318 get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1320 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1321 "Adding myself (%s) to GET bloomfilter for %s\n",
1322 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1323 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity.hashPubKey);
1324 if (0 == target_count)
1326 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1327 "Routing GET for %s terminates after %u hops at %s\n",
1328 GNUNET_h2s (key), (unsigned int) hop_count,
1329 GNUNET_i2s (&my_identity));
1332 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1333 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1334 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1337 GNUNET_free (targets);
1340 GNUNET_STATISTICS_update (GDS_stats,
1342 ("# GET messages queued for transmission"),
1343 target_count, GNUNET_NO);
1344 /* forward request */
1345 for (i = 0; i < target_count; i++)
1347 target = targets[i];
1348 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1349 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1350 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1351 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1352 pending->importance = 0; /* FIXME */
1353 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1354 pgm = (struct PeerGetMessage *) &pending[1];
1355 pending->msg = &pgm->header;
1356 pgm->header.size = htons (msize);
1357 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1358 pgm->options = htonl (options);
1359 pgm->type = htonl (type);
1360 pgm->hop_count = htonl (hop_count + 1);
1361 pgm->desired_replication_level = htonl (desired_replication_level);
1362 pgm->xquery_size = htonl (xquery_size);
1363 pgm->bf_mutator = reply_bf_mutator;
1364 GNUNET_break (GNUNET_YES ==
1365 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1366 &target->id.hashPubKey));
1367 GNUNET_assert (GNUNET_OK ==
1368 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1372 xq = (char *) &pgm[1];
1373 memcpy (xq, xquery, xquery_size);
1374 if (NULL != reply_bf)
1375 GNUNET_assert (GNUNET_OK ==
1376 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1380 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1381 target->pending_count++;
1382 process_peer_queue (target);
1384 GNUNET_free (targets);
1389 * Handle a reply (route to origin). Only forwards the reply back to
1390 * the given peer. Does not do local caching or forwarding to local
1393 * @param target neighbour that should receive the block (if still connected)
1394 * @param type type of the block
1395 * @param expiration_time when does the content expire
1396 * @param key key for the content
1397 * @param put_path_length number of entries in put_path
1398 * @param put_path peers the original PUT traversed (if tracked)
1399 * @param get_path_length number of entries in put_path
1400 * @param get_path peers this reply has traversed so far (if tracked)
1401 * @param data payload of the reply
1402 * @param data_size number of bytes in data
1405 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1406 enum GNUNET_BLOCK_Type type,
1407 struct GNUNET_TIME_Absolute expiration_time,
1408 const GNUNET_HashCode * key,
1409 unsigned int put_path_length,
1410 const struct GNUNET_PeerIdentity *put_path,
1411 unsigned int get_path_length,
1412 const struct GNUNET_PeerIdentity *get_path,
1413 const void *data, size_t data_size)
1415 struct PeerInfo *pi;
1416 struct P2PPendingMessage *pending;
1418 struct PeerResultMessage *prm;
1419 struct GNUNET_PeerIdentity *paths;
1422 data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1424 sizeof (struct GNUNET_PeerIdentity);
1425 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1427 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1429 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1430 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1435 pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers, &target->hashPubKey);
1438 /* peer disconnected in the meantime, drop reply */
1441 GNUNET_STATISTICS_update (GDS_stats,
1443 ("# RESULT messages queued for transmission"), 1,
1445 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1446 pending->importance = 0; /* FIXME */
1447 pending->timeout = expiration_time;
1448 prm = (struct PeerResultMessage *) &pending[1];
1449 pending->msg = &prm->header;
1450 prm->header.size = htons (msize);
1451 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1452 prm->type = htonl (type);
1453 prm->put_path_length = htonl (put_path_length);
1454 prm->get_path_length = htonl (get_path_length);
1455 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1457 paths = (struct GNUNET_PeerIdentity *) &prm[1];
1458 memcpy (paths, put_path,
1459 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1460 memcpy (&paths[put_path_length], get_path,
1461 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1462 memcpy (&paths[put_path_length + get_path_length], data, data_size);
1463 GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1464 pi->pending_count++;
1465 process_peer_queue (pi);
1470 * To be called on core init/fail.
1472 * @param cls service closure
1473 * @param server handle to the server for this service
1474 * @param identity the public identity of this peer
1477 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1478 const struct GNUNET_PeerIdentity *identity)
1480 GNUNET_assert (server != NULL);
1481 my_identity = *identity;
1486 * Core handler for p2p put requests.
1488 * @param cls closure
1489 * @param peer sender of the request
1490 * @param message message
1491 * @param peer peer identity this notification is about
1492 * @param atsi performance data
1493 * @param atsi_count number of records in 'atsi'
1494 * @return GNUNET_OK to keep the connection open,
1495 * GNUNET_SYSERR to close it (signal serious error)
1498 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1499 const struct GNUNET_MessageHeader *message,
1500 const struct GNUNET_ATS_Information *atsi,
1501 unsigned int atsi_count)
1503 const struct PeerPutMessage *put;
1504 const struct GNUNET_PeerIdentity *put_path;
1505 const void *payload;
1508 size_t payload_size;
1509 enum GNUNET_DHT_RouteOption options;
1510 struct GNUNET_CONTAINER_BloomFilter *bf;
1511 GNUNET_HashCode test_key;
1513 msize = ntohs (message->size);
1514 if (msize < sizeof (struct PeerPutMessage))
1516 GNUNET_break_op (0);
1519 put = (const struct PeerPutMessage *) message;
1520 putlen = ntohl (put->put_path_length);
1522 sizeof (struct PeerPutMessage) +
1523 putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1525 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1527 GNUNET_break_op (0);
1530 GNUNET_STATISTICS_update (GDS_stats,
1531 gettext_noop ("# P2P PUT requests received"), 1,
1533 put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1534 payload = &put_path[putlen];
1535 options = ntohl (put->options);
1537 msize - (sizeof (struct PeerPutMessage) +
1538 putlen * sizeof (struct GNUNET_PeerIdentity));
1539 switch (GNUNET_BLOCK_get_key
1540 (GDS_block_context, ntohl (put->type), payload, payload_size,
1544 if (0 != memcmp (&test_key, &put->key, sizeof (GNUNET_HashCode)))
1546 GNUNET_break_op (0);
1551 GNUNET_break_op (0);
1554 /* cannot verify, good luck */
1557 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1558 GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1559 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1560 GNUNET_CONSTANTS_BLOOMFILTER_K);
1561 GNUNET_break_op (GNUNET_YES ==
1562 GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1564 struct GNUNET_PeerIdentity pp[putlen + 1];
1566 /* extend 'put path' by sender */
1567 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1569 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1576 /* give to local clients */
1577 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1578 &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1579 payload_size, payload);
1581 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1582 (am_closest_peer (&put->key, bf)))
1583 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1584 (put->expiration_time), &put->key, putlen, pp,
1585 ntohl (put->type), payload_size, payload);
1586 /* route to other peers */
1587 GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1588 ntohl (put->desired_replication_level),
1589 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1590 ntohl (put->hop_count), bf, &put->key, putlen,
1591 pp, payload, payload_size);
1593 GNUNET_CONTAINER_bloomfilter_free (bf);
1594 GDS_CLIENTS_process_put (options,
1596 ntohl (put->hop_count),
1597 ntohl (put->desired_replication_level),
1599 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1608 * We have received a FIND PEER request. Send matching
1611 * @param sender sender of the FIND PEER request
1612 * @param key peers close to this key are desired
1613 * @param bf peers matching this bf are excluded
1614 * @param bf_mutator mutator for bf
1617 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1618 const GNUNET_HashCode * key,
1619 struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1622 struct PeerBucket *bucket;
1623 struct PeerInfo *peer;
1624 unsigned int choice;
1625 GNUNET_HashCode mhash;
1626 const struct GNUNET_HELLO_Message *hello;
1628 /* first, check about our own HELLO */
1629 if (NULL != GDS_my_hello)
1631 GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1633 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1635 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1636 GNUNET_TIME_relative_to_absolute
1637 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1638 key, 0, NULL, 0, NULL, GDS_my_hello,
1639 GNUNET_HELLO_size ((const struct
1640 GNUNET_HELLO_Message *)
1645 GNUNET_STATISTICS_update (GDS_stats,
1647 ("# FIND PEER requests ignored due to Bloomfilter"),
1653 GNUNET_STATISTICS_update (GDS_stats,
1655 ("# FIND PEER requests ignored due to lack of HELLO"),
1659 /* then, also consider sending a random HELLO from the closest bucket */
1660 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
1661 bucket_idx = closest_bucket;
1663 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1664 if (bucket_idx == GNUNET_SYSERR)
1666 bucket = &k_buckets[bucket_idx];
1667 if (bucket->peers_size == 0)
1670 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
1671 peer = bucket->head;
1674 GNUNET_assert (peer != NULL);
1678 choice = bucket->peers_size;
1683 return; /* no non-masked peer available */
1685 peer = bucket->head;
1686 GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1687 hello = GDS_HELLO_get (&peer->id);
1689 while ((hello == NULL) ||
1690 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
1691 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1692 GNUNET_TIME_relative_to_absolute
1693 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
1694 0, NULL, 0, NULL, hello,
1695 GNUNET_HELLO_size (hello));
1700 * Core handler for p2p get requests.
1702 * @param cls closure
1703 * @param peer sender of the request
1704 * @param message message
1705 * @param peer peer identity this notification is about
1706 * @param atsi performance data
1707 * @param atsi_count number of records in 'atsi'
1708 * @return GNUNET_OK to keep the connection open,
1709 * GNUNET_SYSERR to close it (signal serious error)
1712 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1713 const struct GNUNET_MessageHeader *message,
1714 const struct GNUNET_ATS_Information *atsi,
1715 unsigned int atsi_count)
1717 struct PeerGetMessage *get;
1718 uint32_t xquery_size;
1719 size_t reply_bf_size;
1721 enum GNUNET_BLOCK_Type type;
1722 enum GNUNET_DHT_RouteOption options;
1723 enum GNUNET_BLOCK_EvaluationResult eval;
1724 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1725 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1729 memcmp (peer, &my_identity,
1730 sizeof (struct GNUNET_PeerIdentity)));
1731 /* parse and validate message */
1732 msize = ntohs (message->size);
1733 if (msize < sizeof (struct PeerGetMessage))
1735 GNUNET_break_op (0);
1738 get = (struct PeerGetMessage *) message;
1739 xquery_size = ntohl (get->xquery_size);
1740 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1742 GNUNET_break_op (0);
1745 GNUNET_STATISTICS_update (GDS_stats,
1746 gettext_noop ("# P2P GET requests received"), 1,
1748 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1749 type = ntohl (get->type);
1750 options = ntohl (get->options);
1751 xquery = (const char *) &get[1];
1753 if (reply_bf_size > 0)
1755 GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
1756 GNUNET_CONSTANTS_BLOOMFILTER_K);
1758 GNUNET_BLOCK_evaluate (GDS_block_context, type, &get->key, &reply_bf,
1759 get->bf_mutator, xquery, xquery_size, NULL, 0);
1760 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1762 /* request invalid or block type not supported */
1763 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1764 if (NULL != reply_bf)
1765 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1769 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
1770 GNUNET_CONSTANTS_BLOOMFILTER_K);
1771 GNUNET_break_op (GNUNET_YES ==
1772 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1773 &peer->hashPubKey));
1774 /* remember request for routing replies */
1775 GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
1776 reply_bf, get->bf_mutator);
1777 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "GET for %s at %s after %u hops\n",
1778 GNUNET_h2s (&get->key), GNUNET_i2s (&my_identity),
1779 (unsigned int) ntohl (get->hop_count));
1780 /* local lookup (this may update the reply_bf) */
1781 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1782 (am_closest_peer (&get->key, peer_bf)))
1784 if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1786 GNUNET_STATISTICS_update (GDS_stats,
1788 ("# P2P FIND PEER requests processed"), 1,
1790 handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
1795 GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
1796 &reply_bf, get->bf_mutator);
1801 GNUNET_STATISTICS_update (GDS_stats,
1802 gettext_noop ("# P2P GET requests ONLY routed"),
1807 GDS_CLIENTS_process_get (options,
1809 ntohl(get->hop_count),
1810 ntohl(get->desired_replication_level),
1814 /* P2P forwarding */
1815 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1816 GDS_NEIGHBOURS_handle_get (type, options,
1817 ntohl (get->desired_replication_level),
1818 ntohl (get->hop_count), &get->key, xquery,
1819 xquery_size, reply_bf, get->bf_mutator, peer_bf);
1821 if (NULL != reply_bf)
1822 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1823 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
1829 * Core handler for p2p result messages.
1831 * @param cls closure
1832 * @param message message
1833 * @param peer peer identity this notification is about
1834 * @param atsi performance data
1835 * @param atsi_count number of records in 'atsi'
1836 * @return GNUNET_YES (do not cut p2p connection)
1839 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1840 const struct GNUNET_MessageHeader *message,
1841 const struct GNUNET_ATS_Information *atsi,
1842 unsigned int atsi_count)
1844 const struct PeerResultMessage *prm;
1845 const struct GNUNET_PeerIdentity *put_path;
1846 const struct GNUNET_PeerIdentity *get_path;
1848 uint32_t get_path_length;
1849 uint32_t put_path_length;
1852 enum GNUNET_BLOCK_Type type;
1854 /* parse and validate message */
1855 msize = ntohs (message->size);
1856 if (msize < sizeof (struct PeerResultMessage))
1858 GNUNET_break_op (0);
1861 prm = (struct PeerResultMessage *) message;
1862 put_path_length = ntohl (prm->put_path_length);
1863 get_path_length = ntohl (prm->get_path_length);
1865 sizeof (struct PeerResultMessage) + (get_path_length +
1867 sizeof (struct GNUNET_PeerIdentity)) ||
1869 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1871 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1873 GNUNET_break_op (0);
1876 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
1878 put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
1879 get_path = &put_path[put_path_length];
1880 type = ntohl (prm->type);
1881 data = (const void *) &get_path[get_path_length];
1883 msize - (sizeof (struct PeerResultMessage) +
1885 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1887 /* if we got a HELLO, consider it for our own routing table */
1888 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
1890 const struct GNUNET_MessageHeader *h;
1891 struct GNUNET_PeerIdentity pid;
1894 /* Should be a HELLO, validate and consider using it! */
1895 if (data_size < sizeof (struct GNUNET_MessageHeader))
1897 GNUNET_break_op (0);
1901 if (data_size != ntohs (h->size))
1903 GNUNET_break_op (0);
1907 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h, &pid))
1909 GNUNET_break_op (0);
1912 if (0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
1914 bucket = find_bucket (&pid.hashPubKey);
1915 if ((bucket >= 0) && (k_buckets[bucket].peers_size < bucket_size))
1917 if (NULL != GDS_transport_handle)
1919 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle, h, NULL, NULL);
1920 GNUNET_TRANSPORT_try_connect (GDS_transport_handle, &pid);
1926 /* append 'peer' to 'get_path' */
1928 struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
1930 memcpy (xget_path, get_path,
1931 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1932 xget_path[get_path_length] = *peer;
1935 /* forward to local clients */
1936 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
1937 &prm->key, get_path_length, xget_path,
1938 put_path_length, put_path, type, data_size, data);
1940 /* forward to other peers */
1941 GDS_ROUTING_process (type, GNUNET_TIME_absolute_ntoh (prm->expiration_time),
1942 &prm->key, put_path_length, put_path, get_path_length,
1943 xget_path, data, data_size);
1946 GDS_CLIENTS_process_get_resp (type,
1951 GNUNET_TIME_absolute_ntoh (
1952 prm->expiration_time),
1962 * Initialize neighbours subsystem.
1964 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1967 GDS_NEIGHBOURS_init ()
1969 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1970 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
1971 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
1972 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
1975 unsigned long long temp_config_num;
1978 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
1980 bucket_size = (unsigned int) temp_config_num;
1981 atsAPI = GNUNET_ATS_performance_init (GDS_cfg, NULL, NULL);
1983 GNUNET_CORE_connect (GDS_cfg, 1, NULL, &core_init, &handle_core_connect,
1984 &handle_core_disconnect, NULL, GNUNET_NO, NULL,
1985 GNUNET_NO, core_handlers);
1986 if (coreAPI == NULL)
1987 return GNUNET_SYSERR;
1988 all_known_peers = GNUNET_CONTAINER_multihashmap_create (256);
1994 * Shutdown neighbours subsystem.
1997 GDS_NEIGHBOURS_done ()
1999 if (coreAPI == NULL)
2001 GNUNET_CORE_disconnect (coreAPI);
2003 GNUNET_ATS_performance_done (atsAPI);
2005 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2006 GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2007 all_known_peers = NULL;
2008 if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2010 GNUNET_SCHEDULER_cancel (find_peer_task);
2011 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2016 * Get the ID of the local node.
2018 * @return identity of the local node
2020 struct GNUNET_PeerIdentity *
2021 GDS_NEIGHBOURS_get_id ()
2023 return &my_identity;
2027 /* end of gnunet-service-dht_neighbours.c */