2 This file is part of GNUnet.
3 Copyright (C) 2009-2015 GNUnet e.V.
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, USA.
22 * @file dht/gnunet-service-dht_neighbours.c
23 * @brief GNUnet DHT service's bucket and neighbour management code
24 * @author Christian Grothoff
25 * @author Nathan Evans
28 #include "gnunet_util_lib.h"
29 #include "gnunet_block_lib.h"
30 #include "gnunet_hello_lib.h"
31 #include "gnunet_constants.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_nse_service.h"
34 #include "gnunet_ats_service.h"
35 #include "gnunet_core_service.h"
36 #include "gnunet_datacache_lib.h"
37 #include "gnunet_transport_service.h"
38 #include "gnunet_hello_lib.h"
39 #include "gnunet_dht_service.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet-service-dht.h"
42 #include "gnunet-service-dht_clients.h"
43 #include "gnunet-service-dht_datacache.h"
44 #include "gnunet-service-dht_hello.h"
45 #include "gnunet-service-dht_neighbours.h"
46 #include "gnunet-service-dht_nse.h"
47 #include "gnunet-service-dht_routing.h"
50 #define LOG_TRAFFIC(kind,...) GNUNET_log_from (kind, "dht-traffic",__VA_ARGS__)
53 * How many buckets will we allow total.
55 #define MAX_BUCKETS sizeof (struct GNUNET_HashCode) * 8
58 * What is the maximum number of peers in a given bucket.
60 #define DEFAULT_BUCKET_SIZE 8
63 * Desired replication level for FIND PEER requests
65 #define FIND_PEER_REPLICATION_LEVEL 4
68 * Maximum allowed replication level for all requests.
70 #define MAXIMUM_REPLICATION_LEVEL 16
73 * Maximum allowed number of pending messages per peer.
75 #define MAXIMUM_PENDING_PER_PEER 64
78 * How 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 * Hello address expiration
95 extern struct GNUNET_TIME_Relative hello_expiration;
98 GNUNET_NETWORK_STRUCT_BEGIN
103 struct PeerPutMessage
106 * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
108 struct GNUNET_MessageHeader header;
113 uint32_t options GNUNET_PACKED;
118 uint32_t type GNUNET_PACKED;
123 uint32_t hop_count GNUNET_PACKED;
126 * Replication level for this message
128 uint32_t desired_replication_level GNUNET_PACKED;
131 * Length of the PUT path that follows (if tracked).
133 uint32_t put_path_length GNUNET_PACKED;
136 * When does the content expire?
138 struct GNUNET_TIME_AbsoluteNBO expiration_time;
141 * Bloomfilter (for peer identities) to stop circular routes
143 char bloomfilter[DHT_BLOOM_SIZE];
146 * The key we are storing under.
148 struct GNUNET_HashCode key;
150 /* put path (if tracked) */
160 struct PeerResultMessage
163 * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
165 struct GNUNET_MessageHeader header;
170 uint32_t type GNUNET_PACKED;
173 * Length of the PUT path that follows (if tracked).
175 uint32_t put_path_length GNUNET_PACKED;
178 * Length of the GET path that follows (if tracked).
180 uint32_t get_path_length GNUNET_PACKED;
183 * When does the content expire?
185 struct GNUNET_TIME_AbsoluteNBO expiration_time;
188 * The key of the corresponding GET request.
190 struct GNUNET_HashCode key;
192 /* put path (if tracked) */
194 /* get path (if tracked) */
204 struct PeerGetMessage
207 * Type: #GNUNET_MESSAGE_TYPE_DHT_P2P_GET
209 struct GNUNET_MessageHeader header;
214 uint32_t options GNUNET_PACKED;
217 * Desired content type.
219 uint32_t type GNUNET_PACKED;
224 uint32_t hop_count GNUNET_PACKED;
227 * Desired replication level for this request.
229 uint32_t desired_replication_level GNUNET_PACKED;
232 * Size of the extended query.
234 uint32_t xquery_size;
237 * Bloomfilter mutator.
242 * Bloomfilter (for peer identities) to stop circular routes
244 char bloomfilter[DHT_BLOOM_SIZE];
247 * The key we are looking for.
249 struct GNUNET_HashCode key;
253 /* result bloomfilter */
256 GNUNET_NETWORK_STRUCT_END
259 * Linked list of messages to send to a particular other peer.
261 struct P2PPendingMessage
264 * Pointer to next item in the list
266 struct P2PPendingMessage *next;
269 * Pointer to previous item in the list
271 struct P2PPendingMessage *prev;
274 * Message importance level. FIXME: used? useful?
276 unsigned int importance;
279 * When does this message time out?
281 struct GNUNET_TIME_Absolute timeout;
284 * Actual message to be sent, allocated at the end of the struct:
285 * // msg = (cast) &pm[1];
286 * // memcpy (&pm[1], data, len);
288 const struct GNUNET_MessageHeader *msg;
294 * Entry for a peer in a bucket.
299 * Next peer entry (DLL)
301 struct PeerInfo *next;
304 * Prev peer entry (DLL)
306 struct PeerInfo *prev;
309 * Count of outstanding messages for peer.
311 unsigned int pending_count;
314 * Head of pending messages to be sent to this peer.
316 struct P2PPendingMessage *head;
319 * Tail of pending messages to be sent to this peer.
321 struct P2PPendingMessage *tail;
324 * Core handle for sending messages to this peer.
326 struct GNUNET_CORE_TransmitHandle *th;
329 * What is the identity of the peer?
331 struct GNUNET_PeerIdentity id;
335 * What is the average latency for replies received?
337 struct GNUNET_TIME_Relative latency;
340 * Transport level distance to peer.
342 unsigned int distance;
349 * Peers are grouped into buckets.
356 struct PeerInfo *head;
361 struct PeerInfo *tail;
364 * Number of peers in the bucket.
366 unsigned int peers_size;
371 * Information about a peer that we would like to connect to.
377 * Handle to active HELLO offer operation, or NULL.
379 struct GNUNET_TRANSPORT_OfferHelloHandle *oh;
382 * Handle to active connectivity suggestion operation, or NULL.
384 struct GNUNET_ATS_ConnectivitySuggestHandle *sh;
387 * How much would we like to connect to this peer?
394 * Do we cache all results that we are routing in the local datacache?
396 static int cache_results;
399 * Should routing details be logged to stderr (for debugging)?
401 static int log_route_details_stderr;
404 * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
406 static unsigned int closest_bucket;
409 * How many peers have we added since we sent out our last
412 static unsigned int newly_found_peers;
415 * Option for testing that disables the 'connect' function of the DHT.
417 static int disable_try_connect;
420 * The buckets. Array of size #MAX_BUCKETS. Offset 0 means 0 bits matching.
422 static struct PeerBucket k_buckets[MAX_BUCKETS];
425 * Hash map of all CORE-connected peers, for easy removal from
426 * #k_buckets on disconnect. Values are of type `struct PeerInfo`.
428 static struct GNUNET_CONTAINER_MultiPeerMap *all_connected_peers;
431 * Hash map of all peers we would like to be connected to.
432 * Values are of type `struct ConnectInfo`.
434 static struct GNUNET_CONTAINER_MultiPeerMap *all_desired_peers;
437 * Maximum size for each bucket.
439 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
442 * Task that sends FIND PEER requests.
444 static struct GNUNET_SCHEDULER_Task *find_peer_task;
447 * Identity of this peer.
449 static struct GNUNET_PeerIdentity my_identity;
452 * Hash of the identity of this peer.
454 static struct GNUNET_HashCode my_identity_hash;
459 static struct GNUNET_CORE_Handle *core_api;
462 * Handle to ATS connectivity.
464 static struct GNUNET_ATS_ConnectivityHandle *ats_ch;
468 * Find the optimal bucket for this key.
470 * @param hc the hashcode to compare our identity to
471 * @return the proper bucket index, or GNUNET_SYSERR
472 * on error (same hashcode)
475 find_bucket (const struct GNUNET_HashCode *hc)
479 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, hc);
480 if (bits == MAX_BUCKETS)
482 /* How can all bits match? Got my own ID? */
484 return GNUNET_SYSERR;
486 return MAX_BUCKETS - bits - 1;
491 * Function called when #GNUNET_TRANSPORT_offer_hello() is done.
492 * Clean up the "oh" field in the @a cls
494 * @param cls a `struct ConnectInfo`
497 offer_hello_done (void *cls)
499 struct ConnectInfo *ci = cls;
506 * Function called for all entries in #all_desired_peers to clean up.
509 * @param peer peer the entry is for
510 * @param value the value to remove
511 * @return #GNUNET_YES
514 free_connect_info (void *cls,
515 const struct GNUNET_PeerIdentity *peer,
518 struct ConnectInfo *ci = value;
520 GNUNET_assert (GNUNET_YES ==
521 GNUNET_CONTAINER_multipeermap_remove (all_desired_peers,
526 GNUNET_ATS_connectivity_suggest_cancel (ci->sh);
531 GNUNET_TRANSPORT_offer_hello_cancel (ci->oh);
540 * Consider if we want to connect to a given peer, and if so
541 * let ATS know. If applicable, the HELLO is offered to the
544 * @param pid peer to consider connectivity requirements for
545 * @param h a HELLO message, or NULL
548 try_connect (const struct GNUNET_PeerIdentity *pid,
549 const struct GNUNET_MessageHeader *h)
552 struct GNUNET_HashCode pid_hash;
553 struct ConnectInfo *ci;
556 GNUNET_CRYPTO_hash (pid,
557 sizeof (struct GNUNET_PeerIdentity),
559 bucket = find_bucket (&pid_hash);
562 ci = GNUNET_CONTAINER_multipeermap_get (all_desired_peers,
565 if (k_buckets[bucket].peers_size < bucket_size)
566 strength = (bucket_size - k_buckets[bucket].peers_size) * bucket;
568 strength = bucket; /* minimum value of connectivity */
570 GNUNET_CONTAINER_multipeermap_contains (all_connected_peers,
572 strength *= 2; /* double for connected peers */
573 else if (k_buckets[bucket].peers_size > bucket_size)
574 strength = 0; /* bucket full, we really do not care about more */
576 if ( (0 == strength) &&
579 /* release request */
580 GNUNET_assert (GNUNET_YES ==
581 free_connect_info (NULL,
588 ci = GNUNET_new (struct ConnectInfo);
589 GNUNET_assert (GNUNET_OK ==
590 GNUNET_CONTAINER_multipeermap_put (all_desired_peers,
593 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
595 if ( (NULL != GDS_transport_handle) &&
598 GNUNET_TRANSPORT_offer_hello_cancel (ci->oh);
599 if ( (NULL != GDS_transport_handle) &&
601 ci->oh = GNUNET_TRANSPORT_offer_hello (GDS_transport_handle,
605 if ( (NULL != ci->sh) &&
606 (ci->strength != strength) )
607 GNUNET_ATS_connectivity_suggest_cancel (ci->sh);
608 if (ci->strength != strength)
609 ci->sh = GNUNET_ATS_connectivity_suggest (ats_ch,
612 ci->strength = strength;
617 * Function called for each peer in #all_desired_peers during
618 * #update_connect_preferences() if we have reason to adjust
619 * the strength of our desire to keep connections to certain
620 * peers. Calls #try_connect() to update the calculations for
624 * @param pid peer to update
625 * @param value unused
626 * @return #GNUNET_YES (continue to iterate)
629 update_desire_strength (void *cls,
630 const struct GNUNET_PeerIdentity *pid,
633 try_connect (pid, NULL);
639 * Update our preferences for connectivity as given to ATS.
641 * @param cls the `struct PeerInfo` of the peer
642 * @param tc scheduler context.
645 update_connect_preferences ()
647 GNUNET_CONTAINER_multipeermap_iterate (all_desired_peers,
648 &update_desire_strength,
654 * Closure for #add_known_to_bloom().
656 struct BloomConstructorContext
659 * Bloom filter under construction.
661 struct GNUNET_CONTAINER_BloomFilter *bloom;
671 * Add each of the peers we already know to the bloom filter of
672 * the request so that we don't get duplicate HELLOs.
674 * @param cls the 'struct BloomConstructorContext'.
675 * @param key peer identity to add to the bloom filter
676 * @param value value the peer information (unused)
677 * @return #GNUNET_YES (we should continue to iterate)
680 add_known_to_bloom (void *cls,
681 const struct GNUNET_PeerIdentity *key,
684 struct BloomConstructorContext *ctx = cls;
685 struct GNUNET_HashCode key_hash;
686 struct GNUNET_HashCode mh;
688 GNUNET_CRYPTO_hash (key,
689 sizeof (struct GNUNET_PeerIdentity),
691 GNUNET_BLOCK_mingle_hash (&key_hash,
694 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
695 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
696 GNUNET_i2s (key), ctx->bf_mutator);
697 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
703 * Task to send a find peer message for our own peer identifier
704 * so that we can find the closest peers in the network to ourselves
705 * and attempt to connect to them.
707 * @param cls closure for this task
710 send_find_peer_message (void *cls)
712 struct GNUNET_TIME_Relative next_send_time;
713 struct BloomConstructorContext bcc;
714 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
716 find_peer_task = NULL;
717 if (newly_found_peers > bucket_size)
719 /* If we are finding many peers already, no need to send out our request right now! */
721 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
722 &send_find_peer_message, NULL);
723 newly_found_peers = 0;
727 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
729 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
730 GNUNET_CONSTANTS_BLOOMFILTER_K);
731 GNUNET_CONTAINER_multipeermap_iterate (all_connected_peers,
734 GNUNET_STATISTICS_update (GDS_stats,
735 gettext_noop ("# FIND PEER messages initiated"), 1,
738 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
739 GNUNET_CONSTANTS_BLOOMFILTER_K);
740 // FIXME: pass priority!?
741 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
742 GNUNET_DHT_RO_FIND_PEER,
743 FIND_PEER_REPLICATION_LEVEL, 0,
744 &my_identity_hash, NULL, 0, bcc.bloom,
745 bcc.bf_mutator, peer_bf);
746 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
747 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
748 /* schedule next round */
749 next_send_time.rel_value_us =
750 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value_us +
751 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
752 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value_us /
753 (newly_found_peers + 1));
754 newly_found_peers = 0;
756 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
762 * Method called whenever a peer connects.
765 * @param peer peer identity this notification is about
768 handle_core_connect (void *cls,
769 const struct GNUNET_PeerIdentity *peer)
771 struct PeerInfo *ret;
772 struct GNUNET_HashCode phash;
775 /* Check for connect to self message */
776 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
778 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
782 GNUNET_CONTAINER_multipeermap_contains (all_connected_peers,
788 GNUNET_STATISTICS_update (GDS_stats,
789 gettext_noop ("# peers connected"),
792 GNUNET_CRYPTO_hash (peer,
793 sizeof (struct GNUNET_PeerIdentity),
795 peer_bucket = find_bucket (&phash);
796 GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
797 ret = GNUNET_new (struct PeerInfo);
799 ret->latency = latency;
800 ret->distance = distance;
803 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
804 k_buckets[peer_bucket].tail,
806 k_buckets[peer_bucket].peers_size++;
807 closest_bucket = GNUNET_MAX (closest_bucket,
809 GNUNET_assert (GNUNET_OK ==
810 GNUNET_CONTAINER_multipeermap_put (all_connected_peers,
813 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
814 if ( (peer_bucket > 0) &&
815 (k_buckets[peer_bucket].peers_size <= bucket_size))
817 update_connect_preferences ();
820 if (1 == GNUNET_CONTAINER_multipeermap_size (all_connected_peers) &&
821 (GNUNET_YES != disable_try_connect))
823 /* got a first connection, good time to start with FIND PEER requests... */
824 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message,
831 * Method called whenever a peer disconnects.
834 * @param peer peer identity this notification is about
837 handle_core_disconnect (void *cls,
838 const struct GNUNET_PeerIdentity *peer)
840 struct PeerInfo *to_remove;
842 struct P2PPendingMessage *pos;
843 unsigned int discarded;
844 struct GNUNET_HashCode phash;
846 /* Check for disconnect from self message */
847 if (0 == memcmp (&my_identity,
849 sizeof (struct GNUNET_PeerIdentity)))
851 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
855 GNUNET_CONTAINER_multipeermap_get (all_connected_peers,
857 if (NULL == to_remove)
862 GNUNET_STATISTICS_update (GDS_stats,
863 gettext_noop ("# peers connected"),
866 GNUNET_assert (GNUNET_YES ==
867 GNUNET_CONTAINER_multipeermap_remove (all_connected_peers,
870 GNUNET_CRYPTO_hash (peer,
871 sizeof (struct GNUNET_PeerIdentity),
873 current_bucket = find_bucket (&phash);
874 GNUNET_assert (current_bucket >= 0);
875 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
876 k_buckets[current_bucket].tail,
878 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
879 k_buckets[current_bucket].peers_size--;
880 while ( (closest_bucket > 0) &&
881 (0 == k_buckets[closest_bucket].peers_size) )
883 if (NULL != to_remove->th)
885 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
886 to_remove->th = NULL;
889 while (NULL != (pos = to_remove->head))
891 GNUNET_CONTAINER_DLL_remove (to_remove->head,
897 if (k_buckets[current_bucket].peers_size < bucket_size)
898 update_connect_preferences ();
899 GNUNET_STATISTICS_update (GDS_stats,
900 gettext_noop ("# Queued messages discarded (peer disconnected)"),
903 GNUNET_free (to_remove);
908 * Called when core is ready to send a message we asked for
909 * out to the destination.
911 * @param cls the 'struct PeerInfo' of the target peer
912 * @param size number of bytes available in @a buf
913 * @param buf where the callee should write the message
914 * @return number of bytes written to @a buf
917 core_transmit_notify (void *cls,
921 struct PeerInfo *peer = cls;
923 struct P2PPendingMessage *pending;
928 while ((NULL != (pending = peer->head)) &&
929 (0 == GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value_us))
931 GNUNET_STATISTICS_update (GDS_stats,
933 ("# Messages dropped (CORE timeout)"),
936 peer->pending_count--;
937 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
938 GNUNET_free (pending);
942 /* no messages pending */
948 GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
949 GNUNET_CORE_PRIO_BEST_EFFORT,
950 GNUNET_TIME_absolute_get_remaining
951 (pending->timeout), &peer->id,
952 ntohs (pending->msg->size),
953 &core_transmit_notify, peer);
954 GNUNET_break (NULL != peer->th);
958 while ((NULL != (pending = peer->head)) &&
959 (size - off >= (msize = ntohs (pending->msg->size))))
961 GNUNET_STATISTICS_update (GDS_stats,
963 ("# Bytes transmitted to other peers"), msize,
965 memcpy (&cbuf[off], pending->msg, msize);
967 peer->pending_count--;
968 GNUNET_CONTAINER_DLL_remove (peer->head,
971 GNUNET_free (pending);
973 if (NULL != (pending = peer->head))
975 /* technically redundant, but easier to read and
976 avoids bogus gcc warning... */
977 msize = ntohs (pending->msg->size);
979 GNUNET_CORE_notify_transmit_ready (core_api,
981 GNUNET_CORE_PRIO_BEST_EFFORT,
982 GNUNET_TIME_absolute_get_remaining (pending->timeout),
985 &core_transmit_notify,
987 GNUNET_break (NULL != peer->th);
994 * Transmit all messages in the peer's message queue.
996 * @param peer message queue to process
999 process_peer_queue (struct PeerInfo *peer)
1001 struct P2PPendingMessage *pending;
1003 if (NULL == (pending = peer->head))
1005 if (NULL != peer->th)
1007 GNUNET_STATISTICS_update (GDS_stats,
1009 ("# Bytes of bandwidth requested from core"),
1010 ntohs (pending->msg->size), GNUNET_NO);
1012 GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
1013 GNUNET_CORE_PRIO_BEST_EFFORT,
1014 GNUNET_TIME_absolute_get_remaining
1017 ntohs (pending->msg->size),
1018 &core_transmit_notify,
1020 GNUNET_break (NULL != peer->th);
1025 * To how many peers should we (on average) forward the request to
1026 * obtain the desired target_replication count (on average).
1028 * @param hop_count number of hops the message has traversed
1029 * @param target_replication the number of total paths desired
1030 * @return Some number of peers to forward the message to
1033 get_forward_count (uint32_t hop_count, uint32_t target_replication)
1035 uint32_t random_value;
1036 uint32_t forward_count;
1039 if (hop_count > GDS_NSE_get () * 4.0)
1041 /* forcefully terminate */
1042 GNUNET_STATISTICS_update (GDS_stats,
1043 gettext_noop ("# requests TTL-dropped"),
1047 if (hop_count > GDS_NSE_get () * 2.0)
1049 /* Once we have reached our ideal number of hops, only forward to 1 peer */
1052 /* bound by system-wide maximum */
1053 target_replication =
1054 GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
1056 1 + (target_replication - 1.0) / (GDS_NSE_get () +
1057 ((float) (target_replication - 1.0) *
1059 /* Set forward count to floor of target_value */
1060 forward_count = (uint32_t) target_value;
1061 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
1062 target_value = target_value - forward_count;
1064 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
1065 if (random_value < (target_value * UINT32_MAX))
1067 return forward_count;
1072 * Compute the distance between have and target as a 32-bit value.
1073 * Differences in the lower bits must count stronger than differences
1074 * in the higher bits.
1078 * @return 0 if have==target, otherwise a number
1079 * that is larger as the distance between
1080 * the two hash codes increases
1083 get_distance (const struct GNUNET_HashCode *target,
1084 const struct GNUNET_HashCode *have)
1086 unsigned int bucket;
1091 /* We have to represent the distance between two 2^9 (=512)-bit
1092 * numbers as a 2^5 (=32)-bit number with "0" being used for the
1093 * two numbers being identical; furthermore, we need to
1094 * guarantee that a difference in the number of matching
1095 * bits is always represented in the result.
1097 * We use 2^32/2^9 numerical values to distinguish between
1098 * hash codes that have the same LSB bit distance and
1099 * use the highest 2^9 bits of the result to signify the
1100 * number of (mis)matching LSB bits; if we have 0 matching
1101 * and hence 512 mismatching LSB bits we return -1 (since
1102 * 512 itself cannot be represented with 9 bits) */
1104 /* first, calculate the most significant 9 bits of our
1105 * result, aka the number of LSBs */
1106 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1107 /* bucket is now a value between 0 and 512 */
1109 return 0; /* perfect match */
1111 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1112 * below, we'd end up with max+1 (overflow)) */
1114 /* calculate the most significant bits of the final result */
1115 msb = (512 - bucket) << (32 - 9);
1116 /* calculate the 32-9 least significant bits of the final result by
1117 * looking at the differences in the 32-9 bits following the
1118 * mismatching bit at 'bucket' */
1120 for (i = bucket + 1;
1121 (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1123 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
1124 GNUNET_CRYPTO_hash_get_bit (have, i))
1125 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1126 * last bit set will be 31 -- if
1127 * i does not reach 512 first... */
1134 * Check whether my identity is closer than any known peers. If a
1135 * non-null bloomfilter is given, check if this is the closest peer
1136 * that hasn't already been routed to.
1138 * @param key hash code to check closeness to
1139 * @param bloom bloomfilter, exclude these entries from the decision
1140 * @return #GNUNET_YES if node location is closest,
1141 * #GNUNET_NO otherwise.
1144 am_closest_peer (const struct GNUNET_HashCode *key,
1145 const struct GNUNET_CONTAINER_BloomFilter *bloom)
1151 struct PeerInfo *pos;
1152 struct GNUNET_HashCode phash;
1154 if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1156 bucket_num = find_bucket (key);
1157 GNUNET_assert (bucket_num >= 0);
1158 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, key);
1159 pos = k_buckets[bucket_num].head;
1161 while ((NULL != pos) && (count < bucket_size))
1163 GNUNET_CRYPTO_hash (&pos->id,
1164 sizeof (struct GNUNET_PeerIdentity),
1166 if ((NULL != bloom) &&
1168 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1171 continue; /* Skip already checked entries */
1173 other_bits = GNUNET_CRYPTO_hash_matching_bits (&phash, key);
1174 if (other_bits > bits)
1176 if (other_bits == bits) /* We match the same number of bits */
1180 /* No peers closer, we are the closest! */
1186 * Select a peer from the routing table that would be a good routing
1187 * destination for sending a message for "key". The resulting peer
1188 * must not be in the set of blocked peers.<p>
1190 * Note that we should not ALWAYS select the closest peer to the
1191 * target, peers further away from the target should be chosen with
1192 * exponentially declining probability.
1194 * FIXME: double-check that this is fine
1197 * @param key the key we are selecting a peer to route to
1198 * @param bloom a bloomfilter containing entries this request has seen already
1199 * @param hops how many hops has this message traversed thus far
1200 * @return Peer to route to, or NULL on error
1202 static struct PeerInfo *
1203 select_peer (const struct GNUNET_HashCode *key,
1204 const struct GNUNET_CONTAINER_BloomFilter *bloom,
1209 unsigned int selected;
1210 struct PeerInfo *pos;
1212 unsigned int smallest_distance;
1213 struct PeerInfo *chosen;
1214 struct GNUNET_HashCode phash;
1216 if (hops >= GDS_NSE_get ())
1218 /* greedy selection (closest peer that is not in bloomfilter) */
1219 smallest_distance = UINT_MAX;
1221 for (bc = 0; bc <= closest_bucket; bc++)
1223 pos = k_buckets[bc].head;
1225 while ((pos != NULL) && (count < bucket_size))
1227 GNUNET_CRYPTO_hash (&pos->id,
1228 sizeof (struct GNUNET_PeerIdentity),
1230 if ((bloom == NULL) ||
1232 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1234 dist = get_distance (key, &phash);
1235 if (dist < smallest_distance)
1238 smallest_distance = dist;
1243 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1244 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1245 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1246 GNUNET_STATISTICS_update (GDS_stats,
1248 ("# Peers excluded from routing due to Bloomfilter"),
1250 dist = get_distance (key, &phash);
1251 if (dist < smallest_distance)
1254 smallest_distance = dist;
1262 GNUNET_STATISTICS_update (GDS_stats,
1263 gettext_noop ("# Peer selection failed"), 1,
1268 /* select "random" peer */
1269 /* count number of peers that are available and not filtered */
1271 for (bc = 0; bc <= closest_bucket; bc++)
1273 pos = k_buckets[bc].head;
1274 while ((pos != NULL) && (count < bucket_size))
1276 GNUNET_CRYPTO_hash (&pos->id,
1277 sizeof (struct GNUNET_PeerIdentity),
1279 if ((bloom != NULL) &&
1281 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1283 GNUNET_STATISTICS_update (GDS_stats,
1285 ("# Peers excluded from routing due to Bloomfilter"),
1287 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1288 "Excluded peer `%s' due to BF match in random routing for %s\n",
1289 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1291 continue; /* Ignore bloomfiltered peers */
1297 if (0 == count) /* No peers to select from! */
1299 GNUNET_STATISTICS_update (GDS_stats,
1300 gettext_noop ("# Peer selection failed"), 1,
1304 /* Now actually choose a peer */
1305 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1307 for (bc = 0; bc <= closest_bucket; bc++)
1309 for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next)
1311 GNUNET_CRYPTO_hash (&pos->id,
1312 sizeof (struct GNUNET_PeerIdentity),
1314 if ((bloom != NULL) &&
1316 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1318 continue; /* Ignore bloomfiltered peers */
1320 if (0 == selected--)
1330 * Compute the set of peers that the given request should be
1333 * @param key routing key
1334 * @param bloom bloom filter excluding peers as targets, all selected
1335 * peers will be added to the bloom filter
1336 * @param hop_count number of hops the request has traversed so far
1337 * @param target_replication desired number of replicas
1338 * @param targets where to store an array of target peers (to be
1339 * free'd by the caller)
1340 * @return number of peers returned in 'targets'.
1343 get_target_peers (const struct GNUNET_HashCode *key,
1344 struct GNUNET_CONTAINER_BloomFilter *bloom,
1345 uint32_t hop_count, uint32_t target_replication,
1346 struct PeerInfo ***targets)
1350 struct PeerInfo **rtargets;
1351 struct PeerInfo *nxt;
1352 struct GNUNET_HashCode nhash;
1354 GNUNET_assert (NULL != bloom);
1355 ret = get_forward_count (hop_count, target_replication);
1361 rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1362 for (off = 0; off < ret; off++)
1364 nxt = select_peer (key, bloom, hop_count);
1367 rtargets[off] = nxt;
1368 GNUNET_CRYPTO_hash (&nxt->id,
1369 sizeof (struct GNUNET_PeerIdentity),
1371 GNUNET_break (GNUNET_NO ==
1372 GNUNET_CONTAINER_bloomfilter_test (bloom,
1374 GNUNET_CONTAINER_bloomfilter_add (bloom, &nhash);
1376 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1377 "Selected %u/%u peers at hop %u for %s (target was %u)\n",
1379 GNUNET_CONTAINER_multipeermap_size (all_connected_peers),
1380 (unsigned int) hop_count,
1385 GNUNET_free (rtargets);
1389 *targets = rtargets;
1390 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1391 "Forwarding query `%s' to %u peers (goal was %u peers)\n",
1400 * Perform a PUT operation. Forwards the given request to other
1401 * peers. Does not store the data locally. Does not give the
1402 * data to local clients. May do nothing if this is the only
1403 * peer in the network (or if we are the closest peer in the
1406 * @param type type of the block
1407 * @param options routing options
1408 * @param desired_replication_level desired replication count
1409 * @param expiration_time when does the content expire
1410 * @param hop_count how many hops has this message traversed so far
1411 * @param bf Bloom filter of peers this PUT has already traversed
1412 * @param key key for the content
1413 * @param put_path_length number of entries in @a put_path
1414 * @param put_path peers this request has traversed so far (if tracked)
1415 * @param data payload to store
1416 * @param data_size number of bytes in @a data
1417 * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1420 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1421 enum GNUNET_DHT_RouteOption options,
1422 uint32_t desired_replication_level,
1423 struct GNUNET_TIME_Absolute expiration_time,
1425 struct GNUNET_CONTAINER_BloomFilter *bf,
1426 const struct GNUNET_HashCode *key,
1427 unsigned int put_path_length,
1428 struct GNUNET_PeerIdentity *put_path,
1429 const void *data, size_t data_size)
1431 unsigned int target_count;
1433 struct PeerInfo **targets;
1434 struct PeerInfo *target;
1435 struct P2PPendingMessage *pending;
1437 struct PeerPutMessage *ppm;
1438 struct GNUNET_PeerIdentity *pp;
1439 struct GNUNET_HashCode thash;
1440 unsigned int skip_count;
1442 GNUNET_assert (NULL != bf);
1443 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1444 "Adding myself (%s) to PUT bloomfilter for %s\n",
1445 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1446 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity_hash);
1447 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1450 get_target_peers (key, bf, hop_count, desired_replication_level,
1452 if (0 == target_count)
1454 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1455 "Routing PUT for %s terminates after %u hops at %s\n",
1456 GNUNET_h2s (key), (unsigned int) hop_count,
1457 GNUNET_i2s (&my_identity));
1461 put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1462 sizeof (struct PeerPutMessage);
1463 if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1465 put_path_length = 0;
1466 msize = data_size + sizeof (struct PeerPutMessage);
1468 if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1471 GNUNET_free (targets);
1474 GNUNET_STATISTICS_update (GDS_stats,
1476 ("# PUT messages queued for transmission"),
1477 target_count, GNUNET_NO);
1479 for (i = 0; i < target_count; i++)
1481 target = targets[i];
1482 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1485 GNUNET_STATISTICS_update (GDS_stats,
1486 gettext_noop ("# P2P messages dropped due to full queue"),
1491 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1492 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1493 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1494 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1495 pending->importance = 0; /* FIXME */
1496 pending->timeout = expiration_time;
1497 ppm = (struct PeerPutMessage *) &pending[1];
1498 pending->msg = &ppm->header;
1499 ppm->header.size = htons (msize);
1500 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1501 ppm->options = htonl (options);
1502 ppm->type = htonl (type);
1503 ppm->hop_count = htonl (hop_count + 1);
1504 ppm->desired_replication_level = htonl (desired_replication_level);
1505 ppm->put_path_length = htonl (put_path_length);
1506 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1507 GNUNET_CRYPTO_hash (&target->id,
1508 sizeof (struct GNUNET_PeerIdentity),
1510 GNUNET_break (GNUNET_YES ==
1511 GNUNET_CONTAINER_bloomfilter_test (bf,
1513 GNUNET_assert (GNUNET_OK ==
1514 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1518 pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1519 memcpy (pp, put_path,
1520 sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1521 memcpy (&pp[put_path_length], data, data_size);
1522 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1523 target->pending_count++;
1524 process_peer_queue (target);
1526 GNUNET_free (targets);
1527 return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1532 * Perform a GET operation. Forwards the given request to other
1533 * peers. Does not lookup the key locally. May do nothing if this is
1534 * the only peer in the network (or if we are the closest peer in the
1537 * @param type type of the block
1538 * @param options routing options
1539 * @param desired_replication_level desired replication count
1540 * @param hop_count how many hops did this request traverse so far?
1541 * @param key key for the content
1542 * @param xquery extended query
1543 * @param xquery_size number of bytes in @a xquery
1544 * @param reply_bf bloomfilter to filter duplicates
1545 * @param reply_bf_mutator mutator for @a reply_bf
1546 * @param peer_bf filter for peers not to select (again)
1547 * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1550 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1551 enum GNUNET_DHT_RouteOption options,
1552 uint32_t desired_replication_level,
1553 uint32_t hop_count, const struct GNUNET_HashCode * key,
1554 const void *xquery, size_t xquery_size,
1555 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1556 uint32_t reply_bf_mutator,
1557 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1559 unsigned int target_count;
1561 struct PeerInfo **targets;
1562 struct PeerInfo *target;
1563 struct P2PPendingMessage *pending;
1565 struct PeerGetMessage *pgm;
1567 size_t reply_bf_size;
1568 struct GNUNET_HashCode thash;
1569 unsigned int skip_count;
1571 GNUNET_assert (NULL != peer_bf);
1572 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1575 get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1577 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1578 "Adding myself (%s) to GET bloomfilter for %s\n",
1579 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1580 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity_hash);
1581 if (0 == target_count)
1583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1584 "Routing GET for %s terminates after %u hops at %s\n",
1585 GNUNET_h2s (key), (unsigned int) hop_count,
1586 GNUNET_i2s (&my_identity));
1589 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1590 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1591 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1594 GNUNET_free (targets);
1597 GNUNET_STATISTICS_update (GDS_stats,
1599 ("# GET messages queued for transmission"),
1600 target_count, GNUNET_NO);
1601 /* forward request */
1603 for (i = 0; i < target_count; i++)
1605 target = targets[i];
1606 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1609 GNUNET_STATISTICS_update (GDS_stats,
1610 gettext_noop ("# P2P messages dropped due to full queue"),
1615 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1616 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1617 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1618 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1619 pending->importance = 0; /* FIXME */
1620 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1621 pgm = (struct PeerGetMessage *) &pending[1];
1622 pending->msg = &pgm->header;
1623 pgm->header.size = htons (msize);
1624 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1625 pgm->options = htonl (options);
1626 pgm->type = htonl (type);
1627 pgm->hop_count = htonl (hop_count + 1);
1628 pgm->desired_replication_level = htonl (desired_replication_level);
1629 pgm->xquery_size = htonl (xquery_size);
1630 pgm->bf_mutator = reply_bf_mutator;
1631 GNUNET_CRYPTO_hash (&target->id,
1632 sizeof (struct GNUNET_PeerIdentity),
1634 GNUNET_break (GNUNET_YES ==
1635 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1637 GNUNET_assert (GNUNET_OK ==
1638 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1642 xq = (char *) &pgm[1];
1643 memcpy (xq, xquery, xquery_size);
1644 if (NULL != reply_bf)
1645 GNUNET_assert (GNUNET_OK ==
1646 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1650 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1651 target->pending_count++;
1652 process_peer_queue (target);
1654 GNUNET_free (targets);
1655 return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1660 * Handle a reply (route to origin). Only forwards the reply back to
1661 * the given peer. Does not do local caching or forwarding to local
1664 * @param target neighbour that should receive the block (if still connected)
1665 * @param type type of the block
1666 * @param expiration_time when does the content expire
1667 * @param key key for the content
1668 * @param put_path_length number of entries in @a put_path
1669 * @param put_path peers the original PUT traversed (if tracked)
1670 * @param get_path_length number of entries in @a get_path
1671 * @param get_path peers this reply has traversed so far (if tracked)
1672 * @param data payload of the reply
1673 * @param data_size number of bytes in @a data
1676 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1677 enum GNUNET_BLOCK_Type type,
1678 struct GNUNET_TIME_Absolute expiration_time,
1679 const struct GNUNET_HashCode *key,
1680 unsigned int put_path_length,
1681 const struct GNUNET_PeerIdentity *put_path,
1682 unsigned int get_path_length,
1683 const struct GNUNET_PeerIdentity *get_path,
1687 struct PeerInfo *pi;
1688 struct P2PPendingMessage *pending;
1690 struct PeerResultMessage *prm;
1691 struct GNUNET_PeerIdentity *paths;
1694 data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1696 sizeof (struct GNUNET_PeerIdentity);
1697 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1699 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1701 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1702 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1707 pi = GNUNET_CONTAINER_multipeermap_get (all_connected_peers,
1711 /* peer disconnected in the meantime, drop reply */
1714 if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1717 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1722 GNUNET_STATISTICS_update (GDS_stats,
1724 ("# RESULT messages queued for transmission"), 1,
1726 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1727 pending->importance = 0; /* FIXME */
1728 pending->timeout = expiration_time;
1729 prm = (struct PeerResultMessage *) &pending[1];
1730 pending->msg = &prm->header;
1731 prm->header.size = htons (msize);
1732 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1733 prm->type = htonl (type);
1734 prm->put_path_length = htonl (put_path_length);
1735 prm->get_path_length = htonl (get_path_length);
1736 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1738 paths = (struct GNUNET_PeerIdentity *) &prm[1];
1739 memcpy (paths, put_path,
1740 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1741 memcpy (&paths[put_path_length], get_path,
1742 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1743 memcpy (&paths[put_path_length + get_path_length], data, data_size);
1744 GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1745 pi->pending_count++;
1746 process_peer_queue (pi);
1751 * To be called on core init/fail.
1753 * @param cls service closure
1754 * @param identity the public identity of this peer
1757 core_init (void *cls,
1758 const struct GNUNET_PeerIdentity *identity)
1760 my_identity = *identity;
1761 GNUNET_CRYPTO_hash (identity,
1762 sizeof (struct GNUNET_PeerIdentity),
1768 * Core handler for p2p put requests.
1770 * @param cls closure
1771 * @param peer sender of the request
1772 * @param message message
1773 * @param peer peer identity this notification is about
1774 * @return #GNUNET_OK to keep the connection open,
1775 * #GNUNET_SYSERR to close it (signal serious error)
1778 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1779 const struct GNUNET_MessageHeader *message)
1781 const struct PeerPutMessage *put;
1782 const struct GNUNET_PeerIdentity *put_path;
1783 const void *payload;
1786 size_t payload_size;
1787 enum GNUNET_DHT_RouteOption options;
1788 struct GNUNET_CONTAINER_BloomFilter *bf;
1789 struct GNUNET_HashCode test_key;
1790 struct GNUNET_HashCode phash;
1793 msize = ntohs (message->size);
1794 if (msize < sizeof (struct PeerPutMessage))
1796 GNUNET_break_op (0);
1799 put = (const struct PeerPutMessage *) message;
1800 putlen = ntohl (put->put_path_length);
1802 sizeof (struct PeerPutMessage) +
1803 putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1805 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1807 GNUNET_break_op (0);
1810 GNUNET_STATISTICS_update (GDS_stats,
1811 gettext_noop ("# P2P PUT requests received"), 1,
1813 GNUNET_STATISTICS_update (GDS_stats,
1814 gettext_noop ("# P2P PUT bytes received"), msize,
1816 put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1817 payload = &put_path[putlen];
1818 options = ntohl (put->options);
1820 msize - (sizeof (struct PeerPutMessage) +
1821 putlen * sizeof (struct GNUNET_PeerIdentity));
1823 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1824 GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1825 GNUNET_CRYPTO_hash (peer, sizeof (struct GNUNET_PeerIdentity), &phash);
1826 if (GNUNET_YES == log_route_details_stderr)
1830 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1831 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1832 "R5N PUT %s: %s->%s (%u, %u=>%u)\n",
1833 GNUNET_h2s (&put->key), GNUNET_i2s (peer), tmp,
1834 ntohl(put->hop_count),
1835 GNUNET_CRYPTO_hash_matching_bits (&phash, &put->key),
1836 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &put->key)
1840 switch (GNUNET_BLOCK_get_key
1841 (GDS_block_context, ntohl (put->type), payload, payload_size,
1845 if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1847 char *put_s = GNUNET_strdup (GNUNET_h2s_full (&put->key));
1848 GNUNET_break_op (0);
1849 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1850 "PUT with key `%s' for block with key %s\n",
1851 put_s, GNUNET_h2s_full (&test_key));
1852 GNUNET_free (put_s);
1857 GNUNET_break_op (0);
1860 /* cannot verify, good luck */
1863 if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
1865 switch (GNUNET_BLOCK_evaluate (GDS_block_context,
1867 GNUNET_BLOCK_EO_NONE,
1869 NULL, 0, /* bloom filer */
1870 NULL, 0, /* xquery */
1871 payload, payload_size))
1873 case GNUNET_BLOCK_EVALUATION_OK_MORE:
1874 case GNUNET_BLOCK_EVALUATION_OK_LAST:
1877 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1878 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1879 case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1880 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1881 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1882 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1884 GNUNET_break_op (0);
1889 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1890 GNUNET_CONSTANTS_BLOOMFILTER_K);
1891 GNUNET_break_op (GNUNET_YES ==
1892 GNUNET_CONTAINER_bloomfilter_test (bf, &phash));
1894 struct GNUNET_PeerIdentity pp[putlen + 1];
1896 /* extend 'put path' by sender */
1897 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1899 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1906 /* give to local clients */
1907 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1908 &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1909 payload_size, payload);
1911 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1912 (am_closest_peer (&put->key, bf)))
1913 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1914 (put->expiration_time), &put->key, putlen, pp,
1915 ntohl (put->type), payload_size, payload);
1916 /* route to other peers */
1917 forwarded = GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1918 ntohl (put->desired_replication_level),
1919 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1920 ntohl (put->hop_count), bf,
1926 /* notify monitoring clients */
1927 GDS_CLIENTS_process_put (options
1928 | ( (GNUNET_OK == forwarded)
1929 ? GNUNET_DHT_RO_LAST_HOP
1932 ntohl (put->hop_count),
1933 ntohl (put->desired_replication_level),
1935 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1940 GNUNET_CONTAINER_bloomfilter_free (bf);
1946 * We have received a FIND PEER request. Send matching
1949 * @param sender sender of the FIND PEER request
1950 * @param key peers close to this key are desired
1951 * @param bf peers matching this bf are excluded
1952 * @param bf_mutator mutator for bf
1955 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1956 const struct GNUNET_HashCode * key,
1957 struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1960 struct PeerBucket *bucket;
1961 struct PeerInfo *peer;
1962 unsigned int choice;
1963 struct GNUNET_HashCode phash;
1964 struct GNUNET_HashCode mhash;
1965 const struct GNUNET_HELLO_Message *hello;
1967 /* first, check about our own HELLO */
1968 if (NULL != GDS_my_hello)
1970 GNUNET_BLOCK_mingle_hash (&my_identity_hash, bf_mutator, &mhash);
1972 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1974 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1975 GNUNET_TIME_relative_to_absolute
1977 key, 0, NULL, 0, NULL, GDS_my_hello,
1978 GNUNET_HELLO_size ((const struct
1979 GNUNET_HELLO_Message *)
1984 GNUNET_STATISTICS_update (GDS_stats,
1986 ("# FIND PEER requests ignored due to Bloomfilter"),
1992 GNUNET_STATISTICS_update (GDS_stats,
1994 ("# FIND PEER requests ignored due to lack of HELLO"),
1998 /* then, also consider sending a random HELLO from the closest bucket */
1999 if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
2000 bucket_idx = closest_bucket;
2002 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
2003 if (bucket_idx == GNUNET_SYSERR)
2005 bucket = &k_buckets[bucket_idx];
2006 if (bucket->peers_size == 0)
2009 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
2010 peer = bucket->head;
2013 GNUNET_assert (NULL != peer);
2017 choice = bucket->peers_size;
2022 return; /* no non-masked peer available */
2024 peer = bucket->head;
2025 GNUNET_CRYPTO_hash (&peer->id, sizeof (struct GNUNET_PeerIdentity), &phash);
2026 GNUNET_BLOCK_mingle_hash (&phash, bf_mutator, &mhash);
2027 hello = GDS_HELLO_get (&peer->id);
2029 while ((hello == NULL) ||
2030 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
2031 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
2032 GNUNET_TIME_relative_to_absolute
2033 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
2034 0, NULL, 0, NULL, hello,
2035 GNUNET_HELLO_size (hello));
2040 * Core handler for p2p get requests.
2042 * @param cls closure
2043 * @param peer sender of the request
2044 * @param message message
2045 * @return #GNUNET_OK to keep the connection open,
2046 * #GNUNET_SYSERR to close it (signal serious error)
2049 handle_dht_p2p_get (void *cls,
2050 const struct GNUNET_PeerIdentity *peer,
2051 const struct GNUNET_MessageHeader *message)
2053 struct PeerGetMessage *get;
2054 uint32_t xquery_size;
2055 size_t reply_bf_size;
2057 enum GNUNET_BLOCK_Type type;
2058 enum GNUNET_DHT_RouteOption options;
2059 enum GNUNET_BLOCK_EvaluationResult eval;
2060 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
2061 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
2063 struct GNUNET_HashCode phash;
2067 memcmp (peer, &my_identity,
2068 sizeof (struct GNUNET_PeerIdentity)));
2069 /* parse and validate message */
2070 msize = ntohs (message->size);
2071 if (msize < sizeof (struct PeerGetMessage))
2073 GNUNET_break_op (0);
2076 get = (struct PeerGetMessage *) message;
2077 xquery_size = ntohl (get->xquery_size);
2078 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
2080 GNUNET_break_op (0);
2083 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
2084 type = ntohl (get->type);
2085 options = ntohl (get->options);
2086 xquery = (const char *) &get[1];
2088 GNUNET_STATISTICS_update (GDS_stats,
2089 gettext_noop ("# P2P GET requests received"), 1,
2091 GNUNET_STATISTICS_update (GDS_stats,
2092 gettext_noop ("# P2P GET bytes received"), msize,
2094 GNUNET_CRYPTO_hash (peer,
2095 sizeof (struct GNUNET_PeerIdentity),
2097 if (GNUNET_YES == log_route_details_stderr)
2101 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
2102 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
2103 "R5N GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n",
2104 GNUNET_h2s (&get->key), GNUNET_i2s (peer), tmp,
2105 ntohl(get->hop_count),
2106 GNUNET_CRYPTO_hash_matching_bits (&phash, &get->key),
2107 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &get->key),
2108 ntohl(get->xquery_size), xquery);
2112 if (reply_bf_size > 0)
2114 GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
2115 GNUNET_CONSTANTS_BLOOMFILTER_K);
2117 GNUNET_BLOCK_evaluate (GDS_block_context,
2119 GNUNET_BLOCK_EO_NONE,
2127 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
2129 /* request invalid or block type not supported */
2130 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
2131 if (NULL != reply_bf)
2132 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
2136 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
2137 GNUNET_CONSTANTS_BLOOMFILTER_K);
2138 GNUNET_break_op (GNUNET_YES ==
2139 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
2141 /* remember request for routing replies */
2142 GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
2143 reply_bf, get->bf_mutator);
2144 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2145 "GET for %s at %s after %u hops\n",
2146 GNUNET_h2s (&get->key),
2147 GNUNET_i2s (&my_identity),
2148 (unsigned int) ntohl (get->hop_count));
2149 /* local lookup (this may update the reply_bf) */
2150 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
2151 (am_closest_peer (&get->key, peer_bf)))
2153 if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
2155 GNUNET_STATISTICS_update (GDS_stats,
2157 ("# P2P FIND PEER requests processed"), 1,
2159 handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
2164 GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
2165 &reply_bf, get->bf_mutator);
2170 GNUNET_STATISTICS_update (GDS_stats,
2171 gettext_noop ("# P2P GET requests ONLY routed"),
2175 /* P2P forwarding */
2176 forwarded = GNUNET_NO;
2177 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
2178 forwarded = GDS_NEIGHBOURS_handle_get (type, options,
2179 ntohl (get->desired_replication_level),
2180 ntohl (get->hop_count),
2185 get->bf_mutator, peer_bf);
2186 GDS_CLIENTS_process_get (options
2187 | (GNUNET_OK == forwarded)
2188 ? GNUNET_DHT_RO_LAST_HOP : 0,
2190 ntohl (get->hop_count),
2191 ntohl (get->desired_replication_level),
2197 if (NULL != reply_bf)
2198 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
2199 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
2205 * Core handler for p2p result messages.
2207 * @param cls closure
2208 * @param message message
2209 * @param peer peer identity this notification is about
2210 * @return #GNUNET_YES (do not cut p2p connection)
2213 handle_dht_p2p_result (void *cls,
2214 const struct GNUNET_PeerIdentity *peer,
2215 const struct GNUNET_MessageHeader *message)
2217 const struct PeerResultMessage *prm;
2218 const struct GNUNET_PeerIdentity *put_path;
2219 const struct GNUNET_PeerIdentity *get_path;
2221 uint32_t get_path_length;
2222 uint32_t put_path_length;
2225 enum GNUNET_BLOCK_Type type;
2227 /* parse and validate message */
2228 msize = ntohs (message->size);
2229 if (msize < sizeof (struct PeerResultMessage))
2231 GNUNET_break_op (0);
2234 prm = (struct PeerResultMessage *) message;
2235 put_path_length = ntohl (prm->put_path_length);
2236 get_path_length = ntohl (prm->get_path_length);
2238 sizeof (struct PeerResultMessage) + (get_path_length +
2240 sizeof (struct GNUNET_PeerIdentity)) ||
2242 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
2244 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
2246 GNUNET_break_op (0);
2249 put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
2250 get_path = &put_path[put_path_length];
2251 type = ntohl (prm->type);
2252 data = (const void *) &get_path[get_path_length];
2254 msize - (sizeof (struct PeerResultMessage) +
2256 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
2257 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
2259 GNUNET_STATISTICS_update (GDS_stats,
2260 gettext_noop ("# P2P RESULT bytes received"),
2262 if (GNUNET_YES == log_route_details_stderr)
2266 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
2267 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
2268 "R5N RESULT %s: %s->%s (%u)\n",
2269 GNUNET_h2s (&prm->key),
2272 get_path_length + 1);
2275 /* if we got a HELLO, consider it for our own routing table */
2276 if (GNUNET_BLOCK_TYPE_DHT_HELLO == type)
2278 const struct GNUNET_MessageHeader *h;
2279 struct GNUNET_PeerIdentity pid;
2281 /* Should be a HELLO, validate and consider using it! */
2282 if (data_size < sizeof (struct GNUNET_MessageHeader))
2284 GNUNET_break_op (0);
2288 if (data_size != ntohs (h->size))
2290 GNUNET_break_op (0);
2294 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h,
2297 GNUNET_break_op (0);
2300 if ( (GNUNET_YES != disable_try_connect) &&
2301 (0 != memcmp (&my_identity,
2303 sizeof (struct GNUNET_PeerIdentity))) )
2308 /* append 'peer' to 'get_path' */
2310 struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
2314 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2315 xget_path[get_path_length] = *peer;
2318 /* forward to local clients */
2319 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2328 GDS_CLIENTS_process_get_resp (type,
2331 put_path, put_path_length,
2332 GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2336 if (GNUNET_YES == cache_results)
2338 struct GNUNET_PeerIdentity xput_path[get_path_length + 1 + put_path_length];
2340 memcpy (xput_path, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
2341 memcpy (&xput_path[put_path_length],
2343 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2345 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2347 get_path_length + put_path_length,
2353 /* forward to other peers */
2354 GDS_ROUTING_process (type,
2355 GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2370 * Initialize neighbours subsystem.
2372 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
2375 GDS_NEIGHBOURS_init ()
2377 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2378 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2379 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2380 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2383 unsigned long long temp_config_num;
2386 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2388 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2390 bucket_size = (unsigned int) temp_config_num;
2392 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "CACHE_RESULTS");
2394 log_route_details_stderr =
2395 (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO;
2396 ats_ch = GNUNET_ATS_connectivity_init (GDS_cfg);
2398 GNUNET_CORE_connect (GDS_cfg, NULL,
2400 &handle_core_connect,
2401 &handle_core_disconnect,
2405 if (core_api == NULL)
2406 return GNUNET_SYSERR;
2407 all_connected_peers = GNUNET_CONTAINER_multipeermap_create (256,
2409 all_desired_peers = GNUNET_CONTAINER_multipeermap_create (256,
2416 * Shutdown neighbours subsystem.
2419 GDS_NEIGHBOURS_done ()
2421 if (NULL == core_api)
2423 GNUNET_CORE_disconnect (core_api);
2425 GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (all_connected_peers));
2426 GNUNET_CONTAINER_multipeermap_destroy (all_connected_peers);
2427 all_connected_peers = NULL;
2428 GNUNET_CONTAINER_multipeermap_iterate (all_desired_peers,
2431 GNUNET_CONTAINER_multipeermap_destroy (all_desired_peers);
2432 all_desired_peers = NULL;
2433 GNUNET_ATS_connectivity_done (ats_ch);
2435 if (NULL != find_peer_task)
2437 GNUNET_SCHEDULER_cancel (find_peer_task);
2438 find_peer_task = NULL;
2444 * Get the ID of the local node.
2446 * @return identity of the local node
2448 struct GNUNET_PeerIdentity *
2449 GDS_NEIGHBOURS_get_id ()
2451 return &my_identity;
2455 /* end of gnunet-service-dht_neighbours.c */