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`
498 offer_hello_done (void *cls,
499 const struct GNUNET_SCHEDULER_TaskContext *tc)
501 struct ConnectInfo *ci = cls;
508 * Function called for all entries in #all_desired_peers to clean up.
511 * @param peer peer the entry is for
512 * @param value the value to remove
513 * @return #GNUNET_YES
516 free_connect_info (void *cls,
517 const struct GNUNET_PeerIdentity *peer,
520 struct ConnectInfo *ci = value;
522 GNUNET_assert (GNUNET_YES ==
523 GNUNET_CONTAINER_multipeermap_remove (all_desired_peers,
528 GNUNET_ATS_connectivity_suggest_cancel (ci->sh);
533 GNUNET_TRANSPORT_offer_hello_cancel (ci->oh);
542 * Consider if we want to connect to a given peer, and if so
543 * let ATS know. If applicable, the HELLO is offered to the
546 * @param pid peer to consider connectivity requirements for
547 * @param h a HELLO message, or NULL
550 try_connect (const struct GNUNET_PeerIdentity *pid,
551 const struct GNUNET_MessageHeader *h)
554 struct GNUNET_HashCode pid_hash;
555 struct ConnectInfo *ci;
558 GNUNET_CRYPTO_hash (pid,
559 sizeof (struct GNUNET_PeerIdentity),
561 bucket = find_bucket (&pid_hash);
564 ci = GNUNET_CONTAINER_multipeermap_get (all_desired_peers,
567 if (k_buckets[bucket].peers_size < bucket_size)
568 strength = (bucket_size - k_buckets[bucket].peers_size) * bucket;
570 strength = bucket; /* minimum value of connectivity */
572 GNUNET_CONTAINER_multipeermap_contains (all_connected_peers,
574 strength *= 2; /* double for connected peers */
575 else if (k_buckets[bucket].peers_size > bucket_size)
576 strength = 0; /* bucket full, we really do not care about more */
578 if ( (0 == strength) &&
581 /* release request */
582 GNUNET_assert (GNUNET_YES ==
583 free_connect_info (NULL,
590 ci = GNUNET_new (struct ConnectInfo);
591 GNUNET_assert (GNUNET_OK ==
592 GNUNET_CONTAINER_multipeermap_put (all_desired_peers,
595 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
597 if ( (NULL != GDS_transport_handle) &&
600 GNUNET_TRANSPORT_offer_hello_cancel (ci->oh);
601 if ( (NULL != GDS_transport_handle) &&
603 ci->oh = GNUNET_TRANSPORT_offer_hello (GDS_transport_handle,
607 if ( (NULL != ci->sh) &&
608 (ci->strength != strength) )
609 GNUNET_ATS_connectivity_suggest_cancel (ci->sh);
610 if (ci->strength != strength)
611 ci->sh = GNUNET_ATS_connectivity_suggest (ats_ch,
614 ci->strength = strength;
619 * Function called for each peer in #all_desired_peers during
620 * #update_connect_preferences() if we have reason to adjust
621 * the strength of our desire to keep connections to certain
622 * peers. Calls #try_connect() to update the calculations for
626 * @param pid peer to update
627 * @param value unused
628 * @return #GNUNET_YES (continue to iterate)
631 update_desire_strength (void *cls,
632 const struct GNUNET_PeerIdentity *pid,
635 try_connect (pid, NULL);
641 * Update our preferences for connectivity as given to ATS.
643 * @param cls the `struct PeerInfo` of the peer
644 * @param tc scheduler context.
647 update_connect_preferences ()
649 GNUNET_CONTAINER_multipeermap_iterate (all_desired_peers,
650 &update_desire_strength,
656 * Closure for #add_known_to_bloom().
658 struct BloomConstructorContext
661 * Bloom filter under construction.
663 struct GNUNET_CONTAINER_BloomFilter *bloom;
673 * Add each of the peers we already know to the bloom filter of
674 * the request so that we don't get duplicate HELLOs.
676 * @param cls the 'struct BloomConstructorContext'.
677 * @param key peer identity to add to the bloom filter
678 * @param value value the peer information (unused)
679 * @return #GNUNET_YES (we should continue to iterate)
682 add_known_to_bloom (void *cls,
683 const struct GNUNET_PeerIdentity *key,
686 struct BloomConstructorContext *ctx = cls;
687 struct GNUNET_HashCode key_hash;
688 struct GNUNET_HashCode mh;
690 GNUNET_CRYPTO_hash (key,
691 sizeof (struct GNUNET_PeerIdentity),
693 GNUNET_BLOCK_mingle_hash (&key_hash,
696 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
697 "Adding known peer (%s) to bloomfilter for FIND PEER with mutation %u\n",
698 GNUNET_i2s (key), ctx->bf_mutator);
699 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
705 * Task to send a find peer message for our own peer identifier
706 * so that we can find the closest peers in the network to ourselves
707 * and attempt to connect to them.
709 * @param cls closure for this task
710 * @param tc the context under which the task is running
713 send_find_peer_message (void *cls,
714 const struct GNUNET_SCHEDULER_TaskContext *tc)
716 struct GNUNET_TIME_Relative next_send_time;
717 struct BloomConstructorContext bcc;
718 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
720 find_peer_task = NULL;
721 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
723 if (newly_found_peers > bucket_size)
725 /* If we are finding many peers already, no need to send out our request right now! */
727 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
728 &send_find_peer_message, NULL);
729 newly_found_peers = 0;
733 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
735 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
736 GNUNET_CONSTANTS_BLOOMFILTER_K);
737 GNUNET_CONTAINER_multipeermap_iterate (all_connected_peers,
740 GNUNET_STATISTICS_update (GDS_stats,
741 gettext_noop ("# FIND PEER messages initiated"), 1,
744 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE,
745 GNUNET_CONSTANTS_BLOOMFILTER_K);
746 // FIXME: pass priority!?
747 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
748 GNUNET_DHT_RO_FIND_PEER,
749 FIND_PEER_REPLICATION_LEVEL, 0,
750 &my_identity_hash, NULL, 0, bcc.bloom,
751 bcc.bf_mutator, peer_bf);
752 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
753 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
754 /* schedule next round */
755 next_send_time.rel_value_us =
756 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value_us +
757 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
758 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value_us /
759 (newly_found_peers + 1));
760 newly_found_peers = 0;
762 GNUNET_SCHEDULER_add_delayed (next_send_time, &send_find_peer_message,
768 * Method called whenever a peer connects.
771 * @param peer peer identity this notification is about
774 handle_core_connect (void *cls,
775 const struct GNUNET_PeerIdentity *peer)
777 struct PeerInfo *ret;
778 struct GNUNET_HashCode phash;
781 /* Check for connect to self message */
782 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
784 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
788 GNUNET_CONTAINER_multipeermap_contains (all_connected_peers,
794 GNUNET_STATISTICS_update (GDS_stats,
795 gettext_noop ("# peers connected"),
798 GNUNET_CRYPTO_hash (peer,
799 sizeof (struct GNUNET_PeerIdentity),
801 peer_bucket = find_bucket (&phash);
802 GNUNET_assert ((peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS));
803 ret = GNUNET_new (struct PeerInfo);
805 ret->latency = latency;
806 ret->distance = distance;
809 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
810 k_buckets[peer_bucket].tail,
812 k_buckets[peer_bucket].peers_size++;
813 closest_bucket = GNUNET_MAX (closest_bucket,
815 GNUNET_assert (GNUNET_OK ==
816 GNUNET_CONTAINER_multipeermap_put (all_connected_peers,
819 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
820 if ( (peer_bucket > 0) &&
821 (k_buckets[peer_bucket].peers_size <= bucket_size))
823 update_connect_preferences ();
826 if (1 == GNUNET_CONTAINER_multipeermap_size (all_connected_peers) &&
827 (GNUNET_YES != disable_try_connect))
829 /* got a first connection, good time to start with FIND PEER requests... */
830 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message,
837 * Method called whenever a peer disconnects.
840 * @param peer peer identity this notification is about
843 handle_core_disconnect (void *cls,
844 const struct GNUNET_PeerIdentity *peer)
846 struct PeerInfo *to_remove;
848 struct P2PPendingMessage *pos;
849 unsigned int discarded;
850 struct GNUNET_HashCode phash;
852 /* Check for disconnect from self message */
853 if (0 == memcmp (&my_identity,
855 sizeof (struct GNUNET_PeerIdentity)))
857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
861 GNUNET_CONTAINER_multipeermap_get (all_connected_peers,
863 if (NULL == to_remove)
868 GNUNET_STATISTICS_update (GDS_stats,
869 gettext_noop ("# peers connected"),
872 GNUNET_assert (GNUNET_YES ==
873 GNUNET_CONTAINER_multipeermap_remove (all_connected_peers,
876 GNUNET_CRYPTO_hash (peer,
877 sizeof (struct GNUNET_PeerIdentity),
879 current_bucket = find_bucket (&phash);
880 GNUNET_assert (current_bucket >= 0);
881 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
882 k_buckets[current_bucket].tail,
884 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
885 k_buckets[current_bucket].peers_size--;
886 while ( (closest_bucket > 0) &&
887 (0 == k_buckets[closest_bucket].peers_size) )
889 if (NULL != to_remove->th)
891 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
892 to_remove->th = NULL;
895 while (NULL != (pos = to_remove->head))
897 GNUNET_CONTAINER_DLL_remove (to_remove->head,
903 if (k_buckets[current_bucket].peers_size < bucket_size)
904 update_connect_preferences ();
905 GNUNET_STATISTICS_update (GDS_stats,
906 gettext_noop ("# Queued messages discarded (peer disconnected)"),
909 GNUNET_free (to_remove);
914 * Called when core is ready to send a message we asked for
915 * out to the destination.
917 * @param cls the 'struct PeerInfo' of the target peer
918 * @param size number of bytes available in @a buf
919 * @param buf where the callee should write the message
920 * @return number of bytes written to @a buf
923 core_transmit_notify (void *cls,
927 struct PeerInfo *peer = cls;
929 struct P2PPendingMessage *pending;
934 while ((NULL != (pending = peer->head)) &&
935 (0 == GNUNET_TIME_absolute_get_remaining (pending->timeout).rel_value_us))
937 GNUNET_STATISTICS_update (GDS_stats,
939 ("# Messages dropped (CORE timeout)"),
942 peer->pending_count--;
943 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
944 GNUNET_free (pending);
948 /* no messages pending */
954 GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
955 GNUNET_CORE_PRIO_BEST_EFFORT,
956 GNUNET_TIME_absolute_get_remaining
957 (pending->timeout), &peer->id,
958 ntohs (pending->msg->size),
959 &core_transmit_notify, peer);
960 GNUNET_break (NULL != peer->th);
964 while ((NULL != (pending = peer->head)) &&
965 (size - off >= (msize = ntohs (pending->msg->size))))
967 GNUNET_STATISTICS_update (GDS_stats,
969 ("# Bytes transmitted to other peers"), msize,
971 memcpy (&cbuf[off], pending->msg, msize);
973 peer->pending_count--;
974 GNUNET_CONTAINER_DLL_remove (peer->head,
977 GNUNET_free (pending);
979 if (NULL != (pending = peer->head))
981 /* technically redundant, but easier to read and
982 avoids bogus gcc warning... */
983 msize = ntohs (pending->msg->size);
985 GNUNET_CORE_notify_transmit_ready (core_api,
987 GNUNET_CORE_PRIO_BEST_EFFORT,
988 GNUNET_TIME_absolute_get_remaining (pending->timeout),
991 &core_transmit_notify,
993 GNUNET_break (NULL != peer->th);
1000 * Transmit all messages in the peer's message queue.
1002 * @param peer message queue to process
1005 process_peer_queue (struct PeerInfo *peer)
1007 struct P2PPendingMessage *pending;
1009 if (NULL == (pending = peer->head))
1011 if (NULL != peer->th)
1013 GNUNET_STATISTICS_update (GDS_stats,
1015 ("# Bytes of bandwidth requested from core"),
1016 ntohs (pending->msg->size), GNUNET_NO);
1018 GNUNET_CORE_notify_transmit_ready (core_api, GNUNET_NO,
1019 GNUNET_CORE_PRIO_BEST_EFFORT,
1020 GNUNET_TIME_absolute_get_remaining
1023 ntohs (pending->msg->size),
1024 &core_transmit_notify,
1026 GNUNET_break (NULL != peer->th);
1031 * To how many peers should we (on average) forward the request to
1032 * obtain the desired target_replication count (on average).
1034 * @param hop_count number of hops the message has traversed
1035 * @param target_replication the number of total paths desired
1036 * @return Some number of peers to forward the message to
1039 get_forward_count (uint32_t hop_count, uint32_t target_replication)
1041 uint32_t random_value;
1042 uint32_t forward_count;
1045 if (hop_count > GDS_NSE_get () * 4.0)
1047 /* forcefully terminate */
1048 GNUNET_STATISTICS_update (GDS_stats,
1049 gettext_noop ("# requests TTL-dropped"),
1053 if (hop_count > GDS_NSE_get () * 2.0)
1055 /* Once we have reached our ideal number of hops, only forward to 1 peer */
1058 /* bound by system-wide maximum */
1059 target_replication =
1060 GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL, target_replication);
1062 1 + (target_replication - 1.0) / (GDS_NSE_get () +
1063 ((float) (target_replication - 1.0) *
1065 /* Set forward count to floor of target_value */
1066 forward_count = (uint32_t) target_value;
1067 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
1068 target_value = target_value - forward_count;
1070 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
1071 if (random_value < (target_value * UINT32_MAX))
1073 return forward_count;
1078 * Compute the distance between have and target as a 32-bit value.
1079 * Differences in the lower bits must count stronger than differences
1080 * in the higher bits.
1084 * @return 0 if have==target, otherwise a number
1085 * that is larger as the distance between
1086 * the two hash codes increases
1089 get_distance (const struct GNUNET_HashCode *target,
1090 const struct GNUNET_HashCode *have)
1092 unsigned int bucket;
1097 /* We have to represent the distance between two 2^9 (=512)-bit
1098 * numbers as a 2^5 (=32)-bit number with "0" being used for the
1099 * two numbers being identical; furthermore, we need to
1100 * guarantee that a difference in the number of matching
1101 * bits is always represented in the result.
1103 * We use 2^32/2^9 numerical values to distinguish between
1104 * hash codes that have the same LSB bit distance and
1105 * use the highest 2^9 bits of the result to signify the
1106 * number of (mis)matching LSB bits; if we have 0 matching
1107 * and hence 512 mismatching LSB bits we return -1 (since
1108 * 512 itself cannot be represented with 9 bits) */
1110 /* first, calculate the most significant 9 bits of our
1111 * result, aka the number of LSBs */
1112 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
1113 /* bucket is now a value between 0 and 512 */
1115 return 0; /* perfect match */
1117 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
1118 * below, we'd end up with max+1 (overflow)) */
1120 /* calculate the most significant bits of the final result */
1121 msb = (512 - bucket) << (32 - 9);
1122 /* calculate the 32-9 least significant bits of the final result by
1123 * looking at the differences in the 32-9 bits following the
1124 * mismatching bit at 'bucket' */
1126 for (i = bucket + 1;
1127 (i < sizeof (struct GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
1129 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
1130 GNUNET_CRYPTO_hash_get_bit (have, i))
1131 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
1132 * last bit set will be 31 -- if
1133 * i does not reach 512 first... */
1140 * Check whether my identity is closer than any known peers. If a
1141 * non-null bloomfilter is given, check if this is the closest peer
1142 * that hasn't already been routed to.
1144 * @param key hash code to check closeness to
1145 * @param bloom bloomfilter, exclude these entries from the decision
1146 * @return #GNUNET_YES if node location is closest,
1147 * #GNUNET_NO otherwise.
1150 am_closest_peer (const struct GNUNET_HashCode *key,
1151 const struct GNUNET_CONTAINER_BloomFilter *bloom)
1157 struct PeerInfo *pos;
1158 struct GNUNET_HashCode phash;
1160 if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
1162 bucket_num = find_bucket (key);
1163 GNUNET_assert (bucket_num >= 0);
1164 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, key);
1165 pos = k_buckets[bucket_num].head;
1167 while ((NULL != pos) && (count < bucket_size))
1169 GNUNET_CRYPTO_hash (&pos->id,
1170 sizeof (struct GNUNET_PeerIdentity),
1172 if ((NULL != bloom) &&
1174 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1177 continue; /* Skip already checked entries */
1179 other_bits = GNUNET_CRYPTO_hash_matching_bits (&phash, key);
1180 if (other_bits > bits)
1182 if (other_bits == bits) /* We match the same number of bits */
1186 /* No peers closer, we are the closest! */
1192 * Select a peer from the routing table that would be a good routing
1193 * destination for sending a message for "key". The resulting peer
1194 * must not be in the set of blocked peers.<p>
1196 * Note that we should not ALWAYS select the closest peer to the
1197 * target, peers further away from the target should be chosen with
1198 * exponentially declining probability.
1200 * FIXME: double-check that this is fine
1203 * @param key the key we are selecting a peer to route to
1204 * @param bloom a bloomfilter containing entries this request has seen already
1205 * @param hops how many hops has this message traversed thus far
1206 * @return Peer to route to, or NULL on error
1208 static struct PeerInfo *
1209 select_peer (const struct GNUNET_HashCode *key,
1210 const struct GNUNET_CONTAINER_BloomFilter *bloom,
1215 unsigned int selected;
1216 struct PeerInfo *pos;
1218 unsigned int smallest_distance;
1219 struct PeerInfo *chosen;
1220 struct GNUNET_HashCode phash;
1222 if (hops >= GDS_NSE_get ())
1224 /* greedy selection (closest peer that is not in bloomfilter) */
1225 smallest_distance = UINT_MAX;
1227 for (bc = 0; bc <= closest_bucket; bc++)
1229 pos = k_buckets[bc].head;
1231 while ((pos != NULL) && (count < bucket_size))
1233 GNUNET_CRYPTO_hash (&pos->id,
1234 sizeof (struct GNUNET_PeerIdentity),
1236 if ((bloom == NULL) ||
1238 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1240 dist = get_distance (key, &phash);
1241 if (dist < smallest_distance)
1244 smallest_distance = dist;
1249 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1250 "Excluded peer `%s' due to BF match in greedy routing for %s\n",
1251 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1252 GNUNET_STATISTICS_update (GDS_stats,
1254 ("# Peers excluded from routing due to Bloomfilter"),
1256 dist = get_distance (key, &phash);
1257 if (dist < smallest_distance)
1260 smallest_distance = dist;
1268 GNUNET_STATISTICS_update (GDS_stats,
1269 gettext_noop ("# Peer selection failed"), 1,
1274 /* select "random" peer */
1275 /* count number of peers that are available and not filtered */
1277 for (bc = 0; bc <= closest_bucket; bc++)
1279 pos = k_buckets[bc].head;
1280 while ((pos != NULL) && (count < bucket_size))
1282 GNUNET_CRYPTO_hash (&pos->id,
1283 sizeof (struct GNUNET_PeerIdentity),
1285 if ((bloom != NULL) &&
1287 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1289 GNUNET_STATISTICS_update (GDS_stats,
1291 ("# Peers excluded from routing due to Bloomfilter"),
1293 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1294 "Excluded peer `%s' due to BF match in random routing for %s\n",
1295 GNUNET_i2s (&pos->id), GNUNET_h2s (key));
1297 continue; /* Ignore bloomfiltered peers */
1303 if (0 == count) /* No peers to select from! */
1305 GNUNET_STATISTICS_update (GDS_stats,
1306 gettext_noop ("# Peer selection failed"), 1,
1310 /* Now actually choose a peer */
1311 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1313 for (bc = 0; bc <= closest_bucket; bc++)
1315 for (pos = k_buckets[bc].head; ((pos != NULL) && (count < bucket_size)); pos = pos->next)
1317 GNUNET_CRYPTO_hash (&pos->id,
1318 sizeof (struct GNUNET_PeerIdentity),
1320 if ((bloom != NULL) &&
1322 GNUNET_CONTAINER_bloomfilter_test (bloom, &phash)))
1324 continue; /* Ignore bloomfiltered peers */
1326 if (0 == selected--)
1336 * Compute the set of peers that the given request should be
1339 * @param key routing key
1340 * @param bloom bloom filter excluding peers as targets, all selected
1341 * peers will be added to the bloom filter
1342 * @param hop_count number of hops the request has traversed so far
1343 * @param target_replication desired number of replicas
1344 * @param targets where to store an array of target peers (to be
1345 * free'd by the caller)
1346 * @return number of peers returned in 'targets'.
1349 get_target_peers (const struct GNUNET_HashCode *key,
1350 struct GNUNET_CONTAINER_BloomFilter *bloom,
1351 uint32_t hop_count, uint32_t target_replication,
1352 struct PeerInfo ***targets)
1356 struct PeerInfo **rtargets;
1357 struct PeerInfo *nxt;
1358 struct GNUNET_HashCode nhash;
1360 GNUNET_assert (NULL != bloom);
1361 ret = get_forward_count (hop_count, target_replication);
1367 rtargets = GNUNET_malloc (sizeof (struct PeerInfo *) * ret);
1368 for (off = 0; off < ret; off++)
1370 nxt = select_peer (key, bloom, hop_count);
1373 rtargets[off] = nxt;
1374 GNUNET_CRYPTO_hash (&nxt->id,
1375 sizeof (struct GNUNET_PeerIdentity),
1377 GNUNET_break (GNUNET_NO ==
1378 GNUNET_CONTAINER_bloomfilter_test (bloom,
1380 GNUNET_CONTAINER_bloomfilter_add (bloom, &nhash);
1382 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1383 "Selected %u/%u peers at hop %u for %s (target was %u)\n",
1385 GNUNET_CONTAINER_multipeermap_size (all_connected_peers),
1386 (unsigned int) hop_count,
1391 GNUNET_free (rtargets);
1395 *targets = rtargets;
1396 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1397 "Forwarding query `%s' to %u peers (goal was %u peers)\n",
1406 * Perform a PUT operation. Forwards the given request to other
1407 * peers. Does not store the data locally. Does not give the
1408 * data to local clients. May do nothing if this is the only
1409 * peer in the network (or if we are the closest peer in the
1412 * @param type type of the block
1413 * @param options routing options
1414 * @param desired_replication_level desired replication count
1415 * @param expiration_time when does the content expire
1416 * @param hop_count how many hops has this message traversed so far
1417 * @param bf Bloom filter of peers this PUT has already traversed
1418 * @param key key for the content
1419 * @param put_path_length number of entries in @a put_path
1420 * @param put_path peers this request has traversed so far (if tracked)
1421 * @param data payload to store
1422 * @param data_size number of bytes in @a data
1423 * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1426 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1427 enum GNUNET_DHT_RouteOption options,
1428 uint32_t desired_replication_level,
1429 struct GNUNET_TIME_Absolute expiration_time,
1431 struct GNUNET_CONTAINER_BloomFilter *bf,
1432 const struct GNUNET_HashCode *key,
1433 unsigned int put_path_length,
1434 struct GNUNET_PeerIdentity *put_path,
1435 const void *data, size_t data_size)
1437 unsigned int target_count;
1439 struct PeerInfo **targets;
1440 struct PeerInfo *target;
1441 struct P2PPendingMessage *pending;
1443 struct PeerPutMessage *ppm;
1444 struct GNUNET_PeerIdentity *pp;
1445 struct GNUNET_HashCode thash;
1446 unsigned int skip_count;
1448 GNUNET_assert (NULL != bf);
1449 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1450 "Adding myself (%s) to PUT bloomfilter for %s\n",
1451 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1452 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity_hash);
1453 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# PUT requests routed"),
1456 get_target_peers (key, bf, hop_count, desired_replication_level,
1458 if (0 == target_count)
1460 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1461 "Routing PUT for %s terminates after %u hops at %s\n",
1462 GNUNET_h2s (key), (unsigned int) hop_count,
1463 GNUNET_i2s (&my_identity));
1467 put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size +
1468 sizeof (struct PeerPutMessage);
1469 if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1471 put_path_length = 0;
1472 msize = data_size + sizeof (struct PeerPutMessage);
1474 if (msize >= GNUNET_CONSTANTS_MAX_ENCRYPTED_MESSAGE_SIZE)
1477 GNUNET_free (targets);
1480 GNUNET_STATISTICS_update (GDS_stats,
1482 ("# PUT messages queued for transmission"),
1483 target_count, GNUNET_NO);
1485 for (i = 0; i < target_count; i++)
1487 target = targets[i];
1488 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1491 GNUNET_STATISTICS_update (GDS_stats,
1492 gettext_noop ("# P2P messages dropped due to full queue"),
1497 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1498 "Routing PUT for %s after %u hops to %s\n", GNUNET_h2s (key),
1499 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1500 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1501 pending->importance = 0; /* FIXME */
1502 pending->timeout = expiration_time;
1503 ppm = (struct PeerPutMessage *) &pending[1];
1504 pending->msg = &ppm->header;
1505 ppm->header.size = htons (msize);
1506 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1507 ppm->options = htonl (options);
1508 ppm->type = htonl (type);
1509 ppm->hop_count = htonl (hop_count + 1);
1510 ppm->desired_replication_level = htonl (desired_replication_level);
1511 ppm->put_path_length = htonl (put_path_length);
1512 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1513 GNUNET_CRYPTO_hash (&target->id,
1514 sizeof (struct GNUNET_PeerIdentity),
1516 GNUNET_break (GNUNET_YES ==
1517 GNUNET_CONTAINER_bloomfilter_test (bf,
1519 GNUNET_assert (GNUNET_OK ==
1520 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1524 pp = (struct GNUNET_PeerIdentity *) &ppm[1];
1525 memcpy (pp, put_path,
1526 sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1527 memcpy (&pp[put_path_length], data, data_size);
1528 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1529 target->pending_count++;
1530 process_peer_queue (target);
1532 GNUNET_free (targets);
1533 return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1538 * Perform a GET operation. Forwards the given request to other
1539 * peers. Does not lookup the key locally. May do nothing if this is
1540 * the only peer in the network (or if we are the closest peer in the
1543 * @param type type of the block
1544 * @param options routing options
1545 * @param desired_replication_level desired replication count
1546 * @param hop_count how many hops did this request traverse so far?
1547 * @param key key for the content
1548 * @param xquery extended query
1549 * @param xquery_size number of bytes in @a xquery
1550 * @param reply_bf bloomfilter to filter duplicates
1551 * @param reply_bf_mutator mutator for @a reply_bf
1552 * @param peer_bf filter for peers not to select (again)
1553 * @return #GNUNET_OK if the request was forwarded, #GNUNET_NO if not
1556 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1557 enum GNUNET_DHT_RouteOption options,
1558 uint32_t desired_replication_level,
1559 uint32_t hop_count, const struct GNUNET_HashCode * key,
1560 const void *xquery, size_t xquery_size,
1561 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1562 uint32_t reply_bf_mutator,
1563 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1565 unsigned int target_count;
1567 struct PeerInfo **targets;
1568 struct PeerInfo *target;
1569 struct P2PPendingMessage *pending;
1571 struct PeerGetMessage *pgm;
1573 size_t reply_bf_size;
1574 struct GNUNET_HashCode thash;
1575 unsigned int skip_count;
1577 GNUNET_assert (NULL != peer_bf);
1578 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# GET requests routed"),
1581 get_target_peers (key, peer_bf, hop_count, desired_replication_level,
1583 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1584 "Adding myself (%s) to GET bloomfilter for %s\n",
1585 GNUNET_i2s (&my_identity), GNUNET_h2s (key));
1586 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity_hash);
1587 if (0 == target_count)
1589 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1590 "Routing GET for %s terminates after %u hops at %s\n",
1591 GNUNET_h2s (key), (unsigned int) hop_count,
1592 GNUNET_i2s (&my_identity));
1595 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1596 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1597 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1600 GNUNET_free (targets);
1603 GNUNET_STATISTICS_update (GDS_stats,
1605 ("# GET messages queued for transmission"),
1606 target_count, GNUNET_NO);
1607 /* forward request */
1609 for (i = 0; i < target_count; i++)
1611 target = targets[i];
1612 if (target->pending_count >= MAXIMUM_PENDING_PER_PEER)
1615 GNUNET_STATISTICS_update (GDS_stats,
1616 gettext_noop ("# P2P messages dropped due to full queue"),
1621 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1622 "Routing GET for %s after %u hops to %s\n", GNUNET_h2s (key),
1623 (unsigned int) hop_count, GNUNET_i2s (&target->id));
1624 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1625 pending->importance = 0; /* FIXME */
1626 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1627 pgm = (struct PeerGetMessage *) &pending[1];
1628 pending->msg = &pgm->header;
1629 pgm->header.size = htons (msize);
1630 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1631 pgm->options = htonl (options);
1632 pgm->type = htonl (type);
1633 pgm->hop_count = htonl (hop_count + 1);
1634 pgm->desired_replication_level = htonl (desired_replication_level);
1635 pgm->xquery_size = htonl (xquery_size);
1636 pgm->bf_mutator = reply_bf_mutator;
1637 GNUNET_CRYPTO_hash (&target->id,
1638 sizeof (struct GNUNET_PeerIdentity),
1640 GNUNET_break (GNUNET_YES ==
1641 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
1643 GNUNET_assert (GNUNET_OK ==
1644 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1648 xq = (char *) &pgm[1];
1649 memcpy (xq, xquery, xquery_size);
1650 if (NULL != reply_bf)
1651 GNUNET_assert (GNUNET_OK ==
1652 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1656 GNUNET_CONTAINER_DLL_insert_tail (target->head, target->tail, pending);
1657 target->pending_count++;
1658 process_peer_queue (target);
1660 GNUNET_free (targets);
1661 return (skip_count < target_count) ? GNUNET_OK : GNUNET_NO;
1666 * Handle a reply (route to origin). Only forwards the reply back to
1667 * the given peer. Does not do local caching or forwarding to local
1670 * @param target neighbour that should receive the block (if still connected)
1671 * @param type type of the block
1672 * @param expiration_time when does the content expire
1673 * @param key key for the content
1674 * @param put_path_length number of entries in @a put_path
1675 * @param put_path peers the original PUT traversed (if tracked)
1676 * @param get_path_length number of entries in @a get_path
1677 * @param get_path peers this reply has traversed so far (if tracked)
1678 * @param data payload of the reply
1679 * @param data_size number of bytes in @a data
1682 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1683 enum GNUNET_BLOCK_Type type,
1684 struct GNUNET_TIME_Absolute expiration_time,
1685 const struct GNUNET_HashCode *key,
1686 unsigned int put_path_length,
1687 const struct GNUNET_PeerIdentity *put_path,
1688 unsigned int get_path_length,
1689 const struct GNUNET_PeerIdentity *get_path,
1693 struct PeerInfo *pi;
1694 struct P2PPendingMessage *pending;
1696 struct PeerResultMessage *prm;
1697 struct GNUNET_PeerIdentity *paths;
1700 data_size + sizeof (struct PeerResultMessage) + (get_path_length +
1702 sizeof (struct GNUNET_PeerIdentity);
1703 if ((msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1705 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1707 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1708 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE))
1713 pi = GNUNET_CONTAINER_multipeermap_get (all_connected_peers,
1717 /* peer disconnected in the meantime, drop reply */
1720 if (pi->pending_count >= MAXIMUM_PENDING_PER_PEER)
1723 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P messages dropped due to full queue"),
1728 GNUNET_STATISTICS_update (GDS_stats,
1730 ("# RESULT messages queued for transmission"), 1,
1732 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1733 pending->importance = 0; /* FIXME */
1734 pending->timeout = expiration_time;
1735 prm = (struct PeerResultMessage *) &pending[1];
1736 pending->msg = &prm->header;
1737 prm->header.size = htons (msize);
1738 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1739 prm->type = htonl (type);
1740 prm->put_path_length = htonl (put_path_length);
1741 prm->get_path_length = htonl (get_path_length);
1742 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1744 paths = (struct GNUNET_PeerIdentity *) &prm[1];
1745 memcpy (paths, put_path,
1746 put_path_length * sizeof (struct GNUNET_PeerIdentity));
1747 memcpy (&paths[put_path_length], get_path,
1748 get_path_length * sizeof (struct GNUNET_PeerIdentity));
1749 memcpy (&paths[put_path_length + get_path_length], data, data_size);
1750 GNUNET_CONTAINER_DLL_insert (pi->head, pi->tail, pending);
1751 pi->pending_count++;
1752 process_peer_queue (pi);
1757 * To be called on core init/fail.
1759 * @param cls service closure
1760 * @param identity the public identity of this peer
1763 core_init (void *cls,
1764 const struct GNUNET_PeerIdentity *identity)
1766 my_identity = *identity;
1767 GNUNET_CRYPTO_hash (identity,
1768 sizeof (struct GNUNET_PeerIdentity),
1774 * Core handler for p2p put requests.
1776 * @param cls closure
1777 * @param peer sender of the request
1778 * @param message message
1779 * @param peer peer identity this notification is about
1780 * @return #GNUNET_OK to keep the connection open,
1781 * #GNUNET_SYSERR to close it (signal serious error)
1784 handle_dht_p2p_put (void *cls, const struct GNUNET_PeerIdentity *peer,
1785 const struct GNUNET_MessageHeader *message)
1787 const struct PeerPutMessage *put;
1788 const struct GNUNET_PeerIdentity *put_path;
1789 const void *payload;
1792 size_t payload_size;
1793 enum GNUNET_DHT_RouteOption options;
1794 struct GNUNET_CONTAINER_BloomFilter *bf;
1795 struct GNUNET_HashCode test_key;
1796 struct GNUNET_HashCode phash;
1799 msize = ntohs (message->size);
1800 if (msize < sizeof (struct PeerPutMessage))
1802 GNUNET_break_op (0);
1805 put = (const struct PeerPutMessage *) message;
1806 putlen = ntohl (put->put_path_length);
1808 sizeof (struct PeerPutMessage) +
1809 putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1811 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
1813 GNUNET_break_op (0);
1816 GNUNET_STATISTICS_update (GDS_stats,
1817 gettext_noop ("# P2P PUT requests received"), 1,
1819 GNUNET_STATISTICS_update (GDS_stats,
1820 gettext_noop ("# P2P PUT bytes received"), msize,
1822 put_path = (const struct GNUNET_PeerIdentity *) &put[1];
1823 payload = &put_path[putlen];
1824 options = ntohl (put->options);
1826 msize - (sizeof (struct PeerPutMessage) +
1827 putlen * sizeof (struct GNUNET_PeerIdentity));
1829 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "PUT for `%s' from %s\n",
1830 GNUNET_h2s (&put->key), GNUNET_i2s (peer));
1831 GNUNET_CRYPTO_hash (peer, sizeof (struct GNUNET_PeerIdentity), &phash);
1832 if (GNUNET_YES == log_route_details_stderr)
1836 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
1837 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
1838 "R5N PUT %s: %s->%s (%u, %u=>%u)\n",
1839 GNUNET_h2s (&put->key), GNUNET_i2s (peer), tmp,
1840 ntohl(put->hop_count),
1841 GNUNET_CRYPTO_hash_matching_bits (&phash, &put->key),
1842 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &put->key)
1846 switch (GNUNET_BLOCK_get_key
1847 (GDS_block_context, ntohl (put->type), payload, payload_size,
1851 if (0 != memcmp (&test_key, &put->key, sizeof (struct GNUNET_HashCode)))
1853 char *put_s = GNUNET_strdup (GNUNET_h2s_full (&put->key));
1854 GNUNET_break_op (0);
1855 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1856 "PUT with key `%s' for block with key %s\n",
1857 put_s, GNUNET_h2s_full (&test_key));
1858 GNUNET_free (put_s);
1863 GNUNET_break_op (0);
1866 /* cannot verify, good luck */
1869 if (ntohl (put->type) == GNUNET_BLOCK_TYPE_REGEX) /* FIXME: do for all tpyes */
1871 switch (GNUNET_BLOCK_evaluate (GDS_block_context,
1873 GNUNET_BLOCK_EO_NONE,
1875 NULL, 0, /* bloom filer */
1876 NULL, 0, /* xquery */
1877 payload, payload_size))
1879 case GNUNET_BLOCK_EVALUATION_OK_MORE:
1880 case GNUNET_BLOCK_EVALUATION_OK_LAST:
1883 case GNUNET_BLOCK_EVALUATION_OK_DUPLICATE:
1884 case GNUNET_BLOCK_EVALUATION_RESULT_INVALID:
1885 case GNUNET_BLOCK_EVALUATION_RESULT_IRRELEVANT:
1886 case GNUNET_BLOCK_EVALUATION_REQUEST_VALID:
1887 case GNUNET_BLOCK_EVALUATION_REQUEST_INVALID:
1888 case GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED:
1890 GNUNET_break_op (0);
1895 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter, DHT_BLOOM_SIZE,
1896 GNUNET_CONSTANTS_BLOOMFILTER_K);
1897 GNUNET_break_op (GNUNET_YES ==
1898 GNUNET_CONTAINER_bloomfilter_test (bf, &phash));
1900 struct GNUNET_PeerIdentity pp[putlen + 1];
1902 /* extend 'put path' by sender */
1903 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1905 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1912 /* give to local clients */
1913 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1914 &put->key, 0, NULL, putlen, pp, ntohl (put->type),
1915 payload_size, payload);
1917 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1918 (am_closest_peer (&put->key, bf)))
1919 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh
1920 (put->expiration_time), &put->key, putlen, pp,
1921 ntohl (put->type), payload_size, payload);
1922 /* route to other peers */
1923 forwarded = GDS_NEIGHBOURS_handle_put (ntohl (put->type), options,
1924 ntohl (put->desired_replication_level),
1925 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1926 ntohl (put->hop_count), bf,
1932 /* notify monitoring clients */
1933 GDS_CLIENTS_process_put (options
1934 | ( (GNUNET_OK == forwarded)
1935 ? GNUNET_DHT_RO_LAST_HOP
1938 ntohl (put->hop_count),
1939 ntohl (put->desired_replication_level),
1941 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1946 GNUNET_CONTAINER_bloomfilter_free (bf);
1952 * We have received a FIND PEER request. Send matching
1955 * @param sender sender of the FIND PEER request
1956 * @param key peers close to this key are desired
1957 * @param bf peers matching this bf are excluded
1958 * @param bf_mutator mutator for bf
1961 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1962 const struct GNUNET_HashCode * key,
1963 struct GNUNET_CONTAINER_BloomFilter *bf, uint32_t bf_mutator)
1966 struct PeerBucket *bucket;
1967 struct PeerInfo *peer;
1968 unsigned int choice;
1969 struct GNUNET_HashCode phash;
1970 struct GNUNET_HashCode mhash;
1971 const struct GNUNET_HELLO_Message *hello;
1973 /* first, check about our own HELLO */
1974 if (NULL != GDS_my_hello)
1976 GNUNET_BLOCK_mingle_hash (&my_identity_hash, bf_mutator, &mhash);
1978 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)))
1980 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
1981 GNUNET_TIME_relative_to_absolute
1983 key, 0, NULL, 0, NULL, GDS_my_hello,
1984 GNUNET_HELLO_size ((const struct
1985 GNUNET_HELLO_Message *)
1990 GNUNET_STATISTICS_update (GDS_stats,
1992 ("# FIND PEER requests ignored due to Bloomfilter"),
1998 GNUNET_STATISTICS_update (GDS_stats,
2000 ("# FIND PEER requests ignored due to lack of HELLO"),
2004 /* then, also consider sending a random HELLO from the closest bucket */
2005 if (0 == memcmp (&my_identity_hash, key, sizeof (struct GNUNET_HashCode)))
2006 bucket_idx = closest_bucket;
2008 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
2009 if (bucket_idx == GNUNET_SYSERR)
2011 bucket = &k_buckets[bucket_idx];
2012 if (bucket->peers_size == 0)
2015 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, bucket->peers_size);
2016 peer = bucket->head;
2019 GNUNET_assert (NULL != peer);
2023 choice = bucket->peers_size;
2028 return; /* no non-masked peer available */
2030 peer = bucket->head;
2031 GNUNET_CRYPTO_hash (&peer->id, sizeof (struct GNUNET_PeerIdentity), &phash);
2032 GNUNET_BLOCK_mingle_hash (&phash, bf_mutator, &mhash);
2033 hello = GDS_HELLO_get (&peer->id);
2035 while ((hello == NULL) ||
2036 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)));
2037 GDS_NEIGHBOURS_handle_reply (sender, GNUNET_BLOCK_TYPE_DHT_HELLO,
2038 GNUNET_TIME_relative_to_absolute
2039 (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION), key,
2040 0, NULL, 0, NULL, hello,
2041 GNUNET_HELLO_size (hello));
2046 * Core handler for p2p get requests.
2048 * @param cls closure
2049 * @param peer sender of the request
2050 * @param message message
2051 * @return #GNUNET_OK to keep the connection open,
2052 * #GNUNET_SYSERR to close it (signal serious error)
2055 handle_dht_p2p_get (void *cls,
2056 const struct GNUNET_PeerIdentity *peer,
2057 const struct GNUNET_MessageHeader *message)
2059 struct PeerGetMessage *get;
2060 uint32_t xquery_size;
2061 size_t reply_bf_size;
2063 enum GNUNET_BLOCK_Type type;
2064 enum GNUNET_DHT_RouteOption options;
2065 enum GNUNET_BLOCK_EvaluationResult eval;
2066 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
2067 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
2069 struct GNUNET_HashCode phash;
2073 memcmp (peer, &my_identity,
2074 sizeof (struct GNUNET_PeerIdentity)));
2075 /* parse and validate message */
2076 msize = ntohs (message->size);
2077 if (msize < sizeof (struct PeerGetMessage))
2079 GNUNET_break_op (0);
2082 get = (struct PeerGetMessage *) message;
2083 xquery_size = ntohl (get->xquery_size);
2084 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
2086 GNUNET_break_op (0);
2089 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
2090 type = ntohl (get->type);
2091 options = ntohl (get->options);
2092 xquery = (const char *) &get[1];
2094 GNUNET_STATISTICS_update (GDS_stats,
2095 gettext_noop ("# P2P GET requests received"), 1,
2097 GNUNET_STATISTICS_update (GDS_stats,
2098 gettext_noop ("# P2P GET bytes received"), msize,
2100 GNUNET_CRYPTO_hash (peer,
2101 sizeof (struct GNUNET_PeerIdentity),
2103 if (GNUNET_YES == log_route_details_stderr)
2107 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
2108 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
2109 "R5N GET %s: %s->%s (%u, %u=>%u) xq: %.*s\n",
2110 GNUNET_h2s (&get->key), GNUNET_i2s (peer), tmp,
2111 ntohl(get->hop_count),
2112 GNUNET_CRYPTO_hash_matching_bits (&phash, &get->key),
2113 GNUNET_CRYPTO_hash_matching_bits (&my_identity_hash, &get->key),
2114 ntohl(get->xquery_size), xquery);
2118 if (reply_bf_size > 0)
2120 GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size], reply_bf_size,
2121 GNUNET_CONSTANTS_BLOOMFILTER_K);
2123 GNUNET_BLOCK_evaluate (GDS_block_context,
2125 GNUNET_BLOCK_EO_NONE,
2133 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
2135 /* request invalid or block type not supported */
2136 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
2137 if (NULL != reply_bf)
2138 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
2142 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter, DHT_BLOOM_SIZE,
2143 GNUNET_CONSTANTS_BLOOMFILTER_K);
2144 GNUNET_break_op (GNUNET_YES ==
2145 GNUNET_CONTAINER_bloomfilter_test (peer_bf,
2147 /* remember request for routing replies */
2148 GDS_ROUTING_add (peer, type, options, &get->key, xquery, xquery_size,
2149 reply_bf, get->bf_mutator);
2150 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2151 "GET for %s at %s after %u hops\n",
2152 GNUNET_h2s (&get->key),
2153 GNUNET_i2s (&my_identity),
2154 (unsigned int) ntohl (get->hop_count));
2155 /* local lookup (this may update the reply_bf) */
2156 if ((0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
2157 (am_closest_peer (&get->key, peer_bf)))
2159 if ((0 != (options & GNUNET_DHT_RO_FIND_PEER)))
2161 GNUNET_STATISTICS_update (GDS_stats,
2163 ("# P2P FIND PEER requests processed"), 1,
2165 handle_find_peer (peer, &get->key, reply_bf, get->bf_mutator);
2170 GDS_DATACACHE_handle_get (&get->key, type, xquery, xquery_size,
2171 &reply_bf, get->bf_mutator);
2176 GNUNET_STATISTICS_update (GDS_stats,
2177 gettext_noop ("# P2P GET requests ONLY routed"),
2181 /* P2P forwarding */
2182 forwarded = GNUNET_NO;
2183 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
2184 forwarded = GDS_NEIGHBOURS_handle_get (type, options,
2185 ntohl (get->desired_replication_level),
2186 ntohl (get->hop_count),
2191 get->bf_mutator, peer_bf);
2192 GDS_CLIENTS_process_get (options
2193 | (GNUNET_OK == forwarded)
2194 ? GNUNET_DHT_RO_LAST_HOP : 0,
2196 ntohl (get->hop_count),
2197 ntohl (get->desired_replication_level),
2203 if (NULL != reply_bf)
2204 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
2205 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
2211 * Core handler for p2p result messages.
2213 * @param cls closure
2214 * @param message message
2215 * @param peer peer identity this notification is about
2216 * @return #GNUNET_YES (do not cut p2p connection)
2219 handle_dht_p2p_result (void *cls,
2220 const struct GNUNET_PeerIdentity *peer,
2221 const struct GNUNET_MessageHeader *message)
2223 const struct PeerResultMessage *prm;
2224 const struct GNUNET_PeerIdentity *put_path;
2225 const struct GNUNET_PeerIdentity *get_path;
2227 uint32_t get_path_length;
2228 uint32_t put_path_length;
2231 enum GNUNET_BLOCK_Type type;
2233 /* parse and validate message */
2234 msize = ntohs (message->size);
2235 if (msize < sizeof (struct PeerResultMessage))
2237 GNUNET_break_op (0);
2240 prm = (struct PeerResultMessage *) message;
2241 put_path_length = ntohl (prm->put_path_length);
2242 get_path_length = ntohl (prm->get_path_length);
2244 sizeof (struct PeerResultMessage) + (get_path_length +
2246 sizeof (struct GNUNET_PeerIdentity)) ||
2248 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
2250 GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)))
2252 GNUNET_break_op (0);
2255 put_path = (const struct GNUNET_PeerIdentity *) &prm[1];
2256 get_path = &put_path[put_path_length];
2257 type = ntohl (prm->type);
2258 data = (const void *) &get_path[get_path_length];
2260 msize - (sizeof (struct PeerResultMessage) +
2262 put_path_length) * sizeof (struct GNUNET_PeerIdentity));
2263 GNUNET_STATISTICS_update (GDS_stats, gettext_noop ("# P2P RESULTS received"),
2265 GNUNET_STATISTICS_update (GDS_stats,
2266 gettext_noop ("# P2P RESULT bytes received"),
2268 if (GNUNET_YES == log_route_details_stderr)
2272 tmp = GNUNET_strdup (GNUNET_i2s (&my_identity));
2273 LOG_TRAFFIC (GNUNET_ERROR_TYPE_DEBUG,
2274 "R5N RESULT %s: %s->%s (%u)\n",
2275 GNUNET_h2s (&prm->key),
2278 get_path_length + 1);
2281 /* if we got a HELLO, consider it for our own routing table */
2282 if (GNUNET_BLOCK_TYPE_DHT_HELLO == type)
2284 const struct GNUNET_MessageHeader *h;
2285 struct GNUNET_PeerIdentity pid;
2287 /* Should be a HELLO, validate and consider using it! */
2288 if (data_size < sizeof (struct GNUNET_MessageHeader))
2290 GNUNET_break_op (0);
2294 if (data_size != ntohs (h->size))
2296 GNUNET_break_op (0);
2300 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message *) h,
2303 GNUNET_break_op (0);
2306 if ( (GNUNET_YES != disable_try_connect) &&
2307 (0 != memcmp (&my_identity,
2309 sizeof (struct GNUNET_PeerIdentity))) )
2314 /* append 'peer' to 'get_path' */
2316 struct GNUNET_PeerIdentity xget_path[get_path_length + 1];
2320 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2321 xget_path[get_path_length] = *peer;
2324 /* forward to local clients */
2325 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2334 GDS_CLIENTS_process_get_resp (type,
2337 put_path, put_path_length,
2338 GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2342 if (GNUNET_YES == cache_results)
2344 struct GNUNET_PeerIdentity xput_path[get_path_length + 1 + put_path_length];
2346 memcpy (xput_path, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
2347 memcpy (&xput_path[put_path_length],
2349 get_path_length * sizeof (struct GNUNET_PeerIdentity));
2351 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2353 get_path_length + put_path_length,
2359 /* forward to other peers */
2360 GDS_ROUTING_process (type,
2361 GNUNET_TIME_absolute_ntoh (prm->expiration_time),
2376 * Initialize neighbours subsystem.
2378 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
2381 GDS_NEIGHBOURS_init ()
2383 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
2384 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
2385 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
2386 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
2389 unsigned long long temp_config_num;
2392 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "DISABLE_TRY_CONNECT");
2394 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
2396 bucket_size = (unsigned int) temp_config_num;
2398 = GNUNET_CONFIGURATION_get_value_yesno (GDS_cfg, "DHT", "CACHE_RESULTS");
2400 log_route_details_stderr =
2401 (NULL != getenv("GNUNET_DHT_ROUTE_DEBUG")) ? GNUNET_YES : GNUNET_NO;
2402 ats_ch = GNUNET_ATS_connectivity_init (GDS_cfg);
2404 GNUNET_CORE_connect (GDS_cfg, NULL,
2406 &handle_core_connect,
2407 &handle_core_disconnect,
2411 if (core_api == NULL)
2412 return GNUNET_SYSERR;
2413 all_connected_peers = GNUNET_CONTAINER_multipeermap_create (256,
2415 all_desired_peers = GNUNET_CONTAINER_multipeermap_create (256,
2422 * Shutdown neighbours subsystem.
2425 GDS_NEIGHBOURS_done ()
2427 if (NULL == core_api)
2429 GNUNET_CORE_disconnect (core_api);
2431 GNUNET_assert (0 == GNUNET_CONTAINER_multipeermap_size (all_connected_peers));
2432 GNUNET_CONTAINER_multipeermap_destroy (all_connected_peers);
2433 all_connected_peers = NULL;
2434 GNUNET_CONTAINER_multipeermap_iterate (all_desired_peers,
2437 GNUNET_CONTAINER_multipeermap_destroy (all_desired_peers);
2438 all_desired_peers = NULL;
2439 GNUNET_ATS_connectivity_done (ats_ch);
2441 if (NULL != find_peer_task)
2443 GNUNET_SCHEDULER_cancel (find_peer_task);
2444 find_peer_task = NULL;
2449 * Get the ID of the local node.
2451 * @return identity of the local node
2453 struct GNUNET_PeerIdentity *
2454 GDS_NEIGHBOURS_get_id ()
2456 return &my_identity;
2460 /* end of gnunet-service-dht_neighbours.c */