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_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"
52 * How many buckets will we allow total.
54 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
57 * What is the maximum number of peers in a given bucket.
59 #define DEFAULT_BUCKET_SIZE 8
62 * Desired replication level for FIND PEER requests
64 #define FIND_PEER_REPLICATION_LEVEL 4
67 * Maximum allowed replication level for all requests.
69 #define MAXIMUM_REPLICATION_LEVEL 16
72 * How often to update our preference levels for peers in our routing tables.
74 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
77 * How long at least to wait before sending another find peer request.
79 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
82 * How long at most to wait before sending another find peer request.
84 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10)
87 * How long at most to wait for transmission of a GET request to another peer?
89 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
98 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
100 struct GNUNET_MessageHeader header;
105 uint32_t options GNUNET_PACKED;
110 uint32_t type GNUNET_PACKED;
115 uint32_t hop_count GNUNET_PACKED;
118 * Replication level for this message
120 uint32_t desired_replication_level GNUNET_PACKED;
123 * Length of the PUT path that follows (if tracked).
125 uint32_t put_path_length GNUNET_PACKED;
128 * When does the content expire?
130 struct GNUNET_TIME_AbsoluteNBO expiration_time;
133 * Bloomfilter (for peer identities) to stop circular routes
135 char bloomfilter[DHT_BLOOM_SIZE];
138 * The key we are storing under.
142 /* put path (if tracked) */
152 struct PeerResultMessage
155 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
157 struct GNUNET_MessageHeader header;
162 uint32_t type GNUNET_PACKED;
165 * Length of the PUT path that follows (if tracked).
167 uint32_t put_path_length GNUNET_PACKED;
170 * Length of the GET path that follows (if tracked).
172 uint32_t get_path_length GNUNET_PACKED;
175 * When does the content expire?
177 struct GNUNET_TIME_AbsoluteNBO expiration_time;
180 * The key of the corresponding GET request.
184 /* put path (if tracked) */
186 /* get path (if tracked) */
196 struct PeerGetMessage
199 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_GET
201 struct GNUNET_MessageHeader header;
206 uint32_t options GNUNET_PACKED;
209 * Desired content type.
211 uint32_t type GNUNET_PACKED;
216 uint32_t hop_count GNUNET_PACKED;
219 * Desired replication level for this request.
221 uint32_t desired_replication_level GNUNET_PACKED;
224 * Size of the extended query.
226 uint32_t xquery_size;
229 * Bloomfilter mutator.
234 * Bloomfilter (for peer identities) to stop circular routes
236 char bloomfilter[DHT_BLOOM_SIZE];
239 * The key we are looking for.
245 /* result bloomfilter */
251 * Linked list of messages to send to a particular other peer.
253 struct P2PPendingMessage
256 * Pointer to next item in the list
258 struct P2PPendingMessage *next;
261 * Pointer to previous item in the list
263 struct P2PPendingMessage *prev;
266 * Message importance level. FIXME: used? useful?
268 unsigned int importance;
271 * When does this message time out?
273 struct GNUNET_TIME_Absolute timeout;
276 * Actual message to be sent, allocated at the end of the struct:
277 * // msg = (cast) &pm[1];
278 * // memcpy (&pm[1], data, len);
280 const struct GNUNET_MessageHeader *msg;
286 * Entry for a peer in a bucket.
291 * Next peer entry (DLL)
293 struct PeerInfo *next;
296 * Prev peer entry (DLL)
298 struct PeerInfo *prev;
301 * Count of outstanding messages for peer. FIXME: NEEDED?
302 * FIXME: bound queue size!?
304 unsigned int pending_count;
307 * Head of pending messages to be sent to this peer.
309 struct P2PPendingMessage *head;
312 * Tail of pending messages to be sent to this peer.
314 struct P2PPendingMessage *tail;
317 * Core handle for sending messages to this peer.
319 struct GNUNET_CORE_TransmitHandle *th;
322 * Preference update context
324 struct GNUNET_CORE_InformationRequestContext *info_ctx;
327 * Task for scheduling preference updates
329 GNUNET_SCHEDULER_TaskIdentifier preference_task;
332 * What is the identity of the peer?
334 struct GNUNET_PeerIdentity id;
338 * What is the average latency for replies received?
340 struct GNUNET_TIME_Relative latency;
343 * Transport level distance to peer.
345 unsigned int distance;
352 * Peers are grouped into buckets.
359 struct PeerInfo *head;
364 struct PeerInfo *tail;
367 * Number of peers in the bucket.
369 unsigned int peers_size;
374 * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
376 static unsigned int closest_bucket;
379 * How many peers have we added since we sent out our last
382 static unsigned int newly_found_peers;
385 * The buckets. Array of size MAX_BUCKET_SIZE. Offset 0 means 0 bits matching.
387 static struct PeerBucket k_buckets[MAX_BUCKETS];
390 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
392 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
395 * Maximum size for each bucket.
397 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
400 * Task that sends FIND PEER requests.
402 static GNUNET_SCHEDULER_TaskIdentifier find_peer_task;
405 * Identity of this peer.
407 static struct GNUNET_PeerIdentity my_identity;
410 * Handle to GNUnet core.
412 static struct GNUNET_CORE_Handle *coreAPI;
417 * Find the optimal bucket for this key.
419 * @param hc the hashcode to compare our identity to
420 * @return the proper bucket index, or GNUNET_SYSERR
421 * on error (same hashcode)
424 find_bucket (const GNUNET_HashCode * hc)
428 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
429 if (bits == MAX_BUCKETS)
431 /* How can all bits match? Got my own ID? */
433 return GNUNET_SYSERR;
435 return MAX_BUCKETS - bits - 1;
440 * Let GNUnet core know that we like the given peer.
442 * @param cls the 'struct PeerInfo' of the peer
443 * @param tc scheduler context.
446 update_core_preference (void *cls,
447 const struct GNUNET_SCHEDULER_TaskContext *tc);
451 * Function called with statistics about the given peer.
454 * @param peer identifies the peer
455 * @param bpm_out set to the current bandwidth limit (sending) for this peer
456 * @param amount set to the amount that was actually reserved or unreserved;
457 * either the full requested amount or zero (no partial reservations)
458 * @param res_delay if the reservation could not be satisfied (amount was 0), how
459 * long should the client wait until re-trying?
460 * @param preference current traffic preference for the given peer
463 update_core_preference_finish (void *cls,
464 const struct GNUNET_PeerIdentity *peer,
465 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
467 struct GNUNET_TIME_Relative res_delay,
470 struct PeerInfo *peer_info = cls;
472 peer_info->info_ctx = NULL;
473 peer_info->preference_task
474 = GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
475 &update_core_preference, peer_info);
480 * Let GNUnet core know that we like the given peer.
482 * @param cls the 'struct PeerInfo' of the peer
483 * @param tc scheduler context.
486 update_core_preference (void *cls,
487 const struct GNUNET_SCHEDULER_TaskContext *tc)
489 struct PeerInfo *peer = cls;
491 unsigned int matching;
494 peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
495 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
498 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
499 &peer->id.hashPubKey);
502 bucket = find_bucket (&peer->id.hashPubKey);
503 if (bucket == GNUNET_SYSERR)
507 GNUNET_assert (k_buckets[bucket].peers_size != 0);
508 preference = (1LL << matching) / k_buckets[bucket].peers_size;
512 peer->preference_task
513 = GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
514 &update_core_preference, peer);
517 GNUNET_STATISTICS_update (GDS_stats,
518 gettext_noop ("# Preference updates given to core"), 1,
521 GNUNET_CORE_peer_change_preference (coreAPI, &peer->id,
522 GNUNET_TIME_UNIT_FOREVER_REL,
523 GNUNET_BANDWIDTH_VALUE_MAX, 0,
525 &update_core_preference_finish, peer);
530 * Closure for 'add_known_to_bloom'.
532 struct BloomConstructorContext
535 * Bloom filter under construction.
537 struct GNUNET_CONTAINER_BloomFilter *bloom;
547 * Add each of the peers we already know to the bloom filter of
548 * the request so that we don't get duplicate HELLOs.
550 * @param cls the 'struct BloomConstructorContext'.
551 * @param key peer identity to add to the bloom filter
552 * @param value value the peer information (unused)
553 * @return GNUNET_YES (we should continue to iterate)
556 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
558 struct BloomConstructorContext *ctx = cls;
561 GNUNET_BLOCK_mingle_hash (key, ctx->bf_mutator, &mh);
562 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
563 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
566 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
572 * Task to send a find peer message for our own peer identifier
573 * so that we can find the closest peers in the network to ourselves
574 * and attempt to connect to them.
576 * @param cls closure for this task
577 * @param tc the context under which the task is running
580 send_find_peer_message (void *cls,
581 const struct GNUNET_SCHEDULER_TaskContext *tc)
583 struct GNUNET_TIME_Relative next_send_time;
584 struct BloomConstructorContext bcc;
585 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
587 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
588 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
590 if (newly_found_peers > bucket_size)
592 /* If we are finding many peers already, no need to send out our request right now! */
593 find_peer_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
594 &send_find_peer_message, NULL);
595 newly_found_peers = 0;
598 bcc.bf_mutator = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
600 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, GNUNET_CONSTANTS_BLOOMFILTER_K);
601 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers,
604 GNUNET_STATISTICS_update (GDS_stats,
605 gettext_noop ("# FIND PEER messages initiated"), 1,
607 peer_bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
609 GNUNET_CONSTANTS_BLOOMFILTER_K);
610 // FIXME: pass priority!?
611 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
612 GNUNET_DHT_RO_FIND_PEER,
613 FIND_PEER_REPLICATION_LEVEL,
615 &my_identity.hashPubKey,
617 bcc.bloom, bcc.bf_mutator,
619 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
620 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
621 /* schedule next round */
622 next_send_time.rel_value =
623 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
624 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
625 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / (newly_found_peers+1));
626 newly_found_peers = 0;
627 find_peer_task = GNUNET_SCHEDULER_add_delayed (next_send_time,
628 &send_find_peer_message,
634 * Method called whenever a peer connects.
637 * @param peer peer identity this notification is about
638 * @param atsi performance data
641 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
642 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
644 struct PeerInfo *ret;
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,
651 "Connected %s to %s\n",
652 GNUNET_i2s (&my_identity),
653 GNUNET_h2s (&peer->hashPubKey));
655 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
661 GNUNET_STATISTICS_update (GDS_stats,
662 gettext_noop ("# Peers connected"), 1,
664 peer_bucket = find_bucket (&peer->hashPubKey);
665 GNUNET_assert ( (peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS) );
666 ret = GNUNET_malloc (sizeof (struct PeerInfo));
668 ret->latency = latency;
669 ret->distance = distance;
672 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
673 k_buckets[peer_bucket].tail, ret);
674 k_buckets[peer_bucket].peers_size++;
675 closest_bucket = GNUNET_MAX (closest_bucket,
677 if ( (peer_bucket > 0) &&
678 (k_buckets[peer_bucket].peers_size <= bucket_size) )
680 ret->preference_task = GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
683 GNUNET_assert (GNUNET_OK ==
684 GNUNET_CONTAINER_multihashmap_put (all_known_peers,
685 &peer->hashPubKey, ret,
686 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
687 if (1 == GNUNET_CONTAINER_multihashmap_size (all_known_peers))
689 /* got a first connection, good time to start with FIND PEER requests... */
690 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message,
697 * Method called whenever a peer disconnects.
700 * @param peer peer identity this notification is about
703 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
705 struct PeerInfo *to_remove;
707 struct P2PPendingMessage *pos;
708 unsigned int discarded;
710 /* Check for disconnect from self message */
711 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
713 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
714 "Disconnected %s from %s\n",
715 GNUNET_i2s (&my_identity),
716 GNUNET_h2s (&peer->hashPubKey));
718 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
719 if (NULL == to_remove)
724 GNUNET_STATISTICS_update (GDS_stats,
725 gettext_noop ("# Peers connected"), -1,
727 GNUNET_assert (GNUNET_YES ==
728 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
731 if (NULL != to_remove->info_ctx)
733 GNUNET_CORE_peer_change_preference_cancel (to_remove->info_ctx);
734 to_remove->info_ctx = NULL;
736 if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
738 GNUNET_SCHEDULER_cancel (to_remove->preference_task);
739 to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
741 current_bucket = find_bucket (&to_remove->id.hashPubKey);
742 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
743 k_buckets[current_bucket].tail,
745 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
746 k_buckets[current_bucket].peers_size--;
747 while ( (closest_bucket > 0) &&
748 (k_buckets[closest_bucket].peers_size == 0) )
751 if (to_remove->th != NULL)
753 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
754 to_remove->th = NULL;
757 while (NULL != (pos = to_remove->head))
759 GNUNET_CONTAINER_DLL_remove (to_remove->head,
765 GNUNET_STATISTICS_update (GDS_stats,
766 gettext_noop ("# Queued messages discarded (peer disconnected)"), discarded,
768 GNUNET_free (to_remove);
773 * Called when core is ready to send a message we asked for
774 * out to the destination.
776 * @param cls the 'struct PeerInfo' of the target peer
777 * @param size number of bytes available in buf
778 * @param buf where the callee should write the message
779 * @return number of bytes written to buf
782 core_transmit_notify (void *cls, size_t size, void *buf)
784 struct PeerInfo *peer = cls;
786 struct P2PPendingMessage *pending;
791 while ( (NULL != (pending = peer->head)) &&
792 (GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value == 0) )
794 peer->pending_count--;
795 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
796 GNUNET_free (pending);
800 /* no messages pending */
806 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
808 GNUNET_TIME_absolute_get_remaining (pending->timeout),
809 &peer->id, ntohs (pending->msg->size),
810 &core_transmit_notify, peer);
811 GNUNET_break (NULL != peer->th);
815 while ( (NULL != (pending = peer->head)) &&
816 (size - off >= (msize = ntohs (pending->msg->size))) )
818 GNUNET_STATISTICS_update (GDS_stats,
819 gettext_noop ("# Bytes transmitted to other peers"), msize,
821 memcpy (&cbuf[off], pending->msg, msize);
823 peer->pending_count--;
824 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
825 GNUNET_free (pending);
827 if (peer->head != NULL)
830 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
832 GNUNET_TIME_absolute_get_remaining (pending->timeout),
834 &core_transmit_notify, peer);
835 GNUNET_break (NULL != peer->th);
842 * Transmit all messages in the peer's message queue.
844 * @param peer message queue to process
847 process_peer_queue (struct PeerInfo *peer)
849 struct P2PPendingMessage *pending;
851 if (NULL == (pending = peer->head))
853 if (NULL != peer->th)
855 GNUNET_STATISTICS_update (GDS_stats,
856 gettext_noop ("# Bytes of bandwdith requested from core"),
857 ntohs (pending->msg->size),
860 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
862 GNUNET_TIME_absolute_get_remaining (pending->timeout),
864 ntohs (pending->msg->size),
865 &core_transmit_notify, peer);
866 GNUNET_break (NULL != peer->th);
871 * To how many peers should we (on average) forward the request to
872 * obtain the desired target_replication count (on average).
874 * @param hop_count number of hops the message has traversed
875 * @param target_replication the number of total paths desired
876 * @return Some number of peers to forward the message to
879 get_forward_count (uint32_t hop_count,
880 uint32_t target_replication)
882 uint32_t random_value;
883 uint32_t forward_count;
886 if (hop_count > GDS_NSE_get () * 6.0)
888 /* forcefully terminate */
891 if (hop_count > GDS_NSE_get () * 4.0)
893 /* Once we have reached our ideal number of hops, only forward to 1 peer */
896 /* bound by system-wide maximum */
897 target_replication = GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL,
900 1 + (target_replication - 1.0) / (GDS_NSE_get () +
901 ((float) (target_replication - 1.0) *
903 /* Set forward count to floor of target_value */
904 forward_count = (uint32_t) target_value;
905 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
906 target_value = target_value - forward_count;
908 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
909 if (random_value < (target_value * UINT32_MAX))
911 return forward_count;
916 * Compute the distance between have and target as a 32-bit value.
917 * Differences in the lower bits must count stronger than differences
918 * in the higher bits.
920 * @return 0 if have==target, otherwise a number
921 * that is larger as the distance between
922 * the two hash codes increases
925 get_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
932 /* We have to represent the distance between two 2^9 (=512)-bit
933 * numbers as a 2^5 (=32)-bit number with "0" being used for the
934 * two numbers being identical; furthermore, we need to
935 * guarantee that a difference in the number of matching
936 * bits is always represented in the result.
938 * We use 2^32/2^9 numerical values to distinguish between
939 * hash codes that have the same LSB bit distance and
940 * use the highest 2^9 bits of the result to signify the
941 * number of (mis)matching LSB bits; if we have 0 matching
942 * and hence 512 mismatching LSB bits we return -1 (since
943 * 512 itself cannot be represented with 9 bits) */
945 /* first, calculate the most significant 9 bits of our
946 * result, aka the number of LSBs */
947 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
948 /* bucket is now a value between 0 and 512 */
950 return 0; /* perfect match */
952 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
953 * below, we'd end up with max+1 (overflow)) */
955 /* calculate the most significant bits of the final result */
956 msb = (512 - bucket) << (32 - 9);
957 /* calculate the 32-9 least significant bits of the final result by
958 * looking at the differences in the 32-9 bits following the
959 * mismatching bit at 'bucket' */
962 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
964 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
965 GNUNET_CRYPTO_hash_get_bit (have, i))
966 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
967 * last bit set will be 31 -- if
968 * i does not reach 512 first... */
975 * Check whether my identity is closer than any known peers. If a
976 * non-null bloomfilter is given, check if this is the closest peer
977 * that hasn't already been routed to.
979 * @param key hash code to check closeness to
980 * @param bloom bloomfilter, exclude these entries from the decision
981 * @return GNUNET_YES if node location is closest,
982 * GNUNET_NO otherwise.
985 am_closest_peer (const GNUNET_HashCode *key,
986 const struct GNUNET_CONTAINER_BloomFilter *bloom)
992 struct PeerInfo *pos;
994 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
996 bucket_num = find_bucket (key);
997 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
998 pos = k_buckets[bucket_num].head;
1000 while ((pos != NULL) && (count < bucket_size))
1002 if ((bloom != NULL) &&
1004 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
1007 continue; /* Skip already checked entries */
1009 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
1010 if (other_bits > bits)
1012 if (other_bits == bits) /* We match the same number of bits */
1016 /* No peers closer, we are the closest! */
1022 * Select a peer from the routing table that would be a good routing
1023 * destination for sending a message for "key". The resulting peer
1024 * must not be in the set of blocked peers.<p>
1026 * Note that we should not ALWAYS select the closest peer to the
1027 * target, peers further away from the target should be chosen with
1028 * exponentially declining probability.
1030 * FIXME: double-check that this is fine
1033 * @param key the key we are selecting a peer to route to
1034 * @param bloom a bloomfilter containing entries this request has seen already
1035 * @param hops how many hops has this message traversed thus far
1036 * @return Peer to route to, or NULL on error
1038 static struct PeerInfo *
1039 select_peer (const GNUNET_HashCode *key,
1040 const struct GNUNET_CONTAINER_BloomFilter *bloom,
1045 unsigned int selected;
1046 struct PeerInfo *pos;
1048 unsigned int smallest_distance;
1049 struct PeerInfo *chosen;
1051 if (hops >= GDS_NSE_get ())
1053 /* greedy selection (closest peer that is not in bloomfilter) */
1054 smallest_distance = UINT_MAX;
1056 for (bc = 0; bc < closest_bucket; bc++)
1058 pos = k_buckets[bc].head;
1060 while ((pos != NULL) && (count < bucket_size))
1062 if ( (bloom == NULL) ||
1064 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1066 dist = get_distance (key, &pos->id.hashPubKey);
1067 if (dist < smallest_distance)
1070 smallest_distance = dist;
1075 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1076 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1077 GNUNET_i2s (&pos->id),
1079 GNUNET_STATISTICS_update (GDS_stats,
1080 gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1088 GNUNET_STATISTICS_update (GDS_stats,
1089 gettext_noop ("# Peer selection failed"), 1,
1094 /* select "random" peer */
1095 /* count number of peers that are available and not filtered */
1097 for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1099 pos = k_buckets[bc].head;
1100 while ((pos != NULL) && (count < bucket_size))
1102 if ( (bloom != NULL) &&
1104 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1106 GNUNET_STATISTICS_update (GDS_stats,
1107 gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1109 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1110 "Excluded peer `%s' due to BF match in random routing for %s\n",
1111 GNUNET_i2s (&pos->id),
1114 continue; /* Ignore bloomfiltered peers */
1120 if (count == 0) /* No peers to select from! */
1122 GNUNET_STATISTICS_update (GDS_stats,
1123 gettext_noop ("# Peer selection failed"), 1,
1127 /* Now actually choose a peer */
1128 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1130 for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1132 pos = k_buckets[bc].head;
1133 while ((pos != NULL) && (count < bucket_size))
1135 if ( (bloom != NULL) &&
1137 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1140 continue; /* Ignore bloomfiltered peers */
1142 if (0 == selected--)
1153 * Compute the set of peers that the given request should be
1156 * @param key routing key
1157 * @param bloom bloom filter excluding peers as targets, all selected
1158 * peers will be added to the bloom filter
1159 * @param hop_count number of hops the request has traversed so far
1160 * @param target_replication desired number of replicas
1161 * @param targets where to store an array of target peers (to be
1162 * free'd by the caller)
1163 * @return number of peers returned in 'targets'.
1166 get_target_peers (const GNUNET_HashCode *key,
1167 struct GNUNET_CONTAINER_BloomFilter *bloom,
1169 uint32_t target_replication,
1170 struct PeerInfo ***targets)
1174 struct PeerInfo **rtargets;
1175 struct PeerInfo *nxt;
1177 GNUNET_assert (NULL != bloom);
1178 ret = get_forward_count (hop_count, target_replication);
1184 rtargets = GNUNET_malloc (sizeof (struct PeerInfo*) * ret);
1185 for (off = 0; off < ret; off++)
1187 nxt = select_peer (key, bloom, hop_count);
1190 rtargets[off] = nxt;
1191 GNUNET_break (GNUNET_NO ==
1192 GNUNET_CONTAINER_bloomfilter_test (bloom, &nxt->id.hashPubKey));
1193 GNUNET_CONTAINER_bloomfilter_add (bloom, &rtargets[off]->id.hashPubKey);
1195 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1196 "Selected %u/%u peers at hop %u for %s (target was %u)\n",
1198 GNUNET_CONTAINER_multihashmap_size (all_known_peers),
1199 (unsigned int) hop_count,
1204 GNUNET_free (rtargets);
1208 *targets = rtargets;
1214 * Perform a PUT operation. Forwards the given request to other
1215 * peers. Does not store the data locally. Does not give the
1216 * data to local clients. May do nothing if this is the only
1217 * peer in the network (or if we are the closest peer in the
1220 * @param type type of the block
1221 * @param options routing options
1222 * @param desired_replication_level desired replication count
1223 * @param expiration_time when does the content expire
1224 * @param hop_count how many hops has this message traversed so far
1225 * @param bf Bloom filter of peers this PUT has already traversed
1226 * @param key key for the content
1227 * @param put_path_length number of entries in put_path
1228 * @param put_path peers this request has traversed so far (if tracked)
1229 * @param data payload to store
1230 * @param data_size number of bytes in data
1233 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1234 enum GNUNET_DHT_RouteOption options,
1235 uint32_t desired_replication_level,
1236 struct GNUNET_TIME_Absolute expiration_time,
1238 struct GNUNET_CONTAINER_BloomFilter *bf,
1239 const GNUNET_HashCode *key,
1240 unsigned int put_path_length,
1241 struct GNUNET_PeerIdentity *put_path,
1245 unsigned int target_count;
1247 struct PeerInfo **targets;
1248 struct PeerInfo *target;
1249 struct P2PPendingMessage *pending;
1251 struct PeerPutMessage *ppm;
1252 struct GNUNET_PeerIdentity *pp;
1254 GNUNET_assert (NULL != bf);
1255 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1256 "Adding myself (%s) to PUT bloomfilter for %s\n",
1257 GNUNET_i2s (&my_identity),
1259 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1260 GNUNET_STATISTICS_update (GDS_stats,
1261 gettext_noop ("# PUT requests routed"), 1,
1263 target_count = get_target_peers (key, bf, hop_count,
1264 desired_replication_level,
1266 if (0 == target_count)
1268 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1269 "Routing PUT for %s terminates after %u hops at %s\n",
1271 (unsigned int) hop_count,
1272 GNUNET_i2s (&my_identity));
1275 msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size + sizeof (struct PeerPutMessage);
1276 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1278 put_path_length = 0;
1279 msize = data_size + sizeof (struct PeerPutMessage);
1281 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1286 GNUNET_STATISTICS_update (GDS_stats,
1287 gettext_noop ("# PUT messages queued for transmission"), target_count,
1289 for (i=0;i<target_count;i++)
1291 target = targets[i];
1292 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1293 "Routing PUT for %s after %u hops to %s\n",
1295 (unsigned int) hop_count,
1296 GNUNET_i2s (&target->id));
1297 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1298 pending->importance = 0; /* FIXME */
1299 pending->timeout = expiration_time;
1300 ppm = (struct PeerPutMessage*) &pending[1];
1301 pending->msg = &ppm->header;
1302 ppm->header.size = htons (msize);
1303 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1304 ppm->options = htonl (options);
1305 ppm->type = htonl (type);
1306 ppm->hop_count = htonl (hop_count + 1);
1307 ppm->desired_replication_level = htonl (desired_replication_level);
1308 ppm->put_path_length = htonl (put_path_length);
1309 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1310 GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &target->id.hashPubKey));
1311 GNUNET_assert (GNUNET_OK ==
1312 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1316 pp = (struct GNUNET_PeerIdentity*) &ppm[1];
1317 memcpy (pp, put_path, sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1318 memcpy (&pp[put_path_length], data, data_size);
1319 GNUNET_CONTAINER_DLL_insert_tail (target->head,
1322 target->pending_count++;
1323 process_peer_queue (target);
1325 GNUNET_free (targets);
1330 * Perform a GET operation. Forwards the given request to other
1331 * peers. Does not lookup the key locally. May do nothing if this is
1332 * the only peer in the network (or if we are the closest peer in the
1335 * @param type type of the block
1336 * @param options routing options
1337 * @param desired_replication_level desired replication count
1338 * @param hop_count how many hops did this request traverse so far?
1339 * @param key key for the content
1340 * @param xquery extended query
1341 * @param xquery_size number of bytes in xquery
1342 * @param reply_bf bloomfilter to filter duplicates
1343 * @param reply_bf_mutator mutator for reply_bf
1344 * @param peer_bf filter for peers not to select (again)
1347 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1348 enum GNUNET_DHT_RouteOption options,
1349 uint32_t desired_replication_level,
1351 const GNUNET_HashCode *key,
1354 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1355 uint32_t reply_bf_mutator,
1356 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1358 unsigned int target_count;
1360 struct PeerInfo **targets;
1361 struct PeerInfo *target;
1362 struct P2PPendingMessage *pending;
1364 struct PeerGetMessage *pgm;
1366 size_t reply_bf_size;
1368 GNUNET_assert (NULL != peer_bf);
1369 GNUNET_STATISTICS_update (GDS_stats,
1370 gettext_noop ("# GET requests routed"), 1,
1372 target_count = get_target_peers (key, peer_bf, hop_count,
1373 desired_replication_level,
1375 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1376 "Adding myself (%s) to GET bloomfilter for %s\n",
1377 GNUNET_i2s (&my_identity),
1379 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity.hashPubKey);
1380 if (0 == target_count)
1382 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1383 "Routing GET for %s terminates after %u hops at %s\n",
1385 (unsigned int) hop_count,
1386 GNUNET_i2s (&my_identity));
1389 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1390 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1391 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1396 GNUNET_STATISTICS_update (GDS_stats,
1397 gettext_noop ("# GET messages queued for transmission"), target_count,
1399 /* forward request */
1400 for (i=0;i<target_count;i++)
1402 target = targets[i];
1403 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1404 "Routing GET for %s after %u hops to %s\n",
1406 (unsigned int) hop_count,
1407 GNUNET_i2s (&target->id));
1408 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1409 pending->importance = 0; /* FIXME */
1410 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1411 pgm = (struct PeerGetMessage*) &pending[1];
1412 pending->msg = &pgm->header;
1413 pgm->header.size = htons (msize);
1414 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1415 pgm->options = htonl (options);
1416 pgm->type = htonl (type);
1417 pgm->hop_count = htonl (hop_count + 1);
1418 pgm->desired_replication_level = htonl (desired_replication_level);
1419 pgm->xquery_size = htonl (xquery_size);
1420 pgm->bf_mutator = reply_bf_mutator;
1421 GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &target->id.hashPubKey));
1422 GNUNET_assert (GNUNET_OK ==
1423 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1427 xq = (char *) &pgm[1];
1428 memcpy (xq, xquery, xquery_size);
1429 if (NULL != reply_bf)
1430 GNUNET_assert (GNUNET_OK ==
1431 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1434 GNUNET_CONTAINER_DLL_insert_tail (target->head,
1437 target->pending_count++;
1438 process_peer_queue (target);
1440 GNUNET_free (targets);
1445 * Handle a reply (route to origin). Only forwards the reply back to
1446 * the given peer. Does not do local caching or forwarding to local
1449 * @param target neighbour that should receive the block (if still connected)
1450 * @param type type of the block
1451 * @param expiration_time when does the content expire
1452 * @param key key for the content
1453 * @param put_path_length number of entries in put_path
1454 * @param put_path peers the original PUT traversed (if tracked)
1455 * @param get_path_length number of entries in put_path
1456 * @param get_path peers this reply has traversed so far (if tracked)
1457 * @param data payload of the reply
1458 * @param data_size number of bytes in data
1461 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1462 enum GNUNET_BLOCK_Type type,
1463 struct GNUNET_TIME_Absolute expiration_time,
1464 const GNUNET_HashCode *key,
1465 unsigned int put_path_length,
1466 const struct GNUNET_PeerIdentity *put_path,
1467 unsigned int get_path_length,
1468 const struct GNUNET_PeerIdentity *get_path,
1472 struct PeerInfo *pi;
1473 struct P2PPendingMessage *pending;
1475 struct PeerResultMessage *prm;
1476 struct GNUNET_PeerIdentity *paths;
1478 msize = data_size + sizeof (struct PeerResultMessage) +
1479 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity);
1480 if ( (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1481 (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1482 (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1483 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE) )
1488 pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers,
1489 &target->hashPubKey);
1492 /* peer disconnected in the meantime, drop reply */
1495 GNUNET_STATISTICS_update (GDS_stats,
1496 gettext_noop ("# RESULT messages queued for transmission"), 1,
1498 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1499 pending->importance = 0; /* FIXME */
1500 pending->timeout = expiration_time;
1501 prm = (struct PeerResultMessage*) &pending[1];
1502 pending->msg = &prm->header;
1503 prm->header.size = htons (msize);
1504 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1505 prm->type = htonl (type);
1506 prm->put_path_length = htonl (put_path_length);
1507 prm->get_path_length = htonl (get_path_length);
1508 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1510 paths = (struct GNUNET_PeerIdentity*) &prm[1];
1511 memcpy (paths, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
1512 memcpy (&paths[put_path_length],
1513 get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1514 memcpy (&paths[put_path_length + get_path_length],
1516 GNUNET_CONTAINER_DLL_insert (pi->head,
1519 pi->pending_count++;
1520 process_peer_queue (pi);
1525 * To be called on core init/fail.
1527 * @param cls service closure
1528 * @param server handle to the server for this service
1529 * @param identity the public identity of this peer
1530 * @param publicKey the public key of this peer
1533 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1534 const struct GNUNET_PeerIdentity *identity,
1535 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1537 GNUNET_assert (server != NULL);
1538 my_identity = *identity;
1543 * Core handler for p2p put requests.
1545 * @param cls closure
1546 * @param peer sender of the request
1547 * @param message message
1548 * @param peer peer identity this notification is about
1549 * @param atsi performance data
1550 * @return GNUNET_OK to keep the connection open,
1551 * GNUNET_SYSERR to close it (signal serious error)
1554 handle_dht_p2p_put (void *cls,
1555 const struct GNUNET_PeerIdentity *peer,
1556 const struct GNUNET_MessageHeader *message,
1557 const struct GNUNET_TRANSPORT_ATS_Information
1560 const struct PeerPutMessage *put;
1561 const struct GNUNET_PeerIdentity *put_path;
1562 const void *payload;
1565 size_t payload_size;
1566 enum GNUNET_DHT_RouteOption options;
1567 struct GNUNET_CONTAINER_BloomFilter *bf;
1568 GNUNET_HashCode test_key;
1570 msize = ntohs (message->size);
1571 if (msize < sizeof (struct PeerPutMessage))
1573 GNUNET_break_op (0);
1576 put = (const struct PeerPutMessage*) message;
1577 putlen = ntohl (put->put_path_length);
1578 if ( (msize < sizeof (struct PeerPutMessage) + putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1579 (putlen > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1581 GNUNET_break_op (0);
1584 GNUNET_STATISTICS_update (GDS_stats,
1585 gettext_noop ("# P2P PUT requests received"), 1,
1587 put_path = (const struct GNUNET_PeerIdentity*) &put[1];
1588 payload = &put_path[putlen];
1589 options = ntohl (put->options);
1590 payload_size = msize - (sizeof (struct PeerPutMessage) +
1591 putlen * sizeof (struct GNUNET_PeerIdentity));
1592 switch (GNUNET_BLOCK_get_key (GDS_block_context,
1594 payload, payload_size,
1598 if (0 != memcmp (&test_key, &put->key, sizeof (GNUNET_HashCode)))
1600 GNUNET_break_op (0);
1605 GNUNET_break_op (0);
1608 /* cannot verify, good luck */
1611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1612 "PUT for %s at %s\n",
1613 GNUNET_h2s (&put->key),
1614 GNUNET_i2s (&my_identity));
1615 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter,
1617 GNUNET_CONSTANTS_BLOOMFILTER_K);
1618 GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1620 struct GNUNET_PeerIdentity pp[putlen+1];
1622 /* extend 'put path' by sender */
1623 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1625 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1632 /* give to local clients */
1633 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1642 if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1643 (am_closest_peer (&put->key,
1645 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1651 /* route to other peers */
1652 GDS_NEIGHBOURS_handle_put (ntohl (put->type),
1654 ntohl (put->desired_replication_level),
1655 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1656 ntohl (put->hop_count),
1663 GNUNET_CONTAINER_bloomfilter_free (bf);
1669 * We have received a FIND PEER request. Send matching
1672 * @param sender sender of the FIND PEER request
1673 * @param key peers close to this key are desired
1674 * @param bf peers matching this bf are excluded
1675 * @param bf_mutator mutator for bf
1678 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1679 const GNUNET_HashCode *key,
1680 struct GNUNET_CONTAINER_BloomFilter *bf,
1681 uint32_t bf_mutator)
1684 struct PeerBucket *bucket;
1685 struct PeerInfo *peer;
1686 unsigned int choice;
1687 GNUNET_HashCode mhash;
1688 const struct GNUNET_HELLO_Message *hello;
1690 /* first, check about our own HELLO */
1691 if (NULL != GDS_my_hello)
1693 GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1694 if ( (NULL == bf) ||
1695 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) )
1697 GDS_NEIGHBOURS_handle_reply (sender,
1698 GNUNET_BLOCK_TYPE_DHT_HELLO,
1699 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1704 GNUNET_HELLO_size ((const struct GNUNET_HELLO_Message*) GDS_my_hello));
1708 GNUNET_STATISTICS_update (GDS_stats,
1709 gettext_noop ("# FIND PEER requests ignored due to Bloomfilter"), 1,
1715 GNUNET_STATISTICS_update (GDS_stats,
1716 gettext_noop ("# FIND PEER requests ignored due to lack of HELLO"), 1,
1720 /* then, also consider sending a random HELLO from the closest bucket */
1721 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
1722 bucket_idx = closest_bucket;
1724 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1725 if (bucket_idx == GNUNET_SYSERR)
1727 bucket = &k_buckets[bucket_idx];
1728 if (bucket->peers_size == 0)
1730 choice = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1731 bucket->peers_size);
1732 peer = bucket->head;
1735 GNUNET_assert (peer != NULL);
1739 choice = bucket->peers_size;
1744 return; /* no non-masked peer available */
1746 peer = bucket->head;
1747 GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1748 hello = GDS_HELLO_get (&peer->id);
1750 while ( (hello == NULL) ||
1751 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) );
1752 GDS_NEIGHBOURS_handle_reply (sender,
1753 GNUNET_BLOCK_TYPE_DHT_HELLO,
1754 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1759 GNUNET_HELLO_size (hello));
1764 * Core handler for p2p get requests.
1766 * @param cls closure
1767 * @param peer sender of the request
1768 * @param message message
1769 * @param peer peer identity this notification is about
1770 * @param atsi performance data
1771 * @return GNUNET_OK to keep the connection open,
1772 * GNUNET_SYSERR to close it (signal serious error)
1775 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1776 const struct GNUNET_MessageHeader *message,
1777 const struct GNUNET_TRANSPORT_ATS_Information
1780 struct PeerGetMessage *get;
1781 uint32_t xquery_size;
1782 size_t reply_bf_size;
1784 enum GNUNET_BLOCK_Type type;
1785 enum GNUNET_DHT_RouteOption options;
1786 enum GNUNET_BLOCK_EvaluationResult eval;
1787 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1788 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1791 GNUNET_break (0 != memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)));
1792 /* parse and validate message */
1793 msize = ntohs (message->size);
1794 if (msize < sizeof (struct PeerGetMessage))
1796 GNUNET_break_op (0);
1799 get = (struct PeerGetMessage *) message;
1800 xquery_size = ntohl (get->xquery_size);
1801 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1803 GNUNET_break_op (0);
1806 GNUNET_STATISTICS_update (GDS_stats,
1807 gettext_noop ("# P2P GET requests received"), 1,
1809 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1810 type = ntohl (get->type);
1811 options = ntohl (get->options);
1812 xquery = (const char*) &get[1];
1814 if (reply_bf_size > 0)
1815 reply_bf = GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size],
1817 GNUNET_CONSTANTS_BLOOMFILTER_K);
1818 eval = GNUNET_BLOCK_evaluate (GDS_block_context,
1823 xquery, xquery_size,
1825 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1827 /* request invalid or block type not supported */
1828 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1829 if (NULL != reply_bf)
1830 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1834 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter,
1836 GNUNET_CONSTANTS_BLOOMFILTER_K);
1837 GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &peer->hashPubKey));
1838 /* remember request for routing replies */
1839 GDS_ROUTING_add (peer,
1843 xquery, xquery_size,
1844 reply_bf, get->bf_mutator);
1845 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1846 "GET for %s at %s after %u hops\n",
1847 GNUNET_h2s (&get->key),
1848 GNUNET_i2s (&my_identity),
1849 (unsigned int) ntohl (get->hop_count));
1850 /* local lookup (this may update the reply_bf) */
1851 if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1852 (am_closest_peer (&get->key,
1855 if ( (0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1857 GNUNET_STATISTICS_update (GDS_stats,
1858 gettext_noop ("# P2P FIND PEER requests processed"), 1,
1860 handle_find_peer (peer,
1867 eval = GDS_DATACACHE_handle_get (&get->key,
1869 xquery, xquery_size,
1876 GNUNET_STATISTICS_update (GDS_stats,
1877 gettext_noop ("# P2P GET requests ONLY routed"), 1,
1881 /* P2P forwarding */
1882 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1883 GDS_NEIGHBOURS_handle_get (type,
1885 ntohl (get->desired_replication_level),
1886 ntohl (get->hop_count),
1888 xquery, xquery_size,
1893 if (NULL != reply_bf)
1894 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1895 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
1901 * Core handler for p2p result messages.
1903 * @param cls closure
1904 * @param message message
1905 * @param peer peer identity this notification is about
1906 * @param atsi performance data
1907 * @return GNUNET_YES (do not cut p2p connection)
1910 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1911 const struct GNUNET_MessageHeader *message,
1912 const struct GNUNET_TRANSPORT_ATS_Information
1915 const struct PeerResultMessage *prm;
1916 const struct GNUNET_PeerIdentity *put_path;
1917 const struct GNUNET_PeerIdentity *get_path;
1919 uint32_t get_path_length;
1920 uint32_t put_path_length;
1923 enum GNUNET_BLOCK_Type type;
1925 /* parse and validate message */
1926 msize = ntohs (message->size);
1927 if (msize < sizeof (struct PeerResultMessage))
1929 GNUNET_break_op (0);
1932 prm = (struct PeerResultMessage *) message;
1933 put_path_length = ntohl (prm->put_path_length);
1934 get_path_length = ntohl (prm->get_path_length);
1935 if ( (msize < sizeof (struct PeerResultMessage) +
1936 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity)) ||
1937 (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1938 (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1940 GNUNET_break_op (0);
1943 GNUNET_STATISTICS_update (GDS_stats,
1944 gettext_noop ("# P2P RESULTS received"), 1,
1946 put_path = (const struct GNUNET_PeerIdentity*) &prm[1];
1947 get_path = &put_path[put_path_length];
1948 type = ntohl (prm->type);
1949 data = (const void*) &get_path[get_path_length];
1950 data_size = msize - (sizeof (struct PeerResultMessage) +
1951 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1953 /* if we got a HELLO, consider it for our own routing table */
1954 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
1956 const struct GNUNET_MessageHeader *h;
1957 struct GNUNET_PeerIdentity pid;
1960 /* Should be a HELLO, validate and consider using it! */
1961 if (data_size < sizeof (struct GNUNET_MessageHeader))
1963 GNUNET_break_op (0);
1967 if (data_size != ntohs (h->size))
1969 GNUNET_break_op (0);
1973 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message*) h,
1976 GNUNET_break_op (0);
1979 if (0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
1981 bucket = find_bucket (&pid.hashPubKey);
1982 if ( (bucket >= 0) &&
1983 (k_buckets[bucket].peers_size < bucket_size) )
1985 if (NULL != GDS_transport_handle)
1986 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle,
1988 (void) GNUNET_CORE_peer_request_connect (coreAPI,
1995 /* append 'peer' to 'get_path' */
1997 struct GNUNET_PeerIdentity xget_path[get_path_length+1];
1999 memcpy (xget_path, get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
2000 xget_path[get_path_length] = *peer;
2003 /* forward to local clients */
2004 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2014 /* forward to other peers */
2015 GDS_ROUTING_process (type,
2016 GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2030 * Initialize neighbours subsystem.
2032 * @return GNUNET_OK on success, GNUNET_SYSERR on error
2035 GDS_NEIGHBOURS_init ()
2037 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2038 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2039 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2040 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2043 unsigned long long temp_config_num;
2046 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2048 bucket_size = (unsigned int) temp_config_num;
2049 coreAPI = GNUNET_CORE_connect (GDS_cfg,
2053 &handle_core_connect,
2054 &handle_core_disconnect,
2055 NULL, /* Do we care about "status" updates? */
2059 if (coreAPI == NULL)
2060 return GNUNET_SYSERR;
2061 all_known_peers = GNUNET_CONTAINER_multihashmap_create (256);
2067 * Shutdown neighbours subsystem.
2070 GDS_NEIGHBOURS_done ()
2072 if (coreAPI == NULL)
2074 GNUNET_CORE_disconnect (coreAPI);
2076 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2077 GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2078 all_known_peers = NULL;
2079 if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2081 GNUNET_SCHEDULER_cancel (find_peer_task);
2082 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2087 /* end of gnunet-service-dht_neighbours.c */