2 This file is part of GNUnet.
3 (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file dht/gnunet-service-dht_neighbours.c
23 * @brief GNUnet DHT service's bucket and neighbour management code
24 * @author Christian Grothoff
25 * @author Nathan Evans
29 #include "gnunet_block_lib.h"
30 #include "gnunet_util_lib.h"
31 #include "gnunet_hello_lib.h"
32 #include "gnunet_constants.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_nse_service.h"
35 #include "gnunet_core_service.h"
36 #include "gnunet_datacache_lib.h"
37 #include "gnunet_transport_service.h"
38 #include "gnunet_hello_lib.h"
39 #include "gnunet_dht_service.h"
40 #include "gnunet_statistics_service.h"
41 #include "gnunet-service-dht.h"
42 #include "gnunet-service-dht_clients.h"
43 #include "gnunet-service-dht_datacache.h"
44 #include "gnunet-service-dht_hello.h"
45 #include "gnunet-service-dht_neighbours.h"
46 #include "gnunet-service-dht_nse.h"
47 #include "gnunet-service-dht_routing.h"
52 * How many buckets will we allow total.
54 #define MAX_BUCKETS sizeof (GNUNET_HashCode) * 8
57 * What is the maximum number of peers in a given bucket.
59 #define DEFAULT_BUCKET_SIZE 4
62 * Desired replication level for FIND PEER requests
64 #define FIND_PEER_REPLICATION_LEVEL 4
67 * Maximum allowed replication level for all requests.
69 #define MAXIMUM_REPLICATION_LEVEL 16
72 * How often to update our preference levels for peers in our routing tables.
74 #define DHT_DEFAULT_PREFERENCE_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
77 * How long at least to wait before sending another find peer request.
79 #define DHT_MINIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
82 * How long at most to wait before sending another find peer request.
84 #define DHT_MAXIMUM_FIND_PEER_INTERVAL GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 10)
87 * How long at most to wait for transmission of a GET request to another peer?
89 #define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 2)
98 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_PUT
100 struct GNUNET_MessageHeader header;
105 uint32_t options GNUNET_PACKED;
110 uint32_t type GNUNET_PACKED;
115 uint32_t hop_count GNUNET_PACKED;
118 * Replication level for this message
120 uint32_t desired_replication_level GNUNET_PACKED;
123 * Length of the PUT path that follows (if tracked).
125 uint32_t put_path_length GNUNET_PACKED;
128 * When does the content expire?
130 struct GNUNET_TIME_AbsoluteNBO expiration_time;
133 * Bloomfilter (for peer identities) to stop circular routes
135 char bloomfilter[DHT_BLOOM_SIZE];
138 * The key we are storing under.
142 /* put path (if tracked) */
152 struct PeerResultMessage
155 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT
157 struct GNUNET_MessageHeader header;
162 uint32_t type GNUNET_PACKED;
165 * Length of the PUT path that follows (if tracked).
167 uint32_t put_path_length GNUNET_PACKED;
170 * Length of the GET path that follows (if tracked).
172 uint32_t get_path_length GNUNET_PACKED;
175 * When does the content expire?
177 struct GNUNET_TIME_AbsoluteNBO expiration_time;
180 * The key of the corresponding GET request.
184 /* put path (if tracked) */
186 /* get path (if tracked) */
196 struct PeerGetMessage
199 * Type: GNUNET_MESSAGE_TYPE_DHT_P2P_GET
201 struct GNUNET_MessageHeader header;
206 uint32_t options GNUNET_PACKED;
209 * Desired content type.
211 uint32_t type GNUNET_PACKED;
216 uint32_t hop_count GNUNET_PACKED;
219 * Desired replication level for this request.
221 uint32_t desired_replication_level GNUNET_PACKED;
224 * Size of the extended query.
226 uint32_t xquery_size;
229 * Bloomfilter mutator.
234 * Bloomfilter (for peer identities) to stop circular routes
236 char bloomfilter[DHT_BLOOM_SIZE];
239 * The key we are looking for.
245 /* result bloomfilter */
251 * Linked list of messages to send to a particular other peer.
253 struct P2PPendingMessage
256 * Pointer to next item in the list
258 struct P2PPendingMessage *next;
261 * Pointer to previous item in the list
263 struct P2PPendingMessage *prev;
266 * Message importance level. FIXME: used? useful?
268 unsigned int importance;
271 * When does this message time out?
273 struct GNUNET_TIME_Absolute timeout;
276 * Actual message to be sent, allocated at the end of the struct:
277 * // msg = (cast) &pm[1];
278 * // memcpy (&pm[1], data, len);
280 const struct GNUNET_MessageHeader *msg;
286 * Entry for a peer in a bucket.
291 * Next peer entry (DLL)
293 struct PeerInfo *next;
296 * Prev peer entry (DLL)
298 struct PeerInfo *prev;
301 * Count of outstanding messages for peer. FIXME: NEEDED?
302 * FIXME: bound queue size!?
304 unsigned int pending_count;
307 * Head of pending messages to be sent to this peer.
309 struct P2PPendingMessage *head;
312 * Tail of pending messages to be sent to this peer.
314 struct P2PPendingMessage *tail;
317 * Core handle for sending messages to this peer.
319 struct GNUNET_CORE_TransmitHandle *th;
322 * Preference update context
324 struct GNUNET_CORE_InformationRequestContext *info_ctx;
327 * Task for scheduling preference updates
329 GNUNET_SCHEDULER_TaskIdentifier preference_task;
332 * What is the identity of the peer?
334 struct GNUNET_PeerIdentity id;
338 * What is the average latency for replies received?
340 struct GNUNET_TIME_Relative latency;
343 * Transport level distance to peer.
345 unsigned int distance;
352 * Peers are grouped into buckets.
359 struct PeerInfo *head;
364 struct PeerInfo *tail;
367 * Number of peers in the bucket.
369 unsigned int peers_size;
374 * The lowest currently used bucket, initially 0 (for 0-bits matching bucket).
376 static unsigned int closest_bucket;
379 * How many peers have we added since we sent out our last
382 static unsigned int newly_found_peers;
385 * The buckets. Array of size MAX_BUCKET_SIZE. Offset 0 means 0 bits matching.
387 static struct PeerBucket k_buckets[MAX_BUCKETS];
390 * Hash map of all known peers, for easy removal from k_buckets on disconnect.
392 static struct GNUNET_CONTAINER_MultiHashMap *all_known_peers;
395 * Maximum size for each bucket.
397 static unsigned int bucket_size = DEFAULT_BUCKET_SIZE;
400 * Task that sends FIND PEER requests.
402 static GNUNET_SCHEDULER_TaskIdentifier find_peer_task;
405 * Identity of this peer.
407 static struct GNUNET_PeerIdentity my_identity;
410 * Handle to GNUnet core.
412 static struct GNUNET_CORE_Handle *coreAPI;
416 * Find the optimal bucket for this key.
418 * @param hc the hashcode to compare our identity to
419 * @return the proper bucket index, or GNUNET_SYSERR
420 * on error (same hashcode)
423 find_bucket (const GNUNET_HashCode * hc)
427 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, hc);
428 if (bits == MAX_BUCKETS)
430 /* How can all bits match? Got my own ID? */
432 return GNUNET_SYSERR;
434 return MAX_BUCKETS - bits - 1;
439 * Let GNUnet core know that we like the given peer.
441 * @param cls the 'struct PeerInfo' of the peer
442 * @param tc scheduler context.
445 update_core_preference (void *cls,
446 const struct GNUNET_SCHEDULER_TaskContext *tc);
450 * Function called with statistics about the given peer.
453 * @param peer identifies the peer
454 * @param bpm_out set to the current bandwidth limit (sending) for this peer
455 * @param amount set to the amount that was actually reserved or unreserved;
456 * either the full requested amount or zero (no partial reservations)
457 * @param res_delay if the reservation could not be satisfied (amount was 0), how
458 * long should the client wait until re-trying?
459 * @param preference current traffic preference for the given peer
462 update_core_preference_finish (void *cls,
463 const struct GNUNET_PeerIdentity *peer,
464 struct GNUNET_BANDWIDTH_Value32NBO bpm_out,
466 struct GNUNET_TIME_Relative res_delay,
469 struct PeerInfo *peer_info = cls;
471 peer_info->info_ctx = NULL;
472 peer_info->preference_task
473 = GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
474 &update_core_preference, peer_info);
479 * Let GNUnet core know that we like the given peer.
481 * @param cls the 'struct PeerInfo' of the peer
482 * @param tc scheduler context.
485 update_core_preference (void *cls,
486 const struct GNUNET_SCHEDULER_TaskContext *tc)
488 struct PeerInfo *peer = cls;
490 unsigned int matching;
493 peer->preference_task = GNUNET_SCHEDULER_NO_TASK;
494 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
497 GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey,
498 &peer->id.hashPubKey);
501 bucket = find_bucket (&peer->id.hashPubKey);
502 if (bucket == GNUNET_SYSERR)
505 preference = (1LL << matching) / k_buckets[bucket].peers_size;
508 peer->preference_task
509 = GNUNET_SCHEDULER_add_delayed (DHT_DEFAULT_PREFERENCE_INTERVAL,
510 &update_core_preference, peer);
513 GNUNET_STATISTICS_update (GDS_stats,
514 gettext_noop ("# Preference updates given to core"), 1,
517 GNUNET_CORE_peer_change_preference (coreAPI, &peer->id,
518 GNUNET_TIME_UNIT_FOREVER_REL,
519 GNUNET_BANDWIDTH_VALUE_MAX, 0,
521 &update_core_preference_finish, peer);
526 * Closure for 'add_known_to_bloom'.
528 struct BloomConstructorContext
531 * Bloom filter under construction.
533 struct GNUNET_CONTAINER_BloomFilter *bloom;
543 * Add each of the peers we already know to the bloom filter of
544 * the request so that we don't get duplicate HELLOs.
546 * @param cls the 'struct BloomConstructorContext'.
547 * @param key peer identity to add to the bloom filter
548 * @param value value the peer information (unused)
549 * @return GNUNET_YES (we should continue to iterate)
552 add_known_to_bloom (void *cls, const GNUNET_HashCode * key, void *value)
554 struct BloomConstructorContext *ctx = cls;
557 GNUNET_BLOCK_mingle_hash (key, ctx->bf_mutator, &mh);
558 GNUNET_CONTAINER_bloomfilter_add (ctx->bloom, &mh);
564 * Task to send a find peer message for our own peer identifier
565 * so that we can find the closest peers in the network to ourselves
566 * and attempt to connect to them.
568 * @param cls closure for this task
569 * @param tc the context under which the task is running
572 send_find_peer_message (void *cls,
573 const struct GNUNET_SCHEDULER_TaskContext *tc)
575 struct GNUNET_TIME_Relative next_send_time;
576 struct BloomConstructorContext bcc;
577 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
579 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
580 if ((tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN) != 0)
582 if (newly_found_peers > bucket_size)
584 /* If we are finding many peers already, no need to send out our request right now! */
585 find_peer_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES,
586 &send_find_peer_message, NULL);
587 newly_found_peers = 0;
590 bcc.bf_mutator = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
592 GNUNET_CONTAINER_bloomfilter_init (NULL, DHT_BLOOM_SIZE, GNUNET_CONSTANTS_BLOOMFILTER_K);
593 GNUNET_CONTAINER_multihashmap_iterate (all_known_peers,
596 GNUNET_STATISTICS_update (GDS_stats,
597 gettext_noop ("# FIND PEER messages initiated"), 1,
599 peer_bf = GNUNET_CONTAINER_bloomfilter_init (NULL,
601 GNUNET_CONSTANTS_BLOOMFILTER_K);
602 // FIXME: pass priority!?
603 GDS_NEIGHBOURS_handle_get (GNUNET_BLOCK_TYPE_DHT_HELLO,
604 GNUNET_DHT_RO_FIND_PEER,
605 FIND_PEER_REPLICATION_LEVEL,
607 &my_identity.hashPubKey,
609 bcc.bloom, bcc.bf_mutator,
611 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
612 GNUNET_CONTAINER_bloomfilter_free (bcc.bloom);
613 /* schedule next round */
614 next_send_time.rel_value =
615 DHT_MINIMUM_FIND_PEER_INTERVAL.rel_value +
616 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
617 DHT_MAXIMUM_FIND_PEER_INTERVAL.rel_value / (newly_found_peers+1));
618 newly_found_peers = 0;
619 find_peer_task = GNUNET_SCHEDULER_add_delayed (next_send_time,
620 &send_find_peer_message,
626 * Method called whenever a peer connects.
629 * @param peer peer identity this notification is about
630 * @param atsi performance data
633 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
634 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
636 struct PeerInfo *ret;
639 /* Check for connect to self message */
640 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
643 GNUNET_CONTAINER_multihashmap_contains (all_known_peers,
649 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
650 "Peer `%s' connected!\n",
652 GNUNET_STATISTICS_update (GDS_stats,
653 gettext_noop ("# Peers connected"), 1,
655 peer_bucket = find_bucket (&peer->hashPubKey);
656 GNUNET_assert ( (peer_bucket >= 0) && (peer_bucket < MAX_BUCKETS) );
657 ret = GNUNET_malloc (sizeof (struct PeerInfo));
659 ret->latency = latency;
660 ret->distance = distance;
663 GNUNET_CONTAINER_DLL_insert_tail (k_buckets[peer_bucket].head,
664 k_buckets[peer_bucket].tail, ret);
665 k_buckets[peer_bucket].peers_size++;
666 closest_bucket = GNUNET_MAX (closest_bucket,
668 if ( (peer_bucket > 0) &&
669 (k_buckets[peer_bucket].peers_size <= bucket_size) )
671 ret->preference_task = GNUNET_SCHEDULER_add_now (&update_core_preference, ret);
674 GNUNET_assert (GNUNET_OK ==
675 GNUNET_CONTAINER_multihashmap_put (all_known_peers,
676 &peer->hashPubKey, ret,
677 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
678 if (1 == GNUNET_CONTAINER_multihashmap_size (all_known_peers))
680 /* got a first connection, good time to start with FIND PEER requests... */
681 find_peer_task = GNUNET_SCHEDULER_add_now (&send_find_peer_message,
688 * Method called whenever a peer disconnects.
691 * @param peer peer identity this notification is about
694 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
696 struct PeerInfo *to_remove;
698 struct P2PPendingMessage *pos;
700 /* Check for disconnect from self message */
701 if (0 == memcmp (&my_identity, peer, sizeof (struct GNUNET_PeerIdentity)))
704 GNUNET_CONTAINER_multihashmap_get (all_known_peers, &peer->hashPubKey);
705 if (NULL == to_remove)
710 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
711 "Peer `%s' disconnected!\n",
713 GNUNET_STATISTICS_update (GDS_stats,
714 gettext_noop ("# Peers connected"), -1,
716 GNUNET_assert (GNUNET_YES ==
717 GNUNET_CONTAINER_multihashmap_remove (all_known_peers,
720 if (NULL != to_remove->info_ctx)
722 GNUNET_CORE_peer_change_preference_cancel (to_remove->info_ctx);
723 to_remove->info_ctx = NULL;
725 if (GNUNET_SCHEDULER_NO_TASK != to_remove->preference_task)
727 GNUNET_SCHEDULER_cancel (to_remove->preference_task);
728 to_remove->preference_task = GNUNET_SCHEDULER_NO_TASK;
730 current_bucket = find_bucket (&to_remove->id.hashPubKey);
731 GNUNET_CONTAINER_DLL_remove (k_buckets[current_bucket].head,
732 k_buckets[current_bucket].tail,
734 GNUNET_assert (k_buckets[current_bucket].peers_size > 0);
735 k_buckets[current_bucket].peers_size--;
736 while ( (closest_bucket > 0) &&
737 (k_buckets[closest_bucket].peers_size == 0) )
740 if (to_remove->th != NULL)
742 GNUNET_CORE_notify_transmit_ready_cancel (to_remove->th);
743 to_remove->th = NULL;
745 while (NULL != (pos = to_remove->head))
747 GNUNET_CONTAINER_DLL_remove (to_remove->head,
756 * Called when core is ready to send a message we asked for
757 * out to the destination.
759 * @param cls the 'struct PeerInfo' of the target peer
760 * @param size number of bytes available in buf
761 * @param buf where the callee should write the message
762 * @return number of bytes written to buf
765 core_transmit_notify (void *cls, size_t size, void *buf)
767 struct PeerInfo *peer = cls;
769 struct P2PPendingMessage *pending;
776 /* client disconnected */
779 if (peer->head == NULL)
781 /* no messages pending */
785 while ( (NULL != (pending = peer->head)) &&
786 (size - off >= (msize = ntohs (pending->msg->size))) )
788 GNUNET_STATISTICS_update (GDS_stats,
789 gettext_noop ("# Bytes transmitted to other peers"), msize,
791 memcpy (&cbuf[off], pending->msg, msize);
793 peer->pending_count--;
794 GNUNET_CONTAINER_DLL_remove (peer->head, peer->tail, pending);
795 GNUNET_free (pending);
797 if (peer->head != NULL)
800 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
802 GNUNET_TIME_absolute_get_remaining (pending->timeout),
804 &core_transmit_notify, peer);
811 * Transmit all messages in the peer's message queue.
813 * @param peer message queue to process
816 process_peer_queue (struct PeerInfo *peer)
818 struct P2PPendingMessage *pending;
820 if (NULL == (pending = peer->head))
822 if (NULL != peer->th)
824 GNUNET_STATISTICS_update (GDS_stats,
825 gettext_noop ("# Bytes of bandwdith requested from core"),
826 ntohs (pending->msg->size),
829 = GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_YES,
831 GNUNET_TIME_absolute_get_remaining (pending->timeout),
833 ntohs (pending->msg->size),
834 &core_transmit_notify, peer);
839 * To how many peers should we (on average) forward the request to
840 * obtain the desired target_replication count (on average).
842 * @param hop_count number of hops the message has traversed
843 * @param target_replication the number of total paths desired
844 * @return Some number of peers to forward the message to
847 get_forward_count (uint32_t hop_count,
848 uint32_t target_replication)
850 uint32_t random_value;
851 uint32_t forward_count;
854 if (hop_count > GDS_NSE_get () * 4.0)
856 /* forcefully terminate */
859 if (hop_count > GDS_NSE_get () * 2.0)
861 /* Once we have reached our ideal number of hops, only forward to 1 peer */
864 /* bound by system-wide maximum */
865 target_replication = GNUNET_MIN (MAXIMUM_REPLICATION_LEVEL,
868 1 + (target_replication - 1.0) / (GDS_NSE_get () +
869 ((float) (target_replication - 1.0) *
871 /* Set forward count to floor of target_value */
872 forward_count = (uint32_t) target_value;
873 /* Subtract forward_count (floor) from target_value (yields value between 0 and 1) */
874 target_value = target_value - forward_count;
876 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
877 if (random_value < (target_value * UINT32_MAX))
879 return forward_count;
884 * Compute the distance between have and target as a 32-bit value.
885 * Differences in the lower bits must count stronger than differences
886 * in the higher bits.
888 * @return 0 if have==target, otherwise a number
889 * that is larger as the distance between
890 * the two hash codes increases
893 get_distance (const GNUNET_HashCode * target, const GNUNET_HashCode * have)
900 /* We have to represent the distance between two 2^9 (=512)-bit
901 * numbers as a 2^5 (=32)-bit number with "0" being used for the
902 * two numbers being identical; furthermore, we need to
903 * guarantee that a difference in the number of matching
904 * bits is always represented in the result.
906 * We use 2^32/2^9 numerical values to distinguish between
907 * hash codes that have the same LSB bit distance and
908 * use the highest 2^9 bits of the result to signify the
909 * number of (mis)matching LSB bits; if we have 0 matching
910 * and hence 512 mismatching LSB bits we return -1 (since
911 * 512 itself cannot be represented with 9 bits) */
913 /* first, calculate the most significant 9 bits of our
914 * result, aka the number of LSBs */
915 bucket = GNUNET_CRYPTO_hash_matching_bits (target, have);
916 /* bucket is now a value between 0 and 512 */
918 return 0; /* perfect match */
920 return (unsigned int) -1; /* LSB differs; use max (if we did the bit-shifting
921 * below, we'd end up with max+1 (overflow)) */
923 /* calculate the most significant bits of the final result */
924 msb = (512 - bucket) << (32 - 9);
925 /* calculate the 32-9 least significant bits of the final result by
926 * looking at the differences in the 32-9 bits following the
927 * mismatching bit at 'bucket' */
930 (i < sizeof (GNUNET_HashCode) * 8) && (i < bucket + 1 + 32 - 9); i++)
932 if (GNUNET_CRYPTO_hash_get_bit (target, i) !=
933 GNUNET_CRYPTO_hash_get_bit (have, i))
934 lsb |= (1 << (bucket + 32 - 9 - i)); /* first bit set will be 10,
935 * last bit set will be 31 -- if
936 * i does not reach 512 first... */
943 * Check whether my identity is closer than any known peers. If a
944 * non-null bloomfilter is given, check if this is the closest peer
945 * that hasn't already been routed to.
947 * @param key hash code to check closeness to
948 * @param bloom bloomfilter, exclude these entries from the decision
949 * @return GNUNET_YES if node location is closest,
950 * GNUNET_NO otherwise.
953 am_closest_peer (const GNUNET_HashCode *key,
954 const struct GNUNET_CONTAINER_BloomFilter *bloom)
960 struct PeerInfo *pos;
962 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
964 bucket_num = find_bucket (key);
965 bits = GNUNET_CRYPTO_hash_matching_bits (&my_identity.hashPubKey, key);
966 pos = k_buckets[bucket_num].head;
968 while ((pos != NULL) && (count < bucket_size))
970 if ((bloom != NULL) &&
972 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)))
975 continue; /* Skip already checked entries */
977 other_bits = GNUNET_CRYPTO_hash_matching_bits (&pos->id.hashPubKey, key);
978 if (other_bits > bits)
980 if (other_bits == bits) /* We match the same number of bits */
984 /* No peers closer, we are the closest! */
990 * Select a peer from the routing table that would be a good routing
991 * destination for sending a message for "key". The resulting peer
992 * must not be in the set of blocked peers.<p>
994 * Note that we should not ALWAYS select the closest peer to the
995 * target, peers further away from the target should be chosen with
996 * exponentially declining probability.
998 * FIXME: double-check that this is fine
1001 * @param key the key we are selecting a peer to route to
1002 * @param bloom a bloomfilter containing entries this request has seen already
1003 * @param hops how many hops has this message traversed thus far
1004 * @return Peer to route to, or NULL on error
1006 static struct PeerInfo *
1007 select_peer (const GNUNET_HashCode *key,
1008 const struct GNUNET_CONTAINER_BloomFilter *bloom,
1013 unsigned int selected;
1014 struct PeerInfo *pos;
1016 unsigned int smallest_distance;
1017 struct PeerInfo *chosen;
1019 if (hops >= GDS_NSE_get ())
1021 /* greedy selection (closest peer that is not in bloomfilter) */
1022 smallest_distance = UINT_MAX;
1024 for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1026 pos = k_buckets[bc].head;
1028 while ((pos != NULL) && (count < bucket_size))
1031 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey))
1033 dist = get_distance (key, &pos->id.hashPubKey);
1034 if (dist < smallest_distance)
1037 smallest_distance = dist;
1042 GNUNET_STATISTICS_update (GDS_stats,
1043 gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1051 GNUNET_STATISTICS_update (GDS_stats,
1052 gettext_noop ("# Peer selection failed"), 1,
1057 /* select "random" peer */
1058 /* count number of peers that are available and not filtered */
1060 for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1062 pos = k_buckets[bc].head;
1063 while ((pos != NULL) && (count < bucket_size))
1065 if ( (bloom != NULL) &&
1067 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1069 GNUNET_STATISTICS_update (GDS_stats,
1070 gettext_noop ("# Peers excluded from routing due to Bloomfilter"), 1,
1073 continue; /* Ignore bloomfiltered peers */
1079 if (count == 0) /* No peers to select from! */
1081 GNUNET_STATISTICS_update (GDS_stats,
1082 gettext_noop ("# Peer selection failed"), 1,
1086 /* Now actually choose a peer */
1087 selected = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, count);
1089 for (bc = closest_bucket; bc < MAX_BUCKETS; bc++)
1091 pos = k_buckets[bc].head;
1092 while ((pos != NULL) && (count < bucket_size))
1094 if ( (bloom != NULL) &&
1096 GNUNET_CONTAINER_bloomfilter_test (bloom, &pos->id.hashPubKey)) )
1099 continue; /* Ignore bloomfiltered peers */
1101 if (0 == selected--)
1112 * Compute the set of peers that the given request should be
1115 * @param key routing key
1116 * @param bloom bloom filter excluding peers as targets, all selected
1117 * peers will be added to the bloom filter
1118 * @param hop_count number of hops the request has traversed so far
1119 * @param target_replication desired number of replicas
1120 * @param targets where to store an array of target peers (to be
1121 * free'd by the caller)
1122 * @return number of peers returned in 'targets'.
1125 get_target_peers (const GNUNET_HashCode *key,
1126 struct GNUNET_CONTAINER_BloomFilter *bloom,
1128 uint32_t target_replication,
1129 struct PeerInfo ***targets)
1133 struct PeerInfo **rtargets;
1134 struct PeerInfo *nxt;
1136 GNUNET_assert (NULL != bloom);
1137 ret = get_forward_count (hop_count, target_replication);
1143 rtargets = GNUNET_malloc (sizeof (struct PeerInfo*) * ret);
1147 nxt = select_peer (key, bloom, hop_count);
1150 rtargets[off++] = nxt;
1151 GNUNET_break (GNUNET_NO ==
1152 GNUNET_CONTAINER_bloomfilter_test (bloom, &nxt->id.hashPubKey));
1153 GNUNET_CONTAINER_bloomfilter_add (bloom, &nxt->id.hashPubKey);
1157 GNUNET_free (rtargets);
1161 *targets = rtargets;
1167 * Perform a PUT operation. Forwards the given request to other
1168 * peers. Does not store the data locally. Does not give the
1169 * data to local clients. May do nothing if this is the only
1170 * peer in the network (or if we are the closest peer in the
1173 * @param type type of the block
1174 * @param options routing options
1175 * @param desired_replication_level desired replication count
1176 * @param expiration_time when does the content expire
1177 * @param hop_count how many hops has this message traversed so far
1178 * @param bf Bloom filter of peers this PUT has already traversed
1179 * @param key key for the content
1180 * @param put_path_length number of entries in put_path
1181 * @param put_path peers this request has traversed so far (if tracked)
1182 * @param data payload to store
1183 * @param data_size number of bytes in data
1186 GDS_NEIGHBOURS_handle_put (enum GNUNET_BLOCK_Type type,
1187 enum GNUNET_DHT_RouteOption options,
1188 uint32_t desired_replication_level,
1189 struct GNUNET_TIME_Absolute expiration_time,
1191 struct GNUNET_CONTAINER_BloomFilter *bf,
1192 const GNUNET_HashCode *key,
1193 unsigned int put_path_length,
1194 struct GNUNET_PeerIdentity *put_path,
1198 unsigned int target_count;
1200 struct PeerInfo **targets;
1201 struct PeerInfo *target;
1202 struct P2PPendingMessage *pending;
1204 struct PeerPutMessage *ppm;
1205 struct GNUNET_PeerIdentity *pp;
1207 GNUNET_assert (NULL != bf);
1208 GNUNET_CONTAINER_bloomfilter_add (bf, &my_identity.hashPubKey);
1209 GNUNET_STATISTICS_update (GDS_stats,
1210 gettext_noop ("# PUT requests routed"), 1,
1212 target_count = get_target_peers (key, bf, hop_count,
1213 desired_replication_level,
1215 if (0 == target_count)
1217 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1218 "Not forwarding PUT for `%s' after %u hops (NSE: %f)!\n",
1224 msize = put_path_length * sizeof (struct GNUNET_PeerIdentity) + data_size + sizeof (struct PeerPutMessage);
1225 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1227 put_path_length = 0;
1228 msize = data_size + sizeof (struct PeerPutMessage);
1230 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1235 GNUNET_STATISTICS_update (GDS_stats,
1236 gettext_noop ("# Peers selected as targets for PUT requests"), target_count,
1238 for (i=0;i<target_count;i++)
1240 target = targets[i];
1241 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1242 pending->importance = 0; /* FIXME */
1243 pending->timeout = expiration_time;
1244 ppm = (struct PeerPutMessage*) &pending[1];
1245 pending->msg = &ppm->header;
1246 ppm->header.size = htons (msize);
1247 ppm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_PUT);
1248 ppm->options = htonl (options);
1249 ppm->type = htonl (type);
1250 ppm->hop_count = htonl (hop_count + 1);
1251 ppm->desired_replication_level = htonl (desired_replication_level);
1252 ppm->put_path_length = htonl (put_path_length);
1253 ppm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1254 GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &target->id.hashPubKey));
1255 GNUNET_assert (GNUNET_OK ==
1256 GNUNET_CONTAINER_bloomfilter_get_raw_data (bf,
1260 pp = (struct GNUNET_PeerIdentity*) &ppm[1];
1261 memcpy (pp, put_path, sizeof (struct GNUNET_PeerIdentity) * put_path_length);
1262 memcpy (&pp[put_path_length], data, data_size);
1263 GNUNET_CONTAINER_DLL_insert_tail (target->head,
1266 target->pending_count++;
1267 process_peer_queue (target);
1269 GNUNET_free (targets);
1274 * Perform a GET operation. Forwards the given request to other
1275 * peers. Does not lookup the key locally. May do nothing if this is
1276 * the only peer in the network (or if we are the closest peer in the
1279 * @param type type of the block
1280 * @param options routing options
1281 * @param desired_replication_level desired replication count
1282 * @param hop_count how many hops did this request traverse so far?
1283 * @param key key for the content
1284 * @param xquery extended query
1285 * @param xquery_size number of bytes in xquery
1286 * @param reply_bf bloomfilter to filter duplicates
1287 * @param reply_bf_mutator mutator for reply_bf
1288 * @param peer_bf filter for peers not to select (again)
1291 GDS_NEIGHBOURS_handle_get (enum GNUNET_BLOCK_Type type,
1292 enum GNUNET_DHT_RouteOption options,
1293 uint32_t desired_replication_level,
1295 const GNUNET_HashCode *key,
1298 const struct GNUNET_CONTAINER_BloomFilter *reply_bf,
1299 uint32_t reply_bf_mutator,
1300 struct GNUNET_CONTAINER_BloomFilter *peer_bf)
1302 unsigned int target_count;
1304 struct PeerInfo **targets;
1305 struct PeerInfo *target;
1306 struct P2PPendingMessage *pending;
1308 struct PeerGetMessage *pgm;
1310 size_t reply_bf_size;
1312 GNUNET_assert (NULL != peer_bf);
1313 GNUNET_CONTAINER_bloomfilter_add (peer_bf, &my_identity.hashPubKey);
1314 GNUNET_STATISTICS_update (GDS_stats,
1315 gettext_noop ("# GET requests routed"), 1,
1317 target_count = get_target_peers (key, peer_bf, hop_count,
1318 desired_replication_level,
1320 if (0 == target_count)
1322 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1323 "Not forwarding GET for `%s' after %u hops!\n",
1328 reply_bf_size = GNUNET_CONTAINER_bloomfilter_get_size (reply_bf);
1329 msize = xquery_size + sizeof (struct PeerGetMessage) + reply_bf_size;
1330 if (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE)
1335 GNUNET_STATISTICS_update (GDS_stats,
1336 gettext_noop ("# Peers selected as targets for GET requests"), target_count,
1338 /* forward request */
1339 for (i=0;i<target_count;i++)
1341 target = targets[i];
1342 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1343 pending->importance = 0; /* FIXME */
1344 pending->timeout = GNUNET_TIME_relative_to_absolute (GET_TIMEOUT);
1345 pgm = (struct PeerGetMessage*) &pending[1];
1346 pending->msg = &pgm->header;
1347 pgm->header.size = htons (msize);
1348 pgm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_GET);
1349 pgm->options = htonl (options);
1350 pgm->type = htonl (type);
1351 pgm->hop_count = htonl (hop_count + 1);
1352 pgm->desired_replication_level = htonl (desired_replication_level);
1353 pgm->xquery_size = htonl (xquery_size);
1354 pgm->bf_mutator = reply_bf_mutator;
1355 GNUNET_break (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &target->id.hashPubKey));
1356 GNUNET_assert (GNUNET_OK ==
1357 GNUNET_CONTAINER_bloomfilter_get_raw_data (peer_bf,
1361 xq = (char *) &pgm[1];
1362 memcpy (xq, xquery, xquery_size);
1363 if (NULL != reply_bf)
1364 GNUNET_assert (GNUNET_OK ==
1365 GNUNET_CONTAINER_bloomfilter_get_raw_data (reply_bf,
1368 GNUNET_CONTAINER_DLL_insert_tail (target->head,
1371 target->pending_count++;
1372 process_peer_queue (target);
1374 GNUNET_free (targets);
1379 * Handle a reply (route to origin). Only forwards the reply back to
1380 * the given peer. Does not do local caching or forwarding to local
1383 * @param target neighbour that should receive the block (if still connected)
1384 * @param type type of the block
1385 * @param expiration_time when does the content expire
1386 * @param key key for the content
1387 * @param put_path_length number of entries in put_path
1388 * @param put_path peers the original PUT traversed (if tracked)
1389 * @param get_path_length number of entries in put_path
1390 * @param get_path peers this reply has traversed so far (if tracked)
1391 * @param data payload of the reply
1392 * @param data_size number of bytes in data
1395 GDS_NEIGHBOURS_handle_reply (const struct GNUNET_PeerIdentity *target,
1396 enum GNUNET_BLOCK_Type type,
1397 struct GNUNET_TIME_Absolute expiration_time,
1398 const GNUNET_HashCode *key,
1399 unsigned int put_path_length,
1400 const struct GNUNET_PeerIdentity *put_path,
1401 unsigned int get_path_length,
1402 const struct GNUNET_PeerIdentity *get_path,
1406 struct PeerInfo *pi;
1407 struct P2PPendingMessage *pending;
1409 struct PeerResultMessage *prm;
1410 struct GNUNET_PeerIdentity *paths;
1412 msize = data_size + sizeof (struct PeerResultMessage) +
1413 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity);
1414 if ( (msize >= GNUNET_SERVER_MAX_MESSAGE_SIZE) ||
1415 (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1416 (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1417 (data_size > GNUNET_SERVER_MAX_MESSAGE_SIZE) )
1422 pi = GNUNET_CONTAINER_multihashmap_get (all_known_peers,
1423 &target->hashPubKey);
1426 /* peer disconnected in the meantime, drop reply */
1427 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1428 "Not forwarding REPLY for `%s' due to predecessor disconnect\n",
1432 GNUNET_STATISTICS_update (GDS_stats,
1433 gettext_noop ("# REPLIES routed"), 1,
1435 pending = GNUNET_malloc (sizeof (struct P2PPendingMessage) + msize);
1436 pending->importance = 0; /* FIXME */
1437 pending->timeout = expiration_time;
1438 prm = (struct PeerResultMessage*) &pending[1];
1439 pending->msg = &prm->header;
1440 prm->header.size = htons (msize);
1441 prm->header.type = htons (GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT);
1442 prm->type = htonl (type);
1443 prm->put_path_length = htonl (put_path_length);
1444 prm->get_path_length = htonl (get_path_length);
1445 prm->expiration_time = GNUNET_TIME_absolute_hton (expiration_time);
1447 paths = (struct GNUNET_PeerIdentity*) &prm[1];
1448 memcpy (paths, put_path, put_path_length * sizeof (struct GNUNET_PeerIdentity));
1449 memcpy (&paths[put_path_length],
1450 get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1451 memcpy (&paths[put_path_length + get_path_length],
1453 GNUNET_CONTAINER_DLL_insert (pi->head,
1456 pi->pending_count++;
1457 process_peer_queue (pi);
1462 * To be called on core init/fail.
1464 * @param cls service closure
1465 * @param server handle to the server for this service
1466 * @param identity the public identity of this peer
1467 * @param publicKey the public key of this peer
1470 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1471 const struct GNUNET_PeerIdentity *identity,
1472 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1474 GNUNET_assert (server != NULL);
1475 my_identity = *identity;
1480 * Core handler for p2p put requests.
1482 * @param cls closure
1483 * @param peer sender of the request
1484 * @param message message
1485 * @param peer peer identity this notification is about
1486 * @param atsi performance data
1487 * @return GNUNET_OK to keep the connection open,
1488 * GNUNET_SYSERR to close it (signal serious error)
1491 handle_dht_p2p_put (void *cls,
1492 const struct GNUNET_PeerIdentity *peer,
1493 const struct GNUNET_MessageHeader *message,
1494 const struct GNUNET_TRANSPORT_ATS_Information
1497 const struct PeerPutMessage *put;
1498 const struct GNUNET_PeerIdentity *put_path;
1499 const void *payload;
1502 size_t payload_size;
1503 enum GNUNET_DHT_RouteOption options;
1504 struct GNUNET_CONTAINER_BloomFilter *bf;
1505 GNUNET_HashCode test_key;
1507 msize = ntohs (message->size);
1508 if (msize < sizeof (struct PeerPutMessage))
1510 GNUNET_break_op (0);
1513 put = (const struct PeerPutMessage*) message;
1514 putlen = ntohl (put->put_path_length);
1515 if ( (msize < sizeof (struct PeerPutMessage) + putlen * sizeof (struct GNUNET_PeerIdentity)) ||
1516 (putlen > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1518 GNUNET_break_op (0);
1521 GNUNET_STATISTICS_update (GDS_stats,
1522 gettext_noop ("# P2P PUT requests received"), 1,
1524 put_path = (const struct GNUNET_PeerIdentity*) &put[1];
1525 payload = &put_path[putlen];
1526 options = ntohl (put->options);
1527 payload_size = msize - (sizeof (struct PeerPutMessage) +
1528 putlen * sizeof (struct GNUNET_PeerIdentity));
1529 switch (GNUNET_BLOCK_get_key (GDS_block_context,
1531 payload, payload_size,
1535 if (0 != memcmp (&test_key, &put->key, sizeof (GNUNET_HashCode)))
1537 GNUNET_break_op (0);
1542 GNUNET_break_op (0);
1545 /* cannot verify, good luck */
1548 bf = GNUNET_CONTAINER_bloomfilter_init (put->bloomfilter,
1550 GNUNET_CONSTANTS_BLOOMFILTER_K);
1551 GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &peer->hashPubKey));
1553 struct GNUNET_PeerIdentity pp[putlen+1];
1555 /* extend 'put path' by sender */
1556 if (0 != (options & GNUNET_DHT_RO_RECORD_ROUTE))
1558 memcpy (pp, put_path, putlen * sizeof (struct GNUNET_PeerIdentity));
1565 /* give to local clients */
1566 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1575 if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1576 (am_closest_peer (&put->key,
1578 GDS_DATACACHE_handle_put (GNUNET_TIME_absolute_ntoh (put->expiration_time),
1584 /* route to other peers */
1585 GDS_NEIGHBOURS_handle_put (ntohl (put->type),
1587 ntohl (put->desired_replication_level),
1588 GNUNET_TIME_absolute_ntoh (put->expiration_time),
1589 ntohl (put->hop_count),
1596 GNUNET_CONTAINER_bloomfilter_free (bf);
1602 * We have received a FIND PEER request. Send matching
1605 * @param sender sender of the FIND PEER request
1606 * @param key peers close to this key are desired
1607 * @param bf peers matching this bf are excluded
1608 * @param bf_mutator mutator for bf
1611 handle_find_peer (const struct GNUNET_PeerIdentity *sender,
1612 const GNUNET_HashCode *key,
1613 struct GNUNET_CONTAINER_BloomFilter *bf,
1614 uint32_t bf_mutator)
1617 struct PeerBucket *bucket;
1618 struct PeerInfo *peer;
1619 unsigned int choice;
1620 GNUNET_HashCode mhash;
1621 const struct GNUNET_HELLO_Message *hello;
1623 /* first, check about our own HELLO */
1624 if (NULL != GDS_my_hello)
1626 GNUNET_BLOCK_mingle_hash (&my_identity.hashPubKey, bf_mutator, &mhash);
1627 if ( (NULL == bf) ||
1628 (GNUNET_YES != GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) )
1630 GDS_NEIGHBOURS_handle_reply (sender,
1631 GNUNET_BLOCK_TYPE_DHT_HELLO,
1632 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1637 GNUNET_HELLO_size ((const struct GNUNET_HELLO_Message*) GDS_my_hello));
1641 GNUNET_STATISTICS_update (GDS_stats,
1642 gettext_noop ("# FIND PEER requests ignored due to Bloomfilter"), 1,
1648 GNUNET_STATISTICS_update (GDS_stats,
1649 gettext_noop ("# FIND PEER requests ignored due to lack of HELLO"), 1,
1653 /* then, also consider sending a random HELLO from the closest bucket */
1654 if (0 == memcmp (&my_identity.hashPubKey, key, sizeof (GNUNET_HashCode)))
1655 bucket_idx = closest_bucket;
1657 bucket_idx = GNUNET_MIN (closest_bucket, find_bucket (key));
1658 if (bucket_idx == GNUNET_SYSERR)
1660 bucket = &k_buckets[bucket_idx];
1661 if (bucket->peers_size == 0)
1663 choice = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1664 bucket->peers_size);
1665 peer = bucket->head;
1668 GNUNET_assert (peer != NULL);
1671 choice = bucket->peers_size;
1676 return; /* no non-masked peer available */
1678 peer = bucket->head;
1679 GNUNET_BLOCK_mingle_hash (&peer->id.hashPubKey, bf_mutator, &mhash);
1680 hello = GDS_HELLO_get (&peer->id);
1682 while ( (hello == NULL) ||
1683 (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (bf, &mhash)) );
1684 GDS_NEIGHBOURS_handle_reply (sender,
1685 GNUNET_BLOCK_TYPE_DHT_HELLO,
1686 GNUNET_TIME_relative_to_absolute (GNUNET_CONSTANTS_HELLO_ADDRESS_EXPIRATION),
1691 GNUNET_HELLO_size (hello));
1696 * Core handler for p2p get requests.
1698 * @param cls closure
1699 * @param peer sender of the request
1700 * @param message message
1701 * @param peer peer identity this notification is about
1702 * @param atsi performance data
1703 * @return GNUNET_OK to keep the connection open,
1704 * GNUNET_SYSERR to close it (signal serious error)
1707 handle_dht_p2p_get (void *cls, const struct GNUNET_PeerIdentity *peer,
1708 const struct GNUNET_MessageHeader *message,
1709 const struct GNUNET_TRANSPORT_ATS_Information
1712 struct PeerGetMessage *get;
1713 uint32_t xquery_size;
1714 size_t reply_bf_size;
1716 enum GNUNET_BLOCK_Type type;
1717 enum GNUNET_DHT_RouteOption options;
1718 enum GNUNET_BLOCK_EvaluationResult eval;
1719 struct GNUNET_CONTAINER_BloomFilter *reply_bf;
1720 struct GNUNET_CONTAINER_BloomFilter *peer_bf;
1723 GNUNET_break (0 != memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity)));
1724 /* parse and validate message */
1725 msize = ntohs (message->size);
1726 if (msize < sizeof (struct PeerGetMessage))
1728 GNUNET_break_op (0);
1731 get = (struct PeerGetMessage *) message;
1732 xquery_size = ntohl (get->xquery_size);
1733 if (msize < sizeof (struct PeerGetMessage) + xquery_size)
1735 GNUNET_break_op (0);
1738 GNUNET_STATISTICS_update (GDS_stats,
1739 gettext_noop ("# P2P GET requests received"), 1,
1741 reply_bf_size = msize - (sizeof (struct PeerGetMessage) + xquery_size);
1742 type = ntohl (get->type);
1743 options = ntohl (get->options);
1744 xquery = (const char*) &get[1];
1746 if (reply_bf_size > 0)
1747 reply_bf = GNUNET_CONTAINER_bloomfilter_init (&xquery[xquery_size],
1749 GNUNET_CONSTANTS_BLOOMFILTER_K);
1750 eval = GNUNET_BLOCK_evaluate (GDS_block_context,
1755 xquery, xquery_size,
1757 if (eval != GNUNET_BLOCK_EVALUATION_REQUEST_VALID)
1759 /* request invalid or block type not supported */
1760 GNUNET_break_op (eval == GNUNET_BLOCK_EVALUATION_TYPE_NOT_SUPPORTED);
1761 if (NULL != reply_bf)
1762 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1766 GNUNET_CONTAINER_bloomfilter_init (get->bloomfilter,
1768 GNUNET_CONSTANTS_BLOOMFILTER_K);
1769 GNUNET_break_op (GNUNET_YES == GNUNET_CONTAINER_bloomfilter_test (peer_bf, &peer->hashPubKey));
1770 /* remember request for routing replies */
1771 GDS_ROUTING_add (peer,
1775 xquery, xquery_size,
1776 reply_bf, get->bf_mutator);
1778 /* local lookup (this may update the reply_bf) */
1779 if ( (0 != (options & GNUNET_DHT_RO_DEMULTIPLEX_EVERYWHERE)) ||
1780 (am_closest_peer (&get->key,
1783 if ( (0 != (options & GNUNET_DHT_RO_FIND_PEER)))
1785 GNUNET_STATISTICS_update (GDS_stats,
1786 gettext_noop ("# P2P FIND PEER requests processed"), 1,
1788 handle_find_peer (peer,
1795 eval = GDS_DATACACHE_handle_get (&get->key,
1797 xquery, xquery_size,
1804 GNUNET_STATISTICS_update (GDS_stats,
1805 gettext_noop ("# P2P GET requests ONLY routed"), 1,
1809 /* P2P forwarding */
1810 if (eval != GNUNET_BLOCK_EVALUATION_OK_LAST)
1811 GDS_NEIGHBOURS_handle_get (type,
1813 ntohl (get->desired_replication_level),
1814 ntohl (get->hop_count),
1816 xquery, xquery_size,
1821 if (NULL != reply_bf)
1822 GNUNET_CONTAINER_bloomfilter_free (reply_bf);
1823 GNUNET_CONTAINER_bloomfilter_free (peer_bf);
1829 * Core handler for p2p result messages.
1831 * @param cls closure
1832 * @param message message
1833 * @param peer peer identity this notification is about
1834 * @param atsi performance data
1835 * @return GNUNET_YES (do not cut p2p connection)
1838 handle_dht_p2p_result (void *cls, const struct GNUNET_PeerIdentity *peer,
1839 const struct GNUNET_MessageHeader *message,
1840 const struct GNUNET_TRANSPORT_ATS_Information
1843 const struct PeerResultMessage *prm;
1844 const struct GNUNET_PeerIdentity *put_path;
1845 const struct GNUNET_PeerIdentity *get_path;
1847 uint32_t get_path_length;
1848 uint32_t put_path_length;
1851 enum GNUNET_BLOCK_Type type;
1853 /* parse and validate message */
1854 msize = ntohs (message->size);
1855 if (msize < sizeof (struct PeerResultMessage))
1857 GNUNET_break_op (0);
1860 prm = (struct PeerResultMessage *) message;
1861 put_path_length = ntohl (prm->put_path_length);
1862 get_path_length = ntohl (prm->get_path_length);
1863 if ( (msize < sizeof (struct PeerResultMessage) +
1864 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity)) ||
1865 (get_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) ||
1866 (put_path_length > GNUNET_SERVER_MAX_MESSAGE_SIZE / sizeof (struct GNUNET_PeerIdentity)) )
1868 GNUNET_break_op (0);
1871 GNUNET_STATISTICS_update (GDS_stats,
1872 gettext_noop ("# P2P RESULTS received"), 1,
1874 put_path = (const struct GNUNET_PeerIdentity*) &prm[1];
1875 get_path = &put_path[put_path_length];
1876 type = ntohl (prm->type);
1877 data = (const void*) &get_path[get_path_length];
1878 data_size = msize - (sizeof (struct PeerResultMessage) +
1879 (get_path_length + put_path_length) * sizeof (struct GNUNET_PeerIdentity));
1881 /* if we got a HELLO, consider it for our own routing table */
1882 if (type == GNUNET_BLOCK_TYPE_DHT_HELLO)
1884 const struct GNUNET_MessageHeader *h;
1885 struct GNUNET_PeerIdentity pid;
1888 /* Should be a HELLO, validate and consider using it! */
1889 if (data_size < sizeof (struct GNUNET_MessageHeader))
1891 GNUNET_break_op (0);
1895 if (data_size != ntohs (h->size))
1897 GNUNET_break_op (0);
1901 GNUNET_HELLO_get_id ((const struct GNUNET_HELLO_Message*) h,
1904 GNUNET_break_op (0);
1907 if (0 != memcmp (&my_identity, &pid, sizeof (struct GNUNET_PeerIdentity)))
1909 bucket = find_bucket (&pid.hashPubKey);
1910 if ( (bucket >= 0) &&
1911 (k_buckets[bucket].peers_size < bucket_size) )
1913 if (NULL != GDS_transport_handle)
1914 GNUNET_TRANSPORT_offer_hello (GDS_transport_handle,
1916 (void) GNUNET_CORE_peer_request_connect (coreAPI,
1923 /* append 'peer' to 'get_path' */
1925 struct GNUNET_PeerIdentity xget_path[get_path_length+1];
1927 memcpy (xget_path, get_path, get_path_length * sizeof (struct GNUNET_PeerIdentity));
1928 xget_path[get_path_length] = *peer;
1931 /* forward to local clients */
1932 GDS_CLIENTS_handle_reply (GNUNET_TIME_absolute_ntoh (prm->expiration_time),
1942 /* forward to other peers */
1943 GDS_ROUTING_process (type,
1944 GNUNET_TIME_absolute_ntoh (prm->expiration_time),
1958 * Initialize neighbours subsystem.
1960 * @return GNUNET_OK on success, GNUNET_SYSERR on error
1963 GDS_NEIGHBOURS_init ()
1965 static struct GNUNET_CORE_MessageHandler core_handlers[] = {
1966 {&handle_dht_p2p_get, GNUNET_MESSAGE_TYPE_DHT_P2P_GET, 0},
1967 {&handle_dht_p2p_put, GNUNET_MESSAGE_TYPE_DHT_P2P_PUT, 0},
1968 {&handle_dht_p2p_result, GNUNET_MESSAGE_TYPE_DHT_P2P_RESULT, 0},
1971 unsigned long long temp_config_num;
1974 GNUNET_CONFIGURATION_get_value_number (GDS_cfg, "DHT", "bucket_size",
1976 bucket_size = (unsigned int) temp_config_num;
1977 coreAPI = GNUNET_CORE_connect (GDS_cfg,
1981 &handle_core_connect,
1982 &handle_core_disconnect,
1983 NULL, /* Do we care about "status" updates? */
1987 if (coreAPI == NULL)
1988 return GNUNET_SYSERR;
1989 all_known_peers = GNUNET_CONTAINER_multihashmap_create (256);
1995 * Shutdown neighbours subsystem.
1998 GDS_NEIGHBOURS_done ()
2000 if (coreAPI == NULL)
2002 GNUNET_CORE_disconnect (coreAPI);
2004 GNUNET_assert (0 == GNUNET_CONTAINER_multihashmap_size (all_known_peers));
2005 GNUNET_CONTAINER_multihashmap_destroy (all_known_peers);
2006 all_known_peers = NULL;
2007 if (GNUNET_SCHEDULER_NO_TASK != find_peer_task)
2009 GNUNET_SCHEDULER_cancel (find_peer_task);
2010 find_peer_task = GNUNET_SCHEDULER_NO_TASK;
2015 /* end of gnunet-service-dht_neighbours.c */