From dcd3ff3dca2841a362384eaffae5288928015847 Mon Sep 17 00:00:00 2001 From: Frando Date: Thu, 19 Jun 2025 19:51:25 +0000 Subject: [PATCH] deploy: b8c80c16b91a543b13204e9f556206ebeccd8d6f --- pr/3327/docs/iroh/all.html | 2 +- .../discovery/dns/struct.DnsDiscovery.html | 6 +- .../iroh/discovery/enum.DiscoveryError.html | 29 +- .../discovery/enum.IntoDiscoveryError.html | 12 +- pr/3327/docs/iroh/discovery/index.html | 2 +- .../iroh/discovery/mdns/constant.NAME.html | 2 +- pr/3327/docs/iroh/discovery/mdns/index.html | 2 +- .../discovery/mdns/struct.MdnsDiscovery.html | 14 +- .../mdns/struct.MdnsDiscoveryBuilder.html | 4 +- .../pkarr/constant.DEFAULT_PKARR_TTL.html | 2 +- .../constant.DEFAULT_REPUBLISH_INTERVAL.html | 2 +- .../constant.N0_DNS_PKARR_RELAY_PROD.html | 2 +- .../constant.N0_DNS_PKARR_RELAY_STAGING.html | 2 +- .../docs/iroh/discovery/pkarr/dht/index.html | 2 +- .../discovery/pkarr/dht/struct.Builder.html | 18 +- .../pkarr/dht/struct.DhtDiscovery.html | 10 +- .../iroh/discovery/pkarr/enum.PkarrError.html | 9 +- pr/3327/docs/iroh/discovery/pkarr/index.html | 2 +- .../pkarr/struct.PkarrPublisher.html | 16 +- .../pkarr/struct.PkarrPublisherBuilder.html | 12 +- .../pkarr/struct.PkarrRelayClient.html | 14 +- .../discovery/pkarr/struct.PkarrResolver.html | 14 +- .../pkarr/struct.PkarrResolverBuilder.html | 8 +- .../struct.StaticProvider.html | 6 +- .../discovery/struct.ConcurrentDiscovery.html | 18 +- .../discovery/struct.DiscoveryContext.html | 10 +- .../iroh/discovery/struct.DiscoveryItem.html | 20 +- .../docs/iroh/discovery/struct.Lagged.html | 6 +- .../docs/iroh/discovery/struct.NodeInfo.html | 2 +- .../docs/iroh/discovery/trait.Discovery.html | 10 +- .../iroh/discovery/trait.IntoDiscovery.html | 7 +- pr/3327/docs/iroh/dns/struct.DnsResolver.html | 46 +- .../constant.ENV_FORCE_STAGING_RELAYS.html | 2 +- .../iroh/endpoint/enum.AddNodeAddrError.html | 8 +- .../docs/iroh/endpoint/enum.AlpnError.html | 8 +- .../docs/iroh/endpoint/enum.BindError.html | 8 +- .../docs/iroh/endpoint/enum.ConnectError.html | 8 +- .../endpoint/enum.ConnectWithOptsError.html | 8 +- .../iroh/endpoint/enum.ConnectionError.html | 4 +- .../iroh/endpoint/enum.ConnectionType.html | 10 +- .../docs/iroh/endpoint/enum.ControlMsg.html | 10 +- .../iroh/endpoint/enum.DirectAddrType.html | 12 +- .../endpoint/enum.GetMappingAddressError.html | 6 +- .../iroh/endpoint/enum.PathSelection.html | 6 +- .../docs/iroh/endpoint/enum.RelayMode.html | 8 +- pr/3327/docs/iroh/endpoint/enum.Source.html | 12 +- .../iroh/endpoint/fn.default_relay_mode.html | 2 +- .../iroh/endpoint/fn.force_staging_infra.html | 2 +- pr/3327/docs/iroh/endpoint/index.html | 4 +- pr/3327/docs/iroh/endpoint/sidebar-items.js | 2 +- pr/3327/docs/iroh/endpoint/struct.Accept.html | 6 +- .../docs/iroh/endpoint/struct.Builder.html | 48 +- .../iroh/endpoint/struct.ClosedStream.html | 4 +- .../iroh/endpoint/struct.ConnectOptions.html | 10 +- .../docs/iroh/endpoint/struct.Connecting.html | 12 +- .../docs/iroh/endpoint/struct.Connection.html | 50 +- .../docs/iroh/endpoint/struct.DirectAddr.html | 12 +- .../iroh/endpoint/struct.DirectAddrInfo.html | 10 +- .../docs/iroh/endpoint/struct.Endpoint.html | 80 +- .../docs/iroh/endpoint/struct.Incoming.html | 20 +- .../iroh/endpoint/struct.IncomingFuture.html | 6 +- .../docs/iroh/endpoint/struct.RemoteInfo.html | 16 +- .../endpoint/struct.RemoteNodeIdError.html | 6 +- .../iroh/endpoint/struct.ZeroRttAccepted.html | 4 +- .../iroh/endpoint/type.NodeAddrWatcher.html | 5 - pr/3327/docs/iroh/index.html | 8 +- .../iroh/net_report/enum.ReportError.html | 6 +- .../net_report/fn.bind_local_stun_socket.html | 2 +- pr/3327/docs/iroh/net_report/index.html | 2 +- .../docs/iroh/net_report/struct.Options.html | 19 +- .../iroh/net_report/struct.QuicConfig.html | 4 +- .../docs/iroh/node_info/struct.NodeInfo.html | 2 +- ...otocolError.html => enum.AcceptError.html} | 14 +- pr/3327/docs/iroh/protocol/index.html | 6 +- pr/3327/docs/iroh/protocol/sidebar-items.js | 2 +- .../iroh/protocol/struct.AccessLimit.html | 10 +- pr/3327/docs/iroh/protocol/struct.Router.html | 12 +- .../iroh/protocol/struct.RouterBuilder.html | 12 +- .../iroh/protocol/trait.ProtocolHandler.html | 22 +- pr/3327/docs/iroh/sidebar-items.js | 2 +- pr/3327/docs/iroh/struct.NodeAddr.html | 2 +- pr/3327/docs/iroh/test_utils/index.html | 2 +- pr/3327/docs/iroh/watcher/index.html | 13 - pr/3327/docs/iroh/watcher/sidebar-items.js | 1 - pr/3327/docs/iroh/watcher/struct.Direct.html | 47 - .../iroh/watcher/struct.Disconnected.html | 36 - .../iroh/watcher/struct.InitializedFut.html | 142 - pr/3327/docs/iroh/watcher/struct.Map.html | 52 - pr/3327/docs/iroh/watcher/struct.NextFut.html | 138 - pr/3327/docs/iroh/watcher/struct.Stream.html | 462 - .../docs/iroh/watcher/struct.Watchable.html | 41 - pr/3327/docs/iroh/watcher/trait.Watcher.html | 92 - pr/3327/docs/iroh_relay/all.html | 2 +- .../client/enum.ReceivedMessage.html | 8 +- .../iroh_relay/client/enum.SendMessage.html | 4 +- .../client/struct.ClientBuilder.html | 4 +- .../docs/iroh_relay/dns/enum.DnsError.html | 9 +- pr/3327/docs/iroh_relay/dns/index.html | 4 +- pr/3327/docs/iroh_relay/dns/sidebar-items.js | 2 +- .../dns/staggered/struct.Error.html | 11 - .../iroh_relay/dns/struct.DnsResolver.html | 50 +- ....Error.html => struct.StaggeredError.html} | 11 +- pr/3327/docs/iroh_relay/dns/struct.TXT.html | 6 +- .../docs/iroh_relay/dns/struct.TxtLookup.html | 4 +- pr/3327/docs/iroh_relay/index.html | 2 +- pr/3327/docs/iroh_relay/node_info/index.html | 10 +- .../iroh_relay/node_info/struct.NodeData.html | 16 +- .../iroh_relay/node_info/struct.NodeInfo.html | 26 +- .../iroh_relay/node_info/trait.NodeIdExt.html | 10 +- pr/3327/docs/iroh_relay/quic/index.html | 2 +- .../iroh_relay/server/enum.AccessConfig.html | 6 +- .../docs/iroh_relay/server/struct.Server.html | 4 +- pr/3327/docs/iroh_relay/struct.RelayMap.html | 10 +- pr/3327/docs/iroh_relay/struct.RelayNode.html | 6 +- pr/3327/docs/search-index.js | 4 +- pr/3327/docs/search.desc/iroh/iroh-desc-0-.js | 2 +- .../iroh_relay/iroh_relay-desc-0-.js | 2 +- pr/3327/docs/src-files.js | 4 +- pr/3327/docs/src/iroh/disco.rs.html | 985 +- pr/3327/docs/src/iroh/discovery.rs.html | 2211 +++-- pr/3327/docs/src/iroh/discovery/mdns.rs.html | 950 +- pr/3327/docs/src/iroh/discovery/pkarr.rs.html | 1069 +-- .../docs/src/iroh/discovery/pkarr/dht.rs.html | 435 +- pr/3327/docs/src/iroh/endpoint.rs.html | 6270 +++++++------ .../docs/src/iroh/endpoint/rtt_actor.rs.html | 8 +- pr/3327/docs/src/iroh/lib.rs.html | 23 +- pr/3327/docs/src/iroh/magicsock.rs.html | 8006 ++++++++--------- .../docs/src/iroh/magicsock/node_map.rs.html | 1737 ++-- .../iroh/magicsock/node_map/best_addr.rs.html | 2 +- .../magicsock/node_map/node_state.rs.html | 2374 +++-- .../src/iroh/magicsock/relay_actor.rs.html | 1713 ---- .../src/iroh/magicsock/transports.rs.html | 597 ++ .../src/iroh/magicsock/transports/ip.rs.html | 249 + .../iroh/magicsock/transports/relay.rs.html | 423 + .../magicsock/transports/relay/actor.rs.html | 1747 ++++ .../docs/src/iroh/magicsock/udp_conn.rs.html | 81 - pr/3327/docs/src/iroh/net_report.rs.html | 1506 ++-- .../docs/src/iroh/net_report/options.rs.html | 290 +- .../src/iroh/net_report/reportgen.rs.html | 3601 ++++---- pr/3327/docs/src/iroh/protocol.rs.html | 1126 +-- pr/3327/docs/src/iroh/test_utils.rs.html | 347 +- pr/3327/docs/src/iroh/watcher.rs.html | 699 -- pr/3327/docs/src/iroh_bench/iroh.rs.html | 10 +- .../docs/src/iroh_relay/client/tls.rs.html | 2 +- pr/3327/docs/src/iroh_relay/dns.rs.html | 907 +- pr/3327/docs/src/iroh_relay/quic.rs.html | 208 +- .../docs/trait.impl/core/clone/trait.Clone.js | 4 +- .../trait.impl/core/convert/trait.From.js | 4 +- .../trait.impl/core/default/trait.Default.js | 4 +- .../docs/trait.impl/core/error/trait.Error.js | 4 +- .../docs/trait.impl/core/fmt/trait.Debug.js | 4 +- .../docs/trait.impl/core/fmt/trait.Display.js | 4 +- .../core/future/future/trait.Future.js | 4 +- .../iter/traits/collect/trait.FromIterator.js | 4 +- .../trait.impl/core/marker/trait.Freeze.js | 4 +- .../docs/trait.impl/core/marker/trait.Send.js | 4 +- .../docs/trait.impl/core/marker/trait.Sync.js | 4 +- .../trait.impl/core/marker/trait.Unpin.js | 4 +- .../panic/unwind_safe/trait.RefUnwindSafe.js | 4 +- .../panic/unwind_safe/trait.UnwindSafe.js | 4 +- .../futures_core/stream/trait.Stream.js | 4 +- .../trait.impl/iroh/watcher/trait.Watcher.js | 9 - .../trait.impl/snafu/trait.ErrorCompat.js | 4 +- .../docs/type.impl/iroh/watcher/struct.Map.js | 9 - 164 files changed, 19117 insertions(+), 20631 deletions(-) delete mode 100644 pr/3327/docs/iroh/endpoint/type.NodeAddrWatcher.html rename pr/3327/docs/iroh/protocol/{enum.ProtocolError.html => enum.AcceptError.html} (55%) delete mode 100644 pr/3327/docs/iroh/watcher/index.html delete mode 100644 pr/3327/docs/iroh/watcher/sidebar-items.js delete mode 100644 pr/3327/docs/iroh/watcher/struct.Direct.html delete mode 100644 pr/3327/docs/iroh/watcher/struct.Disconnected.html delete mode 100644 pr/3327/docs/iroh/watcher/struct.InitializedFut.html delete mode 100644 pr/3327/docs/iroh/watcher/struct.Map.html delete mode 100644 pr/3327/docs/iroh/watcher/struct.NextFut.html delete mode 100644 pr/3327/docs/iroh/watcher/struct.Stream.html delete mode 100644 pr/3327/docs/iroh/watcher/struct.Watchable.html delete mode 100644 pr/3327/docs/iroh/watcher/trait.Watcher.html delete mode 100644 pr/3327/docs/iroh_relay/dns/staggered/struct.Error.html rename pr/3327/docs/iroh_relay/dns/{struct.Error.html => struct.StaggeredError.html} (65%) delete mode 100644 pr/3327/docs/src/iroh/magicsock/relay_actor.rs.html create mode 100644 pr/3327/docs/src/iroh/magicsock/transports.rs.html create mode 100644 pr/3327/docs/src/iroh/magicsock/transports/ip.rs.html create mode 100644 pr/3327/docs/src/iroh/magicsock/transports/relay.rs.html create mode 100644 pr/3327/docs/src/iroh/magicsock/transports/relay/actor.rs.html delete mode 100644 pr/3327/docs/src/iroh/magicsock/udp_conn.rs.html delete mode 100644 pr/3327/docs/src/iroh/watcher.rs.html delete mode 100644 pr/3327/docs/trait.impl/iroh/watcher/trait.Watcher.js delete mode 100644 pr/3327/docs/type.impl/iroh/watcher/struct.Map.js diff --git a/pr/3327/docs/iroh/all.html b/pr/3327/docs/iroh/all.html index c3b1849e87..dfdedaab73 100644 --- a/pr/3327/docs/iroh/all.html +++ b/pr/3327/docs/iroh/all.html @@ -1 +1 @@ -List of all items in this crate

List of all items

Structs

Enums

Traits

Functions

Type Aliases

Constants

\ No newline at end of file +List of all items in this crate

List of all items

Structs

Enums

Traits

Functions

Type Aliases

Constants

\ No newline at end of file diff --git a/pr/3327/docs/iroh/discovery/dns/struct.DnsDiscovery.html b/pr/3327/docs/iroh/discovery/dns/struct.DnsDiscovery.html index 6dd6913dd2..e0a0538fd9 100644 --- a/pr/3327/docs/iroh/discovery/dns/struct.DnsDiscovery.html +++ b/pr/3327/docs/iroh/discovery/dns/struct.DnsDiscovery.html @@ -25,7 +25,7 @@ service for testing purposes.

Trait Implementations§

Source§

impl Debug for DnsDiscovery

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Discovery for DnsDiscovery

Source§

fn resolve( &self, node_id: NodeId, -) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn publish(&self, _data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more

Auto Trait Implementations§

§

impl Freeze for DnsDiscovery

§

impl !RefUnwindSafe for DnsDiscovery

§

impl Send for DnsDiscovery

§

impl Sync for DnsDiscovery

§

impl Unpin for DnsDiscovery

§

impl !UnwindSafe for DnsDiscovery

Blanket Implementations§

Source§

impl<T> Any for T
where +) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn publish(&self, _data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more

Auto Trait Implementations§

§

impl Freeze for DnsDiscovery

§

impl !RefUnwindSafe for DnsDiscovery

§

impl Send for DnsDiscovery

§

impl Sync for DnsDiscovery

§

impl Unpin for DnsDiscovery

§

impl !UnwindSafe for DnsDiscovery

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( @@ -42,8 +42,8 @@ service for testing purposes.

U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

-
Source§

impl<T> IntoDiscovery for T
where - T: Discovery,

Source§

impl<T> IntoDiscovery for T
where + T: Discovery,

Source§

fn into_discovery( self, _context: &DiscoveryContext<'_>, ) -> Result<impl Discovery, IntoDiscoveryError>

Turns this discovery builder into a ready-to-use discovery service. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where diff --git a/pr/3327/docs/iroh/discovery/enum.DiscoveryError.html b/pr/3327/docs/iroh/discovery/enum.DiscoveryError.html index 2f47977c7d..13e8f324fa 100644 --- a/pr/3327/docs/iroh/discovery/enum.DiscoveryError.html +++ b/pr/3327/docs/iroh/discovery/enum.DiscoveryError.html @@ -1,25 +1,10 @@ -DiscoveryError in iroh::discovery - Rust

Enum DiscoveryError

Source
#[non_exhaustive]
pub enum DiscoveryError { +DiscoveryError in iroh::discovery - Rust

Enum DiscoveryError

Source
#[non_exhaustive]
pub enum DiscoveryError { NoServiceConfigured { backtrace: Option<Backtrace>, span_trace: SpanTrace, }, - NodeId { - node_id: PublicKey, - backtrace: Option<Backtrace>, - span_trace: SpanTrace, - }, NoResults { - node_id: PublicKey, - backtrace: Option<Backtrace>, - span_trace: SpanTrace, - }, - SignedPacket { - source: Box<EncodingError>, - backtrace: Option<Backtrace>, - span_trace: SpanTrace, - }, - ParsePacket { - source: Box<ParseError>, + node_id: NodeId, backtrace: Option<Backtrace>, span_trace: SpanTrace, }, @@ -30,19 +15,19 @@ span_trace: SpanTrace, }, }
Expand description

Discovery errors

-

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

NoServiceConfigured

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

NodeId

Fields

§node_id: PublicKey
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

NoResults

Fields

§node_id: PublicKey
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

SignedPacket

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ParsePacket

Fields

§source: Box<ParseError>
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

User

Fields

§provenance: &'static str
§source: Box<dyn Error + Send + Sync + 'static>
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Implementations§

Source§

impl DiscoveryError

Source

pub fn from_err<T: Error + Send + Sync + 'static>( +

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

NoServiceConfigured

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

NoResults

Fields

§node_id: NodeId
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

User

Fields

§provenance: &'static str
§source: Box<dyn Error + Send + Sync + 'static>
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Implementations§

Source§

impl DiscoveryError

Source

pub fn from_err<T: Error + Send + Sync + 'static>( provenance: &'static str, source: T, ) -> Self

Creates a new user error from an arbitrary error type.

-
Source

pub fn from_err_box( +

Source

pub fn from_err_box( provenance: &'static str, source: Box<dyn Error + Send + Sync + 'static>, ) -> Self

Creates a new user error from an arbitrary boxed error type.

-

Trait Implementations§

Source§

impl Debug for DiscoveryError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for DiscoveryError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for DiscoveryError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for DiscoveryError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +

Trait Implementations§

Source§

impl Debug for DiscoveryError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for DiscoveryError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for DiscoveryError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for DiscoveryError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<PkarrError> for DiscoveryError

Source§

fn from(err: PkarrError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for DiscoveryError

§

impl !RefUnwindSafe for DiscoveryError

§

impl Send for DiscoveryError

§

impl Sync for DiscoveryError

§

impl Unpin for DiscoveryError

§

impl !UnwindSafe for DiscoveryError

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<PkarrError> for DiscoveryError

Source§

fn from(err: PkarrError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for DiscoveryError

§

impl !RefUnwindSafe for DiscoveryError

§

impl Send for DiscoveryError

§

impl Sync for DiscoveryError

§

impl Unpin for DiscoveryError

§

impl !UnwindSafe for DiscoveryError

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3327/docs/iroh/discovery/enum.IntoDiscoveryError.html b/pr/3327/docs/iroh/discovery/enum.IntoDiscoveryError.html index 84181dbf8b..3fa506d9e9 100644 --- a/pr/3327/docs/iroh/discovery/enum.IntoDiscoveryError.html +++ b/pr/3327/docs/iroh/discovery/enum.IntoDiscoveryError.html @@ -1,4 +1,4 @@ -IntoDiscoveryError in iroh::discovery - Rust

Enum IntoDiscoveryError

Source
#[non_exhaustive]
pub enum IntoDiscoveryError { +IntoDiscoveryError in iroh::discovery - Rust

Enum IntoDiscoveryError

Source
#[non_exhaustive]
pub enum IntoDiscoveryError { User { provenance: &'static str, source: Box<dyn Error + Send + Sync + 'static>, @@ -6,19 +6,19 @@ span_trace: SpanTrace, }, }
Expand description

IntoDiscovery errors

-

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

User

Fields

§provenance: &'static str
§source: Box<dyn Error + Send + Sync + 'static>
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Implementations§

Source§

impl IntoDiscoveryError

Source

pub fn from_err<T: Error + Send + Sync + 'static>( +

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

User

Fields

§provenance: &'static str
§source: Box<dyn Error + Send + Sync + 'static>
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Implementations§

Source§

impl IntoDiscoveryError

Source

pub fn from_err<T: Error + Send + Sync + 'static>( provenance: &'static str, source: T, ) -> Self

Creates a new user error from an arbitrary error type.

-
Source

pub fn from_err_box( +

Source

pub fn from_err_box( provenance: &'static str, source: Box<dyn Error + Send + Sync + 'static>, ) -> Self

Creates a new user error from an arbitrary boxed error type.

-

Trait Implementations§

Source§

impl Debug for IntoDiscoveryError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for IntoDiscoveryError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for IntoDiscoveryError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for IntoDiscoveryError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +

Trait Implementations§

Source§

impl Debug for IntoDiscoveryError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for IntoDiscoveryError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for IntoDiscoveryError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for IntoDiscoveryError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<IntoDiscoveryError> for BindError

Source§

fn from(error: IntoDiscoveryError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<IntoDiscoveryError> for BindError

Source§

fn from(error: IntoDiscoveryError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl Freeze for IntoDiscoveryError

§

impl !RefUnwindSafe for IntoDiscoveryError

§

impl Send for IntoDiscoveryError

§

impl Sync for IntoDiscoveryError

§

impl Unpin for IntoDiscoveryError

§

impl !UnwindSafe for IntoDiscoveryError

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3327/docs/iroh/discovery/index.html b/pr/3327/docs/iroh/discovery/index.html index ce49694992..6d6c0215b7 100644 --- a/pr/3327/docs/iroh/discovery/index.html +++ b/pr/3327/docs/iroh/discovery/index.html @@ -1,4 +1,4 @@ -iroh::discovery - Rust

Module discovery

Source
Expand description

Node address discovery.

+iroh::discovery - Rust

Module discovery

Source
Expand description

Node address discovery.

To connect to an iroh node a NodeAddr is needed, which may contain a RelayUrl or one or more direct addresses in addition to the NodeId.

Since there is a conversion from NodeId to NodeAddr, you can also use diff --git a/pr/3327/docs/iroh/discovery/mdns/constant.NAME.html b/pr/3327/docs/iroh/discovery/mdns/constant.NAME.html index 2ed0c8d20c..f713a95412 100644 --- a/pr/3327/docs/iroh/discovery/mdns/constant.NAME.html +++ b/pr/3327/docs/iroh/discovery/mdns/constant.NAME.html @@ -1,4 +1,4 @@ -NAME in iroh::discovery::mdns - Rust

Constant NAME

Source
pub const NAME: &str = "local.swarm.discovery";
Available on crate feature discovery-local-network only.
Expand description

Name of this discovery service.

+NAME in iroh::discovery::mdns - Rust

Constant NAME

Source
pub const NAME: &str = "local.swarm.discovery";
Available on crate feature discovery-local-network only.
Expand description

Name of this discovery service.

Used as the provenance field in DiscoveryItems.

Used in the crate::endpoint::Source::Discovery enum variant as the name.

\ No newline at end of file diff --git a/pr/3327/docs/iroh/discovery/mdns/index.html b/pr/3327/docs/iroh/discovery/mdns/index.html index ae689c2738..befdab5c4e 100644 --- a/pr/3327/docs/iroh/discovery/mdns/index.html +++ b/pr/3327/docs/iroh/discovery/mdns/index.html @@ -1,4 +1,4 @@ -iroh::discovery::mdns - Rust

Module mdns

Source
Available on crate feature discovery-local-network only.
Expand description

A discovery service that uses an mdns-like service to discover local nodes.

+iroh::discovery::mdns - Rust

Module mdns

Source
Available on crate feature discovery-local-network only.
Expand description

A discovery service that uses an mdns-like service to discover local nodes.

This allows you to use an mdns-like swarm discovery service to find address information about nodes that are on your local network, no relay or outside internet needed. See the swarm-discovery crate for more details.

When MdnsDiscovery is enabled, it’s possible to get a list of the locally discovered nodes by filtering a list of RemoteInfos.

diff --git a/pr/3327/docs/iroh/discovery/mdns/struct.MdnsDiscovery.html b/pr/3327/docs/iroh/discovery/mdns/struct.MdnsDiscovery.html index e061e3e951..a08e9fe089 100644 --- a/pr/3327/docs/iroh/discovery/mdns/struct.MdnsDiscovery.html +++ b/pr/3327/docs/iroh/discovery/mdns/struct.MdnsDiscovery.html @@ -1,15 +1,15 @@ -MdnsDiscovery in iroh::discovery::mdns - Rust

Struct MdnsDiscovery

Source
pub struct MdnsDiscovery { /* private fields */ }
Available on crate feature discovery-local-network only.
Expand description

Discovery using swarm-discovery, a variation on mdns

-

Implementations§

Source§

impl MdnsDiscovery

Source

pub fn builder() -> MdnsDiscoveryBuilder

Returns a MdnsDiscoveryBuilder that implements IntoDiscovery.

-
Source

pub fn new(node_id: NodeId) -> Result<Self, IntoDiscoveryError>

Create a new MdnsDiscovery Service.

+MdnsDiscovery in iroh::discovery::mdns - Rust

Struct MdnsDiscovery

Source
pub struct MdnsDiscovery { /* private fields */ }
Available on crate feature discovery-local-network only.
Expand description

Discovery using swarm-discovery, a variation on mdns

+

Implementations§

Source§

impl MdnsDiscovery

Source

pub fn builder() -> MdnsDiscoveryBuilder

Returns a MdnsDiscoveryBuilder that implements IntoDiscovery.

+
Source

pub fn new(node_id: NodeId) -> Result<Self, IntoDiscoveryError>

Create a new MdnsDiscovery Service.

This starts a [Discoverer] that broadcasts your addresses and receives addresses from other nodes in your local network.

§Errors

Returns an error if the network does not allow ipv4 OR ipv6.

§Panics

This relies on [tokio::runtime::Handle::current] and will panic if called outside of the context of a tokio runtime.

-

Trait Implementations§

Source§

impl Debug for MdnsDiscovery

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Discovery for MdnsDiscovery

Trait Implementations§

Source§

impl Debug for MdnsDiscovery

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Discovery for MdnsDiscovery

Source§

fn resolve( &self, node_id: NodeId, -) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn publish(&self, data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn publish(&self, data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( @@ -26,8 +26,8 @@ U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

-
Source§

impl<T> IntoDiscovery for T
where - T: Discovery,

Source§

impl<T> IntoDiscovery for T
where + T: Discovery,

Source§

fn into_discovery( self, _context: &DiscoveryContext<'_>, ) -> Result<impl Discovery, IntoDiscoveryError>

Turns this discovery builder into a ready-to-use discovery service. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where diff --git a/pr/3327/docs/iroh/discovery/mdns/struct.MdnsDiscoveryBuilder.html b/pr/3327/docs/iroh/discovery/mdns/struct.MdnsDiscoveryBuilder.html index 8acf3572bb..adff7168fe 100644 --- a/pr/3327/docs/iroh/discovery/mdns/struct.MdnsDiscoveryBuilder.html +++ b/pr/3327/docs/iroh/discovery/mdns/struct.MdnsDiscoveryBuilder.html @@ -1,5 +1,5 @@ -MdnsDiscoveryBuilder in iroh::discovery::mdns - Rust

Struct MdnsDiscoveryBuilder

Source
pub struct MdnsDiscoveryBuilder;
Available on crate feature discovery-local-network only.
Expand description

Builder for MdnsDiscovery.

-

Trait Implementations§

Source§

impl Debug for MdnsDiscoveryBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl IntoDiscovery for MdnsDiscoveryBuilder

Source§

fn into_discovery( +MdnsDiscoveryBuilder in iroh::discovery::mdns - Rust

Struct MdnsDiscoveryBuilder

Source
pub struct MdnsDiscoveryBuilder;
Available on crate feature discovery-local-network only.
Expand description

Builder for MdnsDiscovery.

+

Trait Implementations§

Source§

impl Debug for MdnsDiscoveryBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl IntoDiscovery for MdnsDiscoveryBuilder

Source§

fn into_discovery( self, context: &DiscoveryContext<'_>, ) -> Result<impl Discovery, IntoDiscoveryError>

Turns this discovery builder into a ready-to-use discovery service. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where diff --git a/pr/3327/docs/iroh/discovery/pkarr/constant.DEFAULT_PKARR_TTL.html b/pr/3327/docs/iroh/discovery/pkarr/constant.DEFAULT_PKARR_TTL.html index 5683c7706d..8be2e9056d 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/constant.DEFAULT_PKARR_TTL.html +++ b/pr/3327/docs/iroh/discovery/pkarr/constant.DEFAULT_PKARR_TTL.html @@ -1,4 +1,4 @@ -DEFAULT_PKARR_TTL in iroh::discovery::pkarr - Rust

Constant DEFAULT_PKARR_TTL

Source
pub const DEFAULT_PKARR_TTL: u32 = 30;
Expand description

Default TTL for the records in the pkarr signed packet.

+DEFAULT_PKARR_TTL in iroh::discovery::pkarr - Rust

Constant DEFAULT_PKARR_TTL

Source
pub const DEFAULT_PKARR_TTL: u32 = 30;
Expand description

Default TTL for the records in the pkarr signed packet.

The Time To Live (TTL) tells DNS caches how long to store a record. It is ignored by the iroh-dns-server, e.g. as running on N0_DNS_PKARR_RELAY_PROD, as the home server keeps the records for the domain. When using the pkarr relay no DNS is involved and the diff --git a/pr/3327/docs/iroh/discovery/pkarr/constant.DEFAULT_REPUBLISH_INTERVAL.html b/pr/3327/docs/iroh/discovery/pkarr/constant.DEFAULT_REPUBLISH_INTERVAL.html index 9f71256c08..70e5c3d43b 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/constant.DEFAULT_REPUBLISH_INTERVAL.html +++ b/pr/3327/docs/iroh/discovery/pkarr/constant.DEFAULT_REPUBLISH_INTERVAL.html @@ -1,2 +1,2 @@ -DEFAULT_REPUBLISH_INTERVAL in iroh::discovery::pkarr - Rust

Constant DEFAULT_REPUBLISH_INTERVAL

Source
pub const DEFAULT_REPUBLISH_INTERVAL: Duration;
Expand description

Interval in which to republish the node info even if unchanged: 5 minutes.

+DEFAULT_REPUBLISH_INTERVAL in iroh::discovery::pkarr - Rust

Constant DEFAULT_REPUBLISH_INTERVAL

Source
pub const DEFAULT_REPUBLISH_INTERVAL: Duration;
Expand description

Interval in which to republish the node info even if unchanged: 5 minutes.

\ No newline at end of file diff --git a/pr/3327/docs/iroh/discovery/pkarr/constant.N0_DNS_PKARR_RELAY_PROD.html b/pr/3327/docs/iroh/discovery/pkarr/constant.N0_DNS_PKARR_RELAY_PROD.html index 25d05eba48..9950207afa 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/constant.N0_DNS_PKARR_RELAY_PROD.html +++ b/pr/3327/docs/iroh/discovery/pkarr/constant.N0_DNS_PKARR_RELAY_PROD.html @@ -1,4 +1,4 @@ -N0_DNS_PKARR_RELAY_PROD in iroh::discovery::pkarr - Rust

Constant N0_DNS_PKARR_RELAY_PROD

Source
pub const N0_DNS_PKARR_RELAY_PROD: &str = "https://dns.iroh.link/pkarr";
Expand description

The production pkarr relay run by number 0.

+N0_DNS_PKARR_RELAY_PROD in iroh::discovery::pkarr - Rust

Constant N0_DNS_PKARR_RELAY_PROD

Source
pub const N0_DNS_PKARR_RELAY_PROD: &str = "https://dns.iroh.link/pkarr";
Expand description

The production pkarr relay run by number 0.

This server is both a pkarr relay server as well as a DNS resolver, see the module documentation. However it does not interact with the Mainline DHT, so is a more central service. It is a reliable service to use for node discovery.

diff --git a/pr/3327/docs/iroh/discovery/pkarr/constant.N0_DNS_PKARR_RELAY_STAGING.html b/pr/3327/docs/iroh/discovery/pkarr/constant.N0_DNS_PKARR_RELAY_STAGING.html index 60efa6f310..9deb17434c 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/constant.N0_DNS_PKARR_RELAY_STAGING.html +++ b/pr/3327/docs/iroh/discovery/pkarr/constant.N0_DNS_PKARR_RELAY_STAGING.html @@ -1,4 +1,4 @@ -N0_DNS_PKARR_RELAY_STAGING in iroh::discovery::pkarr - Rust

Constant N0_DNS_PKARR_RELAY_STAGING

Source
pub const N0_DNS_PKARR_RELAY_STAGING: &str = "https://staging-dns.iroh.link/pkarr";
Expand description

The testing pkarr relay run by number 0.

+N0_DNS_PKARR_RELAY_STAGING in iroh::discovery::pkarr - Rust

Constant N0_DNS_PKARR_RELAY_STAGING

Source
pub const N0_DNS_PKARR_RELAY_STAGING: &str = "https://staging-dns.iroh.link/pkarr";
Expand description

The testing pkarr relay run by number 0.

This server operates similarly to N0_DNS_PKARR_RELAY_PROD but is not as reliable. It is meant for more experimental use and testing purposes.

\ No newline at end of file diff --git a/pr/3327/docs/iroh/discovery/pkarr/dht/index.html b/pr/3327/docs/iroh/discovery/pkarr/dht/index.html index 0705ac0238..90fab29ce5 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/dht/index.html +++ b/pr/3327/docs/iroh/discovery/pkarr/dht/index.html @@ -1,4 +1,4 @@ -iroh::discovery::pkarr::dht - Rust

Module dht

Source
Available on crate feature discovery-pkarr-dht only.
Expand description

Pkarr based node discovery for iroh, supporting both relay servers and the DHT.

+iroh::discovery::pkarr::dht - Rust

Module dht

Source
Available on crate feature discovery-pkarr-dht only.
Expand description

Pkarr based node discovery for iroh, supporting both relay servers and the DHT.

This module contains pkarr-based node discovery for iroh which can use both pkarr relay servers as well as the Mainline DHT directly. See the pkarr module for an overview of pkarr.

diff --git a/pr/3327/docs/iroh/discovery/pkarr/dht/struct.Builder.html b/pr/3327/docs/iroh/discovery/pkarr/dht/struct.Builder.html index d623dc71ec..1256048e90 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/dht/struct.Builder.html +++ b/pr/3327/docs/iroh/discovery/pkarr/dht/struct.Builder.html @@ -1,18 +1,18 @@ Builder in iroh::discovery::pkarr::dht - Rust

Struct Builder

Source
pub struct Builder { /* private fields */ }
Available on crate feature discovery-pkarr-dht only.
Expand description

Builder for DhtDiscovery.

By default, publishing to the DHT is enabled, and relay publishing is disabled.

-

Implementations§

Source§

impl Builder

Source

pub fn client(self, client: PkarrClient) -> Self

Explicitly sets the pkarr client to use.

+

Implementations§

Source§

impl Builder

Source

pub fn client(self, client: PkarrClient) -> Self

Explicitly sets the pkarr client to use.

Source

pub fn secret_key(self, secret_key: SecretKey) -> Self

Sets the secret key to use for signing the DNS packets.

Without a secret key, the node will not publish its address to the DHT.

Source

pub fn ttl(self, ttl: u32) -> Self

Sets the time-to-live value for the DNS packets.

Source

pub fn pkarr_relay(self, pkarr_relay: Url) -> Self

Sets the pkarr relay URL to use.

-
Source

pub fn n0_dns_pkarr_relay(self) -> Self

Uses the default number 0 pkarr relay URL.

-
Source

pub fn dht(self, dht: bool) -> Self

Sets whether to publish to the Mainline DHT.

-
Source

pub fn include_direct_addresses(self, include_direct_addresses: bool) -> Self

Sets whether to include the direct addresses in the DNS packet.

-
Source

pub fn initial_publish_delay(self, initial_publish_delay: Duration) -> Self

Sets the initial delay before the first publish.

-
Source

pub fn republish_delay(self, republish_delay: Duration) -> Self

Sets the republish delay for the DHT.

-
Source

pub fn no_publish(self) -> Self

Disables publishing even if a secret key is set.

-
Source

pub fn build(self) -> Result<DhtDiscovery, IntoDiscoveryError>

Builds the discovery mechanism.

-

Trait Implementations§

Source§

impl Debug for Builder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Builder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl IntoDiscovery for Builder

Source

pub fn n0_dns_pkarr_relay(self) -> Self

Uses the default number 0 pkarr relay URL.

+
Source

pub fn dht(self, dht: bool) -> Self

Sets whether to publish to the Mainline DHT.

+
Source

pub fn include_direct_addresses(self, include_direct_addresses: bool) -> Self

Sets whether to include the direct addresses in the DNS packet.

+
Source

pub fn initial_publish_delay(self, initial_publish_delay: Duration) -> Self

Sets the initial delay before the first publish.

+
Source

pub fn republish_delay(self, republish_delay: Duration) -> Self

Sets the republish delay for the DHT.

+
Source

pub fn no_publish(self) -> Self

Disables publishing even if a secret key is set.

+
Source

pub fn build(self) -> Result<DhtDiscovery, IntoDiscoveryError>

Builds the discovery mechanism.

+

Trait Implementations§

Source§

impl Debug for Builder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Builder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl IntoDiscovery for Builder

Source§

fn into_discovery( self, context: &DiscoveryContext<'_>, ) -> Result<impl Discovery, IntoDiscoveryError>

Turns this discovery builder into a ready-to-use discovery service. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where diff --git a/pr/3327/docs/iroh/discovery/pkarr/dht/struct.DhtDiscovery.html b/pr/3327/docs/iroh/discovery/pkarr/dht/struct.DhtDiscovery.html index 31ffd36aac..47015f956b 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/dht/struct.DhtDiscovery.html +++ b/pr/3327/docs/iroh/discovery/pkarr/dht/struct.DhtDiscovery.html @@ -4,11 +4,11 @@ them to the BitTorrent Mainline DHT. See the Discovery trait to be used as a node discovery service which can be used as both a publisher and resolver. Calling DhtDiscovery::publish will start a background task that periodically publishes the node address.

-

Implementations§

Source§

impl DhtDiscovery

Source

pub fn builder() -> Builder

Creates a new builder for DhtDiscovery.

-

Trait Implementations§

Source§

impl Clone for DhtDiscovery

Source§

fn clone(&self) -> DhtDiscovery

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DhtDiscovery

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for DhtDiscovery

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Discovery for DhtDiscovery

Source§

fn publish(&self, data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn resolve( +

Implementations§

Source§

impl DhtDiscovery

Source

pub fn builder() -> Builder

Creates a new builder for DhtDiscovery.

+

Trait Implementations§

Source§

impl Clone for DhtDiscovery

Source§

fn clone(&self) -> DhtDiscovery

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DhtDiscovery

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for DhtDiscovery

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Discovery for DhtDiscovery

Source§

fn publish(&self, data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn resolve( &self, node_id: NodeId, -) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( @@ -28,8 +28,8 @@ a background task that periodically publishes the node address.

U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

-
Source§

impl<T> IntoDiscovery for T
where - T: Discovery,

Source§

impl<T> IntoDiscovery for T
where + T: Discovery,

Source§

fn into_discovery( self, _context: &DiscoveryContext<'_>, ) -> Result<impl Discovery, IntoDiscoveryError>

Turns this discovery builder into a ready-to-use discovery service. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where diff --git a/pr/3327/docs/iroh/discovery/pkarr/enum.PkarrError.html b/pr/3327/docs/iroh/discovery/pkarr/enum.PkarrError.html index ccc496331b..ea71978b02 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/enum.PkarrError.html +++ b/pr/3327/docs/iroh/discovery/pkarr/enum.PkarrError.html @@ -1,4 +1,4 @@ -PkarrError in iroh::discovery::pkarr - Rust

Enum PkarrError

Source
#[non_exhaustive]
pub enum PkarrError { +PkarrError in iroh::discovery::pkarr - Rust

Enum PkarrError

Source
#[non_exhaustive]
pub enum PkarrError { PublicKey { source: PublicKeyError, }, @@ -17,11 +17,14 @@ HttpPayload { source: Error, }, -}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

PublicKey

Fields

§source: PublicKeyError
§

Verify

Fields

§source: SignedPacketVerifyError
§

InvalidRelayUrl

Fields

§

HttpSend

Fields

§source: Error
§

HttpRequest

Fields

§status: StatusCode
§

HttpPayload

Fields

§source: Error

Trait Implementations§

Source§

impl Debug for PkarrError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for PkarrError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for PkarrError
where + Encoding { + source: EncodingError, + }, +}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

PublicKey

Fields

§source: PublicKeyError
§

Verify

Fields

§source: SignedPacketVerifyError
§

InvalidRelayUrl

Fields

§

HttpSend

Fields

§source: Error
§

HttpRequest

Fields

§status: StatusCode
§

HttpPayload

Fields

§source: Error
§

Encoding

Fields

Trait Implementations§

Source§

impl Debug for PkarrError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for PkarrError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for PkarrError
where Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for PkarrError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<PkarrError> for DiscoveryError

Source§

fn from(err: PkarrError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<PkarrError> for DiscoveryError

Source§

fn from(err: PkarrError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3327/docs/iroh/discovery/pkarr/index.html b/pr/3327/docs/iroh/discovery/pkarr/index.html index 08a21045e8..75531baebd 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/index.html +++ b/pr/3327/docs/iroh/discovery/pkarr/index.html @@ -1,4 +1,4 @@ -iroh::discovery::pkarr - Rust

Module pkarr

Source
Expand description

A discovery service which publishes and resolves node information using a pkarr relay.

+iroh::discovery::pkarr - Rust

Module pkarr

Source
Expand description

A discovery service which publishes and resolves node information using a pkarr relay.

Public-Key Addressable Resource Records, pkarr, is a system which allows publishing DNS Resource Records owned by a particular SecretKey under a name derived from its corresponding PublicKey, also known as the NodeId. Additionally this pkarr diff --git a/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrPublisher.html b/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrPublisher.html index 44bdb40322..312594ac56 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrPublisher.html +++ b/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrPublisher.html @@ -1,28 +1,28 @@ -PkarrPublisher in iroh::discovery::pkarr - Rust

Struct PkarrPublisher

Source
pub struct PkarrPublisher { /* private fields */ }
Expand description

Publisher of node discovery information to a pkarr relay.

+PkarrPublisher in iroh::discovery::pkarr - Rust

Struct PkarrPublisher

Source
pub struct PkarrPublisher { /* private fields */ }
Expand description

Publisher of node discovery information to a pkarr relay.

This publisher uses HTTP to publish node discovery information to a pkarr relay server, see the module docs for details.

This implements the Discovery trait to be used as a node discovery service. Note that it only publishes node discovery information, for the corresponding resolver use the PkarrResolver together with ConcurrentDiscovery.

This publisher will only publish the RelayUrl if it is set, otherwise the direct addresses are published instead.

-

Implementations§

Source§

impl PkarrPublisher

Source

pub fn builder(pkarr_relay: Url) -> PkarrPublisherBuilder

Returns a PkarrPublisherBuilder that publishes node info to a pkarr relay at pkarr_relay.

+

Implementations§

Source§

impl PkarrPublisher

Source

pub fn builder(pkarr_relay: Url) -> PkarrPublisherBuilder

Returns a PkarrPublisherBuilder that publishes node info to a pkarr relay at pkarr_relay.

If no further options are set, the pkarr publisher will use DEFAULT_PKARR_TTL as the time-to-live value for the published packets, and it will republish discovery information every DEFAULT_REPUBLISH_INTERVAL, even if the information is unchanged.

PkarrPublisherBuilder implements IntoDiscovery, so it can be passed to add_discovery. It will then use the endpoint’s secret key to sign published packets.

-
Source

pub fn n0_dns() -> PkarrPublisherBuilder

Creates a pkarr publisher which uses the number 0 pkarr relay server.

+
Source

pub fn n0_dns() -> PkarrPublisherBuilder

Creates a pkarr publisher which uses the number 0 pkarr relay server.

This uses the pkarr relay server operated by number 0, at N0_DNS_PKARR_RELAY_PROD.

When running with the environment variable IROH_FORCE_STAGING_RELAYS set to any non empty value N0_DNS_PKARR_RELAY_STAGING server is used instead.

-
Source

pub fn update_node_data(&self, data: &NodeData)

Publishes the addressing information about this node to a pkarr relay.

+
Source

pub fn update_node_data(&self, data: &NodeData)

Publishes the addressing information about this node to a pkarr relay.

This is a nonblocking function, the actual update is performed in the background.

-

Trait Implementations§

Source§

impl Clone for PkarrPublisher

Source§

fn clone(&self) -> PkarrPublisher

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PkarrPublisher

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Discovery for PkarrPublisher

Source§

fn publish(&self, data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn resolve( +

Trait Implementations§

Source§

impl Clone for PkarrPublisher

Source§

fn clone(&self) -> PkarrPublisher

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PkarrPublisher

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Discovery for PkarrPublisher

Source§

fn publish(&self, data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn resolve( &self, _node_id: NodeId, -) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( @@ -42,8 +42,8 @@ server is used instead.

U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

-
Source§

impl<T> IntoDiscovery for T
where - T: Discovery,

Source§

impl<T> IntoDiscovery for T
where + T: Discovery,

Source§

fn into_discovery( self, _context: &DiscoveryContext<'_>, ) -> Result<impl Discovery, IntoDiscoveryError>

Turns this discovery builder into a ready-to-use discovery service. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where diff --git a/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrPublisherBuilder.html b/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrPublisherBuilder.html index b7ae325465..908196d281 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrPublisherBuilder.html +++ b/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrPublisherBuilder.html @@ -1,13 +1,13 @@ -PkarrPublisherBuilder in iroh::discovery::pkarr - Rust

Struct PkarrPublisherBuilder

Source
pub struct PkarrPublisherBuilder { /* private fields */ }
Expand description

Builder for PkarrPublisher.

+PkarrPublisherBuilder in iroh::discovery::pkarr - Rust

Struct PkarrPublisherBuilder

Source
pub struct PkarrPublisherBuilder { /* private fields */ }
Expand description

Implementations§

Source§

impl PkarrPublisherBuilder

Source

pub fn ttl(self, ttl: u32) -> Self

Sets the TTL (time-to-live) for published packets.

+

Implementations§

Source§

impl PkarrPublisherBuilder

Source

pub fn ttl(self, ttl: u32) -> Self

Sets the TTL (time-to-live) for published packets.

Default is DEFAULT_PKARR_TTL.

-
Source

pub fn republish_interval(self, republish_interval: Duration) -> Self

Sets the interval after which packets are republished even if our node info did not change.

+
Source

pub fn republish_interval(self, republish_interval: Duration) -> Self

Sets the interval after which packets are republished even if our node info did not change.

Default is DEFAULT_REPUBLISH_INTERVAL.

-
Source

pub fn dns_resolver(self, dns_resolver: DnsResolver) -> Self

Available on non-wasm_browser only.

Sets the DNS resolver to use for resolving the pkarr relay URL.

-
Source

pub fn build(self, secret_key: SecretKey) -> PkarrPublisher

Builds the PkarrPublisher with the passed secret key for signing packets.

+
Source

pub fn dns_resolver(self, dns_resolver: DnsResolver) -> Self

Available on non-wasm_browser only.

Sets the DNS resolver to use for resolving the pkarr relay URL.

+
Source

pub fn build(self, secret_key: SecretKey) -> PkarrPublisher

Builds the PkarrPublisher with the passed secret key for signing packets.

This publisher will be able to publish [pkarr] records for SecretKey.

-

Trait Implementations§

Source§

impl Debug for PkarrPublisherBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl IntoDiscovery for PkarrPublisherBuilder

Trait Implementations§

Source§

impl Debug for PkarrPublisherBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl IntoDiscovery for PkarrPublisherBuilder

Source§

fn into_discovery( self, context: &DiscoveryContext<'_>, ) -> Result<impl Discovery, IntoDiscoveryError>

Turns this discovery builder into a ready-to-use discovery service. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where diff --git a/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrRelayClient.html b/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrRelayClient.html index fb08914345..565f447003 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrRelayClient.html +++ b/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrRelayClient.html @@ -1,18 +1,18 @@ -PkarrRelayClient in iroh::discovery::pkarr - Rust

Struct PkarrRelayClient

Source
pub struct PkarrRelayClient { /* private fields */ }
Expand description

A pkarr client to publish [pkarr::SignedPacket]s to a pkarr relay.

-

Implementations§

Source§

impl PkarrRelayClient

Source

pub fn new(pkarr_relay_url: Url) -> Self

Creates a new client.

-
Source

pub fn with_dns_resolver( +PkarrRelayClient in iroh::discovery::pkarr - Rust

Struct PkarrRelayClient

Source
pub struct PkarrRelayClient { /* private fields */ }
Expand description

A pkarr client to publish [pkarr::SignedPacket]s to a pkarr relay.

+

Implementations§

Source§

impl PkarrRelayClient

Source

pub fn new(pkarr_relay_url: Url) -> Self

Creates a new client.

+
Source

pub fn with_dns_resolver( pkarr_relay_url: Url, dns_resolver: DnsResolver, ) -> Self

Available on non-wasm_browser only.

Creates a new client while passing a DNS resolver to use.

-
Source

pub async fn resolve( +

Source

pub async fn resolve( &self, node_id: NodeId, ) -> Result<SignedPacket, DiscoveryError>

Resolves a [SignedPacket] for the given NodeId.

-
Source

pub async fn publish( +

Source

pub async fn publish( &self, signed_packet: &SignedPacket, -) -> Result<(), DiscoveryError>

Publishes a [SignedPacket].

-

Trait Implementations§

Source§

impl Clone for PkarrRelayClient

Source§

fn clone(&self) -> PkarrRelayClient

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PkarrRelayClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +) -> Result<(), PkarrError>

Publishes a [SignedPacket].

+

Trait Implementations§

Source§

impl Clone for PkarrRelayClient

Source§

fn clone(&self) -> PkarrRelayClient

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PkarrRelayClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrResolver.html b/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrResolver.html index dfb5b7d2d3..061d3abc04 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrResolver.html +++ b/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrResolver.html @@ -1,21 +1,21 @@ -PkarrResolver in iroh::discovery::pkarr - Rust

Struct PkarrResolver

Source
pub struct PkarrResolver { /* private fields */ }
Expand description

Resolver of node discovery information from a pkarr relay.

+PkarrResolver in iroh::discovery::pkarr - Rust

Struct PkarrResolver

Source
pub struct PkarrResolver { /* private fields */ }
Expand description

Resolver of node discovery information from a pkarr relay.

The resolver uses HTTP to query node discovery information from a pkarr relay server, see the module docs for details.

This implements the Discovery trait to be used as a node discovery service. Note that it only resolves node discovery information, for the corresponding publisher use the PkarrPublisher together with ConcurrentDiscovery.

-

Implementations§

Source§

impl PkarrResolver

Source

pub fn builder(pkarr_relay: Url) -> PkarrResolverBuilder

Creates a new resolver builder using the pkarr relay server at the URL.

+

Implementations§

Source§

impl PkarrResolver

Source

pub fn builder(pkarr_relay: Url) -> PkarrResolverBuilder

Creates a new resolver builder using the pkarr relay server at the URL.

The builder implements IntoDiscovery.

-
Source

pub fn n0_dns() -> PkarrResolverBuilder

Creates a pkarr resolver builder which uses the number 0 pkarr relay server.

+
Source

pub fn n0_dns() -> PkarrResolverBuilder

Creates a pkarr resolver builder which uses the number 0 pkarr relay server.

This uses the pkarr relay server operated by number 0 at N0_DNS_PKARR_RELAY_PROD.

When running with the environment variable IROH_FORCE_STAGING_RELAYS set to any non empty value N0_DNS_PKARR_RELAY_STAGING server is used instead.

-

Trait Implementations§

Source§

impl Clone for PkarrResolver

Source§

fn clone(&self) -> PkarrResolver

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PkarrResolver

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Discovery for PkarrResolver

Trait Implementations§

Source§

impl Clone for PkarrResolver

Source§

fn clone(&self) -> PkarrResolver

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PkarrResolver

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Discovery for PkarrResolver

Source§

fn resolve( &self, node_id: NodeId, -) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn publish(&self, _data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn publish(&self, _data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( @@ -35,8 +35,8 @@ server is used instead.

U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

-
Source§

impl<T> IntoDiscovery for T
where - T: Discovery,

Source§

impl<T> IntoDiscovery for T
where + T: Discovery,

Source§

fn into_discovery( self, _context: &DiscoveryContext<'_>, ) -> Result<impl Discovery, IntoDiscoveryError>

Turns this discovery builder into a ready-to-use discovery service. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where diff --git a/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrResolverBuilder.html b/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrResolverBuilder.html index e86db9ff33..d6032b1808 100644 --- a/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrResolverBuilder.html +++ b/pr/3327/docs/iroh/discovery/pkarr/struct.PkarrResolverBuilder.html @@ -1,8 +1,8 @@ -PkarrResolverBuilder in iroh::discovery::pkarr - Rust

Struct PkarrResolverBuilder

Source
pub struct PkarrResolverBuilder { /* private fields */ }
Expand description

Builder for PkarrResolver.

+PkarrResolverBuilder in iroh::discovery::pkarr - Rust

Struct PkarrResolverBuilder

Source
pub struct PkarrResolverBuilder { /* private fields */ }
Expand description

Implementations§

Source§

impl PkarrResolverBuilder

Source

pub fn dns_resolver(self, dns_resolver: DnsResolver) -> Self

Available on non-wasm_browser only.

Sets the DNS resolver to use for resolving the pkarr relay URL.

-
Source

pub fn build(self) -> PkarrResolver

Creates a PkarrResolver from this builder.

-

Trait Implementations§

Source§

impl Debug for PkarrResolverBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl IntoDiscovery for PkarrResolverBuilder

Implementations§

Source§

impl PkarrResolverBuilder

Source

pub fn dns_resolver(self, dns_resolver: DnsResolver) -> Self

Available on non-wasm_browser only.

Sets the DNS resolver to use for resolving the pkarr relay URL.

+
Source

pub fn build(self) -> PkarrResolver

Creates a PkarrResolver from this builder.

+

Trait Implementations§

Source§

impl Debug for PkarrResolverBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl IntoDiscovery for PkarrResolverBuilder

Source§

fn into_discovery( self, context: &DiscoveryContext<'_>, ) -> Result<impl Discovery, IntoDiscoveryError>

Turns this discovery builder into a ready-to-use discovery service. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where diff --git a/pr/3327/docs/iroh/discovery/static_provider/struct.StaticProvider.html b/pr/3327/docs/iroh/discovery/static_provider/struct.StaticProvider.html index f6530564de..123286b6de 100644 --- a/pr/3327/docs/iroh/discovery/static_provider/struct.StaticProvider.html +++ b/pr/3327/docs/iroh/discovery/static_provider/struct.StaticProvider.html @@ -61,7 +61,7 @@ relay URL is overwritten.

Trait Implementations§

Source§

impl Clone for StaticProvider

Source§

fn clone(&self) -> StaticProvider

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for StaticProvider

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for StaticProvider

Source§

fn default() -> StaticProvider

Returns the “default value” for a type. Read more
Source§

impl Discovery for StaticProvider

Source§

fn publish(&self, _data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn resolve( &self, node_id: NodeId, -) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( @@ -81,8 +81,8 @@ relay URL is overwritten.

U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

-
Source§

impl<T> IntoDiscovery for T
where - T: Discovery,

Source§

impl<T> IntoDiscovery for T
where + T: Discovery,

Source§

fn into_discovery( self, _context: &DiscoveryContext<'_>, ) -> Result<impl Discovery, IntoDiscoveryError>

Turns this discovery builder into a ready-to-use discovery service. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where diff --git a/pr/3327/docs/iroh/discovery/struct.ConcurrentDiscovery.html b/pr/3327/docs/iroh/discovery/struct.ConcurrentDiscovery.html index ea3920ec16..bef417d7b7 100644 --- a/pr/3327/docs/iroh/discovery/struct.ConcurrentDiscovery.html +++ b/pr/3327/docs/iroh/discovery/struct.ConcurrentDiscovery.html @@ -1,13 +1,13 @@ -ConcurrentDiscovery in iroh::discovery - Rust

Struct ConcurrentDiscovery

Source
pub struct ConcurrentDiscovery { /* private fields */ }
Expand description

A discovery service that combines multiple discovery sources.

+ConcurrentDiscovery in iroh::discovery - Rust

Struct ConcurrentDiscovery

Source
pub struct ConcurrentDiscovery { /* private fields */ }
Expand description

A discovery service that combines multiple discovery sources.

The discovery services will resolve concurrently.

-

Implementations§

Source§

impl ConcurrentDiscovery

Source

pub fn empty() -> Self

Creates an empty ConcurrentDiscovery.

-
Source

pub fn from_services(services: Vec<Box<dyn Discovery>>) -> Self

Creates a new ConcurrentDiscovery.

-
Source

pub fn add(&mut self, service: impl Discovery + 'static)

Adds a Discovery service.

-

Trait Implementations§

Source§

impl Debug for ConcurrentDiscovery

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ConcurrentDiscovery

Source§

fn default() -> ConcurrentDiscovery

Returns the “default value” for a type. Read more
Source§

impl Discovery for ConcurrentDiscovery

Source§

fn publish(&self, data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn resolve( +

Implementations§

Source§

impl ConcurrentDiscovery

Source

pub fn empty() -> Self

Creates an empty ConcurrentDiscovery.

+
Source

pub fn from_services(services: Vec<Box<dyn Discovery>>) -> Self

Creates a new ConcurrentDiscovery.

+
Source

pub fn add(&mut self, service: impl Discovery + 'static)

Adds a Discovery service.

+

Trait Implementations§

Source§

impl Debug for ConcurrentDiscovery

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ConcurrentDiscovery

Source§

fn default() -> ConcurrentDiscovery

Returns the “default value” for a type. Read more
Source§

impl Discovery for ConcurrentDiscovery

Source§

fn publish(&self, data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn resolve( &self, node_id: NodeId, -) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more
Source§

impl<T> From<T> for ConcurrentDiscovery
where - T: IntoIterator<Item = Box<dyn Discovery>>,

Source§

fn from(iter: T) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId. Read more
Source§

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered. Read more
Source§

impl<T> From<T> for ConcurrentDiscovery
where + T: IntoIterator<Item = Box<dyn Discovery>>,

Source§

fn from(iter: T) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( @@ -24,8 +24,8 @@ U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

-
Source§

impl<T> IntoDiscovery for T
where - T: Discovery,

Source§

impl<T> IntoDiscovery for T
where + T: Discovery,

Source§

fn into_discovery( self, _context: &DiscoveryContext<'_>, ) -> Result<impl Discovery, IntoDiscoveryError>

Turns this discovery builder into a ready-to-use discovery service. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where diff --git a/pr/3327/docs/iroh/discovery/struct.DiscoveryContext.html b/pr/3327/docs/iroh/discovery/struct.DiscoveryContext.html index 06c8431c9f..0718d526ed 100644 --- a/pr/3327/docs/iroh/discovery/struct.DiscoveryContext.html +++ b/pr/3327/docs/iroh/discovery/struct.DiscoveryContext.html @@ -1,8 +1,8 @@ -DiscoveryContext in iroh::discovery - Rust

Struct DiscoveryContext

Source
pub struct DiscoveryContext<'a> { /* private fields */ }
Expand description

Context about the Endpoint for discovery services.

-

Implementations§

Source§

impl<'a> DiscoveryContext<'a>

Source

pub fn node_id(&self) -> NodeId

Returns the NodeId of the endpoint.

-
Source

pub fn secret_key(&self) -> &SecretKey

Returns the SecretKey of the endpoint.

-
Source

pub fn dns_resolver(&self) -> &DnsResolver

Available on non-wasm_browser only.

Returns the DnsResolver used by the endpoint.

-

Trait Implementations§

Source§

impl<'a> Debug for DiscoveryContext<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for DiscoveryContext<'a>

§

impl<'a> !RefUnwindSafe for DiscoveryContext<'a>

§

impl<'a> Send for DiscoveryContext<'a>

§

impl<'a> Sync for DiscoveryContext<'a>

§

impl<'a> Unpin for DiscoveryContext<'a>

§

impl<'a> !UnwindSafe for DiscoveryContext<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where +DiscoveryContext in iroh::discovery - Rust

Struct DiscoveryContext

Source
pub struct DiscoveryContext<'a> { /* private fields */ }
Expand description

Context about the Endpoint for discovery services.

+

Implementations§

Source§

impl<'a> DiscoveryContext<'a>

Source

pub fn node_id(&self) -> NodeId

Returns the NodeId of the endpoint.

+
Source

pub fn secret_key(&self) -> &SecretKey

Returns the SecretKey of the endpoint.

+
Source

pub fn dns_resolver(&self) -> &DnsResolver

Available on non-wasm_browser only.

Returns the DnsResolver used by the endpoint.

+

Trait Implementations§

Source§

impl<'a> Debug for DiscoveryContext<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> Freeze for DiscoveryContext<'a>

§

impl<'a> !RefUnwindSafe for DiscoveryContext<'a>

§

impl<'a> Send for DiscoveryContext<'a>

§

impl<'a> Sync for DiscoveryContext<'a>

§

impl<'a> Unpin for DiscoveryContext<'a>

§

impl<'a> !UnwindSafe for DiscoveryContext<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/discovery/struct.DiscoveryItem.html b/pr/3327/docs/iroh/discovery/struct.DiscoveryItem.html index 89a3696e41..3735ead6c4 100644 --- a/pr/3327/docs/iroh/discovery/struct.DiscoveryItem.html +++ b/pr/3327/docs/iroh/discovery/struct.DiscoveryItem.html @@ -1,28 +1,28 @@ -DiscoveryItem in iroh::discovery - Rust

Struct DiscoveryItem

Source
pub struct DiscoveryItem { /* private fields */ }
Expand description

Node discovery results from Discovery services.

+DiscoveryItem in iroh::discovery - Rust

Struct DiscoveryItem

Source
pub struct DiscoveryItem { /* private fields */ }
Expand description

Node discovery results from Discovery services.

This is the item in the streams returned from Discovery::resolve and Discovery::subscribe. It contains the NodeData about the discovered node, and some additional metadata about the discovery.

This struct derefs to NodeData, so you can access the methods from NodeData directly from DiscoveryItem.

-

Implementations§

Source§

impl DiscoveryItem

Source

pub fn new( +

Implementations§

Source§

impl DiscoveryItem

Source

pub fn new( node_info: NodeInfo, provenance: &'static str, last_updated: Option<u64>, ) -> Self

Creates a new DiscoveryItem from a NodeInfo.

-
Source

pub fn node_id(&self) -> NodeId

Returns the node id of the discovered node.

-
Source

pub fn node_info(&self) -> &NodeInfo

Returns the NodeInfo for the discovered node.

-
Source

pub fn provenance(&self) -> &'static str

Returns the provenance of this discovery item.

+
Source

pub fn node_id(&self) -> NodeId

Returns the node id of the discovered node.

+
Source

pub fn node_info(&self) -> &NodeInfo

Returns the NodeInfo for the discovered node.

+
Source

pub fn provenance(&self) -> &'static str

Returns the provenance of this discovery item.

The provenance is a static string which identifies the discovery service that produced this discovery item.

-
Source

pub fn last_updated(&self) -> Option<u64>

Returns the optional timestamp when this node info was last updated.

+
Source

pub fn last_updated(&self) -> Option<u64>

Returns the optional timestamp when this node info was last updated.

The value is microseconds since the unix epoch.

-
Source

pub fn to_node_addr(&self) -> NodeAddr

Converts into a NodeAddr by cloning the needed fields.

-
Source

pub fn into_node_addr(self) -> NodeAddr

Converts into a NodeAddr without cloning.

-
Source

pub fn user_data(&self) -> Option<UserData>

Returns any user-defined data.

+
Source

pub fn to_node_addr(&self) -> NodeAddr

Converts into a NodeAddr by cloning the needed fields.

+
Source

pub fn into_node_addr(self) -> NodeAddr

Converts into a NodeAddr without cloning.

+
Source

pub fn user_data(&self) -> Option<UserData>

Returns any user-defined data.

Methods from Deref<Target = NodeData>§

Source

pub fn relay_url(&self) -> Option<&RelayUrl>

Returns the relay URL of the node.

Source

pub fn user_data(&self) -> Option<&UserData>

Returns the optional user-defined data of the node.

Source

pub fn direct_addresses(&self) -> &BTreeSet<SocketAddr>

Returns the direct addresses of the node.

-

Trait Implementations§

Source§

impl Clone for DiscoveryItem

Source§

fn clone(&self) -> DiscoveryItem

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DiscoveryItem

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for DiscoveryItem

Source§

type Target = NodeData

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl From<DiscoveryItem> for NodeInfo

Source§

fn from(item: DiscoveryItem) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for DiscoveryItem

Source§

fn clone(&self) -> DiscoveryItem

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DiscoveryItem

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Deref for DiscoveryItem

Source§

type Target = NodeData

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl From<DiscoveryItem> for NodeInfo

Source§

fn from(item: DiscoveryItem) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/discovery/struct.Lagged.html b/pr/3327/docs/iroh/discovery/struct.Lagged.html index 2e10a2d8be..e30bad414d 100644 --- a/pr/3327/docs/iroh/discovery/struct.Lagged.html +++ b/pr/3327/docs/iroh/discovery/struct.Lagged.html @@ -1,4 +1,4 @@ -Lagged in iroh::discovery - Rust

Struct Lagged

Source
pub struct Lagged {
+Lagged in iroh::discovery - Rust

Struct Lagged

Source
pub struct Lagged {
     pub val: u64,
 }
Expand description

Error returned when a discovery watch stream lagged too far behind.

The stream returned from Endpoint::discovery_stream yields this error @@ -7,8 +7,8 @@ discovery events. Attempting to read the next item from the channel afterwards will return the oldest DiscoveryItem that is still retained.

Includes the number of skipped messages.

Fields§

§val: u64

The number of skipped messages

-

Trait Implementations§

Source§

impl Debug for Lagged

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Lagged

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Lagged
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for Lagged

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +

Trait Implementations§

Source§

impl Debug for Lagged

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Lagged

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Lagged
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for Lagged

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error and continuing with recursive calls to Error::source. Read more

Auto Trait Implementations§

§

impl Freeze for Lagged

§

impl RefUnwindSafe for Lagged

§

impl Send for Lagged

§

impl Sync for Lagged

§

impl Unpin for Lagged

§

impl UnwindSafe for Lagged

Blanket Implementations§

Source§

impl<T> Any for T
where diff --git a/pr/3327/docs/iroh/discovery/struct.NodeInfo.html b/pr/3327/docs/iroh/discovery/struct.NodeInfo.html index 457db49d88..69dfd8c811 100644 --- a/pr/3327/docs/iroh/discovery/struct.NodeInfo.html +++ b/pr/3327/docs/iroh/discovery/struct.NodeInfo.html @@ -36,7 +36,7 @@ )

Adds direct addresses to the node data.

Source

pub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)

Sets the relay URL of the node data.

Source

pub fn set_user_data(&mut self, user_data: Option<UserData>)

Sets the user-defined data of the node data.

-

Trait Implementations§

Source§

impl Clone for NodeInfo

Source§

fn clone(&self) -> NodeInfo

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for NodeInfo

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Deref for NodeInfo

Source§

type Target = NodeData

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<NodeInfo as Deref>::Target

Dereferences the value.
Source§

impl DerefMut for NodeInfo

Source§

fn deref_mut(&mut self) -> &mut <NodeInfo as Deref>::Target

Mutably dereferences the value.
Source§

impl From<&TxtAttrs<IrohAttr>> for NodeInfo

Source§

fn from(attrs: &TxtAttrs<IrohAttr>) -> NodeInfo

Converts to this type from the input type.
Source§

impl From<DiscoveryItem> for NodeInfo

Source§

fn from(item: DiscoveryItem) -> Self

Converts to this type from the input type.
Source§

impl From<NodeAddr> for NodeInfo

Source§

fn from(addr: NodeAddr) -> NodeInfo

Converts to this type from the input type.
Source§

impl From<NodeInfo> for NodeAddr

Source§

fn from(value: NodeInfo) -> NodeAddr

Converts to this type from the input type.
Source§

impl From<TxtAttrs<IrohAttr>> for NodeInfo

Source§

fn from(attrs: TxtAttrs<IrohAttr>) -> NodeInfo

Converts to this type from the input type.
Source§

impl PartialEq for NodeInfo

Source§

fn eq(&self, other: &NodeInfo) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +

Trait Implementations§

Source§

impl Clone for NodeInfo

Source§

fn clone(&self) -> NodeInfo

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for NodeInfo

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Deref for NodeInfo

Source§

type Target = NodeData

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<NodeInfo as Deref>::Target

Dereferences the value.
Source§

impl DerefMut for NodeInfo

Source§

fn deref_mut(&mut self) -> &mut <NodeInfo as Deref>::Target

Mutably dereferences the value.
Source§

impl From<&TxtAttrs<IrohAttr>> for NodeInfo

Source§

fn from(attrs: &TxtAttrs<IrohAttr>) -> NodeInfo

Converts to this type from the input type.
Source§

impl From<DiscoveryItem> for NodeInfo

Source§

fn from(item: DiscoveryItem) -> Self

Converts to this type from the input type.
Source§

impl From<NodeAddr> for NodeInfo

Source§

fn from(addr: NodeAddr) -> NodeInfo

Converts to this type from the input type.
Source§

impl From<NodeInfo> for NodeAddr

Source§

fn from(value: NodeInfo) -> NodeAddr

Converts to this type from the input type.
Source§

impl From<TxtAttrs<IrohAttr>> for NodeInfo

Source§

fn from(attrs: TxtAttrs<IrohAttr>) -> NodeInfo

Converts to this type from the input type.
Source§

impl PartialEq for NodeInfo

Source§

fn eq(&self, other: &NodeInfo) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for NodeInfo

Source§

impl StructuralPartialEq for NodeInfo

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where diff --git a/pr/3327/docs/iroh/discovery/trait.Discovery.html b/pr/3327/docs/iroh/discovery/trait.Discovery.html index 642f3437c0..dd27f88c9c 100644 --- a/pr/3327/docs/iroh/discovery/trait.Discovery.html +++ b/pr/3327/docs/iroh/discovery/trait.Discovery.html @@ -1,4 +1,4 @@ -Discovery in iroh::discovery - Rust

Trait Discovery

Source
pub trait Discovery:
+Discovery in iroh::discovery - Rust

Trait Discovery

Source
pub trait Discovery:
     Debug
     + Send
     + Sync
@@ -21,18 +21,18 @@ addresses. See super::Endpoint will call publish whenever
 discovery information changes. If a discovery mechanism requires a periodic
 refresh, it should start its own task.

-

Provided Methods§

Source

fn publish(&self, _data: &NodeData)

Publishes the given NodeData to the discovery mechanism.

+

Provided Methods§

Source

fn publish(&self, _data: &NodeData)

Publishes the given NodeData to the discovery mechanism.

This is fire and forget, since the Endpoint can not wait for successful publishing. If publishing is async, the implementation should start it’s own task.

This will be called from a tokio task, so it is safe to spawn new tasks. These tasks will be run on the runtime of the super::Endpoint.

-
Source

fn resolve( +

Source

fn resolve( &self, _node_id: NodeId, ) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>>

Resolves the DiscoveryItem for the given NodeId.

Once the returned [BoxStream] is dropped, the service should stop any pending work.

-
Source

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered.

+
Source

fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>>

Subscribe to all addresses that get passively discovered.

An implementation may choose to defer emitting passively discovered nodes until the stream is actually polled. To avoid missing discovered nodes, poll the stream as soon as possible.

@@ -49,4 +49,4 @@ should be sent on all streams.

The crate::endpoint::Endpoint will subscribe to the discovery system and add the discovered addresses to the internal address book as they arrive on this stream.

-

Implementations on Foreign Types§

Source§

impl<T: Discovery> Discovery for Arc<T>

Implementors§

Source§

impl Discovery for DnsDiscovery

Available on non-wasm_browser only.
Source§

impl Discovery for MdnsDiscovery

Available on crate feature discovery-local-network only.
Source§

impl Discovery for DhtDiscovery

Available on crate feature discovery-pkarr-dht only.
Source§

impl Discovery for PkarrPublisher

Source§

impl Discovery for PkarrResolver

Source§

impl Discovery for StaticProvider

Source§

impl Discovery for ConcurrentDiscovery

\ No newline at end of file +

Implementations on Foreign Types§

Source§

impl<T: Discovery> Discovery for Arc<T>

Implementors§

Source§

impl Discovery for DnsDiscovery

Available on non-wasm_browser only.
Source§

impl Discovery for MdnsDiscovery

Available on crate feature discovery-local-network only.
Source§

impl Discovery for DhtDiscovery

Available on crate feature discovery-pkarr-dht only.
Source§

impl Discovery for PkarrPublisher

Source§

impl Discovery for PkarrResolver

Source§

impl Discovery for StaticProvider

Source§

impl Discovery for ConcurrentDiscovery

\ No newline at end of file diff --git a/pr/3327/docs/iroh/discovery/trait.IntoDiscovery.html b/pr/3327/docs/iroh/discovery/trait.IntoDiscovery.html index f6b32ece95..79c4a5b954 100644 --- a/pr/3327/docs/iroh/discovery/trait.IntoDiscovery.html +++ b/pr/3327/docs/iroh/discovery/trait.IntoDiscovery.html @@ -1,6 +1,7 @@ -IntoDiscovery in iroh::discovery - Rust

Trait IntoDiscovery

Source
pub trait IntoDiscovery:
+IntoDiscovery in iroh::discovery - Rust

Trait IntoDiscovery

Source
pub trait IntoDiscovery:
     Send
     + Sync
+    + Debug
     + 'static {
     // Required method
     fn into_discovery(
@@ -14,7 +15,7 @@ trait can be added as a discovery service in DiscoveryContext parameter to IntoDiscovery::into_discovery.

-

Required Methods§

Required Methods§

Source

fn into_discovery( self, context: &DiscoveryContext<'_>, ) -> Result<impl Discovery, IntoDiscoveryError>

Turns this discovery builder into a ready-to-use discovery service.

@@ -22,5 +23,5 @@ creation via the Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl IntoDiscovery for DnsDiscoveryBuilder

Available on non-wasm_browser only.
Source§

impl IntoDiscovery for MdnsDiscoveryBuilder

Available on crate feature discovery-local-network only.
Source§

impl IntoDiscovery for Builder

Available on crate feature discovery-pkarr-dht only.
Source§

impl IntoDiscovery for PkarrPublisherBuilder

Source§

impl IntoDiscovery for PkarrResolverBuilder

Source§

impl<T: Discovery> IntoDiscovery for T

Blanket no-op impl of IntoDiscovery for T: Discovery.

+

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl IntoDiscovery for DnsDiscoveryBuilder

Available on non-wasm_browser only.
Source§

impl IntoDiscovery for MdnsDiscoveryBuilder

Available on crate feature discovery-local-network only.
Source§

impl IntoDiscovery for Builder

Available on crate feature discovery-pkarr-dht only.
Source§

impl IntoDiscovery for PkarrPublisherBuilder

Source§

impl IntoDiscovery for PkarrResolverBuilder

Source§

impl<T: Discovery> IntoDiscovery for T

Blanket no-op impl of IntoDiscovery for T: Discovery.

\ No newline at end of file diff --git a/pr/3327/docs/iroh/dns/struct.DnsResolver.html b/pr/3327/docs/iroh/dns/struct.DnsResolver.html index cbf3e120a8..0a60797138 100644 --- a/pr/3327/docs/iroh/dns/struct.DnsResolver.html +++ b/pr/3327/docs/iroh/dns/struct.DnsResolver.html @@ -1,26 +1,26 @@ -DnsResolver in iroh::dns - Rust

Struct DnsResolver

Source
pub struct DnsResolver(/* private fields */);
Available on non-wasm_browser only.
Expand description

The DNS resolver used throughout iroh.

-

Implementations§

Source§

impl DnsResolver

Source

pub fn new() -> DnsResolver

Create a new DNS resolver with sensible cross-platform defaults.

+DnsResolver in iroh::dns - Rust

Struct DnsResolver

Source
pub struct DnsResolver(/* private fields */);
Available on non-wasm_browser only.
Expand description

The DNS resolver used throughout iroh.

+

Implementations§

Source§

impl DnsResolver

Source

pub fn new() -> DnsResolver

Create a new DNS resolver with sensible cross-platform defaults.

We first try to read the system’s resolver from /etc/resolv.conf. This does not work at least on some Androids, therefore we fallback to the default ResolverConfig which uses eg. to google’s 8.8.8.8 or 8.8.4.4.

-
Source

pub fn with_nameserver(nameserver: SocketAddr) -> DnsResolver

Create a new DNS resolver configured with a single UDP DNS nameserver.

-
Source

pub fn clear_cache(&self)

Removes all entries from the cache.

-
Source

pub async fn lookup_txt( +

Source

pub fn with_nameserver(nameserver: SocketAddr) -> DnsResolver

Create a new DNS resolver configured with a single UDP DNS nameserver.

+
Source

pub fn clear_cache(&self)

Removes all entries from the cache.

+
Source

pub async fn lookup_txt( &self, host: impl ToString, timeout: Duration, ) -> Result<TxtLookup, DnsError>

Lookup a TXT record.

-
Source

pub async fn lookup_ipv4( +

Source

pub async fn lookup_ipv4( &self, host: impl ToString, timeout: Duration, ) -> Result<impl Iterator<Item = IpAddr>, DnsError>

Perform an ipv4 lookup with a timeout.

-
Source

pub async fn lookup_ipv6( +

Source

pub async fn lookup_ipv6( &self, host: impl ToString, timeout: Duration, ) -> Result<impl Iterator<Item = IpAddr>, DnsError>

Perform an ipv6 lookup with a timeout.

-
Source

pub async fn lookup_ipv4_ipv6( +

Source

pub async fn lookup_ipv4_ipv6( &self, host: impl ToString, timeout: Duration, @@ -28,76 +28,76 @@ to the default ResolverConfig which uses eg. to google’s 8.

LookupIpStrategy::Ipv4AndIpv6 will wait for ipv6 resolution timeout, even if it is not usable on the stack, so we manually query both lookups concurrently and time them out individually.

-

Source

pub async fn resolve_host( +

Source

pub async fn resolve_host( &self, url: &Url, prefer_ipv6: bool, timeout: Duration, ) -> Result<IpAddr, DnsError>

Resolve a hostname from a URL to an IP address.

-
Source

pub async fn lookup_ipv4_staggered( +

Source

pub async fn lookup_ipv4_staggered( &self, host: impl ToString, timeout: Duration, delays_ms: &[u64], -) -> Result<impl Iterator<Item = IpAddr>, DnsError>

Perform an ipv4 lookup with a timeout in a staggered fashion.

+) -> Result<impl Iterator<Item = IpAddr>, StaggeredError<DnsError>>

Perform an ipv4 lookup with a timeout in a staggered fashion.

From the moment this function is called, each lookup is scheduled after the delays in delays_ms with the first call being done immediately. [200ms, 300ms] results in calls at T+0ms, T+200ms and T+300ms. The timeout is applied to each call individually. The result of the first successful call is returned, or a summary of all errors otherwise.

-
Source

pub async fn lookup_ipv6_staggered( +

Source

pub async fn lookup_ipv6_staggered( &self, host: impl ToString, timeout: Duration, delays_ms: &[u64], -) -> Result<impl Iterator<Item = IpAddr>, DnsError>

Perform an ipv6 lookup with a timeout in a staggered fashion.

+) -> Result<impl Iterator<Item = IpAddr>, StaggeredError<DnsError>>

Perform an ipv6 lookup with a timeout in a staggered fashion.

From the moment this function is called, each lookup is scheduled after the delays in delays_ms with the first call being done immediately. [200ms, 300ms] results in calls at T+0ms, T+200ms and T+300ms. The timeout is applied to each call individually. The result of the first successful call is returned, or a summary of all errors otherwise.

-
Source

pub async fn lookup_ipv4_ipv6_staggered( +

Source

pub async fn lookup_ipv4_ipv6_staggered( &self, host: impl ToString, timeout: Duration, delays_ms: &[u64], -) -> Result<impl Iterator<Item = IpAddr>, DnsError>

Race an ipv4 and ipv6 lookup with a timeout in a staggered fashion.

+) -> Result<impl Iterator<Item = IpAddr>, StaggeredError<DnsError>>

Race an ipv4 and ipv6 lookup with a timeout in a staggered fashion.

From the moment this function is called, each lookup is scheduled after the delays in delays_ms with the first call being done immediately. [200ms, 300ms] results in calls at T+0ms, T+200ms and T+300ms. The timeout is applied as stated in Self::lookup_ipv4_ipv6. The result of the first successful call is returned, or a summary of all errors otherwise.

-
Source

pub async fn lookup_node_by_id( +

Source

pub async fn lookup_node_by_id( &self, node_id: &PublicKey, origin: &str, ) -> Result<NodeInfo, LookupError>

Looks up node info by NodeId and origin domain name.

To lookup nodes that published their node info to the DNS servers run by n0, pass N0_DNS_NODE_ORIGIN_PROD as origin.

-
Source

pub async fn lookup_node_by_domain_name( +

Source

pub async fn lookup_node_by_domain_name( &self, name: &str, ) -> Result<NodeInfo, LookupError>

Looks up node info by DNS name.

-
Source

pub async fn lookup_node_by_domain_name_staggered( +

Source

pub async fn lookup_node_by_domain_name_staggered( &self, name: &str, delays_ms: &[u64], -) -> Result<NodeInfo, Error>

Looks up node info by DNS name in a staggered fashion.

+) -> Result<NodeInfo, StaggeredError<LookupError>>

Looks up node info by DNS name in a staggered fashion.

From the moment this function is called, each lookup is scheduled after the delays in delays_ms with the first call being done immediately. [200ms, 300ms] results in calls at T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a summary of all errors otherwise.

-
Source

pub async fn lookup_node_by_id_staggered( +

Source

pub async fn lookup_node_by_id_staggered( &self, node_id: &PublicKey, origin: &str, delays_ms: &[u64], -) -> Result<NodeInfo, Error>

Looks up node info by NodeId and origin domain name.

+) -> Result<NodeInfo, StaggeredError<LookupError>>

Looks up node info by NodeId and origin domain name.

From the moment this function is called, each lookup is scheduled after the delays in delays_ms with the first call being done immediately. [200ms, 300ms] results in calls at T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a summary of all errors otherwise.

-

Trait Implementations§

Source§

impl Clone for DnsResolver

Source§

fn clone(&self) -> DnsResolver

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DnsResolver

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for DnsResolver

Source§

fn default() -> DnsResolver

Returns the “default value” for a type. Read more
Source§

impl From<Resolver<GenericConnector<TokioRuntimeProvider>>> for DnsResolver

Trait Implementations§

Source§

impl Clone for DnsResolver

Source§

fn clone(&self) -> DnsResolver

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DnsResolver

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for DnsResolver

Source§

fn default() -> DnsResolver

Returns the “default value” for a type. Read more
Source§

impl From<Resolver<GenericConnector<TokioRuntimeProvider>>> for DnsResolver

Source§

fn from( resolver: Resolver<GenericConnector<TokioRuntimeProvider>>, -) -> DnsResolver

Converts to this type from the input type.
Source§

impl Resolve for DnsResolver

Source§

fn resolve( +) -> DnsResolver

Converts to this type from the input type.
Source§

impl Resolve for DnsResolver

Source§

fn resolve( &self, name: Name, ) -> Pin<Box<dyn Future<Output = Result<Box<dyn Iterator<Item = SocketAddr> + Send>, Box<dyn Error + Send + Sync>>> + Send>>

Performs DNS resolution on a Name. diff --git a/pr/3327/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html b/pr/3327/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html index ac4c97186f..53813d6e41 100644 --- a/pr/3327/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html +++ b/pr/3327/docs/iroh/endpoint/constant.ENV_FORCE_STAGING_RELAYS.html @@ -1,2 +1,2 @@ -ENV_FORCE_STAGING_RELAYS in iroh::endpoint - Rust

Constant ENV_FORCE_STAGING_RELAYS

Source
pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS";
Expand description

Environment variable to force the use of staging relays.

+ENV_FORCE_STAGING_RELAYS in iroh::endpoint - Rust

Constant ENV_FORCE_STAGING_RELAYS

Source
pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS";
Expand description

Environment variable to force the use of staging relays.

\ No newline at end of file diff --git a/pr/3327/docs/iroh/endpoint/enum.AddNodeAddrError.html b/pr/3327/docs/iroh/endpoint/enum.AddNodeAddrError.html index 0b210851e6..5af9dd87d4 100644 --- a/pr/3327/docs/iroh/endpoint/enum.AddNodeAddrError.html +++ b/pr/3327/docs/iroh/endpoint/enum.AddNodeAddrError.html @@ -1,4 +1,4 @@ -AddNodeAddrError in iroh::endpoint - Rust

Enum AddNodeAddrError

Source
#[non_exhaustive]
pub enum AddNodeAddrError { +AddNodeAddrError in iroh::endpoint - Rust

Enum AddNodeAddrError

Source
#[non_exhaustive]
pub enum AddNodeAddrError { Empty { backtrace: Option<Backtrace>, span_trace: SpanTrace, @@ -12,11 +12,11 @@ backtrace: Option<Backtrace>, span_trace: SpanTrace, }, -}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Empty

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

EmptyPruned

Fields

§pruned: usize
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

OwnAddress

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for AddNodeAddrError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for AddNodeAddrError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for AddNodeAddrError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for AddNodeAddrError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Empty

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

EmptyPruned

Fields

§pruned: usize
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

OwnAddress

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for AddNodeAddrError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for AddNodeAddrError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for AddNodeAddrError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for AddNodeAddrError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<AddNodeAddrError> for ConnectWithOptsError

Source§

fn from(error: AddNodeAddrError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<AddNodeAddrError> for ConnectWithOptsError

Source§

fn from(error: AddNodeAddrError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3327/docs/iroh/endpoint/enum.AlpnError.html b/pr/3327/docs/iroh/endpoint/enum.AlpnError.html index a615509148..b0e0a97b3f 100644 --- a/pr/3327/docs/iroh/endpoint/enum.AlpnError.html +++ b/pr/3327/docs/iroh/endpoint/enum.AlpnError.html @@ -1,4 +1,4 @@ -AlpnError in iroh::endpoint - Rust

Enum AlpnError

Source
#[non_exhaustive]
pub enum AlpnError { +AlpnError in iroh::endpoint - Rust

Enum AlpnError

Source
#[non_exhaustive]
pub enum AlpnError { ConnectionError { source: ConnectionError, backtrace: Option<Backtrace>, @@ -12,11 +12,11 @@ backtrace: Option<Backtrace>, span_trace: SpanTrace, }, -}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

ConnectionError

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Unavailable

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

UnknownHandshake

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for AlpnError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for AlpnError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for AlpnError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for AlpnError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

ConnectionError

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Unavailable

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

UnknownHandshake

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for AlpnError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for AlpnError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for AlpnError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for AlpnError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<ConnectionError> for AlpnError

Source§

fn from(error: ConnectionError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<ConnectionError> for AlpnError

Source§

fn from(error: ConnectionError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3327/docs/iroh/endpoint/enum.BindError.html b/pr/3327/docs/iroh/endpoint/enum.BindError.html index eb0c2057a2..3dd45fcbef 100644 --- a/pr/3327/docs/iroh/endpoint/enum.BindError.html +++ b/pr/3327/docs/iroh/endpoint/enum.BindError.html @@ -1,4 +1,4 @@ -BindError in iroh::endpoint - Rust

Enum BindError

Source
#[non_exhaustive]
pub enum BindError { +BindError in iroh::endpoint - Rust

Enum BindError

Source
#[non_exhaustive]
pub enum BindError { MagicSpawn { source: CreateHandleError, backtrace: Option<Backtrace>, @@ -9,11 +9,11 @@ backtrace: Option<Backtrace>, span_trace: SpanTrace, }, -}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

MagicSpawn

Fields

§source: CreateHandleError
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Discovery

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for BindError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for BindError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for BindError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for BindError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

MagicSpawn

Fields

§source: CreateHandleError
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Discovery

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for BindError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for BindError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for BindError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for BindError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<IntoDiscoveryError> for BindError

Source§

fn from(error: IntoDiscoveryError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<IntoDiscoveryError> for BindError

Source§

fn from(error: IntoDiscoveryError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3327/docs/iroh/endpoint/enum.ConnectError.html b/pr/3327/docs/iroh/endpoint/enum.ConnectError.html index a3b11c9d3e..aabd197908 100644 --- a/pr/3327/docs/iroh/endpoint/enum.ConnectError.html +++ b/pr/3327/docs/iroh/endpoint/enum.ConnectError.html @@ -1,4 +1,4 @@ -ConnectError in iroh::endpoint - Rust

Enum ConnectError

Source
#[non_exhaustive]
pub enum ConnectError { +ConnectError in iroh::endpoint - Rust

Enum ConnectError

Source
#[non_exhaustive]
pub enum ConnectError { Connect { source: Box<ConnectWithOptsError>, backtrace: Option<Backtrace>, @@ -9,11 +9,11 @@ backtrace: Option<Backtrace>, span_trace: SpanTrace, }, -}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Connect

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Connection

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for ConnectError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for ConnectError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for ConnectError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for ConnectError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Connect

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Connection

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for ConnectError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for ConnectError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for ConnectError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for ConnectError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<ConnectWithOptsError> for ConnectError

Source§

fn from(error: ConnectWithOptsError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectError

Source§

fn from(error: ConnectionError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<ConnectWithOptsError> for ConnectError

Source§

fn from(error: ConnectWithOptsError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectError

Source§

fn from(error: ConnectionError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3327/docs/iroh/endpoint/enum.ConnectWithOptsError.html b/pr/3327/docs/iroh/endpoint/enum.ConnectWithOptsError.html index f374477b54..22e369eb62 100644 --- a/pr/3327/docs/iroh/endpoint/enum.ConnectWithOptsError.html +++ b/pr/3327/docs/iroh/endpoint/enum.ConnectWithOptsError.html @@ -1,4 +1,4 @@ -ConnectWithOptsError in iroh::endpoint - Rust

Enum ConnectWithOptsError

Source
#[non_exhaustive]
pub enum ConnectWithOptsError { +ConnectWithOptsError in iroh::endpoint - Rust

Enum ConnectWithOptsError

Source
#[non_exhaustive]
pub enum ConnectWithOptsError { AddNodeAddr { source: AddNodeAddrError, backtrace: Option<Backtrace>, @@ -18,11 +18,11 @@ backtrace: Option<Backtrace>, span_trace: SpanTrace, }, -}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

AddNodeAddr

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

SelfConnect

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

NoAddress

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Quinn

Fields

§source: ConnectError
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for ConnectWithOptsError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for ConnectWithOptsError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for ConnectWithOptsError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for ConnectWithOptsError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

AddNodeAddr

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

SelfConnect

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

NoAddress

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Quinn

Fields

§source: ConnectError
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for ConnectWithOptsError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for ConnectWithOptsError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for ConnectWithOptsError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for ConnectWithOptsError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<AddNodeAddrError> for ConnectWithOptsError

Source§

fn from(error: AddNodeAddrError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for ConnectError

Source§

fn from(error: ConnectWithOptsError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<AddNodeAddrError> for ConnectWithOptsError

Source§

fn from(error: AddNodeAddrError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectWithOptsError> for ConnectError

Source§

fn from(error: ConnectWithOptsError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3327/docs/iroh/endpoint/enum.ConnectionError.html b/pr/3327/docs/iroh/endpoint/enum.ConnectionError.html index b7aef0e02f..8f000da4e4 100644 --- a/pr/3327/docs/iroh/endpoint/enum.ConnectionError.html +++ b/pr/3327/docs/iroh/endpoint/enum.ConnectionError.html @@ -1,4 +1,4 @@ -ConnectionError in iroh::endpoint - Rust

Enum ConnectionError

pub enum ConnectionError {
+ConnectionError in iroh::endpoint - Rust

Enum ConnectionError

pub enum ConnectionError {
     VersionMismatch,
     TransportError(Error),
     ConnectionClosed(ConnectionClose),
@@ -20,7 +20,7 @@ and §

LocallyClosed

The local application closed the connection

§

CidsExhausted

The connection could not be created because not enough of the CID space is available

Try using longer connection IDs.

-

Trait Implementations§

§

impl Clone for ConnectionError

§

fn clone(&self) -> ConnectionError

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for ConnectionError

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Display for ConnectionError

§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Error for ConnectionError

§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
§

impl From<Close> for ConnectionError

§

fn from(x: Close) -> ConnectionError

Converts to this type from the input type.
Source§

impl From<ConnectionError> for AlpnError

Source§

fn from(error: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectError

Source§

fn from(error: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ProtocolError

Source§

fn from(error: ConnectionError) -> Self

Converts to this type from the input type.
§

impl From<ConnectionError> for ReadError

§

fn from(source: ConnectionError) -> ReadError

Converts to this type from the input type.
§

impl From<ConnectionError> for ResetError

§

fn from(source: ConnectionError) -> ResetError

Converts to this type from the input type.
§

impl From<ConnectionError> for SendDatagramError

§

fn from(source: ConnectionError) -> SendDatagramError

Converts to this type from the input type.
§

impl From<ConnectionError> for StoppedError

§

fn from(source: ConnectionError) -> StoppedError

Converts to this type from the input type.
§

impl From<ConnectionError> for WriteError

§

fn from(source: ConnectionError) -> WriteError

Converts to this type from the input type.
§

impl From<Error> for ConnectionError

§

fn from(source: Error) -> ConnectionError

Converts to this type from the input type.
§

impl PartialEq for ConnectionError

§

fn eq(&self, other: &ConnectionError) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +

Trait Implementations§

§

impl Clone for ConnectionError

§

fn clone(&self) -> ConnectionError

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for ConnectionError

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Display for ConnectionError

§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Error for ConnectionError

§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
§

impl From<Close> for ConnectionError

§

fn from(x: Close) -> ConnectionError

Converts to this type from the input type.
Source§

impl From<ConnectionError> for AcceptError

Source§

fn from(error: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for AlpnError

Source§

fn from(error: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ConnectError

Source§

fn from(error: ConnectionError) -> Self

Converts to this type from the input type.
§

impl From<ConnectionError> for ReadError

§

fn from(source: ConnectionError) -> ReadError

Converts to this type from the input type.
§

impl From<ConnectionError> for ResetError

§

fn from(source: ConnectionError) -> ResetError

Converts to this type from the input type.
§

impl From<ConnectionError> for SendDatagramError

§

fn from(source: ConnectionError) -> SendDatagramError

Converts to this type from the input type.
§

impl From<ConnectionError> for StoppedError

§

fn from(source: ConnectionError) -> StoppedError

Converts to this type from the input type.
§

impl From<ConnectionError> for WriteError

§

fn from(source: ConnectionError) -> WriteError

Converts to this type from the input type.
§

impl From<Error> for ConnectionError

§

fn from(source: Error) -> ConnectionError

Converts to this type from the input type.
§

impl PartialEq for ConnectionError

§

fn eq(&self, other: &ConnectionError) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl Eq for ConnectionError

§

impl StructuralPartialEq for ConnectionError

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method diff --git a/pr/3327/docs/iroh/endpoint/enum.ConnectionType.html b/pr/3327/docs/iroh/endpoint/enum.ConnectionType.html index 6a53e2f602..dc93653b7e 100644 --- a/pr/3327/docs/iroh/endpoint/enum.ConnectionType.html +++ b/pr/3327/docs/iroh/endpoint/enum.ConnectionType.html @@ -1,4 +1,4 @@ -ConnectionType in iroh::endpoint - Rust

Enum ConnectionType

Source
pub enum ConnectionType {
+ConnectionType in iroh::endpoint - Rust

Enum ConnectionType

Source
pub enum ConnectionType {
     Direct(SocketAddr),
     Relay(RelayUrl),
     Mixed(SocketAddr, RelayUrl),
@@ -10,10 +10,10 @@
 

This is the case if we do have a UDP address, but are missing a recent confirmation that the address works.

§

None

We have no verified connection to this PublicKey

-

Trait Implementations§

Source§

impl Clone for ConnectionType

Source§

fn clone(&self) -> ConnectionType

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ConnectionType

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ConnectionType

Source§

fn default() -> ConnectionType

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for ConnectionType

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where - __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for ConnectionType

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for ConnectionType

Source§

fn eq(&self, other: &ConnectionType) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl Serialize for ConnectionType

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where - __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for ConnectionType

Source§

impl StructuralPartialEq for ConnectionType

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for ConnectionType

Source§

fn clone(&self) -> ConnectionType

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ConnectionType

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ConnectionType

Source§

fn default() -> ConnectionType

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for ConnectionType

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where + __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for ConnectionType

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for ConnectionType

Source§

fn eq(&self, other: &ConnectionType) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl Serialize for ConnectionType

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where + __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for ConnectionType

Source§

impl StructuralPartialEq for ConnectionType

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/enum.ControlMsg.html b/pr/3327/docs/iroh/endpoint/enum.ControlMsg.html index 92b49c1873..bd0974fa8d 100644 --- a/pr/3327/docs/iroh/endpoint/enum.ControlMsg.html +++ b/pr/3327/docs/iroh/endpoint/enum.ControlMsg.html @@ -1,4 +1,4 @@ -ControlMsg in iroh::endpoint - Rust

Enum ControlMsg

Source
pub enum ControlMsg {
+ControlMsg in iroh::endpoint - Rust

Enum ControlMsg

Source
pub enum ControlMsg {
     Ping,
     Pong,
     CallMeMaybe,
@@ -6,10 +6,10 @@
 

Variants§

§

Ping

We received a Ping from the node.

§

Pong

We received a Pong from the node.

§

CallMeMaybe

We received a CallMeMaybe.

-

Trait Implementations§

Source§

impl Clone for ControlMsg

Source§

fn clone(&self) -> ControlMsg

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ControlMsg

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for ControlMsg

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where - __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for ControlMsg

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for ControlMsg

Source§

fn eq(&self, other: &ControlMsg) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl Serialize for ControlMsg

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where - __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Copy for ControlMsg

Source§

impl Eq for ControlMsg

Source§

impl StructuralPartialEq for ControlMsg

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for ControlMsg

Source§

fn clone(&self) -> ControlMsg

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ControlMsg

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for ControlMsg

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where + __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for ControlMsg

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for ControlMsg

Source§

fn eq(&self, other: &ControlMsg) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl Serialize for ControlMsg

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where + __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Copy for ControlMsg

Source§

impl Eq for ControlMsg

Source§

impl StructuralPartialEq for ControlMsg

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/enum.DirectAddrType.html b/pr/3327/docs/iroh/endpoint/enum.DirectAddrType.html index 472af1a0a7..28777f69c9 100644 --- a/pr/3327/docs/iroh/endpoint/enum.DirectAddrType.html +++ b/pr/3327/docs/iroh/endpoint/enum.DirectAddrType.html @@ -1,4 +1,4 @@ -DirectAddrType in iroh::endpoint - Rust

Enum DirectAddrType

Source
pub enum DirectAddrType {
+DirectAddrType in iroh::endpoint - Rust

Enum DirectAddrType

Source
pub enum DirectAddrType {
     Unknown,
     Local,
     Stun,
@@ -20,16 +20,16 @@ get a publicly routable direct address.

It is possible to configure iroh to bound to a specific port and independently configure the router to forward this port to the iroh node. This indicates a situation like this, which still uses STUN to discover the public address.

-

Trait Implementations§

Source§

impl Clone for DirectAddrType

Source§

fn clone(&self) -> DirectAddrType

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddrType

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for DirectAddrType

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Hash for DirectAddrType

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where +

Trait Implementations§

Source§

impl Clone for DirectAddrType

Source§

fn clone(&self) -> DirectAddrType

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddrType

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for DirectAddrType

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Hash for DirectAddrType

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, - Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DirectAddrType

Source§

fn cmp(&self, other: &DirectAddrType) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DirectAddrType

Source§

fn cmp(&self, other: &DirectAddrType) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where - Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DirectAddrType

Source§

fn eq(&self, other: &DirectAddrType) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl PartialOrd for DirectAddrType

Source§

fn partial_cmp(&self, other: &DirectAddrType) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the + Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DirectAddrType

Source§

fn eq(&self, other: &DirectAddrType) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl PartialOrd for DirectAddrType

Source§

fn partial_cmp(&self, other: &DirectAddrType) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by -the >= operator. Read more
Source§

impl Copy for DirectAddrType

Source§

impl Eq for DirectAddrType

Source§

impl StructuralPartialEq for DirectAddrType

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +the >= operator. Read more

Source§

impl Copy for DirectAddrType

Source§

impl Eq for DirectAddrType

Source§

impl StructuralPartialEq for DirectAddrType

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/enum.GetMappingAddressError.html b/pr/3327/docs/iroh/endpoint/enum.GetMappingAddressError.html index 270349eb79..0d075b6bdb 100644 --- a/pr/3327/docs/iroh/endpoint/enum.GetMappingAddressError.html +++ b/pr/3327/docs/iroh/endpoint/enum.GetMappingAddressError.html @@ -1,4 +1,4 @@ -GetMappingAddressError in iroh::endpoint - Rust

Enum GetMappingAddressError

Source
#[non_exhaustive]
pub enum GetMappingAddressError { +GetMappingAddressError in iroh::endpoint - Rust

Enum GetMappingAddressError

Source
#[non_exhaustive]
pub enum GetMappingAddressError { DiscoveryStart { source: DiscoveryError, backtrace: Option<Backtrace>, @@ -13,8 +13,8 @@ backtrace: Option<Backtrace>, span_trace: SpanTrace, }, -}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

DiscoveryStart

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Discover

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

NoAddress

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for GetMappingAddressError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for GetMappingAddressError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for GetMappingAddressError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for GetMappingAddressError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

DiscoveryStart

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Discover

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

NoAddress

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for GetMappingAddressError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for GetMappingAddressError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for GetMappingAddressError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for GetMappingAddressError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error and continuing with recursive calls to Error::source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where diff --git a/pr/3327/docs/iroh/endpoint/enum.PathSelection.html b/pr/3327/docs/iroh/endpoint/enum.PathSelection.html index 1fba094739..7c0c3102f5 100644 --- a/pr/3327/docs/iroh/endpoint/enum.PathSelection.html +++ b/pr/3327/docs/iroh/endpoint/enum.PathSelection.html @@ -1,12 +1,12 @@ -PathSelection in iroh::endpoint - Rust

Enum PathSelection

Source
pub enum PathSelection {
+PathSelection in iroh::endpoint - Rust

Enum PathSelection

Source
pub enum PathSelection {
     All,
     RelayOnly,
 }
Available on crate feature test-utils only.
Expand description

Defines the mode of path selection for all traffic flowing through the endpoint.

Variants§

§

All

Uses all available paths

§

RelayOnly

Forces all traffic to go exclusively through relays

-

Trait Implementations§

Source§

impl Clone for PathSelection

Source§

fn clone(&self) -> PathSelection

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PathSelection

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for PathSelection

Source§

fn default() -> PathSelection

Returns the “default value” for a type. Read more
Source§

impl PartialEq for PathSelection

Source§

fn eq(&self, other: &PathSelection) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl Copy for PathSelection

Source§

impl Eq for PathSelection

Source§

impl StructuralPartialEq for PathSelection

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for PathSelection

Source§

fn clone(&self) -> PathSelection

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for PathSelection

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for PathSelection

Source§

fn default() -> PathSelection

Returns the “default value” for a type. Read more
Source§

impl PartialEq for PathSelection

Source§

fn eq(&self, other: &PathSelection) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl Copy for PathSelection

Source§

impl Eq for PathSelection

Source§

impl StructuralPartialEq for PathSelection

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/enum.RelayMode.html b/pr/3327/docs/iroh/endpoint/enum.RelayMode.html index e63aeac9d5..e4ad1d3942 100644 --- a/pr/3327/docs/iroh/endpoint/enum.RelayMode.html +++ b/pr/3327/docs/iroh/endpoint/enum.RelayMode.html @@ -1,4 +1,4 @@ -RelayMode in iroh::endpoint - Rust

Enum RelayMode

Source
pub enum RelayMode {
+RelayMode in iroh::endpoint - Rust

Enum RelayMode

Source
pub enum RelayMode {
     Disabled,
     Default,
     Staging,
@@ -9,9 +9,9 @@
 

See crate::defaults::prod for the severs used.

§

Staging

Use the staging relay servers from n0.

§

Custom(RelayMap)

Use a custom relay map.

-

Implementations§

Source§

impl RelayMode

Source

pub fn relay_map(&self) -> RelayMap

Returns the relay map for this mode.

-

Trait Implementations§

Source§

impl Clone for RelayMode

Source§

fn clone(&self) -> RelayMode

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RelayMode

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for RelayMode

Source§

fn eq(&self, other: &RelayMode) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl Eq for RelayMode

Source§

impl StructuralPartialEq for RelayMode

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Implementations§

Source§

impl RelayMode

Source

pub fn relay_map(&self) -> RelayMap

Returns the relay map for this mode.

+

Trait Implementations§

Source§

impl Clone for RelayMode

Source§

fn clone(&self) -> RelayMode

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RelayMode

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for RelayMode

Source§

fn eq(&self, other: &RelayMode) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl Eq for RelayMode

Source§

impl StructuralPartialEq for RelayMode

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/enum.Source.html b/pr/3327/docs/iroh/endpoint/enum.Source.html index 09d493d145..1ce1674d34 100644 --- a/pr/3327/docs/iroh/endpoint/enum.Source.html +++ b/pr/3327/docs/iroh/endpoint/enum.Source.html @@ -1,4 +1,4 @@ -Source in iroh::endpoint - Rust

Enum Source

Source
pub enum Source {
+Source in iroh::endpoint - Rust

Enum Source

Source
pub enum Source {
     Saved,
     Udp,
     Relay,
@@ -30,12 +30,12 @@ discovered, such as a configured discovery service, the network itself
 

Fields

§name: String

The name of the discovery service that discovered the address.

§

NamedApp

Application layer with a specific name added the node directly.

Fields

§name: String

The name of the application that added the node

-

Trait Implementations§

Source§

impl Clone for Source

Source§

fn clone(&self) -> Source

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Source

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Source

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where - __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Source

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Hash for Source

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where +

Trait Implementations§

Source§

impl Clone for Source

Source§

fn clone(&self) -> Source

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Source

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Source

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where + __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Source

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Hash for Source

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, - Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Source

Source§

fn eq(&self, other: &Source) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl Serialize for Source

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where - __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for Source

Source§

impl StructuralPartialEq for Source

Auto Trait Implementations§

§

impl Freeze for Source

§

impl RefUnwindSafe for Source

§

impl Send for Source

§

impl Sync for Source

§

impl Unpin for Source

§

impl UnwindSafe for Source

Blanket Implementations§

Source§

impl<T> Any for T
where + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Source

Source§

fn eq(&self, other: &Source) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl Serialize for Source

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where + __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for Source

Source§

impl StructuralPartialEq for Source

Auto Trait Implementations§

§

impl Freeze for Source

§

impl RefUnwindSafe for Source

§

impl Send for Source

§

impl Sync for Source

§

impl Unpin for Source

§

impl UnwindSafe for Source

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/fn.default_relay_mode.html b/pr/3327/docs/iroh/endpoint/fn.default_relay_mode.html index 9876ad7608..9fb7d1bdea 100644 --- a/pr/3327/docs/iroh/endpoint/fn.default_relay_mode.html +++ b/pr/3327/docs/iroh/endpoint/fn.default_relay_mode.html @@ -1,4 +1,4 @@ -default_relay_mode in iroh::endpoint - Rust

Function default_relay_mode

Source
pub fn default_relay_mode() -> RelayMode
Expand description

Returns the default relay mode.

+default_relay_mode in iroh::endpoint - Rust

Function default_relay_mode

Source
pub fn default_relay_mode() -> RelayMode
Expand description

Returns the default relay mode.

If the IROH_FORCE_STAGING_RELAYS environment variable is non empty, it will return RelayMode::Staging. Otherwise, it will return RelayMode::Default.

\ No newline at end of file diff --git a/pr/3327/docs/iroh/endpoint/fn.force_staging_infra.html b/pr/3327/docs/iroh/endpoint/fn.force_staging_infra.html index 63b546cf5b..7c6f0878d5 100644 --- a/pr/3327/docs/iroh/endpoint/fn.force_staging_infra.html +++ b/pr/3327/docs/iroh/endpoint/fn.force_staging_infra.html @@ -1,2 +1,2 @@ -force_staging_infra in iroh::endpoint - Rust

Function force_staging_infra

Source
pub fn force_staging_infra() -> bool
Expand description

Returns true if the use of staging relays is forced.

+force_staging_infra in iroh::endpoint - Rust

Function force_staging_infra

Source
pub fn force_staging_infra() -> bool
Expand description

Returns true if the use of staging relays is forced.

\ No newline at end of file diff --git a/pr/3327/docs/iroh/endpoint/index.html b/pr/3327/docs/iroh/endpoint/index.html index fe055da2d1..c707558289 100644 --- a/pr/3327/docs/iroh/endpoint/index.html +++ b/pr/3327/docs/iroh/endpoint/index.html @@ -1,4 +1,4 @@ -iroh::endpoint - Rust

Module endpoint

Source
Expand description

The Endpoint allows establishing connections to other iroh nodes.

+iroh::endpoint - Rust

Module endpoint

Source
Expand description

The Endpoint allows establishing connections to other iroh nodes.

The Endpoint is the main API interface to manage a local iroh node. It allows connecting to and accepting connections from other nodes. See the module docs for more details on how iroh connections work.

@@ -10,4 +10,4 @@ more details on how iroh connections work.

Structs§

Accept
Future produced by Endpoint::accept.
AcceptBi
Future produced by [Connection::accept_bi]
AcceptUni
Future produced by [Connection::accept_uni]
AckFrequencyConfig
Parameters for controlling the peer’s acknowledgement frequency
ApplicationClose
Reason given by an application for closing the connection
Builder
Builder for Endpoint.
Chunk
A chunk of data from the receive stream
ClosedStream
Error indicating that a stream has not been opened or has already been finished or reset
ConnectOptions
Options for the Endpoint::connect_with_opts function.
Connecting
In-progress connection attempt future
Connection
A QUIC connection.
ConnectionClose
Reason given by the transport for closing the connection
ConnectionStats
Connection statistics
CryptoError
Generic crypto errors
DirectAddr
A direct address on which an iroh-node might be contactable.
DirectAddrInfo
Information about a direct address.
Endpoint
Controls an iroh node, establishing connections with other nodes.
ExportKeyingMaterialError
Error returned by [Session::export_keying_material].
FrameStats
Number of frames transmitted of each frame type
Incoming
An incoming connection for which the server has not yet begun its parts of the handshake.
IncomingFuture
Adaptor to let Incoming be awaited like a Connecting.
MtuDiscoveryConfig
Parameters governing MTU discovery.
OpenBi
Future produced by [Connection::open_bi]
OpenUni
Future produced by [Connection::open_uni]
PathStats
Statistics related to a transmission path
ReadDatagram
Future produced by [Connection::read_datagram]
RecvStream
A stream that can only be used to receive data
RemoteInfo
Details about a remote iroh node which is known to this node.
RemoteNodeIdError
RetryError
Error for attempting to retry an [Incoming] which already bears a token from a previous retry
SendStream
A stream that can only be used to send data
ServerConfig
Parameters governing incoming connections
StreamId
Identifier for a stream within a particular connection
TransportConfig
Parameters governing the core QUIC state machine
TransportError
Transport-level errors occur when a peer violates the protocol specification
TransportErrorCode
Transport-level error code
UdpStats
Statistics about UDP datagrams transmitted or received on a connection
UnsupportedVersion
Error indicating that the specified QUIC version is not supported
VarInt
An integer less than 2^62
WeakConnectionHandle
A handle to some connection internals, use with care.
Written
Indicates how many bytes and chunks had been transferred in a write operation
ZeroRttAccepted
Future that completes when a connection is fully established.

Enums§

AddNodeAddrError
AlpnError
BindError
ConnectError
ConnectWithOptsError
ConnectionError
Reasons why a connection might be lost
ConnectionType
The type of connection we have to the endpoint.
ControlMsg
The type of control message we have received.
DirectAddrType
The type of direct address.
GetMappingAddressError
PathSelectiontest-utils
Defines the mode of path selection for all traffic flowing through the endpoint.
ReadError
Errors that arise from reading from a stream.
ReadExactError
Errors that arise from reading from a stream.
ReadToEndError
Errors from RecvStream::read_to_end
RelayMode
Configuration of the relay servers for an Endpoint.
ResetError
Errors that arise while waiting for a stream to be reset
SendDatagramError
Errors that can arise when sending a datagram
Source
The origin or source through which an address associated with a remote node -was discovered.
StoppedError
Errors that arise while monitoring for a send stream stop from the peer
WriteError
Errors that arise from writing to a stream

Constants§

ENV_FORCE_STAGING_RELAYS
Environment variable to force the use of staging relays.

Traits§

AeadKey
A key for sealing data with AEAD-based algorithms
Controller
Common interface for different congestion controllers
ControllerFactory
Constructs controllers on demand
CryptoServerConfig
Server-side configuration for the crypto protocol
HandshakeTokenKey
A pseudo random key for HKDF

Functions§

default_relay_mode
Returns the default relay mode.
force_staging_infra
Returns true if the use of staging relays is forced.

Type Aliases§

NodeAddrWatcherNon-wasm_browser
A type alias for the return value of Endpoint::node_addr.
\ No newline at end of file +was discovered.
StoppedError
Errors that arise while monitoring for a send stream stop from the peer
WriteError
Errors that arise from writing to a stream

Constants§

ENV_FORCE_STAGING_RELAYS
Environment variable to force the use of staging relays.

Traits§

AeadKey
A key for sealing data with AEAD-based algorithms
Controller
Common interface for different congestion controllers
ControllerFactory
Constructs controllers on demand
CryptoServerConfig
Server-side configuration for the crypto protocol
HandshakeTokenKey
A pseudo random key for HKDF

Functions§

default_relay_mode
Returns the default relay mode.
force_staging_infra
Returns true if the use of staging relays is forced.
\ No newline at end of file diff --git a/pr/3327/docs/iroh/endpoint/sidebar-items.js b/pr/3327/docs/iroh/endpoint/sidebar-items.js index f19bc1e294..3f9dd865dd 100644 --- a/pr/3327/docs/iroh/endpoint/sidebar-items.js +++ b/pr/3327/docs/iroh/endpoint/sidebar-items.js @@ -1 +1 @@ -window.SIDEBAR_ITEMS = {"constant":["ENV_FORCE_STAGING_RELAYS"],"enum":["AddNodeAddrError","AlpnError","BindError","ConnectError","ConnectWithOptsError","ConnectionError","ConnectionType","ControlMsg","DirectAddrType","GetMappingAddressError","PathSelection","ReadError","ReadExactError","ReadToEndError","RelayMode","ResetError","SendDatagramError","Source","StoppedError","WriteError"],"fn":["default_relay_mode","force_staging_infra"],"struct":["Accept","AcceptBi","AcceptUni","AckFrequencyConfig","ApplicationClose","Builder","Chunk","ClosedStream","ConnectOptions","Connecting","Connection","ConnectionClose","ConnectionStats","CryptoError","DirectAddr","DirectAddrInfo","Endpoint","ExportKeyingMaterialError","FrameStats","Incoming","IncomingFuture","MtuDiscoveryConfig","OpenBi","OpenUni","PathStats","ReadDatagram","RecvStream","RemoteInfo","RemoteNodeIdError","RetryError","SendStream","ServerConfig","StreamId","TransportConfig","TransportError","TransportErrorCode","UdpStats","UnsupportedVersion","VarInt","WeakConnectionHandle","Written","ZeroRttAccepted"],"trait":["AeadKey","Controller","ControllerFactory","CryptoServerConfig","HandshakeTokenKey"],"type":["NodeAddrWatcher"]}; \ No newline at end of file +window.SIDEBAR_ITEMS = {"constant":["ENV_FORCE_STAGING_RELAYS"],"enum":["AddNodeAddrError","AlpnError","BindError","ConnectError","ConnectWithOptsError","ConnectionError","ConnectionType","ControlMsg","DirectAddrType","GetMappingAddressError","PathSelection","ReadError","ReadExactError","ReadToEndError","RelayMode","ResetError","SendDatagramError","Source","StoppedError","WriteError"],"fn":["default_relay_mode","force_staging_infra"],"struct":["Accept","AcceptBi","AcceptUni","AckFrequencyConfig","ApplicationClose","Builder","Chunk","ClosedStream","ConnectOptions","Connecting","Connection","ConnectionClose","ConnectionStats","CryptoError","DirectAddr","DirectAddrInfo","Endpoint","ExportKeyingMaterialError","FrameStats","Incoming","IncomingFuture","MtuDiscoveryConfig","OpenBi","OpenUni","PathStats","ReadDatagram","RecvStream","RemoteInfo","RemoteNodeIdError","RetryError","SendStream","ServerConfig","StreamId","TransportConfig","TransportError","TransportErrorCode","UdpStats","UnsupportedVersion","VarInt","WeakConnectionHandle","Written","ZeroRttAccepted"],"trait":["AeadKey","Controller","ControllerFactory","CryptoServerConfig","HandshakeTokenKey"]}; \ No newline at end of file diff --git a/pr/3327/docs/iroh/endpoint/struct.Accept.html b/pr/3327/docs/iroh/endpoint/struct.Accept.html index 781c879225..93beae76c8 100644 --- a/pr/3327/docs/iroh/endpoint/struct.Accept.html +++ b/pr/3327/docs/iroh/endpoint/struct.Accept.html @@ -1,6 +1,6 @@ -Accept in iroh::endpoint - Rust

Struct Accept

Source
pub struct Accept<'a> { /* private fields */ }
Expand description

Future produced by Endpoint::accept.

-

Trait Implementations§

Source§

impl<'a> Debug for Accept<'a>

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Future for Accept<'_>

Source§

type Output = Option<Incoming>

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering -the current task for wakeup if the value is not yet available. Read more
Source§

impl<'pin, 'a> Unpin for Accept<'a>
where +Accept in iroh::endpoint - Rust

Struct Accept

Source
pub struct Accept<'a> { /* private fields */ }
Expand description

Future produced by Endpoint::accept.

+

Trait Implementations§

Source§

impl<'a> Debug for Accept<'a>

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Future for Accept<'_>

Source§

type Output = Option<Incoming>

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more
Source§

impl<'pin, 'a> Unpin for Accept<'a>
where PinnedFieldsOf<__Accept<'pin, 'a>>: Unpin,

Auto Trait Implementations§

§

impl<'a> !Freeze for Accept<'a>

§

impl<'a> !RefUnwindSafe for Accept<'a>

§

impl<'a> Send for Accept<'a>

§

impl<'a> Sync for Accept<'a>

§

impl<'a> !UnwindSafe for Accept<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where diff --git a/pr/3327/docs/iroh/endpoint/struct.Builder.html b/pr/3327/docs/iroh/endpoint/struct.Builder.html index 5128ed238e..af5780f1a4 100644 --- a/pr/3327/docs/iroh/endpoint/struct.Builder.html +++ b/pr/3327/docs/iroh/endpoint/struct.Builder.html @@ -1,24 +1,24 @@ -Builder in iroh::endpoint - Rust

Struct Builder

Source
pub struct Builder { /* private fields */ }
Expand description

Builder for Endpoint.

+Builder in iroh::endpoint - Rust

Struct Builder

Source
pub struct Builder { /* private fields */ }
Expand description

Builder for Endpoint.

By default the endpoint will generate a new random SecretKey, which will result in a new NodeId.

To create the Endpoint call Builder::bind.

-

Implementations§

Source§

impl Builder

Source

pub async fn bind(self) -> Result<Endpoint, BindError>

Binds the magic endpoint.

-
Source

pub fn bind_addr_v4(self, addr: SocketAddrV4) -> Self

Sets the IPv4 bind address.

+

Implementations§

Source§

impl Builder

Source

pub async fn bind(self) -> Result<Endpoint, BindError>

Binds the magic endpoint.

+
Source

pub fn bind_addr_v4(self, addr: SocketAddrV4) -> Self

Sets the IPv4 bind address.

Setting the port to 0 will use a random port. If the port specified is already in use, it will fallback to choosing a random port.

By default will use 0.0.0.0:0 to bind to.

-
Source

pub fn bind_addr_v6(self, addr: SocketAddrV6) -> Self

Sets the IPv6 bind address.

+
Source

pub fn bind_addr_v6(self, addr: SocketAddrV6) -> Self

Sets the IPv6 bind address.

Setting the port to 0 will use a random port. If the port specified is already in use, it will fallback to choosing a random port.

By default will use [::]:0 to bind to.

-
Source

pub fn secret_key(self, secret_key: SecretKey) -> Self

Sets a secret key to authenticate with other peers.

+
Source

pub fn secret_key(self, secret_key: SecretKey) -> Self

Sets a secret key to authenticate with other peers.

This secret key’s public key will be the PublicKey of this endpoint and thus also its NodeId

If not set, a new secret key will be generated.

-
Source

pub fn alpns(self, alpn_protocols: Vec<Vec<u8>>) -> Self

Sets the ALPN protocols that this endpoint will accept on incoming connections.

+
Source

pub fn alpns(self, alpn_protocols: Vec<Vec<u8>>) -> Self

Sets the ALPN protocols that this endpoint will accept on incoming connections.

Not setting this will still allow creating connections, but to accept incoming connections at least one ALPN must be set.

-
Source

pub fn relay_mode(self, relay_mode: RelayMode) -> Self

Sets the relay servers to assist in establishing connectivity.

+
Source

pub fn relay_mode(self, relay_mode: RelayMode) -> Self

Sets the relay servers to assist in establishing connectivity.

Relay servers are used to establish initial connection with another iroh node. They also perform various functions related to hole punching, see the crate docs for more details.

@@ -26,20 +26,20 @@ for more details.

When using RelayMode::Custom, the provided relay_map must contain at least one configured relay node. If an invalid RelayMap is provided bind will result in an error.

-
Source

pub fn relay_conn_protocol(self, protocol: RelayProtocol) -> Self

Sets the protocol to use for relay connections.

+
Source

pub fn relay_conn_protocol(self, protocol: RelayProtocol) -> Self

Sets the protocol to use for relay connections.

Options are either RelayProtocol::Websocket or RelayProtocol::Relay.

Websocket is considered unstable between iroh versions at the moment. The protocol can change in compatibility-breaking ways before iroh 1.0.

Default is set to Relay at the moment, until we’ve stabilized the websocket protocol.

-
Source

pub fn clear_discovery(self) -> Self

Removes all discovery services from the builder.

-
Source

pub fn discovery(self, discovery: impl IntoDiscovery) -> Self

Optionally sets a discovery mechanism for this endpoint.

+
Source

pub fn clear_discovery(self) -> Self

Removes all discovery services from the builder.

+
Source

pub fn discovery(self, discovery: impl IntoDiscovery) -> Self

Optionally sets a discovery mechanism for this endpoint.

If you want to combine multiple discovery services, you can use Builder::add_discovery instead. This will internally create a crate::discovery::ConcurrentDiscovery.

If no discovery service is set, connecting to a node without providing its direct addresses or relay URLs will fail.

See the documentation of the Discovery trait for details.

-
Source

pub fn add_discovery(self, discovery: impl IntoDiscovery) -> Self

Adds a discovery mechanism for this endpoint.

+
Source

pub fn add_discovery(self, discovery: impl IntoDiscovery) -> Self

Adds a discovery mechanism for this endpoint.

The function discovery will be called on endpoint creation with the configured secret key of the endpoint. Discovery services that need to publish information need @@ -50,7 +50,7 @@ to use this secret key to sign the information.

direct addresses or relay URLs will fail.

To clear all discovery services, use Builder::clear_discovery.

See the documentation of the Discovery trait for details.

-
Source

pub fn discovery_n0(self) -> Self

Configures the endpoint to use the default n0 DNS discovery service.

+
Source

pub fn discovery_n0(self) -> Self

Configures the endpoint to use the default n0 DNS discovery service.

The default discovery service publishes to and resolves from the n0.computer dns server iroh.link.

This is equivalent to adding both a crate::discovery::pkarr::PkarrPublisher @@ -59,24 +59,24 @@ n0.computer dns server.

This will by default use N0_DNS_PKARR_RELAY_PROD. When in tests, or when the test-utils feature is enabled, this will use the N0_DNS_PKARR_RELAY_STAGING.

-
Source

pub fn discovery_dht(self) -> Self

Available on crate feature discovery-pkarr-dht only.

Configures the endpoint to also use the mainline DHT with default settings.

+
Source

pub fn discovery_dht(self) -> Self

Available on crate feature discovery-pkarr-dht only.

Configures the endpoint to also use the mainline DHT with default settings.

This is equivalent to adding a crate::discovery::pkarr::dht::DhtDiscovery with default settings. Note that DhtDiscovery has various more advanced configuration options. If you need any of those, you should manually create a DhtDiscovery and add it with Builder::add_discovery.

-
Source

pub fn discovery_local_network(self) -> Self

Available on crate feature discovery-local-network only.

Configures the endpoint to also use local network discovery.

+
Source

pub fn discovery_local_network(self) -> Self

Available on crate feature discovery-local-network only.

Configures the endpoint to also use local network discovery.

This is equivalent to adding a crate::discovery::mdns::MdnsDiscovery with default settings. Note that MdnsDiscovery has various more advanced configuration options. If you need any of those, you should manually create a MdnsDiscovery and add it with Builder::add_discovery.

-
Source

pub fn user_data_for_discovery(self, user_data: UserData) -> Self

Sets the initial user-defined data to be published in discovery services for this node.

+
Source

pub fn user_data_for_discovery(self, user_data: UserData) -> Self

Sets the initial user-defined data to be published in discovery services for this node.

When using discovery services, this string of UserData will be published together with the node’s addresses and relay URL. When other nodes discover this node, they retrieve the UserData in addition to the addressing info.

Iroh itself does not interpret the user-defined data in any way, it is purely left for applications to parse and use.

-
Source

pub fn known_nodes(self, nodes: Vec<NodeAddr>) -> Self

Optionally set a list of known nodes.

-
Source

pub fn transport_config(self, transport_config: TransportConfig) -> Self

Sets a custom quinn::TransportConfig for this endpoint.

+
Source

pub fn known_nodes(self, nodes: Vec<NodeAddr>) -> Self

Optionally set a list of known nodes.

+
Source

pub fn transport_config(self, transport_config: TransportConfig) -> Self

Sets a custom quinn::TransportConfig for this endpoint.

The transport config contains parameters governing the QUIC state machine.

If unset, the default config is used. Default values should be suitable for most internet applications. Applications protocols which forbid remotely-initiated @@ -84,31 +84,31 @@ streams should set max_concurrent_bidi_streams and max_concur zero.

Please be aware that changing some settings may have adverse effects on establishing and maintaining direct connections.

-
Source

pub fn dns_resolver(self, dns_resolver: DnsResolver) -> Self

Available on non-wasm_browser only.

Optionally sets a custom DNS resolver to use for this endpoint.

+
Source

pub fn dns_resolver(self, dns_resolver: DnsResolver) -> Self

Available on non-wasm_browser only.

Optionally sets a custom DNS resolver to use for this endpoint.

The DNS resolver is used to resolve relay hostnames, and node addresses if crate::discovery::dns::DnsDiscovery is configured.

By default, a new DNS resolver is created which is configured to use the host system’s DNS configuration. You can pass a custom instance of DnsResolver here to use a differently configured DNS resolver for this endpoint, or to share a DnsResolver between multiple endpoints.

-
Source

pub fn proxy_url(self, url: Url) -> Self

Sets an explicit proxy url to proxy all HTTP(S) traffic through.

-
Source

pub fn proxy_from_env(self) -> Self

Sets the proxy url from the environment, in this order:

+
Source

pub fn proxy_url(self, url: Url) -> Self

Sets an explicit proxy url to proxy all HTTP(S) traffic through.

+
Source

pub fn proxy_from_env(self) -> Self

Sets the proxy url from the environment, in this order:

  • HTTP_PROXY
  • http_proxy
  • HTTPS_PROXY
  • https_proxy
-
Source

pub fn keylog(self, keylog: bool) -> Self

Enables saving the TLS pre-master key for connections.

+
Source

pub fn keylog(self, keylog: bool) -> Self

Enables saving the TLS pre-master key for connections.

This key should normally remain secret but can be useful to debug networking issues by decrypting captured traffic.

If keylog is true then setting the SSLKEYLOGFILE environment variable to a filename will result in this file being used to log the TLS pre-master keys.

-
Source

pub fn insecure_skip_relay_cert_verify(self, skip_verify: bool) -> Self

Available on crate feature test-utils only.

Skip verification of SSL certificates from relay servers

+
Source

pub fn insecure_skip_relay_cert_verify(self, skip_verify: bool) -> Self

Available on crate feature test-utils only.

Skip verification of SSL certificates from relay servers

May only be used in tests.

-
Source

pub fn path_selection(self, path_selection: PathSelection) -> Self

Available on crate feature test-utils only.

This implies we only use the relay to communicate +

Source

pub fn path_selection(self, path_selection: PathSelection) -> Self

Available on crate feature test-utils only.

This implies we only use the relay to communicate and do not attempt to do any hole punching.

-

Trait Implementations§

Source§

impl Debug for Builder

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Builder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Debug for Builder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Builder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/struct.ClosedStream.html b/pr/3327/docs/iroh/endpoint/struct.ClosedStream.html index 6f08f9dc28..3698eb4ca8 100644 --- a/pr/3327/docs/iroh/endpoint/struct.ClosedStream.html +++ b/pr/3327/docs/iroh/endpoint/struct.ClosedStream.html @@ -1,5 +1,5 @@ -ClosedStream in iroh::endpoint - Rust

Struct ClosedStream

pub struct ClosedStream { /* private fields */ }
Expand description

Error indicating that a stream has not been opened or has already been finished or reset

-

Trait Implementations§

§

impl Clone for ClosedStream

§

fn clone(&self) -> ClosedStream

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for ClosedStream

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Default for ClosedStream

§

fn default() -> ClosedStream

Returns the “default value” for a type. Read more
§

impl Display for ClosedStream

§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Error for ClosedStream

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<ClosedStream> for ProtocolError

Source§

fn from(err: ClosedStream) -> Self

Converts to this type from the input type.
§

impl From<ClosedStream> for WriteError

§

fn from(_: ClosedStream) -> WriteError

Converts to this type from the input type.
§

impl PartialEq for ClosedStream

§

fn eq(&self, other: &ClosedStream) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +ClosedStream in iroh::endpoint - Rust

Struct ClosedStream

pub struct ClosedStream { /* private fields */ }
Expand description

Error indicating that a stream has not been opened or has already been finished or reset

+

Trait Implementations§

§

impl Clone for ClosedStream

§

fn clone(&self) -> ClosedStream

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
§

impl Debug for ClosedStream

§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Default for ClosedStream

§

fn default() -> ClosedStream

Returns the “default value” for a type. Read more
§

impl Display for ClosedStream

§

fn fmt(&self, __formatter: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
§

impl Error for ClosedStream

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<ClosedStream> for AcceptError

Source§

fn from(err: ClosedStream) -> Self

Converts to this type from the input type.
§

impl From<ClosedStream> for WriteError

§

fn from(_: ClosedStream) -> WriteError

Converts to this type from the input type.
§

impl PartialEq for ClosedStream

§

fn eq(&self, other: &ClosedStream) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl Eq for ClosedStream

§

impl StructuralPartialEq for ClosedStream

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method diff --git a/pr/3327/docs/iroh/endpoint/struct.ConnectOptions.html b/pr/3327/docs/iroh/endpoint/struct.ConnectOptions.html index 72a932c629..14ad62b0f3 100644 --- a/pr/3327/docs/iroh/endpoint/struct.ConnectOptions.html +++ b/pr/3327/docs/iroh/endpoint/struct.ConnectOptions.html @@ -1,12 +1,12 @@ -ConnectOptions in iroh::endpoint - Rust

Struct ConnectOptions

Source
pub struct ConnectOptions { /* private fields */ }
Expand description

Options for the Endpoint::connect_with_opts function.

-

Implementations§

Source§

impl ConnectOptions

Source

pub fn new() -> Self

Initializes new connection options.

+ConnectOptions in iroh::endpoint - Rust

Struct ConnectOptions

Source
pub struct ConnectOptions { /* private fields */ }
Expand description

Options for the Endpoint::connect_with_opts function.

+

Implementations§

Source§

impl ConnectOptions

Source

pub fn new() -> Self

Initializes new connection options.

By default, the connection will use the same options as Endpoint::connect, e.g. a default TransportConfig.

-
Source

pub fn with_transport_config( +

Source

pub fn with_transport_config( self, transport_config: Arc<TransportConfig>, ) -> Self

Sets the QUIC transport config options for this connection.

-
Source

pub fn with_additional_alpns(self, alpns: Vec<Vec<u8>>) -> Self

Sets ALPN identifiers that should be signaled as supported on connection, in +

Source

pub fn with_additional_alpns(self, alpns: Vec<Vec<u8>>) -> Self

Sets ALPN identifiers that should be signaled as supported on connection, in addition to the main ALPN identifier used in Endpoint::connect_with_opts.

This allows connecting to servers that may only support older versions of your protocol. In this case, you would add the older ALPN identifiers with this @@ -20,7 +20,7 @@ list or the main ALPN identifiers on the accept side, see the endpoint builder’s Builder::alpns function.

-

Trait Implementations§

Source§

impl Clone for ConnectOptions

Source§

fn clone(&self) -> ConnectOptions

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ConnectOptions

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ConnectOptions

Source§

fn default() -> ConnectOptions

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for ConnectOptions

Source§

fn clone(&self) -> ConnectOptions

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ConnectOptions

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ConnectOptions

Source§

fn default() -> ConnectOptions

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/struct.Connecting.html b/pr/3327/docs/iroh/endpoint/struct.Connecting.html index 55024b1259..1c3ab8c7a3 100644 --- a/pr/3327/docs/iroh/endpoint/struct.Connecting.html +++ b/pr/3327/docs/iroh/endpoint/struct.Connecting.html @@ -1,5 +1,5 @@ -Connecting in iroh::endpoint - Rust

Struct Connecting

Source
pub struct Connecting { /* private fields */ }
Expand description

In-progress connection attempt future

-

Implementations§

Source§

impl Connecting

Source

pub fn into_0rtt(self) -> Result<(Connection, ZeroRttAccepted), Self>

Converts this Connecting into a 0-RTT or 0.5-RTT connection at the cost of weakened +Connecting in iroh::endpoint - Rust

Struct Connecting

Source
pub struct Connecting { /* private fields */ }
Expand description

In-progress connection attempt future

+

Implementations§

Source§

impl Connecting

Source

pub fn into_0rtt(self) -> Result<(Connection, ZeroRttAccepted), Self>

Converts this Connecting into a 0-RTT or 0.5-RTT connection at the cost of weakened security.

Returns Ok immediately if the local endpoint is able to attempt sending 0/0.5-RTT data. If so, the returned Connection can be used to send application data without waiting for @@ -33,10 +33,10 @@ before TLS client authentication has occurred, and should therefore not be used data for which client authentication is being used.

You can use RecvStream::is_0rtt to check whether a stream has been opened in 0-RTT and thus whether parts of the stream are operating under this reduced security level.

-
Source

pub async fn handshake_data(&mut self) -> Result<Box<dyn Any>, ConnectionError>

Parameters negotiated during the handshake

-
Source

pub async fn alpn(&mut self) -> Result<Vec<u8>, AlpnError>

Extracts the ALPN protocol from the peer’s handshake data.

-

Trait Implementations§

Source§

impl Debug for Connecting

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Future for Connecting

Source§

type Output = Result<Connection, ConnectionError>

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering -the current task for wakeup if the value is not yet available. Read more
Source§

impl<'pin> Unpin for Connecting
where +

Source

pub async fn handshake_data(&mut self) -> Result<Box<dyn Any>, ConnectionError>

Parameters negotiated during the handshake

+
Source

pub async fn alpn(&mut self) -> Result<Vec<u8>, AlpnError>

Extracts the ALPN protocol from the peer’s handshake data.

+

Trait Implementations§

Source§

impl Debug for Connecting

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Future for Connecting

Source§

type Output = Result<Connection, ConnectionError>

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more
Source§

impl<'pin> Unpin for Connecting
where PinnedFieldsOf<__Connecting<'pin>>: Unpin,

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where diff --git a/pr/3327/docs/iroh/endpoint/struct.Connection.html b/pr/3327/docs/iroh/endpoint/struct.Connection.html index f361b494fc..7514eb2f13 100644 --- a/pr/3327/docs/iroh/endpoint/struct.Connection.html +++ b/pr/3327/docs/iroh/endpoint/struct.Connection.html @@ -1,4 +1,4 @@ -Connection in iroh::endpoint - Rust

Struct Connection

Source
pub struct Connection { /* private fields */ }
Expand description

A QUIC connection.

+Connection in iroh::endpoint - Rust

Struct Connection

Source
pub struct Connection { /* private fields */ }
Expand description

A QUIC connection.

If all references to a connection (including every clone of the Connection handle, streams of incoming streams, and the various stream types) have been dropped, then the connection will be automatically closed with an error_code of 0 and an empty reason. You @@ -8,29 +8,29 @@ receiving CONNECTION_CLOSE the peer may drop any stream data not yet delivered t application. Connection::close describes in more detail how to gracefully close a connection without losing application data.

May be cloned to obtain another handle to the same connection.

-

Implementations§

Source§

impl Connection

Source

pub fn open_uni(&self) -> OpenUni<'_> ⓘ

Initiates a new outgoing unidirectional stream.

+

Implementations§

Source§

impl Connection

Source

pub fn open_uni(&self) -> OpenUni<'_> ⓘ

Initiates a new outgoing unidirectional stream.

Streams are cheap and instantaneous to open unless blocked by flow control. As a consequence, the peer won’t be notified that a stream has been opened until the stream is actually used.

-
Source

pub fn open_bi(&self) -> OpenBi<'_> ⓘ

Initiates a new outgoing bidirectional stream.

+
Source

pub fn open_bi(&self) -> OpenBi<'_> ⓘ

Initiates a new outgoing bidirectional stream.

Streams are cheap and instantaneous to open unless blocked by flow control. As a consequence, the peer won’t be notified that a stream has been opened until the stream is actually used. Calling open_bi then waiting on the RecvStream without writing anything to SendStream will never succeed.

-
Source

pub fn accept_uni(&self) -> AcceptUni<'_> ⓘ

Accepts the next incoming uni-directional stream.

-
Source

pub fn accept_bi(&self) -> AcceptBi<'_> ⓘ

Accept the next incoming bidirectional stream.

+
Source

pub fn accept_uni(&self) -> AcceptUni<'_> ⓘ

Accepts the next incoming uni-directional stream.

+
Source

pub fn accept_bi(&self) -> AcceptBi<'_> ⓘ

Accept the next incoming bidirectional stream.

Important Note: The peer that calls open_bi must write to its SendStream before the peer Connection is able to accept the stream using accept_bi(). Calling open_bi then waiting on the RecvStream without writing anything to the connected SendStream will never succeed.

-
Source

pub fn read_datagram(&self) -> ReadDatagram<'_> ⓘ

Receives an application datagram.

-
Source

pub async fn closed(&self) -> ConnectionError

Wait for the connection to be closed for any reason.

+
Source

pub fn read_datagram(&self) -> ReadDatagram<'_> ⓘ

Receives an application datagram.

+
Source

pub async fn closed(&self) -> ConnectionError

Wait for the connection to be closed for any reason.

Despite the return type’s name, closed connections are often not an error condition at the application layer. Cases that might be routine include ConnectionError::LocallyClosed and ConnectionError::ApplicationClosed.

-
Source

pub fn close_reason(&self) -> Option<ConnectionError>

If the connection is closed, the reason why.

+
Source

pub fn close_reason(&self) -> Option<ConnectionError>

If the connection is closed, the reason why.

Returns None if the connection is still open.

-
Source

pub fn close(&self, error_code: VarInt, reason: &[u8])

Closes the connection immediately.

+
Source

pub fn close(&self, error_code: VarInt, reason: &[u8])

Closes the connection immediately.

Pending operations will fail immediately with ConnectionError::LocallyClosed. No more data is sent to the peer and the peer may drop buffered data upon receiving the CONNECTION_CLOSE frame.

@@ -51,41 +51,41 @@ endpoint. Once the local side sends a CONNECTION_CLOSE frame in response to call close the remote endpoint may drop any data it received but is as yet undelivered to the application, including data that was acknowledged as received to the local endpoint.

-
Source

pub fn send_datagram(&self, data: Bytes) -> Result<(), SendDatagramError>

Transmits data as an unreliable, unordered application datagram.

+
Source

pub fn send_datagram(&self, data: Bytes) -> Result<(), SendDatagramError>

Transmits data as an unreliable, unordered application datagram.

Application datagrams are a low-level primitive. They may be lost or delivered out of order, and data must both fit inside a single QUIC packet and be smaller than the maximum dictated by the peer.

-
Source

pub fn max_datagram_size(&self) -> Option<usize>

Computes the maximum size of datagrams that may be passed to send_datagram.

+
Source

pub fn max_datagram_size(&self) -> Option<usize>

Computes the maximum size of datagrams that may be passed to send_datagram.

Returns None if datagrams are unsupported by the peer or disabled locally.

This may change over the lifetime of a connection according to variation in the path MTU estimate. The peer can also enforce an arbitrarily small fixed limit, but if the peer’s limit is large this is guaranteed to be a little over a kilobyte at minimum.

Not necessarily the maximum size of received datagrams.

-
Source

pub fn datagram_send_buffer_space(&self) -> usize

Bytes available in the outgoing datagram buffer.

+
Source

pub fn datagram_send_buffer_space(&self) -> usize

Bytes available in the outgoing datagram buffer.

When greater than zero, calling send_datagram with a datagram of at most this size is guaranteed not to cause older datagrams to be dropped.

-
Source

pub fn rtt(&self) -> Duration

Current best estimate of this connection’s latency (round-trip-time).

-
Source

pub fn stats(&self) -> ConnectionStats

Returns connection statistics.

-
Source

pub fn congestion_state(&self) -> Box<dyn Controller>

Current state of the congestion control algorithm, for debugging purposes.

-
Source

pub fn handshake_data(&self) -> Option<Box<dyn Any>>

Parameters negotiated during the handshake.

+
Source

pub fn rtt(&self) -> Duration

Current best estimate of this connection’s latency (round-trip-time).

+
Source

pub fn stats(&self) -> ConnectionStats

Returns connection statistics.

+
Source

pub fn congestion_state(&self) -> Box<dyn Controller>

Current state of the congestion control algorithm, for debugging purposes.

+
Source

pub fn handshake_data(&self) -> Option<Box<dyn Any>>

Parameters negotiated during the handshake.

Guaranteed to return Some on fully established connections or after Connecting::handshake_data() succeeds. See that method’s documentations for details on the returned value.

-
Source

pub fn alpn(&self) -> Option<Vec<u8>>

Extracts the ALPN protocol from the peer’s handshake data.

-
Source

pub fn peer_identity(&self) -> Option<Box<dyn Any>>

Cryptographic identity of the peer.

+
Source

pub fn alpn(&self) -> Option<Vec<u8>>

Extracts the ALPN protocol from the peer’s handshake data.

+
Source

pub fn peer_identity(&self) -> Option<Box<dyn Any>>

Cryptographic identity of the peer.

The dynamic type returned is determined by the configured Session. For the default rustls session, the return value can be downcast to a Vec<[rustls::pki_types::CertificateDer]>

-
Source

pub fn remote_node_id(&self) -> Result<NodeId, RemoteNodeIdError>

Returns the NodeId from the peer’s TLS certificate.

+
Source

pub fn remote_node_id(&self) -> Result<NodeId, RemoteNodeIdError>

Returns the NodeId from the peer’s TLS certificate.

The PublicKey of a node is also known as a NodeId. This PublicKey is included in the TLS certificate presented during the handshake when connecting. This function allows you to get the NodeId of the remote node of this connection.

-
Source

pub fn stable_id(&self) -> usize

A stable identifier for this connection.

+
Source

pub fn stable_id(&self) -> usize

A stable identifier for this connection.

Peer addresses and connection IDs can change, but this value will remain fixed for the lifetime of the connection.

-
Source

pub fn export_keying_material( +

Source

pub fn export_keying_material( &self, output: &mut [u8], label: &[u8], @@ -96,14 +96,14 @@ arguments and output buffers of equal length, they will get the same sequence of bytes in output. These bytes are cryptographically strong and pseudorandom, and are suitable for use as keying material.

See RFC5705 for more information.

-

Source

pub fn set_max_concurrent_uni_streams(&self, count: VarInt)

Modifies the number of unidirectional streams that may be concurrently opened.

+
Source

pub fn set_max_concurrent_uni_streams(&self, count: VarInt)

Modifies the number of unidirectional streams that may be concurrently opened.

No streams may be opened by the peer unless fewer than count are already open. Large counts increase both minimum and worst-case memory consumption.

-
Source

pub fn set_receive_window(&self, receive_window: VarInt)

Source

pub fn set_max_concurrent_bi_streams(&self, count: VarInt)

Modifies the number of bidirectional streams that may be concurrently opened.

+
Source

pub fn set_receive_window(&self, receive_window: VarInt)

Source

pub fn set_max_concurrent_bi_streams(&self, count: VarInt)

Modifies the number of bidirectional streams that may be concurrently opened.

No streams may be opened by the peer unless fewer than count are already open. Large counts increase both minimum and worst-case memory consumption.

-

Trait Implementations§

Source§

impl Clone for Connection

Source§

fn clone(&self) -> Connection

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Connection

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for Connection

Source§

fn clone(&self) -> Connection

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Connection

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/struct.DirectAddr.html b/pr/3327/docs/iroh/endpoint/struct.DirectAddr.html index 733b3f6522..4e674ff25c 100644 --- a/pr/3327/docs/iroh/endpoint/struct.DirectAddr.html +++ b/pr/3327/docs/iroh/endpoint/struct.DirectAddr.html @@ -1,4 +1,4 @@ -DirectAddr in iroh::endpoint - Rust

Struct DirectAddr

Source
pub struct DirectAddr {
+DirectAddr in iroh::endpoint - Rust

Struct DirectAddr

Source
pub struct DirectAddr {
     pub addr: SocketAddr,
     pub typ: DirectAddrType,
 }
Expand description

A direct address on which an iroh-node might be contactable.

@@ -7,16 +7,16 @@ contacted. These can come from various sources depending on the network topolog iroh node, see DirectAddrType for the several kinds of sources.

Fields§

§addr: SocketAddr

The address.

§typ: DirectAddrType

The origin of this direct address.

-

Trait Implementations§

Source§

impl Clone for DirectAddr

Source§

fn clone(&self) -> DirectAddr

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddr

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Hash for DirectAddr

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where +

Trait Implementations§

Source§

impl Clone for DirectAddr

Source§

fn clone(&self) -> DirectAddr

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddr

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Hash for DirectAddr

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, - Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DirectAddr

Source§

fn cmp(&self, other: &DirectAddr) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DirectAddr

Source§

fn cmp(&self, other: &DirectAddr) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where - Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DirectAddr

Source§

fn eq(&self, other: &DirectAddr) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl PartialOrd for DirectAddr

Source§

fn partial_cmp(&self, other: &DirectAddr) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the + Self: Sized,

Restrict a value to a certain interval. Read more

Source§

impl PartialEq for DirectAddr

Source§

fn eq(&self, other: &DirectAddr) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl PartialOrd for DirectAddr

Source§

fn partial_cmp(&self, other: &DirectAddr) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by -the >= operator. Read more
Source§

impl Eq for DirectAddr

Source§

impl StructuralPartialEq for DirectAddr

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +the >= operator. Read more

Source§

impl Eq for DirectAddr

Source§

impl StructuralPartialEq for DirectAddr

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/struct.DirectAddrInfo.html b/pr/3327/docs/iroh/endpoint/struct.DirectAddrInfo.html index 31edb96875..33fbba9a1f 100644 --- a/pr/3327/docs/iroh/endpoint/struct.DirectAddrInfo.html +++ b/pr/3327/docs/iroh/endpoint/struct.DirectAddrInfo.html @@ -1,4 +1,4 @@ -DirectAddrInfo in iroh::endpoint - Rust

Struct DirectAddrInfo

Source
pub struct DirectAddrInfo {
+DirectAddrInfo in iroh::endpoint - Rust

Struct DirectAddrInfo

Source
pub struct DirectAddrInfo {
     pub addr: SocketAddr,
     pub latency: Option<Duration>,
     pub last_control: Option<(Duration, ControlMsg)>,
@@ -36,10 +36,10 @@ node discovery the path may never have been known to exist.

recorded this address.

The Duration will always indicate the most recent time the source recorded this address.

-

Trait Implementations§

Source§

impl Clone for DirectAddrInfo

Source§

fn clone(&self) -> DirectAddrInfo

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddrInfo

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for DirectAddrInfo

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where - __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for DirectAddrInfo

Source§

fn eq(&self, other: &DirectAddrInfo) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl Serialize for DirectAddrInfo

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where - __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for DirectAddrInfo

Source§

impl StructuralPartialEq for DirectAddrInfo

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for DirectAddrInfo

Source§

fn clone(&self) -> DirectAddrInfo

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DirectAddrInfo

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for DirectAddrInfo

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where + __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for DirectAddrInfo

Source§

fn eq(&self, other: &DirectAddrInfo) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl Serialize for DirectAddrInfo

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where + __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for DirectAddrInfo

Source§

impl StructuralPartialEq for DirectAddrInfo

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/struct.Endpoint.html b/pr/3327/docs/iroh/endpoint/struct.Endpoint.html index 4c1c6d1fd1..d562570673 100644 --- a/pr/3327/docs/iroh/endpoint/struct.Endpoint.html +++ b/pr/3327/docs/iroh/endpoint/struct.Endpoint.html @@ -1,4 +1,4 @@ -Endpoint in iroh::endpoint - Rust

Struct Endpoint

Source
pub struct Endpoint { /* private fields */ }
Expand description

Controls an iroh node, establishing connections with other nodes.

+Endpoint in iroh::endpoint - Rust

Struct Endpoint

Source
pub struct Endpoint { /* private fields */ }
Expand description

Controls an iroh node, establishing connections with other nodes.

This is the main API interface to create connections to, and accept connections from other iroh nodes. The connections are peer-to-peer and encrypted, a Relay server is used to make the connections reliable. See the [crate docs] for a more detailed @@ -16,11 +16,11 @@ the peer are created using the Connection::open_uni and Connection::open_bi functions.

Note that due to the light-weight properties of streams a stream will only be accepted once the initiating peer has sent some data on it.

-

Implementations§

Source§

impl Endpoint

Source

pub fn builder() -> Builder

Returns the builder for an Endpoint, with a production configuration.

-
Source

pub fn set_alpns(&self, alpns: Vec<Vec<u8>>)

Sets the list of accepted ALPN protocols.

+

Implementations§

Source§

impl Endpoint

Source

pub fn builder() -> Builder

Returns the builder for an Endpoint, with a production configuration.

+
Source

pub fn set_alpns(&self, alpns: Vec<Vec<u8>>)

Sets the list of accepted ALPN protocols.

This will only affect new incoming connections. Note that this overrides the current list of ALPNs.

-
Source

pub async fn connect( +

Source

pub async fn connect( &self, node_addr: impl Into<NodeAddr>, alpn: &[u8], @@ -41,7 +41,7 @@ connection attempt will fail with an error.

The alpn, or application-level protocol identifier, is also required. The remote endpoint must support this alpn, otherwise the connection attempt will fail with an error.

-

Source

pub async fn connect_with_opts( +

Source

pub async fn connect_with_opts( &self, node_addr: impl Into<NodeAddr>, alpn: &[u8], @@ -61,13 +61,13 @@ security concerns. establishing and maintaining direct connections. Carefully test settings you use and consider this currently as still rather experimental. -

Source

pub fn accept(&self) -> Accept<'_> ⓘ

Accepts an incoming connection on the endpoint.

+
Source

pub fn accept(&self) -> Accept<'_> ⓘ

Accepts an incoming connection on the endpoint.

Only connections with the ALPNs configured in Builder::alpns will be accepted. If multiple ALPNs have been configured the ALPN can be inspected before accepting the connection using Connecting::alpn.

The returned future will yield None if the endpoint is closed by calling Endpoint::close.

-
Source

pub fn add_node_addr(&self, node_addr: NodeAddr) -> Result<(), AddNodeAddrError>

Informs this Endpoint about addresses of the iroh node.

+
Source

pub fn add_node_addr(&self, node_addr: NodeAddr) -> Result<(), AddNodeAddrError>

Informs this Endpoint about addresses of the iroh node.

This updates the local state for the remote node. If the provided NodeAddr contains a RelayUrl this will be used as the new relay server for this node. If it contains any new IP endpoints they will also be stored and tried when next @@ -80,7 +80,7 @@ This provides more flexibility and future proofing.

§Errors

Will return an error if we attempt to add our own NodeId to the node map or if the direct addresses are a subset of ours.

-
Source

pub fn add_node_addr_with_source( +

Source

pub fn add_node_addr_with_source( &self, node_addr: NodeAddr, source: &'static str, @@ -96,23 +96,24 @@ This provides more flexibility and future proofing.

§Errors

Will return an error if we attempt to add our own NodeId to the node map or if the direct addresses are a subset of ours.

-

Source

pub fn secret_key(&self) -> &SecretKey

Returns the secret_key of this endpoint.

-
Source

pub fn node_id(&self) -> NodeId

Returns the node id of this endpoint.

+
Source

pub fn secret_key(&self) -> &SecretKey

Returns the secret_key of this endpoint.

+
Source

pub fn node_id(&self) -> NodeId

Returns the node id of this endpoint.

This ID is the unique addressing information of this node and other peers must know it to be able to connect to this node.

-
Source

pub fn node_addr(&self) -> NodeAddrWatcher

Available on non-wasm_browser only.

Returns a Watcher for the current NodeAddr for this endpoint.

+
Source

pub fn node_addr(&self) -> impl Watcher<Value = Option<NodeAddr>>

Available on non-wasm_browser only.

Returns a [Watcher] for the current NodeAddr for this endpoint.

The observed NodeAddr will have the current RelayUrl and direct addresses as they would be returned by Endpoint::home_relay and Endpoint::direct_addresses.

-

Use Watcher::initialized to wait for a NodeAddr that is ready to be connected to:

+

Use [Watcher::initialized] to wait for a NodeAddr that is ready to be connected to:

-
use iroh::{watcher::Watcher, Endpoint};
+
use iroh::Endpoint;
+use n0_watcher::Watcher;
 
 let endpoint = Endpoint::builder()
     .alpns(vec![b"my-alpn".to_vec()])
     .bind()
     .await?;
 let node_addr = endpoint.node_addr().initialized().await?;
-
Source

pub fn home_relay(&self) -> Direct<Option<RelayUrl>>

Returns a Watcher for the RelayUrl of the Relay server used as home relay.

+
Source

pub fn home_relay(&self) -> impl Watcher<Value = Vec<RelayUrl>>

Returns a [Watcher] for the RelayUrl of the Relay server used as home relay.

Every endpoint has a home Relay server which it chooses as the server with the lowest latency out of the configured servers provided by Builder::relay_mode. This is the server other iroh nodes can use to reliably establish a connection @@ -121,14 +122,15 @@ to this node.

Note that this will store None right after the Endpoint is created since it takes some time to connect to find and connect to the home relay server.

§Examples
-

To wait for a home relay connection to be established, use Watcher::initialized:

+

To wait for a home relay connection to be established, use [Watcher::initialized]:

-
use futures_lite::StreamExt;
-use iroh::{watcher::Watcher, Endpoint};
+
use iroh::Endpoint;
+use n0_future::StreamExt;
+use n0_watcher::Watcher as _;
 
 let mep = Endpoint::builder().bind().await.unwrap();
 let _relay_url = mep.home_relay().initialized().await.unwrap();
-
Source

pub fn direct_addresses(&self) -> Direct<Option<BTreeSet<DirectAddr>>>

Returns a Watcher for the direct addresses of this Endpoint.

+
Source

pub fn direct_addresses(&self) -> Direct<Option<BTreeSet<DirectAddr>>>

Returns a [Watcher] for the direct addresses of this Endpoint.

The direct addresses of the Endpoint are those that could be used by other iroh nodes to establish direct connectivity, depending on the network situation. The yielded lists of direct addresses contain both the locally-bound @@ -139,22 +141,23 @@ will be applicable to a certain remote iroh node.

location in the network might change. Whenever changes are detected this stream will yield a new list of direct addresses.

When issuing the first call to this method the first direct address discovery might -still be underway, in this case the Watcher might not be initialized with Some -value yet. Once the first set of local direct addresses are discovered the Watcher +still be underway, in this case the [Watcher] might not be initialized with Some +value yet. Once the first set of local direct addresses are discovered the [Watcher] will always return Some set of direct addresses immediately, which are the most recently discovered direct addresses.

§Examples
-

To get the first set of direct addresses use Watcher::initialized:

+

To get the first set of direct addresses use [Watcher::initialized]:

-
use futures_lite::StreamExt;
-use iroh::{watcher::Watcher, Endpoint};
+
use iroh::Endpoint;
+use n0_future::StreamExt;
+use n0_watcher::Watcher as _;
 
 let mep = Endpoint::builder().bind().await.unwrap();
 let _addrs = mep.direct_addresses().initialized().await.unwrap();
-
Source

pub fn bound_sockets(&self) -> (SocketAddr, Option<SocketAddr>)

Available on non-wasm_browser only.

Returns the local socket addresses on which the underlying sockets are bound.

+
Source

pub fn bound_sockets(&self) -> Vec<SocketAddr>

Returns the local socket addresses on which the underlying sockets are bound.

The Endpoint always binds on an IPv4 address and also tries to bind on an IPv6 address if available.

-
Source

pub fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo>

Returns information about the remote node identified by a NodeId.

+
Source

pub fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo>

Returns information about the remote node identified by a NodeId.

The Endpoint keeps some information about remote iroh nodes, which it uses to find the best path to a node. Having information on a remote node, however, does not mean we have ever connected to it to or even whether a connection is even possible. The information about a @@ -163,14 +166,14 @@ calls may return different information. Furthermore, node information may even b completely evicted as it becomes stale.

See also Endpoint::remote_info_iter which returns information on all nodes known by this Endpoint.

-
Source

pub fn remote_info_iter(&self) -> impl Iterator<Item = RemoteInfo>

Returns information about all the remote nodes this Endpoint knows about.

+
Source

pub fn remote_info_iter(&self) -> impl Iterator<Item = RemoteInfo>

Returns information about all the remote nodes this Endpoint knows about.

This returns the same information as Endpoint::remote_info for each node known to this Endpoint.

The Endpoint keeps some information about remote iroh nodes, which it uses to find the best path to a node. This returns all the nodes it knows about, regardless of whether a connection was ever made or is even possible.

See also Endpoint::remote_info to only retrieve information about a single node.

-
Source

pub fn discovery_stream( +

Source

pub fn discovery_stream( &self, ) -> impl Stream<Item = Result<DiscoveryItem, Lagged>>

Returns a stream of all remote nodes discovered through the endpoint’s discovery services.

Whenever a node is discovered via the endpoint’s discovery service, the corresponding @@ -189,10 +192,10 @@ at the time of adding it to the static provider.

Lagged may be yielded, indicating that items were missed.

See also Endpoint::remote_info_iter, which returns an iterator over all remotes the endpoint knows about at a specific point in time.

-
Source

pub fn conn_type(&self, node_id: NodeId) -> Option<Direct<ConnectionType>>

Returns a Watcher that reports the current connection type and any changes for +

Source

pub fn conn_type(&self, node_id: NodeId) -> Option<Direct<ConnectionType>>

Returns a [Watcher] that reports the current connection type and any changes for given remote node.

This watcher allows observing a stream of ConnectionType items by calling -Watcher::stream(). If the underlying connection to a remote node changes, it will +[Watcher::stream()]. If the underlying connection to a remote node changes, it will yield a new item. These connection changes are when the connection switches between using the Relay server and a direct connection.

Note that this does not guarantee each connection change is yielded in the stream. @@ -200,19 +203,18 @@ If the connection type changes several times before this stream is polled, only last recorded state is returned. This can be observed e.g. right at the start of a connection when the switch from a relayed to a direct connection can be so fast that the relayed state is never exposed.

-

If there is currently a connection with the remote node, then using Watcher::get +

If there is currently a connection with the remote node, then using [Watcher::get] will immediately return either ConnectionType::Relay, ConnectionType::Direct or ConnectionType::Mixed.

It is possible for the connection type to be ConnectionType::None if you’ve recently connected to this node id but previous methods of reaching the node have become inaccessible.

-
§Errors

Will return None if we do not have any address information for the given node_id.

-
Source

pub fn dns_resolver(&self) -> &DnsResolver

Available on non-wasm_browser only.

Returns the DNS resolver used in this Endpoint.

+
Source

pub fn dns_resolver(&self) -> &DnsResolver

Available on non-wasm_browser only.

Returns the DNS resolver used in this Endpoint.

See Builder::dns_resolver.

-
Source

pub fn discovery(&self) -> Option<&dyn Discovery>

Returns the discovery mechanism, if configured.

+
Source

pub fn discovery(&self) -> Option<&dyn Discovery>

Returns the discovery mechanism, if configured.

See Builder::discovery.

-
Source

pub fn metrics(&self) -> &EndpointMetrics

Available on crate feature metrics only.

Returns metrics collected for this endpoint.

+
Source

pub fn metrics(&self) -> &EndpointMetrics

Available on crate feature metrics only.

Returns metrics collected for this endpoint.

The endpoint internally collects various metrics about its operation. The returned EndpointMetrics struct contains all of these metrics.

You can access individual metrics directly by using the public fields:

@@ -283,7 +285,7 @@ registry.write().unwrap().register_all(endpoint.metrics()); assert!(res.contains(r#"TYPE magicsock_recv_datagrams counter"#)); assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#));

-

Source

pub async fn network_change(&self)

Notifies the system of potential network changes.

+
Source

pub async fn network_change(&self)

Notifies the system of potential network changes.

On many systems iroh is able to detect network changes by itself, however some systems like android do not expose this functionality to native code. Android does however provide this functionality to Java code. This @@ -291,12 +293,12 @@ function allows for notifying iroh of any potential network changes like this.

Even when the network did not change, or iroh was already able to detect the network change itself, there is no harm in calling this function.

-
Source

pub fn set_user_data_for_discovery(&self, user_data: Option<UserData>)

Sets the initial user-defined data to be published in discovery services for this node.

+
Source

pub fn set_user_data_for_discovery(&self, user_data: Option<UserData>)

Sets the initial user-defined data to be published in discovery services for this node.

If the user-defined data passed to this function is different to the previous one, the endpoint will republish its node info to the configured discovery services.

See also Builder::user_data_for_discovery for setting an initial value when building the endpoint.

-
Source

pub async fn close(&self)

Closes the QUIC endpoint and the magic socket.

+
Source

pub async fn close(&self)

Closes the QUIC endpoint and the magic socket.

This will close any remaining open Connections with an error code of 0 and an empty reason. Though it is best practice to close those explicitly before with a custom error code and reason.

@@ -322,8 +324,8 @@ while TCP sockets usually get closed and drained by the operating system in the kernel during the “Time-Wait” period of the TCP socket.

Be aware however that the underlying UDP sockets are only closed once all clones of the the respective Endpoint are dropped.

-
Source

pub fn is_closed(&self) -> bool

Check if this endpoint is still alive, or already closed.

-

Trait Implementations§

Source§

impl Clone for Endpoint

Source§

fn clone(&self) -> Endpoint

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Endpoint

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Source

pub fn is_closed(&self) -> bool

Check if this endpoint is still alive, or already closed.

+

Trait Implementations§

Source§

impl Clone for Endpoint

Source§

fn clone(&self) -> Endpoint

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Endpoint

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/struct.Incoming.html b/pr/3327/docs/iroh/endpoint/struct.Incoming.html index 19e4ec2cb1..18c3b563be 100644 --- a/pr/3327/docs/iroh/endpoint/struct.Incoming.html +++ b/pr/3327/docs/iroh/endpoint/struct.Incoming.html @@ -1,29 +1,29 @@ -Incoming in iroh::endpoint - Rust

Struct Incoming

Source
pub struct Incoming { /* private fields */ }
Expand description

An incoming connection for which the server has not yet begun its parts of the +Incoming in iroh::endpoint - Rust

Struct Incoming

Source
pub struct Incoming { /* private fields */ }
Expand description

An incoming connection for which the server has not yet begun its parts of the handshake.

-

Implementations§

Source§

impl Incoming

Source

pub fn accept(self) -> Result<Connecting, ConnectionError>

Attempts to accept this incoming connection (an error may still occur).

+

Implementations§

Source§

impl Incoming

Source

pub fn accept(self) -> Result<Connecting, ConnectionError>

Attempts to accept this incoming connection (an error may still occur).

Errors occurring here are likely not caused by the application or remote. The QUIC connection listens on a normal UDP socket and any reachable network endpoint can send datagrams to it, solicited or not. Even if the first few bytes look like a QUIC packet, it might not even be a QUIC packet that is being received.

Thus it is common to simply log the errors here and accept them as something which can happen.

-
Source

pub fn accept_with( +

Source

pub fn accept_with( self, server_config: Arc<ServerConfig>, ) -> Result<Connecting, ConnectionError>

Accepts this incoming connection using a custom configuration.

See accept() for more details.

-
Source

pub fn refuse(self)

Rejects this incoming connection attempt.

-
Source

pub fn retry(self) -> Result<(), RetryError>

Responds with a retry packet.

+
Source

pub fn refuse(self)

Rejects this incoming connection attempt.

+
Source

pub fn retry(self) -> Result<(), RetryError>

Responds with a retry packet.

This requires the client to retry with address validation.

Errors if remote_address_validated() is true.

-
Source

pub fn ignore(self)

Ignores this incoming connection attempt, not sending any packet in response.

-
Source

pub fn local_ip(&self) -> Option<IpAddr>

Returns the local IP address which was used when the peer established the +

Source

pub fn ignore(self)

Ignores this incoming connection attempt, not sending any packet in response.

+
Source

pub fn local_ip(&self) -> Option<IpAddr>

Returns the local IP address which was used when the peer established the connection.

-
Source

pub fn remote_address(&self) -> SocketAddr

Returns the peer’s UDP address.

-
Source

pub fn remote_address_validated(&self) -> bool

Whether the socket address that is initiating this connection has been validated.

+
Source

pub fn remote_address(&self) -> SocketAddr

Returns the peer’s UDP address.

+
Source

pub fn remote_address_validated(&self) -> bool

Whether the socket address that is initiating this connection has been validated.

This means that the sender of the initial packet has proved that they can receive traffic sent to self.remote_address().

-

Trait Implementations§

Source§

impl Debug for Incoming

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl IntoFuture for Incoming

Source§

type Output = Result<Connection, ConnectionError>

The output that the future will produce on completion.
Source§

type IntoFuture = IncomingFuture

Which kind of future are we turning this into?
Source§

fn into_future(self) -> Self::IntoFuture

Creates a future from a value. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Debug for Incoming

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl IntoFuture for Incoming

Source§

type Output = Result<Connection, ConnectionError>

The output that the future will produce on completion.
Source§

type IntoFuture = IncomingFuture

Which kind of future are we turning this into?
Source§

fn into_future(self) -> Self::IntoFuture

Creates a future from a value. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/struct.IncomingFuture.html b/pr/3327/docs/iroh/endpoint/struct.IncomingFuture.html index 6a5e23ec08..8598f298b9 100644 --- a/pr/3327/docs/iroh/endpoint/struct.IncomingFuture.html +++ b/pr/3327/docs/iroh/endpoint/struct.IncomingFuture.html @@ -1,6 +1,6 @@ -IncomingFuture in iroh::endpoint - Rust

Struct IncomingFuture

Source
pub struct IncomingFuture { /* private fields */ }
Expand description

Adaptor to let Incoming be awaited like a Connecting.

-

Trait Implementations§

Source§

impl Debug for IncomingFuture

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Future for IncomingFuture

Source§

type Output = Result<Connection, ConnectionError>

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering -the current task for wakeup if the value is not yet available. Read more
Source§

impl<'pin> Unpin for IncomingFuture
where +IncomingFuture in iroh::endpoint - Rust

Struct IncomingFuture

Source
pub struct IncomingFuture { /* private fields */ }
Expand description

Adaptor to let Incoming be awaited like a Connecting.

+

Trait Implementations§

Source§

impl Debug for IncomingFuture

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Future for IncomingFuture

Source§

type Output = Result<Connection, ConnectionError>

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering +the current task for wakeup if the value is not yet available. Read more
Source§

impl<'pin> Unpin for IncomingFuture
where PinnedFieldsOf<__IncomingFuture<'pin>>: Unpin,

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where diff --git a/pr/3327/docs/iroh/endpoint/struct.RemoteInfo.html b/pr/3327/docs/iroh/endpoint/struct.RemoteInfo.html index 40e8680cf4..e75e4129c5 100644 --- a/pr/3327/docs/iroh/endpoint/struct.RemoteInfo.html +++ b/pr/3327/docs/iroh/endpoint/struct.RemoteInfo.html @@ -1,4 +1,4 @@ -RemoteInfo in iroh::endpoint - Rust

Struct RemoteInfo

Source
pub struct RemoteInfo {
+RemoteInfo in iroh::endpoint - Rust

Struct RemoteInfo

Source
pub struct RemoteInfo {
     pub node_id: NodeId,
     pub relay_url: Option<RelayUrlInfo>,
     pub addrs: Vec<DirectAddrInfo>,
@@ -21,20 +21,20 @@ node might be a part of.

This is the duration since any data (payload or control messages) was sent or receive from the remote node. Note that sending to the remote node does not imply the remote node received anything.

-

Implementations§

Source§

impl RemoteInfo

Source

pub fn last_received(&self) -> Option<Duration>

Get the duration since the last activity we received from this endpoint +

Implementations§

Source§

impl RemoteInfo

Source

pub fn last_received(&self) -> Option<Duration>

Get the duration since the last activity we received from this endpoint on any of its direct addresses.

-
Source

pub fn has_send_address(&self) -> bool

Whether there is a possible known network path to the remote node.

+
Source

pub fn has_send_address(&self) -> bool

Whether there is a possible known network path to the remote node.

Note that this does not provide any guarantees of whether any network path is usable.

-
Source

pub fn sources(&self) -> Vec<(Source, Duration)>

Returns a deduplicated list of Sources merged from all address in the RemoteInfo.

+
Source

pub fn sources(&self) -> Vec<(Source, Duration)>

Returns a deduplicated list of Sources merged from all address in the RemoteInfo.

Deduplication is on the (Source, Duration) tuple, so you will get multiple Sources for each Source variant, if different addresses were discovered from the same Source at different times.

The list is sorted from least to most recent Source.

-

Trait Implementations§

Source§

impl Clone for RemoteInfo

Source§

fn clone(&self) -> RemoteInfo

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RemoteInfo

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for RemoteInfo

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where - __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<RemoteInfo> for NodeAddr

Source§

fn from(info: RemoteInfo) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for RemoteInfo

Source§

fn eq(&self, other: &RemoteInfo) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl Serialize for RemoteInfo

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where - __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for RemoteInfo

Source§

impl StructuralPartialEq for RemoteInfo

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for RemoteInfo

Source§

fn clone(&self) -> RemoteInfo

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for RemoteInfo

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for RemoteInfo

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where + __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<RemoteInfo> for NodeAddr

Source§

fn from(info: RemoteInfo) -> Self

Converts to this type from the input type.
Source§

impl PartialEq for RemoteInfo

Source§

fn eq(&self, other: &RemoteInfo) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl Serialize for RemoteInfo

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where + __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl Eq for RemoteInfo

Source§

impl StructuralPartialEq for RemoteInfo

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/endpoint/struct.RemoteNodeIdError.html b/pr/3327/docs/iroh/endpoint/struct.RemoteNodeIdError.html index f0a0278289..0c24a96e51 100644 --- a/pr/3327/docs/iroh/endpoint/struct.RemoteNodeIdError.html +++ b/pr/3327/docs/iroh/endpoint/struct.RemoteNodeIdError.html @@ -1,8 +1,8 @@ -RemoteNodeIdError in iroh::endpoint - Rust

Struct RemoteNodeIdError

Source
pub struct RemoteNodeIdError { /* private fields */ }

Trait Implementations§

Source§

impl Debug for RemoteNodeIdError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for RemoteNodeIdError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for RemoteNodeIdError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for RemoteNodeIdError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +RemoteNodeIdError in iroh::endpoint - Rust

Struct RemoteNodeIdError

Source
pub struct RemoteNodeIdError { /* private fields */ }

Trait Implementations§

Source§

impl Debug for RemoteNodeIdError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for RemoteNodeIdError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for RemoteNodeIdError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for RemoteNodeIdError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<RemoteNodeIdError> for ProtocolError

Source§

fn from(error: RemoteNodeIdError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<RemoteNodeIdError> for AcceptError

Source§

fn from(error: RemoteNodeIdError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3327/docs/iroh/endpoint/struct.ZeroRttAccepted.html b/pr/3327/docs/iroh/endpoint/struct.ZeroRttAccepted.html index dc3c144ce8..9e48ec4670 100644 --- a/pr/3327/docs/iroh/endpoint/struct.ZeroRttAccepted.html +++ b/pr/3327/docs/iroh/endpoint/struct.ZeroRttAccepted.html @@ -1,7 +1,7 @@ -ZeroRttAccepted in iroh::endpoint - Rust

Struct ZeroRttAccepted

Source
pub struct ZeroRttAccepted { /* private fields */ }
Expand description

Future that completes when a connection is fully established.

+ZeroRttAccepted in iroh::endpoint - Rust

Struct ZeroRttAccepted

Source
pub struct ZeroRttAccepted { /* private fields */ }
Expand description

Future that completes when a connection is fully established.

For clients, the resulting value indicates if 0-RTT was accepted. For servers, the resulting value is meaningless.

-

Trait Implementations§

Source§

impl Debug for ZeroRttAccepted

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Future for ZeroRttAccepted

Source§

type Output = bool

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering +

Trait Implementations§

Source§

impl Debug for ZeroRttAccepted

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Future for ZeroRttAccepted

Source§

type Output = bool

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering the current task for wakeup if the value is not yet available. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where diff --git a/pr/3327/docs/iroh/endpoint/type.NodeAddrWatcher.html b/pr/3327/docs/iroh/endpoint/type.NodeAddrWatcher.html deleted file mode 100644 index c0df7e9961..0000000000 --- a/pr/3327/docs/iroh/endpoint/type.NodeAddrWatcher.html +++ /dev/null @@ -1,5 +0,0 @@ -NodeAddrWatcher in iroh::endpoint - Rust

Type Alias NodeAddrWatcher

Source
pub type NodeAddrWatcher = Map<(Direct<Option<BTreeSet<DirectAddr>>>, Direct<Option<RelayUrl>>), Option<NodeAddr>>;
Available on non-wasm_browser only.
Expand description

A type alias for the return value of Endpoint::node_addr.

-

This type implements Watcher with Value being an optional NodeAddr.

-

We return a named type instead of impl Watcher<Value = NodeAddr>, as this allows -you to e.g. store the watcher in a struct.

-

Aliased Type§

struct NodeAddrWatcher { /* private fields */ }
\ No newline at end of file diff --git a/pr/3327/docs/iroh/index.html b/pr/3327/docs/iroh/index.html index a0dff277e6..871fa2aa78 100644 --- a/pr/3327/docs/iroh/index.html +++ b/pr/3327/docs/iroh/index.html @@ -1,4 +1,4 @@ -iroh - Rust

Crate iroh

Source
Expand description

Peer-to-peer QUIC connections.

+iroh - Rust

Crate iroh

Source
Expand description

Peer-to-peer QUIC connections.

iroh is a library to establish direct connectivity between peers. It exposes an interface to QUIC connections and streams to the user, while implementing direct connectivity using hole punching complemented by relay servers under the hood.

@@ -149,8 +149,8 @@ connecting using only the < }

Every Endpoint can also accept connections:

-
use futures_lite::StreamExt;
-use iroh::{Endpoint, NodeAddr};
+
use iroh::{Endpoint, NodeAddr};
+use n0_future::StreamExt;
 use n0_snafu::{Result, ResultExt};
 
 async fn accept() -> Result<()> {
@@ -179,4 +179,4 @@ connecting using only the <
 }

Please see the examples directory for more nuanced examples.

Re-exports§

pub use endpoint::Endpoint;
pub use endpoint::RelayMode;

Modules§

defaults
Default values used in iroh
discovery
Node address discovery.
dnsNon-wasm_browser
This module exports a DNS resolver, which is also the default resolver used in the -crate::Endpoint if no custom resolver is configured.
endpoint
The Endpoint allows establishing connections to other iroh nodes.
metrics
Co-locating all of the iroh metrics structs
net_report
Checks the network conditions from the current host.
node_info
Support for handling DNS resource records for dialing by NodeId.
protocol
Tools for spawning an accept loop that routes incoming requests to the right protocol.
test_utilstest-utils
Internal utilities to support testing.
watcher
Watchable values.

Structs§

NodeAddr
Network-level addressing information for an iroh node.
PublicKey
A public key.
RelayMap
Configuration of all the relay servers that can be used.
RelayNode
Information on a specific relay server.
RelayUrl
A URL identifying a relay server.
RelayUrlParseError
Can occur when parsing a string into a RelayUrl.
SecretKey
A secret key.

Enums§

KeyParsingError
Error when deserialising a PublicKey or a SecretKey.
RelayProtocol
The HTTP upgrade protocol used for relaying.

Type Aliases§

NodeId
The identifier for a node in the (iroh) network.
\ No newline at end of file +crate::Endpoint if no custom resolver is configured.
endpoint
The Endpoint allows establishing connections to other iroh nodes.
metrics
Co-locating all of the iroh metrics structs
net_report
Checks the network conditions from the current host.
node_info
Support for handling DNS resource records for dialing by NodeId.
protocol
Tools for spawning an accept loop that routes incoming requests to the right protocol.
test_utilstest-utils
Internal utilities to support testing.

Structs§

NodeAddr
Network-level addressing information for an iroh node.
PublicKey
A public key.
RelayMap
Configuration of all the relay servers that can be used.
RelayNode
Information on a specific relay server.
RelayUrl
A URL identifying a relay server.
RelayUrlParseError
Can occur when parsing a string into a RelayUrl.
SecretKey
A secret key.

Enums§

KeyParsingError
Error when deserialising a PublicKey or a SecretKey.
RelayProtocol
The HTTP upgrade protocol used for relaying.

Type Aliases§

NodeId
The identifier for a node in the (iroh) network.

\ No newline at end of file diff --git a/pr/3327/docs/iroh/net_report/enum.ReportError.html b/pr/3327/docs/iroh/net_report/enum.ReportError.html index 19938aac9b..e333cb8386 100644 --- a/pr/3327/docs/iroh/net_report/enum.ReportError.html +++ b/pr/3327/docs/iroh/net_report/enum.ReportError.html @@ -1,4 +1,4 @@ -ReportError in iroh::net_report - Rust

Enum ReportError

Source
#[non_exhaustive]
pub enum ReportError { +ReportError in iroh::net_report - Rust

Enum ReportError

Source
#[non_exhaustive]
pub enum ReportError { Abort { reason: ActorRunError, backtrace: Option<Backtrace>, @@ -12,8 +12,8 @@ backtrace: Option<Backtrace>, span_trace: SpanTrace, }, -}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Abort

Fields

§reason: ActorRunError
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

AlreadyRunning

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ActorGone

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for ReportError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for ReportError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for ReportError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for ReportError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Abort

Fields

§reason: ActorRunError
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

AlreadyRunning

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ActorGone

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for ReportError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for ReportError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for ReportError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for ReportError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error and continuing with recursive calls to Error::source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where diff --git a/pr/3327/docs/iroh/net_report/fn.bind_local_stun_socket.html b/pr/3327/docs/iroh/net_report/fn.bind_local_stun_socket.html index 327188cc8a..27314b3941 100644 --- a/pr/3327/docs/iroh/net_report/fn.bind_local_stun_socket.html +++ b/pr/3327/docs/iroh/net_report/fn.bind_local_stun_socket.html @@ -1,4 +1,4 @@ -bind_local_stun_socket in iroh::net_report - Rust

Function bind_local_stun_socket

Source
pub fn bind_local_stun_socket(
+bind_local_stun_socket in iroh::net_report - Rust

Function bind_local_stun_socket

Source
pub fn bind_local_stun_socket(
     network: IpFamily,
     actor_addr: Addr,
     cancel_token: CancellationToken,
diff --git a/pr/3327/docs/iroh/net_report/index.html b/pr/3327/docs/iroh/net_report/index.html
index 4ee4b8e4f4..a43054396e 100644
--- a/pr/3327/docs/iroh/net_report/index.html
+++ b/pr/3327/docs/iroh/net_report/index.html
@@ -1,4 +1,4 @@
-iroh::net_report - Rust

Module net_report

Source
Expand description

Checks the network conditions from the current host.

+iroh::net_report - Rust

Module net_report

Source
Expand description

Checks the network conditions from the current host.

NetReport is responsible for finding out the network conditions of the current host, like whether it is connected to the internet via IPv4 and/or IPv6, what the NAT situation is etc and reachability to the configured relays.

diff --git a/pr/3327/docs/iroh/net_report/struct.Options.html b/pr/3327/docs/iroh/net_report/struct.Options.html index 8b3e360134..80918aa027 100644 --- a/pr/3327/docs/iroh/net_report/struct.Options.html +++ b/pr/3327/docs/iroh/net_report/struct.Options.html @@ -1,15 +1,16 @@ -Options in iroh::net_report - Rust

Struct Options

Source
pub struct Options { /* private fields */ }
Available on non-wasm_browser only.
Expand description

Options for running probes

+Options in iroh::net_report - Rust

Struct Options

Source
pub struct Options { /* private fields */ }
Available on non-wasm_browser only.
Expand description

Options for running probes

By default, will run icmp over IPv4, icmp over IPv6, and Https probes.

Use Options::stun_v4, Options::stun_v6, and Options::quic_config to enable STUN over IPv4, STUN over IPv6, and QUIC address discovery.

-

Implementations§

Source§

impl Options

Source

pub fn disabled() -> Self

Create an Options that disables all probes

-
Source

pub fn stun_v4(self, sock: Option<Arc<UdpSocket>>) -> Self

Set the ipv4 stun socket and enable ipv4 stun probes

-
Source

pub fn stun_v6(self, sock: Option<Arc<UdpSocket>>) -> Self

Set the ipv6 stun socket and enable ipv6 stun probes

-
Source

pub fn quic_config(self, quic_config: Option<QuicConfig>) -> Self

Enable quic probes

-
Source

pub fn icmp_v4(self, enable: bool) -> Self

Enable or disable icmp_v4 probe

-
Source

pub fn icmp_v6(self, enable: bool) -> Self

Enable or disable icmp_v6 probe

-
Source

pub fn https(self, enable: bool) -> Self

Enable or disable https probe

-

Trait Implementations§

Source§

impl Clone for Options

Source§

fn clone(&self) -> Options

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Options

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Options

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Implementations§

Source§

impl Options

Source

pub fn disabled() -> Self

Create an Options that disables all probes

+
Source

pub fn stun_v4(self, sock: Option<Arc<UdpSocket>>) -> Self

Set the ipv4 stun socket and enable ipv4 stun probes

+
Source

pub fn stun_v6(self, sock: Option<Arc<UdpSocket>>) -> Self

Set the ipv6 stun socket and enable ipv6 stun probes

+
Source

pub fn quic_config(self, quic_config: Option<QuicConfig>) -> Self

Enable quic probes

+
Source

pub fn icmp_v4(self, enable: bool) -> Self

Enable or disable icmp_v4 probe

+
Source

pub fn icmp_v6(self, enable: bool) -> Self

Enable or disable icmp_v6 probe

+
Source

pub fn https(self, enable: bool) -> Self

Enable or disable https probe

+
Source

pub fn insecure_skip_relay_cert_verify(self, skip: bool) -> Self

Available on crate feature test-utils only.

Skip cert verification

+

Trait Implementations§

Source§

impl Clone for Options

Source§

fn clone(&self) -> Options

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Options

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Options

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/net_report/struct.QuicConfig.html b/pr/3327/docs/iroh/net_report/struct.QuicConfig.html index 9790e72d21..0b8366d7fb 100644 --- a/pr/3327/docs/iroh/net_report/struct.QuicConfig.html +++ b/pr/3327/docs/iroh/net_report/struct.QuicConfig.html @@ -1,4 +1,4 @@ -QuicConfig in iroh::net_report - Rust

Struct QuicConfig

Source
pub struct QuicConfig {
+QuicConfig in iroh::net_report - Rust

Struct QuicConfig

Source
pub struct QuicConfig {
     pub ep: Endpoint,
     pub client_config: ClientConfig,
     pub ipv4: bool,
@@ -8,7 +8,7 @@
 
§client_config: ClientConfig

A client config.

§ipv4: bool

Enable ipv4 QUIC address discovery probes

§ipv6: bool

Enable ipv6 QUIC address discovery probes

-

Trait Implementations§

Source§

impl Clone for QuicConfig

Source§

fn clone(&self) -> QuicConfig

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for QuicConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for QuicConfig

Source§

fn clone(&self) -> QuicConfig

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for QuicConfig

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/node_info/struct.NodeInfo.html b/pr/3327/docs/iroh/node_info/struct.NodeInfo.html index a790c1f8c5..86987bbccb 100644 --- a/pr/3327/docs/iroh/node_info/struct.NodeInfo.html +++ b/pr/3327/docs/iroh/node_info/struct.NodeInfo.html @@ -36,7 +36,7 @@ )

Adds direct addresses to the node data.

Source

pub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)

Sets the relay URL of the node data.

Source

pub fn set_user_data(&mut self, user_data: Option<UserData>)

Sets the user-defined data of the node data.

-

Trait Implementations§

Source§

impl Clone for NodeInfo

Source§

fn clone(&self) -> NodeInfo

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for NodeInfo

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Deref for NodeInfo

Source§

type Target = NodeData

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<NodeInfo as Deref>::Target

Dereferences the value.
Source§

impl DerefMut for NodeInfo

Source§

fn deref_mut(&mut self) -> &mut <NodeInfo as Deref>::Target

Mutably dereferences the value.
Source§

impl From<&TxtAttrs<IrohAttr>> for NodeInfo

Source§

fn from(attrs: &TxtAttrs<IrohAttr>) -> NodeInfo

Converts to this type from the input type.
Source§

impl From<DiscoveryItem> for NodeInfo

Source§

fn from(item: DiscoveryItem) -> Self

Converts to this type from the input type.
Source§

impl From<NodeAddr> for NodeInfo

Source§

fn from(addr: NodeAddr) -> NodeInfo

Converts to this type from the input type.
Source§

impl From<NodeInfo> for NodeAddr

Source§

fn from(value: NodeInfo) -> NodeAddr

Converts to this type from the input type.
Source§

impl From<TxtAttrs<IrohAttr>> for NodeInfo

Source§

fn from(attrs: TxtAttrs<IrohAttr>) -> NodeInfo

Converts to this type from the input type.
Source§

impl PartialEq for NodeInfo

Source§

fn eq(&self, other: &NodeInfo) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +

Trait Implementations§

Source§

impl Clone for NodeInfo

Source§

fn clone(&self) -> NodeInfo

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for NodeInfo

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Deref for NodeInfo

Source§

type Target = NodeData

The resulting type after dereferencing.
Source§

fn deref(&self) -> &<NodeInfo as Deref>::Target

Dereferences the value.
Source§

impl DerefMut for NodeInfo

Source§

fn deref_mut(&mut self) -> &mut <NodeInfo as Deref>::Target

Mutably dereferences the value.
Source§

impl From<&TxtAttrs<IrohAttr>> for NodeInfo

Source§

fn from(attrs: &TxtAttrs<IrohAttr>) -> NodeInfo

Converts to this type from the input type.
Source§

impl From<DiscoveryItem> for NodeInfo

Source§

fn from(item: DiscoveryItem) -> Self

Converts to this type from the input type.
Source§

impl From<NodeAddr> for NodeInfo

Source§

fn from(addr: NodeAddr) -> NodeInfo

Converts to this type from the input type.
Source§

impl From<NodeInfo> for NodeAddr

Source§

fn from(value: NodeInfo) -> NodeAddr

Converts to this type from the input type.
Source§

impl From<TxtAttrs<IrohAttr>> for NodeInfo

Source§

fn from(attrs: TxtAttrs<IrohAttr>) -> NodeInfo

Converts to this type from the input type.
Source§

impl PartialEq for NodeInfo

Source§

fn eq(&self, other: &NodeInfo) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for NodeInfo

Source§

impl StructuralPartialEq for NodeInfo

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where diff --git a/pr/3327/docs/iroh/protocol/enum.ProtocolError.html b/pr/3327/docs/iroh/protocol/enum.AcceptError.html similarity index 55% rename from pr/3327/docs/iroh/protocol/enum.ProtocolError.html rename to pr/3327/docs/iroh/protocol/enum.AcceptError.html index 7e6bb2d482..465083fb43 100644 --- a/pr/3327/docs/iroh/protocol/enum.ProtocolError.html +++ b/pr/3327/docs/iroh/protocol/enum.AcceptError.html @@ -1,22 +1,22 @@ -ProtocolError in iroh::protocol - Rust

Enum ProtocolError

Source
#[non_exhaustive]
pub enum ProtocolError { - Connect { +AcceptError in iroh::protocol - Rust

Enum AcceptError

Source
#[non_exhaustive]
pub enum AcceptError { + Connection { source: ConnectionError, backtrace: Option<Backtrace>, span_trace: SpanTrace, }, - RemoteNodeId { + MissingRemoteNodeId { source: RemoteNodeIdError, }, NotAllowed {}, User { source: Box<dyn Error + Send + Sync + 'static>, }, -}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Connect

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

RemoteNodeId

Fields

§

NotAllowed

§

User

Fields

§source: Box<dyn Error + Send + Sync + 'static>

Implementations§

Source§

impl ProtocolError

Source

pub fn from_err<T: Error + Send + Sync + 'static>(value: T) -> Self

Creates a new user error from an arbitrary error type.

-

Trait Implementations§

Source§

impl Debug for ProtocolError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for ProtocolError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for ProtocolError
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for ProtocolError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +}

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Connection

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

MissingRemoteNodeId

Fields

§

NotAllowed

§

User

Fields

§source: Box<dyn Error + Send + Sync + 'static>

Implementations§

Source§

impl AcceptError

Source

pub fn from_err<T: Error + Send + Sync + 'static>(value: T) -> Self

Creates a new user error from an arbitrary error type.

+

Trait Implementations§

Source§

impl Debug for AcceptError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for AcceptError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for AcceptError
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for AcceptError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more
Source§

impl From<Box<dyn Error + Send + Sync>> for ProtocolError

Source§

fn from(error: Box<dyn Error + Send + Sync + 'static>) -> Self

Converts to this type from the input type.
Source§

impl From<ClosedStream> for ProtocolError

Source§

fn from(err: ClosedStream) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for ProtocolError

Source§

fn from(error: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for ProtocolError

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<RemoteNodeIdError> for ProtocolError

Source§

fn from(error: RemoteNodeIdError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Source§

impl From<Box<dyn Error + Send + Sync>> for AcceptError

Source§

fn from(error: Box<dyn Error + Send + Sync + 'static>) -> Self

Converts to this type from the input type.
Source§

impl From<ClosedStream> for AcceptError

Source§

fn from(err: ClosedStream) -> Self

Converts to this type from the input type.
Source§

impl From<ConnectionError> for AcceptError

Source§

fn from(error: ConnectionError) -> Self

Converts to this type from the input type.
Source§

impl From<Error> for AcceptError

Source§

fn from(err: Error) -> Self

Converts to this type from the input type.
Source§

impl From<RemoteNodeIdError> for AcceptError

Source§

fn from(error: RemoteNodeIdError) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3327/docs/iroh/protocol/index.html b/pr/3327/docs/iroh/protocol/index.html index 8ea185381f..01e644e6f9 100644 --- a/pr/3327/docs/iroh/protocol/index.html +++ b/pr/3327/docs/iroh/protocol/index.html @@ -1,4 +1,4 @@ -iroh::protocol - Rust

Module protocol

Source
Expand description

Tools for spawning an accept loop that routes incoming requests to the right protocol.

+iroh::protocol - Rust

Module protocol

Source
Expand description

Tools for spawning an accept loop that routes incoming requests to the right protocol.

§Example

let endpoint = Endpoint::builder().discovery_n0().bind().await?;
 
@@ -11,7 +11,7 @@
 struct Echo;
 
 impl ProtocolHandler for Echo {
-    async fn accept(&self, connection: Connection) -> Result<(), ProtocolError> {
+    async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
         let (mut send, mut recv) = connection.accept_bi().await?;
 
         // Echo any bytes received back directly.
@@ -24,4 +24,4 @@
     }
 }

Structs§

AccessLimit
Wraps an existing protocol, limiting its access, -based on the provided function.
Router
The built router.
RouterBuilder
Builder for creating a Router for accepting protocols.

Enums§

ProtocolError

Traits§

ProtocolHandler
Handler for incoming connections.
\ No newline at end of file +based on the provided function.
Router
The built router.
RouterBuilder
Builder for creating a Router for accepting protocols.

Enums§

AcceptError

Traits§

ProtocolHandler
Handler for incoming connections.
\ No newline at end of file diff --git a/pr/3327/docs/iroh/protocol/sidebar-items.js b/pr/3327/docs/iroh/protocol/sidebar-items.js index 262cf537cb..82af8e7ed2 100644 --- a/pr/3327/docs/iroh/protocol/sidebar-items.js +++ b/pr/3327/docs/iroh/protocol/sidebar-items.js @@ -1 +1 @@ -window.SIDEBAR_ITEMS = {"enum":["ProtocolError"],"struct":["AccessLimit","Router","RouterBuilder"],"trait":["ProtocolHandler"]}; \ No newline at end of file +window.SIDEBAR_ITEMS = {"enum":["AcceptError"],"struct":["AccessLimit","Router","RouterBuilder"],"trait":["ProtocolHandler"]}; \ No newline at end of file diff --git a/pr/3327/docs/iroh/protocol/struct.AccessLimit.html b/pr/3327/docs/iroh/protocol/struct.AccessLimit.html index fb61997fa1..a35487643a 100644 --- a/pr/3327/docs/iroh/protocol/struct.AccessLimit.html +++ b/pr/3327/docs/iroh/protocol/struct.AccessLimit.html @@ -1,15 +1,15 @@ -AccessLimit in iroh::protocol - Rust

Struct AccessLimit

Source
pub struct AccessLimit<P: ProtocolHandler + Clone> { /* private fields */ }
Expand description

Wraps an existing protocol, limiting its access, +AccessLimit in iroh::protocol - Rust

Struct AccessLimit

Source
pub struct AccessLimit<P: ProtocolHandler + Clone> { /* private fields */ }
Expand description

Wraps an existing protocol, limiting its access, based on the provided function.

Any refused connection will be closed with an error code of 0 and reason not allowed.

-

Implementations§

Source§

impl<P: ProtocolHandler + Clone> AccessLimit<P>

Source

pub fn new<F>(proto: P, limiter: F) -> Self
where +

Implementations§

Source§

impl<P: ProtocolHandler + Clone> AccessLimit<P>

Source

pub fn new<F>(proto: P, limiter: F) -> Self
where F: Fn(NodeId) -> bool + Send + Sync + 'static,

Create a new AccessLimit.

The function should return true for nodes that are allowed to connect, and false otherwise.

-

Trait Implementations§

Source§

impl<P: Clone + ProtocolHandler + Clone> Clone for AccessLimit<P>

Source§

fn clone(&self) -> AccessLimit<P>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<P> Debug for AccessLimit<P>
where - P: Debug + ProtocolHandler + Clone,

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<P: ProtocolHandler + Clone> ProtocolHandler for AccessLimit<P>

Trait Implementations§

Source§

impl<P: Clone + ProtocolHandler + Clone> Clone for AccessLimit<P>

Source§

fn clone(&self) -> AccessLimit<P>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<P> Debug for AccessLimit<P>
where + P: Debug + ProtocolHandler + Clone,

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<P: ProtocolHandler + Clone> ProtocolHandler for AccessLimit<P>

Source§

fn on_connecting( &self, conn: Connecting, -) -> impl Future<Output = Result<Connection, ProtocolError>> + Send

Optional interception point to handle the Connecting state. Read more
Source§

async fn accept(&self, conn: Connection) -> Result<(), ProtocolError>

Handle an incoming connection. Read more
Source§

fn shutdown(&self) -> impl Future<Output = ()> + Send

Called when the router shuts down. Read more

Auto Trait Implementations§

§

impl<P> Freeze for AccessLimit<P>
where +) -> impl Future<Output = Result<Connection, AcceptError>> + Send

Optional interception point to handle the Connecting state. Read more
Source§

async fn accept(&self, conn: Connection) -> Result<(), AcceptError>

Handle an incoming connection. Read more
Source§

fn shutdown(&self) -> impl Future<Output = ()> + Send

Called when the router shuts down. Read more

Auto Trait Implementations§

§

impl<P> Freeze for AccessLimit<P>
where P: Freeze,

§

impl<P> !RefUnwindSafe for AccessLimit<P>

§

impl<P> Send for AccessLimit<P>

§

impl<P> Sync for AccessLimit<P>

§

impl<P> Unpin for AccessLimit<P>
where P: Unpin,

§

impl<P> !UnwindSafe for AccessLimit<P>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where diff --git a/pr/3327/docs/iroh/protocol/struct.Router.html b/pr/3327/docs/iroh/protocol/struct.Router.html index 1b27c1cc9c..f2a1a4a21e 100644 --- a/pr/3327/docs/iroh/protocol/struct.Router.html +++ b/pr/3327/docs/iroh/protocol/struct.Router.html @@ -1,4 +1,4 @@ -Router in iroh::protocol - Rust

Struct Router

Source
pub struct Router { /* private fields */ }
Expand description

The built router.

+Router in iroh::protocol - Rust

Struct Router

Source
pub struct Router { /* private fields */ }
Expand description

The built router.

Construct this using Router::builder.

When dropped, this will abort listening the tasks, so make sure to store it.

Even with this abort-on-drop behaviour, it’s recommended to call and await @@ -15,16 +15,16 @@ wait for [tokio::signal::ctrl_c()]:

// wait until the user wants to tokio::signal::ctrl_c().await.context("ctrl+c")?; router.shutdown().await.context("shutdown")?;

-

Implementations§

Source§

impl Router

Source

pub fn builder(endpoint: Endpoint) -> RouterBuilder

Creates a new Router using given Endpoint.

-
Source

pub fn endpoint(&self) -> &Endpoint

Returns the Endpoint stored in this router.

-
Source

pub fn is_shutdown(&self) -> bool

Checks if the router is already shutdown.

-
Source

pub async fn shutdown(&self) -> Result<(), JoinError>

Shuts down the accept loop cleanly.

+

Implementations§

Source§

impl Router

Source

pub fn builder(endpoint: Endpoint) -> RouterBuilder

Creates a new Router using given Endpoint.

+
Source

pub fn endpoint(&self) -> &Endpoint

Returns the Endpoint stored in this router.

+
Source

pub fn is_shutdown(&self) -> bool

Checks if the router is already shutdown.

+
Source

pub async fn shutdown(&self) -> Result<(), JoinError>

Shuts down the accept loop cleanly.

When this function returns, all ProtocolHandlers will be shutdown and Endpoint::close will have been called.

If already shutdown, it returns Ok.

If some ProtocolHandler panicked in the accept loop, this will propagate that panic into the result here.

-

Trait Implementations§

Source§

impl Clone for Router

Source§

fn clone(&self) -> Router

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Router

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Router

§

impl !RefUnwindSafe for Router

§

impl Send for Router

§

impl Sync for Router

§

impl Unpin for Router

§

impl !UnwindSafe for Router

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for Router

Source§

fn clone(&self) -> Router

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Router

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Router

§

impl !RefUnwindSafe for Router

§

impl Send for Router

§

impl Sync for Router

§

impl Unpin for Router

§

impl !UnwindSafe for Router

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/protocol/struct.RouterBuilder.html b/pr/3327/docs/iroh/protocol/struct.RouterBuilder.html index 2bf1c14ab0..591cec88cc 100644 --- a/pr/3327/docs/iroh/protocol/struct.RouterBuilder.html +++ b/pr/3327/docs/iroh/protocol/struct.RouterBuilder.html @@ -1,14 +1,14 @@ -RouterBuilder in iroh::protocol - Rust

Struct RouterBuilder

Source
pub struct RouterBuilder { /* private fields */ }
Expand description

Builder for creating a Router for accepting protocols.

-

Implementations§

Source§

impl RouterBuilder

Source

pub fn new(endpoint: Endpoint) -> Self

Creates a new router builder using given Endpoint.

-
Source

pub fn accept( +RouterBuilder in iroh::protocol - Rust

Struct RouterBuilder

Source
pub struct RouterBuilder { /* private fields */ }
Expand description

Builder for creating a Router for accepting protocols.

+

Implementations§

Source§

impl RouterBuilder

Source

pub fn new(endpoint: Endpoint) -> Self

Creates a new router builder using given Endpoint.

+
Source

pub fn accept( self, alpn: impl AsRef<[u8]>, handler: impl ProtocolHandler, ) -> Self

Configures the router to accept the ProtocolHandler when receiving a connection with this alpn.

-
Source

pub fn endpoint(&self) -> &Endpoint

Returns the Endpoint of the node.

-
Source

pub fn spawn(self) -> Router

Spawns an accept loop and returns a handle to it encapsulated as the Router.

-

Trait Implementations§

Source§

impl Debug for RouterBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Source

pub fn endpoint(&self) -> &Endpoint

Returns the Endpoint of the node.

+
Source

pub fn spawn(self) -> Router

Spawns an accept loop and returns a handle to it encapsulated as the Router.

+

Trait Implementations§

Source§

impl Debug for RouterBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh/protocol/trait.ProtocolHandler.html b/pr/3327/docs/iroh/protocol/trait.ProtocolHandler.html index 63f570983c..c7b1ce01b2 100644 --- a/pr/3327/docs/iroh/protocol/trait.ProtocolHandler.html +++ b/pr/3327/docs/iroh/protocol/trait.ProtocolHandler.html @@ -1,4 +1,4 @@ -ProtocolHandler in iroh::protocol - Rust

Trait ProtocolHandler

Source
pub trait ProtocolHandler:
+ProtocolHandler in iroh::protocol - Rust

Trait ProtocolHandler

Source
pub trait ProtocolHandler:
     Send
     + Sync
     + Debug
@@ -7,13 +7,13 @@
     fn accept(
         &self,
         connection: Connection,
-    ) -> impl Future<Output = Result<(), ProtocolError>> + Send;
+    ) -> impl Future<Output = Result<(), AcceptError>> + Send;
 
     // Provided methods
     fn on_connecting(
         &self,
         connecting: Connecting,
-    ) -> impl Future<Output = Result<Connection, ProtocolError>> + Send { ... }
+    ) -> impl Future<Output = Result<Connection, AcceptError>> + Send { ... }
     fn shutdown(&self) -> impl Future<Output = ()> + Send { ... }
 }
Expand description

Handler for incoming connections.

A router accepts connections for arbitrary ALPN protocols.

@@ -22,29 +22,29 @@ The protocol handler must then be registered on the node for an ALPN protocol with crate::protocol::RouterBuilder::accept.

See the module documentation for an example.

-

Required Methods§

Required Methods§

Source

fn accept( &self, connection: Connection, -) -> impl Future<Output = Result<(), ProtocolError>> + Send

Handle an incoming connection.

+) -> impl Future<Output = Result<(), AcceptError>> + Send

Handle an incoming connection.

Can be implemented as async fn accept(&self, connection: Connection) -> Result<Connection>.

The returned future runs on a freshly spawned tokio task so it can be long-running.

When Router::shutdown is called, no further connections will be accepted, and the futures returned by Self::accept will be aborted after the future returned from ProtocolHandler::shutdown completes.

-

Provided Methods§

Provided Methods§

Source

fn on_connecting( &self, connecting: Connecting, -) -> impl Future<Output = Result<Connection, ProtocolError>> + Send

Optional interception point to handle the Connecting state.

+) -> impl Future<Output = Result<Connection, AcceptError>> + Send

Optional interception point to handle the Connecting state.

Can be implemented as async fn on_connecting(&self, connecting: Connecting) -> Result<Connection>.

This enables accepting 0-RTT data from clients, among other things.

-
Source

fn shutdown(&self) -> impl Future<Output = ()> + Send

Called when the router shuts down.

+
Source

fn shutdown(&self) -> impl Future<Output = ()> + Send

Called when the router shuts down.

Can be implemented as async fn shutdown(&self).

This is called from Router::shutdown. The returned future is awaited before the router closes the endpoint.

-

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T: ProtocolHandler> ProtocolHandler for Box<T>

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<T: ProtocolHandler> ProtocolHandler for Box<T>

Source§

async fn on_connecting( &self, conn: Connecting, -) -> Result<Connection, ProtocolError>

Source§

async fn accept(&self, conn: Connection) -> Result<(), ProtocolError>

Source§

async fn shutdown(&self)

Source§

impl<T: ProtocolHandler> ProtocolHandler for Arc<T>

Source§

impl<T: ProtocolHandler> ProtocolHandler for Arc<T>

Source§

async fn on_connecting( &self, conn: Connecting, -) -> Result<Connection, ProtocolError>

Source§

async fn accept(&self, conn: Connection) -> Result<(), ProtocolError>

Source§

async fn shutdown(&self)

Implementors§

\ No newline at end of file +) -> Result<Connection, AcceptError>
Source§

async fn accept(&self, conn: Connection) -> Result<(), AcceptError>

Source§

async fn shutdown(&self)

Implementors§

\ No newline at end of file diff --git a/pr/3327/docs/iroh/sidebar-items.js b/pr/3327/docs/iroh/sidebar-items.js index 9d05707435..ec4dc65c16 100644 --- a/pr/3327/docs/iroh/sidebar-items.js +++ b/pr/3327/docs/iroh/sidebar-items.js @@ -1 +1 @@ -window.SIDEBAR_ITEMS = {"enum":["KeyParsingError","RelayProtocol"],"mod":["defaults","discovery","dns","endpoint","metrics","net_report","node_info","protocol","test_utils","watcher"],"struct":["NodeAddr","PublicKey","RelayMap","RelayNode","RelayUrl","RelayUrlParseError","SecretKey"],"type":["NodeId"]}; \ No newline at end of file +window.SIDEBAR_ITEMS = {"enum":["KeyParsingError","RelayProtocol"],"mod":["defaults","discovery","dns","endpoint","metrics","net_report","node_info","protocol","test_utils"],"struct":["NodeAddr","PublicKey","RelayMap","RelayNode","RelayUrl","RelayUrlParseError","SecretKey"],"type":["NodeId"]}; \ No newline at end of file diff --git a/pr/3327/docs/iroh/struct.NodeAddr.html b/pr/3327/docs/iroh/struct.NodeAddr.html index 442c4d5e63..a497c87569 100644 --- a/pr/3327/docs/iroh/struct.NodeAddr.html +++ b/pr/3327/docs/iroh/struct.NodeAddr.html @@ -45,7 +45,7 @@ whenever a connection to other nodes needs to be established.

__deserializer: __D, ) -> Result<NodeAddr, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
Source§

impl From<(PublicKey, Option<RelayUrl>, &[SocketAddr])> for NodeAddr

Source§

fn from(value: (PublicKey, Option<RelayUrl>, &[SocketAddr])) -> NodeAddr

Converts to this type from the input type.
Source§

impl From<NodeAddr> for NodeData

Source§

fn from(node_addr: NodeAddr) -> NodeData

Converts to this type from the input type.
Source§

impl From<NodeAddr> for NodeInfo

Source§

fn from(addr: NodeAddr) -> NodeInfo

Converts to this type from the input type.
Source§

impl From<NodeInfo> for NodeAddr

Source§

fn from(value: NodeInfo) -> NodeAddr

Converts to this type from the input type.
Source§

impl From<NodeTicket> for NodeAddr

Source§

fn from(ticket: NodeTicket) -> NodeAddr

Returns the addressing info from given ticket.

-
Source§

impl From<PublicKey> for NodeAddr

Source§

fn from(node_id: PublicKey) -> NodeAddr

Converts to this type from the input type.
Source§

impl From<RemoteInfo> for NodeAddr

Source§

fn from(info: RemoteInfo) -> Self

Converts to this type from the input type.
Source§

impl Ord for NodeAddr

Source§

fn cmp(&self, other: &NodeAddr) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where +

Source§

impl From<PublicKey> for NodeAddr

Source§

fn from(node_id: PublicKey) -> NodeAddr

Converts to this type from the input type.
Source§

impl From<RemoteInfo> for NodeAddr

Source§

fn from(info: RemoteInfo) -> Self

Converts to this type from the input type.
Source§

impl Ord for NodeAddr

Source§

fn cmp(&self, other: &NodeAddr) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for NodeAddr

Source§

fn eq(&self, other: &NodeAddr) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, diff --git a/pr/3327/docs/iroh/test_utils/index.html b/pr/3327/docs/iroh/test_utils/index.html index d677d03af5..a8200899e5 100644 --- a/pr/3327/docs/iroh/test_utils/index.html +++ b/pr/3327/docs/iroh/test_utils/index.html @@ -1,2 +1,2 @@ -iroh::test_utils - Rust

Module test_utils

Source
Available on crate feature test-utils only.
Expand description

Internal utilities to support testing.

+iroh::test_utils - Rust

Module test_utils

Source
Available on crate feature test-utils only.
Expand description

Internal utilities to support testing.

Structs§

CleanupDropGuard
A drop guard to clean up test infrastructure.
DnsPkarrServer
Handle and drop guard for test DNS and Pkarr servers.

Functions§

run_relay_server
Runs a relay server with STUN and QUIC enabled suitable for tests.
run_relay_server_with
Runs a relay server.
run_relay_server_with_stun
Runs a relay server with STUN enabled suitable for tests.
\ No newline at end of file diff --git a/pr/3327/docs/iroh/watcher/index.html b/pr/3327/docs/iroh/watcher/index.html deleted file mode 100644 index 986782c7b4..0000000000 --- a/pr/3327/docs/iroh/watcher/index.html +++ /dev/null @@ -1,13 +0,0 @@ -iroh::watcher - Rust

Module watcher

Source
Expand description

Watchable values.

-

A Watchable exists to keep track of a value which may change over time. It allows -observers to be notified of changes to the value. The aim is to always be aware of the -last value, not to observe every value change.

-

In that way, a Watchable is like a [tokio::sync::broadcast::Sender] (and a -Watcher is like a [tokio::sync::broadcast::Receiver]), except that there’s no risk -of the channel filling up, but instead you might miss items.

-

This module is meant to be imported like this (if you use all of these things):

- -
ⓘ
use iroh::watcher::{self, Watchable, Watcher as _};
-

Structs§

Direct
The immediate, direct observer of a Watchable value.
Disconnected
The error for when a Watcher is disconnected from its underlying -Watchable value, because of that watchable having been dropped.
InitializedFut
Future returning the current or next value that’s Some value. -in a Watcher.
Map
Wraps a Watcher to allow observing a derived value.
NextFut
Future returning the next item after the current one in a Watcher.
Stream
A stream for a Watcher’s next values.
Watchable
A wrapper around a value that notifies Watchers when the value is modified.

Traits§

Watcher
A handle to a value that’s represented by one or more underlying Watchables.
\ No newline at end of file diff --git a/pr/3327/docs/iroh/watcher/sidebar-items.js b/pr/3327/docs/iroh/watcher/sidebar-items.js deleted file mode 100644 index e446a321c5..0000000000 --- a/pr/3327/docs/iroh/watcher/sidebar-items.js +++ /dev/null @@ -1 +0,0 @@ -window.SIDEBAR_ITEMS = {"struct":["Direct","Disconnected","InitializedFut","Map","NextFut","Stream","Watchable"],"trait":["Watcher"]}; \ No newline at end of file diff --git a/pr/3327/docs/iroh/watcher/struct.Direct.html b/pr/3327/docs/iroh/watcher/struct.Direct.html deleted file mode 100644 index 7118f9a35e..0000000000 --- a/pr/3327/docs/iroh/watcher/struct.Direct.html +++ /dev/null @@ -1,47 +0,0 @@ -Direct in iroh::watcher - Rust

Struct Direct

Source
pub struct Direct<T> { /* private fields */ }
Expand description

The immediate, direct observer of a Watchable value.

-

This type is mainly used via the Watcher interface.

-

Trait Implementations§

Source§

impl<T: Clone> Clone for Direct<T>

Source§

fn clone(&self) -> Direct<T>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug> Debug for Direct<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Clone + Eq> Watcher for Direct<T>

Source§

type Value = T

The type of value that can change. Read more
Source§

fn get(&self) -> Result<Self::Value, Disconnected>

Returns the current state of the underlying value, or errors out with -Disconnected, if one of the underlying Watchables has been dropped.
Source§

fn poll_updated( - &mut self, - cx: &mut Context<'_>, -) -> Poll<Result<Self::Value, Disconnected>>

Polls for the next value, or returns Disconnected if one of the underlying -Watchables has been dropped.
Source§

fn updated(&mut self) -> NextFut<'_, Self> ⓘ

Returns a future completing with Ok(value) once a new value is set, or with -Err(Disconnected) if the connected Watchable was dropped. Read more
Source§

fn initialized<T>(&mut self) -> InitializedFut<'_, T, Self> ⓘ
where - Self: Watcher<Value = Option<T>>,

Returns a future completing once the value is set to Some value. Read more
Source§

fn stream(self) -> Stream<Self>
where - Self: Unpin,

Returns a stream which will yield the most recent values as items. Read more
Source§

fn stream_updates_only(self) -> Stream<Self>
where - Self: Unpin,

Returns a stream which will yield the most recent values as items, starting from -the next unobserved future value. Read more
Source§

fn map<T: Clone + Eq>( - self, - map: impl Fn(Self::Value) -> T + 'static, -) -> Result<Map<Self, T>, Disconnected>

Maps this watcher with a function that transforms the observed values. Read more
Source§

fn or<W: Watcher>(self, other: W) -> (Self, W)

Returns a watcher that updates every time this or the other watcher -updates, and yields both watcher’s items together when that happens.

Auto Trait Implementations§

§

impl<T> Freeze for Direct<T>

§

impl<T> RefUnwindSafe for Direct<T>

§

impl<T> Send for Direct<T>
where - T: Send + Sync,

§

impl<T> Sync for Direct<T>
where - T: Send + Sync,

§

impl<T> Unpin for Direct<T>

§

impl<T> UnwindSafe for Direct<T>

Blanket Implementations§

Source§

impl<T> Any for T
where - T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where - T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where - T: 'a,

§

fn implicit( - self, - class: Class, - constructed: bool, - tag: u32, -) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where - T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where - T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where - T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
Source§

impl<T> DynClone for T
where - T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

-
§

impl<T> FromRef<T> for T
where - T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an -Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an -Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where - U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

-

That is, this conversion is whatever the implementation of -From<T> for U chooses to do.

-
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where - T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where - U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where - U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where - V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where - S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where - T: 'static,

§

impl<T> MaybeSendSync for T

\ No newline at end of file diff --git a/pr/3327/docs/iroh/watcher/struct.Disconnected.html b/pr/3327/docs/iroh/watcher/struct.Disconnected.html deleted file mode 100644 index 54d07fdc94..0000000000 --- a/pr/3327/docs/iroh/watcher/struct.Disconnected.html +++ /dev/null @@ -1,36 +0,0 @@ -Disconnected in iroh::watcher - Rust

Struct Disconnected

Source
pub struct Disconnected { /* private fields */ }
Expand description

The error for when a Watcher is disconnected from its underlying -Watchable value, because of that watchable having been dropped.

-

Trait Implementations§

Source§

impl Debug for Disconnected

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Disconnected

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Disconnected
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for Disconnected

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where - Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, -starting with the current error -and continuing with recursive calls to Error::source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where - T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where - T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method -to benefit from Rust’s automatic dereferencing of method -receivers.
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where - T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where - T: 'a,

§

fn implicit( - self, - class: Class, - constructed: bool, - tag: u32, -) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where - T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where - T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

-
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an -Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an -Instrumented wrapper. Read more
§

impl<E> InstrumentError for E
where - TracedError<E>: From<E>,

§

type Instrumented = TracedError<E>

The type of the wrapped error after instrumentation
§

fn in_current_span(self) -> <E as InstrumentError>::Instrumented

Instrument an Error by bundling it with a SpanTrace Read more
Source§

impl<T, U> Into<U> for T
where - U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

-

That is, this conversion is whatever the implementation of -From<T> for U chooses to do.

-
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToString for T
where - T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where - U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where - U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where - V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where - S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where - T: 'static,

§

impl<T> MaybeSendSync for T

\ No newline at end of file diff --git a/pr/3327/docs/iroh/watcher/struct.InitializedFut.html b/pr/3327/docs/iroh/watcher/struct.InitializedFut.html deleted file mode 100644 index 8d1034c14b..0000000000 --- a/pr/3327/docs/iroh/watcher/struct.InitializedFut.html +++ /dev/null @@ -1,142 +0,0 @@ -InitializedFut in iroh::watcher - Rust

Struct InitializedFut

Source
pub struct InitializedFut<'a, T, W: Watcher<Value = Option<T>>> { /* private fields */ }
Expand description

Future returning the current or next value that’s Some value. -in a Watcher.

-

See Watcher::initialized.

-

§Cancel Safety

-

This Future is cancel-safe.

-

Trait Implementations§

Source§

impl<'a, T: Debug, W: Debug + Watcher<Value = Option<T>>> Debug for InitializedFut<'a, T, W>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Clone + Eq + Unpin, W: Watcher<Value = Option<T>> + Unpin> Future for InitializedFut<'_, T, W>

Source§

type Output = Result<T, Disconnected>

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering -the current task for wakeup if the value is not yet available. Read more

Auto Trait Implementations§

§

impl<'a, T, W> Freeze for InitializedFut<'a, T, W>
where - T: Freeze,

§

impl<'a, T, W> !RefUnwindSafe for InitializedFut<'a, T, W>

§

impl<'a, T, W> Send for InitializedFut<'a, T, W>
where - W: Send, - T: Send,

§

impl<'a, T, W> Sync for InitializedFut<'a, T, W>
where - W: Sync, - T: Sync,

§

impl<'a, T, W> Unpin for InitializedFut<'a, T, W>
where - T: Unpin,

§

impl<'a, T, W> !UnwindSafe for InitializedFut<'a, T, W>

Blanket Implementations§

Source§

impl<T> Any for T
where - T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where - T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where - T: 'a,

§

fn implicit( - self, - class: Class, - constructed: bool, - tag: u32, -) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where - T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where - T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

-
§

impl<F> FutureExt for F
where - F: Future + ?Sized,

§

fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
where - Self: Unpin,

A convenience for calling Future::poll() on !Unpin types.
§

fn or<F>(self, other: F) -> Or<Self, F>
where - Self: Sized, - F: Future<Output = Self::Output>,

Returns the result of self or other future, preferring self if both are ready. Read more
§

fn race<F>(self, other: F) -> Race<Self, F>
where - Self: Sized, - F: Future<Output = Self::Output>,

Available on crate features std and race only.
Returns the result of self or other future, with no preference if both are ready. Read more
§

fn catch_unwind(self) -> CatchUnwind<Self>
where - Self: Sized + UnwindSafe,

Available on crate feature std only.
Catches panics while polling the future. Read more
§

fn boxed<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>
where - Self: Sized + Send + 'a,

Available on crate feature alloc only.
Boxes the future and changes its type to dyn Future + Send + 'a. Read more
§

fn boxed_local<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + 'a>>
where - Self: Sized + 'a,

Available on crate feature alloc only.
Boxes the future and changes its type to dyn Future + 'a. Read more
§

impl<T> FutureExt for T
where - T: Future + ?Sized,

§

fn map<U, F>(self, f: F) -> Map<Self, F>
where - F: FnOnce(Self::Output) -> U, - Self: Sized,

Map this future’s output to a different type, returning a new future of -the resulting type. Read more
§

fn map_into<U>(self) -> MapInto<Self, U>
where - Self::Output: Into<U>, - Self: Sized,

Map this future’s output to a different type, returning a new future of -the resulting type. Read more
§

fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
where - F: FnOnce(Self::Output) -> Fut, - Fut: Future, - Self: Sized,

Chain on a computation for when a future finished, passing the result of -the future to the provided closure f. Read more
§

fn left_future<B>(self) -> Either<Self, B>
where - B: Future<Output = Self::Output>, - Self: Sized,

Wrap this future in an Either future, making it the left-hand variant -of that Either. Read more
§

fn right_future<A>(self) -> Either<A, Self>
where - A: Future<Output = Self::Output>, - Self: Sized,

Wrap this future in an Either future, making it the right-hand variant -of that Either. Read more
§

fn into_stream(self) -> IntoStream<Self>
where - Self: Sized,

Convert this future into a single element stream. Read more
§

fn flatten(self) -> Flatten<Self>
where - Self::Output: Future, - Self: Sized,

Flatten the execution of this future when the output of this -future is itself another future. Read more
§

fn flatten_stream(self) -> FlattenStream<Self>
where - Self::Output: Stream, - Self: Sized,

Flatten the execution of this future when the successful result of this -future is a stream. Read more
§

fn fuse(self) -> Fuse<Self>
where - Self: Sized,

Fuse a future such that poll will never again be called once it has -completed. This method can be used to turn any Future into a -FusedFuture. Read more
§

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where - F: FnOnce(&Self::Output), - Self: Sized,

Do something with the output of a future before passing it on. Read more
§

fn catch_unwind(self) -> CatchUnwind<Self>
where - Self: Sized + UnwindSafe,

Available on crate feature std only.
Catches unwinding panics while polling the future. Read more
§

fn shared(self) -> Shared<Self>
where - Self: Sized, - Self::Output: Clone,

Available on crate feature std only.
Create a cloneable handle to this future where all handles will resolve -to the same result. Read more
§

fn remote_handle(self) -> (Remote<Self>, RemoteHandle<Self::Output>)
where - Self: Sized,

Available on crate features channel and std only.
Turn this future into a future that yields () on completion and sends -its output to another future on a separate task. Read more
§

fn boxed<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>
where - Self: Sized + Send + 'a,

Available on crate feature alloc only.
Wrap the future in a Box, pinning it. Read more
§

fn boxed_local<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + 'a>>
where - Self: Sized + 'a,

Available on crate feature alloc only.
Wrap the future in a Box, pinning it. Read more
§

fn unit_error(self) -> UnitError<Self>
where - Self: Sized,

§

fn never_error(self) -> NeverError<Self>
where - Self: Sized,

§

fn poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
where - Self: Unpin,

A convenience for calling Future::poll on Unpin future types.
§

fn now_or_never(self) -> Option<Self::Output>
where - Self: Sized,

Evaluates and consumes the future, returning the resulting output if -the future is ready after the first call to Future::poll. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an -Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an -Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where - U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

-

That is, this conversion is whatever the implementation of -From<T> for U chooses to do.

-
Source§

impl<F> IntoFuture for F
where - F: Future,

Source§

type Output = <F as Future>::Output

The output that the future will produce on completion.
Source§

type IntoFuture = F

Which kind of future are we turning this into?
Source§

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where - U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<F, T, E> TryFuture for F
where - F: Future<Output = Result<T, E>> + ?Sized,

§

type Ok = T

The type of successful values yielded by this future
§

type Error = E

The type of failures yielded by this future
§

fn try_poll( - self: Pin<&mut F>, - cx: &mut Context<'_>, -) -> Poll<<F as Future>::Output>

Poll this TryFuture as if it were a Future. Read more
§

impl<T, E, F> TryFuture for F
where - F: Future<Output = Result<T, E>> + ?Sized,

§

type Ok = T

§

type Err = E

§

impl<Fut> TryFutureExt for Fut
where - Fut: TryFuture + ?Sized,

§

fn flatten_sink<Item>(self) -> FlattenSink<Self, Self::Ok>
where - Self::Ok: Sink<Item, Error = Self::Error>, - Self: Sized,

Available on crate feature sink only.
Flattens the execution of this future when the successful result of this -future is a [Sink]. Read more
§

fn map_ok<T, F>(self, f: F) -> MapOk<Self, F>
where - F: FnOnce(Self::Ok) -> T, - Self: Sized,

Maps this future’s success value to a different value. Read more
§

fn map_ok_or_else<T, E, F>(self, e: E, f: F) -> MapOkOrElse<Self, F, E>
where - F: FnOnce(Self::Ok) -> T, - E: FnOnce(Self::Error) -> T, - Self: Sized,

Maps this future’s success value to a different value, and permits for error handling resulting in the same type. Read more
§

fn map_err<E, F>(self, f: F) -> MapErr<Self, F>
where - F: FnOnce(Self::Error) -> E, - Self: Sized,

Maps this future’s error value to a different value. Read more
§

fn err_into<E>(self) -> ErrInto<Self, E>
where - Self: Sized, - Self::Error: Into<E>,

Maps this future’s Error to a new error type -using the Into trait. Read more
§

fn ok_into<U>(self) -> OkInto<Self, U>
where - Self: Sized, - Self::Ok: Into<U>,

Maps this future’s Ok to a new type -using the Into trait.
§

fn and_then<Fut, F>(self, f: F) -> AndThen<Self, Fut, F>
where - F: FnOnce(Self::Ok) -> Fut, - Fut: TryFuture<Error = Self::Error>, - Self: Sized,

Executes another future after this one resolves successfully. The -success value is passed to a closure to create this subsequent future. Read more
§

fn or_else<Fut, F>(self, f: F) -> OrElse<Self, Fut, F>
where - F: FnOnce(Self::Error) -> Fut, - Fut: TryFuture<Ok = Self::Ok>, - Self: Sized,

Executes another future if this one resolves to an error. The -error value is passed to a closure to create this subsequent future. Read more
§

fn inspect_ok<F>(self, f: F) -> InspectOk<Self, F>
where - F: FnOnce(&Self::Ok), - Self: Sized,

Do something with the success value of a future before passing it on. Read more
§

fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
where - F: FnOnce(&Self::Error), - Self: Sized,

Do something with the error value of a future before passing it on. Read more
§

fn try_flatten(self) -> TryFlatten<Self, Self::Ok>
where - Self::Ok: TryFuture<Error = Self::Error>, - Self: Sized,

Flatten the execution of this future when the successful result of this -future is another future. Read more
§

fn try_flatten_stream(self) -> TryFlattenStream<Self>
where - Self::Ok: TryStream<Error = Self::Error>, - Self: Sized,

Flatten the execution of this future when the successful result of this -future is a stream. Read more
§

fn unwrap_or_else<F>(self, f: F) -> UnwrapOrElse<Self, F>
where - Self: Sized, - F: FnOnce(Self::Error) -> Self::Ok,

Unwraps this future’s output, producing a future with this future’s -Ok type as its -Output type. Read more
§

fn into_future(self) -> IntoFuture<Self>
where - Self: Sized,

Wraps a [TryFuture] into a type that implements -Future. Read more
§

fn try_poll_unpin( - &mut self, - cx: &mut Context<'_>, -) -> Poll<Result<Self::Ok, Self::Error>>
where - Self: Unpin,

A convenience method for calling [TryFuture::try_poll] on Unpin -future types.
Source§

impl<T, U> TryInto<U> for T
where - U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where - V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where - S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where - T: 'static,

§

impl<T> MaybeSendSync for T

\ No newline at end of file diff --git a/pr/3327/docs/iroh/watcher/struct.Map.html b/pr/3327/docs/iroh/watcher/struct.Map.html deleted file mode 100644 index 4d526362e0..0000000000 --- a/pr/3327/docs/iroh/watcher/struct.Map.html +++ /dev/null @@ -1,52 +0,0 @@ -Map in iroh::watcher - Rust

Struct Map

Source
pub struct Map<W: Watcher, T: Clone + Eq> { /* private fields */ }
Expand description

Wraps a Watcher to allow observing a derived value.

-

See Watcher::map.

-

Trait Implementations§

Source§

impl<W: Clone + Watcher, T: Clone + Clone + Eq> Clone for Map<W, T>
where - W::Value: Clone,

Source§

fn clone(&self) -> Map<W, T>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<W, T> Debug for Map<W, T>
where - W: Debug + Watcher, - T: Debug + Clone + Eq,

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<W: Watcher, T: Clone + Eq> Watcher for Map<W, T>

Source§

type Value = T

The type of value that can change. Read more
Source§

fn get(&self) -> Result<Self::Value, Disconnected>

Returns the current state of the underlying value, or errors out with -Disconnected, if one of the underlying Watchables has been dropped.
Source§

fn poll_updated( - &mut self, - cx: &mut Context<'_>, -) -> Poll<Result<Self::Value, Disconnected>>

Polls for the next value, or returns Disconnected if one of the underlying -Watchables has been dropped.
Source§

fn updated(&mut self) -> NextFut<'_, Self> ⓘ

Returns a future completing with Ok(value) once a new value is set, or with -Err(Disconnected) if the connected Watchable was dropped. Read more
Source§

fn initialized<T>(&mut self) -> InitializedFut<'_, T, Self> ⓘ
where - Self: Watcher<Value = Option<T>>,

Returns a future completing once the value is set to Some value. Read more
Source§

fn stream(self) -> Stream<Self>
where - Self: Unpin,

Returns a stream which will yield the most recent values as items. Read more
Source§

fn stream_updates_only(self) -> Stream<Self>
where - Self: Unpin,

Returns a stream which will yield the most recent values as items, starting from -the next unobserved future value. Read more
Source§

fn map<T: Clone + Eq>( - self, - map: impl Fn(Self::Value) -> T + 'static, -) -> Result<Map<Self, T>, Disconnected>

Maps this watcher with a function that transforms the observed values. Read more
Source§

fn or<W: Watcher>(self, other: W) -> (Self, W)

Returns a watcher that updates every time this or the other watcher -updates, and yields both watcher’s items together when that happens.

Auto Trait Implementations§

§

impl<W, T> Freeze for Map<W, T>
where - W: Freeze, - T: Freeze,

§

impl<W, T> !RefUnwindSafe for Map<W, T>

§

impl<W, T> !Send for Map<W, T>

§

impl<W, T> !Sync for Map<W, T>

§

impl<W, T> Unpin for Map<W, T>
where - W: Unpin, - T: Unpin,

§

impl<W, T> !UnwindSafe for Map<W, T>

Blanket Implementations§

Source§

impl<T> Any for T
where - T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where - T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where - T: 'a,

§

fn implicit( - self, - class: Class, - constructed: bool, - tag: u32, -) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where - T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where - T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where - T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
Source§

impl<T> DynClone for T
where - T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

-
§

impl<T> FromRef<T> for T
where - T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an -Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an -Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where - U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

-

That is, this conversion is whatever the implementation of -From<T> for U chooses to do.

-
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where - T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where - U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where - U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where - V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where - S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where - T: 'static,

§

impl<T> MaybeSendSync for T

\ No newline at end of file diff --git a/pr/3327/docs/iroh/watcher/struct.NextFut.html b/pr/3327/docs/iroh/watcher/struct.NextFut.html deleted file mode 100644 index 1876a31d89..0000000000 --- a/pr/3327/docs/iroh/watcher/struct.NextFut.html +++ /dev/null @@ -1,138 +0,0 @@ -NextFut in iroh::watcher - Rust

Struct NextFut

Source
pub struct NextFut<'a, W: Watcher> { /* private fields */ }
Expand description

Future returning the next item after the current one in a Watcher.

-

See Watcher::updated.

-

§Cancel Safety

-

This future is cancel-safe.

-

Trait Implementations§

Source§

impl<'a, W: Debug + Watcher> Debug for NextFut<'a, W>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<W: Watcher> Future for NextFut<'_, W>

Source§

type Output = Result<<W as Watcher>::Value, Disconnected>

The type of value produced on completion.
Source§

fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>

Attempts to resolve the future to a final value, registering -the current task for wakeup if the value is not yet available. Read more

Auto Trait Implementations§

§

impl<'a, W> Freeze for NextFut<'a, W>

§

impl<'a, W> RefUnwindSafe for NextFut<'a, W>
where - W: RefUnwindSafe,

§

impl<'a, W> Send for NextFut<'a, W>
where - W: Send,

§

impl<'a, W> Sync for NextFut<'a, W>
where - W: Sync,

§

impl<'a, W> Unpin for NextFut<'a, W>

§

impl<'a, W> !UnwindSafe for NextFut<'a, W>

Blanket Implementations§

Source§

impl<T> Any for T
where - T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where - T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where - T: 'a,

§

fn implicit( - self, - class: Class, - constructed: bool, - tag: u32, -) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where - T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where - T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

-
§

impl<F> FutureExt for F
where - F: Future + ?Sized,

§

fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
where - Self: Unpin,

A convenience for calling Future::poll() on !Unpin types.
§

fn or<F>(self, other: F) -> Or<Self, F>
where - Self: Sized, - F: Future<Output = Self::Output>,

Returns the result of self or other future, preferring self if both are ready. Read more
§

fn race<F>(self, other: F) -> Race<Self, F>
where - Self: Sized, - F: Future<Output = Self::Output>,

Available on crate features std and race only.
Returns the result of self or other future, with no preference if both are ready. Read more
§

fn catch_unwind(self) -> CatchUnwind<Self>
where - Self: Sized + UnwindSafe,

Available on crate feature std only.
Catches panics while polling the future. Read more
§

fn boxed<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>
where - Self: Sized + Send + 'a,

Available on crate feature alloc only.
Boxes the future and changes its type to dyn Future + Send + 'a. Read more
§

fn boxed_local<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + 'a>>
where - Self: Sized + 'a,

Available on crate feature alloc only.
Boxes the future and changes its type to dyn Future + 'a. Read more
§

impl<T> FutureExt for T
where - T: Future + ?Sized,

§

fn map<U, F>(self, f: F) -> Map<Self, F>
where - F: FnOnce(Self::Output) -> U, - Self: Sized,

Map this future’s output to a different type, returning a new future of -the resulting type. Read more
§

fn map_into<U>(self) -> MapInto<Self, U>
where - Self::Output: Into<U>, - Self: Sized,

Map this future’s output to a different type, returning a new future of -the resulting type. Read more
§

fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
where - F: FnOnce(Self::Output) -> Fut, - Fut: Future, - Self: Sized,

Chain on a computation for when a future finished, passing the result of -the future to the provided closure f. Read more
§

fn left_future<B>(self) -> Either<Self, B>
where - B: Future<Output = Self::Output>, - Self: Sized,

Wrap this future in an Either future, making it the left-hand variant -of that Either. Read more
§

fn right_future<A>(self) -> Either<A, Self>
where - A: Future<Output = Self::Output>, - Self: Sized,

Wrap this future in an Either future, making it the right-hand variant -of that Either. Read more
§

fn into_stream(self) -> IntoStream<Self>
where - Self: Sized,

Convert this future into a single element stream. Read more
§

fn flatten(self) -> Flatten<Self>
where - Self::Output: Future, - Self: Sized,

Flatten the execution of this future when the output of this -future is itself another future. Read more
§

fn flatten_stream(self) -> FlattenStream<Self>
where - Self::Output: Stream, - Self: Sized,

Flatten the execution of this future when the successful result of this -future is a stream. Read more
§

fn fuse(self) -> Fuse<Self>
where - Self: Sized,

Fuse a future such that poll will never again be called once it has -completed. This method can be used to turn any Future into a -FusedFuture. Read more
§

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where - F: FnOnce(&Self::Output), - Self: Sized,

Do something with the output of a future before passing it on. Read more
§

fn catch_unwind(self) -> CatchUnwind<Self>
where - Self: Sized + UnwindSafe,

Available on crate feature std only.
Catches unwinding panics while polling the future. Read more
§

fn shared(self) -> Shared<Self>
where - Self: Sized, - Self::Output: Clone,

Available on crate feature std only.
Create a cloneable handle to this future where all handles will resolve -to the same result. Read more
§

fn remote_handle(self) -> (Remote<Self>, RemoteHandle<Self::Output>)
where - Self: Sized,

Available on crate features channel and std only.
Turn this future into a future that yields () on completion and sends -its output to another future on a separate task. Read more
§

fn boxed<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>
where - Self: Sized + Send + 'a,

Available on crate feature alloc only.
Wrap the future in a Box, pinning it. Read more
§

fn boxed_local<'a>(self) -> Pin<Box<dyn Future<Output = Self::Output> + 'a>>
where - Self: Sized + 'a,

Available on crate feature alloc only.
Wrap the future in a Box, pinning it. Read more
§

fn unit_error(self) -> UnitError<Self>
where - Self: Sized,

§

fn never_error(self) -> NeverError<Self>
where - Self: Sized,

§

fn poll_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Self::Output>
where - Self: Unpin,

A convenience for calling Future::poll on Unpin future types.
§

fn now_or_never(self) -> Option<Self::Output>
where - Self: Sized,

Evaluates and consumes the future, returning the resulting output if -the future is ready after the first call to Future::poll. Read more
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an -Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an -Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where - U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

-

That is, this conversion is whatever the implementation of -From<T> for U chooses to do.

-
Source§

impl<F> IntoFuture for F
where - F: Future,

Source§

type Output = <F as Future>::Output

The output that the future will produce on completion.
Source§

type IntoFuture = F

Which kind of future are we turning this into?
Source§

fn into_future(self) -> <F as IntoFuture>::IntoFuture

Creates a future from a value. Read more
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where - U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
§

impl<F, T, E> TryFuture for F
where - F: Future<Output = Result<T, E>> + ?Sized,

§

type Ok = T

The type of successful values yielded by this future
§

type Error = E

The type of failures yielded by this future
§

fn try_poll( - self: Pin<&mut F>, - cx: &mut Context<'_>, -) -> Poll<<F as Future>::Output>

Poll this TryFuture as if it were a Future. Read more
§

impl<T, E, F> TryFuture for F
where - F: Future<Output = Result<T, E>> + ?Sized,

§

type Ok = T

§

type Err = E

§

impl<Fut> TryFutureExt for Fut
where - Fut: TryFuture + ?Sized,

§

fn flatten_sink<Item>(self) -> FlattenSink<Self, Self::Ok>
where - Self::Ok: Sink<Item, Error = Self::Error>, - Self: Sized,

Available on crate feature sink only.
Flattens the execution of this future when the successful result of this -future is a [Sink]. Read more
§

fn map_ok<T, F>(self, f: F) -> MapOk<Self, F>
where - F: FnOnce(Self::Ok) -> T, - Self: Sized,

Maps this future’s success value to a different value. Read more
§

fn map_ok_or_else<T, E, F>(self, e: E, f: F) -> MapOkOrElse<Self, F, E>
where - F: FnOnce(Self::Ok) -> T, - E: FnOnce(Self::Error) -> T, - Self: Sized,

Maps this future’s success value to a different value, and permits for error handling resulting in the same type. Read more
§

fn map_err<E, F>(self, f: F) -> MapErr<Self, F>
where - F: FnOnce(Self::Error) -> E, - Self: Sized,

Maps this future’s error value to a different value. Read more
§

fn err_into<E>(self) -> ErrInto<Self, E>
where - Self: Sized, - Self::Error: Into<E>,

Maps this future’s Error to a new error type -using the Into trait. Read more
§

fn ok_into<U>(self) -> OkInto<Self, U>
where - Self: Sized, - Self::Ok: Into<U>,

Maps this future’s Ok to a new type -using the Into trait.
§

fn and_then<Fut, F>(self, f: F) -> AndThen<Self, Fut, F>
where - F: FnOnce(Self::Ok) -> Fut, - Fut: TryFuture<Error = Self::Error>, - Self: Sized,

Executes another future after this one resolves successfully. The -success value is passed to a closure to create this subsequent future. Read more
§

fn or_else<Fut, F>(self, f: F) -> OrElse<Self, Fut, F>
where - F: FnOnce(Self::Error) -> Fut, - Fut: TryFuture<Ok = Self::Ok>, - Self: Sized,

Executes another future if this one resolves to an error. The -error value is passed to a closure to create this subsequent future. Read more
§

fn inspect_ok<F>(self, f: F) -> InspectOk<Self, F>
where - F: FnOnce(&Self::Ok), - Self: Sized,

Do something with the success value of a future before passing it on. Read more
§

fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
where - F: FnOnce(&Self::Error), - Self: Sized,

Do something with the error value of a future before passing it on. Read more
§

fn try_flatten(self) -> TryFlatten<Self, Self::Ok>
where - Self::Ok: TryFuture<Error = Self::Error>, - Self: Sized,

Flatten the execution of this future when the successful result of this -future is another future. Read more
§

fn try_flatten_stream(self) -> TryFlattenStream<Self>
where - Self::Ok: TryStream<Error = Self::Error>, - Self: Sized,

Flatten the execution of this future when the successful result of this -future is a stream. Read more
§

fn unwrap_or_else<F>(self, f: F) -> UnwrapOrElse<Self, F>
where - Self: Sized, - F: FnOnce(Self::Error) -> Self::Ok,

Unwraps this future’s output, producing a future with this future’s -Ok type as its -Output type. Read more
§

fn into_future(self) -> IntoFuture<Self>
where - Self: Sized,

Wraps a [TryFuture] into a type that implements -Future. Read more
§

fn try_poll_unpin( - &mut self, - cx: &mut Context<'_>, -) -> Poll<Result<Self::Ok, Self::Error>>
where - Self: Unpin,

A convenience method for calling [TryFuture::try_poll] on Unpin -future types.
Source§

impl<T, U> TryInto<U> for T
where - U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where - V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where - S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where - T: 'static,

§

impl<T> MaybeSendSync for T

\ No newline at end of file diff --git a/pr/3327/docs/iroh/watcher/struct.Stream.html b/pr/3327/docs/iroh/watcher/struct.Stream.html deleted file mode 100644 index e144a70080..0000000000 --- a/pr/3327/docs/iroh/watcher/struct.Stream.html +++ /dev/null @@ -1,462 +0,0 @@ -Stream in iroh::watcher - Rust

Struct Stream

Source
pub struct Stream<W: Watcher + Unpin> { /* private fields */ }
Expand description

A stream for a Watcher’s next values.

-

See Watcher::stream and Watcher::stream_updates_only.

-

§Cancel Safety

-

This stream is cancel-safe.

-

Trait Implementations§

Source§

impl<W: Clone + Watcher + Unpin> Clone for Stream<W>
where - W::Value: Clone,

Source§

fn clone(&self) -> Stream<W>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<W: Debug + Watcher + Unpin> Debug for Stream<W>
where - W::Value: Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<W: Watcher + Unpin> Stream for Stream<W>
where - W::Value: Unpin,

Source§

type Item = <W as Watcher>::Value

Values yielded by the stream.
Source§

fn poll_next( - self: Pin<&mut Self>, - cx: &mut Context<'_>, -) -> Poll<Option<Self::Item>>

Attempt to pull out the next value of this stream, registering the -current task for wakeup if the value is not yet available, and returning -None if the stream is exhausted. Read more
§

fn size_hint(&self) -> (usize, Option<usize>)

Returns the bounds on the remaining length of the stream. Read more

Auto Trait Implementations§

§

impl<W> Freeze for Stream<W>
where - W: Freeze, - <W as Watcher>::Value: Freeze,

§

impl<W> RefUnwindSafe for Stream<W>
where - W: RefUnwindSafe, - <W as Watcher>::Value: RefUnwindSafe,

§

impl<W> Send for Stream<W>
where - W: Send, - <W as Watcher>::Value: Send,

§

impl<W> Sync for Stream<W>
where - W: Sync, - <W as Watcher>::Value: Sync,

§

impl<W> Unpin for Stream<W>
where - <W as Watcher>::Value: Unpin,

§

impl<W> UnwindSafe for Stream<W>
where - W: UnwindSafe, - <W as Watcher>::Value: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where - T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where - T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where - T: 'a,

§

fn implicit( - self, - class: Class, - constructed: bool, - tag: u32, -) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where - T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where - T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> BufferedStreamExt for T
where - T: Stream + ?Sized,

§

fn buffered_ordered(self, n: usize) -> BufferedOrdered<Self>
where - Self::Item: Future, - Self: Sized,

An adaptor for creating a buffered list of pending futures. Read more
§

fn buffered_unordered(self, n: usize) -> BufferUnordered<Self>
where - Self::Item: Future, - Self: Sized,

An adaptor for creating a buffered list of pending futures (unordered). Read more
§

fn for_each_concurrent<Fut, F>( - self, - limit: usize, - f: F, -) -> ForEachConcurrent<Self, Fut, F>
where - F: FnMut(Self::Item) -> Fut, - Fut: Future<Output = ()>, - Self: Sized,

Runs this stream to completion, executing the provided asynchronous -closure for each element on the stream concurrently as elements become -available. Read more
§

impl<T> BufferedTryStreamExt for T
where - T: TryStream + ?Sized,

§

fn try_buffered_ordered(self, n: usize) -> TryBufferedOrdered<Self>
where - Self::Ok: TryFuture<Err = Self::Err>, - Self: Sized,

An adaptor for creating a buffered list of pending futures. Read more
§

fn try_buffered_unordered(self, n: usize) -> TryBufferUnordered<Self>
where - Self::Ok: TryFuture<Err = Self::Err>, - Self: Sized,

An adaptor for creating a buffered list of pending futures (unordered). Read more
Source§

impl<T> CloneToUninit for T
where - T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
Source§

impl<T> DynClone for T
where - T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

§

impl<E, S, T> FirstAnswer<T, E> for S
where - S: Stream<Item = Result<T, E>> + Unpin, - E: From<ProtoError>,

§

fn first_answer(self) -> FirstAnswerFuture<Self>

Convert a Stream of dns response into a Future yielding the first answer, -discarding others if any.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

-
§

impl<T> FromRef<T> for T
where - T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an -Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an -Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where - U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

-

That is, this conversion is whatever the implementation of -From<T> for U chooses to do.

-
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<S> StreamExt for S
where - S: Stream + ?Sized,

§

fn poll_next(&mut self, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>
where - Self: Unpin,

A convenience for calling [Stream::poll_next()] on !Unpin types.
§

fn next(&mut self) -> NextFuture<'_, Self>
where - Self: Unpin,

Retrieves the next item in the stream. Read more
§

fn try_next<T, E>(&mut self) -> TryNextFuture<'_, Self>
where - Self: Stream<Item = Result<T, E>> + Unpin,

Retrieves the next item in the stream. Read more
§

fn count(self) -> CountFuture<Self>
where - Self: Sized,

Counts the number of items in the stream. Read more
§

fn map<T, F>(self, f: F) -> Map<Self, F>
where - Self: Sized, - F: FnMut(Self::Item) -> T,

Maps items of the stream to new values using a closure. Read more
§

fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
where - Self: Sized, - U: Stream, - F: FnMut(Self::Item) -> U,

Maps items to streams and then concatenates them. Read more
§

fn flatten(self) -> Flatten<Self>
where - Self: Sized, - Self::Item: Stream,

Concatenates inner streams. Read more
§

fn then<F, Fut>(self, f: F) -> Then<Self, F, Fut>
where - Self: Sized, - F: FnMut(Self::Item) -> Fut, - Fut: Future,

Maps items of the stream to new values using an async closure. Read more
§

fn filter<P>(self, predicate: P) -> Filter<Self, P>
where - Self: Sized, - P: FnMut(&Self::Item) -> bool,

Keeps items of the stream for which predicate returns true. Read more
§

fn filter_map<T, F>(self, f: F) -> FilterMap<Self, F>
where - Self: Sized, - F: FnMut(Self::Item) -> Option<T>,

Filters and maps items of the stream using a closure. Read more
§

fn take(self, n: usize) -> Take<Self>
where - Self: Sized,

Takes only the first n items of the stream. Read more
§

fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P>
where - Self: Sized, - P: FnMut(&Self::Item) -> bool,

Takes items while predicate returns true. Read more
§

fn map_while<B, P>(self, predicate: P) -> MapWhile<Self, P>
where - Self: Sized, - P: FnMut(Self::Item) -> Option<B>,

Maps items while predicate returns Some. Read more
§

fn skip(self, n: usize) -> Skip<Self>
where - Self: Sized,

Skips the first n items of the stream. Read more
§

fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P>
where - Self: Sized, - P: FnMut(&Self::Item) -> bool,

Skips items while predicate returns true. Read more
§

fn step_by(self, step: usize) -> StepBy<Self>
where - Self: Sized,

Yields every stepth item. Read more
§

fn chain<U>(self, other: U) -> Chain<Self, U>
where - Self: Sized, - U: Stream<Item = Self::Item>,

Appends another stream to the end of this one. Read more
§

fn cloned<'a, T>(self) -> Cloned<Self>
where - Self: Sized + Stream<Item = &'a T>, - T: Clone + 'a,

Clones all items. Read more
§

fn copied<'a, T>(self) -> Copied<Self>
where - Self: Sized + Stream<Item = &'a T>, - T: Copy + 'a,

Copies all items. Read more
§

fn collect<C>(self) -> CollectFuture<Self, C>
where - Self: Sized, - C: Default + Extend<Self::Item>,

Collects all items in the stream into a collection. Read more
§

fn try_collect<T, E, C>(self) -> TryCollectFuture<Self, C>
where - Self: Sized + Stream<Item = Result<T, E>>, - C: Default + Extend<T>,

Collects all items in the fallible stream into a collection. Read more
§

fn partition<B, P>(self, predicate: P) -> PartitionFuture<Self, P, B>
where - Self: Sized, - B: Default + Extend<Self::Item>, - P: FnMut(&Self::Item) -> bool,

Partitions items into those for which predicate is true and those for which it is -false, and then collects them into two collections. Read more
§

fn fold<T, F>(self, init: T, f: F) -> FoldFuture<Self, F, T>
where - Self: Sized, - F: FnMut(T, Self::Item) -> T,

Accumulates a computation over the stream. Read more
§

fn try_fold<T, E, F, B>( - &mut self, - init: B, - f: F, -) -> TryFoldFuture<'_, Self, F, B>
where - Self: Sized + Stream<Item = Result<T, E>> + Unpin, - F: FnMut(B, T) -> Result<B, E>,

Accumulates a fallible computation over the stream. Read more
§

fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
where - Self: Sized, - F: FnMut(&mut St, Self::Item) -> Option<B>,

Maps items of the stream to new values using a state value and a closure. Read more
§

fn fuse(self) -> Fuse<Self>
where - Self: Sized,

Fuses the stream so that it stops yielding items after the first None. Read more
§

fn cycle(self) -> Cycle<Self>
where - Self: Sized + Clone,

Repeats the stream from beginning to end, forever. Read more
§

fn enumerate(self) -> Enumerate<Self>
where - Self: Sized,

Enumerates items, mapping them to (index, item). Read more
§

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where - Self: Sized, - F: FnMut(&Self::Item),

Calls a closure on each item and passes it on. Read more
§

fn nth(&mut self, n: usize) -> NthFuture<'_, Self>
where - Self: Unpin,

Gets the nth item of the stream. Read more
§

fn last(self) -> LastFuture<Self>
where - Self: Sized,

Returns the last item in the stream. Read more
§

fn find<P>(&mut self, predicate: P) -> FindFuture<'_, Self, P>
where - Self: Unpin, - P: FnMut(&Self::Item) -> bool,

Finds the first item of the stream for which predicate returns true. Read more
§

fn find_map<F, B>(&mut self, f: F) -> FindMapFuture<'_, Self, F>
where - Self: Unpin, - F: FnMut(Self::Item) -> Option<B>,

Applies a closure to items in the stream and returns the first Some result. Read more
§

fn position<P>(&mut self, predicate: P) -> PositionFuture<'_, Self, P>
where - Self: Unpin, - P: FnMut(Self::Item) -> bool,

Finds the index of the first item of the stream for which predicate returns true. Read more
§

fn all<P>(&mut self, predicate: P) -> AllFuture<'_, Self, P>
where - Self: Unpin, - P: FnMut(Self::Item) -> bool,

Tests if predicate returns true for all items in the stream. Read more
§

fn any<P>(&mut self, predicate: P) -> AnyFuture<'_, Self, P>
where - Self: Unpin, - P: FnMut(Self::Item) -> bool,

Tests if predicate returns true for any item in the stream. Read more
§

fn for_each<F>(self, f: F) -> ForEachFuture<Self, F>
where - Self: Sized, - F: FnMut(Self::Item),

Calls a closure on each item of the stream. Read more
§

fn try_for_each<F, E>(&mut self, f: F) -> TryForEachFuture<'_, Self, F>
where - Self: Unpin, - F: FnMut(Self::Item) -> Result<(), E>,

Calls a fallible closure on each item of the stream, stopping on first error. Read more
§

fn zip<U>(self, other: U) -> Zip<Self, U>
where - Self: Sized, - U: Stream,

Zips up two streams into a single stream of pairs. Read more
§

fn unzip<A, B, FromA, FromB>(self) -> UnzipFuture<Self, FromA, FromB>
where - FromA: Default + Extend<A>, - FromB: Default + Extend<B>, - Self: Sized + Stream<Item = (A, B)>,

Collects a stream of pairs into a pair of collections. Read more
§

fn or<S>(self, other: S) -> Or<Self, S>
where - Self: Sized, - S: Stream<Item = Self::Item>,

Merges with other stream, preferring items from self whenever both streams are ready. Read more
§

fn race<S>(self, other: S) -> Race<Self, S>
where - Self: Sized, - S: Stream<Item = Self::Item>,

Available on crate features std and race only.
Merges with other stream, with no preference for either stream when both are ready. Read more
§

fn drain(&mut self) -> Drain<'_, Self>

Yields all immediately available values from a stream. Read more
§

fn boxed<'a>(self) -> Pin<Box<dyn Stream<Item = Self::Item> + Send + 'a>>
where - Self: Sized + Send + 'a,

Available on crate feature alloc only.
Boxes the stream and changes its type to dyn Stream + Send + 'a. Read more
§

fn boxed_local<'a>(self) -> Pin<Box<dyn Stream<Item = Self::Item> + 'a>>
where - Self: Sized + 'a,

Available on crate feature alloc only.
Boxes the stream and changes its type to dyn Stream + 'a. Read more
§

impl<St> StreamExt for St
where - St: Stream + ?Sized,

§

fn next(&mut self) -> Next<'_, Self>
where - Self: Unpin,

Consumes and returns the next value in the stream or None if the -stream is finished. Read more
§

fn try_next<T, E>(&mut self) -> TryNext<'_, Self>
where - Self: Stream<Item = Result<T, E>> + Unpin,

Consumes and returns the next item in the stream. If an error is -encountered before the next item, the error is returned instead. Read more
§

fn map<T, F>(self, f: F) -> Map<Self, F>
where - F: FnMut(Self::Item) -> T, - Self: Sized,

Maps this stream’s items to a different type, returning a new stream of -the resulting type. Read more
§

fn map_while<T, F>(self, f: F) -> MapWhile<Self, F>
where - F: FnMut(Self::Item) -> Option<T>, - Self: Sized,

Map this stream’s items to a different type for as long as determined by -the provided closure. A stream of the target type will be returned, -which will yield elements until the closure returns None. Read more
§

fn then<F, Fut>(self, f: F) -> Then<Self, Fut, F>
where - F: FnMut(Self::Item) -> Fut, - Fut: Future, - Self: Sized,

Maps this stream’s items asynchronously to a different type, returning a -new stream of the resulting type. Read more
§

fn merge<U>(self, other: U) -> Merge<Self, U>
where - U: Stream<Item = Self::Item>, - Self: Sized,

Combine two streams into one by interleaving the output of both as it -is produced. Read more
§

fn filter<F>(self, f: F) -> Filter<Self, F>
where - F: FnMut(&Self::Item) -> bool, - Self: Sized,

Filters the values produced by this stream according to the provided -predicate. Read more
§

fn filter_map<T, F>(self, f: F) -> FilterMap<Self, F>
where - F: FnMut(Self::Item) -> Option<T>, - Self: Sized,

Filters the values produced by this stream while simultaneously mapping -them to a different type according to the provided closure. Read more
§

fn fuse(self) -> Fuse<Self>
where - Self: Sized,

Creates a stream which ends after the first None. Read more
§

fn take(self, n: usize) -> Take<Self>
where - Self: Sized,

Creates a new stream of at most n items of the underlying stream. Read more
§

fn take_while<F>(self, f: F) -> TakeWhile<Self, F>
where - F: FnMut(&Self::Item) -> bool, - Self: Sized,

Take elements from this stream while the provided predicate -resolves to true. Read more
§

fn skip(self, n: usize) -> Skip<Self>
where - Self: Sized,

Creates a new stream that will skip the n first items of the -underlying stream. Read more
§

fn skip_while<F>(self, f: F) -> SkipWhile<Self, F>
where - F: FnMut(&Self::Item) -> bool, - Self: Sized,

Skip elements from the underlying stream while the provided predicate -resolves to true. Read more
§

fn all<F>(&mut self, f: F) -> AllFuture<'_, Self, F>
where - Self: Unpin, - F: FnMut(Self::Item) -> bool,

Tests if every element of the stream matches a predicate. Read more
§

fn any<F>(&mut self, f: F) -> AnyFuture<'_, Self, F>
where - Self: Unpin, - F: FnMut(Self::Item) -> bool,

Tests if any element of the stream matches a predicate. Read more
§

fn chain<U>(self, other: U) -> Chain<Self, U>
where - U: Stream<Item = Self::Item>, - Self: Sized,

Combine two streams into one by first returning all values from the -first stream then all values from the second stream. Read more
§

fn fold<B, F>(self, init: B, f: F) -> FoldFuture<Self, B, F>
where - Self: Sized, - F: FnMut(B, Self::Item) -> B,

A combinator that applies a function to every element in a stream -producing a single, final value. Read more
§

fn collect<T>(self) -> Collect<Self, T>
where - T: FromStream<Self::Item>, - Self: Sized,

Drain stream pushing all emitted values into a collection. Read more
§

fn timeout(self, duration: Duration) -> Timeout<Self>
where - Self: Sized,

Available on crate feature time only.
Applies a per-item timeout to the passed stream. Read more
§

fn timeout_repeating(self, interval: Interval) -> TimeoutRepeating<Self>
where - Self: Sized,

Available on crate feature time only.
Applies a per-item timeout to the passed stream. Read more
§

fn throttle(self, duration: Duration) -> Throttle<Self>
where - Self: Sized,

Available on crate feature time only.
Slows down a stream by enforcing a delay between items. Read more
§

fn chunks_timeout( - self, - max_size: usize, - duration: Duration, -) -> ChunksTimeout<Self>
where - Self: Sized,

Available on crate feature time only.
Batches the items in the given stream using a maximum duration and size for each batch. Read more
§

fn peekable(self) -> Peekable<Self>
where - Self: Sized,

Turns the stream into a peekable stream, whose next element can be peeked at without being -consumed. Read more
§

impl<T> StreamExt for T
where - T: Stream + ?Sized,

§

fn next(&mut self) -> Next<'_, Self>
where - Self: Unpin,

Creates a future that resolves to the next item in the stream. Read more
§

fn into_future(self) -> StreamFuture<Self>
where - Self: Sized + Unpin,

Converts this stream into a future of (next_item, tail_of_stream). -If the stream terminates, then the next item is None. Read more
§

fn map<T, F>(self, f: F) -> Map<Self, F>
where - F: FnMut(Self::Item) -> T, - Self: Sized,

Maps this stream’s items to a different type, returning a new stream of -the resulting type. Read more
§

fn enumerate(self) -> Enumerate<Self>
where - Self: Sized,

Creates a stream which gives the current iteration count as well as -the next value. Read more
§

fn filter<Fut, F>(self, f: F) -> Filter<Self, Fut, F>
where - F: FnMut(&Self::Item) -> Fut, - Fut: Future<Output = bool>, - Self: Sized,

Filters the values produced by this stream according to the provided -asynchronous predicate. Read more
§

fn filter_map<Fut, T, F>(self, f: F) -> FilterMap<Self, Fut, F>
where - F: FnMut(Self::Item) -> Fut, - Fut: Future<Output = Option<T>>, - Self: Sized,

Filters the values produced by this stream while simultaneously mapping -them to a different type according to the provided asynchronous closure. Read more
§

fn then<Fut, F>(self, f: F) -> Then<Self, Fut, F>
where - F: FnMut(Self::Item) -> Fut, - Fut: Future, - Self: Sized,

Computes from this stream’s items new items of a different type using -an asynchronous closure. Read more
§

fn collect<C>(self) -> Collect<Self, C>
where - C: Default + Extend<Self::Item>, - Self: Sized,

Transforms a stream into a collection, returning a -future representing the result of that computation. Read more
§

fn unzip<A, B, FromA, FromB>(self) -> Unzip<Self, FromA, FromB>
where - FromA: Default + Extend<A>, - FromB: Default + Extend<B>, - Self: Sized + Stream<Item = (A, B)>,

Converts a stream of pairs into a future, which -resolves to pair of containers. Read more
§

fn concat(self) -> Concat<Self>
where - Self: Sized, - Self::Item: Extend<<Self::Item as IntoIterator>::Item> + IntoIterator + Default,

Concatenate all items of a stream into a single extendable -destination, returning a future representing the end result. Read more
§

fn count(self) -> Count<Self>
where - Self: Sized,

Drives the stream to completion, counting the number of items. Read more
§

fn cycle(self) -> Cycle<Self>
where - Self: Sized + Clone,

Repeats a stream endlessly. Read more
§

fn fold<T, Fut, F>(self, init: T, f: F) -> Fold<Self, Fut, T, F>
where - F: FnMut(T, Self::Item) -> Fut, - Fut: Future<Output = T>, - Self: Sized,

Execute an accumulating asynchronous computation over a stream, -collecting all the values into one final result. Read more
§

fn any<Fut, F>(self, f: F) -> Any<Self, Fut, F>
where - F: FnMut(Self::Item) -> Fut, - Fut: Future<Output = bool>, - Self: Sized,

Execute predicate over asynchronous stream, and return true if any element in stream satisfied a predicate. Read more
§

fn all<Fut, F>(self, f: F) -> All<Self, Fut, F>
where - F: FnMut(Self::Item) -> Fut, - Fut: Future<Output = bool>, - Self: Sized,

Execute predicate over asynchronous stream, and return true if all element in stream satisfied a predicate. Read more
§

fn flatten(self) -> Flatten<Self>
where - Self::Item: Stream, - Self: Sized,

Flattens a stream of streams into just one continuous stream. Read more
§

fn flatten_unordered( - self, - limit: impl Into<Option<usize>>, -) -> FlattenUnorderedWithFlowController<Self, ()>
where - Self::Item: Stream + Unpin, - Self: Sized,

Available on crate feature alloc only.
Flattens a stream of streams into just one continuous stream. Polls -inner streams produced by the base stream concurrently. Read more
§

fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
where - F: FnMut(Self::Item) -> U, - U: Stream, - Self: Sized,

Maps a stream like [StreamExt::map] but flattens nested Streams. Read more
§

fn flat_map_unordered<U, F>( - self, - limit: impl Into<Option<usize>>, - f: F, -) -> FlatMapUnordered<Self, U, F>
where - U: Stream + Unpin, - F: FnMut(Self::Item) -> U, - Self: Sized,

Available on crate feature alloc only.
Maps a stream like [StreamExt::map] but flattens nested Streams -and polls them concurrently, yielding items in any order, as they made -available. Read more
§

fn scan<S, B, Fut, F>(self, initial_state: S, f: F) -> Scan<Self, S, Fut, F>
where - F: FnMut(&mut S, Self::Item) -> Fut, - Fut: Future<Output = Option<B>>, - Self: Sized,

Combinator similar to [StreamExt::fold] that holds internal state -and produces a new stream. Read more
§

fn skip_while<Fut, F>(self, f: F) -> SkipWhile<Self, Fut, F>
where - F: FnMut(&Self::Item) -> Fut, - Fut: Future<Output = bool>, - Self: Sized,

Skip elements on this stream while the provided asynchronous predicate -resolves to true. Read more
§

fn take_while<Fut, F>(self, f: F) -> TakeWhile<Self, Fut, F>
where - F: FnMut(&Self::Item) -> Fut, - Fut: Future<Output = bool>, - Self: Sized,

Take elements from this stream while the provided asynchronous predicate -resolves to true. Read more
§

fn take_until<Fut>(self, fut: Fut) -> TakeUntil<Self, Fut>
where - Fut: Future, - Self: Sized,

Take elements from this stream until the provided future resolves. Read more
§

fn for_each<Fut, F>(self, f: F) -> ForEach<Self, Fut, F>
where - F: FnMut(Self::Item) -> Fut, - Fut: Future<Output = ()>, - Self: Sized,

Runs this stream to completion, executing the provided asynchronous -closure for each element on the stream. Read more
§

fn for_each_concurrent<Fut, F>( - self, - limit: impl Into<Option<usize>>, - f: F, -) -> ForEachConcurrent<Self, Fut, F>
where - F: FnMut(Self::Item) -> Fut, - Fut: Future<Output = ()>, - Self: Sized,

Available on crate feature alloc only.
Runs this stream to completion, executing the provided asynchronous -closure for each element on the stream concurrently as elements become -available. Read more
§

fn take(self, n: usize) -> Take<Self>
where - Self: Sized,

Creates a new stream of at most n items of the underlying stream. Read more
§

fn skip(self, n: usize) -> Skip<Self>
where - Self: Sized,

Creates a new stream which skips n items of the underlying stream. Read more
§

fn fuse(self) -> Fuse<Self>
where - Self: Sized,

Fuse a stream such that poll_next will never -again be called once it has finished. This method can be used to turn -any Stream into a FusedStream. Read more
§

fn by_ref(&mut self) -> &mut Self

Borrows a stream, rather than consuming it. Read more
§

fn catch_unwind(self) -> CatchUnwind<Self>
where - Self: Sized + UnwindSafe,

Available on crate feature std only.
Catches unwinding panics while polling the stream. Read more
§

fn boxed<'a>(self) -> Pin<Box<dyn Stream<Item = Self::Item> + Send + 'a>>
where - Self: Sized + Send + 'a,

Available on crate feature alloc only.
Wrap the stream in a Box, pinning it. Read more
§

fn boxed_local<'a>(self) -> Pin<Box<dyn Stream<Item = Self::Item> + 'a>>
where - Self: Sized + 'a,

Available on crate feature alloc only.
Wrap the stream in a Box, pinning it. Read more
§

fn buffered(self, n: usize) -> Buffered<Self>
where - Self::Item: Future, - Self: Sized,

Available on crate feature alloc only.
An adaptor for creating a buffered list of pending futures. Read more
§

fn buffer_unordered(self, n: usize) -> BufferUnordered<Self>
where - Self::Item: Future, - Self: Sized,

Available on crate feature alloc only.
An adaptor for creating a buffered list of pending futures (unordered). Read more
§

fn zip<St>(self, other: St) -> Zip<Self, St>
where - St: Stream, - Self: Sized,

An adapter for zipping two streams together. Read more
§

fn chain<St>(self, other: St) -> Chain<Self, St>
where - St: Stream<Item = Self::Item>, - Self: Sized,

Adapter for chaining two streams. Read more
§

fn peekable(self) -> Peekable<Self>
where - Self: Sized,

Creates a new stream which exposes a peek method. Read more
§

fn chunks(self, capacity: usize) -> Chunks<Self>
where - Self: Sized,

Available on crate feature alloc only.
An adaptor for chunking up items of the stream inside a vector. Read more
§

fn ready_chunks(self, capacity: usize) -> ReadyChunks<Self>
where - Self: Sized,

Available on crate feature alloc only.
An adaptor for chunking up ready items of the stream inside a vector. Read more
§

fn forward<S>(self, sink: S) -> Forward<Self, S>
where - S: Sink<Self::Ok, Error = Self::Error>, - Self: Sized + TryStream,

Available on crate feature sink only.
A future that completes after the given stream has been fully processed -into the sink and the sink has been flushed and closed. Read more
§

fn split<Item>(self) -> (SplitSink<Self, Item>, SplitStream<Self>)
where - Self: Sized + Sink<Item>,

Available on crate features sink and alloc only.
Splits this Stream + Sink object into separate Sink and Stream -objects. Read more
§

fn inspect<F>(self, f: F) -> Inspect<Self, F>
where - F: FnMut(&Self::Item), - Self: Sized,

Do something with each item of this stream, afterwards passing it on. Read more
§

fn left_stream<B>(self) -> Either<Self, B>
where - B: Stream<Item = Self::Item>, - Self: Sized,

Wrap this stream in an Either stream, making it the left-hand variant -of that Either. Read more
§

fn right_stream<B>(self) -> Either<B, Self>
where - B: Stream<Item = Self::Item>, - Self: Sized,

Wrap this stream in an Either stream, making it the right-hand variant -of that Either. Read more
§

fn poll_next_unpin(&mut self, cx: &mut Context<'_>) -> Poll<Option<Self::Item>>
where - Self: Unpin,

A convenience method for calling [Stream::poll_next] on Unpin -stream types.
§

fn select_next_some(&mut self) -> SelectNextSome<'_, Self>
where - Self: Unpin + FusedStream,

Returns a Future that resolves when the next item in this stream is -ready. Read more
§

impl<'a, S> StreamRateLimitExt<'a> for S
where - S: Stream,

§

fn ratelimit_stream<D, C, MW>( - self, - limiter: &'a RateLimiter<NotKeyed, D, C, MW>, -) -> RatelimitedStream<'a, S, D, C, MW>
where - D: DirectStateStore, - C: ReasonablyRealtime, - MW: RateLimitingMiddleware<<C as Clock>::Instant>,

Limits the rate at which the stream produces items. Read more
§

fn ratelimit_stream_with_jitter<D, C, MW>( - self, - limiter: &'a RateLimiter<NotKeyed, D, C, MW>, - jitter: Jitter, -) -> RatelimitedStream<'a, S, D, C, MW>
where - D: DirectStateStore, - C: ReasonablyRealtime, - MW: RateLimitingMiddleware<<C as Clock>::Instant>,

Limits the rate at which the stream produces items, with a randomized wait period. Read more
Source§

impl<T> ToOwned for T
where - T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where - U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where - U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<S, T, E> TryStream for S
where - S: Stream<Item = Result<T, E>> + ?Sized,

§

type Ok = T

The type of successful values yielded by this future
§

type Error = E

The type of failures yielded by this future
§

fn try_poll_next( - self: Pin<&mut S>, - cx: &mut Context<'_>, -) -> Poll<Option<Result<<S as TryStream>::Ok, <S as TryStream>::Error>>>

Poll this TryStream as if it were a Stream. Read more
§

impl<T, E, S> TryStream for S
where - S: Stream<Item = Result<T, E>> + ?Sized,

§

type Ok = T

§

type Err = E

§

impl<S> TryStreamExt for S
where - S: TryStream + ?Sized,

§

fn err_into<E>(self) -> ErrInto<Self, E>
where - Self: Sized, - Self::Error: Into<E>,

Wraps the current stream in a new stream which converts the error type -into the one provided. Read more
§

fn map_ok<T, F>(self, f: F) -> MapOk<Self, F>
where - Self: Sized, - F: FnMut(Self::Ok) -> T,

Wraps the current stream in a new stream which maps the success value -using the provided closure. Read more
§

fn map_err<E, F>(self, f: F) -> MapErr<Self, F>
where - Self: Sized, - F: FnMut(Self::Error) -> E,

Wraps the current stream in a new stream which maps the error value -using the provided closure. Read more
§

fn and_then<Fut, F>(self, f: F) -> AndThen<Self, Fut, F>
where - F: FnMut(Self::Ok) -> Fut, - Fut: TryFuture<Error = Self::Error>, - Self: Sized,

Chain on a computation for when a value is ready, passing the successful -results to the provided closure f. Read more
§

fn or_else<Fut, F>(self, f: F) -> OrElse<Self, Fut, F>
where - F: FnMut(Self::Error) -> Fut, - Fut: TryFuture<Ok = Self::Ok>, - Self: Sized,

Chain on a computation for when an error happens, passing the -erroneous result to the provided closure f. Read more
§

fn inspect_ok<F>(self, f: F) -> InspectOk<Self, F>
where - F: FnMut(&Self::Ok), - Self: Sized,

Do something with the success value of this stream, afterwards passing -it on. Read more
§

fn inspect_err<F>(self, f: F) -> InspectErr<Self, F>
where - F: FnMut(&Self::Error), - Self: Sized,

Do something with the error value of this stream, afterwards passing it on. Read more
§

fn into_stream(self) -> IntoStream<Self>
where - Self: Sized,

Wraps a [TryStream] into a type that implements -Stream Read more
§

fn try_next(&mut self) -> TryNext<'_, Self>
where - Self: Unpin,

Creates a future that attempts to resolve the next item in the stream. -If an error is encountered before the next item, the error is returned -instead. Read more
§

fn try_for_each<Fut, F>(self, f: F) -> TryForEach<Self, Fut, F>
where - F: FnMut(Self::Ok) -> Fut, - Fut: TryFuture<Ok = (), Error = Self::Error>, - Self: Sized,

Attempts to run this stream to completion, executing the provided -asynchronous closure for each element on the stream. Read more
§

fn try_skip_while<Fut, F>(self, f: F) -> TrySkipWhile<Self, Fut, F>
where - F: FnMut(&Self::Ok) -> Fut, - Fut: TryFuture<Ok = bool, Error = Self::Error>, - Self: Sized,

Skip elements on this stream while the provided asynchronous predicate -resolves to true. Read more
§

fn try_take_while<Fut, F>(self, f: F) -> TryTakeWhile<Self, Fut, F>
where - F: FnMut(&Self::Ok) -> Fut, - Fut: TryFuture<Ok = bool, Error = Self::Error>, - Self: Sized,

Take elements on this stream while the provided asynchronous predicate -resolves to true. Read more
§

fn try_for_each_concurrent<Fut, F>( - self, - limit: impl Into<Option<usize>>, - f: F, -) -> TryForEachConcurrent<Self, Fut, F>
where - F: FnMut(Self::Ok) -> Fut, - Fut: Future<Output = Result<(), Self::Error>>, - Self: Sized,

Available on crate feature alloc only.
Attempts to run this stream to completion, executing the provided asynchronous -closure for each element on the stream concurrently as elements become -available, exiting as soon as an error occurs. Read more
§

fn try_collect<C>(self) -> TryCollect<Self, C>
where - C: Default + Extend<Self::Ok>, - Self: Sized,

Attempt to transform a stream into a collection, -returning a future representing the result of that computation. Read more
§

fn try_chunks(self, capacity: usize) -> TryChunks<Self>
where - Self: Sized,

Available on crate feature alloc only.
An adaptor for chunking up successful items of the stream inside a vector. Read more
§

fn try_ready_chunks(self, capacity: usize) -> TryReadyChunks<Self>
where - Self: Sized,

Available on crate feature alloc only.
An adaptor for chunking up successful, ready items of the stream inside a vector. Read more
§

fn try_filter<Fut, F>(self, f: F) -> TryFilter<Self, Fut, F>
where - Fut: Future<Output = bool>, - F: FnMut(&Self::Ok) -> Fut, - Self: Sized,

Attempt to filter the values produced by this stream according to the -provided asynchronous closure. Read more
§

fn try_filter_map<Fut, F, T>(self, f: F) -> TryFilterMap<Self, Fut, F>
where - Fut: TryFuture<Ok = Option<T>, Error = Self::Error>, - F: FnMut(Self::Ok) -> Fut, - Self: Sized,

Attempt to filter the values produced by this stream while -simultaneously mapping them to a different type according to the -provided asynchronous closure. Read more
§

fn try_flatten_unordered( - self, - limit: impl Into<Option<usize>>, -) -> TryFlattenUnordered<Self>
where - Self::Ok: TryStream + Unpin, - <Self::Ok as TryStream>::Error: From<Self::Error>, - Self: Sized,

Available on crate feature alloc only.
Flattens a stream of streams into just one continuous stream. Produced streams -will be polled concurrently and any errors will be passed through without looking at them. -If the underlying base stream returns an error, it will be immediately propagated. Read more
§

fn try_flatten(self) -> TryFlatten<Self>
where - Self::Ok: TryStream, - <Self::Ok as TryStream>::Error: From<Self::Error>, - Self: Sized,

Flattens a stream of streams into just one continuous stream. Read more
§

fn try_fold<T, Fut, F>(self, init: T, f: F) -> TryFold<Self, Fut, T, F>
where - F: FnMut(T, Self::Ok) -> Fut, - Fut: TryFuture<Ok = T, Error = Self::Error>, - Self: Sized,

Attempt to execute an accumulating asynchronous computation over a -stream, collecting all the values into one final result. Read more
§

fn try_concat(self) -> TryConcat<Self>
where - Self: Sized, - Self::Ok: Extend<<Self::Ok as IntoIterator>::Item> + IntoIterator + Default,

Attempt to concatenate all items of a stream into a single -extendable destination, returning a future representing the end result. Read more
§

fn try_buffer_unordered(self, n: usize) -> TryBufferUnordered<Self>
where - Self::Ok: TryFuture<Error = Self::Error>, - Self: Sized,

Available on crate feature alloc only.
Attempt to execute several futures from a stream concurrently (unordered). Read more
§

fn try_buffered(self, n: usize) -> TryBuffered<Self>
where - Self::Ok: TryFuture<Error = Self::Error>, - Self: Sized,

Available on crate feature alloc only.
Attempt to execute several futures from a stream concurrently. Read more
§

fn try_poll_next_unpin( - &mut self, - cx: &mut Context<'_>, -) -> Poll<Option<Result<Self::Ok, Self::Error>>>
where - Self: Unpin,

A convenience method for calling [TryStream::try_poll_next] on Unpin -stream types.
§

fn into_async_read(self) -> IntoAsyncRead<Self>
where - Self: Sized + TryStreamExt<Error = Error>, - Self::Ok: AsRef<[u8]>,

Available on crate features io and std only.
Adapter that converts this stream into an AsyncBufRead. Read more
§

fn try_all<Fut, F>(self, f: F) -> TryAll<Self, Fut, F>
where - Self: Sized, - F: FnMut(Self::Ok) -> Fut, - Fut: Future<Output = bool>,

Attempt to execute a predicate over an asynchronous stream and evaluate if all items -satisfy the predicate. Exits early if an Err is encountered or if an Ok item is found -that does not satisfy the predicate. Read more
§

fn try_any<Fut, F>(self, f: F) -> TryAny<Self, Fut, F>
where - Self: Sized, - F: FnMut(Self::Ok) -> Fut, - Fut: Future<Output = bool>,

Attempt to execute a predicate over an asynchronous stream and evaluate if any items -satisfy the predicate. Exits early if an Err is encountered or if an Ok item is found -that satisfies the predicate. Read more
§

impl<V, T> VZip<V> for T
where - V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where - S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where - T: 'static,

§

impl<T> MaybeSendSync for T

\ No newline at end of file diff --git a/pr/3327/docs/iroh/watcher/struct.Watchable.html b/pr/3327/docs/iroh/watcher/struct.Watchable.html deleted file mode 100644 index a159fb7346..0000000000 --- a/pr/3327/docs/iroh/watcher/struct.Watchable.html +++ /dev/null @@ -1,41 +0,0 @@ -Watchable in iroh::watcher - Rust

Struct Watchable

Source
pub struct Watchable<T> { /* private fields */ }
Expand description

A wrapper around a value that notifies Watchers when the value is modified.

-

Only the most recent value is available to any observer, but the observer is guaranteed -to be notified of the most recent value.

-

Implementations§

Source§

impl<T: Clone + Eq> Watchable<T>

Source

pub fn new(value: T) -> Self

Creates a Watchable initialized to given value.

-
Source

pub fn set(&self, value: T) -> Result<T, T>

Sets a new value.

-

Returns Ok(previous_value) if the value was different from the one set, or -returns the provided value back as Err(value) if the value didn’t change.

-

Watchers are only notified if the value changed.

-
Source

pub fn watch(&self) -> Direct<T>

Creates a Direct Watcher, allowing the value to be observed, but not modified.

-
Source

pub fn get(&self) -> T

Returns the currently stored value.

-

Trait Implementations§

Source§

impl<T> Clone for Watchable<T>

Source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<T: Debug> Debug for Watchable<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Default> Default for Watchable<T>

Source§

fn default() -> Watchable<T>

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Watchable<T>

§

impl<T> RefUnwindSafe for Watchable<T>

§

impl<T> Send for Watchable<T>
where - T: Send + Sync,

§

impl<T> Sync for Watchable<T>
where - T: Send + Sync,

§

impl<T> Unpin for Watchable<T>

§

impl<T> UnwindSafe for Watchable<T>

Blanket Implementations§

Source§

impl<T> Any for T
where - T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where - T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where - T: 'a,

§

fn implicit( - self, - class: Class, - constructed: bool, - tag: u32, -) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where - T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where - T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where - T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dst: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. Read more
§

impl<T> CompatExt for T

§

fn compat(self) -> Compat<T>

Applies the [Compat] adapter by value. Read more
§

fn compat_ref(&self) -> Compat<&T>

Applies the [Compat] adapter by shared reference. Read more
§

fn compat_mut(&mut self) -> Compat<&mut T>

Applies the [Compat] adapter by mutable reference. Read more
Source§

impl<T> DynClone for T
where - T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

-
§

impl<T> FromRef<T> for T
where - T: Clone,

§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an -Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an -Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where - U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

-

That is, this conversion is whatever the implementation of -From<T> for U chooses to do.

-
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where - T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where - U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where - U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where - V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where - S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a -[WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where - T: 'static,

§

impl<T> MaybeSendSync for T

\ No newline at end of file diff --git a/pr/3327/docs/iroh/watcher/trait.Watcher.html b/pr/3327/docs/iroh/watcher/trait.Watcher.html deleted file mode 100644 index 4f55e84838..0000000000 --- a/pr/3327/docs/iroh/watcher/trait.Watcher.html +++ /dev/null @@ -1,92 +0,0 @@ -Watcher in iroh::watcher - Rust

Trait Watcher

Source
pub trait Watcher: Clone {
-    type Value: Clone + Eq;
-
-    // Required methods
-    fn get(&self) -> Result<Self::Value, Disconnected>;
-    fn poll_updated(
-        &mut self,
-        cx: &mut Context<'_>,
-    ) -> Poll<Result<Self::Value, Disconnected>>;
-
-    // Provided methods
-    fn updated(&mut self) -> NextFut<'_, Self> ⓘ { ... }
-    fn initialized<T>(&mut self) -> InitializedFut<'_, T, Self> ⓘ
-       where Self: Watcher<Value = Option<T>> { ... }
-    fn stream(self) -> Stream<Self>
-       where Self: Unpin { ... }
-    fn stream_updates_only(self) -> Stream<Self>
-       where Self: Unpin { ... }
-    fn map<T: Clone + Eq>(
-        self,
-        map: impl Fn(Self::Value) -> T + 'static,
-    ) -> Result<Map<Self, T>, Disconnected> { ... }
-    fn or<W: Watcher>(self, other: W) -> (Self, W) { ... }
-}
Expand description

A handle to a value that’s represented by one or more underlying Watchables.

-

A Watcher can get the current value, and will be notified when the value changes. -Only the most recent value is accessible, and if the threads with the underlying Watchables -change the value faster than the threads with the Watcher can keep up with, then -it’ll miss in-between values. -When the thread changing the Watchable pauses updating, the Watcher will always -end up reporting the most recent state eventually.

-

Watchers can be modified via Watcher::map to observe a value derived from the original -value via a function.

-

Watchers can be combined via Watcher::or to allow observing multiple values at once and -getting an update in case any of the values updates.

-

One of the underlying Watchables might already be dropped. In that case, -the watcher will be “disconnected” and return Err(Disconnected) -on some function calls or, when turned into a stream, that stream will end.

-

Required Associated Types§

Source

type Value: Clone + Eq

The type of value that can change.

-

We require Clone, because we need to be able to make -the values have a lifetime that’s detached from the original Watchable’s -lifetime.

-

We require Eq, to be able to check whether the value actually changed or -not, so we can notify or not notify accordingly.

-

Required Methods§

Source

fn get(&self) -> Result<Self::Value, Disconnected>

Returns the current state of the underlying value, or errors out with -Disconnected, if one of the underlying Watchables has been dropped.

-
Source

fn poll_updated( - &mut self, - cx: &mut Context<'_>, -) -> Poll<Result<Self::Value, Disconnected>>

Polls for the next value, or returns Disconnected if one of the underlying -Watchables has been dropped.

-

Provided Methods§

Source

fn updated(&mut self) -> NextFut<'_, Self> ⓘ

Returns a future completing with Ok(value) once a new value is set, or with -Err(Disconnected) if the connected Watchable was dropped.

-
§Cancel Safety
-

The returned future is cancel-safe.

-
Source

fn initialized<T>(&mut self) -> InitializedFut<'_, T, Self> ⓘ
where - Self: Watcher<Value = Option<T>>,

Returns a future completing once the value is set to Some value.

-

If the current value is Some value, this future will resolve immediately.

-

This is a utility for the common case of storing an Option inside a -Watchable.

-
§Cancel Safety
-

The returned future is cancel-safe.

-
Source

fn stream(self) -> Stream<Self>
where - Self: Unpin,

Returns a stream which will yield the most recent values as items.

-

The first item of the stream is the current value, so that this stream can be easily -used to operate on the most recent value.

-

Note however, that only the last item is stored. If the stream is not polled when an -item is available it can be replaced with another item by the time it is polled.

-

This stream ends once the original Watchable has been dropped.

-
§Cancel Safety
-

The returned stream is cancel-safe.

-
Source

fn stream_updates_only(self) -> Stream<Self>
where - Self: Unpin,

Returns a stream which will yield the most recent values as items, starting from -the next unobserved future value.

-

This means this stream will only yield values when the watched value changes, -the value stored at the time the stream is created is not yielded.

-

Note however, that only the last item is stored. If the stream is not polled when an -item is available it can be replaced with another item by the time it is polled.

-

This stream ends once the original Watchable has been dropped.

-
§Cancel Safety
-

The returned stream is cancel-safe.

-
Source

fn map<T: Clone + Eq>( - self, - map: impl Fn(Self::Value) -> T + 'static, -) -> Result<Map<Self, T>, Disconnected>

Maps this watcher with a function that transforms the observed values.

-

The returned watcher will only register updates, when the mapped value -observably changes. For this, it needs to store a clone of T in the watcher.

-
Source

fn or<W: Watcher>(self, other: W) -> (Self, W)

Returns a watcher that updates every time this or the other watcher -updates, and yields both watcher’s items together when that happens.

-

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl<S: Watcher, T: Watcher> Watcher for (S, T)

Source§

type Value = (<S as Watcher>::Value, <T as Watcher>::Value)

Source§

fn get(&self) -> Result<Self::Value, Disconnected>

Source§

fn poll_updated( - &mut self, - cx: &mut Context<'_>, -) -> Poll<Result<Self::Value, Disconnected>>

Implementors§

Source§

impl<T: Clone + Eq> Watcher for Direct<T>

Source§

type Value = T

Source§

impl<W: Watcher, T: Clone + Eq> Watcher for Map<W, T>

Source§

type Value = T

\ No newline at end of file diff --git a/pr/3327/docs/iroh_relay/all.html b/pr/3327/docs/iroh_relay/all.html index e1df15558b..24f48fc1fe 100644 --- a/pr/3327/docs/iroh_relay/all.html +++ b/pr/3327/docs/iroh_relay/all.html @@ -1 +1 @@ -List of all items in this crate

List of all items

Structs

Enums

Traits

Functions

Constants

\ No newline at end of file +List of all items in this crate

List of all items

Structs

Enums

Traits

Functions

Constants

\ No newline at end of file diff --git a/pr/3327/docs/iroh_relay/client/enum.ReceivedMessage.html b/pr/3327/docs/iroh_relay/client/enum.ReceivedMessage.html index 7c862d05b7..4f2e1b3f73 100644 --- a/pr/3327/docs/iroh_relay/client/enum.ReceivedMessage.html +++ b/pr/3327/docs/iroh_relay/client/enum.ReceivedMessage.html @@ -1,9 +1,9 @@ ReceivedMessage in iroh_relay::client - Rust

Enum ReceivedMessage

Source
pub enum ReceivedMessage {
     ReceivedPacket {
-        remote_node_id: NodeId,
+        remote_node_id: NodeId,
         data: Bytes,
     },
-    NodeGone(NodeId),
+    NodeGone(NodeId),
     Ping([u8; 8]),
     Pong([u8; 8]),
     KeepAlive,
@@ -17,9 +17,9 @@
 }
Expand description

The messages received from a framed relay stream.

This is a type-validated version of the Frames on the RelayCodec.

Variants§

§

ReceivedPacket

Represents an incoming packet.

-

Fields

§remote_node_id: NodeId

The NodeId of the packet sender.

+

Fields

§remote_node_id: NodeId

The [NodeId] of the packet sender.

§data: Bytes

The received packet bytes.

-
§

NodeGone(NodeId)

Indicates that the client identified by the underlying public key had previously sent you a +

§

NodeGone(NodeId)

Indicates that the client identified by the underlying public key had previously sent you a packet but has now disconnected from the server.

§

Ping([u8; 8])

Request from a client or server to reply to the other side with a ReceivedMessage::Pong with the given payload.

diff --git a/pr/3327/docs/iroh_relay/client/enum.SendMessage.html b/pr/3327/docs/iroh_relay/client/enum.SendMessage.html index e07368647b..6a3c982bf5 100644 --- a/pr/3327/docs/iroh_relay/client/enum.SendMessage.html +++ b/pr/3327/docs/iroh_relay/client/enum.SendMessage.html @@ -1,9 +1,9 @@ SendMessage in iroh_relay::client - Rust

Enum SendMessage

Source
pub enum SendMessage {
-    SendPacket(NodeId, Bytes),
+    SendPacket(NodeId, Bytes),
     Ping([u8; 8]),
     Pong([u8; 8]),
 }
Expand description

Messages we can send to a relay server.

-

Variants§

§

SendPacket(NodeId, Bytes)

Send a packet of data to the NodeId.

+

Variants§

§

SendPacket(NodeId, Bytes)

Send a packet of data to the [NodeId].

§

Ping([u8; 8])

Sends a ping message to the connected relay server.

§

Pong([u8; 8])

Sends a pong message to the connected relay server.

Trait Implementations§

Source§

impl Debug for SendMessage

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Sink<SendMessage> for Client

Source§

type Error = SendError

The type of value produced by the sink when an error occurs.
Source§

fn poll_ready( diff --git a/pr/3327/docs/iroh_relay/client/struct.ClientBuilder.html b/pr/3327/docs/iroh_relay/client/struct.ClientBuilder.html index 6e63827fbb..53e281c526 100644 --- a/pr/3327/docs/iroh_relay/client/struct.ClientBuilder.html +++ b/pr/3327/docs/iroh_relay/client/struct.ClientBuilder.html @@ -1,7 +1,7 @@ ClientBuilder in iroh_relay::client - Rust

Struct ClientBuilder

Source
pub struct ClientBuilder { /* private fields */ }
Expand description

Build a Client.

Implementations§

Source§

impl ClientBuilder

Source

pub fn new( - url: impl Into<RelayUrl>, - secret_key: SecretKey, + url: impl Into<RelayUrl>, + secret_key: SecretKey, dns_resolver: DnsResolver, ) -> Self

Create a new ClientBuilder

Source

pub fn protocol(self, protocol: Protocol) -> Self

Sets whether to connect to the relay via websockets or not. diff --git a/pr/3327/docs/iroh_relay/dns/enum.DnsError.html b/pr/3327/docs/iroh_relay/dns/enum.DnsError.html index fe64c35117..5f506a4ddb 100644 --- a/pr/3327/docs/iroh_relay/dns/enum.DnsError.html +++ b/pr/3327/docs/iroh_relay/dns/enum.DnsError.html @@ -1,4 +1,4 @@ -DnsError in iroh_relay::dns - Rust

Enum DnsError

Source
#[non_exhaustive]
pub enum DnsError { +DnsError in iroh_relay::dns - Rust

Enum DnsError

Source
#[non_exhaustive]
pub enum DnsError { Timeout { source: Elapsed, backtrace: Option<Backtrace>, @@ -27,13 +27,8 @@ backtrace: Option<Backtrace>, span_trace: SpanTrace, }, - Staggered { - errors: Vec<DnsError>, - backtrace: Option<Backtrace>, - span_trace: SpanTrace, - }, }
Available on non-wasm_browser only.
Expand description

Potential errors related to dns.

-

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Timeout

Fields

§source: Elapsed
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

NoResponse

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ResolveBoth

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

MissingHost

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Resolve

Fields

§source: ResolveError
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

InvalidResponse

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Staggered

Fields

§errors: Vec<DnsError>
§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for DnsError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for DnsError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for DnsError
where +

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Timeout

Fields

§source: Elapsed
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

NoResponse

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

ResolveBoth

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

MissingHost

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

Resolve

Fields

§source: ResolveError
§backtrace: Option<Backtrace>
§span_trace: SpanTrace
§

InvalidResponse

Fields

§backtrace: Option<Backtrace>
§span_trace: SpanTrace

Trait Implementations§

Source§

impl Debug for DnsError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for DnsError

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for DnsError
where Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for DnsError

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error diff --git a/pr/3327/docs/iroh_relay/dns/index.html b/pr/3327/docs/iroh_relay/dns/index.html index 4d1607714b..7266218105 100644 --- a/pr/3327/docs/iroh_relay/dns/index.html +++ b/pr/3327/docs/iroh_relay/dns/index.html @@ -1,2 +1,2 @@ -iroh_relay::dns - Rust

Module dns

Source
Available on non-wasm_browser only.
Expand description

DNS resolver

-

Structs§

DnsResolver
The DNS resolver used throughout iroh.
Error
Error returned when an input value is too long for crate::node_info::UserData.
TXT
Record data for a TXT record
TxtLookup
TXT records returned from DnsResolver::lookup_txt

Enums§

DnsError
Potential errors related to dns.

Constants§

N0_DNS_NODE_ORIGIN_PROD
The n0 testing DNS node origin, for production.
N0_DNS_NODE_ORIGIN_STAGING
The n0 testing DNS node origin, for testing.
\ No newline at end of file +iroh_relay::dns - Rust

Module dns

Source
Available on non-wasm_browser only.
Expand description

DNS resolver

+

Structs§

DnsResolver
The DNS resolver used throughout iroh.
StaggeredError
Error returned when an input value is too long for crate::node_info::UserData.
TXT
Record data for a TXT record
TxtLookup
TXT records returned from DnsResolver::lookup_txt

Enums§

DnsError
Potential errors related to dns.

Constants§

N0_DNS_NODE_ORIGIN_PROD
The n0 testing DNS node origin, for production.
N0_DNS_NODE_ORIGIN_STAGING
The n0 testing DNS node origin, for testing.
\ No newline at end of file diff --git a/pr/3327/docs/iroh_relay/dns/sidebar-items.js b/pr/3327/docs/iroh_relay/dns/sidebar-items.js index d942855610..e8599b6f6f 100644 --- a/pr/3327/docs/iroh_relay/dns/sidebar-items.js +++ b/pr/3327/docs/iroh_relay/dns/sidebar-items.js @@ -1 +1 @@ -window.SIDEBAR_ITEMS = {"constant":["N0_DNS_NODE_ORIGIN_PROD","N0_DNS_NODE_ORIGIN_STAGING"],"enum":["DnsError"],"struct":["DnsResolver","Error","TXT","TxtLookup"]}; \ No newline at end of file +window.SIDEBAR_ITEMS = {"constant":["N0_DNS_NODE_ORIGIN_PROD","N0_DNS_NODE_ORIGIN_STAGING"],"enum":["DnsError"],"struct":["DnsResolver","StaggeredError","TXT","TxtLookup"]}; \ No newline at end of file diff --git a/pr/3327/docs/iroh_relay/dns/staggered/struct.Error.html b/pr/3327/docs/iroh_relay/dns/staggered/struct.Error.html deleted file mode 100644 index 24ed9ec807..0000000000 --- a/pr/3327/docs/iroh_relay/dns/staggered/struct.Error.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - Redirection - - -

Redirecting to ../../../iroh_relay/dns/struct.Error.html...

- - - \ No newline at end of file diff --git a/pr/3327/docs/iroh_relay/dns/struct.DnsResolver.html b/pr/3327/docs/iroh_relay/dns/struct.DnsResolver.html index 2741715939..03806dc49f 100644 --- a/pr/3327/docs/iroh_relay/dns/struct.DnsResolver.html +++ b/pr/3327/docs/iroh_relay/dns/struct.DnsResolver.html @@ -1,26 +1,26 @@ -DnsResolver in iroh_relay::dns - Rust

Struct DnsResolver

Source
pub struct DnsResolver(/* private fields */);
Available on non-wasm_browser only.
Expand description

The DNS resolver used throughout iroh.

-

Implementations§

Source§

impl DnsResolver

Source

pub fn new() -> Self

Create a new DNS resolver with sensible cross-platform defaults.

+DnsResolver in iroh_relay::dns - Rust

Struct DnsResolver

Source
pub struct DnsResolver(/* private fields */);
Available on non-wasm_browser only.
Expand description

The DNS resolver used throughout iroh.

+

Implementations§

Source§

impl DnsResolver

Source

pub fn new() -> Self

Create a new DNS resolver with sensible cross-platform defaults.

We first try to read the system’s resolver from /etc/resolv.conf. This does not work at least on some Androids, therefore we fallback to the default ResolverConfig which uses eg. to google’s 8.8.8.8 or 8.8.4.4.

-
Source

pub fn with_nameserver(nameserver: SocketAddr) -> Self

Create a new DNS resolver configured with a single UDP DNS nameserver.

-
Source

pub fn clear_cache(&self)

Removes all entries from the cache.

-
Source

pub async fn lookup_txt( +

Source

pub fn with_nameserver(nameserver: SocketAddr) -> Self

Create a new DNS resolver configured with a single UDP DNS nameserver.

+
Source

pub fn clear_cache(&self)

Removes all entries from the cache.

+
Source

pub async fn lookup_txt( &self, host: impl ToString, timeout: Duration, ) -> Result<TxtLookup, DnsError>

Lookup a TXT record.

-
Source

pub async fn lookup_ipv4( +

Source

pub async fn lookup_ipv4( &self, host: impl ToString, timeout: Duration, ) -> Result<impl Iterator<Item = IpAddr>, DnsError>

Perform an ipv4 lookup with a timeout.

-
Source

pub async fn lookup_ipv6( +

Source

pub async fn lookup_ipv6( &self, host: impl ToString, timeout: Duration, ) -> Result<impl Iterator<Item = IpAddr>, DnsError>

Perform an ipv6 lookup with a timeout.

-
Source

pub async fn lookup_ipv4_ipv6( +

Source

pub async fn lookup_ipv4_ipv6( &self, host: impl ToString, timeout: Duration, @@ -28,74 +28,74 @@ to the default ResolverConfig which uses eg. to google’s 8.

LookupIpStrategy::Ipv4AndIpv6 will wait for ipv6 resolution timeout, even if it is not usable on the stack, so we manually query both lookups concurrently and time them out individually.

-

Source

pub async fn resolve_host( +

Source

pub async fn resolve_host( &self, url: &Url, prefer_ipv6: bool, timeout: Duration, ) -> Result<IpAddr, DnsError>

Resolve a hostname from a URL to an IP address.

-
Source

pub async fn lookup_ipv4_staggered( +

Source

pub async fn lookup_ipv4_staggered( &self, host: impl ToString, timeout: Duration, delays_ms: &[u64], -) -> Result<impl Iterator<Item = IpAddr>, DnsError>

Perform an ipv4 lookup with a timeout in a staggered fashion.

+) -> Result<impl Iterator<Item = IpAddr>, StaggeredError<DnsError>>

Perform an ipv4 lookup with a timeout in a staggered fashion.

From the moment this function is called, each lookup is scheduled after the delays in delays_ms with the first call being done immediately. [200ms, 300ms] results in calls at T+0ms, T+200ms and T+300ms. The timeout is applied to each call individually. The result of the first successful call is returned, or a summary of all errors otherwise.

-
Source

pub async fn lookup_ipv6_staggered( +

Source

pub async fn lookup_ipv6_staggered( &self, host: impl ToString, timeout: Duration, delays_ms: &[u64], -) -> Result<impl Iterator<Item = IpAddr>, DnsError>

Perform an ipv6 lookup with a timeout in a staggered fashion.

+) -> Result<impl Iterator<Item = IpAddr>, StaggeredError<DnsError>>

Perform an ipv6 lookup with a timeout in a staggered fashion.

From the moment this function is called, each lookup is scheduled after the delays in delays_ms with the first call being done immediately. [200ms, 300ms] results in calls at T+0ms, T+200ms and T+300ms. The timeout is applied to each call individually. The result of the first successful call is returned, or a summary of all errors otherwise.

-
Source

pub async fn lookup_ipv4_ipv6_staggered( +

Source

pub async fn lookup_ipv4_ipv6_staggered( &self, host: impl ToString, timeout: Duration, delays_ms: &[u64], -) -> Result<impl Iterator<Item = IpAddr>, DnsError>

Race an ipv4 and ipv6 lookup with a timeout in a staggered fashion.

+) -> Result<impl Iterator<Item = IpAddr>, StaggeredError<DnsError>>

Race an ipv4 and ipv6 lookup with a timeout in a staggered fashion.

From the moment this function is called, each lookup is scheduled after the delays in delays_ms with the first call being done immediately. [200ms, 300ms] results in calls at T+0ms, T+200ms and T+300ms. The timeout is applied as stated in Self::lookup_ipv4_ipv6. The result of the first successful call is returned, or a summary of all errors otherwise.

-
Source

pub async fn lookup_node_by_id( +

Source

pub async fn lookup_node_by_id( &self, - node_id: &NodeId, + node_id: &NodeId, origin: &str, -) -> Result<NodeInfo, LookupError>

Looks up node info by NodeId and origin domain name.

+) -> Result<NodeInfo, LookupError>

Looks up node info by [NodeId] and origin domain name.

To lookup nodes that published their node info to the DNS servers run by n0, pass N0_DNS_NODE_ORIGIN_PROD as origin.

-
Source

pub async fn lookup_node_by_domain_name( +

Source

pub async fn lookup_node_by_domain_name( &self, name: &str, ) -> Result<NodeInfo, LookupError>

Looks up node info by DNS name.

-
Source

pub async fn lookup_node_by_domain_name_staggered( +

Source

pub async fn lookup_node_by_domain_name_staggered( &self, name: &str, delays_ms: &[u64], -) -> Result<NodeInfo, Error>

Looks up node info by DNS name in a staggered fashion.

+) -> Result<NodeInfo, StaggeredError<LookupError>>

Looks up node info by DNS name in a staggered fashion.

From the moment this function is called, each lookup is scheduled after the delays in delays_ms with the first call being done immediately. [200ms, 300ms] results in calls at T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a summary of all errors otherwise.

-
Source

pub async fn lookup_node_by_id_staggered( +

Source

pub async fn lookup_node_by_id_staggered( &self, - node_id: &NodeId, + node_id: &NodeId, origin: &str, delays_ms: &[u64], -) -> Result<NodeInfo, Error>

Looks up node info by NodeId and origin domain name.

+) -> Result<NodeInfo, StaggeredError<LookupError>>

Looks up node info by [NodeId] and origin domain name.

From the moment this function is called, each lookup is scheduled after the delays in delays_ms with the first call being done immediately. [200ms, 300ms] results in calls at T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a summary of all errors otherwise.

-

Trait Implementations§

Source§

impl Clone for DnsResolver

Source§

fn clone(&self) -> DnsResolver

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DnsResolver

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for DnsResolver

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl From<Resolver<GenericConnector<TokioRuntimeProvider>>> for DnsResolver

Source§

fn from(resolver: TokioResolver) -> Self

Converts to this type from the input type.
Source§

impl Resolve for DnsResolver

Source§

fn resolve(&self, name: Name) -> Resolving

Performs DNS resolution on a Name. +

Trait Implementations§

Source§

impl Clone for DnsResolver

Source§

fn clone(&self) -> DnsResolver

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DnsResolver

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for DnsResolver

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl From<Resolver<GenericConnector<TokioRuntimeProvider>>> for DnsResolver

Source§

fn from(resolver: TokioResolver) -> Self

Converts to this type from the input type.
Source§

impl Resolve for DnsResolver

Source§

fn resolve(&self, name: Name) -> Resolving

Performs DNS resolution on a Name. The return type is a future containing an iterator of SocketAddr. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where diff --git a/pr/3327/docs/iroh_relay/dns/struct.Error.html b/pr/3327/docs/iroh_relay/dns/struct.StaggeredError.html similarity index 65% rename from pr/3327/docs/iroh_relay/dns/struct.Error.html rename to pr/3327/docs/iroh_relay/dns/struct.StaggeredError.html index 19c7b00e49..4bc23ebbfd 100644 --- a/pr/3327/docs/iroh_relay/dns/struct.Error.html +++ b/pr/3327/docs/iroh_relay/dns/struct.StaggeredError.html @@ -1,9 +1,12 @@ -Error in iroh_relay::dns - Rust

Struct Error

Source
pub struct Error { /* private fields */ }
Available on non-wasm_browser only.
Expand description

Error returned when an input value is too long for crate::node_info::UserData.

-

Trait Implementations§

Source§

impl Debug for Error

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Error

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Error for Error
where - Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl ErrorCompat for Error

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where +StaggeredError in iroh_relay::dns - Rust

Struct StaggeredError

Source
pub struct StaggeredError<E: Debug + Display> { /* private fields */ }
Available on non-wasm_browser only.
Expand description

Error returned when an input value is too long for crate::node_info::UserData.

+

Trait Implementations§

Source§

impl<E: Debug + Debug + Display> Debug for StaggeredError<E>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<E: Debug + Display> Display for StaggeredError<E>

Source§

fn fmt(&self, __snafu_display_formatter: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<E: Debug + Display> Error for StaggeredError<E>
where + Self: Debug + Display,

Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl<E: Debug + Display> ErrorCompat for StaggeredError<E>

Source§

fn backtrace(&self) -> Option<&Backtrace>

Returns a [Backtrace][] that may be printed.
§

fn iter_chain(&self) -> ChainCompat<'_, '_>
where Self: AsErrorSource,

Returns an iterator for traversing the chain of errors, starting with the current error -and continuing with recursive calls to Error::source. Read more

Auto Trait Implementations§

§

impl Freeze for Error

§

impl !RefUnwindSafe for Error

§

impl Send for Error

§

impl Sync for Error

§

impl Unpin for Error

§

impl !UnwindSafe for Error

Blanket Implementations§

Source§

impl<T> Any for T
where +and continuing with recursive calls to Error::source. Read more

Auto Trait Implementations§

§

impl<E> Freeze for StaggeredError<E>

§

impl<E> !RefUnwindSafe for StaggeredError<E>

§

impl<E> Send for StaggeredError<E>
where + E: Send,

§

impl<E> Sync for StaggeredError<E>
where + E: Sync,

§

impl<E> Unpin for StaggeredError<E>
where + E: Unpin,

§

impl<E> !UnwindSafe for StaggeredError<E>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AsErrorSource for T
where T: Error + 'static,

§

fn as_error_source(&self) -> &(dyn Error + 'static)

For maximum effectiveness, this needs to be called as a method to benefit from Rust’s automatic dereferencing of method diff --git a/pr/3327/docs/iroh_relay/dns/struct.TXT.html b/pr/3327/docs/iroh_relay/dns/struct.TXT.html index 8dbc61621a..e7b2bc8400 100644 --- a/pr/3327/docs/iroh_relay/dns/struct.TXT.html +++ b/pr/3327/docs/iroh_relay/dns/struct.TXT.html @@ -1,6 +1,6 @@ -TXT in iroh_relay::dns - Rust

Struct TXT

Source
pub struct TXT(/* private fields */);
Available on non-wasm_browser only.
Expand description

Record data for a TXT record

-

Implementations§

Source§

impl TXT

Source

pub fn txt_data(&self) -> &[Box<[u8]>]

Returns the raw character strings of this TXT record.

-

Trait Implementations§

Source§

impl Clone for TXT

Source§

fn clone(&self) -> TXT

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TXT

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for TXT

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for TXT

§

impl RefUnwindSafe for TXT

§

impl Send for TXT

§

impl Sync for TXT

§

impl Unpin for TXT

§

impl UnwindSafe for TXT

Blanket Implementations§

Source§

impl<T> Any for T
where +TXT in iroh_relay::dns - Rust

Struct TXT

Source
pub struct TXT(/* private fields */);
Available on non-wasm_browser only.
Expand description

Record data for a TXT record

+

Implementations§

Source§

impl TXT

Source

pub fn txt_data(&self) -> &[Box<[u8]>]

Returns the raw character strings of this TXT record.

+

Trait Implementations§

Source§

impl Clone for TXT

Source§

fn clone(&self) -> TXT

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TXT

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for TXT

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for TXT

§

impl RefUnwindSafe for TXT

§

impl Send for TXT

§

impl Sync for TXT

§

impl Unpin for TXT

§

impl UnwindSafe for TXT

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh_relay/dns/struct.TxtLookup.html b/pr/3327/docs/iroh_relay/dns/struct.TxtLookup.html index d9322b5a8d..f3f1f4d036 100644 --- a/pr/3327/docs/iroh_relay/dns/struct.TxtLookup.html +++ b/pr/3327/docs/iroh_relay/dns/struct.TxtLookup.html @@ -1,5 +1,5 @@ -TxtLookup in iroh_relay::dns - Rust

Struct TxtLookup

Source
pub struct TxtLookup(/* private fields */);
Available on non-wasm_browser only.
Expand description

TXT records returned from DnsResolver::lookup_txt

-

Trait Implementations§

Source§

impl Clone for TxtLookup

Source§

fn clone(&self) -> TxtLookup

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TxtLookup

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<TxtLookup> for TxtLookup

Source§

fn from(value: TxtLookup) -> Self

Converts to this type from the input type.
Source§

impl IntoIterator for TxtLookup

Source§

type Item = TXT

The type of the elements being iterated over.
Source§

type IntoIter = Box<dyn Iterator<Item = TXT>>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +TxtLookup in iroh_relay::dns - Rust

Struct TxtLookup

Source
pub struct TxtLookup(/* private fields */);
Available on non-wasm_browser only.
Expand description

TXT records returned from DnsResolver::lookup_txt

+

Trait Implementations§

Source§

impl Clone for TxtLookup

Source§

fn clone(&self) -> TxtLookup

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for TxtLookup

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<TxtLookup> for TxtLookup

Source§

fn from(value: TxtLookup) -> Self

Converts to this type from the input type.
Source§

impl IntoIterator for TxtLookup

Source§

type Item = TXT

The type of the elements being iterated over.
Source§

type IntoIter = Box<dyn Iterator<Item = TXT>>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3327/docs/iroh_relay/index.html b/pr/3327/docs/iroh_relay/index.html index 5b1f8aca6e..a4c2940432 100644 --- a/pr/3327/docs/iroh_relay/index.html +++ b/pr/3327/docs/iroh_relay/index.html @@ -25,6 +25,6 @@ Tailscale.

STUN support and expose metrics.

-

Re-exports§

pub use protos::relay::MAX_PACKET_SIZE;

Modules§

client
Exposes Client, which allows to establish connections to a relay server.
defaults
Default values used in the relay.
dnsNon-wasm_browser
DNS resolver
http
HTTP-specific constants for the relay server and client.
node_info
Support for handling DNS resource records for dialing by NodeId.
protos
Protocols used by the iroh-relay
quic
Create a QUIC server that accepts connections +

Re-exports§

pub use protos::relay::MAX_PACKET_SIZE;

Modules§

client
Exposes Client, which allows to establish connections to a relay server.
defaults
Default values used in the relay.
dnsNon-wasm_browser
DNS resolver
http
HTTP-specific constants for the relay server and client.
node_info
Support for handling DNS resource records for dialing by [NodeId].
protos
Protocols used by the iroh-relay
quic
Create a QUIC server that accepts connections for QUIC address discovery.
serverserver
A fully-fledged iroh-relay server over HTTP or HTTPS.

Structs§

PingTracker
Tracks pings on a single relay connection.
RelayMap
Configuration of all the relay servers that can be used.
RelayNode
Information on a specific relay server.
RelayQuicConfig
Configuration for speaking to the QUIC endpoint on the relay server to do QUIC address discovery.
\ No newline at end of file diff --git a/pr/3327/docs/iroh_relay/node_info/index.html b/pr/3327/docs/iroh_relay/node_info/index.html index 7c44a3876d..00c61b2d49 100644 --- a/pr/3327/docs/iroh_relay/node_info/index.html +++ b/pr/3327/docs/iroh_relay/node_info/index.html @@ -1,5 +1,5 @@ -iroh_relay::node_info - Rust

Module node_info

Source
Expand description

Support for handling DNS resource records for dialing by NodeId.

-

Dialing by NodeId is supported by iroh nodes publishing Pkarr records to DNS +iroh_relay::node_info - Rust

Module node_info

Source
Expand description

Support for handling DNS resource records for dialing by [NodeId].

+

Dialing by [NodeId] is supported by iroh nodes publishing Pkarr records to DNS servers or the Mainline DHT. This module supports creating and parsing these records.

DNS records are published under the following names:

_iroh.<z32-node-id>.<origin-domain> TXT

@@ -8,7 +8,7 @@ servers or the Mainline DHT. This module supports creating and parsing these re

_iroh is the record name as defined by IROH_TXT_NAME.

  • -

    <z32-node-id> is the z-base-32 encoding of the NodeId.

    +

    <z32-node-id> is the z-base-32 encoding of the [NodeId].

  • <origin-domain> is the domain name of the publishing DNS server, @@ -23,12 +23,12 @@ servers or the Mainline DHT. This module supports creating and parsing these re in RFC1464. The following attributes are defined:

    • -

      relay=<url>: The home RelayUrl of this node.

      +

      relay=<url>: The home RelayUrl of this node.

    • addr=<addr> <addr>: A space-separated list of sockets addresses for this iroh node. Each address is an IPv4 or IPv6 address with a port.

    -
  • Structs§

    MaxLengthExceededError
    Error returned when an input value is too long for UserData.
    NodeData
    Data about a node that may be published to and resolved from discovery services.
    NodeInfo
    Information about a node that may be published to and resolved from discovery services.
    UserData
    Under the hood this is a UTF-8 String is no longer than UserData::MAX_LENGTH bytes.

    Enums§

    DecodingError
    EncodingError
    LookupErrorNon-wasm_browser
    ParseError

    Constants§

    IROH_TXT_NAME
    The DNS name for the iroh TXT record.

    Traits§

    NodeIdExt
    Extension methods for NodeId to encode to and decode from [z32], +

    Structs§

    MaxLengthExceededError
    Error returned when an input value is too long for UserData.
    NodeData
    Data about a node that may be published to and resolved from discovery services.
    NodeInfo
    Information about a node that may be published to and resolved from discovery services.
    UserData
    Under the hood this is a UTF-8 String is no longer than UserData::MAX_LENGTH bytes.

    Enums§

    DecodingError
    EncodingError
    LookupErrorNon-wasm_browser
    ParseError

    Constants§

    IROH_TXT_NAME
    The DNS name for the iroh TXT record.

    Traits§

    NodeIdExt
    Extension methods for [NodeId] to encode to and decode from [z32], which is the encoding used in [pkarr] domain names.
    \ No newline at end of file diff --git a/pr/3327/docs/iroh_relay/node_info/struct.NodeData.html b/pr/3327/docs/iroh_relay/node_info/struct.NodeData.html index 238c3986d7..8315d3cd78 100644 --- a/pr/3327/docs/iroh_relay/node_info/struct.NodeData.html +++ b/pr/3327/docs/iroh_relay/node_info/struct.NodeData.html @@ -1,20 +1,20 @@ NodeData in iroh_relay::node_info - Rust

    Struct NodeData

    Source
    pub struct NodeData { /* private fields */ }
    Expand description

    Data about a node that may be published to and resolved from discovery services.

    -

    This includes an optional RelayUrl, a set of direct addresses, and the optional +

    This includes an optional [RelayUrl], a set of direct addresses, and the optional UserData, a string that can be set by applications and is not parsed or used by iroh itself.

    -

    This struct does not include the node’s NodeId, only the data about a certain -node. See NodeInfo for a struct that contains a NodeId with associated NodeData.

    +

    This struct does not include the node’s [NodeId], only the data about a certain +node. See NodeInfo for a struct that contains a [NodeId] with associated NodeData.

    Implementations§

    Source§

    impl NodeData

    Source

    pub fn new( - relay_url: Option<RelayUrl>, + relay_url: Option<RelayUrl>, direct_addresses: BTreeSet<SocketAddr>, ) -> Self

    Creates a new NodeData with a relay URL and a set of direct addresses.

    -
    Source

    pub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self

    Sets the relay URL and returns the updated node data.

    +
    Source

    pub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self

    Sets the relay URL and returns the updated node data.

    Source

    pub fn with_direct_addresses( self, direct_addresses: BTreeSet<SocketAddr>, ) -> Self

    Sets the direct addresses and returns the updated node data.

    Source

    pub fn with_user_data(self, user_data: Option<UserData>) -> Self

    Sets the user-defined data and returns the updated node data.

    -
    Source

    pub fn relay_url(&self) -> Option<&RelayUrl>

    Returns the relay URL of the node.

    +
    Source

    pub fn relay_url(&self) -> Option<&RelayUrl>

    Returns the relay URL of the node.

    Source

    pub fn user_data(&self) -> Option<&UserData>

    Returns the optional user-defined data of the node.

    Source

    pub fn direct_addresses(&self) -> &BTreeSet<SocketAddr>

    Returns the direct addresses of the node.

    Source

    pub fn clear_direct_addresses(&mut self)

    Removes all direct addresses from the node data.

    @@ -22,9 +22,9 @@ node. See IntoIterator<Item = SocketAddr>, )

    Adds direct addresses to the node data.

    -
    Source

    pub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)

    Sets the relay URL of the node data.

    +
    Source

    pub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)

    Sets the relay URL of the node data.

    Source

    pub fn set_user_data(&mut self, user_data: Option<UserData>)

    Sets the user-defined data of the node data.

    -

    Trait Implementations§

    Source§

    impl Clone for NodeData

    Source§

    fn clone(&self) -> NodeData

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for NodeData

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl Default for NodeData

    Source§

    fn default() -> NodeData

    Returns the “default value” for a type. Read more
    Source§

    impl From<NodeAddr> for NodeData

    Source§

    fn from(node_addr: NodeAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for NodeData

    Source§

    fn eq(&self, other: &NodeData) -> bool

    Tests for self and other values to be equal, and is used by ==.
    1.0.0 · Source§

    fn ne(&self, other: &Rhs) -> bool

    Tests for !=. The default implementation is almost always sufficient, +

    Trait Implementations§

    Source§

    impl Clone for NodeData

    Source§

    fn clone(&self) -> NodeData

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for NodeData

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl Default for NodeData

    Source§

    fn default() -> NodeData

    Returns the “default value” for a type. Read more
    Source§

    impl From<NodeAddr> for NodeData

    Source§

    fn from(node_addr: NodeAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for NodeData

    Source§

    fn eq(&self, other: &NodeData) -> bool

    Tests for self and other values to be equal, and is used by ==.
    1.0.0 · Source§

    fn ne(&self, other: &Rhs) -> bool

    Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
    Source§

    impl Eq for NodeData

    Source§

    impl StructuralPartialEq for NodeData

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where T: 'static + ?Sized,

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

    impl<'a, T, E> AsTaggedExplicit<'a, E> for T
    where T: 'a,

    §

    fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3327/docs/iroh_relay/node_info/struct.NodeInfo.html b/pr/3327/docs/iroh_relay/node_info/struct.NodeInfo.html index 62193891d4..3009617365 100644 --- a/pr/3327/docs/iroh_relay/node_info/struct.NodeInfo.html +++ b/pr/3327/docs/iroh_relay/node_info/struct.NodeInfo.html @@ -1,32 +1,32 @@ NodeInfo in iroh_relay::node_info - Rust

    Struct NodeInfo

    Source
    pub struct NodeInfo {
    -    pub node_id: NodeId,
    +    pub node_id: NodeId,
         pub data: NodeData,
     }
    Expand description

    Information about a node that may be published to and resolved from discovery services.

    -

    This struct couples a NodeId with its associated NodeData.

    -

    Fields§

    §node_id: NodeId

    The NodeId of the node this is about.

    +

    This struct couples a [NodeId] with its associated NodeData.

    +

    Fields§

    §node_id: NodeId

    The [NodeId] of the node this is about.

    §data: NodeData

    The information published about the node.

    -

    Implementations§

    Source§

    impl NodeInfo

    Source

    pub fn new(node_id: NodeId) -> Self

    Creates a new NodeInfo with an empty NodeData.

    -
    Source

    pub fn from_parts(node_id: NodeId, data: NodeData) -> Self

    Creates a new NodeInfo from its parts.

    -
    Source

    pub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self

    Sets the relay URL and returns the updated node info.

    +

    Implementations§

    Source§

    impl NodeInfo

    Source

    pub fn new(node_id: NodeId) -> Self

    Creates a new NodeInfo with an empty NodeData.

    +
    Source

    pub fn from_parts(node_id: NodeId, data: NodeData) -> Self

    Creates a new NodeInfo from its parts.

    +
    Source

    pub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self

    Sets the relay URL and returns the updated node info.

    Source

    pub fn with_direct_addresses( self, direct_addresses: BTreeSet<SocketAddr>, ) -> Self

    Sets the direct addresses and returns the updated node info.

    Source

    pub fn with_user_data(self, user_data: Option<UserData>) -> Self

    Sets the user-defined data and returns the updated node info.

    -
    Source

    pub fn to_node_addr(&self) -> NodeAddr

    Converts into a NodeAddr by cloning the needed fields.

    -
    Source

    pub fn into_node_addr(self) -> NodeAddr

    Converts into a NodeAddr without cloning.

    +
    Source

    pub fn to_node_addr(&self) -> NodeAddr

    Converts into a [NodeAddr] by cloning the needed fields.

    +
    Source

    pub fn into_node_addr(self) -> NodeAddr

    Converts into a [NodeAddr] without cloning.

    Source

    pub fn from_txt_lookup(lookup: TxtLookup) -> Result<Self, ParseError>

    Available on non-wasm_browser only.

    Parses a NodeInfo from a TXT records lookup.

    Source

    pub fn from_pkarr_signed_packet( packet: &SignedPacket, ) -> Result<Self, ParseError>

    Parses a NodeInfo from a [pkarr::SignedPacket].

    Source

    pub fn to_pkarr_signed_packet( &self, - secret_key: &SecretKey, + secret_key: &SecretKey, ttl: u32, ) -> Result<SignedPacket, EncodingError>

    Creates a [pkarr::SignedPacket].

    -

    This constructs a DNS packet and signs it with a SecretKey.

    +

    This constructs a DNS packet and signs it with a [SecretKey].

    Source

    pub fn to_txt_strings(&self) -> Vec<String>

    Converts into a list of {key}={value} strings.

    -

    Methods from Deref<Target = NodeData>§

    Source

    pub fn relay_url(&self) -> Option<&RelayUrl>

    Returns the relay URL of the node.

    +

    Methods from Deref<Target = NodeData>§

    Source

    pub fn relay_url(&self) -> Option<&RelayUrl>

    Returns the relay URL of the node.

    Source

    pub fn user_data(&self) -> Option<&UserData>

    Returns the optional user-defined data of the node.

    Source

    pub fn direct_addresses(&self) -> &BTreeSet<SocketAddr>

    Returns the direct addresses of the node.

    Source

    pub fn clear_direct_addresses(&mut self)

    Removes all direct addresses from the node data.

    @@ -34,9 +34,9 @@ &mut self, addrs: impl IntoIterator<Item = SocketAddr>, )

    Adds direct addresses to the node data.

    -
    Source

    pub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)

    Sets the relay URL of the node data.

    +
    Source

    pub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)

    Sets the relay URL of the node data.

    Source

    pub fn set_user_data(&mut self, user_data: Option<UserData>)

    Sets the user-defined data of the node data.

    -

    Trait Implementations§

    Source§

    impl Clone for NodeInfo

    Source§

    fn clone(&self) -> NodeInfo

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for NodeInfo

    Source§

    fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl Deref for NodeInfo

    Source§

    type Target = NodeData

    The resulting type after dereferencing.
    Source§

    fn deref(&self) -> &Self::Target

    Dereferences the value.
    Source§

    impl DerefMut for NodeInfo

    Source§

    fn deref_mut(&mut self) -> &mut Self::Target

    Mutably dereferences the value.
    Source§

    impl From<NodeAddr> for NodeInfo

    Source§

    fn from(addr: NodeAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl From<NodeInfo> for NodeAddr

    Source§

    fn from(value: NodeInfo) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for NodeInfo

    Source§

    fn eq(&self, other: &NodeInfo) -> bool

    Tests for self and other values to be equal, and is used by ==.
    1.0.0 · Source§

    fn ne(&self, other: &Rhs) -> bool

    Tests for !=. The default implementation is almost always sufficient, +

    Trait Implementations§

    Source§

    impl Clone for NodeInfo

    Source§

    fn clone(&self) -> NodeInfo

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for NodeInfo

    Source§

    fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl Deref for NodeInfo

    Source§

    type Target = NodeData

    The resulting type after dereferencing.
    Source§

    fn deref(&self) -> &Self::Target

    Dereferences the value.
    Source§

    impl DerefMut for NodeInfo

    Source§

    fn deref_mut(&mut self) -> &mut Self::Target

    Mutably dereferences the value.
    Source§

    impl From<NodeAddr> for NodeInfo

    Source§

    fn from(addr: NodeAddr) -> Self

    Converts to this type from the input type.
    Source§

    impl From<NodeInfo> for NodeAddr

    Source§

    fn from(value: NodeInfo) -> Self

    Converts to this type from the input type.
    Source§

    impl PartialEq for NodeInfo

    Source§

    fn eq(&self, other: &NodeInfo) -> bool

    Tests for self and other values to be equal, and is used by ==.
    1.0.0 · Source§

    fn ne(&self, other: &Rhs) -> bool

    Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
    Source§

    impl Eq for NodeInfo

    Source§

    impl StructuralPartialEq for NodeInfo

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where T: 'static + ?Sized,

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

    impl<'a, T, E> AsTaggedExplicit<'a, E> for T
    where T: 'a,

    §

    fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3327/docs/iroh_relay/node_info/trait.NodeIdExt.html b/pr/3327/docs/iroh_relay/node_info/trait.NodeIdExt.html index 19265ef095..e60ccd0737 100644 --- a/pr/3327/docs/iroh_relay/node_info/trait.NodeIdExt.html +++ b/pr/3327/docs/iroh_relay/node_info/trait.NodeIdExt.html @@ -1,9 +1,9 @@ NodeIdExt in iroh_relay::node_info - Rust

    Trait NodeIdExt

    Source
    pub trait NodeIdExt {
         // Required methods
         fn to_z32(&self) -> String;
    -    fn from_z32(s: &str) -> Result<NodeId, DecodingError>;
    -}
    Expand description

    Extension methods for NodeId to encode to and decode from [z32], + fn from_z32(s: &str) -> Result<NodeId, DecodingError>; +}

    Expand description

    Extension methods for [NodeId] to encode to and decode from [z32], which is the encoding used in [pkarr] domain names.

    -

    Required Methods§

    Source

    fn to_z32(&self) -> String

    Encodes a NodeId in [z-base-32] encoding.

    -
    Source

    fn from_z32(s: &str) -> Result<NodeId, DecodingError>

    Parses a NodeId from [z-base-32] encoding.

    -

    Dyn Compatibility§

    This trait is not dyn compatible.

    In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

    Implementations on Foreign Types§

    Source§

    impl NodeIdExt for NodeId

    Implementors§

    \ No newline at end of file +

    Required Methods§

    Source

    fn to_z32(&self) -> String

    Encodes a [NodeId] in [z-base-32] encoding.

    +
    Source

    fn from_z32(s: &str) -> Result<NodeId, DecodingError>

    Parses a [NodeId] from [z-base-32] encoding.

    +

    Dyn Compatibility§

    This trait is not dyn compatible.

    In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

    Implementations on Foreign Types§

    Source§

    impl NodeIdExt for NodeId

    Implementors§

    \ No newline at end of file diff --git a/pr/3327/docs/iroh_relay/quic/index.html b/pr/3327/docs/iroh_relay/quic/index.html index 5b2dc36302..9cf8efb7bf 100644 --- a/pr/3327/docs/iroh_relay/quic/index.html +++ b/pr/3327/docs/iroh_relay/quic/index.html @@ -1,3 +1,3 @@ -iroh_relay::quic - Rust

    Module quic

    Source
    Expand description

    Create a QUIC server that accepts connections +iroh_relay::quic - Rust

    Module quic

    Source
    Expand description

    Create a QUIC server that accepts connections for QUIC address discovery.

    Structs§

    QuicClient
    Handles the client side of QUIC address discovery.

    Enums§

    Error
    Quic client related errors.

    Constants§

    ALPN_QUIC_ADDR_DISC
    ALPN for our quic addr discovery
    QUIC_ADDR_DISC_CLOSE_CODE
    Endpoint close error code
    QUIC_ADDR_DISC_CLOSE_REASON
    Endpoint close reason
    \ No newline at end of file diff --git a/pr/3327/docs/iroh_relay/server/enum.AccessConfig.html b/pr/3327/docs/iroh_relay/server/enum.AccessConfig.html index d23a81bd37..bb46abbe03 100644 --- a/pr/3327/docs/iroh_relay/server/enum.AccessConfig.html +++ b/pr/3327/docs/iroh_relay/server/enum.AccessConfig.html @@ -1,10 +1,10 @@ AccessConfig in iroh_relay::server - Rust

    Enum AccessConfig

    Source
    pub enum AccessConfig {
         Everyone,
    -    Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>),
    +    Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>),
     }
    Available on crate feature server only.
    Expand description

    Controls which nodes are allowed to use the relay.

    Variants§

    §

    Everyone

    Everyone

    -
    §

    Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>)

    Only nodes for which the function returns Access::Allow.

    -

    Implementations§

    Source§

    impl AccessConfig

    Source

    pub async fn is_allowed(&self, node: NodeId) -> bool

    Is this node allowed?

    +
    §

    Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>)

    Only nodes for which the function returns Access::Allow.

    +

    Implementations§

    Source§

    impl AccessConfig

    Source

    pub async fn is_allowed(&self, node: NodeId) -> bool

    Is this node allowed?

    Trait Implementations§

    Source§

    impl Debug for AccessConfig

    Source§

    fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more

    Auto Trait Implementations§

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where T: 'static + ?Sized,

    Source§

    fn type_id(&self) -> TypeId

    Gets the TypeId of self. Read more
    §

    impl<'a, T, E> AsTaggedExplicit<'a, E> for T
    where T: 'a,

    §

    fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

    §

    impl<'a, T, E> AsTaggedImplicit<'a, E> for T
    where diff --git a/pr/3327/docs/iroh_relay/server/struct.Server.html b/pr/3327/docs/iroh_relay/server/struct.Server.html index 4b30f61650..095b81c3bc 100644 --- a/pr/3327/docs/iroh_relay/server/struct.Server.html +++ b/pr/3327/docs/iroh_relay/server/struct.Server.html @@ -18,9 +18,9 @@ case there is an error in the server before it is shut down.

    Source

    pub fn quic_addr(&self) -> Option<SocketAddr>

    The socket address the QUIC server is listening on.

    Source

    pub fn stun_addr(&self) -> Option<SocketAddr>

    The socket address the STUN server is listening on.

    Source

    pub fn certificates(&self) -> Option<Vec<CertificateDer<'static>>>

    The certificates chain if configured with manual TLS certificates.

    -
    Source

    pub fn https_url(&self) -> Option<RelayUrl>

    Available on crate feature test-utils only.

    Get the server’s https RelayUrl.

    +
    Source

    pub fn https_url(&self) -> Option<RelayUrl>

    Available on crate feature test-utils only.

    Get the server’s https [RelayUrl].

    This uses Self::https_addr so it’s mostly useful for local development.

    -
    Source

    pub fn http_url(&self) -> Option<RelayUrl>

    Available on crate feature test-utils only.

    Get the server’s http RelayUrl.

    +
    Source

    pub fn http_url(&self) -> Option<RelayUrl>

    Available on crate feature test-utils only.

    Get the server’s http [RelayUrl].

    This uses Self::http_addr so it’s mostly useful for local development.

    Source

    pub fn metrics(&self) -> &RelayMetrics

    Returns the metrics collected in the relay server.

    Trait Implementations§

    Source§

    impl Debug for Server

    Source§

    fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more

    Auto Trait Implementations§

    §

    impl Freeze for Server

    §

    impl RefUnwindSafe for Server

    §

    impl Send for Server

    §

    impl Sync for Server

    §

    impl Unpin for Server

    §

    impl UnwindSafe for Server

    Blanket Implementations§

    Source§

    impl<T> Any for T
    where diff --git a/pr/3327/docs/iroh_relay/struct.RelayMap.html b/pr/3327/docs/iroh_relay/struct.RelayMap.html index 66406bee10..0c33630093 100644 --- a/pr/3327/docs/iroh_relay/struct.RelayMap.html +++ b/pr/3327/docs/iroh_relay/struct.RelayMap.html @@ -1,15 +1,15 @@ RelayMap in iroh_relay - Rust

    Struct RelayMap

    Source
    pub struct RelayMap { /* private fields */ }
    Expand description

    Configuration of all the relay servers that can be used.

    -

    Implementations§

    Source§

    impl RelayMap

    Source

    pub fn urls(&self) -> impl Iterator<Item = &RelayUrl>

    Returns the sorted relay URLs.

    +

    Implementations§

    Source§

    impl RelayMap

    Source

    pub fn urls(&self) -> impl Iterator<Item = &RelayUrl>

    Returns the sorted relay URLs.

    Source

    pub fn empty() -> Self

    Create an empty relay map.

    Source

    pub fn nodes(&self) -> impl Iterator<Item = &Arc<RelayNode>>

    Returns an Iterator over all known nodes.

    -
    Source

    pub fn contains_node(&self, url: &RelayUrl) -> bool

    Is this a known node?

    -
    Source

    pub fn get_node(&self, url: &RelayUrl) -> Option<&Arc<RelayNode>>

    Get the given node.

    +
    Source

    pub fn contains_node(&self, url: &RelayUrl) -> bool

    Is this a known node?

    +
    Source

    pub fn get_node(&self, url: &RelayUrl) -> Option<&Arc<RelayNode>>

    Get the given node.

    Source

    pub fn len(&self) -> usize

    How many nodes are known?

    Source

    pub fn is_empty(&self) -> bool

    Are there any nodes in this map?

    -

    Trait Implementations§

    Source§

    impl Clone for RelayMap

    Source§

    fn clone(&self) -> RelayMap

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for RelayMap

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl Display for RelayMap

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl From<RelayNode> for RelayMap

    Source§

    fn from(value: RelayNode) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayMap

    Source§

    fn from(value: RelayUrl) -> Self

    Creates a RelayMap from a RelayUrl.

    +

    Trait Implementations§

    Source§

    impl Clone for RelayMap

    Source§

    fn clone(&self) -> RelayMap

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for RelayMap

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl Display for RelayMap

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl From<RelayNode> for RelayMap

    Source§

    fn from(value: RelayNode) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayMap

    Source§

    fn from(value: RelayUrl) -> Self

    Creates a RelayMap from a [RelayUrl].

    The RelayNodes in the RelayMap will have the default STUN and QUIC address discovery ports.

    -
    Source§

    impl FromIterator<RelayNode> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayNode>>(iter: T) -> Self

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayUrl> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayUrl>>(iter: T) -> Self

    Creates a RelayMap from an iterator of RelayUrl.

    +
    Source§

    impl FromIterator<RelayNode> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayNode>>(iter: T) -> Self

    Creates a value from an iterator. Read more
    Source§

    impl FromIterator<RelayUrl> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayUrl>>(iter: T) -> Self

    Creates a RelayMap from an iterator of [RelayUrl].

    The RelayNodes in the RelayMap will have the default STUN and QUIC address discovery ports.

    Source§

    impl PartialEq for RelayMap

    Source§

    fn eq(&self, other: &RelayMap) -> bool

    Tests for self and other values to be equal, and is used by ==.
    1.0.0 · Source§

    fn ne(&self, other: &Rhs) -> bool

    Tests for !=. The default implementation is almost always sufficient, diff --git a/pr/3327/docs/iroh_relay/struct.RelayNode.html b/pr/3327/docs/iroh_relay/struct.RelayNode.html index 7690812c63..9c9fd26a54 100644 --- a/pr/3327/docs/iroh_relay/struct.RelayNode.html +++ b/pr/3327/docs/iroh_relay/struct.RelayNode.html @@ -1,11 +1,11 @@ RelayNode in iroh_relay - Rust

    Struct RelayNode

    Source
    pub struct RelayNode {
    -    pub url: RelayUrl,
    +    pub url: RelayUrl,
         pub stun_only: bool,
         pub stun_port: u16,
         pub quic: Option<RelayQuicConfig>,
     }
    Expand description

    Information on a specific relay server.

    Includes the Url where it can be dialed.

    -

    Fields§

    §url: RelayUrl

    The RelayUrl where this relay server can be dialed.

    +

    Fields§

    §url: RelayUrl

    The [RelayUrl] where this relay server can be dialed.

    §stun_only: bool

    Whether this relay server should only be used for STUN requests.

    This essentially allows you to use a normal STUN server as a relay node, no relay functionality is used.

    @@ -15,7 +15,7 @@ functionality is used.

    When None, we will not attempt to do QUIC address discovery with this relay server.

    Trait Implementations§

    Source§

    impl Clone for RelayNode

    Source§

    fn clone(&self) -> RelayNode

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    Source§

    impl Debug for RelayNode

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl<'de> Deserialize<'de> for RelayNode

    Source§

    fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
    where - __D: Deserializer<'de>,

    Deserialize this value from the given Serde deserializer. Read more
    Source§

    impl Display for RelayNode

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl From<RelayNode> for RelayMap

    Source§

    fn from(value: RelayNode) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayNode

    Source§

    fn from(value: RelayUrl) -> Self

    Converts to this type from the input type.
    Source§

    impl FromIterator<RelayNode> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayNode>>(iter: T) -> Self

    Creates a value from an iterator. Read more
    Source§

    impl Ord for RelayNode

    Source§

    fn cmp(&self, other: &RelayNode) -> Ordering

    This method returns an Ordering between self and other. Read more
    1.21.0 · Source§

    fn max(self, other: Self) -> Self
    where + __D: Deserializer<'de>,

    Deserialize this value from the given Serde deserializer. Read more
    Source§

    impl Display for RelayNode

    Source§

    fn fmt(&self, f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    Source§

    impl From<RelayNode> for RelayMap

    Source§

    fn from(value: RelayNode) -> Self

    Converts to this type from the input type.
    Source§

    impl From<RelayUrl> for RelayNode

    Source§

    fn from(value: RelayUrl) -> Self

    Converts to this type from the input type.
    Source§

    impl FromIterator<RelayNode> for RelayMap

    Source§

    fn from_iter<T: IntoIterator<Item = RelayNode>>(iter: T) -> Self

    Creates a value from an iterator. Read more
    Source§

    impl Ord for RelayNode

    Source§

    fn cmp(&self, other: &RelayNode) -> Ordering

    This method returns an Ordering between self and other. Read more
    1.21.0 · Source§

    fn max(self, other: Self) -> Self
    where Self: Sized,

    Compares and returns the maximum of two values. Read more
    1.21.0 · Source§

    fn min(self, other: Self) -> Self
    where Self: Sized,

    Compares and returns the minimum of two values. Read more
    1.50.0 · Source§

    fn clamp(self, min: Self, max: Self) -> Self
    where Self: Sized,

    Restrict a value to a certain interval. Read more
    Source§

    impl PartialEq for RelayNode

    Source§

    fn eq(&self, other: &RelayNode) -> bool

    Tests for self and other values to be equal, and is used by ==.
    1.0.0 · Source§

    fn ne(&self, other: &Rhs) -> bool

    Tests for !=. The default implementation is almost always sufficient, diff --git a/pr/3327/docs/search-index.js b/pr/3327/docs/search-index.js index 94ebb996eb..1d174bbeb6 100644 --- a/pr/3327/docs/search-index.js +++ b/pr/3327/docs/search-index.js @@ -1,4 +1,4 @@ -var searchIndex = new Map(JSON.parse('[["bulk",{"t":"HHHHH","n":["collect_and_print","main","run_iroh","run_quinn","run_s2n"],"q":[[0,"bulk"],[5,"iroh_metrics::base"],[6,"iroh_bench"],[7,"n0_snafu::error"],[8,"iroh_bench::s2n"]],"i":"`````","f":"{{{d{b}}{d{f}}}h}{{}h}{j{{l{h}}}}0{n{{l{h}}}}","D":"`","p":[[1,"str"],[1,"reference",null,null,1],[10,"MetricsGroup",5],[1,"unit"],[5,"Opt",6],[8,"Result",7],[5,"Opt",8]],"r":[],"b":[],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAAUAAQAAAAUA","P":[]}],["iroh",{"t":"PPEPGTFIFPFEFGFFFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNOCCNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCCNOCNNNNNNCNNONONNNNNNNNNOOCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNCNNOOOOOOOOSSSSSCCSSSHHHHSSHHHPFPKFGFKGFTPPFPFPPGPPPPPFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNCNNNNNONNCNNNNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOFFSSNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFFSNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNSSPPPPSSGFFFFFPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOFFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNTFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFSSNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNTTFFFFPGKPGPFPGFTTTPFPFPPPGFGFFPFPGPPPPPPFGGKKFKPPPFFGPPPPPPSPPFFTTTPFGKTTPFFTPPTTPPFTTPPPIPFFPTGFPPPPPFGPGGFPPGPFFPPGFTTPPGFFGPPGFPPTPPPFFPFPFPPPPFFPFGFFPPPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONONNNOOOMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNOOONNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNONNONOONOOOONNNONNNNNNNNNNNNNNNNNHNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNHOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNONNNNNNOOONOOONOOONNNONNNOOONNNNNNNNNNOONNOOONMNMNMNNNNNNNOOONNNONNNNNNNNNNNNNNNNNNNNNNNNNNOOONNNNNNNONNNNNNNOONMNNONMNNNNNNOONNNNNNNNNNNNNNNNNNNNNNNNNNNONMNNONOONOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOONNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOFFEFFNOOOOOOOOONNNNNNNNNNNOONNNNNNNNNNNNNNNOOONNNNNNNNNNNNNNNOOOONNNNONNNNNNNNNNONNNNNONNNNNNNNNNOOOONNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNOOOOOOONNNNOPPFPFFFFFFGNNNNNNNNNHNNNNNNNNNNNNNNNNONONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOONNNOONNNNNNNNNNNNNNNNNOOOOOONOONNOOONNOOOOONNOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNOOOOOOOPGPGPSPPPPPGPFFKFPPGPPFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNONNNNNNNNMNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOFPPGKPFFPNNMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOFFNNNNNNNNNNNNNNNNNNNNNNNNNNOONONHHHNNNNNNNNNFFFFFFRFKNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN","n":["Decode","DecodeInvalidLength","Endpoint","Key","KeyParsingError","LENGTH","NodeAddr","NodeId","PublicKey","Relay","RelayMap","RelayMode","RelayNode","RelayProtocol","RelayUrl","RelayUrlParseError","SecretKey","Websocket","__clone_box","","","","","","","as_bytes","as_error_source","","as_ref","backtrace","","borrow","","","","","","","","","","borrow_mut","","","","","","","","","cause","","clone","","","","","","","clone_into","","","","","","","clone_to_uninit","","","","","","","cmp","","","","compare","","","","compat","","","","","","","","","compat_mut","","","","","","","","","compat_ref","","","","","","","","","contains_node","default","defaults","deref","","","","","","","","","","deref_mut","","","","","","","","","description","","deserialize","","","","","direct_addresses","","discovery","dns","drop","","","","","","","","","empty","endpoint","eq","","","","","","equivalent","","","","","","","","","","","","","","","","","","fmt","","","","","","","","","","","","","","","","fmt_short","from","","","","","","","","","","","","","","","","","","","","","","","from_bytes","","from_iter","","from_parts","from_ref","","","","","","","from_str","","","from_z32","generate","get_node","hash","","in_current_span","","init","","","","","","","","","into","","","","","","","","","is_empty","","len","metrics","net_report","new","node_id","node_info","nodes","parse_header","partial_cmp","","","","protocol","public","","quic","relay_url","","secret","serialize","","","","","sign","source","","stun_only","stun_port","test_utils","to_bytes","to_owned","","","","","","","to_string","","","","","","","to_z32","try_from","","","","","","","","","","","","try_into","","","","","","","","","type_id","","","","","","","","","upgrade_header","url","urls","verify","vzip","","","","","","","","","watcher","with_direct_addresses","with_relay_url","backtrace","","","source","","span_trace","","","DEFAULT_HTTPS_PORT","DEFAULT_HTTP_PORT","DEFAULT_METRICS_PORT","DEFAULT_RELAY_QUIC_PORT","DEFAULT_STUN_PORT","prod","staging","AP_RELAY_HOSTNAME","EU_RELAY_HOSTNAME","NA_RELAY_HOSTNAME","default_ap_relay_node","default_eu_relay_node","default_na_relay_node","default_relay_map","EU_RELAY_HOSTNAME","NA_RELAY_HOSTNAME","default_eu_relay_node","default_na_relay_node","default_relay_map","AttrFromString","ConcurrentDiscovery","DecodingError","Discovery","DiscoveryContext","DiscoveryError","DiscoveryItem","IntoDiscovery","IntoDiscoveryError","Lagged","MAX_LENGTH","NoResults","NoServiceConfigured","NodeData","NodeId","NodeInfo","NotAnIrohRecord","NumLabels","ParseError","ParsePacket","SignedPacket","UnexpectedFormat","User","","UserData","Utf8","__clone_box","","","","add","add_direct_addresses","as_error_source","","","","as_ref","backtrace","","","","borrow","","","","","","","","","","borrow_mut","","","","","","","","","","cause","","","","clear_direct_addresses","clone","","","","clone_into","","","","clone_to_uninit","","","","cmp","compare","compat","","","","","","","","","","compat_mut","","","","","","","","","","compat_ref","","","","","","","","","","data","default","","deref","","","","","","","","","","","","deref_mut","","","","","","","","","","","description","","","","direct_addresses","dns","dns_resolver","drop","","","","","","","","","","empty","eq","","","equivalent","","","","","","","","","fmt","","","","","","","","","","","","","","","from","","","","","","","","","","","","","","","","","","from_err","","from_err_box","","from_parts","from_pkarr_signed_packet","from_ref","","","","from_services","from_str","from_txt_lookup","hash","in_current_span","","","","init","","","","","","","","","","into","","","","","","","","","","into_discovery","","into_node_addr","","last_updated","mdns","new","","","node_id","","","node_info","partial_cmp","pkarr","provenance","publish","","relay_url","resolve","","secret_key","set_relay_url","set_user_data","source","","","","static_provider","subscribe","","to_node_addr","","to_owned","","","","to_pkarr_signed_packet","to_string","","","","","to_txt_strings","try_from","","","","","","","","","","","try_into","","","","","","","","","","type_id","","","","","","","","","","user_data","","val","vzip","","","","","","","","","","with_direct_addresses","","with_relay_url","","with_user_data","","backtrace","","","","","","node_id","","provenance","source","","","span_trace","","","","","","backtrace","provenance","source","span_trace","backtrace","","","","","","key","label","num_labels","s","source","","span_trace","","","","","","DnsDiscovery","DnsDiscoveryBuilder","N0_DNS_NODE_ORIGIN_PROD","N0_DNS_NODE_ORIGIN_STAGING","borrow","","borrow_mut","","build","builder","compat","","compat_mut","","compat_ref","","deref","","deref_mut","","dns_resolver","drop","","fmt","","from","","init","","into","","into_discovery","","n0_dns","resolve","try_from","","try_into","","type_id","","vzip","","MdnsDiscovery","MdnsDiscoveryBuilder","NAME","borrow","","borrow_mut","","builder","compat","","compat_mut","","compat_ref","","deref","","deref_mut","","drop","","fmt","","from","","init","","into","","into_discovery","","new","publish","resolve","subscribe","try_from","","try_into","","type_id","","vzip","","DEFAULT_PKARR_TTL","DEFAULT_REPUBLISH_INTERVAL","HttpPayload","HttpRequest","HttpSend","InvalidRelayUrl","N0_DNS_PKARR_RELAY_PROD","N0_DNS_PKARR_RELAY_STAGING","PkarrError","PkarrPublisher","PkarrPublisherBuilder","PkarrRelayClient","PkarrResolver","PkarrResolverBuilder","PublicKey","Verify","__clone_box","","","as_error_source","backtrace","borrow","","","","","","borrow_mut","","","","","","build","","builder","","cause","clone","","","clone_into","","","clone_to_uninit","","","compat","","","","","","compat_mut","","","","","","compat_ref","","","","","","deref","","","","","","deref_mut","","","","","","description","dht","dns_resolver","","drop","","","","","","fmt","","","","","","","from","","","","","","from_ref","","","in_current_span","init","","","","","","into","","","","","","into_discovery","","","","n0_dns","","new","publish","","republish_interval","resolve","","source","to_owned","","","to_string","try_from","","","","","","try_into","","","","","","ttl","type_id","","","","","","update_node_data","vzip","","","","","","with_dns_resolver","source","","","","status","url","Builder","DhtDiscovery","__clone_box","borrow","","borrow_mut","","build","builder","client","clone","clone_into","clone_to_uninit","compat","","compat_mut","","compat_ref","","default","","deref","","deref_mut","","dht","drop","","fmt","","from","","from_ref","include_direct_addresses","init","","initial_publish_delay","into","","into_discovery","","n0_dns_pkarr_relay","no_publish","pkarr_relay","publish","republish_delay","resolve","secret_key","to_owned","try_from","","try_into","","ttl","type_id","","vzip","","PROVENANCE","StaticProvider","__clone_box","add_node_info","borrow","borrow_mut","clone","clone_into","clone_to_uninit","compat","compat_mut","compat_ref","default","deref","deref_mut","drop","fmt","from","from_node_info","from_ref","get_node_info","init","into","into_discovery","new","publish","remove_node_info","resolve","set_node_info","to_owned","try_from","try_into","type_id","vzip","DnsResolver","N0_DNS_NODE_ORIGIN_PROD","N0_DNS_NODE_ORIGIN_STAGING","__clone_box","borrow","borrow_mut","clear_cache","clone","clone_into","clone_to_uninit","compat","compat_mut","compat_ref","default","deref","deref_mut","drop","fmt","from","","from_ref","init","into","lookup_ipv4","lookup_ipv4_ipv6","lookup_ipv4_ipv6_staggered","lookup_ipv4_staggered","lookup_ipv6","lookup_ipv6_staggered","lookup_node_by_domain_name","lookup_node_by_domain_name_staggered","lookup_node_by_id","lookup_node_by_id_staggered","lookup_txt","new","resolve","resolve_host","to_owned","try_from","try_into","type_id","vzip","with_nameserver","AEAD_LIMIT_REACHED","APPLICATION_ERROR","Accept","AcceptBi","AcceptUni","AckFrequencyConfig","AddNodeAddr","AddNodeAddrError","AeadKey","All","AlpnError","App","ApplicationClose","ApplicationClosed","BindError","Builder","CONNECTION_ID_LIMIT_ERROR","CONNECTION_REFUSED","CRYPTO_BUFFER_EXCEEDED","CallMeMaybe","Chunk","CidsExhausted","ClosedStream","","","Connect","ConnectError","ConnectOptions","ConnectWithOptsError","Connecting","Connection","","ConnectionClose","ConnectionClosed","ConnectionError","","ConnectionLost","","","","","ConnectionStats","ConnectionType","ControlMsg","Controller","ControllerFactory","CryptoError","CryptoServerConfig","Custom","Default","Direct","DirectAddr","DirectAddrInfo","DirectAddrType","Disabled","","Discover","Discovery","","DiscoveryStart","ENV_FORCE_STAGING_RELAYS","Empty","EmptyPruned","Endpoint","ExportKeyingMaterialError","FINAL_SIZE_ERROR","FLOW_CONTROL_ERROR","FRAME_ENCODING_ERROR","FinishedEarly","FrameStats","GetMappingAddressError","HandshakeTokenKey","INTERNAL_ERROR","INVALID_TOKEN","IllegalOrderedRead","Incoming","IncomingFuture","KEY_UPDATE_ERROR","Local","LocallyClosed","MAX","MAX_SIZE","MagicSpawn","Mixed","MtuDiscoveryConfig","NO_ERROR","NO_VIABLE_PATH","NamedApp","NoAddress","","NodeAddrWatcher","None","OpenBi","OpenUni","OwnAddress","PROTOCOL_VIOLATION","PathSelection","PathStats","Ping","Pong","Portmapped","Quinn","Read","ReadDatagram","ReadError","","ReadExactError","ReadToEndError","RecvStream","Relay","","RelayMode","RelayOnly","RemoteInfo","RemoteNodeIdError","Reset","","ResetError","RetryError","STREAM_LIMIT_ERROR","STREAM_STATE_ERROR","Saved","SelfConnect","SendDatagramError","SendStream","ServerConfig","Source","Staging","Stopped","StoppedError","StreamId","Stun","Stun4LocalPort","TRANSPORT_PARAMETER_ERROR","TimedOut","TooLarge","TooLong","TransportConfig","TransportError","","TransportErrorCode","Udp","UdpStats","Unavailable","Unknown","UnknownHandshake","UnsupportedByPeer","UnsupportedVersion","VarInt","VersionMismatch","WeakConnectionHandle","WriteError","Written","ZeroRttAccepted","ZeroRttRejected","","","","__clone_box","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","accept","","accept_bi","accept_uni","accept_with","ack_eliciting_threshold","ack_frequency","ack_frequency_config","acks","add_discovery","add_node_addr","add_node_addr_with_source","addr","","addrs","aead_from_hkdf","allow_spin","alpn","","alpns","as_error_source","","","","","","","","","","","","","","","","","","backtrace","","","","","","","bind","bind_addr_v4","bind_addr_v6","black_hole_cooldown","black_holes_detected","borrow","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","borrow_mut","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","bound_sockets","build","builder","bytes","","","cause","","","","","","","chunks","clear_discovery","clone","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","clone_box","clone_into","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","clone_to_uninit","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","close","","close_reason","closed","cmp","","","","code","compare","","","","compat","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","compat_mut","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","compat_ref","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","congestion_controller_factory","congestion_events","congestion_state","conn_type","","connect","connect_with_opts","connection_close","crypto","","","crypto_buffer_size","current_mtu","cwnd","data_blocked","datagram","datagram_receive_buffer_size","datagram_send_buffer_size","datagram_send_buffer_space","datagrams","decode","","","default","","","","","","","","","","","","","","default_relay_mode","deref","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","deref_mut","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","description","","","","","","","deserialize","","","","","dir","direct_addresses","discovery","","discovery_dht","discovery_local_network","discovery_n0","discovery_stream","dns_resolver","","drop","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","enable_segmentation_offload","encode","","","eq","","","","","","","","","","","","","","","","","","","","","","","","","","","equivalent","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","error_code","","export_keying_material","finish","fmt","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","force_staging_infra","frame","frame_rx","frame_tx","frame_type","from","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","from_ref","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","from_u32","from_u64","from_u64_unchecked","handshake_data","","handshake_done","has_send_address","hash","","","","","home_relay","id","","ignore","immediate_ack","in_current_span","","","","","","","","","","","","","","","","","","incoming_buffer_size","incoming_buffer_size_total","index","init","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","initial_keys","initial_mtu","initial_rtt","initial_window","initiator","insecure_skip_relay_cert_verify","interval","into","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","into_0rtt","into_any","into_future","","","","","","","","","","into_incoming","into_inner","ios","is_0rtt","is_alive","is_closed","keep_alive_interval","keylog","known_nodes","last_alive","last_control","last_payload","last_received","last_used","latency","","local_ip","lost_bytes","lost_packets","lost_plpmtud_probes","max_ack_delay","max_concurrent_bidi_streams","max_concurrent_uni_streams","max_data","max_datagram_size","max_idle_timeout","max_incoming","max_stream_data","max_streams_bidi","max_streams_uni","metrics","migration","min_mtu","minimum_change","mtu_discovery_config","network_change","network_path_changed","new","","","new_connection_id","new_token","node_addr","node_id","","observed_addr","offset","on_ack","on_congestion_event","on_end_acks","on_mtu_update","on_sent","open","open_bi","open_uni","packet_threshold","partial_cmp","","","","path","path_challenge","path_response","path_selection","peer_identity","persistent_congestion_threshold","ping","poll","","","","","","","","","poll_flush","poll_read","","poll_shutdown","poll_write","","preferred_address_v4","preferred_address_v6","priority","proxy_from_env","proxy_url","read","read_chunk","read_chunks","read_datagram","read_exact","read_to_end","reason","","","receive_observed_address_reports","receive_window","received_reset","refuse","relay_conn_protocol","relay_map","relay_mode","relay_url","remote_address","remote_address_validated","remote_info","remote_info_iter","remote_node_id","reordering_threshold","reset","reset_stream","retire_connection_id","retry","retry_tag","retry_token_lifetime","rtt","","saturating_add","seal","secret_key","","send_datagram","send_fairness","send_observed_address_reports","send_window","sent_packets","sent_plpmtud_probes","serialize","","","","","set_alpns","set_max_concurrent_bi_streams","set_max_concurrent_uni_streams","set_priority","set_receive_window","set_user_data_for_discovery","source","","","","","","","","","","","","","","","sources","","stable_id","start_session","stats","stop","stop_sending","stopped","stream","stream_data_blocked","stream_receive_window","streams_blocked_bidi","streams_blocked_uni","time_source","time_threshold","to_owned","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","to_string","","","","","","","","","","","","","","","","","","","","","","","","","","","token_key","transport","transport_config","","try_from","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","try_into","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","try_poll","","","","","","","typ","type_id","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","udp_rx","udp_tx","upper_bound","user_data_for_discovery","validation_token","validation_token_config","vzip","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","window","with_additional_alpns","with_crypto","with_single_cert","with_transport_config","write","write_all","write_all_chunks","write_chunk","write_chunks","backtrace","","","pruned","span_trace","","","backtrace","","","source","span_trace","","","backtrace","","source","","span_trace","","backtrace","","source","","span_trace","","backtrace","","","","source","","","span_trace","","","","backtrace","","","source","","span_trace","","","name","","EndpointMetrics","MagicsockMetrics","NetReportMetrics","PortmapMetrics","RelayMetrics","__clone_box","accepts","actor_link_change","actor_tick_direct_addr_heartbeat","actor_tick_direct_addr_update_receiver","actor_tick_main","actor_tick_msg","actor_tick_other","actor_tick_portmap_changed","actor_tick_re_stun","as_iterable","","","borrow","","","","borrow_mut","","","","bytes_recv","bytes_sent","clone","clone_into","clone_to_uninit","compat","","","","compat_mut","","","","compat_ref","","","","connection_became_direct","connection_handshake_success","conns_rx_ratelimited_total","default","","","","deref","","","","deref_mut","","","","deserialize","","","disco_packets_dropped","disco_packets_recv","disco_packets_sent","disconnects","drop","","","","external_address_updated","field_count","","","field_ref","","","fmt","","","","frames_rx_ratelimited_total","from","","","","from_ref","got_ping","groups","groups_cloned","init","","","","into","","","","local_port_updates","magicsock","mapping_attempts","mapping_failures","name","","","","net_report","nodes_contacted","nodes_contacted_directly","num_direct_conns_added","num_direct_conns_removed","num_relay_conns_added","num_relay_conns_removed","other_packets_dropped","other_packets_recv","other_packets_sent","pcp_available","pcp_probes","portmapper","probes_started","re_stun_calls","recv_data_ipv4","recv_data_ipv6","recv_data_relay","recv_datagrams","recv_disco_bad_key","recv_disco_bad_parse","recv_disco_call_me_maybe","recv_disco_call_me_maybe_bad_disco","recv_disco_ping","recv_disco_pong","recv_disco_relay","recv_disco_udp","recv_gro_datagrams","relay_accepts","relay_home_change","send_data","send_data_network_down","send_disco_relay","send_disco_udp","send_ipv4","send_ipv6","send_packets_dropped","send_packets_recv","send_packets_sent","send_relay","send_relay_error","sent_disco_call_me_maybe","sent_disco_ping","sent_disco_pong","sent_disco_relay","sent_disco_udp","sent_pong","serialize","","","to_owned","try_from","","","","try_into","","","","type_id","","","","unique_client_keys","unknown_frames","update_direct_addrs","upnp_available","upnp_gateway_updated","upnp_probes","upnp_probes_failed","vzip","","","","websocket_accepts","Abort","ActorGone","Addr","AlreadyRunning","Client","Metrics","Options","QuicConfig","RelayLatencies","Report","ReportError","__clone_box","","","","","addr","as_error_source","as_iterable","backtrace","bind_local_stun_socket","borrow","","","","","","","","borrow_mut","","","","","","","","captive_portal","cause","client_config","clone","","","","","clone_into","","","","","clone_to_uninit","","","","","compat","","","","","","","","compat_mut","","","","","","","","compat_ref","","","","","","","","default","","","","deref","","","","","","","","deref_mut","","","","","","","","description","deserialize","disabled","drop","","","","","","","","ep","eq","","equivalent","","","","","","field_count","field_ref","fmt","","","","","","","","","","from","","","","","","","","from_ref","","","","","get_report","global_v4","global_v6","hair_pinning","https","icmp_v4","icmp_v6","icmpv4","icmpv6","in_current_span","init","","","","","","","","into","","","","","","","","ipv4","","ipv4_can_send","ipv6","","ipv6_can_send","iter","mapping_varies_by_dest_ip","mapping_varies_by_dest_ipv6","name","new","os_has_ipv6","portmap_probe","preferred_relay","quic_config","receive_stun_packet","relay_latency","relay_v4_latency","relay_v6_latency","reports","reports_full","serialize","source","stun_packets_dropped","stun_packets_recv_ipv4","stun_packets_recv_ipv6","stun_packets_sent_ipv4","stun_packets_sent_ipv6","stun_v4","stun_v6","to_owned","","","","","to_string","","try_from","","","","","","","","try_into","","","","","","","","type_id","","","","","","","","udp","vzip","","","","","","","","backtrace","","","reason","span_trace","","","AttrFromString","DecodingError","","EncodingError","FailedBuildingPacket","IROH_TXT_NAME","InvalidEncodingZ32","InvalidLabel","InvalidLength","InvalidSignature","InvalidTxtEntry","LookupError","LookupFailed","MaxLengthExceededError","NodeData","NodeIdExt","NodeInfo","NotAnIrohRecord","NumLabels","ParseError","","UnexpectedFormat","UserData","Utf8","as_error_source","","","","backtrace","","","","borrow","","","","borrow_mut","","","","cause","","","","compat","","","","compat_mut","","","","compat_ref","","","","data","deref","","","","deref_mut","","","","description","","","","drop","","","","fmt","","","","","","","","from","","","","","from_z32","in_current_span","","","","init","","","","into","","","","node_id","source","","","","to_string","","","","to_z32","try_from","","","","try_into","","","","type_id","","","","vzip","","","","backtrace","","","len","source","","span_trace","","","backtrace","","source","","span_trace","","backtrace","","","source","","","span_trace","","","backtrace","","","","","","key","label","num_labels","s","source","","span_trace","","","","","","AccessLimit","Connect","NotAllowed","ProtocolError","ProtocolHandler","RemoteNodeId","Router","RouterBuilder","User","__clone_box","","accept","","","as_error_source","backtrace","borrow","","","","borrow_mut","","","","builder","cause","clone","","clone_into","","clone_to_uninit","","compat","","","","compat_mut","","","","compat_ref","","","","deref","","","","deref_mut","","","","description","drop","","","","endpoint","","fmt","","","","","from","","","","","","","","","from_err","from_ref","","in_current_span","init","","","","into","","","","is_shutdown","new","","on_connecting","","shutdown","","","source","spawn","to_owned","","to_string","try_from","","","","try_into","","","","type_id","","","","vzip","","","","backtrace","source","","","span_trace","CleanupDropGuard","DnsPkarrServer","borrow","","borrow_mut","","compat","","compat_mut","","compat_ref","","deref","","deref_mut","","discovery","dns_resolver","drop","","fmt","","from","","init","","into","","nameserver","node_origin","on_node","pkarr_url","run","run_relay_server","run_relay_server_with","run_relay_server_with_stun","run_with_origin","try_from","","try_into","","type_id","","vzip","","Direct","Disconnected","InitializedFut","Map","NextFut","Stream","Value","Watchable","Watcher","__clone_box","","","","as_error_source","backtrace","borrow","","","","","","","borrow_mut","","","","","","","cause","clone","","","","clone_into","","","","clone_to_uninit","","","","compat","","","","","","","compat_mut","","","","","","","compat_ref","","","","","","","default","deref","","","","","","","deref_mut","","","","","","","description","drop","","","","","","","fmt","","","","","","","","from","","","","","","","from_ref","","","","get","","","","in_current_span","init","","","","","","","initialized","into","","","","","","","into_future","","map","new","or","poll","","poll_next","poll_updated","","","ratelimit_stream","ratelimit_stream_with_jitter","set","source","stream","stream_updates_only","to_owned","","","","to_string","try_from","","","","","","","try_into","","","","","","","try_poll","","try_poll_next","type_id","","","","","","","updated","vzip","","","","","","","watch"],"q":[[0,"iroh"],[350,"iroh::KeyParsingError"],[358,"iroh::defaults"],[365,"iroh::defaults::prod"],[372,"iroh::defaults::staging"],[377,"iroh::discovery"],[708,"iroh::discovery::DiscoveryError"],[726,"iroh::discovery::IntoDiscoveryError"],[730,"iroh::discovery::ParseError"],[748,"iroh::discovery::dns"],[791,"iroh::discovery::mdns"],[833,"iroh::discovery::pkarr"],[993,"iroh::discovery::pkarr::PkarrError"],[999,"iroh::discovery::pkarr::dht"],[1057,"iroh::discovery::static_provider"],[1091,"iroh::dns"],[1134,"iroh::endpoint"],[3090,"iroh::endpoint::AddNodeAddrError"],[3097,"iroh::endpoint::AlpnError"],[3104,"iroh::endpoint::BindError"],[3110,"iroh::endpoint::ConnectError"],[3116,"iroh::endpoint::ConnectWithOptsError"],[3127,"iroh::endpoint::GetMappingAddressError"],[3135,"iroh::endpoint::Source"],[3137,"iroh::metrics"],[3317,"iroh::net_report"],[3557,"iroh::net_report::ReportError"],[3564,"iroh::discovery"],[3565,"iroh::node_info"],[3566,"iroh::discovery"],[3567,"iroh::node_info"],[3581,"iroh::discovery"],[3583,"iroh::node_info"],[3585,"iroh::discovery"],[3586,"iroh::node_info"],[3587,"iroh::discovery"],[3588,"iroh::node_info"],[3620,"iroh::discovery"],[3621,"iroh::node_info"],[3663,"iroh::discovery"],[3664,"iroh::node_info"],[3689,"iroh::node_info::DecodingError"],[3698,"iroh::node_info::EncodingError"],[3704,"iroh::node_info::LookupError"],[3713,"iroh::discovery::ParseError"],[3731,"iroh::protocol"],[3845,"iroh::protocol::ProtocolError"],[3850,"iroh::test_utils"],[3895,"iroh::watcher"],[4075,"dyn_clone::sealed"],[4076,"iroh_base::key"],[4077,"core::error"],[4078,"backtrace::capture"],[4079,"core::option"],[4080,"iroh_base::relay_url"],[4081,"iroh_base::node_addr"],[4082,"iroh_relay::relay_map"],[4083,"core::cmp"],[4084,"async_compat"],[4085,"core::result"],[4086,"serde::de"],[4087,"core::net::socket_addr"],[4088,"core::iter::traits::iterator"],[4089,"alloc::collections::btree::set"],[4090,"core::fmt"],[4091,"alloc::string"],[4092,"ed25519_dalek::verifying"],[4093,"data_encoding"],[4094,"signature::error"],[4095,"ed25519_dalek::signing"],[4096,"iroh_base::ticket::node"],[4097,"iroh::magicsock::node_map::node_state"],[4098,"iroh_relay::node_info"],[4099,"url"],[4100,"core::iter::traits::collect"],[4101,"rand_core"],[4102,"alloc::sync"],[4103,"core::hash"],[4104,"http::header::value"],[4105,"serde::ser"],[4106,"ed25519"],[4107,"core::any"],[4108,"n0_snafu::spantrace"],[4109,"iroh_relay::dns"],[4110,"alloc::boxed"],[4111,"core::marker"],[4112,"pkarr::signed_packet"],[4113,"alloc::vec"],[4114,"futures_lite::stream"],[4115,"core::str::error"],[4116,"core::time"],[4117,"pkarr::keys"],[4118,"reqwest::error"],[4119,"http::status"],[4120,"pkarr::client"],[4121,"core::convert"],[4122,"anyhow"],[4123,"hickory_proto::runtime::tokio_runtime"],[4124,"hickory_resolver::name_server::connection_provider"],[4125,"hickory_resolver::resolver"],[4126,"core::net::ip_addr"],[4127,"iroh_relay::dns::staggered"],[4128,"reqwest::dns::resolve"],[4129,"core::future::future"],[4130,"core::pin"],[4131,"iroh_quinn_proto::connection"],[4132,"iroh_quinn::connection"],[4133,"iroh_quinn_proto::config"],[4134,"iroh_quinn_proto::config::transport"],[4135,"iroh_quinn_proto::varint"],[4136,"iroh_quinn_proto::connection::stats"],[4137,"iroh::magicsock"],[4138,"iroh_quinn_proto::crypto"],[4139,"iroh_quinn_proto::congestion"],[4140,"std::time"],[4141,"iroh_quinn_proto::connection::assembler"],[4142,"bytes::bytes"],[4143,"iroh_quinn_proto::connection::streams::send"],[4144,"iroh_quinn::recv_stream"],[4145,"iroh_quinn::send_stream"],[4146,"iroh_quinn_proto::connection::streams"],[4147,"iroh::magicsock::node_map"],[4148,"iroh_quinn_proto::frame"],[4149,"iroh_quinn_proto"],[4150,"iroh_quinn_proto::coding"],[4151,"bytes::buf::buf_impl"],[4152,"futures_core::stream"],[4153,"bytes::buf::buf_mut"],[4154,"iroh_quinn::incoming"],[4155,"iroh_quinn_proto::connection::streams::recv"],[4156,"ring::error::unspecified"],[4157,"iroh_quinn_proto::transport_parameters"],[4158,"iroh_quinn_proto::shared"],[4159,"iroh_quinn_proto::connection::paths"],[4160,"core::task::wake"],[4161,"core::task::poll"],[4162,"std::io::error"],[4163,"tokio::io::read_buf"],[4164,"std::collections::hash::map"],[4165,"rustls_pki_types"],[4166,"rustls::error"],[4167,"iroh_quinn_proto::endpoint"],[4168,"iroh_metrics::metrics"],[4169,"iroh_metrics::iterable"],[4170,"iroh_metrics::base"],[4171,"netwatch::ip_family"],[4172,"tokio_util::sync::cancellation_token"],[4173,"netwatch::udp"],[4174,"iroh::net_report::reportgen"],[4175,"rustls::client::client_conn"],[4176,"iroh::net_report::options::imp"],[4177,"iroh::net_report::metrics"],[4178,"iroh_quinn::endpoint"],[4179,"portmapper"],[4180,"z32"],[4181,"simple_dns::simple_dns_error"],[4182,"hickory_proto::error"],[4183,"core::clone"],[4184,"core::ops::function"],[4185,"tokio::runtime::task::error"],[4186,"iroh::test_utils::dns_and_pkarr_servers"],[4187,"iroh_relay::server"],[4188,"core::default"],[4189,"governor::state::direct"],[4190,"governor::state"],[4191,"governor::state::direct::streams"],[4192,"governor::clock::with_std"],[4193,"governor::middleware"],[4194,"governor::jitter"],[4195,"iroh_relay"],[4196,"iroh_relay::defaults"],[4197,"iroh::net_report::stun_utils"]],"i":"Ab0`0`h```Bb```````01AlAnB`3BdBf67Ah7807785430621785430621807543621754362175436217431743178543062178543062178543062126`7854330621785430621807543144``7854306212`74362177744433366622211177885543300622117778885554444443306222117522475436217537527380785430621785430621422``44`267431`7514457543158011`57543621785302177778554306217854306217854306216127785430621`44FjFlFn21210```````````````````Gj`0```````GhGn0`0`22`002Gl1`3Gf3EbHbGb3745H`785604738Hd67321584906732196715584358435843885849067321584906732158490673214525844906733215844906732196715`05849067321258455588844458849906677321155844444990677322167674458432848967158490673215849067321Il3544`65414549`4Gd4704277;893`04657:656:;89367::6;2895437:6;2895437:6;2895437537:6;289543767676JhJjJlJnK`Kb430210543210Kd000KfKhKjKlKnL`413520543210````LfLd1001101010101001010101010101110101010```LjLh1011010101010101010101010111110101010``Hn000````````00M`MdMf333Ln3Mb32514032104354324324325140325140325140325140325140325`105140325514032514032432551403251403214034324213254325514032514032151403245140322MhMlN`NdNfNj``Nn0Nl10010111101010101010010101010100101000010101101001010Ob`00000000000000000000000000000000```Hf000000000000000000000000000000000000000AGd0````ACf``AGj`AFl`AAf``444AFf`1`AEjAF`ACh`````0`4`ACdAEf4AEl4AFb```````AGn0AFj```41ACl40;AEbABdADfAFdAEd=AFhABlE`AFjAFlAAfAB`ADdAAnAFnAG`AGbAGdAGfABnAGhAGjA@nAGlAAhAGn3AAb220?ABdABf1ABh77ABl;E`AC`4AAd94AEfAIdAEhAEjAElAEnAF`AFbAFhAAfABjAGbACfAChACjAClACdACn7543210ABh00ADdADfAL`AKnAAlAAjALfAIbAEfAIdAHjAEhAEjAElAEnAHlAF`AFbABfABbADnAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAI`AIfAIhAFnAG`ABjAGbAGdAGfABnAGhAGjABhA@nACfAChACjAClAGlAA`AAbAIjAAdACdAIlAAhACnAGnAL`AKnAAlAAjALfAIbAEfAIdAHjAEhAEjAElAEnAHlAF`AFbABfABbADnAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAI`AIfAIhAFnAG`ABjAGbAGdAGfABnAGhAGjABhA@nACfAChACjAClAGlAA`AAbAIjAAdACdAIlAAhACnAGn>ADh?ADnAEbAEdABjACfAChACjACl=:5ABhAEfAEhAEjAElAEnAF`AFbABb?ABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAFnAG`AGbAGdAGfABnAGhAGjA@nAGlAAhAGnADlAEfAEhAEjAElAEnAF`AFbABbAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAFnAG`AGbAGdAGfABnAGhAGjA@nAGlAAhAGnAEfAEhAEjAElAEnAF`AFbABbAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAFnAG`AGbAGdAGfABnAGhAGjA@nAGlAAhAGn3111ABb876:0876AL`AKnAAlAAjALfAIbAEfAIdAHjAEhAEjAElAEnAHlAF`AFbABfABbADnAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAI`AIfAIhAFnAG`ABjAGbAGdAGfABnAGhAGjABhA@nACfAChACjAClAGlAA`AAbAIjAAdACdAIlAAhACnAGnAL`AKnAAlAAjALfAIbAEfAIdAHjAEhAEjAElAEnAHlAF`AFbABfABbADnAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAI`AIfAIhAFnAG`ABjAGbAGdAGfABnAGhAGjABhA@nACfAChACjAClAGlAA`AAbAIjAAdACdAIlAAhACnAGnAL`AKnAAlAAjALfAIbAEfAIdAHjAEhAEjAElAEnAHlAF`AFbABfABbADnAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAI`AIfAIhAFnAG`ABjAGbAGdAGfABnAGhAGjABhA@nACfAChACjAClAGlAA`AAbAIjAAdACdAIlAAhACnAGnABfADf4A@nE`11ABdAGd1AAn65522669AEbABb3AGf91258AFdAEdAFhAFjAB`ADdAGjABhAGl`AL`AKnAAlAAjALfAIbAEfAIdAHjAEhAEjAElAEnAHlAF`AFbABfABbADnAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAI`AIfAIhAFnAG`ABjAGbAGdAGfABnAGhAGjABhA@nACfAChACjAClAGlAA`AAbAIjAAdACdAIlAAhACnAGnAL`AKnAAlAAjALfAIbAEfAIdAHjAEhAEjAElAEnAHlAF`AFbABfABbADnAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAI`AIfAIhAFnAG`ABjAGbAGdAGfABnAGhAGjABhA@nACfAChACjAClAGlAA`AAbAIjAAdACdAIlAAhACnAGnABj>=<;52AFfABlE`AFjAFlAGfA@nABh1000101AL`AKnAAlAAjALfAIbAEfAIdAHj0AEhAEjAElAEnAHl0AF`AFbABfABbADnAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAI`AIfAIhAFnAG`ABjAGbAGdAGfABnAGhAGjABhA@nACfAChACjAClAGlAA`AAbAIjAAdACdAIlAAhACnAGnABfABbAGdAGfAEfAEhAEjAElAEnAF`AFb9ADnAEdAFfAFhABlE`AFjAFlAAfAI`AFnAG`AGbAGdAGfABnAGhAGjAGnAEf00AEh00AEj00AEl00AEn00AF`00AFb00ABb00ADn00AEd00AFf00AFh00ABl00E`00AFj00AFl00AAf00AI`00AFn00AG`00AGb00AGd00AGf00ABn00AGh00AGj00AGn0087AAhAHlAIbAEf0AId0AHjAEh0AEj0AEl0AEn08AF`0AFb0ABfABb0ADnAEbABdADfAFdAEdAFf0AFh0ABlE`AFj0AFl0AAf0AB`ADdAAnAI`AIfAIhAFn0AG`0ABj0AGb0AGd0AGf0ABnAGh0AGjABhA@nACf0ACh0ACj0ACl0AGlAA`AAbAIjAAdACd0AIlAAhACn0AGn`AGbAFd0AFnAL`AKnAAlAAjALfAIbAEf0AIdAHjAEh0AEj000AEl0AEn0AHlAF`000AFb0ABfABb0000ADnAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAf00AB`ADdAAnAI`AIf0AIhAFn0AG`ABjAGb000AGdAGf0ABnAGhAGjABhA@nACf0ACh00ACj0AClAGlAA`AAbAIjAAdACd0AIlAAhACnAGnAEfAEhAEjAElAEnAF`AFbABbAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAFnAG`AGbAGdAGfABnAGhAGjA@nAGlAAhAGnABb00AAd3ABdE`3AFl<;:8AHjAHlAAb5AEfAIdAEhAEjAElAEnAF`AFbAFhAAfABjAGbACfAChACjAClACdACnAAn0AGfAL`AKnAAlAAjALfAIbAEfAIdAHjAEhAEjAElAEnAHlAF`AFbABfABbADnAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAI`AIfAIhAFnAG`ABjAGbAGdAGfABnAGhAGjABhA@nACfAChACjAClAGlAA`AAbAIjAAdACdAIlAAhACnAGnAJlABf0ADlAGfABhADdAL`AKnAAlAAjALfAIbAEfAIdAHjAEhAEjAElAEnAHlAF`AFbABfABbADnAEbABdADfAFdAEdAFfAFhABlE`AFjAFlAAfAB`ADdAAnAI`AIfAIhAFnAG`ABjAGbAGdAGfABnAGhAGjABhA@nACfAChACjAClAGlAA`AAbAIjAAdACdAIlAAhACnAGn5ADlAL`AKnAAlAAjALf>=<;9AIdABbAEbAHjAIbA@nABfABh0ABl00E`010AAbADf00AB`66ABdAAh8AAn222:09ADd:;<1AGfAGl55==95ADnADl0000ACb77?ABb5ABnAGhAFd<AL`AKnAAlAAjALfAA`AIjAAdAIlAHlAHj0111AAn02==111AAh22AFnAG`AGbABf06AAbABhAGn1E`33A@n09AB`=ABd06AJl=>>{AIdAKd}{ABbIn}{AEbIn}{{{b{AHj}}}Bl}{{{b{AIb}}}Bl}{{{b{A@n}}}Bl}{{{b{AjABf}}{Af{Ll}}}{{b{AjABf}}}}<{{ABh{Ih{An}}}ABh}{ABlAf}00{{{b{E`}}}{{Af{Ll}}}}{E`Af}20{{{b{AAb}}}{{Af{On}}}}{ADfIn}00{{{b{AjAB`}}{Af{Ll}}}{{b{AjAB`}}}}{{{b{AjABf}}ABb}{{b{AjABf}}}}0{ABdIn}{{{b{AAh}}}{{Af{Bn}}}}{{{b{AjABf}}{Af{AKf}}}{{b{AjABf}}}}{{{b{AjAAn}}Bn}{{b{AjAAn}}}}333{{{b{A@n}}}{{b{AKh}}}}{{{b{AjAAn}}Bl}{{b{AjAAn}}}}{{{b{AjABf}}Ff}{{b{AjABf}}}}{{{b{AjADd}}Ff}{{b{AjADd}}}}{{{b{AjABf}}{Af{ADd}}}{{b{AjABf}}}}{{{b{A@n}}}f}{{{b{AIb}}}Bl}{{{El{AJl}}{El{AC`}}}AAn}{{AKbAHfIn}AGf}{{}AGl}=={{{b{A@n}}}AKj}{{{b{A@n}}}J`}{E`J`}{ABdIn}{ADnIn}{{{b{AjADl}}ADjADjInBl{b{AKl}}}f}{{{b{AjADl}}ADjADjBlIn}f}{{{b{AjADl}}ADjInBl{Af{In}}}f}{{{b{AjADl}}Ff}f}{{{b{AjADl}}ADjInIn}f}{{{b{ACb}}{b{Aj{A`{j}}}}{b{{A`{j}}}}}{{Cb{{b{Aj{A`{j}}}}AIf}}}}{{{b{AAh}}}AKn}{{{b{AAh}}}AL`}{{{b{AjABf}}Jd}{{b{AjABf}}}}{{{b{ABb}}{b{ABb}}}{{Af{Bh}}}}{{{b{AGf}}{b{AGf}}}{{Af{Bh}}}}{{{b{ABn}}{b{ABn}}}{{Af{Bh}}}}{{{b{AGh}}{b{AGh}}}{{Af{Bh}}}}{AFdADf}??{{ABhAGj}ABh}{{{b{AAh}}}{{Af{{I`{AJj}}}}}}7{ABdIn}{{{A@l{{b{AjAL`}}}}{b{AjALb}}}ALd}{{{A@l{{b{AjAKn}}}}{b{AjALb}}}ALd}{{{A@l{{b{AjAAl}}}}{b{AjALb}}}ALd}{{{A@l{{b{AjAAj}}}}{b{AjALb}}}ALd}{{{A@l{{b{AjALf}}}}{b{AjALb}}}ALd}{{{A@l{{b{AjAA`}}}}{b{AjALb}}}{{ALd{c}}}{}}{{{A@l{{b{AjAIj}}}}{b{AjALb}}}{{ALd{c}}}{}}{{{A@l{{b{AjAAd}}}}{b{AjALb}}}{{ALd{c}}}{}}{{{A@l{{b{AjAIl}}}}{b{AjALb}}}{{ALd{c}}}{}}{{{A@l{{b{AjAHl}}}}{b{AjALb}}}{{ALd{{Cb{fALh}}}}}}{{{A@l{{b{AjAHj}}}}{b{AjALb}}{b{AjALj}}}{{ALd{{Cb{fALh}}}}}}{{{b{AjAHj}}{b{AjALb}}{b{Aj{A`{j}}}}}{{ALd{{Cb{BnAEj}}}}}}2{{{A@l{{b{AjAHl}}}}{b{AjALb}}{b{{A`{j}}}}}{{ALd{{Cb{BnAF`}}}}}}{{{A@l{{b{AjAHl}}}}{b{AjALb}}{b{{A`{j}}}}}{{ALd{{Cb{BnALh}}}}}}{{{b{AjAAn}}{Af{AD`}}}{{b{AjAAn}}}}{{{b{AjAAn}}{Af{ADb}}}{{b{AjAAn}}}}{{{b{AHl}}}{{Cb{ALlAFh}}}}{ABhABh}{{ABhEd}ABh}{{{b{AjAHj}}{b{Aj{A`{j}}}}}{{Cb{{Af{Bn}}AEj}}}}{{{b{AjAHj}}BnBl}{{Cb{{Af{ADn}}AEj}}}}{{{b{AjAHj}}{b{Aj{A`{AE`}}}}}{{Cb{{Af{Bn}}AEj}}}}{{{b{AAh}}}ALf}{{{b{AjAHj}}{b{Aj{A`{j}}}}}{{Cb{fAEn}}}}{{{b{AjAHj}}Bn}{{Cb{{Ih{j}}AEh}}}}{AFnAE`}{AG`AE`}{AGbDb}{{{b{AjABf}}Bl}{{b{AjABf}}}}{{{b{AjABf}}ABb}{{b{AjABf}}}}{{{b{AjAHj}}}{{Cb{{Af{ABb}}AEl}}}}{AAbf}{{ABhBb}ABh}{{{b{AGn}}}Bd}{{ABhAGn}ABh}{E`Af}{{{b{AAb}}}Ch}{{{b{AAb}}}Bl}{{{b{A@n}}J`}{{Af{E`}}}}{{{b{A@n}}}{{`{{Cj{}{{Cf{E`}}}}}}}}{{{b{AAh}}}{{Cb{J`ACn}}}}{{{b{AjAB`}}ABb}{{b{AjAB`}}}}{{{b{AjAHl}}ABb}{{Cb{fAFh}}}}{ABdIn}0{AAb{{Cb{fAId}}}}{{{b{AJl}}Jd{b{AJn}}{b{{A`{j}}}}}{{l{j}}}}{{{b{AjAAn}}Ll}{{b{AjAAn}}}}{{{b{AAh}}}Ll}{ADfLl}{{ABbc}ABb{{Od{ABb}}}}{{{b{ACb}}{b{Aj{Ih{j}}}}{b{{A`{j}}}}}{{Cb{fAIf}}}}{{ABhAl}ABh}{{{b{A@n}}}{{b{Al}}}}{{{b{AAh}}AE`}{{Cb{fAEf}}}}{{{b{AjABf}}Bl}{{b{AjABf}}}}0{{{b{AjABf}}In}{{b{AjABf}}}}{ADfIn}0{{{b{AFf}}c}CbFb}{{{b{ABl}}c}CbFb}{{{b{E`}}c}CbFb}{{{b{AFj}}c}CbFb}{{{b{AFl}}c}CbFb}{{{b{A@n}}{Ih{{Ih{j}}}}}f}{{{b{AAh}}ABb}f}0{{{b{AHl}}ALl}{{Cb{fAFh}}}}1{{{b{A@n}}{Af{Gh}}}f}{{{b{AEf}}}{{Af{{b{n}}}}}}{{{b{AEh}}}{{Af{{b{n}}}}}}{{{b{AEj}}}{{Af{{b{n}}}}}}{{{b{AEl}}}{{Af{{b{n}}}}}}{{{b{AEn}}}{{Af{{b{n}}}}}}{{{b{AF`}}}{{Af{{b{n}}}}}}{{{b{AFb}}}{{Af{{b{n}}}}}}{{{b{AAf}}}{{Af{{b{n}}}}}}{{{b{ABj}}}{{Af{{b{n}}}}}}{{{b{ACf}}}{{Af{{b{n}}}}}}{{{b{ACh}}}{{Af{{b{n}}}}}}{{{b{ACj}}}{{Af{{b{n}}}}}}{{{b{ACl}}}{{Af{{b{n}}}}}}{{{b{ACd}}}{{Af{{b{n}}}}}}{{{b{ACn}}}{{Af{{b{n}}}}}}{{{b{E`}}}{{Ih{{Dn{AFlLl}}}}}}{ABlALn}{{{b{AAh}}}Bn}{{{El{AJl}}Jd{b{AM`}}}{{I`{AMb}}}}{{{b{AAh}}}AFd}{{{b{AjAHj}}ABb}{{Cb{fAFh}}}}{ABdIn}{{{b{AjAHl}}}{{Cb{{Af{ABb}}AFb}}}}11{{{b{AjABf}}ABb}{{b{AjABf}}}}22{{{b{AjAAn}}{El{AMd}}}{{b{AjAAn}}}}{{{b{AjABf}}AMf}{{b{AjABf}}}}{bc{}}0000000000000000000000000000000000{bDb}00000000000000000000000000{{{b{AjAAn}}{El{AC`}}}{{b{AjAAn}}}}{AAnEl}{{{b{AjAAn}}{El{ABf}}}{{b{AjAAn}}}}{{ABhABf}ABh}{c{{Cb{e}}}{}{}}0000000000000000{In{{Cb{ABbAJh}}}}{AMh{{Cb{ABbAJh}}}}{Bn{{Cb{ABbAJh}}}}333333333333333333333333333333333333333333333{{}{{Cb{c}}}{}}0000000000000000000000000000000000000000000000000000000000000{{{A@l{{b{Ajc}}}}{b{AjALb}}}ALd{}}000000{ABnAGh}{bFh}0000000000000000000000000000000000000000000000000000000000000{AFdAEb}0{{{b{AjADd}}Ff}{{b{AjADd}}}}{{ABhGh}ABh}{AAnAMj}{{{b{AjAAn}}AMj}{{b{AjAAn}}}}{{}c{}}0000000000000000000000000000000000000000000000000000000000000{{{b{ADl}}}In}{{AGl{Ih{{Ih{j}}}}}AGl}{{{El{AJl}}}AAn}{{{Ih{AMl}}AMn}{{Cb{AAnAN`}}}}{{AGl{El{ABf}}}AGl}{{{b{AjAHl}}{b{{A`{j}}}}}{{Cb{BnAF`}}}}{{{b{AjAHl}}{b{{A`{j}}}}}{{Cb{fAF`}}}}{{{b{AjAHl}}{b{Aj{A`{AE`}}}}}{{Cb{fAF`}}}}{{{b{AjAHl}}AE`}{{Cb{fAF`}}}}{{{b{AjAHl}}{b{Aj{A`{AE`}}}}}{{Cb{AEdAF`}}}}{ANbAf}{ANdAf}{ANfAf}{ANdBn}{ANbG`}{ANdG`}{ANfG`}{ANhAf}{ANjAf}{ANlAf}{ANhAAf}{ANhG`}{ANjG`}{ANlG`}{ANnAf}{AO`Af}`{AO`Gl}{ANnG`}{AO`G`}{AObAf}{AOdAf}{AObI`}{AOdI`}{AObG`}{AOdG`}{AOfAf}{AOhAf}{AOjAf}{AOlAf}{AOfABj}{AOjACl}{AOlAOn}{AOfG`}{AOhG`}{AOjG`}{AOlG`}{B@`Af}{B@bAf}{B@dAf}{B@`Gn}{B@bGn}{B@`G`}{B@bG`}{B@dG`}{B@fDb}{B@hDb}`````{{bd}f}{B@jB@l}{B@nB@l}0000000{b{{b{BA`}}}}00{b{{b{c}}}{}}000{{{b{Aj}}}{{b{Ajc}}}{}}00044{{{b{AKh}}}AKh}{{b{b{Ajc}}}f{}}{{bj}f}{{}{{Bj{c}}}{}}000{{{b{Aj}}}{{Bj{{b{Ajc}}}}}{}}000{b{{Bj{{b{c}}}}}{}}00099:{{}BAb}{{}B@n}{{}B@j}{{}AKh}{Bn{{b{c}}}{}}000{Bn{{b{Ajc}}}{}}000{c{{Cb{BAb}}}Cd}{c{{Cb{B@n}}}Cd}{c{{Cb{AKh}}}Cd}{B@jB@l}000{Bnf}000{BAbB@l}{{{b{BAb}}}Bn}{{{b{B@n}}}Bn}{{{b{B@j}}}Bn}{{{b{BAb}}Bn}{{Af{BAd}}}}{{{b{B@n}}Bn}{{Af{BAd}}}}{{{b{B@j}}Bn}{{Af{BAd}}}}{{{b{BAb}}{b{AjCn}}}{{Cb{fD`}}}}{{{b{B@n}}{b{AjCn}}}Hh}{{{b{B@j}}{b{AjCn}}}{{Cb{fD`}}}}{{{b{AKh}}{b{AjCn}}}Hh}<{cc{}}000{{{b{c}}}c{}}>{{{b{AKh}}}{{`{{Cj{}{{Cf{{b{BAf}}}}}}}}}}{{{b{AKh}}}{{`{{Cj{}{{Cf{{El{BAf}}}}}}}}}}{{}Bn}000{{}c{}}000{BAbB@l}{AKhEl}11{{{b{BAb}}}{{b{C`}}}}{{{b{B@n}}}{{b{C`}}}}{{{b{B@j}}}{{b{C`}}}}{{{b{AKh}}}{{b{C`}}}}4{B@nB@l}00000{B@jB@l}007767111111111111110111111100011111110{{{b{BAb}}c}CbFb}{{{b{B@n}}c}CbFb}{{{b{AKh}}c}CbFb}{bc{}}{c{{Cb{e}}}{}{}}000{{}{{Cb{c}}}{}}000{bFh}000778>>>>{{}c{}}0008```````````{{bd}f}0000{{{b{BAh}}}BAj}{b{{b{n}}}}{b{{b{BA`}}}}{{{b{BAl}}}{{Af{{b{Ad}}}}}}{{BAnBAjBB`}{{Af{{El{BBb}}}}}}{b{{b{c}}}{}}0000000{{{b{Aj}}}{{b{Ajc}}}{}}0000000{BBdAf}{{{b{BAl}}}{{Af{{b{n}}}}}}{BBfBBh}{{{b{BBf}}}BBf}{{{b{BBj}}}BBj}{{{b{BBd}}}BBd}{{{b{BBl}}}BBl}{{{b{BAj}}}BAj}{{b{b{Ajc}}}f{}}0000{{bj}f}0000{{}{{Bj{c}}}{}}0000000{{{b{Aj}}}{{Bj{{b{Ajc}}}}}{}}0000000{b{{Bj{{b{c}}}}}{}}0000000{{}BBn}{{}BBj}{{}BBd}{{}BBl}{Bn{{b{c}}}{}}0000000{Bn{{b{Ajc}}}{}}0000000{{{b{BAl}}}{{b{C`}}}}{c{{Cb{BBn}}}Cd}6{Bnf}0000000{BBfBC`}{{{b{BBd}}{b{BBd}}}Bl}{{{b{BBl}}{b{BBl}}}Bl}{{b{b{c}}}Bl{}}00000{{{b{BBn}}}Bn}{{{b{BBn}}Bn}{{Af{BAd}}}}{{{b{BBn}}{b{AjCn}}}Hh}{{{b{BBf}}{b{AjCn}}}Hh}{{{b{BBj}}{b{AjCn}}}Hh}{{{b{BBd}}{b{AjCn}}}Hh}0{{{b{BBl}}{b{AjCn}}}Hh}{{{b{BAh}}{b{AjCn}}}Hh}{{{b{BAj}}{b{AjCn}}}Hh}{{{b{BAl}}{b{AjCn}}}Hh}0{cc{}}0000000{{{b{c}}}c{}}0000{{{b{AjBAh}}BdBBj}{{Cb{{El{BBd}}BAl}}}}{BBdAf}00{{BBjBl}BBj}0011{{}}{{}Bn}0000000{{}c{}}0000000{BBfBl}{BBdBl}0100{{{b{BBl}}}{{`{{Cj{}{{Cf{{Dn{{b{B`}}Ll}}}}}}}}}}77{{{b{BBn}}}{{b{C`}}}}{{{Af{BCb}}Hf{Af{`}}{El{BBn}}}BAh}399{{BBj{Af{BBf}}}BBj}{{{b{BAj}}AE`Ch}f}{BBdBBl}00{BBnB@l}0{{{b{BBn}}c}CbFb}{{{b{BAl}}}{{Af{{b{n}}}}}}22222{{BBj{Af{{El{BBb}}}}}BBj}0{bc{}}0000{bDb}0{c{{Cb{e}}}{}{}}0000000{{}{{Cb{c}}}{}}0000000{bFh}0000000?{{}c{}}0000000{BCdAf}{BCfAf}{BChAf}`{BCdG`}{BCfG`}{BChG`}`````{{}b}``````````````````{b{{b{n}}}}000{{{b{Jf}}}{{Af{{b{Ad}}}}}}{{{b{Eh}}}{{Af{{b{Ad}}}}}}{{{b{BCj}}}{{Af{{b{Ad}}}}}}{{{b{A@d}}}{{Af{{b{Ad}}}}}}{b{{b{c}}}{}}000{{{b{Aj}}}{{b{Ajc}}}{}}000{{{b{Jf}}}{{Af{{b{n}}}}}}{{{b{Eh}}}{{Af{{b{n}}}}}}{{{b{BCj}}}{{Af{{b{n}}}}}}{{{b{A@d}}}{{Af{{b{n}}}}}}{{}{{Bj{c}}}{}}000{{{b{Aj}}}{{Bj{{b{Ajc}}}}}{}}000{b{{Bj{{b{c}}}}}{}}000{EbGf}{Bn{{b{c}}}{}}000{Bn{{b{Ajc}}}{}}000{{{b{Jf}}}{{b{C`}}}}{{{b{Eh}}}{{b{C`}}}}{{{b{BCj}}}{{b{C`}}}}{{{b{A@d}}}{{b{C`}}}}{Bnf}000{{{b{Jf}}{b{AjCn}}}{{Cb{fD`}}}}0{{{b{Eh}}{b{AjCn}}}{{Cb{fD`}}}}0{{{b{BCj}}{b{AjCn}}}{{Cb{fD`}}}}0{{{b{A@d}}{b{AjCn}}}{{Cb{fD`}}}}0{cc{}}{BClJf}111{{{b{C`}}}{{Cb{hEh}}}}{{}}000{{}Bn}000{{}c{}}000{Ebh}{{{b{Jf}}}{{Af{{b{n}}}}}}{{{b{Eh}}}{{Af{{b{n}}}}}}{{{b{BCj}}}{{Af{{b{n}}}}}}{{{b{A@d}}}{{Af{{b{n}}}}}}{bDb}000{{{b{BCn}}}Db}{c{{Cb{e}}}{}{}}000{{}{{Cb{c}}}{}}000{bFh}000{{}c{}}000{BD`Af}{BDbAf}{BDdAf}{BDbBn}{BD`BDf}{BDdDh}{BD`G`}{BDbG`}{BDdG`}{BDhAf}{BDjAf}{BDhBCl}{BDjBDl}{BDhG`}{BDjG`}{BDnAf}{BE`Af}{BEbAf}{BDnI`}{BE`I`}{BEbBEd}{BDnG`}{BE`G`}{BEbG`}{KfAf}{KhAf}{KjAf}{KlAf}{KnAf}{L`Af}{KhDb}{KnDb}{KjBn}{KfDb}{KlLb}{L`I`}{KfG`}{KhG`}{KjG`}{KlG`}{KnG`}{L`G`}`````````{{bd}f}0{{{b{BEf}}AAh}{{`{{A@j{}{{BEh{{Cb{fBEj}}}}}}Ib}}}}{{BElce}BEl{{BEn{{A`{j}}}}}BEf}{{{b{{BF`{c}}}}AAh}{{Cb{fBEj}}}{BEfBFb}}{b{{b{n}}}}{{{b{BEj}}}{{Af{{b{Ad}}}}}}{b{{b{c}}}{}}000{{{b{Aj}}}{{b{Ajc}}}{}}000{A@nBEl}{{{b{BEj}}}{{Af{{b{n}}}}}}{{{b{BFd}}}BFd}{{{b{{BF`{c}}}}}{{BF`{c}}}{BFbBEfBFb}}{{b{b{Ajc}}}f{}}0{{bj}f}0{{}{{Bj{c}}}{}}000{{{b{Aj}}}{{Bj{{b{Ajc}}}}}{}}000{b{{Bj{{b{c}}}}}{}}000{Bn{{b{c}}}{}}000{Bn{{b{Ajc}}}{}}000{{{b{BEj}}}{{b{C`}}}}{Bnf}000{{{b{BFd}}}{{b{A@n}}}}{{{b{BEl}}}{{b{A@n}}}}{{{b{BFd}}{b{AjCn}}}Hh}{{{b{BEl}}{b{AjCn}}}Hh}{{{b{BEj}}{b{AjCn}}}Hh}0{{{b{{BF`{c}}}}{b{AjCn}}}Hh{BFfBEfBFb}}{cc{}}0{ALhBEj}{{{I`{n}}}BEj}{AFhBEj}{AAfBEj}4{ACnBEj}5{cBEj{nIbId}}{{{b{c}}}c{}}0{{}}{{}Bn}000{{}c{}}000{{{b{BFd}}}Bl}{A@nBEl}{{ce}{{BF`{c}}}{BEfBFb}{{BFh{J`}{{BEh{Bl}}}}IbId}}{{{b{BEf}}AAd}{{`{{A@j{}{{BEh{{Cb{AAhBEj}}}}}}Ib}}}}{{{b{{BF`{c}}}}AAd}{{`{{A@j{}{{BEh{{Cb{AAhBEj}}}}}}Ib}}}{BEfBFb}}{{{b{BEf}}}{{`{{A@j{}{{BEh{f}}}}Ib}}}}{{{b{BFd}}}{{Cb{fBFj}}}}{{{b{{BF`{c}}}}}{{`{{A@j{}{{BEh{f}}}}Ib}}}{BEfBFb}}{{{b{BEj}}}{{Af{{b{n}}}}}}{BElBFd}{bc{}}0{bDb}{c{{Cb{e}}}{}{}}000{{}{{Cb{c}}}{}}000{bFh}000{{}c{}}000{BFlAf}{BFlAAf}{BFnACn}{BG`I`}{BFlG`}``{b{{b{c}}}{}}0{{{b{Aj}}}{{b{Ajc}}}{}}0{{}{{Bj{c}}}{}}0{{{b{Aj}}}{{Bj{{b{Ajc}}}}}{}}0{b{{Bj{{b{c}}}}}{}}0{Bn{{b{c}}}{}}0{Bn{{b{Ajc}}}{}}0{{{b{BGb}}Al}Gb}{{{b{BGb}}}Hf}{Bnf}0{{{b{BGd}}{b{AjCn}}}Hh}{{{b{BGb}}{b{AjCn}}}Hh}{cc{}}0{{}Bn}0{{}c{}}0{BGbCh}{BGbDb}{{{b{BGb}}{b{J`}}Ll}{{BGf{f}}}}{BGbEd}{{}{{BGf{BGb}}}}{{}{{Cb{{Dn{BdB`BGh}}BGj}}}}{{{Af{BGl}}Bl}{{Cb{{Dn{BdB`BGh}}BGj}}}}1{Db{{BGf{BGb}}}}{c{{Cb{e}}}{}{}}0{{}{{Cb{c}}}{}}0{bFh}0{{}c{}}0`````````{{bd}f}000{b{{b{n}}}}{{{b{BGn}}}{{Af{{b{Ad}}}}}}{b{{b{c}}}{}}000000{{{b{Aj}}}{{b{Ajc}}}{}}000000{{{b{BGn}}}{{Af{{b{n}}}}}}{{{b{{BH`{c}}}}}{{BH`{c}}}{}}{{{b{{AH`{c}}}}}{{AH`{c}}}BFb}{{{b{{BHb{ce}}}}}{{BHb{ce}}}{BFbBHd}{BFbBFbBHf}}{{{b{{BHh{c}}}}}{{BHh{c}}}{BFbBHdBHj}}{{b{b{Ajc}}}f{}}000{{bj}f}000{{}{{Bj{c}}}{}}000000{{{b{Aj}}}{{Bj{{b{Ajc}}}}}{}}000000{b{{Bj{{b{c}}}}}{}}000000{{}{{BH`{c}}}BHl}{Bn{{b{c}}}{}}000000{Bn{{b{Ajc}}}{}}000000{{{b{BGn}}}{{b{C`}}}}{Bnf}000000{{{b{{BH`{c}}}}{b{AjCn}}}HhBFf}{{{b{{AH`{c}}}}{b{AjCn}}}HhBFf}{{{b{{BHb{ce}}}}{b{AjCn}}}Hh{BFfBHd}{BFfBFbBHf}}{{{b{{BHn{c}}}}{b{AjCn}}}Hh{BFfBHd}}{{{b{{BI`{ce}}}}{b{AjCn}}}HhBFf{BFf{BHd{}{{BIb{{Af{c}}}}}}}}{{{b{{BHh{c}}}}{b{AjCn}}}Hh{BFfBHdBHj}}{{{b{BGn}}{b{AjCn}}}Hh}0{cc{}}000000{{{b{c}}}c{}}000{{{b{{BHd{}{{BIb{c}}}}}}}{{Cb{cBGn}}}{BFbBHf}}{{{b{{BH`{c}}}}}c{BFbBHf}}{{{b{{AH`{c}}}}}{{Cb{eBGn}}}{BFbBHf}{}}{{{b{{BHb{ce}}}}}{{Cb{gBGn}}}BHd{BFbBHf}{}}{{}}{{}Bn}000000{{{b{Aj{BHd{}{{BIb{c}}}}}}}{{BI`{e{BHd{}{{BIb{c}}}}}}}{BFbBHf}{}}{{}c{}}00000033{{{BHd{}{{BIb{c}}}}g}{{Cb{{BHb{{BHd{}{{BIb{c}}}}e}}BGn}}}{BFbBHf}{BFbBHf}{{BFh{c}{{BEh{e}}}}}}{c{{BH`{c}}}{BFbBHf}}{{{BHd{}{{BIb{c}}}}e}{{Dn{{BHd{}{{BIb{c}}}}e}}}{BFbBHf}BHd}{{{A@l{{b{Aj{BHn{c}}}}}}{b{AjALb}}}{{ALd{e}}}BHd{}}{{{A@l{{b{Aj{BI`{ce}}}}}}{b{AjALb}}}{{ALd{g}}}{BFbBHfBHj}{{BHd{}{{BIb{{Af{c}}}}}}BHj}{}}{{{A@l{{b{Aj{BHh{c}}}}}}{b{AjALb}}}{{ALd{{Af{e}}}}}{BHdBHj}{}}{{{b{Aj{BHd{}{{BIb{c}}}}}}{b{AjALb}}}{{ALd{{Cb{cBGn}}}}}{BFbBHf}}{{{b{Aj{AH`{c}}}}{b{AjALb}}}{{ALd{{Cb{eBGn}}}}}{BFbBHf}{}}{{{b{Aj{BHb{ce}}}}{b{AjALb}}}{{ALd{{Cb{gBGn}}}}}BHd{BFbBHf}{}}{{{b{{BIf{BIdceg}}}}}{{BIh{iceg}}}BIjBIlBIn{}}{{{b{{BIf{BIdceg}}}}BJ`}{{BIh{iceg}}}BIjBIlBIn{}}{{{b{{BH`{c}}}}c}{{Cb{cc}}}{BFbBHf}}{{{b{BGn}}}{{Af{{b{n}}}}}}{{{BHd{}{{BIb{c}}}}}{{BHh{{BHd{}{{BIb{c}}}}}}}{BFbBHf}}0{bc{}}000{bDb}{c{{Cb{e}}}{}{}}000000{{}{{Cb{c}}}{}}000000{{{A@l{{b{Ajc}}}}{b{AjALb}}}ALd{}}0{{{A@l{{b{Ajc}}}}{b{AjALb}}}{{ALd{{Af{Cb}}}}}{}}{bFh}000000{{{b{Aj{BHd{}{{BIb{c}}}}}}}{{BHn{{BHd{}{{BIb{c}}}}}}}{BFbBHf}}{{}c{}}000000{{{b{{BH`{c}}}}}{{AH`{c}}}{BFbBHf}}","D":"GMf","p":[[1,"reference",null,null,1],[5,"Private",4075],[1,"unit"],[5,"PublicKey",0,4076],[1,"u8"],[1,"array"],[10,"Error",4077],[1,"slice"],[6,"KeyParsingError",0,4076],[5,"Backtrace",4078],[6,"Option",4079,null,1],[5,"RelayUrlParseError",0,4080],[0,"mut"],[5,"SecretKey",0,4076],[5,"NodeAddr",0,4081],[5,"RelayUrl",0,4080],[6,"RelayProtocol",0],[5,"RelayMap",0,4082],[5,"RelayNode",0,4082],[6,"Ordering",4083],[5,"Compat",4084],[1,"bool"],[1,"usize"],[1,"str"],[6,"Result",4085,null,1],[10,"Deserializer",4086],[17,"Item"],[6,"SocketAddr",4087],[10,"Iterator",4088],[5,"BTreeSet",4089],[5,"Formatter",4090],[5,"Error",4090],[5,"String",4091],[5,"VerifyingKey",4092],[5,"DecodeError",4093],[5,"Error",4094],[5,"SigningKey",4095],[5,"NodeTicket",4096],[1,"tuple",null,null,1],[5,"RemoteInfo",1134,4097],[5,"NodeInfo",3663,4098],[5,"Url",4099],[10,"IntoIterator",4100],[6,"DecodingError",3664,4098],[10,"CryptoRngCore",4101],[5,"Arc",4102,null,1],[10,"Hasher",4103],[5,"HeaderValue",4104],[10,"Serializer",4105],[5,"Signature",4106],[1,"u16"],[5,"TypeId",4107],[15,"Decode",350],[15,"Key",350],[15,"DecodeInvalidLength",350],[5,"SpanTrace",4108],[5,"ConcurrentDiscovery",3663],[10,"Discovery",3663],[5,"NodeData",3663,4098],[5,"UserData",3663,4098],[6,"ParseError",3663,4098],[6,"IntoDiscoveryError",3663],[6,"DiscoveryError",3663],[5,"Lagged",3663],[5,"DiscoveryItem",3663],[5,"DiscoveryContext",3663],[5,"DnsResolver",1091,4109],[8,"Result",4090],[6,"IrohAttr",4098],[5,"TxtAttrs",4098],[6,"PkarrError",833],[5,"Box",4110,null,1],[10,"Send",4111],[10,"Sync",4111],[5,"SignedPacket",4112],[5,"Vec",4113],[5,"TxtLookup",4109],[10,"IntoDiscovery",3663],[1,"u64"],[8,"NodeId",0,4076],[8,"Boxed",4114],[1,"u32"],[6,"EncodingError",3664,4098],[15,"NoServiceConfigured",708],[15,"NodeId",708],[15,"NoResults",708],[15,"SignedPacket",708],[15,"ParsePacket",708],[15,"User",708],[15,"User",726],[15,"UnexpectedFormat",3713],[15,"AttrFromString",3713],[15,"NumLabels",3713],[15,"Utf8",3713],[15,"NotAnIrohRecord",3713],[15,"DecodingError",3713],[5,"Utf8Error",4115],[5,"DnsDiscoveryBuilder",748],[5,"DnsDiscovery",748],[5,"MdnsDiscoveryBuilder",791],[5,"MdnsDiscovery",791],[5,"Duration",4116],[5,"PkarrPublisherBuilder",833],[5,"PkarrPublisher",833],[5,"PkarrResolverBuilder",833],[5,"PkarrResolver",833],[5,"PkarrRelayClient",833],[15,"PublicKey",993],[6,"PublicKeyError",4117],[15,"Verify",993],[6,"SignedPacketVerifyError",4112],[15,"HttpSend",993],[5,"Error",4118],[15,"HttpPayload",993],[15,"HttpRequest",993],[5,"StatusCode",4119],[15,"InvalidRelayUrl",993],[5,"Builder",999],[5,"DhtDiscovery",999],[5,"Client",4120],[5,"StaticProvider",1057],[10,"Into",4121,null,1],[8,"Result",4122],[5,"TokioRuntimeProvider",4123],[5,"GenericConnector",4124],[5,"Resolver",4125],[6,"IpAddr",4126],[6,"DnsError",4109],[10,"ToString",4091],[6,"LookupError",3664,4098],[5,"Error",4127],[5,"Name",4128],[10,"Future",4129,null,1],[5,"Pin",4130],[5,"Endpoint",1134],[5,"Accept",1134],[5,"Incoming",1134],[5,"Connecting",1134],[6,"ConnectionError",1134,4131],[5,"Connection",1134],[5,"AcceptBi",1134,4132],[5,"AcceptUni",1134,4132],[5,"ServerConfig",1134,4133],[5,"AckFrequencyConfig",1134,4134],[5,"VarInt",1134,4135],[5,"FrameStats",1134,4136],[5,"TransportConfig",1134,4134],[5,"Builder",1134],[6,"AddNodeAddrError",1134,4137],[5,"DirectAddrInfo",1134,4097],[5,"DirectAddr",1134,4137],[10,"HandshakeTokenKey",1134,4138],[10,"AeadKey",1134,4138],[6,"AlpnError",1134],[6,"ConnectWithOptsError",1134],[6,"ConnectError",1134],[6,"BindError",1134],[6,"GetMappingAddressError",1134],[5,"RemoteNodeIdError",1134],[5,"SocketAddrV4",4087],[5,"SocketAddrV6",4087],[5,"MtuDiscoveryConfig",1134,4134],[5,"PathStats",1134,4136],[10,"ControllerFactory",1134,4139],[5,"Instant",4140],[10,"Controller",1134,4139],[5,"Chunk",1134,4141],[5,"Bytes",4142],[5,"UdpStats",1134,4136],[5,"Written",1134,4143],[6,"SendDatagramError",1134,4132],[6,"ReadToEndError",1134,4144],[6,"ReadError",1134,4144],[6,"ResetError",1134,4144],[6,"ReadExactError",1134,4144],[6,"WriteError",1134,4145],[6,"StoppedError",1134,4145],[5,"ConnectionStats",1134,4136],[6,"ControlMsg",1134,4097],[5,"ClosedStream",1134,4146],[6,"ConnectionType",1134,4097],[6,"Source",1134,4147],[5,"ConnectionClose",1134,4148],[5,"ApplicationClose",1134,4148],[5,"TransportError",1134],[5,"TransportErrorCode",1134],[5,"StreamId",1134,4149],[6,"DirectAddrType",1134,4137],[6,"PathSelection",1134],[5,"ConnectOptions",1134],[6,"RelayMode",1134],[5,"Direct",3895],[5,"UnexpectedEnd",4150],[10,"Buf",4151],[6,"Dir",4149],[10,"Stream",4152],[5,"RecvStream",1134,4144],[5,"SendStream",1134,4145],[10,"BufMut",4153],[5,"ExportKeyingMaterialError",1134,4138],[5,"WeakConnectionHandle",1134,4132],[5,"RetryError",1134,4154],[5,"CryptoError",1134,4138],[5,"UnsupportedVersion",1134,4138],[5,"IncomingFuture",1134],[5,"ZeroRttAccepted",1134],[6,"ReadableError",4155],[6,"Close",4148],[5,"Unspecified",4156],[6,"Error",4157],[5,"InvalidFrame",4148],[5,"VarIntBoundsExceeded",4135],[10,"Any",4107],[10,"CryptoServerConfig",1134],[5,"ConnectionId",4158],[5,"Keys",4138],[6,"Side",4149],[5,"Incoming",4154],[5,"IdleTimeout",4134],[5,"EndpointMetrics",3137],[8,"NodeAddrWatcher",1134],[5,"RttEstimator",4159],[5,"OpenBi",1134,4132],[5,"OpenUni",1134,4132],[5,"Context",4160],[6,"Poll",4161],[5,"ReadDatagram",1134,4132],[5,"Error",4162],[5,"ReadBuf",4163],[1,"i32"],[5,"HashMap",4164],[5,"TransportParameters",4157],[10,"Session",4138],[10,"TimeSource",4133],[1,"f32"],[1,"u128"],[5,"ValidationTokenConfig",4133],[5,"CertificateDer",4165],[6,"PrivateKeyDer",4165],[6,"Error",4166],[15,"Empty",3090],[15,"EmptyPruned",3090],[15,"OwnAddress",3090],[15,"ConnectionError",3097],[15,"Unavailable",3097],[15,"UnknownHandshake",3097],[15,"MagicSpawn",3104],[15,"Discovery",3104],[15,"Connect",3110],[15,"Connection",3110],[15,"AddNodeAddr",3116],[15,"SelfConnect",3116],[15,"NoAddress",3116],[15,"Quinn",3116],[6,"ConnectError",4167],[15,"DiscoveryStart",3127],[15,"Discover",3127],[15,"NoAddress",3127],[15,"Discovery",3135],[15,"NamedApp",3135],[5,"RelayMetrics",3137],[5,"Counter",4168],[5,"MagicsockMetrics",3137],[10,"Iterable",4169],[5,"PortmapMetrics",3137],[5,"MetricItem",4170],[10,"MetricsGroup",4170],[5,"Client",3317],[5,"Addr",3317],[6,"ReportError",3317],[6,"IpFamily",4171],[5,"CancellationToken",4172],[5,"UdpSocket",4173],[5,"Report",3317],[5,"QuicConfig",3317,4174],[5,"ClientConfig",4175],[5,"Options",3317,4176],[5,"RelayLatencies",3317],[5,"Metrics",3317,4177],[5,"Endpoint",4178],[5,"Client",4179],[15,"Abort",3557],[15,"AlreadyRunning",3557],[15,"ActorGone",3557],[5,"MaxLengthExceededError",3664,4098],[6,"SignedPacketBuildError",4112],[10,"NodeIdExt",3664,4098],[15,"InvalidEncodingZ32",3689],[15,"InvalidLength",3689],[15,"InvalidSignature",3689],[6,"Z32Error",4180],[15,"FailedBuildingPacket",3698],[15,"InvalidTxtEntry",3698],[6,"SimpleDnsError",4181],[15,"ParseError",3704],[15,"LookupFailed",3704],[15,"InvalidLabel",3704],[5,"ProtoError",4182],[10,"ProtocolHandler",3731],[17,"Output"],[6,"ProtocolError",3731],[5,"RouterBuilder",3731],[10,"AsRef",4121],[5,"AccessLimit",3731],[10,"Clone",4183],[5,"Router",3731],[10,"Debug",4090],[10,"Fn",4184],[5,"JoinError",4185],[15,"Connect",3845],[15,"RemoteNodeId",3845],[15,"User",3845],[5,"DnsPkarrServer",3850,4186],[5,"CleanupDropGuard",3850],[8,"Result",4162],[5,"Server",4187],[6,"SpawnError",4187],[5,"StunConfig",4187],[5,"Disconnected",3895],[5,"Watchable",3895],[5,"Map",3895],[10,"Watcher",3895],[10,"Eq",4083],[5,"Stream",3895],[10,"Unpin",4111],[10,"Default",4188],[5,"NextFut",3895],[5,"InitializedFut",3895],[17,"Value"],[6,"NotKeyed",4189],[5,"RateLimiter",4190],[5,"RatelimitedStream",4191],[10,"DirectStateStore",4189],[10,"ReasonablyRealtime",4192],[10,"RateLimitingMiddleware",4193],[5,"Jitter",4194]],"r":[[0,4076],[1,4076],[2,1134],[3,4076],[4,4076],[5,4076],[6,4081],[7,4076],[8,4076],[10,4082],[11,1134],[12,4082],[14,4080],[15,4080],[16,4076],[18,4076],[19,4076],[20,4081],[21,4080],[23,4082],[24,4082],[25,4076],[26,4076],[27,4080],[28,4076],[29,4076],[30,4080],[31,4076],[32,4076],[33,4076],[34,4076],[35,4081],[36,4080],[37,4080],[39,4082],[40,4082],[41,4076],[42,4076],[43,4076],[44,4081],[45,4080],[46,4080],[48,4082],[49,4082],[50,4076],[51,4080],[52,4076],[53,4076],[54,4081],[55,4080],[57,4082],[58,4082],[59,4076],[60,4076],[61,4081],[62,4080],[64,4082],[65,4082],[66,4076],[67,4076],[68,4081],[69,4080],[71,4082],[72,4082],[73,4076],[74,4081],[75,4080],[76,4082],[77,4076],[78,4081],[79,4080],[80,4082],[81,4076],[82,4076],[83,4076],[84,4081],[85,4080],[86,4080],[88,4082],[89,4082],[90,4076],[91,4076],[92,4076],[93,4081],[94,4080],[95,4080],[97,4082],[98,4082],[99,4076],[100,4076],[101,4076],[102,4081],[103,4080],[104,4080],[106,4082],[107,4082],[108,4082],[111,4076],[112,4076],[113,4076],[114,4081],[115,4080],[116,4080],[117,4080],[119,4082],[120,4082],[121,4076],[122,4076],[123,4076],[124,4081],[125,4080],[126,4080],[128,4082],[129,4082],[130,4076],[131,4080],[132,4076],[133,4076],[134,4081],[135,4080],[136,4082],[137,4081],[138,4081],[141,4076],[142,4076],[143,4076],[144,4081],[145,4080],[146,4080],[148,4082],[149,4082],[150,4082],[152,4076],[153,4081],[154,4080],[156,4082],[157,4082],[158,4076],[159,4076],[160,4076],[161,4081],[162,4081],[163,4081],[164,4080],[165,4080],[166,4080],[170,4082],[171,4082],[172,4082],[173,4082],[174,4082],[175,4082],[176,4076],[177,4076],[178,4076],[179,4076],[180,4076],[181,4076],[182,4081],[183,4080],[184,4080],[185,4080],[186,4080],[188,4082],[189,4082],[190,4082],[191,4082],[192,4076],[193,4076],[194,4076],[195,4076],[196,4076],[197,4076],[198,4076],[199,4076],[200,4076],[201,4081],[202,4081],[203,4081],[204,4081],[205,4081],[206,4081],[207,4080],[208,4080],[209,4080],[211,4082],[212,4082],[213,4082],[214,4082],[215,4082],[216,4076],[217,4076],[218,4082],[219,4082],[220,4081],[221,4076],[222,4076],[223,4081],[224,4080],[226,4082],[227,4082],[228,4076],[229,4076],[230,4080],[231,4076],[232,4076],[233,4082],[234,4076],[235,4080],[236,4076],[237,4080],[238,4076],[239,4076],[240,4076],[241,4081],[242,4080],[243,4080],[245,4082],[246,4082],[247,4076],[248,4076],[249,4076],[250,4081],[251,4080],[252,4080],[254,4082],[255,4082],[256,4081],[257,4082],[258,4082],[261,4081],[262,4081],[263,4195],[264,4082],[266,4076],[267,4081],[268,4080],[269,4082],[271,4076],[272,4076],[273,4082],[274,4081],[275,4081],[276,4076],[277,4076],[278,4076],[279,4081],[280,4080],[281,4082],[282,4076],[283,4076],[284,4080],[285,4082],[286,4082],[288,4076],[289,4076],[290,4076],[291,4081],[292,4080],[294,4082],[295,4082],[296,4076],[297,4076],[298,4076],[299,4080],[300,4080],[301,4082],[302,4082],[303,4076],[304,4076],[305,4076],[306,4076],[307,4076],[308,4076],[309,4076],[310,4081],[311,4080],[312,4080],[314,4082],[315,4082],[316,4076],[317,4076],[318,4076],[319,4081],[320,4080],[321,4080],[323,4082],[324,4082],[325,4076],[326,4076],[327,4076],[328,4081],[329,4080],[330,4080],[332,4082],[333,4082],[335,4082],[336,4082],[337,4076],[338,4076],[339,4076],[340,4076],[341,4081],[342,4080],[343,4080],[345,4082],[346,4082],[348,4081],[349,4081],[361,4196],[362,4196],[377,4098],[379,4098],[387,4098],[390,4098],[392,4098],[393,4098],[394,4098],[395,4098],[398,4098],[401,4098],[402,4098],[403,4098],[404,4098],[405,4098],[408,4098],[409,4098],[413,4098],[414,4098],[418,4098],[419,4098],[420,4098],[421,4098],[428,4098],[429,4098],[430,4098],[431,4098],[438,4098],[442,4098],[443,4098],[444,4098],[445,4098],[447,4098],[448,4098],[449,4098],[451,4098],[452,4098],[453,4098],[455,4098],[456,4098],[457,4098],[458,4098],[459,4098],[460,4098],[467,4098],[468,4098],[469,4098],[470,4098],[477,4098],[478,4098],[479,4098],[480,4098],[487,4098],[488,4098],[490,4098],[491,4098],[492,4098],[493,4098],[494,4098],[502,4098],[503,4098],[504,4098],[505,4098],[506,4098],[513,4098],[517,4098],[520,4098],[521,4098],[522,4098],[523,4098],[531,4098],[532,4098],[533,4098],[534,4098],[535,4098],[536,4098],[537,4098],[538,4098],[539,4098],[540,4098],[541,4098],[542,4098],[543,4098],[544,4098],[545,4098],[546,4098],[547,4098],[548,4098],[558,4098],[559,4098],[560,4098],[561,4098],[562,4098],[563,4098],[564,4098],[565,4098],[566,4098],[567,4098],[580,4098],[581,4098],[582,4098],[583,4098],[584,4098],[587,4098],[588,4098],[589,4098],[590,4098],[594,4098],[595,4098],[596,4098],[597,4098],[604,4098],[605,4098],[606,4098],[607,4098],[616,4098],[620,4098],[621,4098],[625,4098],[627,4098],[632,4098],[636,4098],[637,4098],[638,4098],[645,4098],[647,4098],[648,4098],[649,4098],[651,4098],[652,4098],[653,4098],[657,4098],[658,4098],[659,4098],[660,4098],[661,4098],[662,4098],[669,4098],[670,4098],[671,4098],[672,4098],[679,4098],[680,4098],[681,4098],[682,4098],[689,4098],[692,4098],[693,4098],[694,4098],[695,4098],[702,4098],[703,4098],[704,4098],[705,4098],[706,4098],[707,4098],[750,4109],[751,4109],[1091,4109],[1092,4109],[1093,4109],[1094,4109],[1095,4109],[1096,4109],[1097,4109],[1098,4109],[1099,4109],[1100,4109],[1101,4109],[1102,4109],[1103,4109],[1104,4109],[1105,4109],[1106,4109],[1107,4109],[1108,4109],[1109,4109],[1110,4109],[1111,4109],[1112,4109],[1113,4109],[1114,4109],[1115,4109],[1116,4109],[1117,4109],[1118,4109],[1119,4109],[1120,4109],[1121,4109],[1122,4109],[1123,4109],[1124,4109],[1125,4109],[1126,4109],[1127,4109],[1128,4109],[1129,4109],[1130,4109],[1131,4109],[1132,4109],[1133,4109],[1137,4132],[1138,4132],[1139,4134],[1141,4137],[1142,4138],[1145,4147],[1146,4148],[1147,4131],[1153,4097],[1154,4141],[1155,4131],[1156,4146],[1157,4144],[1158,4145],[1166,4148],[1167,4131],[1168,4131],[1170,4132],[1171,4144],[1172,4144],[1173,4145],[1174,4145],[1175,4136],[1176,4097],[1177,4097],[1178,4139],[1179,4139],[1180,4138],[1184,4097],[1185,4137],[1186,4097],[1187,4137],[1188,4132],[1191,4147],[1195,4137],[1196,4137],[1198,4138],[1202,4144],[1203,4136],[1205,4138],[1208,4144],[1212,4137],[1213,4131],[1214,4135],[1215,4135],[1217,4097],[1218,4134],[1221,4147],[1225,4097],[1226,4132],[1227,4132],[1228,4137],[1231,4136],[1232,4097],[1233,4097],[1234,4137],[1236,4144],[1237,4132],[1238,4144],[1239,4144],[1240,4144],[1241,4144],[1242,4144],[1243,4097],[1244,4147],[1247,4097],[1249,4144],[1250,4131],[1251,4144],[1252,4154],[1255,4147],[1257,4132],[1258,4145],[1259,4133],[1260,4147],[1262,4145],[1263,4145],[1264,4149],[1265,4137],[1266,4137],[1268,4131],[1269,4132],[1270,4144],[1271,4134],[1273,4131],[1275,4147],[1276,4136],[1278,4137],[1280,4132],[1281,4138],[1282,4135],[1283,4131],[1284,4132],[1285,4145],[1286,4143],[1288,4144],[1289,4144],[1290,4145],[1291,4145],[1292,4132],[1293,4144],[1294,4144],[1295,4144],[1296,4144],[1297,4145],[1298,4145],[1299,4135],[1300,4136],[1301,4136],[1302,4136],[1303,4136],[1304,4143],[1305,4097],[1306,4146],[1307,4097],[1308,4097],[1309,4097],[1310,4147],[1311,4131],[1312,4134],[1313,4134],[1314,4133],[1315,4148],[1316,4148],[1319,4149],[1320,4137],[1321,4137],[1332,4134],[1333,4136],[1334,4134],[1335,4136],[1339,4097],[1340,4137],[1341,4097],[1342,4138],[1343,4134],[1347,4132],[1348,4154],[1349,4144],[1350,4144],[1351,4144],[1352,4144],[1353,4145],[1354,4145],[1355,4146],[1356,4131],[1357,4137],[1365,4137],[1375,4134],[1376,4136],[1377,4132],[1378,4132],[1379,4132],[1380,4132],[1381,4132],[1382,4132],[1383,4132],[1384,4154],[1385,4144],[1386,4144],[1387,4144],[1388,4144],[1389,4144],[1390,4145],[1391,4145],[1392,4145],[1393,4134],[1394,4135],[1395,4141],[1396,4136],[1397,4136],[1398,4136],[1399,4136],[1400,4143],[1401,4097],[1402,4146],[1403,4097],[1404,4097],[1405,4097],[1406,4147],[1407,4131],[1408,4134],[1409,4134],[1410,4133],[1411,4138],[1412,4138],[1413,4138],[1414,4148],[1415,4148],[1416,4137],[1419,4149],[1420,4137],[1421,4137],[1439,4132],[1440,4132],[1441,4132],[1442,4132],[1443,4132],[1444,4132],[1445,4132],[1446,4154],[1447,4144],[1448,4144],[1449,4144],[1450,4144],[1451,4144],[1452,4145],[1453,4145],[1454,4145],[1455,4134],[1456,4135],[1457,4141],[1458,4136],[1459,4136],[1460,4136],[1461,4136],[1462,4143],[1463,4097],[1464,4146],[1465,4097],[1466,4097],[1467,4097],[1468,4147],[1469,4131],[1470,4134],[1471,4134],[1472,4133],[1473,4138],[1474,4138],[1475,4138],[1476,4148],[1477,4148],[1478,4137],[1481,4149],[1482,4137],[1483,4137],[1502,4139],[1504,4141],[1505,4136],[1506,4143],[1507,4137],[1514,4143],[1516,4132],[1517,4144],[1518,4144],[1519,4144],[1520,4144],[1521,4145],[1522,4145],[1523,4135],[1524,4136],[1525,4136],[1526,4136],[1527,4136],[1528,4143],[1529,4097],[1530,4146],[1531,4097],[1532,4097],[1533,4097],[1534,4147],[1535,4131],[1536,4134],[1537,4134],[1538,4133],[1539,4148],[1540,4148],[1543,4149],[1544,4137],[1545,4137],[1551,4139],[1552,4132],[1553,4144],[1554,4144],[1555,4144],[1556,4144],[1557,4145],[1558,4145],[1559,4135],[1560,4136],[1561,4136],[1562,4136],[1563,4136],[1564,4143],[1565,4097],[1566,4146],[1567,4097],[1568,4097],[1569,4097],[1570,4147],[1571,4131],[1572,4134],[1573,4134],[1574,4133],[1575,4148],[1576,4148],[1579,4149],[1580,4137],[1581,4137],[1587,4132],[1588,4144],[1589,4144],[1590,4144],[1591,4144],[1592,4145],[1593,4145],[1594,4135],[1595,4136],[1596,4136],[1597,4136],[1598,4136],[1599,4143],[1600,4097],[1601,4146],[1602,4097],[1603,4097],[1604,4097],[1605,4147],[1606,4131],[1607,4134],[1608,4134],[1609,4133],[1610,4148],[1611,4148],[1614,4149],[1615,4137],[1616,4137],[1626,4135],[1627,4149],[1628,4137],[1629,4137],[1631,4135],[1632,4149],[1633,4137],[1634,4137],[1635,4132],[1636,4132],[1637,4132],[1638,4132],[1639,4132],[1640,4132],[1641,4132],[1642,4154],[1643,4144],[1644,4144],[1645,4144],[1646,4144],[1647,4144],[1648,4145],[1649,4145],[1650,4145],[1651,4134],[1652,4135],[1653,4141],[1654,4136],[1655,4136],[1656,4136],[1657,4136],[1658,4143],[1659,4097],[1660,4146],[1661,4097],[1662,4097],[1663,4097],[1664,4147],[1665,4131],[1666,4134],[1667,4134],[1668,4133],[1669,4138],[1670,4138],[1671,4138],[1672,4148],[1673,4148],[1674,4137],[1677,4149],[1678,4137],[1679,4137],[1697,4132],[1698,4132],[1699,4132],[1700,4132],[1701,4132],[1702,4132],[1703,4132],[1704,4154],[1705,4144],[1706,4144],[1707,4144],[1708,4144],[1709,4144],[1710,4145],[1711,4145],[1712,4145],[1713,4134],[1714,4135],[1715,4141],[1716,4136],[1717,4136],[1718,4136],[1719,4136],[1720,4143],[1721,4097],[1722,4146],[1723,4097],[1724,4097],[1725,4097],[1726,4147],[1727,4131],[1728,4134],[1729,4134],[1730,4133],[1731,4138],[1732,4138],[1733,4138],[1734,4148],[1735,4148],[1736,4137],[1739,4149],[1740,4137],[1741,4137],[1759,4132],[1760,4132],[1761,4132],[1762,4132],[1763,4132],[1764,4132],[1765,4132],[1766,4154],[1767,4144],[1768,4144],[1769,4144],[1770,4144],[1771,4144],[1772,4145],[1773,4145],[1774,4145],[1775,4134],[1776,4135],[1777,4141],[1778,4136],[1779,4136],[1780,4136],[1781,4136],[1782,4143],[1783,4097],[1784,4146],[1785,4097],[1786,4097],[1787,4097],[1788,4147],[1789,4131],[1790,4134],[1791,4134],[1792,4133],[1793,4138],[1794,4138],[1795,4138],[1796,4148],[1797,4148],[1798,4137],[1801,4149],[1802,4137],[1803,4137],[1821,4134],[1822,4136],[1825,4097],[1828,4136],[1830,4136],[1831,4133],[1832,4134],[1833,4136],[1834,4136],[1835,4136],[1836,4136],[1837,4134],[1838,4134],[1840,4136],[1841,4135],[1843,4149],[1844,4134],[1845,4135],[1846,4136],[1847,4136],[1848,4136],[1849,4136],[1850,4143],[1851,4146],[1852,4097],[1853,4134],[1854,4134],[1859,4132],[1860,4132],[1861,4132],[1862,4132],[1863,4132],[1864,4132],[1865,4132],[1866,4154],[1867,4144],[1868,4144],[1869,4144],[1870,4144],[1871,4144],[1872,4145],[1873,4145],[1874,4145],[1875,4134],[1876,4135],[1877,4141],[1878,4136],[1879,4136],[1880,4136],[1881,4136],[1882,4143],[1883,4097],[1884,4146],[1885,4097],[1886,4097],[1887,4097],[1888,4147],[1889,4131],[1890,4134],[1891,4134],[1892,4133],[1893,4138],[1894,4138],[1895,4138],[1896,4148],[1897,4148],[1898,4137],[1901,4149],[1902,4137],[1903,4137],[1921,4132],[1922,4132],[1923,4132],[1924,4132],[1925,4132],[1926,4132],[1927,4132],[1928,4154],[1929,4144],[1930,4144],[1931,4144],[1932,4144],[1933,4144],[1934,4145],[1935,4145],[1936,4145],[1937,4134],[1938,4135],[1939,4141],[1940,4136],[1941,4136],[1942,4136],[1943,4136],[1944,4143],[1945,4097],[1946,4146],[1947,4097],[1948,4097],[1949,4097],[1950,4147],[1951,4131],[1952,4134],[1953,4134],[1954,4133],[1955,4138],[1956,4138],[1957,4138],[1958,4148],[1959,4148],[1960,4137],[1963,4149],[1964,4137],[1965,4137],[1983,4137],[1990,4097],[1991,4097],[1992,4097],[1993,4097],[1994,4147],[1995,4149],[2005,4132],[2006,4132],[2007,4132],[2008,4132],[2009,4132],[2010,4132],[2011,4132],[2012,4154],[2013,4144],[2014,4144],[2015,4144],[2016,4144],[2017,4144],[2018,4144],[2019,4145],[2020,4145],[2021,4145],[2022,4145],[2023,4134],[2024,4135],[2025,4141],[2026,4136],[2027,4136],[2028,4136],[2029,4136],[2030,4143],[2031,4097],[2032,4146],[2033,4097],[2034,4097],[2035,4097],[2036,4147],[2037,4131],[2038,4134],[2039,4134],[2040,4133],[2041,4138],[2042,4138],[2043,4138],[2044,4148],[2045,4148],[2046,4137],[2049,4149],[2050,4137],[2051,4137],[2069,4134],[2070,4135],[2072,4149],[2073,4132],[2074,4144],[2075,4144],[2076,4144],[2077,4144],[2078,4145],[2079,4145],[2080,4135],[2081,4141],[2082,4143],[2083,4097],[2084,4146],[2085,4097],[2086,4097],[2087,4097],[2088,4147],[2089,4131],[2090,4138],[2091,4148],[2092,4148],[2095,4149],[2096,4137],[2097,4137],[2100,4132],[2101,4132],[2102,4132],[2103,4144],[2104,4144],[2105,4144],[2106,4144],[2107,4144],[2108,4144],[2109,4144],[2110,4144],[2111,4144],[2112,4144],[2113,4144],[2114,4144],[2115,4145],[2116,4145],[2117,4145],[2118,4145],[2119,4145],[2120,4145],[2121,4135],[2122,4135],[2123,4135],[2124,4141],[2125,4141],[2126,4141],[2127,4143],[2128,4143],[2129,4143],[2130,4097],[2131,4097],[2132,4097],[2133,4146],[2134,4146],[2135,4146],[2136,4097],[2137,4097],[2138,4097],[2139,4097],[2140,4097],[2141,4097],[2142,4097],[2143,4097],[2144,4097],[2145,4147],[2146,4147],[2147,4147],[2148,4131],[2149,4131],[2150,4131],[2151,4138],[2152,4138],[2153,4138],[2154,4148],[2155,4148],[2156,4148],[2157,4148],[2158,4148],[2159,4148],[2166,4149],[2167,4149],[2168,4149],[2169,4137],[2170,4137],[2171,4137],[2172,4137],[2173,4137],[2174,4137],[2181,4148],[2182,4148],[2184,4145],[2185,4132],[2186,4132],[2187,4132],[2188,4154],[2189,4154],[2190,4144],[2191,4144],[2192,4144],[2193,4144],[2194,4144],[2195,4144],[2196,4144],[2197,4144],[2198,4144],[2199,4145],[2200,4145],[2201,4145],[2202,4145],[2203,4145],[2204,4134],[2205,4135],[2206,4135],[2207,4141],[2208,4136],[2209,4136],[2210,4136],[2211,4136],[2212,4143],[2213,4097],[2214,4097],[2215,4146],[2216,4146],[2217,4097],[2218,4097],[2219,4097],[2220,4097],[2221,4147],[2222,4147],[2223,4131],[2224,4131],[2225,4134],[2226,4134],[2227,4133],[2228,4138],[2229,4138],[2230,4138],[2231,4148],[2232,4148],[2233,4148],[2234,4148],[2235,4137],[2236,4137],[2241,4149],[2242,4149],[2243,4137],[2244,4137],[2245,4137],[2271,4136],[2272,4136],[2273,4148],[2274,4132],[2275,4132],[2276,4132],[2277,4132],[2278,4132],[2279,4132],[2280,4132],[2281,4132],[2282,4154],[2283,4144],[2284,4144],[2285,4144],[2286,4144],[2287,4144],[2288,4144],[2289,4144],[2290,4144],[2291,4144],[2292,4144],[2293,4144],[2294,4145],[2295,4145],[2296,4145],[2297,4145],[2298,4145],[2299,4145],[2300,4145],[2301,4134],[2302,4135],[2303,4135],[2304,4135],[2305,4135],[2306,4135],[2307,4141],[2308,4136],[2309,4136],[2310,4136],[2311,4136],[2312,4143],[2313,4097],[2314,4146],[2315,4097],[2316,4097],[2317,4097],[2318,4147],[2319,4131],[2320,4131],[2321,4131],[2322,4134],[2323,4134],[2324,4133],[2325,4138],[2326,4138],[2327,4138],[2328,4138],[2329,4148],[2330,4148],[2331,4148],[2332,4137],[2338,4149],[2339,4149],[2340,4137],[2341,4137],[2364,4132],[2365,4144],[2366,4144],[2367,4144],[2368,4144],[2369,4145],[2370,4145],[2371,4135],[2372,4136],[2373,4136],[2374,4136],[2375,4136],[2376,4143],[2377,4097],[2378,4146],[2379,4097],[2380,4097],[2381,4097],[2382,4147],[2383,4131],[2384,4134],[2385,4134],[2386,4133],[2387,4148],[2388,4148],[2391,4149],[2392,4137],[2393,4137],[2399,4135],[2400,4135],[2401,4135],[2404,4136],[2405,4097],[2406,4135],[2407,4147],[2408,4149],[2409,4137],[2410,4137],[2412,4144],[2413,4145],[2415,4136],[2416,4132],[2417,4154],[2418,4144],[2419,4144],[2420,4144],[2421,4144],[2422,4145],[2423,4145],[2424,4146],[2425,4131],[2426,4137],[2434,4133],[2435,4133],[2436,4149],[2437,4132],[2438,4132],[2439,4132],[2440,4132],[2441,4132],[2442,4132],[2443,4132],[2444,4154],[2445,4144],[2446,4144],[2447,4144],[2448,4144],[2449,4144],[2450,4145],[2451,4145],[2452,4145],[2453,4134],[2454,4135],[2455,4141],[2456,4136],[2457,4136],[2458,4136],[2459,4136],[2460,4143],[2461,4097],[2462,4146],[2463,4097],[2464,4097],[2465,4097],[2466,4147],[2467,4131],[2468,4134],[2469,4134],[2470,4133],[2471,4138],[2472,4138],[2473,4138],[2474,4148],[2475,4148],[2476,4137],[2479,4149],[2480,4137],[2481,4137],[2500,4134],[2501,4134],[2502,4139],[2503,4149],[2505,4134],[2506,4132],[2507,4132],[2508,4132],[2509,4132],[2510,4132],[2511,4132],[2512,4132],[2513,4154],[2514,4144],[2515,4144],[2516,4144],[2517,4144],[2518,4144],[2519,4145],[2520,4145],[2521,4145],[2522,4134],[2523,4135],[2524,4141],[2525,4136],[2526,4136],[2527,4136],[2528,4136],[2529,4143],[2530,4097],[2531,4146],[2532,4097],[2533,4097],[2534,4097],[2535,4147],[2536,4131],[2537,4134],[2538,4134],[2539,4133],[2540,4138],[2541,4138],[2542,4138],[2543,4148],[2544,4148],[2545,4137],[2548,4149],[2549,4137],[2550,4137],[2569,4139],[2570,4132],[2571,4132],[2572,4132],[2573,4132],[2574,4132],[2580,4154],[2581,4135],[2582,4136],[2583,4144],[2584,4132],[2586,4134],[2589,4097],[2590,4097],[2591,4097],[2592,4097],[2593,4097],[2594,4097],[2595,4097],[2597,4136],[2598,4136],[2599,4136],[2600,4134],[2601,4134],[2602,4134],[2603,4136],[2605,4134],[2606,4133],[2607,4136],[2608,4136],[2609,4136],[2611,4133],[2612,4134],[2613,4134],[2614,4134],[2616,4132],[2617,4133],[2618,4149],[2620,4136],[2621,4136],[2624,4097],[2625,4136],[2626,4141],[2627,4139],[2628,4139],[2629,4139],[2630,4139],[2631,4139],[2632,4138],[2635,4134],[2636,4135],[2637,4149],[2638,4137],[2639,4137],[2640,4136],[2641,4136],[2642,4136],[2645,4134],[2646,4136],[2647,4132],[2648,4132],[2649,4132],[2650,4132],[2651,4132],[2656,4145],[2657,4144],[2658,4144],[2659,4145],[2660,4145],[2661,4145],[2662,4133],[2663,4133],[2664,4145],[2667,4144],[2668,4144],[2669,4144],[2671,4144],[2672,4144],[2673,4148],[2674,4148],[2676,4134],[2677,4134],[2678,4144],[2683,4097],[2689,4134],[2690,4145],[2691,4136],[2692,4136],[2695,4133],[2697,4136],[2698,4135],[2699,4138],[2703,4134],[2704,4134],[2705,4134],[2706,4136],[2707,4136],[2708,4097],[2709,4097],[2710,4097],[2711,4097],[2712,4147],[2716,4145],[2719,4132],[2720,4144],[2721,4144],[2722,4144],[2723,4144],[2724,4145],[2725,4145],[2726,4131],[2727,4137],[2734,4097],[2735,4097],[2739,4144],[2740,4136],[2741,4145],[2742,4136],[2743,4136],[2744,4134],[2745,4136],[2746,4136],[2747,4133],[2748,4134],[2749,4132],[2750,4144],[2751,4144],[2752,4144],[2753,4144],[2754,4145],[2755,4145],[2756,4135],[2757,4136],[2758,4136],[2759,4136],[2760,4136],[2761,4143],[2762,4097],[2763,4146],[2764,4097],[2765,4097],[2766,4097],[2767,4147],[2768,4131],[2769,4134],[2770,4134],[2771,4133],[2772,4148],[2773,4148],[2776,4149],[2777,4137],[2778,4137],[2784,4132],[2785,4154],[2786,4144],[2787,4144],[2788,4144],[2789,4144],[2790,4145],[2791,4145],[2792,4135],[2793,4097],[2794,4146],[2795,4097],[2796,4147],[2797,4131],[2798,4148],[2799,4148],[2800,4137],[2803,4149],[2804,4137],[2811,4133],[2812,4133],[2813,4133],[2815,4132],[2816,4132],[2817,4132],[2818,4132],[2819,4132],[2820,4132],[2821,4132],[2822,4154],[2823,4144],[2824,4144],[2825,4144],[2826,4144],[2827,4144],[2828,4145],[2829,4145],[2830,4145],[2831,4134],[2832,4135],[2833,4135],[2834,4135],[2835,4135],[2836,4141],[2837,4136],[2838,4136],[2839,4136],[2840,4136],[2841,4143],[2842,4097],[2843,4146],[2844,4097],[2845,4097],[2846,4097],[2847,4147],[2848,4131],[2849,4134],[2850,4134],[2851,4133],[2852,4138],[2853,4138],[2854,4138],[2855,4148],[2856,4148],[2857,4137],[2860,4149],[2861,4137],[2862,4137],[2880,4132],[2881,4132],[2882,4132],[2883,4132],[2884,4132],[2885,4132],[2886,4132],[2887,4154],[2888,4144],[2889,4144],[2890,4144],[2891,4144],[2892,4144],[2893,4145],[2894,4145],[2895,4145],[2896,4134],[2897,4135],[2898,4141],[2899,4136],[2900,4136],[2901,4136],[2902,4136],[2903,4143],[2904,4097],[2905,4146],[2906,4097],[2907,4097],[2908,4097],[2909,4147],[2910,4131],[2911,4134],[2912,4134],[2913,4133],[2914,4138],[2915,4138],[2916,4138],[2917,4148],[2918,4148],[2919,4137],[2922,4149],[2923,4137],[2924,4137],[2942,4132],[2943,4132],[2944,4132],[2945,4132],[2946,4132],[2949,4137],[2950,4132],[2951,4132],[2952,4132],[2953,4132],[2954,4132],[2955,4132],[2956,4132],[2957,4154],[2958,4144],[2959,4144],[2960,4144],[2961,4144],[2962,4144],[2963,4145],[2964,4145],[2965,4145],[2966,4134],[2967,4135],[2968,4141],[2969,4136],[2970,4136],[2971,4136],[2972,4136],[2973,4143],[2974,4097],[2975,4146],[2976,4097],[2977,4097],[2978,4097],[2979,4147],[2980,4131],[2981,4134],[2982,4134],[2983,4133],[2984,4138],[2985,4138],[2986,4138],[2987,4148],[2988,4148],[2989,4137],[2992,4149],[2993,4137],[2994,4137],[3012,4136],[3013,4136],[3014,4134],[3016,4133],[3017,4133],[3018,4132],[3019,4132],[3020,4132],[3021,4132],[3022,4132],[3023,4132],[3024,4132],[3025,4154],[3026,4144],[3027,4144],[3028,4144],[3029,4144],[3030,4144],[3031,4145],[3032,4145],[3033,4145],[3034,4134],[3035,4135],[3036,4141],[3037,4136],[3038,4136],[3039,4136],[3040,4136],[3041,4143],[3042,4097],[3043,4146],[3044,4097],[3045,4097],[3046,4097],[3047,4147],[3048,4131],[3049,4134],[3050,4134],[3051,4133],[3052,4138],[3053,4138],[3054,4138],[3055,4148],[3056,4148],[3057,4137],[3060,4149],[3061,4137],[3062,4137],[3080,4139],[3082,4133],[3083,4133],[3085,4145],[3086,4145],[3087,4145],[3088,4145],[3089,4145],[3322,4177],[3323,4176],[3324,4174],[3328,4174],[3329,4176],[3335,4177],[3337,4197],[3338,4177],[3339,4174],[3340,4176],[3346,4177],[3347,4174],[3348,4176],[3356,4174],[3357,4174],[3358,4176],[3362,4174],[3363,4176],[3367,4174],[3368,4176],[3372,4177],[3373,4174],[3374,4176],[3380,4177],[3381,4174],[3382,4176],[3388,4177],[3389,4174],[3390,4176],[3396,4177],[3397,4176],[3400,4177],[3401,4174],[3402,4176],[3408,4177],[3409,4174],[3410,4176],[3417,4177],[3418,4176],[3419,4177],[3420,4174],[3421,4176],[3427,4174],[3436,4177],[3437,4177],[3438,4177],[3439,4174],[3440,4176],[3448,4177],[3449,4174],[3450,4176],[3456,4174],[3457,4176],[3465,4176],[3466,4176],[3467,4176],[3471,4177],[3472,4174],[3473,4176],[3479,4177],[3480,4174],[3481,4176],[3487,4174],[3490,4174],[3496,4177],[3501,4176],[3506,4177],[3507,4177],[3508,4177],[3510,4177],[3511,4177],[3512,4177],[3513,4177],[3514,4177],[3515,4176],[3516,4176],[3517,4174],[3518,4176],[3524,4177],[3525,4174],[3526,4176],[3532,4177],[3533,4174],[3534,4176],[3540,4177],[3541,4174],[3542,4176],[3549,4177],[3550,4174],[3551,4176],[3564,4098],[3565,4098],[3566,4098],[3567,4098],[3568,4098],[3569,4098],[3570,4098],[3571,4098],[3572,4098],[3573,4098],[3574,4098],[3575,4098],[3576,4098],[3577,4098],[3578,4098],[3579,4098],[3580,4098],[3581,4098],[3582,4098],[3583,4098],[3584,4098],[3585,4098],[3586,4098],[3587,4098],[3588,4098],[3589,4098],[3590,4098],[3591,4098],[3592,4098],[3593,4098],[3594,4098],[3595,4098],[3596,4098],[3597,4098],[3598,4098],[3599,4098],[3600,4098],[3601,4098],[3602,4098],[3603,4098],[3604,4098],[3605,4098],[3606,4098],[3607,4098],[3608,4098],[3609,4098],[3610,4098],[3611,4098],[3612,4098],[3613,4098],[3614,4098],[3615,4098],[3616,4098],[3617,4098],[3618,4098],[3619,4098],[3620,4098],[3621,4098],[3622,4098],[3623,4098],[3624,4098],[3625,4098],[3626,4098],[3627,4098],[3628,4098],[3629,4098],[3630,4098],[3631,4098],[3632,4098],[3633,4098],[3634,4098],[3635,4098],[3636,4098],[3637,4098],[3638,4098],[3639,4098],[3640,4098],[3641,4098],[3642,4098],[3643,4098],[3644,4098],[3645,4098],[3646,4098],[3647,4098],[3648,4098],[3649,4098],[3650,4098],[3651,4098],[3652,4098],[3653,4098],[3654,4098],[3655,4098],[3656,4098],[3657,4098],[3658,4098],[3659,4098],[3660,4098],[3661,4098],[3662,4098],[3663,4098],[3664,4098],[3665,4098],[3666,4098],[3667,4098],[3668,4098],[3669,4098],[3670,4098],[3671,4098],[3672,4098],[3673,4098],[3674,4098],[3675,4098],[3676,4098],[3677,4098],[3678,4098],[3679,4098],[3680,4098],[3681,4098],[3682,4098],[3683,4098],[3684,4098],[3685,4098],[3686,4098],[3687,4098],[3688,4098],[3851,4186],[3853,4186],[3855,4186],[3857,4186],[3859,4186],[3861,4186],[3863,4186],[3865,4186],[3866,4186],[3867,4186],[3869,4186],[3871,4186],[3873,4186],[3875,4186],[3877,4186],[3878,4186],[3879,4186],[3880,4186],[3881,4186],[3882,4186],[3886,4186],[3888,4186],[3890,4186],[3892,4186],[3894,4186]],"b":[[176,"impl-Display-for-PublicKey"],[177,"impl-Debug-for-PublicKey"],[178,"impl-Debug-for-KeyParsingError"],[179,"impl-Display-for-KeyParsingError"],[180,"impl-Debug-for-SecretKey"],[181,"impl-Display-for-SecretKey"],[183,"impl-Debug-for-RelayUrl"],[184,"impl-Display-for-RelayUrl"],[185,"impl-Display-for-RelayUrlParseError"],[186,"impl-Debug-for-RelayUrlParseError"],[188,"impl-Debug-for-RelayMap"],[189,"impl-Display-for-RelayMap"],[190,"impl-Display-for-RelayNode"],[191,"impl-Debug-for-RelayNode"],[195,"impl-From%3CDecodeError%3E-for-KeyParsingError"],[196,"impl-From%3CError%3E-for-KeyParsingError"],[198,"impl-From%3C%5Bu8;+32%5D%3E-for-SecretKey"],[199,"impl-From%3CSigningKey%3E-for-SecretKey"],[202,"impl-From%3CNodeTicket%3E-for-NodeAddr"],[203,"impl-From%3C(PublicKey,+Option%3CRelayUrl%3E,+%26%5BSocketAddr%5D)%3E-for-NodeAddr"],[204,"impl-From%3CPublicKey%3E-for-NodeAddr"],[205,"impl-From%3CRemoteInfo%3E-for-NodeAddr"],[206,"impl-From%3CNodeInfo%3E-for-NodeAddr"],[211,"impl-From%3CRelayUrl%3E-for-RelayMap"],[213,"impl-From%3CRelayNode%3E-for-RelayMap"],[218,"impl-FromIterator%3CRelayUrl%3E-for-RelayMap"],[219,"impl-FromIterator%3CRelayNode%3E-for-RelayMap"],[305,"impl-TryFrom%3C%26%5Bu8%5D%3E-for-PublicKey"],[306,"impl-TryFrom%3C%26%5Bu8;+32%5D%3E-for-PublicKey"],[544,"impl-Debug-for-UserData"],[545,"impl-Display-for-UserData"],[547,"impl-Debug-for-ParseError"],[548,"impl-Display-for-ParseError"],[550,"impl-Debug-for-IntoDiscoveryError"],[551,"impl-Display-for-IntoDiscoveryError"],[552,"impl-Display-for-DiscoveryError"],[553,"impl-Debug-for-DiscoveryError"],[556,"impl-Debug-for-Lagged"],[557,"impl-Display-for-Lagged"],[561,"impl-From%3CDiscoveryItem%3E-for-NodeInfo"],[563,"impl-From%3CNodeAddr%3E-for-NodeInfo"],[564,"impl-From%3CTxtAttrs%3CIrohAttr%3E%3E-for-NodeInfo"],[565,"impl-From%3C%26TxtAttrs%3CIrohAttr%3E%3E-for-NodeInfo"],[920,"impl-Display-for-PkarrError"],[921,"impl-Debug-for-PkarrError"],[2186,"impl-Display-for-SendDatagramError"],[2187,"impl-Debug-for-SendDatagramError"],[2188,"impl-Debug-for-RetryError"],[2189,"impl-Display-for-RetryError"],[2191,"impl-Display-for-ReadToEndError"],[2192,"impl-Debug-for-ReadToEndError"],[2193,"impl-Display-for-ReadError"],[2194,"impl-Debug-for-ReadError"],[2195,"impl-Debug-for-ResetError"],[2196,"impl-Display-for-ResetError"],[2197,"impl-Display-for-ReadExactError"],[2198,"impl-Debug-for-ReadExactError"],[2200,"impl-Display-for-WriteError"],[2201,"impl-Debug-for-WriteError"],[2202,"impl-Debug-for-StoppedError"],[2203,"impl-Display-for-StoppedError"],[2205,"impl-Debug-for-VarInt"],[2206,"impl-Display-for-VarInt"],[2213,"impl-Display-for-ControlMsg"],[2214,"impl-Debug-for-ControlMsg"],[2215,"impl-Debug-for-ClosedStream"],[2216,"impl-Display-for-ClosedStream"],[2219,"impl-Display-for-ConnectionType"],[2220,"impl-Debug-for-ConnectionType"],[2221,"impl-Debug-for-Source"],[2222,"impl-Display-for-Source"],[2223,"impl-Debug-for-ConnectionError"],[2224,"impl-Display-for-ConnectionError"],[2231,"impl-Display-for-ConnectionClose"],[2232,"impl-Debug-for-ConnectionClose"],[2233,"impl-Debug-for-ApplicationClose"],[2234,"impl-Display-for-ApplicationClose"],[2235,"impl-Debug-for-AddNodeAddrError"],[2236,"impl-Display-for-AddNodeAddrError"],[2237,"impl-Display-for-TransportError"],[2238,"impl-Debug-for-TransportError"],[2239,"impl-Display-for-TransportErrorCode"],[2240,"impl-Debug-for-TransportErrorCode"],[2241,"impl-Debug-for-StreamId"],[2242,"impl-Display-for-StreamId"],[2244,"impl-Debug-for-DirectAddrType"],[2245,"impl-Display-for-DirectAddrType"],[2249,"impl-Display-for-ConnectWithOptsError"],[2250,"impl-Debug-for-ConnectWithOptsError"],[2251,"impl-Debug-for-ConnectError"],[2252,"impl-Display-for-ConnectError"],[2253,"impl-Debug-for-BindError"],[2254,"impl-Display-for-BindError"],[2255,"impl-Debug-for-GetMappingAddressError"],[2256,"impl-Display-for-GetMappingAddressError"],[2262,"impl-Display-for-AlpnError"],[2263,"impl-Debug-for-AlpnError"],[2266,"impl-Display-for-RemoteNodeIdError"],[2267,"impl-Debug-for-RemoteNodeIdError"],[2286,"impl-From%3CReadableError%3E-for-ReadError"],[2287,"impl-From%3CConnectionError%3E-for-ReadError"],[2288,"impl-From%3CResetError%3E-for-ReadError"],[2295,"impl-From%3CStoppedError%3E-for-WriteError"],[2297,"impl-From%3CClosedStream%3E-for-WriteError"],[2298,"impl-From%3CConnectionError%3E-for-WriteError"],[2302,"impl-From%3Cu8%3E-for-VarInt"],[2303,"impl-From%3Cu16%3E-for-VarInt"],[2305,"impl-From%3Cu32%3E-for-VarInt"],[2306,"impl-From%3CStreamId%3E-for-VarInt"],[2319,"impl-From%3CTransportError%3E-for-ConnectionError"],[2321,"impl-From%3CClose%3E-for-ConnectionError"],[2333,"impl-From%3CError%3E-for-TransportError"],[2335,"impl-From%3CTransportErrorCode%3E-for-TransportError"],[2336,"impl-From%3CInvalidFrame%3E-for-TransportError"],[2347,"impl-From%3CConnectionError%3E-for-ConnectError"],[2348,"impl-From%3CConnectWithOptsError%3E-for-ConnectError"],[2657,"impl-AsyncRead-for-RecvStream"],[2658,"impl-RecvStream"],[2660,"impl-SendStream"],[2661,"impl-AsyncWrite-for-SendStream"],[2832,"impl-TryFrom%3Cu64%3E-for-VarInt"],[2833,"impl-TryFrom%3Cu128%3E-for-VarInt"],[2834,"impl-TryFrom%3Cusize%3E-for-VarInt"],[3441,"impl-Display-for-Report"],[3442,"impl-Debug-for-Report"],[3446,"impl-Display-for-ReportError"],[3447,"impl-Debug-for-ReportError"],[3637,"impl-Debug-for-EncodingError"],[3638,"impl-Display-for-EncodingError"],[3639,"impl-Debug-for-DecodingError"],[3640,"impl-Display-for-DecodingError"],[3641,"impl-Display-for-MaxLengthExceededError"],[3642,"impl-Debug-for-MaxLengthExceededError"],[3643,"impl-Debug-for-LookupError"],[3644,"impl-Display-for-LookupError"],[3792,"impl-Debug-for-ProtocolError"],[3793,"impl-Display-for-ProtocolError"],[3797,"impl-From%3CError%3E-for-ProtocolError"],[3798,"impl-From%3CBox%3Cdyn+Error+%2B+Send+%2B+Sync%3E%3E-for-ProtocolError"],[3799,"impl-From%3CClosedStream%3E-for-ProtocolError"],[3800,"impl-From%3CConnectionError%3E-for-ProtocolError"],[3802,"impl-From%3CRemoteNodeIdError%3E-for-ProtocolError"],[3987,"impl-Debug-for-Disconnected"],[3988,"impl-Display-for-Disconnected"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAAAM9wADAAAADAAAABMABgAbAFEAbgAAAHAAGQCOAAgAmQAnAMIAAADEAAEAxwABAMwABADWAAEA3AAAAN4ACgDrAAwACwEDABYBBAAcAQEAIgEsAFMBCABfAQcAegEAAHwBAACFAQEAiAEAAIoBBwCTAQQAmgEgALwBKwDpARwACQIJABQCGgAwAgAAMgIAADQCAgA4AgAAOwIAAD4CAABHAgMATAIAAE4CDgBoAgAAdAIAAHgCAAB7AgAAfwIDAIUCAACIAgMAjQIEAJMCHgC1AgkAxQInAPECAwD3AgkAAgMDAAgDAQAMAwEADwMIABsDAwAgAw0AMAMBADQDAQA3AwoARAMDAEoDAABQAxIAZwMoAJMDDACmAwkAtgMDAL0DAADAAwAAwgMQANQDBQDbAwUA4gMFAOoDBADyAw4AAgQDAAgEAAAKBAEADwQBABQEAAAWBAAAGAQEAB4EAwAkBAAAJgQMADUEAAA3BAAAOQQAADsEAAA9BAAAPwQEAEcEAgBLBAsAWAQBAGcEAABpBAQAdQQBAHkEAAB9BAAAiAQBAIsEAACOBAAAkgQAAKcEAACpBAEArAQBALUEAADBBAAAxwQBAM0EAADUBAAA4QQAAOkEAAD+BAAAAAUAAA0FIgA2BQAAOAUAAEQFGABiBXsA5AUGAO0FIgARBkUAWwYDAGAGvQAlBwAAJwcAACwHAQAyBxAARAeHANYHPwAXCG4AighTAOkIAADuCAMA8wgAAPUIAAD4CAAA+ggCAP8IAQACCQEAEAkAABIJAAAYCQAAGgkAAB4JAAAgCQEAJAkAACsJAgAwCQAAOAkAAD0JIgBlCQAAZwkEAHAJEgCGCT0ACwoJACwKAAAwCgIAPQoBAEIKAABNCgMAUgoBAFcKCwBkCgAAZgoAAIQKAQCVCgQAoAoOALUKAAC3CgEAugoBAL4KPQAACxAAFAtxAIcLPQDLCz0AEwwsAEQMAABHDAAASQwSAF4MDgBwDA4AgwwDAIgMCQCXDAAAmQwFAKcMAwC5DAMAvgwHAMgMBgDSDAYA2gwPAOwMAADxDAMA9gwBAPkMAAAADQUABw0CAAsNDwAcDQAAHg08AFwNBwBlDRMAgQ0EAI8NCACpDQAAtQ0BAL4NHgDeDRMA8w0GAP4NBAAEDiAAJg4XAD8OAABEDgcAUQ4HAFoOOQCVDgIAmQ4AAJwOAgChDgoArQ4fAM8OBADWDgMA2w4AAN4OBgDtDgAA8A4BAPMOFwANDw0AHQ8DACMPAQAwDwcAQQ9UAJ0PAwCjDwkAtQ8BALoPAgC+DwMAww8AAMYPHADkDwYA","P":[[31,"T"],[32,""],[33,"T"],[50,""],[59,"T"],[66,""],[77,"K"],[81,"T"],[108,""],[111,"T"],[115,""],[116,"T"],[130,""],[132,"D"],[134,"__D"],[137,""],[158,"K"],[176,""],[194,"T"],[195,""],[197,"T"],[198,""],[200,"T"],[202,""],[208,"T"],[211,""],[212,"T"],[213,""],[215,"T"],[216,""],[218,"T"],[220,""],[221,"T"],[228,""],[232,"R"],[233,""],[234,"H"],[235,"__H"],[236,""],[247,"U"],[256,""],[277,"S"],[279,"__S"],[282,""],[289,"T"],[296,""],[304,"U,T"],[305,""],[307,"U,T"],[309,""],[310,"U,T"],[316,"U"],[325,""],[338,"V"],[348,""],[349,""],[407,""],[409,""],[418,"T"],[438,""],[447,"T"],[451,""],[456,"K"],[457,"T"],[487,""],[490,"T"],[493,""],[494,"T"],[499,"Deref::Target"],[500,"T"],[504,""],[505,"T"],[513,""],[534,"K"],[543,""],[558,"T"],[559,""],[560,"T"],[561,""],[562,"T"],[563,""],[566,"T"],[567,""],[568,"T"],[570,""],[571,"T"],[578,""],[582,"T"],[586,""],[589,"__H"],[590,""],[604,"U"],[614,""],[647,"T"],[651,""],[658,"U,T"],[659,""],[660,"U,T"],[669,"U"],[679,""],[692,"V"],[702,""],[752,"T"],[756,""],[758,"T"],[768,""],[773,"T"],[775,""],[777,"U"],[779,""],[783,"U,T"],[785,"U"],[787,""],[789,"V"],[793,""],[794,"T"],[798,""],[799,"T"],[809,""],[813,"T"],[815,""],[817,"U"],[819,""],[825,"U,T"],[827,"U"],[829,""],[831,"V"],[833,""],[854,"T"],[866,""],[874,"T"],[877,""],[880,"T"],[910,""],[927,"T"],[936,""],[943,"U"],[949,""],[962,"T"],[965,""],[966,"U,T"],[972,"U"],[978,""],[986,"V"],[992,""],[1002,"T"],[1006,""],[1010,"T"],[1011,""],[1012,"T"],[1018,""],[1020,"T"],[1024,""],[1029,"T"],[1032,""],[1036,"U"],[1038,""],[1047,"T"],[1048,"U,T"],[1050,"U"],[1052,""],[1055,"V"],[1059,""],[1060,""],[1061,"T"],[1063,""],[1064,"T"],[1065,""],[1066,"T"],[1069,""],[1070,"T"],[1072,""],[1074,"T"],[1075,","],[1076,"T"],[1077,""],[1079,"U"],[1080,""],[1085,""],[1086,"T"],[1087,"U,T"],[1088,"U"],[1089,""],[1090,"V"],[1092,""],[1095,"T"],[1097,""],[1099,"T"],[1100,""],[1101,"T"],[1104,""],[1105,"T"],[1107,""],[1110,"T"],[1112,""],[1113,"U"],[1114,""],[1120,""],[1124,""],[1125,""],[1128,"T"],[1129,"U,T"],[1130,"U"],[1131,""],[1132,"V"],[1133,""],[1336,""],[1337,""],[1377,"T"],[1501,""],[1552,"T"],[1587,""],[1631,"K"],[1635,"T"],[1821,""],[1826,""],[1828,""],[1841,"B"],[1844,""],[1859,"T"],[1983,""],[1990,"__D"],[1995,""],[1997,""],[1998,""],[2070,"B"],[2073,""],[2100,"K"],[2181,""],[2274,"T"],[2280,""],[2281,"T"],[2285,""],[2289,"T"],[2290,""],[2291,"T"],[2292,""],[2293,"T"],[2295,""],[2296,"T"],[2297,""],[2300,"T"],[2302,""],[2304,"T"],[2305,""],[2307,"T"],[2319,""],[2320,"T"],[2321,""],[2322,"T"],[2327,""],[2328,"T"],[2329,""],[2330,"T"],[2333,""],[2334,"T"],[2335,""],[2337,"T"],[2339,""],[2340,"T"],[2346,""],[2349,"T"],[2351,""],[2352,"T"],[2359,""],[2360,"T"],[2399,""],[2406,"__H"],[2411,""],[2506,"U"],[2568,""],[2576,"IntoFuture::IntoFuture"],[2577,""],[2652,"Future::Output"],[2656,""],[2698,""],[2699,""],[2708,"__S"],[2713,""],[2749,"T"],[2784,""],[2815,"U,T"],[2832,""],[2835,"U,T"],[2880,"U"],[2942,"F"],[2949,""],[3018,"V"],[3080,""],[3155,"T"],[3163,""],[3166,"T"],[3167,""],[3168,"T"],[3180,""],[3187,"T"],[3195,"__D"],[3198,""],[3218,"T"],[3223,""],[3230,"U"],[3234,""],[3289,"__S"],[3292,"T"],[3293,"U,T"],[3297,"U"],[3301,""],[3312,"V"],[3316,""],[3338,"T"],[3354,""],[3362,"T"],[3367,""],[3372,"T"],[3396,""],[3400,"T"],[3416,""],[3417,"__D"],[3418,""],[3430,"K"],[3436,""],[3448,"T"],[3461,""],[3479,"U"],[3487,""],[3508,"__S"],[3509,""],[3517,"T"],[3522,""],[3524,"U,T"],[3532,"U"],[3540,""],[3549,"V"],[3557,""],[3596,"T"],[3604,""],[3608,"T"],[3620,""],[3621,"T"],[3629,""],[3645,"T"],[3646,""],[3647,"T"],[3650,""],[3659,"U"],[3663,""],[3673,"U,T"],[3677,"U"],[3681,""],[3685,"V"],[3689,""],[3743,","],[3744,"P"],[3745,""],[3747,"T"],[3755,""],[3758,"P"],[3759,"T"],[3761,""],[3763,"T"],[3783,""],[3794,"P"],[3795,"T"],[3797,""],[3801,"T"],[3802,""],[3803,"T"],[3807,""],[3812,"U"],[3816,""],[3818,"P,F"],[3819,""],[3820,"P"],[3821,""],[3823,"P"],[3824,""],[3826,"T"],[3828,""],[3829,"U,T"],[3833,"U"],[3837,""],[3841,"V"],[3845,""],[3852,"T"],[3866,""],[3872,"T"],[3874,""],[3876,"U"],[3878,""],[3887,"U,T"],[3889,"U"],[3891,""],[3893,"V"],[3904,""],[3910,"T"],[3924,""],[3925,"T"],[3927,"W,T"],[3928,"W"],[3929,"T"],[3933,""],[3937,"T"],[3973,""],[3981,"T"],[3983,"W,T"],[3984,"W"],[3985,"T,W"],[3986,"W"],[3987,""],[3989,"T"],[4000,"Watcher::Value"],[4001,"T"],[4002,"T,Watcher::Value"],[4003,"W,T,Watcher::Value"],[4004,""],[4012,"Watcher::Value,T"],[4013,"U"],[4020,""],[4022,"Watcher::Value,T,"],[4023,"T"],[4024,"Watcher::Value,W"],[4025,"W,Future::Output"],[4026,"T,W,Future::Output"],[4027,"W,Stream::Item"],[4028,"Watcher::Value"],[4029,"T,Watcher::Value"],[4030,"W,T,Watcher::Value"],[4031,"D,C,MW,S"],[4033,"T"],[4034,""],[4035,"Watcher::Value"],[4037,"T"],[4041,""],[4042,"U,T"],[4049,"U"],[4056,"F"],[4058,"S"],[4059,""],[4066,"Watcher::Value"],[4067,"V"],[4074,"T"]]}],["iroh_base",{"t":"TPPPGTFIFFFFFINNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNONNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOPTPFGPKPNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNMNNNNNNNNNNOOOOOOOOOOOO","n":["BYTE_SIZE","Decode","DecodeInvalidLength","Key","KeyParsingError","LENGTH","NodeAddr","NodeId","PublicKey","RelayUrl","RelayUrlParseError","SecretKey","Signature","SignatureError","as_bytes","as_error_source","","as_ref","backtrace","","borrow","","","","","","","","borrow_mut","","","","","","","cause","","clone","","","","","clone_into","","","","","clone_to_uninit","","","","","cmp","","","deref","description","","deserialize","","","","","direct_addresses","","eq","","","","fmt","","","","","","","","","","","","","","","fmt_short","from","","","","","","","","","","","","","","","","","","","from_bytes","","","from_components","from_parts","from_slice","from_str","","","","generate","hash","","in_current_span","","into","","","","","","","is_empty","new","node_id","partial_cmp","","","public","","r_bytes","relay_url","","s_bytes","secret","serialize","","","","","sign","source","","ticket","to_bytes","","","to_owned","","","","","to_string","","","","","","to_vec","try_from","","","","","","","","","","","try_into","","","","","","","type_id","","","","","","","verify","with_direct_addresses","with_relay_url","backtrace","","","source","","span_trace","","","Encoding","KIND","Kind","NodeTicket","ParseError","Postcard","Ticket","Verify","as_error_source","backtrace","borrow","","borrow_mut","","cause","clone","clone_into","clone_to_uninit","description","deserialize","","eq","fmt","","","","from","","","","from_bytes","","from_str","in_current_span","into","","new","node_addr","serialize","","source","to_bytes","","to_owned","to_string","","try_from","","try_into","","type_id","","backtrace","","","","expected","message","source","","span_trace","","",""],"q":[[0,"iroh_base"],[191,"iroh_base::KeyParsingError"],[199,"iroh_base::ticket"],[251,"iroh_base::ticket::ParseError"],[263,"iroh_base::key"],[264,"core::error"],[265,"backtrace::capture"],[266,"core::option"],[267,"iroh_base::relay_url"],[268,"ed25519"],[269,"iroh_base::node_addr"],[270,"core::cmp"],[271,"core::result"],[272,"serde::de"],[273,"core::net::socket_addr"],[274,"core::iter::traits::iterator"],[275,"alloc::collections::btree::set"],[276,"core::fmt"],[277,"alloc::string"],[278,"ed25519_dalek::signature"],[279,"ed25519_dalek::verifying"],[280,"data_encoding"],[281,"ed25519_dalek::errors"],[282,"ed25519_dalek::signing"],[283,"iroh_base::ticket::node"],[284,"url"],[285,"core::iter::traits::collect"],[286,"signature::error"],[287,"rand_core"],[288,"core::hash"],[289,"serde::ser"],[290,"alloc::vec"],[291,"core::any"],[292,"n0_snafu::spantrace"],[293,"postcard::error"]],"i":"Ahn00`b````````01Ad1203112AjAlAn364521035364210642106421041005364210116410666644552210033466664455522211110036426166420240536452103111410426116264210253`6626421064520366644452210364521036452103411ElEnF`21210FdFf1``1`111Dj20220002100002200221002020010210002020202FhFjFlFn30213210","f":"``````````````{{{d{b}}}{{d{{h{f}}}}}}{d{{d{j}}}}0{{{d{b}}}{{d{{l{f}}}}}}{{{d{n}}}{{Ab{{d{A`}}}}}}{{{d{Ad}}}{{Ab{{d{A`}}}}}}{d{{d{c}}}{}}0500000{{{d{Af}}}{{d{Afc}}}{}}000000{{{d{n}}}{{Ab{{d{j}}}}}}{{{d{Ad}}}{{Ab{{d{j}}}}}}{{{d{Ah}}}Ah}{{{d{b}}}b}{{{d{Aj}}}Aj}{{{d{Al}}}Al}{{{d{An}}}An}{{d{d{Afc}}}B`{}}0000{{df}B`}0000{{{d{b}}{d{b}}}Bb}{{{d{Al}}{d{Al}}}Bb}{{{d{An}}{d{An}}}Bb}{{{d{An}}}{{d{c}}}{}}{{{d{n}}}{{d{Bd}}}}{{{d{Ad}}}{{d{Bd}}}}{c{{Bf{Ah}}}Bh}{c{{Bf{b}}}Bh}{c{{Bf{Aj}}}Bh}{c{{Bf{Al}}}Bh}{c{{Bf{An}}}Bh}{{{d{Al}}}{{`{{Bn{}{{Bj{{d{Bl}}}}}}}}}}{AlC`}{{{d{Ah}}{d{Ah}}}Cb}{{{d{b}}{d{b}}}Cb}{{{d{Al}}{d{Al}}}Cb}{{{d{An}}{d{An}}}Cb}{{{d{Ah}}{d{AfCd}}}{{Bf{B`Cf}}}}000{{{d{b}}{d{AfCd}}}Ch}0{{{d{n}}{d{AfCd}}}Ch}0{{{d{Aj}}{d{AfCd}}}Ch}0{{{d{Al}}{d{AfCd}}}Ch}{{{d{An}}{d{AfCd}}}Ch}0{{{d{Ad}}{d{AfCd}}}Ch}0{{{d{b}}}Cj}{cc{}}{{{d{{h{f}}}}}Ah}{{{h{f}}}Ah}{ClAh}{Cnb}4{D`n}5{Dbn}{DdAj}7{{{h{f}}}Aj}{DfAl}{{{Dh{b{Ab{An}}{d{{l{Bl}}}}}}}Al}:{DjAl};{DlAn}<;{{{d{{h{f}}}}}{{Bf{bDb}}}}{{{d{{h{f}}}}}Aj}{{{h{f}}{h{f}}}Ah}{{b{Ab{An}}c}Al{{Dn{}{{Bj{Bl}}}}}}{{{d{{l{f}}}}}{{Bf{AhE`}}}}{{{d{Bd}}}{{Bf{AhE`}}}}{{{d{Bd}}}{{Bf{bc}}}{}}{{{d{Bd}}}{{Bf{Ajc}}}{}}{{{d{Bd}}}{{Bf{Anc}}}{}}{cAjEb}{{{d{b}}{d{Afc}}}B`Ed}{{{d{An}}{d{Afc}}}B`Ed}{{}}0{{}c{}}000000{{{d{Al}}}Cb}{bAl}{AlDf}{{{d{b}}{d{b}}}{{Ab{Bb}}}}{{{d{Al}}{d{Al}}}{{Ab{Bb}}}}{{{d{An}}{d{An}}}{{Ab{Bb}}}}{{{d{b}}}Cn}{{{d{Aj}}}b}{{{d{Ah}}}{{d{{h{f}}}}}}{{{d{Al}}}{{Ab{{d{An}}}}}}{AlAb}2{{{d{Aj}}}{{d{Dd}}}}{{{d{Ah}}c}BfEf}{{{d{b}}c}BfEf}{{{d{Aj}}c}BfEf}{{{d{Al}}c}BfEf}{{{d{An}}c}BfEf}{{{d{Aj}}{d{{l{f}}}}}Ah}{{{d{n}}}{{Ab{{d{j}}}}}}{{{d{Ad}}}{{Ab{{d{j}}}}}}`{{{d{Ah}}}{{h{f}}}}0{{{d{Aj}}}{{h{f}}}}{dc{}}0000{dCj}00000{{{d{Ah}}}{{Eh{f}}}}{c{{Bf{e}}}{}{}}{{{d{{l{f}}}}}{{Bf{AhE`}}}}1{{{d{{l{f}}}}}{{Bf{bc}}}{}}{{{d{{h{f}}}}}{{Bf{bc}}}{}}3{{{d{{l{f}}}}}{{Bf{Ajc}}}{}}4444{{}{{Bf{c}}}{}}000000{dEj}000000{{{d{b}}{d{{l{f}}}}{d{Ah}}}{{Bf{B`Db}}}}{{Alc}Al{{Dn{}{{Bj{Bl}}}}}}{{AlAn}Al}{ElAb}{EnAb}{F`Ab}{ElD`}{EnDb}{ElFb}{EnFb}{F`Fb}````````{d{{d{j}}}}{{{d{Fd}}}{{Ab{{d{A`}}}}}}{d{{d{c}}}{}}0{{{d{Af}}}{{d{Afc}}}{}}0{{{d{Fd}}}{{Ab{{d{j}}}}}}{{{d{Dj}}}Dj}{{d{d{Afc}}}B`{}}{{df}B`}{{{d{Fd}}}{{d{Bd}}}}{{{d{Bd}}}{{Bf{FfFd}}}}{c{{Bf{Dj}}}Bh}{{{d{Dj}}{d{Dj}}}Cb}{{{d{Dj}}{d{AfCd}}}Ch}0{{{d{Fd}}{d{AfCd}}}Ch}0{cc{}}{AlDj}1{D`Fd}{{{d{{l{f}}}}}{{Bf{FfFd}}}}{{{d{{l{f}}}}}{{Bf{DjFd}}}}{{{d{Bd}}}{{Bf{Djc}}}{}}{{}}{{}c{}}06{{{d{Dj}}}{{d{Al}}}}{{{d{Ff}}}Cj}{{{d{Dj}}c}BfEf}{{{d{Fd}}}{{Ab{{d{j}}}}}}{{{d{Ff}}}{{Eh{f}}}}{{{d{Dj}}}{{Eh{f}}}}{dc{}}{dCj}0{c{{Bf{e}}}{}{}}0{{}{{Bf{c}}}{}}0{dEj}0{FhAb}{FjAb}{FlAb}{FnAb}{Fhd}{Fnd}{FjG`}{FlD`}{FhFb}{FjFb}{FlFb}{FnFb}","D":"In","p":[[5,"PublicKey",0,263],[1,"reference",null,null,1],[1,"u8"],[1,"array"],[10,"Error",264],[1,"slice"],[6,"KeyParsingError",0,263],[5,"Backtrace",265],[6,"Option",266,null,1],[5,"RelayUrlParseError",0,267],[0,"mut"],[5,"Signature",0,268],[5,"SecretKey",0,263],[5,"NodeAddr",0,269],[5,"RelayUrl",0,267],[1,"unit"],[6,"Ordering",270],[1,"str"],[6,"Result",271,null,1],[10,"Deserializer",272],[17,"Item"],[6,"SocketAddr",273],[10,"Iterator",274],[5,"BTreeSet",275],[1,"bool"],[5,"Formatter",276],[5,"Error",276],[8,"Result",276],[5,"String",277],[5,"InternalSignature",278],[5,"VerifyingKey",279],[5,"DecodeError",280],[8,"SignatureError",0,281],[5,"SigningKey",282],[8,"NodeId",0,263],[1,"tuple",null,null,1],[5,"NodeTicket",199,283],[5,"Url",284],[10,"IntoIterator",285],[5,"Error",286],[10,"CryptoRngCore",287],[10,"Hasher",288],[10,"Serializer",289],[5,"Vec",290],[5,"TypeId",291],[15,"Decode",191],[15,"Key",191],[15,"DecodeInvalidLength",191],[5,"SpanTrace",292],[6,"ParseError",199],[10,"Ticket",199],[15,"Kind",251],[15,"Postcard",251],[15,"Encoding",251],[15,"Verify",251],[6,"Error",293]],"r":[[0,268],[1,263],[2,263],[3,263],[4,263],[5,263],[6,269],[7,263],[8,263],[9,267],[10,267],[11,263],[12,268],[13,281],[14,263],[15,263],[16,267],[17,263],[18,263],[19,267],[20,268],[21,263],[22,263],[23,263],[24,263],[25,269],[26,267],[27,267],[28,268],[29,263],[30,263],[31,263],[32,269],[33,267],[34,267],[35,263],[36,267],[37,268],[38,263],[39,263],[40,269],[41,267],[42,268],[43,263],[44,263],[45,269],[46,267],[47,268],[48,263],[49,263],[50,269],[51,267],[52,263],[53,269],[54,267],[55,267],[56,263],[57,267],[58,268],[59,263],[60,263],[61,269],[62,267],[63,269],[64,269],[65,268],[66,263],[67,269],[68,267],[69,268],[70,268],[71,268],[72,268],[73,263],[74,263],[75,263],[76,263],[77,263],[78,263],[79,269],[80,267],[81,267],[82,267],[83,267],[84,263],[85,268],[86,268],[87,268],[88,268],[89,263],[90,263],[91,263],[92,263],[93,263],[94,263],[95,263],[96,263],[97,269],[98,269],[99,269],[100,269],[101,267],[102,267],[103,267],[104,268],[105,263],[106,263],[107,268],[108,269],[109,268],[110,268],[111,263],[112,263],[113,267],[114,263],[115,263],[116,267],[117,263],[118,267],[119,268],[120,263],[121,263],[122,263],[123,269],[124,267],[125,267],[126,269],[127,269],[128,269],[129,263],[130,269],[131,267],[132,263],[133,263],[134,268],[135,269],[136,269],[137,268],[138,263],[139,268],[140,263],[141,263],[142,269],[143,267],[144,263],[145,263],[146,267],[148,268],[149,268],[150,263],[151,268],[152,263],[153,263],[154,269],[155,267],[156,268],[157,263],[158,263],[159,263],[160,267],[161,267],[162,268],[163,268],[164,268],[165,263],[166,263],[167,263],[168,263],[169,263],[170,263],[171,269],[172,267],[173,267],[174,268],[175,263],[176,263],[177,263],[178,269],[179,267],[180,267],[181,268],[182,263],[183,263],[184,263],[185,269],[186,267],[187,267],[188,263],[189,269],[190,269],[202,283],[209,283],[211,283],[214,283],[215,283],[216,283],[219,283],[220,283],[221,283],[222,283],[225,283],[226,283],[230,283],[231,283],[233,283],[235,283],[236,283],[238,283],[241,283],[242,283],[243,283],[245,283],[247,283],[249,283]],"b":[[69,"impl-LowerHex-for-Signature"],[70,"impl-Display-for-Signature"],[71,"impl-Debug-for-Signature"],[72,"impl-UpperHex-for-Signature"],[73,"impl-Display-for-PublicKey"],[74,"impl-Debug-for-PublicKey"],[75,"impl-Display-for-KeyParsingError"],[76,"impl-Debug-for-KeyParsingError"],[77,"impl-Debug-for-SecretKey"],[78,"impl-Display-for-SecretKey"],[80,"impl-Debug-for-RelayUrl"],[81,"impl-Display-for-RelayUrl"],[82,"impl-Display-for-RelayUrlParseError"],[83,"impl-Debug-for-RelayUrlParseError"],[86,"impl-From%3C%26%5Bu8;+ed25519::::SignatureBytes::%7Bconstant%230%7D%5D%3E-for-Signature"],[87,"impl-From%3C%5Bu8;+ed25519::::SignatureBytes::%7Bconstant%230%7D%5D%3E-for-Signature"],[88,"impl-From%3CInternalSignature%3E-for-Signature"],[91,"impl-From%3CDecodeError%3E-for-KeyParsingError"],[93,"impl-From%3CError%3E-for-KeyParsingError"],[94,"impl-From%3CSigningKey%3E-for-SecretKey"],[96,"impl-From%3C%5Bu8;+32%5D%3E-for-SecretKey"],[97,"impl-From%3CPublicKey%3E-for-NodeAddr"],[98,"impl-From%3C(PublicKey,+Option%3CRelayUrl%3E,+%26%5BSocketAddr%5D)%3E-for-NodeAddr"],[100,"impl-From%3CNodeTicket%3E-for-NodeAddr"],[148,"impl-Signature"],[149,"impl-SignatureEncoding-for-Signature"],[166,"impl-TryFrom%3C%26%5Bu8%5D%3E-for-PublicKey"],[167,"impl-TryFrom%3C%26%5Bu8;+32%5D%3E-for-PublicKey"],[221,"impl-Debug-for-NodeTicket"],[222,"impl-Display-for-NodeTicket"],[223,"impl-Display-for-ParseError"],[224,"impl-Debug-for-ParseError"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAALgAFwAQAC8AQgASAFcAAwBcAAAAXgABAGEAAgBnAAAAbwADAHQAAwCCAAIAjAAEAJIAAQCWAAAAmAAKAKQAGADAAAcA0AAKANwABQDlAAAA5wACAO8AAQDyAA0AAQEGAA==","P":[[20,"T"],[22,""],[23,"T"],[35,""],[42,"T"],[47,""],[55,"Deref::Target"],[56,""],[58,"D"],[61,"__D"],[63,""],[85,"T"],[86,""],[90,"T"],[91,""],[92,"T"],[93,""],[95,"T"],[96,""],[99,"T"],[100,""],[101,"T"],[102,""],[103,"T"],[104,""],[108,""],[109,""],[111,"FromStr::Err"],[114,"R"],[115,"H"],[116,"__H"],[117,""],[119,"U"],[126,""],[139,"S"],[142,"__S"],[144,""],[151,"T"],[156,""],[163,"U,T"],[164,""],[165,"U,T"],[166,"TryFrom::Error"],[168,"U,T"],[169,"TryFrom::Error"],[170,"U,T"],[174,"U"],[181,""],[189,""],[190,""],[209,"T"],[213,""],[215,"T"],[216,""],[219,"D"],[220,""],[225,"T"],[226,""],[227,"T"],[228,""],[231,"FromStr::Err"],[232,""],[233,"U"],[235,""],[238,"S"],[239,""],[242,"T"],[243,""],[245,"U,T"],[247,"U"],[249,""]]}],["iroh_bench",{"t":"FGGGPPPFPPPPNNNNNNNNNNNNNNNNHONNNNNNNNNNNNNNNNNNNNNNNNNNNHNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNONNNNNCOOONCOHCCNOONNNNNNNNNNNNNNNNNNNNNONNNNNSHHHHHHSHHHHHHFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFFFONNNNNNOOOONNNNNNNNNNNNNNNNNNNNOONNNNNNNNNNNNNNONOOOHOOONNNNNNOONNNNNN","n":["ClientStats","Commands","ConnectionSelector","EndpointSelector","Iroh","","","Opt","Quinn","","","S2n","__clone_box","","augment_args","augment_args_for_update","augment_subcommands","augment_subcommands_for_update","borrow","","","","","borrow_mut","","","","","client_handler","clients","clone","","clone_into","","clone_to_uninit","","close","","command","","command_for_update","","compat","","","","","compat_mut","","","","","compat_ref","","","","","configure_tracing_subscriber","default","deref","","","","","deref_mut","","","","","download_size","drop","","","","","fmt","","from","","","","","from_arg_matches","","from_arg_matches_mut","","from_ref","","group_id","has_subcommand","init","","","","","initial_mtu","into","","","","","iroh","max_streams","metrics","only_relay","print","quinn","read_unordered","rt","s2n","stats","","","streams","to_owned","","try_from","","","","","try_into","","","","","type_id","","","","","update_from_arg_matches","","update_from_arg_matches_mut","","upload_size","vzip","","","","","ALPN","client","connect_client","handle_client_stream","server","server_endpoint","transport_config","ALPN","client","connect_client","handle_client_stream","server","server_endpoint","transport_config","Opt","__clone_box","augment_args","augment_args_for_update","borrow","borrow_mut","clone","clone_into","clone_to_uninit","command","command_for_update","compat","compat_mut","compat_ref","deref","deref_mut","drop","fmt","from","from_arg_matches","from_arg_matches_mut","from_ref","group_id","init","into","to_owned","try_from","try_into","type_id","update_from_arg_matches","update_from_arg_matches_mut","vzip","Stats","StreamStats","TransferResult","avg_chunk_size","borrow","","","borrow_mut","","","chunk_size","chunk_time","chunks","","compat","","","compat_mut","","","compat_ref","","","default","","deref","","","deref_mut","","","drop","","","duration","duration_hist","fmt","","","from","","","init","","","into","","","new","print","size","stream_finished","stream_stats","streams","throughput","throughput_bps","throughput_hist","total_duration","total_size","try_from","","","try_into","","","ttfb","ttfb_hist","type_id","","","vzip","",""],"q":[[0,"iroh_bench"],[141,"iroh_bench::iroh"],[148,"iroh_bench::quinn"],[155,"iroh_bench::s2n"],[187,"iroh_bench::stats"],[260,"dyn_clone::sealed"],[261,"clap_builder::builder::command"],[262,"n0_snafu::error"],[263,"async_compat"],[264,"core::fmt"],[265,"clap_builder::parser::matches::arg_matches"],[266,"clap_builder"],[267,"core::result"],[268,"clap_builder::util::id"],[269,"core::option"],[270,"tokio::runtime::runtime"],[271,"core::any"],[272,"iroh_base::node_addr"],[273,"iroh_base::relay_url"],[274,"iroh::endpoint"],[275,"iroh_quinn_proto::config::transport"],[276,"core::net::socket_addr"],[277,"rustls_pki_types"],[278,"iroh_quinn::endpoint"],[279,"iroh_quinn::connection"],[280,"hdrhistogram"],[281,"core::time"]],"i":"````lnAh`21000A`00113210Ab43210`1212121432121432104321043210`0432104321014321021432102121211243210143210`1110`1```311214321043210432102121143210```````````````Ed000000000000000000000000000000```DfEjEf2102000210210210210102102102201021021021022121112`01110210220102102","f":"````````````{{bd}f}0{hh}000{b{{b{c}}}{}}0000{{{b{j}}}{{b{jc}}}{}}0000{{lnA`}{{Ad{Ab}}}}{A`Af}{{{b{Ah}}}Ah}{{{b{A`}}}A`}{{b{b{jc}}}f{}}0{{bAj}f}0{lf}{{{b{n}}Al{b{{An{Aj}}}}}f}{{}h}000{{}{{B`{c}}}{}}0000{{{b{j}}}{{B`{{b{jc}}}}}{}}0000{b{{B`{{b{c}}}}}{}}0000{{}f}{{}Ab}{Af{{b{c}}}{}}0000{Af{{b{jc}}}{}}0000{A`Bb}{Aff}0000{{{b{Ah}}{b{jBd}}}Bf}{{{b{A`}}{b{jBd}}}Bf}{cc{}}0000{{{b{Bh}}}{{Bl{AhBj}}}}{{{b{Bh}}}{{Bl{A`Bj}}}}{{{b{jBh}}}{{Bl{AhBj}}}}{{{b{jBh}}}{{Bl{A`Bj}}}}{{{b{c}}}c{}}0{{}{{C`{Bn}}}}{{{b{Cb}}}Cd}{{}Af}0000{A`Cf}{{}c{}}0000`{A`Af}{A`Cd}0{{{b{Ab}}Af}f}`1{{}Ch}``{{{b{n}}}f}34{bc{}}0{c{{Bl{e}}}{}{}}0000{{}{{Bl{c}}}{}}0000{bCj}0000{{{b{jAh}}{b{Bh}}}{{Bl{fBj}}}}{{{b{jA`}}{b{Bh}}}{{Bl{fBj}}}}{{{b{jAh}}{b{jBh}}}{{Bl{fBj}}}}{{{b{jA`}}{b{jBh}}}{{Bl{fBj}}}}{A`Bb}{{}c{}}0000{{}b}{{Cl{C`{Cn}}A`}{{Ad{Ab}}}}{{Cl{C`{Cn}}A`}{{Ad{{Dd{D`Db}}}}}}{{{b{Db}}BbCd}{{Ad{{Dd{DfDf}}}}}}{{D`A`}{{Ad{f}}}}{{{b{Ch}}{b{{C`{Cn}}}}{b{A`}}}{{Dd{ClD`}}}}{{AfCf}Dh}6{{DjDlA`}{{Ad{Ab}}}}{{DjDlA`}{{Ad{{Dd{DnE`}}}}}}{{{b{E`}}BbCd}{{Ad{{Dd{DfDf}}}}}}{{DnA`}{{Ad{f}}}}{{{b{Ch}}DlEb{b{A`}}}{{Dd{DjDn}}}}5`{{bd}f}{hh}0{b{{b{c}}}{}}{{{b{j}}}{{b{jc}}}{}}{{{b{Ed}}}Ed}{{b{b{jc}}}f{}}{{bAj}f}{{}h}0{{}{{B`{c}}}{}}{{{b{j}}}{{B`{{b{jc}}}}}{}}{b{{B`{{b{c}}}}}{}}{Af{{b{c}}}{}}{Af{{b{jc}}}{}}{Aff}{{{b{Ed}}{b{jBd}}}Bf}{cc{}}{{{b{Bh}}}{{Bl{EdBj}}}}{{{b{jBh}}}{{Bl{EdBj}}}}{{{b{c}}}c{}}{{}{{C`{Bn}}}}{{}Af}{{}c{}}{bc{}}{c{{Bl{e}}}{}{}}{{}{{Bl{c}}}{}}{bCj}{{{b{jEd}}{b{Bh}}}{{Bl{fBj}}}}{{{b{jEd}}{b{jBh}}}{{Bl{fBj}}}}{{}c{}}```{DfBb}{b{{b{c}}}{}}00{{{b{j}}}{{b{jc}}}{}}00{EfEh}0{EfBb}4{{}{{B`{c}}}{}}00{{{b{j}}}{{B`{{b{jc}}}}}{}}00{b{{B`{{b{c}}}}}{}}00{{}Ej}{{}Ef}{Af{{b{c}}}{}}00{Af{{b{jc}}}{}}00{Aff}00{DfEl}:{{{b{Ej}}{b{jBd}}}Bf}{{{b{Ef}}{b{jBd}}}Bf}{{{b{Df}}{b{jBd}}}Bf}{cc{}}00{{}Af}00{{}c{}}00{{ElBbElBb}Df}{{{b{Ej}}{b{Cb}}}f}{DfBb}{{{b{jEj}}Df}f}{EjEf}{EjAf}{DfEn}{{ElBb}En}{EfEh}{EjEl}{EjBb}{c{{Bl{e}}}{}{}}00{{}{{Bl{c}}}{}}00{DfEl}5{bCj}00{{}c{}}00","D":"Dj","p":[[1,"reference",null,null,1],[5,"Private",260],[1,"unit"],[5,"Command",261],[0,"mut"],[6,"EndpointSelector",0],[6,"ConnectionSelector",0],[5,"Opt",0],[5,"ClientStats",0],[8,"Result",262],[1,"usize"],[6,"Commands",0],[1,"u8"],[1,"u32"],[1,"slice"],[5,"Compat",263],[1,"u64"],[5,"Formatter",264],[8,"Result",264],[5,"ArgMatches",265],[8,"Error",266],[6,"Result",267,null,1],[5,"Id",268],[6,"Option",269,null,1],[1,"str"],[1,"bool"],[1,"u16"],[5,"Runtime",270],[5,"TypeId",271],[5,"NodeAddr",272],[5,"RelayUrl",273],[5,"Endpoint",274],[5,"Connection",274],[1,"tuple",null,null,1],[5,"TransferResult",187],[5,"TransportConfig",275],[6,"SocketAddr",276],[5,"CertificateDer",277],[5,"Endpoint",278],[5,"Connection",279],[6,"PrivateKeyDer",277],[5,"Opt",155],[5,"StreamStats",187],[5,"Histogram",280],[5,"Stats",187],[5,"Duration",281],[1,"f64"]],"r":[],"b":[],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAN8AEQAAABwAHwAmAEcABgBTAAwAZgAAAGoAAQBtAAMAcwAUAIkABQCRAAAAlAABAJgAAACbABIArwAEALUALQDmAAIA7AAYAA==","P":[[18,"T"],[28,""],[32,"T"],[34,""],[42,"T"],[57,""],[59,"T"],[69,""],[77,"T"],[82,""],[86,"T"],[88,""],[96,"U"],[102,""],[114,"T"],[116,"U,T"],[121,"U"],[126,""],[136,"V"],[141,""],[159,"T"],[161,""],[162,"T"],[163,""],[166,"T"],[171,""],[173,"T"],[174,""],[176,"T"],[177,""],[179,"U"],[180,"T"],[181,"U,T"],[182,"U"],[183,""],[186,"V"],[190,""],[191,"T"],[197,""],[201,"T"],[210,""],[212,"T"],[218,""],[226,"T"],[229,""],[232,"U"],[235,""],[246,"U,T"],[249,"U"],[252,""],[257,"V"]]}],["iroh_dns_server",{"t":"FNNNNNNNNNCCNNNNCNNNCNNNCCNNNNNNGFPPFFFNOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOONNNNNNNNNNNOONNNNNNOOONNNNNNNNNNNNNNNNNNNNNNNNNNNOFFFFNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNOONNNNNNNNNNNNNNNNNNOOOOONNNNNNNNNNNNNNNNNNNNNNNNGPFFFPPGPPPNNNNOONNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFNNNNNNNOOOOOONNNNOOOONNOOOOOONNNNFNNNNNNNNHNNNNNNFNNNNNNNNNONNNOONNNNN","n":["ZoneStore","__clone_box","borrow","borrow_mut","clone","clone_into","clone_to_uninit","compat","compat_mut","compat_ref","config","dns","fmt","from","from_ref","get_signed_packet","http","in_memory","insert","into","metrics","new","persistent","resolve","server","state","to_owned","try_from","try_into","type_id","vzip","with_mainline_fallback","BootstrapOption","Config","Custom","Default","MainlineConfig","MetricsConfig","StoreConfig","__clone_box","bind_addr","bootstrap","borrow","","","","","borrow_mut","","","","","clone","clone_into","clone_to_uninit","compat","","","","","compat_mut","","","","","compat_ref","","","","","data_dir","default","","","","deserialize","","","","","disabled","","dns","enabled","fmt","","","","","from","","","","","from_ref","http","https","into","","","","","load","mainline","metrics","pkarr_put_rate_limit","serialize","","","","","signed_packet_store_path","to_owned","try_from","","","","","try_into","","","","","type_id","","","","","vzip","","","","","zone_store","DnsConfig","DnsHandler","DnsServer","Handle","__clone_box","","","answer_request","bind_addr","borrow","","","","borrow_mut","","","","clone","","","clone_into","","","clone_to_uninit","","","compat","","","","compat_mut","","","","compat_ref","","","","default_soa","default_ttl","deserialize","fmt","","","from","","","","from_ref","","","handle_request","into","","","","local_addr","new","origins","port","rr_a","rr_aaaa","rr_ns","run_until_done","send_response","serialize","shutdown","spawn","to_owned","","","try_from","","","","try_into","","","","type_id","","","","vzip","","","","CertMode","Disabled","HttpConfig","HttpServer","HttpsConfig","LetsEncrypt","Manual","RateLimitConfig","SelfSigned","Simple","Smart","__clone_box","","","","bind_addr","","borrow","","","","","borrow_mut","","","","","cert_mode","clone","","","","clone_into","","","","clone_to_uninit","","","","compat","","","","","compat_mut","","","","","compat_ref","","","","","default","","deserialize","","","","domains","eq","equivalent","","","fmt","","","","","from","","","","","from_ref","","","","http_addr","https_addr","into","","","","","letsencrypt_contact","letsencrypt_prod","port","","run_until_done","serialize","","","","shutdown","spawn","to_owned","","","","to_string","try_from","","","","","try_into","","","","","type_id","","","","","vzip","","","","","Metrics","as_iterable","borrow","borrow_mut","compat","compat_mut","compat_ref","default","dns_lookup_error","dns_lookup_notfound","dns_lookup_success","dns_requests","dns_requests_https","dns_requests_udp","field_count","field_ref","fmt","from","http_requests","http_requests_duration_ms","http_requests_error","http_requests_success","into","name","pkarr_publish_noop","pkarr_publish_update","store_packets_expired","store_packets_inserted","store_packets_removed","store_packets_updated","try_from","try_into","type_id","vzip","Server","borrow","borrow_mut","compat","compat_mut","compat_ref","from","into","run_until_error","run_with_config_until_ctrl_c","shutdown","spawn","try_from","try_into","type_id","vzip","AppState","__clone_box","borrow","borrow_mut","clone","clone_into","clone_to_uninit","compat","compat_mut","compat_ref","dns_handler","from","from_ref","into","metrics","store","to_owned","try_from","try_into","type_id","vzip"],"q":[[0,"iroh_dns_server"],[32,"iroh_dns_server::config"],[134,"iroh_dns_server::dns"],[221,"iroh_dns_server::http"],[344,"iroh_dns_server::metrics"],[378,"iroh_dns_server::server"],[394,"iroh_dns_server::state"],[415,"dyn_clone::sealed"],[416,"iroh_dns_server::store"],[417,"async_compat"],[418,"core::fmt"],[419,"pkarr::signed_packet"],[420,"core::option"],[421,"n0_snafu::error"],[422,"alloc::sync"],[423,"std::path"],[424,"core::convert"],[425,"hickory_proto::rr::domain::name"],[426,"hickory_proto::rr::record_type"],[427,"hickory_proto::rr::rr_set"],[428,"core::result"],[429,"core::any"],[430,"serde::de"],[431,"iroh_dns_server::http::rate_limiting"],[432,"serde::ser"],[433,"hickory_server::server::request_handler"],[434,"bytes::bytes"],[435,"alloc::string"],[436,"core::future::future"],[437,"alloc::boxed"],[438,"core::pin"],[439,"hickory_server::server::response_handler"],[440,"core::net::socket_addr"],[441,"alloc::vec"],[442,"hickory_server::authority::message_response"],[443,"hickory_proto::rr::resource"],[444,"core::iter::traits::iterator"],[445,"core::marker"],[446,"iroh_dns_server::http::tls"],[447,"iroh_metrics::iterable"],[448,"iroh_metrics::metrics"],[449,"iroh_metrics::base"]],"i":"`j00000000``0000`000`000``000000``Bn0```CdC`CbCh3214032143330321403214032140031403214220103214032143000321400000321403032140321403214032140````ClDbDh12Ef32103213213213210321032103213333210321321203210233333013003210321032103210321`Cn```Fl0`01110FhFj10G`432104321143214321432104321043210432144432113333433210432143210004321112104321004321304321043210432104321`Aj00000000000000000000000000000000`Gn0000000`000000`Gb0000000000000000000","f":"`{{bd}f}{b{{b{c}}}{}}{{{b{h}}}{{b{hc}}}{}}{{{b{j}}}j}{{b{b{hc}}}f{}}{{bl}f}{{}{{n{c}}}{}}{{{b{h}}}{{n{{b{hc}}}}}{}}{b{{n{{b{c}}}}}{}}``{{{b{j}}{b{hA`}}}Ab}{cc{}}{{{b{c}}}c{}}{{{b{j}}{b{`}}}{{Ah{{Af{Ad}}}}}}```{{}c{}}```{{{b{j}}{b{`}}{b{Bd}}Bf}{{Ah{{Af{{Al{Bh}}}}}}}}``{bc{}}{c{{Bj{e}}}{}{}}{{}{{Bj{c}}}{}}{bBl}{{}c{}}{{jBn}j}```````{{bd}f}{C`Af}{CbAf}{b{{b{c}}}{}}0000{{{b{h}}}{{b{hc}}}{}}0000{{{b{Cd}}}Cd}{{b{b{hc}}}f{}}{{bl}f}{{}{{n{c}}}{}}0000{{{b{h}}}{{n{{b{hc}}}}}{}}0000{b{{n{{b{c}}}}}{}}0000{{}{{Ah{Cf}}}}{{}Ch}{{}Cd}{{}Cb}{{}Bn}{c{{Bj{Ch}}}Cj}{c{{Bj{Cd}}}Cj}{c{{Bj{C`}}}Cj}{c{{Bj{Cb}}}Cj}{c{{Bj{Bn}}}Cj}{{}C`}{C`An}{ChCl}{CbAn}{{{b{Ch}}{b{hA`}}}Ab}{{{b{Cd}}{b{hA`}}}Ab}{{{b{C`}}{b{hA`}}}Ab}{{{b{Cb}}{b{hA`}}}Ab}{{{b{Bn}}{b{hA`}}}Ab}{cc{}}0000{{{b{c}}}c{}}{ChAf}0{{}c{}}0000{c{{Ah{Ch}}}{{Bb{B`}}}}22{ChCn}{{{b{Ch}}c}BjD`}{{{b{Cd}}c}BjD`}{{{b{C`}}c}BjD`}{{{b{Cb}}c}BjD`}{{{b{Bn}}c}BjD`}{{}{{Ah{Cf}}}}{bc{}}{c{{Bj{e}}}{}{}}0000{{}{{Bj{c}}}{}}0000{bBl}0000{{}c{}}0000>````{{bd}f}00{{{b{Db}}Dd}{{Ah{Df}}}}{ClAf}{b{{b{c}}}{}}000{{{b{h}}}{{b{hc}}}{}}000{{{b{Cl}}}Cl}{{{b{Db}}}Db}{{{b{Dh}}}Dh}{{b{b{hc}}}f{}}00{{bl}f}00{{}{{n{c}}}{}}000{{{b{h}}}{{n{{b{hc}}}}}{}}000{b{{n{{b{c}}}}}{}}000{ClDj}{ClDl}{c{{Bj{Cl}}}Cj}{{{b{Cl}}{b{hA`}}}Ab}{{{b{Db}}{b{hA`}}}Ab}{{{b{Dh}}{b{hA`}}}Ab}{cc{}}000{{{b{c}}}c{}}00{{{b{Db}}{b{Dd}}c}{{Eb{{E`{Dn}}}}}Ed}{{}c{}}000{{{b{Ef}}}Eh}{{j{b{Cl}}{Al{Aj}}}{{Ah{Db}}}}{ClEj}{ClEl}{ClAf}00{Ef{{Ah{f}}}}{{{b{hDh}}{En{cegi}}}{{Eb{{E`{Dn}}}}}{{Fd{}{{F`{{b{Fb}}}}}}Ff}{{Fd{}{{F`{{b{Fb}}}}}}Ff}{{Fd{}{{F`{{b{Fb}}}}}}Ff}{{Fd{}{{F`{{b{Fb}}}}}}Ff}}{{{b{Cl}}c}BjD`}2{{ClDb}{{Ah{Ef}}}}{bc{}}00{c{{Bj{e}}}{}{}}000{{}{{Bj{c}}}{}}000{bBl}000{{}c{}}000```````````{{bd}f}000{FhAf}{FjAf}{b{{b{c}}}{}}0000{{{b{h}}}{{b{hc}}}{}}0000{FjFl}{{{b{Cn}}}Cn}{{{b{Fl}}}Fl}{{{b{Fh}}}Fh}{{{b{Fj}}}Fj}{{b{b{hc}}}f{}}000{{bl}f}000{{}{{n{c}}}{}}0000{{{b{h}}}{{n{{b{hc}}}}}{}}0000{b{{n{{b{c}}}}}{}}0000{{}Cn}{{}{{b{Cn}}}}{c{{Bj{Cn}}}Cj}{c{{Bj{Fl}}}Cj}{c{{Bj{Fh}}}Cj}{c{{Bj{Fj}}}Cj}{FjEj}{{{b{Fl}}{b{Fl}}}An}{{b{b{c}}}An{}}00{{{b{Cn}}{b{hA`}}}Ab}{{{b{Fl}}{b{hA`}}}{{Bj{fFn}}}}{{{b{Fl}}{b{hA`}}}Ab}{{{b{Fh}}{b{hA`}}}Ab}{{{b{Fj}}{b{hA`}}}Ab}{cc{}}0000{{{b{c}}}c{}}000{{{b{G`}}}{{Af{Eh}}}}0{{}c{}}0000{FjAf}0{FhEl}{FjEl}{G`{{Ah{f}}}}{{{b{Cn}}c}BjD`}{{{b{Fl}}c}BjD`}{{{b{Fh}}c}BjD`}{{{b{Fj}}c}BjD`}4{{{Af{Fh}}{Af{Fj}}CnGb}{{Ah{G`}}}}{bc{}}000{bDj}{c{{Bj{e}}}{}{}}0000{{}{{Bj{c}}}{}}0000{bBl}0000{{}c{}}0000`{b{{b{Gd}}}}{b{{b{c}}}{}}{{{b{h}}}{{b{hc}}}{}}{{}{{n{c}}}{}}{{{b{h}}}{{n{{b{hc}}}}}{}}{b{{n{{b{c}}}}}{}}{{}Aj}{AjGf}00000{{{b{Aj}}}Gh}{{{b{Aj}}Gh}{{Af{Gj}}}}{{{b{Aj}}{b{hA`}}}Ab}{cc{}}4444{{}c{}}{{{b{Aj}}}{{b{Gl}}}}666666{c{{Bj{e}}}{}{}}{{}{{Bj{c}}}{}}{bBl}{{}c{}}`{b{{b{c}}}{}}{{{b{h}}}{{b{hc}}}{}}{{}{{n{c}}}{}}{{{b{h}}}{{n{{b{hc}}}}}{}}{b{{n{{b{c}}}}}{}};:{Gn{{Ah{f}}}}{Ch{{Ah{f}}}}1{{Chj{Al{Aj}}}{{Ah{Gn}}}};:98`{{bd}f}87{{{b{Gb}}}Gb}{{b{b{hc}}}f{}}{{bl}f}987{GbDb}{cc{}}{{{b{c}}}c{}}{{}c{}}{GbAl}{Gbj}{bc{}}{c{{Bj{e}}}{}{}}{{}{{Bj{c}}}{}}{bBl}{{}c{}}","D":"AAj","p":[[1,"reference",null,null,1],[5,"Private",415],[1,"unit"],[0,"mut"],[5,"ZoneStore",0,416],[1,"u8"],[5,"Compat",417],[5,"Formatter",418],[8,"Result",418],[5,"SignedPacket",419],[6,"Option",420,null,1],[8,"Result",421],[5,"Metrics",344],[5,"Arc",422,null,1],[1,"bool"],[5,"Path",423],[10,"AsRef",424],[5,"Name",425],[6,"RecordType",426],[5,"RecordSet",427],[6,"Result",428,null,1],[5,"TypeId",429],[6,"BootstrapOption",32],[5,"MetricsConfig",32],[5,"MainlineConfig",32],[5,"StoreConfig",32],[5,"PathBuf",423],[5,"Config",32],[10,"Deserializer",430],[5,"DnsConfig",134],[6,"RateLimitConfig",221,431],[10,"Serializer",432],[5,"DnsHandler",134],[5,"Request",433],[5,"Bytes",434],[5,"Handle",134],[5,"String",435],[1,"u32"],[10,"Future",436,null,1],[5,"Box",437,null,1],[5,"Pin",438],[10,"ResponseHandler",439],[5,"DnsServer",134],[6,"SocketAddr",440],[5,"Vec",441],[1,"u16"],[5,"MessageResponse",442],[17,"Item"],[5,"Record",443],[10,"Iterator",444],[10,"Send",445],[5,"HttpConfig",221],[5,"HttpsConfig",221],[6,"CertMode",221,446],[5,"Error",418],[5,"HttpServer",221],[5,"AppState",394],[10,"Iterable",447],[5,"Counter",448],[1,"usize"],[5,"MetricItem",449],[1,"str"],[5,"Server",378]],"r":[[0,416],[1,416],[2,416],[3,416],[4,416],[5,416],[6,416],[7,416],[8,416],[9,416],[12,416],[13,416],[14,416],[15,416],[17,416],[18,416],[19,416],[21,416],[22,416],[23,416],[26,416],[27,416],[28,416],[29,416],[30,416],[31,416],[221,446],[222,431],[226,446],[227,446],[228,431],[229,446],[230,431],[231,431],[232,431],[233,446],[239,431],[240,446],[244,431],[245,446],[249,431],[250,446],[253,431],[254,446],[257,431],[258,446],[262,431],[263,446],[267,431],[268,446],[272,431],[273,446],[276,431],[277,431],[278,431],[279,446],[283,446],[284,446],[285,446],[286,446],[287,431],[288,446],[289,446],[293,431],[294,446],[297,431],[298,446],[304,431],[305,446],[313,431],[314,446],[319,431],[320,446],[323,446],[325,431],[326,446],[330,431],[331,446],[335,431],[336,446],[340,431],[341,446]],"b":[[276,"impl-Default-for-RateLimitConfig"],[277,"impl-Default-for-%26RateLimitConfig"],[288,"impl-Display-for-CertMode"],[289,"impl-Debug-for-CertMode"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAABIBIQACAAgADQAAAA8AAAAbAAQAKAAAACsAGwBIAAgAVQAEAF8AAABrAAQAcQAUAIsAAgCQABwArwADALcAAwDHAAEAywASAOkAAwDvAAkA+gAgABwBCAAqAQMAOgEDAEABGABaAQYAZwECAHABAAB3AQMAfAEEAIcBAwCMAQgAlwEAAJsBBAA=","P":[[2,"T"],[4,""],[5,"T"],[6,""],[7,"T"],[12,""],[13,"T"],[15,""],[19,"U"],[21,""],[22,""],[23,""],[26,"T"],[27,"U,T"],[28,"U"],[29,""],[30,"V"],[31,""],[42,"T"],[52,""],[53,"T"],[54,""],[55,"T"],[70,""],[75,"__D"],[80,""],[89,"T"],[95,""],[97,"U"],[102,""],[103,""],[106,"__S"],[111,""],[112,"T"],[113,"U,T"],[118,"U"],[123,""],[128,"V"],[133,""],[143,"T"],[151,""],[154,"T"],[157,""],[160,"T"],[172,""],[174,"__D"],[175,""],[178,"T"],[185,"R"],[186,"U"],[190,""],[198,",,,"],[199,"__S"],[200,""],[202,"T"],[205,"U,T"],[209,"U"],[213,""],[217,"V"],[232,""],[238,"T"],[248,""],[253,"T"],[257,""],[261,"T"],[276,""],[278,"__D"],[282,""],[284,"K"],[287,""],[292,"T"],[301,""],[303,"U"],[308,""],[313,"__S"],[317,""],[319,"T"],[323,""],[324,"U,T"],[329,"U"],[334,""],[339,"V"],[345,""],[346,"T"],[351,""],[361,"T"],[362,""],[366,"U"],[367,""],[374,"U,T"],[375,"U"],[376,""],[377,"V"],[379,"T"],[385,"U"],[386,""],[390,"U,T"],[391,"U"],[392,""],[393,"V"],[395,""],[396,"T"],[398,""],[399,"T"],[400,""],[401,"T"],[404,""],[405,"T"],[407,"U"],[408,""],[410,"T"],[411,"U,T"],[412,"U"],[413,""],[414,"V"]]}],["iroh_relay",{"t":"EFFFFNNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNNCNNNNOCCONNCOONNNNNNNNNNNNNNNNNNONNNNNFFFFGPGPPPPPPPPPPPPPPPPPPPPPPPPPPGPGPGGPPPPPPPPPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNHNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOSSSSSSGFFPPSSPPPPFPFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOGSSPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNPGPGPSPPPPPGPTFFKFPPGPPFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOCCCSHPPPGPPPPPPPSPPPPGPPGPPPPPPPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPGFPPPPPPPPPPPGFGPFPPPPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNHNNNNNNNNNNNNNNNNCHHNHHNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOSSSSPPGPSSFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOGGPPPPGFSPPPPFPPFPPPFPFFPFPFFGFFGPFPPNNNOOOONNNNNNOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOONNONONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOONNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNONNNONNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOONOOONONNNOOOONOOONONOOOOOOONNNNNOONNCONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOONNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOHHHHHH","n":["MAX_PACKET_SIZE","PingTracker","RelayMap","RelayNode","RelayQuicConfig","__clone_box","","","borrow","","","","borrow_mut","","","","client","clone","","","clone_into","","","clone_to_uninit","","","cmp","","compare","","compat","","","","compat_mut","","","","compat_ref","","","","contains_node","default","","default_timeout","defaults","deref","","","","deref_mut","","","","deserialize","","dns","drop","","","","empty","eq","","","equivalent","","","","","","","","","fmt","","","","","","from","","","","","","","from_iter","","get_node","http","init","","","","into","","","","is_empty","len","new","new_ping","node_info","nodes","partial_cmp","","pong_received","port","protos","quic","","serialize","","server","stun_only","stun_port","timeout","to_owned","","","to_string","","try_from","","","","try_into","","","","type_id","","","","url","urls","vzip","","","","Client","ClientBuilder","ClientSink","ClientStream","ConnectError","Dial","DialError","Dns","ExceedsMaxPacketSize","Handshake","Health","InvalidProtocolMessageEncoding","InvalidRelayUrl","InvalidTargetPort","InvalidTlsServername","InvalidUrl","InvalidWebsocketUrl","Io","","KeepAlive","NoLocalAddr","NodeGone","Ping","","Pong","","ProtocolRecv","ProtocolSend","ProxyConnect","ProxyConnectInvalidStatus","ProxyInvalidTargetPort","ProxyInvalidTlsServername","ProxyInvalidUrl","ReceivedMessage","ReceivedPacket","RecvError","RelayIo","SendError","SendMessage","SendPacket","ServerRestarting","Timeout","Tls","UnexpectedFrame","UnexpectedUpgradeStatus","Upgrade","Websocket","","WebsocketIo","__clone_box","","address_family_selector","as_error_source","","","","backtrace","","","","borrow","","","","","","","","","","borrow_mut","","","","","","","","","","cause","","","","clone","","clone_into","","clone_to_uninit","","compat","","","","","","","","","","compat_mut","","","","","","","","","","compat_ref","","","","","","","","","","connect","deref","","","","","","","","","","deref_mut","","","","","","","","","","description","","","","drop","","","","","","","","","","fmt","","","","","","","","","","","","","","from","","","","","","","","","","","","","","","","","","","","","","in_current_span","","","","init","","","","","","","","","","insecure_skip_cert_verify","into","","","","","","","","","","is_prober","key_cache_capacity","local_addr","make_dangerous_client_config","new","poll_close","","poll_flush","","poll_next","","poll_ready","","protocol","proxy_url","ratelimit_sink","","ratelimit_sink_with_jitter","","ratelimit_stream","","ratelimit_stream_with_jitter","","source","","","","split","start_send","","to_owned","","to_string","","","","try_from","","","","","","","","","","try_into","","","","","","","","","","try_poll_next","","type_id","","","","","","","","","","vzip","","","","","","","","","","backtrace","","","","","","","","","","code","source","","","","","span_trace","","","","","","","","","","url","","backtrace","","","","","","","","","","proxy_hostname","proxy_url","source","","","","span_trace","","","","","","","","","","status","url","data","problem","reconnect_in","remote_node_id","try_for","backtrace","","","","","","frame_type","source","","","","","span_trace","","","","","","backtrace","","","size","source","","span_trace","","","DEFAULT_HTTPS_PORT","DEFAULT_HTTP_PORT","DEFAULT_KEY_CACHE_CAPACITY","DEFAULT_METRICS_PORT","DEFAULT_RELAY_QUIC_PORT","DEFAULT_STUN_PORT","DnsError","DnsResolver","Error","InvalidResponse","MissingHost","N0_DNS_NODE_ORIGIN_PROD","N0_DNS_NODE_ORIGIN_STAGING","NoResponse","Resolve","ResolveBoth","Staggered","TXT","Timeout","TxtLookup","__clone_box","","","as_error_source","","backtrace","","borrow","","","","","borrow_mut","","","","","cause","","clear_cache","clone","","","clone_into","","","clone_to_uninit","","","compat","","","","","compat_mut","","","","","compat_ref","","","","","default","deref","","","","","deref_mut","","","","","description","","drop","","","","","fmt","","","","","","","","from","","","","","","","","","in_current_span","","init","","","","","into","","","","","into_iter","lookup_ipv4","lookup_ipv4_ipv6","lookup_ipv4_ipv6_staggered","lookup_ipv4_staggered","lookup_ipv6","lookup_ipv6_staggered","lookup_node_by_domain_name","lookup_node_by_domain_name_staggered","lookup_node_by_id","lookup_node_by_id_staggered","lookup_txt","new","resolve","resolve_host","source","","to_owned","","","to_string","","","try_from","","","","","try_into","","","","","txt_data","type_id","","","","","vzip","","","","","with_nameserver","backtrace","","","","","","","errors","ipv4","ipv6","source","","span_trace","","","","","","","Protocol","RELAY_PATH","RELAY_PROBE_PATH","Relay","Websocket","__clone_box","borrow","borrow_mut","clone","clone_into","clone_to_uninit","compat","compat_mut","compat_ref","default","deref","deref_mut","drop","eq","equivalent","","","fmt","from","init","into","parse_header","to_owned","try_from","try_into","type_id","upgrade_header","vzip","AttrFromString","DecodingError","","EncodingError","FailedBuildingPacket","IROH_TXT_NAME","InvalidEncodingZ32","InvalidLabel","InvalidLength","InvalidSignature","InvalidTxtEntry","LookupError","LookupFailed","MAX_LENGTH","MaxLengthExceededError","NodeData","NodeIdExt","NodeInfo","NotAnIrohRecord","NumLabels","ParseError","","UnexpectedFormat","UserData","Utf8","__clone_box","","","add_direct_addresses","as_error_source","","","","","as_ref","backtrace","","","","","borrow","","","","","","","","borrow_mut","","","","","","","","cause","","","","","clear_direct_addresses","clone","","","clone_into","","","clone_to_uninit","","","cmp","compare","compat","","","","","","","","compat_mut","","","","","","","","compat_ref","","","","","","","","data","default","deref","","","","","","","","","deref_mut","","","","","","","","","description","","","","","direct_addresses","drop","","","","","","","","eq","","","equivalent","","","","","","","","","fmt","","","","","","","","","","","","","","from","","","","","","","","","","","","from_parts","from_pkarr_signed_packet","from_str","from_txt_lookup","from_z32","hash","in_current_span","","","","","init","","","","","","","","into","","","","","","","","into_node_addr","new","","node_id","partial_cmp","relay_url","set_relay_url","set_user_data","source","","","","","to_node_addr","to_owned","","","to_pkarr_signed_packet","to_string","","","","","","to_txt_strings","to_z32","try_from","","","","","","","","","try_into","","","","","","","","type_id","","","","","","","","user_data","vzip","","","","","","","","with_direct_addresses","","with_relay_url","","with_user_data","","backtrace","","","len","source","","span_trace","","","backtrace","","source","","span_trace","","backtrace","","","source","","","span_trace","","","backtrace","","","","","","key","label","num_labels","s","source","","span_trace","","","","","","disco","relay","stun","MAGIC","looks_like_disco_wrapper","ClientInfo","ConnSend","FrameTooLarge","FrameType","Health","InvalidFrame","InvalidFrameType","InvalidSignature","Io","","KeepAlive","MAX_PACKET_SIZE","NotePreferred","PeerGone","Ping","Pong","RecvError","RecvPacket","Restarting","SendError","SendPacket","SerDe","","Timeout","","TooSmall","UnexpectedFrame","Unknown","__clone_box","as_error_source","","backtrace","","borrow","","","borrow_mut","","","cause","","clone","clone_into","clone_to_uninit","compat","","","compat_mut","","","compat_ref","","","deref","","","deref_mut","","","description","","drop","","","eq","equivalent","","","fmt","","","","","","from","","","","","","","","","","","","from_primitive","in_current_span","","init","","","into","","","source","","to_owned","to_string","","","try_from","","","try_into","","","type_id","","","vzip","","","backtrace","","","","","","","","","expected","frame_len","frame_type","got","source","","","","span_trace","","","","","","","","","backtrace","","","","source","","","","span_trace","","","","AlternateServer","ErrorCode","ErrorResponse","Fingerprint","Indication","InvalidFingerprint","InvalidMessage","MalformedAttrs","MappedAddress","MessageClass","MessageDecoder","MessageIntegrity","MessageIntegritySha256","NoFingerprint","Nonce","NotBinding","NotSuccessResponse","PasswordAlgorithm","PasswordAlgorithms","Realm","Request","Software","StunAttribute","StunDecodeError","StunError","SuccessResponse","TransactionId","Unknown","UnknownAttributes","UserHash","UserName","XorMappedAddress","__clone_box","","","","as_alternate_server","as_bytes","as_error_code","as_error_source","","as_fingerprint","as_mapped_address","as_message_integrity","as_message_integrity_sha256","as_nonce","as_password_algorithm","as_password_algorithms","as_realm","as_ref","as_software","as_unknown","as_unknown_attributes","as_user_hash","as_user_name","as_xor_mapped_address","attribute_type","backtrace","borrow","","","","","","borrow_mut","","","","","","cause","clone","","","","clone_into","","","","clone_to_uninit","","","","cmp","compare","compat","","","","","","compat_mut","","","","","","compat_ref","","","","","","decode","default","","deref","","","","","","","deref_mut","","","","","","description","drop","","","","","","eq","","equivalent","","","","","","expect_alternate_server","expect_error_code","expect_fingerprint","expect_mapped_address","expect_message_integrity","expect_message_integrity_sha256","expect_nonce","expect_password_algorithm","expect_password_algorithms","expect_realm","expect_software","expect_unknown","expect_unknown_attributes","expect_user_hash","expect_user_name","expect_xor_mapped_address","fmt","","","","","","","","","from","","","","","","","","","","","","","","","","","","","","","","","","get_context","hash","in_current_span","","init","","","","","","into","","","","","","is","is_alternate_server","is_error_code","is_fingerprint","is_mapped_address","is_message_integrity","is_message_integrity_sha256","is_nonce","is_password_algorithm","is_password_algorithms","is_realm","is_software","is_unknown","is_unknown_attributes","is_user_hash","is_user_name","is_xor_mapped_address","methods","parse_binding_request","parse_response","partial_cmp","request","response","source","to_owned","","","","to_string","","","try_from","","","","","","","try_into","","","","","","type_id","","","","","","vzip","","","","","","backtrace","","","","","","span_trace","","","","","","BINDING","RESERVED","SHARED_SECRET","ALPN_QUIC_ADDR_DISC","Connect","Connection","Error","NoIntitialCipherSuite","QUIC_ADDR_DISC_CLOSE_CODE","QUIC_ADDR_DISC_CLOSE_REASON","QuicClient","WatchRecv","as_error_source","backtrace","borrow","","borrow_mut","","cause","compat","","compat_mut","","compat_ref","","deref","","deref_mut","","description","drop","","fmt","","","from","","","","","","get_addr_and_latency","in_current_span","init","","into","","new","source","to_string","try_from","","try_into","","type_id","","vzip","","backtrace","","","","source","","","","span_trace","","","","Access","AccessConfig","AcmeEventStreamFinished","Allow","BindTcpListener","BindTlsListener","CertConfig","ClientRateLimit","DEFAULT_CERT_RELOAD_INTERVAL","Deny","Everyone","JoinError","LetsEncrypt","Limits","LocalAddr","Manual","Metrics","","NoLocalAddr","NoRelayServicesEnabled","QuicConfig","QuicSpawn","RelayConfig","RelayMetrics","Reloading","ReloadingResolver","Restricted","Server","ServerConfig","SpawnError","StunConfig","StunMetrics","SupervisorError","TaskCancelled","TlsConfig","TlsHeaderParse","UdpSocketBind","__clone_box","","","accept_conn_burst","accept_conn_limit","accepts","access","as_error_source","","as_iterable","","backtrace","","bad_requests","bind_addr","","borrow","","","","","","","","","","","","","","","","","borrow_mut","","","","","","","","","","","","","","","","","bytes_per_second","bytes_recv","bytes_sent","cause","","cert","certificates","client_rx","clone","","","clone_into","","","clone_to_uninit","","","compat","","","","","","","","","","","","","","","","","compat_mut","","","","","","","","","","","","","","","","","compat_ref","","","","","","","","","","","","","","","","","conns_rx_ratelimited_total","default","","","","","deref","","","","","","","","","","","","","","","","","","deref_mut","","","","","","","","","","","","","","","","","description","","disco_packets_dropped","disco_packets_recv","disco_packets_sent","disconnects","drop","","","","","","","","","","","","","","","","","eq","equivalent","","","failures","field_count","","field_ref","","fmt","","","","","","","","","","","","","","","","","","","frames_rx_ratelimited_total","from","","","","","","","","","","","","","","","","","","got_ping","groups","groups_cloned","http_addr","http_bind_addr","http_url","https_addr","https_bind_addr","https_url","in_current_span","","init","","","","","","","","","","","","","","","","","","into","","","","","","","","","","","","","","","","","ipv4_success","ipv6_success","is_allowed","key_cache_capacity","limits","max_burst_bytes","metrics","metrics_addr","name","","","other_packets_dropped","other_packets_recv","other_packets_sent","quic","quic_addr","quic_bind_addr","relay","relay_accepts","reload","requests","resolve","send_packets_dropped","send_packets_recv","send_packets_sent","sent_pong","server","server_config","","shutdown","","source","","spawn","stun","","stun_addr","task_handle","testing","tls","to_owned","","","to_string","","try_from","","","","","","","","","","","","","","","","","try_into","","","","","","","","","","","","","","","","","type_id","","","","","","","","","","","","","","","","","unique_client_keys","unknown_frames","vzip","","","","","","","","","","","","","","","","","websocket_accepts","certs","state","addr","backtrace","","","","","","","source","","","","","","span_trace","","","","","","","backtrace","","","","","source","","span_trace","","","","","quic_config","relay_config","self_signed_tls_certs_and_config","server_config","stun_config","tls_config"],"q":[[0,"iroh_relay"],[142,"iroh_relay::client"],[436,"iroh_relay::client::ConnectError"],[464,"iroh_relay::client::DialError"],[492,"iroh_relay::client::ReceivedMessage"],[497,"iroh_relay::client::RecvError"],[515,"iroh_relay::client::SendError"],[524,"iroh_relay::defaults"],[530,"iroh_relay::dns"],[680,"iroh_relay::dns::DnsError"],[699,"iroh_relay::http"],[732,"iroh_relay::node_info"],[994,"iroh_relay::node_info::DecodingError"],[1003,"iroh_relay::node_info::EncodingError"],[1009,"iroh_relay::node_info::LookupError"],[1018,"iroh_relay::node_info::ParseError"],[1036,"iroh_relay::protos"],[1039,"iroh_relay::protos::disco"],[1041,"iroh_relay::protos::relay"],[1154,"iroh_relay::protos::relay::RecvError"],[1180,"iroh_relay::protos::relay::SendError"],[1192,"iroh_relay::protos::stun"],[1447,"iroh_relay::protos::stun::StunError"],[1459,"iroh_relay::protos::stun::methods"],[1462,"iroh_relay::quic"],[1517,"iroh_relay::quic::Error"],[1529,"iroh_relay::server"],[1957,"iroh_relay::server::CertConfig"],[1959,"iroh_relay::server::SpawnError"],[1980,"iroh_relay::server::SupervisorError"],[1992,"iroh_relay::server::testing"],[1998,"dyn_clone::sealed"],[1999,"iroh_relay::relay_map"],[2000,"core::cmp"],[2001,"async_compat"],[2002,"iroh_base::relay_url"],[2003,"iroh_relay::ping_tracker"],[2004,"core::time"],[2005,"core::result"],[2006,"serde::de"],[2007,"core::fmt"],[2008,"core::iter::traits::collect"],[2009,"alloc::sync"],[2010,"core::option"],[2011,"core::iter::traits::iterator"],[2012,"serde::ser"],[2013,"alloc::string"],[2014,"core::any"],[2015,"core::ops::function"],[2016,"core::marker"],[2017,"core::error"],[2018,"iroh_relay::client::conn"],[2019,"backtrace::capture"],[2020,"std::io::error"],[2021,"tokio_websockets::error"],[2022,"tokio::time::error"],[2023,"core::net::socket_addr"],[2024,"rustls::client::client_conn"],[2025,"iroh_base::key"],[2026,"core::convert"],[2027,"core::pin"],[2028,"core::task::wake"],[2029,"core::task::poll"],[2030,"url"],[2031,"governor::state::direct"],[2032,"governor::state"],[2033,"governor::state::direct::sinks"],[2034,"governor::clock::with_std"],[2035,"governor::gcra"],[2036,"governor::middleware"],[2037,"governor::jitter"],[2038,"governor::state::direct::streams"],[2039,"http::status"],[2040,"hyper::error"],[2041,"n0_snafu::spantrace"],[2042,"bytes::bytes"],[2043,"core::str::error"],[2044,"iroh_relay::dns::staggered"],[2045,"hickory_resolver::error"],[2046,"hickory_resolver::resolver"],[2047,"hickory_resolver::lookup"],[2048,"core::net::ip_addr"],[2049,"reqwest::dns::resolve"],[2050,"alloc::boxed"],[2051,"alloc::vec"],[2052,"http::header::value"],[2053,"alloc::collections::btree::set"],[2054,"pkarr::signed_packet"],[2055,"iroh_base::node_addr"],[2056,"core::hash"],[2057,"z32"],[2058,"ed25519_dalek::errors"],[2059,"simple_dns::simple_dns_error"],[2060,"hickory_proto::error"],[2061,"postcard::error"],[2062,"stun_rs::attributes"],[2063,"stun_rs::attributes::stun::alternate_server"],[2064,"stun_rs::error"],[2065,"stun_rs::types"],[2066,"stun_rs::attributes::stun::error_code"],[2067,"stun_rs::attributes::stun::fingerprint"],[2068,"stun_rs::attributes::stun::mapped_address"],[2069,"stun_rs::attributes::stun::message_integrity"],[2070,"stun_rs::attributes::stun::message_integrity_sha256"],[2071,"stun_rs::attributes::stun::nonce"],[2072,"stun_rs::attributes::stun::password_algorithm"],[2073,"stun_rs::attributes::stun::password_algorithms"],[2074,"stun_rs::attributes::stun::realm"],[2075,"stun_rs::attributes::stun::software"],[2076,"stun_rs::attributes::unknown"],[2077,"stun_rs::attributes::stun::unknown_attributes"],[2078,"stun_rs::attributes::stun::user_hash"],[2079,"stun_rs::attributes::stun::user_name"],[2080,"stun_rs::attributes::stun::xor_mapped_address"],[2081,"stun_rs::context"],[2082,"stun_rs::message"],[2083,"iroh_quinn_proto::varint"],[2084,"tokio::sync::watch::error"],[2085,"iroh_quinn_proto::endpoint"],[2086,"iroh_quinn_proto::connection"],[2087,"iroh_quinn_proto::crypto::rustls"],[2088,"iroh_quinn::endpoint"],[2089,"iroh_relay::server::metrics"],[2090,"iroh_metrics::metrics"],[2091,"iroh_metrics::iterable"],[2092,"core::num::nonzero"],[2093,"rustls_pki_types"],[2094,"core::default"],[2095,"iroh_relay::server::resolver"],[2096,"iroh_metrics::base"],[2097,"tokio::runtime::task::error"],[2098,"rustls::crypto::signer"],[2099,"reloadable_core"],[2100,"rustls::server::server_conn"],[2101,"tokio_util::task::abort_on_drop"],[2102,"tokio_rustls_acme::state"],[2103,"stun_rs"],[2104,"stun_rs::methods"]],"i":"`````jlnAj3210321`32132132121210321032103213010`0321032121`032133213332221110332210333221333`032103213300`32101``221`22032132032103210321230321`````Dn`E`Dh2EbDl43434031411Eh201144444`2`3``02451551532Cl0426542654231650EdEjEl75649832107598636363756498321075649832107564983210375649832107564983210759875649832107755649988321077755555649999888832107598756498321037564983210330`32121202133212120207598221637598756498321075649832102075649832107564983210IdIfIhIjIlInJ`JbJdJf476530987654321098JnK`KbKdKfKhKjKlKnL`138762987654321045LbLfLh20LlLnM`MbMdMf054321543210MlMnN`021210`````````Fh0``0000`0`G`NdNf3Nb40403214032140332132132140321403214032134032140321404032144003211444033221404032140321233333333333333403214014032140321140321403213A@`A@bA@dA@fA@hA@jA@l044626543210```Gj00000000000000000000000000000AAl`0`AAf`AAhOh112`0AAd````44`14`4AAb1Of154AAj473650476523014765230147650472231231231336523014765230147652301471265230114765230114765047265230147231222333111665523300144776652230114771131ABj4761587634125876341258232243337615823422764158207634412587634125876341258376341258323232ABlABnAC`120210ACfACh1010AClACnAD`210210ADdADfADhADjADlADn413520543210`````MhFbFd`2000102`2222`22`210100022101021021010222210210210210210102102222221100221111100000210210210102210210210210210AEbAEdAEfAEhAEjAElAEnAF`AFb76178543876543210AFdAFfAFhAFj32103210AFl0AIh10AId002``22020022212```1`22222AIf2AGb4404AIl355555555155555553241503241503324152415241511241503241503241503221241150324150332415034144411155555555555555552411500332411155555555555555555032103241503241503`5555555555555555```1``324151032441503241503241503241503AJbAJdAJfAJhAJjAJl543210````AKb0`0```0000AKd101101010101011011011111001101001110101010AL`ALbALdALf32103210``AMfANlAMd0```1AM`3ANd`20`424`2``0`1``````4`22ANj4AMnALh0ALjALn791AMh8:0AMjAMl427AOdANn5;=32ANb89;ANf>AMf97<438>ANl763;<>2AMd2=;;0243<>1=>1=>1=;9>65:AM`2985=>ANd524=;ANj98=24;:7?AMn2746?=1:9>35<;8ALh13857ALj0?3;10?3<<;ALn68?>;235:791AMh5>=179AMjAMl>568=:<:<4444427AOdANn5;=32ANb89;ANf>AMfANl0008:8:8:8=549?0763;<>2AMd022;;9>65:AM`2985=>ANd5244=ANj06=667635><0998=24;:7?AMn2746?=1:9>35<;8ALh13857>>4??18:ALj?3000;9:;0=179AMjAMl>568=:<427AOdANn5;=32ANb89;ANf>AMf97<438>ANl763;<>2AMd2;;;9>65:AM`2985=>ANd524=B@hB@jB@nBA`BAbBAdBAfBAhBAj65432105432106BAnBB`BBbBBdBBf4243210``````","f":"`````{{bd}f}00{b{{b{c}}}{}}000{{{b{h}}}{{b{hc}}}{}}000`{{{b{j}}}j}{{{b{l}}}l}{{{b{n}}}n}{{b{b{hc}}}f{}}00{{bA`}f}00{{{b{l}}{b{l}}}Ab}{{{b{n}}{b{n}}}Ab}{{b{b{c}}}Ab{}}0{{}{{Ad{c}}}{}}000{{{b{h}}}{{Ad{{b{hc}}}}}{}}000{b{{Ad{{b{c}}}}}{}}000{{{b{j}}{b{Af}}}Ah}{{}Aj}{{}n}{{{b{Aj}}}Al}`{An{{b{c}}}{}}000{An{{b{hc}}}{}}000{c{{B`{l}}}Bb}{c{{B`{n}}}Bb}`{Anf}000{{}j}{{{b{j}}{b{j}}}Ah}{{{b{l}}{b{l}}}Ah}{{{b{n}}{b{n}}}Ah}{{b{b{c}}}Ah{}}00000000{{{b{Aj}}{b{hBd}}}Bf}{{{b{j}}{b{hBd}}}Bf}0{{{b{l}}{b{hBd}}}Bf}0{{{b{n}}{b{hBd}}}Bf}{cc{}}{lj}1{Afj}2{Afl}3{cj{{Bj{}{{Bh{l}}}}}}{cj{{Bj{}{{Bh{Af}}}}}}{{{b{j}}{b{Af}}}{{Bn{{b{{Bl{l}}}}}}}}`{{}An}000{{}c{}}000{{{b{j}}}Ah}{{{b{j}}}An}{AlAj}{{{b{hAj}}}{{C`{A`}}}}`{{{b{j}}}{{`{{Cb{}{{Bh{{b{{Bl{l}}}}}}}}}}}}{{{b{l}}{b{l}}}{{Bn{Ab}}}}{{{b{n}}{b{n}}}{{Bn{Ab}}}}{{{b{hAj}}{C`{A`}}}f}{nCd}``{lBn}{{{b{l}}c}B`Cf}{{{b{n}}c}B`Cf}`{lAh}{lCd}{{{b{hAj}}}f}{bc{}}00{bCh}0{c{{B`{e}}}{}{}}000{{}{{B`{c}}}{}}000{bCj}000{lAf}{{{b{j}}}{{`{{Cb{}{{Bh{{b{Af}}}}}}}}}}{{}c{}}000`````````````````````````````````````````````````{{bd}f}0{{Clc}Cl{{D`{}{{Cn{Ah}}}}DbDd}}{b{{b{Df}}}}000{{{b{Dh}}}{{Bn{{b{Dj}}}}}}{{{b{Dl}}}{{Bn{{b{Dj}}}}}}{{{b{Dn}}}{{Bn{{b{Dj}}}}}}{{{b{E`}}}{{Bn{{b{Dj}}}}}}{b{{b{c}}}{}}000000000{{{b{h}}}{{b{hc}}}{}}000000000{{{b{Dh}}}{{Bn{{b{Df}}}}}}{{{b{Dl}}}{{Bn{{b{Df}}}}}}{{{b{Dn}}}{{Bn{{b{Df}}}}}}{{{b{E`}}}{{Bn{{b{Df}}}}}}{{{b{Eb}}}Eb}{{{b{Cl}}}Cl}{{b{b{hc}}}f{}}0{{bA`}f}0{{}{{Ad{c}}}{}}000000000{{{b{h}}}{{Ad{{b{hc}}}}}{}}000000000{b{{Ad{{b{c}}}}}{}}000000000{{{b{Cl}}}{{B`{EdDn}}}}{An{{b{c}}}{}}000000000{An{{b{hc}}}{}}000000000{{{b{Dh}}}{{b{Ef}}}}{{{b{Dl}}}{{b{Ef}}}}{{{b{Dn}}}{{b{Ef}}}}{{{b{E`}}}{{b{Ef}}}}{Anf}000000000{{{b{Dh}}{b{hBd}}}Bf}0{{{b{Dl}}{b{hBd}}}Bf}0{{{b{Eb}}{b{hBd}}}Bf}{{{b{Eh}}{b{hBd}}}Bf}{{{b{Dn}}{b{hBd}}}Bf}0{{{b{E`}}{b{hBd}}}Bf}0{{{b{Cl}}{b{hBd}}}Bf}{{{b{Ed}}{b{hBd}}}Bf}{{{b{Ej}}{b{hBd}}}Bf}{{{b{El}}{b{hBd}}}Bf}{EnDh}{F`Dh}{cc{}}{F`Dl}{EnDl}2{FbDl}{FdDl}44{FbDn}{F`Dn}6{E`Dn}{EnE`}8{FfE`}{FhE`}::::{{}}000{{}An}000000000{{ClAh}Cl}{{}c{}}0000000001{{ClAn}Cl}{{{b{El}}}{{Bn{Fj}}}}{{}Fl}{{cFnG`}Cl{{Gb{Af}}}}{{{Gd{{b{hEd}}}}{b{hGf}}}{{Gh{{B`{fc}}}}}{}}{{{Gd{{b{hEj}}}}{b{hGf}}}{{Gh{{B`{fc}}}}}{}}10{{{Gd{{b{hEd}}}}{b{hGf}}}{{Gh{{Bn{c}}}}}{}}{{{Gd{{b{hEl}}}}{b{hGf}}}{{Gh{{Bn{c}}}}}{}}32{{ClGj}Cl}{{ClGl}Cl}{{{b{{H`{Gnceg}}}}}{{Hb{ikceg}}}HdHf{{Hl{}{{Hh{Hj}}}}}{}{}}0{{{b{{H`{Gnceg}}}}Hn}{{Hb{ikceg}}}HdHf{{Hl{}{{Hh{Hj}}}}}{}{}}0{{{b{{H`{Gnceg}}}}}{{I`{iceg}}}HdHfHl{}}0{{{b{{H`{Gnceg}}}}Hn}{{I`{iceg}}}HdHfHl{}}0{{{b{Dh}}}{{Bn{{b{Df}}}}}}{{{b{Dl}}}{{Bn{{b{Df}}}}}}{{{b{Dn}}}{{Bn{{b{Df}}}}}}{{{b{E`}}}{{Bn{{b{Df}}}}}}{Ed{{Ib{ElEj}}}}{{{Gd{{b{hEd}}}}Eh}{{B`{fc}}}{}}{{{Gd{{b{hEj}}}}Eh}{{B`{fc}}}{}}{bc{}}0{bCh}000{c{{B`{e}}}{}{}}000000000{{}{{B`{c}}}{}}000000000{{{Gd{{b{hc}}}}{b{hGf}}}{{Gh{{Bn{B`}}}}}{}}0{bCj}000000000{{}c{}}000000000{IdBn}{IfBn}{IhBn}{IjBn}{IlBn}{InBn}{J`Bn}{JbBn}{JdBn}{JfBn}{InJh}{IhF`}{IjFb}{IlE`}{J`Jj}{JfEn}{IdJl}{IfJl}{IhJl}{IjJl}{IlJl}{InJl}{J`Jl}{JbJl}{JdJl}{JfJl}{IdGl}{IfGl}{JnBn}{K`Bn}{KbBn}{KdBn}{KfBn}{KhBn}{KjBn}{KlBn}{KnBn}{L`Bn}{KnCh}{KjGl}{K`Fh}{KbFf}{KdEn}{KlJj}{JnJl}{K`Jl}{KbJl}{KdJl}{KfJl}{KhJl}{KjJl}{KlJl}{KnJl}{L`Jl}{KhJh}{KfGl}{LbLd}{LfBn}{LhAl}{LbLj}1{LlBn}{LnBn}{M`Bn}{MbBn}{MdBn}{MfBn}{MfMh}{LlEn}{LnFb}{M`Fd}{MbF`}{MdMj}{LlJl}{LnJl}{M`Jl}{MbJl}{MdJl}{MfJl}{MlBn}{MnBn}{N`Bn}{N`An}{MlEn}{MnF`}{MlJl}{MnJl}{N`Jl}{{}Cd}0{{}An}111`````{{}b}0```````{{bd}f}00{b{{b{Df}}}}0{{{b{Fh}}}{{Bn{{b{Dj}}}}}}{{{b{Nb}}}{{Bn{{b{Dj}}}}}}{b{{b{c}}}{}}0000{{{b{h}}}{{b{hc}}}{}}0000{{{b{Fh}}}{{Bn{{b{Df}}}}}}{{{b{Nb}}}{{Bn{{b{Df}}}}}}{{{b{G`}}}f}{{{b{G`}}}G`}{{{b{Nd}}}Nd}{{{b{Nf}}}Nf}{{b{b{hc}}}f{}}00{{bA`}f}00{{}{{Ad{c}}}{}}0000{{{b{h}}}{{Ad{{b{hc}}}}}{}}0000{b{{Ad{{b{c}}}}}{}}0000{{}G`}{An{{b{c}}}{}}0000{An{{b{hc}}}{}}0000{{{b{Fh}}}{{b{Ef}}}}{{{b{Nb}}}{{b{Ef}}}}{Anf}0000{{{b{Fh}}{b{hBd}}}Bf}0{{{b{Nb}}{b{hBd}}}Bf}0{{{b{G`}}{b{hBd}}}Bf}{{{b{Nd}}{b{hBd}}}Bf}{{{b{Nf}}{b{hBd}}}Bf}0{cc{}}{NhFh}{FfFh}2{NjG`}33{NlNd}4{{}}0{{}An}0000{{}c{}}0000{Ndc{}}{{{b{G`}}cAl}{{B`{{`{{Cb{}{{Bh{Nn}}}}}}Fh}}}O`}0{{{b{G`}}cAl{b{{Od{Ob}}}}}{{B`{{`{{Cb{}{{Bh{Nn}}}}}}Fh}}}O`}010{{{b{G`}}{b{Ef}}}{{B`{OfOh}}}}{{{b{G`}}{b{Ef}}{b{{Od{Ob}}}}}{{B`{OfNb}}}}{{{b{G`}}{b{Lj}}{b{Ef}}}{{B`{OfOh}}}}{{{b{G`}}{b{Lj}}{b{Ef}}{b{{Od{Ob}}}}}{{B`{OfNb}}}}{{{b{G`}}cAl}{{B`{NdFh}}}O`}{{}G`}{{{b{G`}}Oj}Ol}{{{b{G`}}{b{Gl}}AhAl}{{B`{NnFh}}}}{{{b{Fh}}}{{Bn{{b{Df}}}}}}{{{b{Nb}}}{{Bn{{b{Df}}}}}}{bc{}}00{bCh}00{c{{B`{e}}}{}{}}0000{{}{{B`{c}}}{}}0000{{{b{Nf}}}{{b{{Od{{On{{Od{A`}}}}}}}}}}{bCj}0000{{}c{}}0000{FjG`}{A@`Bn}{A@bBn}{A@dBn}{A@fBn}{A@hBn}{A@jBn}{A@lBn}{A@lA@n}{A@dOn}0{A@`Ff}{A@hNh}{A@`Jl}{A@bJl}{A@dJl}{A@fJl}{A@hJl}{A@jJl}{A@lJl}`{{}b}0``{{bd}f}{b{{b{c}}}{}}{{{b{h}}}{{b{hc}}}{}}{{{b{Gj}}}Gj}{{b{b{hc}}}f{}}{{bA`}f}{{}{{Ad{c}}}{}}{{{b{h}}}{{Ad{{b{hc}}}}}{}}{b{{Ad{{b{c}}}}}{}}{{}Gj}{An{{b{c}}}{}}{An{{b{hc}}}{}}{Anf}{{{b{Gj}}{b{Gj}}}Ah}{{b{b{c}}}Ah{}}00{{{b{Gj}}{b{hBd}}}Bf}{cc{}}{{}An}{{}c{}}{{{b{AA`}}}{{Bn{Gj}}}}{bc{}}{c{{B`{e}}}{}{}}{{}{{B`{c}}}{}}{bCj}{{{b{Gj}}}{{b{Ef}}}}{{}c{}}`````{{}b}```````````````````{{bd}f}00{{{b{hAAb}}c}f{{Bj{}{{Bh{Fj}}}}}}{b{{b{Df}}}}0000{{{b{AAd}}}{{b{Ef}}}}{{{b{AAf}}}{{Bn{{b{Dj}}}}}}{{{b{AAh}}}{{Bn{{b{Dj}}}}}}{{{b{AAj}}}{{Bn{{b{Dj}}}}}}{{{b{Oh}}}{{Bn{{b{Dj}}}}}}{{{b{AAl}}}{{Bn{{b{Dj}}}}}}{b{{b{c}}}{}}0000000{{{b{h}}}{{b{hc}}}{}}0000000{{{b{AAf}}}{{Bn{{b{Df}}}}}}{{{b{AAh}}}{{Bn{{b{Df}}}}}}{{{b{AAj}}}{{Bn{{b{Df}}}}}}{{{b{Oh}}}{{Bn{{b{Df}}}}}}{{{b{AAl}}}{{Bn{{b{Df}}}}}}{{{b{hAAb}}}f}{{{b{AAb}}}AAb}{{{b{AAd}}}AAd}{{{b{Of}}}Of}{{b{b{hc}}}f{}}00{{bA`}f}00{{{b{AAd}}{b{AAd}}}Ab}{{b{b{c}}}Ab{}}{{}{{Ad{c}}}{}}0000000{{{b{h}}}{{Ad{{b{hc}}}}}{}}0000000{b{{Ad{{b{c}}}}}{}}0000000{OfAAb}{{}AAb}{An{{b{c}}}{}}0000{{{b{Of}}}{{b{c}}}{}}111{An{{b{hc}}}{}}0000{{{b{hOf}}}{{b{hc}}}{}}111{{{b{AAf}}}{{b{Ef}}}}{{{b{AAh}}}{{b{Ef}}}}{{{b{AAj}}}{{b{Ef}}}}{{{b{Oh}}}{{b{Ef}}}}{{{b{AAl}}}{{b{Ef}}}}{{{b{AAb}}}{{b{{AAn{Fj}}}}}}{Anf}0000000{{{b{AAb}}{b{AAb}}}Ah}{{{b{AAd}}{b{AAd}}}Ah}{{{b{Of}}{b{Of}}}Ah}{{b{b{c}}}Ah{}}00000000{{{b{AAf}}{b{hBd}}}Bf}0{{{b{AAh}}{b{hBd}}}Bf}0{{{b{AAb}}{b{hBd}}}Bf}{{{b{AAd}}{b{hBd}}}Bf}0{{{b{AAj}}{b{hBd}}}Bf}0{{{b{Of}}{b{hBd}}}Bf}{{{b{Oh}}{b{hBd}}}Bf}0{{{b{AAl}}{b{hBd}}}Bf}0{cc{}}{AB`AAf}1{ABbAAb}222{ABbOf}333{AAhAAl}{{LjAAb}Of}{{{b{ABd}}}{{B`{OfAAl}}}}{{{b{Ef}}}{{B`{AAdc}}}{}}{Nd{{B`{OfAAl}}}}{{{b{Ef}}}{{B`{LjAAh}}}}{{{b{AAd}}{b{hc}}}fABf}{{}}0000{{}An}0000000{{}c{}}0000000{OfABb}{{{Bn{Af}}{AAn{Fj}}}AAb}{LjOf}{OfLj}{{{b{AAd}}{b{AAd}}}{{Bn{Ab}}}}{{{b{AAb}}}{{Bn{{b{Af}}}}}}{{{b{hAAb}}{Bn{Af}}}f}{{{b{hAAb}}{Bn{AAd}}}f}{{{b{AAf}}}{{Bn{{b{Df}}}}}}{{{b{AAh}}}{{Bn{{b{Df}}}}}}{{{b{AAj}}}{{Bn{{b{Df}}}}}}{{{b{Oh}}}{{Bn{{b{Df}}}}}}{{{b{AAl}}}{{Bn{{b{Df}}}}}}{{{b{Of}}}ABb}{bc{}}00{{{b{Of}}{b{Fn}}ABh}{{B`{ABdAAf}}}}{bCh}00000{{{b{Of}}}{{A@n{Ch}}}}{{{b{ABj}}}Ch}{c{{B`{e}}}{}{}}00{Ch{{B`{AAdc}}}{}}11111{{}{{B`{c}}}{}}0000000{bCj}0000000{{{b{AAb}}}{{Bn{{b{AAd}}}}}}{{}c{}}0000000{{AAb{AAn{Fj}}}AAb}{{Of{AAn{Fj}}}Of}{{AAb{Bn{Af}}}AAb}{{Of{Bn{Af}}}Of}{{AAb{Bn{AAd}}}AAb}{{Of{Bn{AAd}}}Of}{ABlBn}{ABnBn}{AC`Bn}{ABnAn}{ABlACb}{AC`ACd}{ABlJl}{ABnJl}{AC`Jl}{ACfBn}{AChBn}{ACfAB`}{AChACj}{ACfJl}{AChJl}{AClBn}{ACnBn}{AD`Bn}{AClOn}{ACnOn}{AD`ADb}{AClJl}{ACnJl}{AD`Jl}{ADdBn}{ADfBn}{ADhBn}{ADjBn}{ADlBn}{ADnBn}{ADfCh}{ADlCh}{ADhAn}{ADdCh}{ADjMj}{ADnOn}{ADdJl}{ADfJl}{ADhJl}{ADjJl}{ADlJl}{ADnJl}```{{}b}{{{b{{Od{A`}}}}}Ah}```````````{{}An}````````````````{{bd}f}{b{{b{Df}}}}0{{{b{Fb}}}{{Bn{{b{Dj}}}}}}{{{b{Fd}}}{{Bn{{b{Dj}}}}}}{b{{b{c}}}{}}00{{{b{h}}}{{b{hc}}}{}}00{{{b{Fb}}}{{Bn{{b{Df}}}}}}{{{b{Fd}}}{{Bn{{b{Df}}}}}}{{{b{Mh}}}Mh}{{b{b{hc}}}f{}}{{bA`}f}{{}{{Ad{c}}}{}}00{{{b{h}}}{{Ad{{b{hc}}}}}{}}00{b{{Ad{{b{c}}}}}{}}00{An{{b{c}}}{}}00{An{{b{hc}}}{}}00{{{b{Fb}}}{{b{Ef}}}}{{{b{Fd}}}{{b{Ef}}}}{Anf}00{{{b{Mh}}{b{Mh}}}Ah}{{b{b{c}}}Ah{}}00{{{b{Mh}}{b{hBd}}}Bf}0{{{b{Fb}}{b{hBd}}}Bf}0{{{b{Fd}}{b{hBd}}}Bf}0{cc{}}{A`Mh}{DhFb}{AE`Fb}{FfFb}{EnFb}55{AE`Fd}{FfFd}{ACdFd}{EnFd}{cMh{}}{{}}0{{}An}00{{}c{}}00{{{b{Fb}}}{{Bn{{b{Df}}}}}}{{{b{Fd}}}{{Bn{{b{Df}}}}}}{bc{}}{bCh}00{c{{B`{e}}}{}{}}00{{}{{B`{c}}}{}}00{bCj}00{{}c{}}00{AEbBn}{AEdBn}{AEfBn}{AEhBn}{AEjBn}{AElBn}{AEnBn}{AF`Bn}{AFbBn}{AEdMh}{AEfAn}{AF`Mh}2{AEbEn}{AEhFf}{AEjAE`}{AElACd}{AEbJl}{AEdJl}{AEfJl}{AEhJl}{AEjJl}{AElJl}{AEnJl}{AF`Jl}{AFbJl}{AFdBn}{AFfBn}{AFhBn}{AFjBn}{AFdEn}{AFfFf}{AFhDh}{AFjAE`}{AFdJl}{AFfJl}{AFhJl}{AFjJl}````````````````````````````````{{bd}f}000{{{b{AFl}}}{{B`{{b{AFn}}AG`}}}}{{{b{AGb}}}{{b{{C`{A`}}}}}}{{{b{AFl}}}{{B`{{b{AGd}}AG`}}}}{b{{b{Df}}}}0{{{b{AFl}}}{{B`{{b{AGf}}AG`}}}}{{{b{AFl}}}{{B`{{b{AGh}}AG`}}}}{{{b{AFl}}}{{B`{{b{AGj}}AG`}}}}{{{b{AFl}}}{{B`{{b{AGl}}AG`}}}}{{{b{AFl}}}{{B`{{b{AGn}}AG`}}}}{{{b{AFl}}}{{B`{{b{AH`}}AG`}}}}{{{b{AFl}}}{{B`{{b{AHb}}AG`}}}}{{{b{AFl}}}{{B`{{b{AHd}}AG`}}}}{{{b{AGb}}}{{b{{Od{A`}}}}}}{{{b{AFl}}}{{B`{{b{AHf}}AG`}}}}{{{b{AFl}}}{{B`{{b{AHh}}AG`}}}}{{{b{AFl}}}{{B`{{b{AHj}}AG`}}}}{{{b{AFl}}}{{B`{{b{AHl}}AG`}}}}{{{b{AFl}}}{{B`{{b{AHn}}AG`}}}}{{{b{AFl}}}{{B`{{b{AI`}}AG`}}}}{{{b{AFl}}}AIb}{{{b{AId}}}{{Bn{{b{Dj}}}}}}{b{{b{c}}}{}}00000{{{b{h}}}{{b{hc}}}{}}00000{{{b{AId}}}{{Bn{{b{Df}}}}}}{{{b{AIf}}}AIf}{{{b{AIh}}}AIh}{{{b{AGb}}}AGb}{{{b{AFl}}}AFl}{{b{b{hc}}}f{}}000{{bA`}f}000{{{b{AGb}}{b{AGb}}}Ab}{{b{b{c}}}Ab{}}{{}{{Ad{c}}}{}}00000{{{b{h}}}{{Ad{{b{hc}}}}}{}}00000{b{{Ad{{b{c}}}}}{}}00000{{{b{AIf}}{b{{Od{A`}}}}}{{B`{{Ib{AIjAn}}AIl}}}}{{}AIf}{{}AGb}{An{{b{c}}}{}}0{{{b{AGb}}}{{b{{Od{A`}}}}}}1111{An{{b{hc}}}{}}00000{{{b{AId}}}{{b{Ef}}}}{Anf}00000{{{b{AIh}}{b{AIh}}}Ah}{{{b{AGb}}{b{AGb}}}Ah}{{b{b{c}}}Ah{}}00000{{{b{AFl}}}{{b{AFn}}}}{{{b{AFl}}}{{b{AGd}}}}{{{b{AFl}}}{{b{AGf}}}}{{{b{AFl}}}{{b{AGh}}}}{{{b{AFl}}}{{b{AGj}}}}{{{b{AFl}}}{{b{AGl}}}}{{{b{AFl}}}{{b{AGn}}}}{{{b{AFl}}}{{b{AH`}}}}{{{b{AFl}}}{{b{AHb}}}}{{{b{AFl}}}{{b{AHd}}}}{{{b{AFl}}}{{b{AHf}}}}{{{b{AFl}}}{{b{AHh}}}}{{{b{AFl}}}{{b{AHj}}}}{{{b{AFl}}}{{b{AHl}}}}{{{b{AFl}}}{{b{AHn}}}}{{{b{AFl}}}{{b{AI`}}}}{{{b{AIf}}{b{hBd}}}{{B`{fAIn}}}}{{{b{AIh}}{b{hBd}}}{{B`{fAIn}}}}{{{b{AGb}}{b{hBd}}}{{B`{fAIn}}}}0{{{b{AFl}}{b{hBd}}}{{B`{fAIn}}}}{{{b{AIl}}{b{hBd}}}{{B`{fAIn}}}}0{{{b{AId}}{b{hBd}}}Bf}0{cc{}}00{{{b{{C`{A`}}}}}AGb}{{{C`{A`}}}AGb}{AGhAFl}{AGlAFl}{AI`AFl}{AHlAFl}{AHhAFl}7{AFnAFl}{AGdAFl}{AHjAFl}{AGfAFl}{AGjAFl}{AHfAFl}{AHdAFl}{AHbAFl}{AH`AFl}{AGnAFl}{AHnAFl}{cc{}}0{{{b{AIf}}}{{Bn{{b{AJ`}}}}}}{{{b{AGb}}{b{hc}}}fABf}{{}}0{{}An}00000{{}c{}}00000{{{b{{Od{A`}}}}}Ah}{{{b{AFl}}}Ah}000000000000000`{{{b{{Od{A`}}}}}{{B`{AGbAId}}}}{{{b{{Od{A`}}}}}{{B`{{Ib{AGbFj}}AId}}}}{{{b{AGb}}{b{AGb}}}{{Bn{Ab}}}}{AGb{{A@n{A`}}}}{{AGbFj}{{A@n{A`}}}}{{{b{AId}}}{{Bn{{b{Df}}}}}}{bc{}}000{bCh}00{c{{B`{e}}}{}{}}{A`{{B`{AIh}}}}11111{{}{{B`{c}}}{}}00000{bCj}00000{{}c{}}00000{AJbBn}{AJdBn}{AJfBn}{AJhBn}{AJjBn}{AJlBn}{AJbJl}{AJdJl}{AJfJl}{AJhJl}{AJjJl}{AJlJl}{{}AJn}00{{}b}````{{}AK`}1``{b{{b{Df}}}}{{{b{AKb}}}{{Bn{{b{Dj}}}}}}{b{{b{c}}}{}}0{{{b{h}}}{{b{hc}}}{}}0{{{b{AKb}}}{{Bn{{b{Df}}}}}}{{}{{Ad{c}}}{}}0{{{b{h}}}{{Ad{{b{hc}}}}}{}}0{b{{Ad{{b{c}}}}}{}}0{An{{b{c}}}{}}0{An{{b{hc}}}{}}0{{{b{AKb}}}{{b{Ef}}}}{Anf}0{{{b{AKb}}{b{hBd}}}Bf}0{{{b{AKd}}{b{hBd}}}Bf}{AKfAKb}{cc{}}{AKhAKb}{AKjAKb}{AKlAKb}3{{{b{AKd}}Fj{b{Ef}}}{{B`{{Ib{FjAl}}AKb}}}}{{}}{{}An}0{{}c{}}0{{AKnFl}{{B`{AKdAKb}}}}{{{b{AKb}}}{{Bn{{b{Df}}}}}}{bCh}{c{{B`{e}}}{}{}}0{{}{{B`{c}}}{}}0{bCj}0{{}c{}}0{AL`Bn}{ALbBn}{ALdBn}{ALfBn}{AL`AKh}{ALbAKj}{ALdAKf}{ALfAKl}{AL`Jl}{ALbJl}{ALdJl}{ALfJl}````````{{}Al}````````````````````````````{{bd}f}00{ALhBn}0{ALjALl}{ALnAM`}{b{{b{Df}}}}0{b{{b{AMb}}}}0{{{b{AMd}}}{{Bn{{b{Dj}}}}}}{{{b{AMf}}}{{Bn{{b{Dj}}}}}}{AMhALl}{AMjFj}{AMlFj}{b{{b{c}}}{}}0000000000000000{{{b{h}}}{{b{hc}}}{}}0000000000000000{AMnAN`};;{{{b{AMd}}}{{Bn{{b{Df}}}}}}{{{b{AMf}}}{{Bn{{b{Df}}}}}}{ANbANd}{{{b{ANf}}}{{Bn{{A@n{ANh}}}}}}{ALhBn}{{{b{ANj}}}ANj}{{{b{ANl}}}ANl}{{{b{AMn}}}AMn}{{b{b{hc}}}f{}}00{{bA`}f}00{{}{{Ad{c}}}{}}0000000000000000{{{b{h}}}{{Ad{{b{hc}}}}}{}}0000000000000000{b{{Ad{{b{c}}}}}{}}0000000000000000{ALjALl}{{}ALj}{{}AMh}{{}ANj}{{}{{ANn{ce}}}{AO`AOb}{AO`AOb}}{{}ALh}{An{{b{c}}}{}}000{{{b{{AOd{c}}}}}{{b{e}}}Db{}}1111111111111{An{{b{hc}}}{}}0000000000000000{{{b{AMd}}}{{b{Ef}}}}{{{b{AMf}}}{{b{Ef}}}}::::{Anf}0000000000000000{{{b{ANl}}{b{ANl}}}Ah}{{b{b{c}}}Ah{}}00{AMhALl}{{{b{ALj}}}An}{{{b{AMh}}}An}{{{b{ALj}}An}{{Bn{AOf}}}}{{{b{AMh}}An}{{Bn{AOf}}}}{{{b{ALj}}{b{hBd}}}Bf}{{{b{AMh}}{b{hBd}}}Bf}{{{b{ANj}}{b{hBd}}}Bf}{{{b{{AOd{c}}}}{b{hBd}}}Bf{AObDb}}{{{b{{ANn{ce}}}}{b{hBd}}}BfAObAOb}{{{b{{ALn{ce}}}}{b{hBd}}}BfAObAOb}{{{b{AM`}}{b{hBd}}}Bf}{{{b{ANl}}{b{hBd}}}Bf}{{{b{AMj}}{b{hBd}}}Bf}{{{b{AMl}}{b{hBd}}}Bf}{{{b{{ANb{ce}}}}{b{hBd}}}BfAObAOb}{{{b{ALh}}{b{hBd}}}Bf}{{{b{AMn}}{b{hBd}}}Bf}{{{b{{ANd{ce}}}}{b{hBd}}}BfAObAOb}{{{b{ANf}}{b{hBd}}}Bf}{{{b{AMd}}{b{hBd}}}Bf}0{{{b{AMf}}{b{hBd}}}Bf}0{ALjALl}{cc{}}000000000000000{AOhAMf}12{{{b{ANj}}}{{`{{Cb{}{{Bh{{b{AOj}}}}}}}}}}{{{b{ANj}}}{{`{{Cb{}{{Bh{{Bl{AOj}}}}}}}}}}{{{b{ANf}}}{{Bn{Fj}}}}{ALnFj}{{{b{ANf}}}{{Bn{Af}}}}2{ANbFj}1{{}}0{{}An}000{{cAl}{{B`{{AOd{c}}}}}{Db{B@`{}{{AOl{AOn}}}}}}1111111111111{{}c{}}0000000000000000{AMhALl}0{{{b{AM`}}Lj}Ah}{ALnBn}{ALnALh}{AMnBn}{{{b{ANf}}}{{b{ANj}}}}{ANnBn}{{{b{ALj}}}{{b{Ef}}}}{{{b{AMh}}}{{b{Ef}}}}{{{b{ANj}}}{{b{Ef}}}}{ALjALl}004{{{b{ANf}}}{{Bn{Fj}}}}{ANbFj}62{{{b{{AOd{c}}}}}f{Db{B@`{}{{AOl{AOn}}}}}}={{{b{{AOd{c}}}}B@b}{{Bn{{Bl{AOn}}}}}{{B@`{}{{AOl{AOn}}}}DbAOb}}4444{ANjBl}{AMlB@d}{ANbB@d}{{{AOd{c}}}f{Db{B@`{}{{AOl{AOn}}}}}}{ANf{{B`{fAMf}}}}{{{b{AMd}}}{{Bn{{b{Df}}}}}}{{{b{AMf}}}{{Bn{{b{Df}}}}}}{{{ANn{ce}}}{{B`{ANfAMd}}}AObAOb}7{ANnBn}<{{{b{hANf}}}{{b{h{B@f{{B`{fAMf}}}}}}}}`{ALnBn}{bc{}}00{bCh}0{c{{B`{e}}}{}{}}0000000000000000{{}{{B`{c}}}{}}0000000000000000{bCj}0000000000000000{ALjALl}0{{}c{}}00000000000000001{B@hA@n}{B@jB@l}{B@nFj}{BA`Bn}{BAbBn}{BAdBn}{BAfBn}{BAhBn}{BAjBn}{B@nBn}{BA`En}{BAbEn}`{BAfBAl}{BAhEn}{BAjEn}{BA`Jl}{BAbJl}{BAdJl}{BAfJl}{BAhJl}{BAjJl}{B@nJl}{BAnBn}{BB`Bn}{BBbBn}{BBdBn}{BBfBn}{BAnEn}{BBbAOh}{BAnJl}{BB`Jl}{BBbJl}{BBdJl}{BBfJl}{{}AMl}{{}{{ALn{f}}}}{{}{{Ib{{A@n{ANh}}B@d}}}}{{}{{ANn{f}}}}{{}AMj}{{}{{ANb{f}}}}","D":"CJh","p":[[1,"reference",null,null,1],[5,"Private",1998],[1,"unit"],[0,"mut"],[5,"RelayMap",0,1999],[5,"RelayNode",0,1999],[5,"RelayQuicConfig",0,1999],[1,"u8"],[6,"Ordering",2000],[5,"Compat",2001],[5,"RelayUrl",2002],[1,"bool"],[5,"PingTracker",0,2003],[5,"Duration",2004],[1,"usize"],[6,"Result",2005,null,1],[10,"Deserializer",2006],[5,"Formatter",2007],[8,"Result",2007],[17,"Item"],[10,"IntoIterator",2008],[5,"Arc",2009,null,1],[6,"Option",2010,null,1],[1,"array"],[10,"Iterator",2011],[1,"u16"],[10,"Serializer",2012],[5,"String",2013],[5,"TypeId",2014],[5,"ClientBuilder",142],[17,"Output"],[10,"Fn",2015],[10,"Send",2016],[10,"Sync",2016],[10,"Error",2017],[6,"SendError",142,2018],[5,"Backtrace",2019],[6,"RecvError",142,2018],[6,"ConnectError",142],[6,"DialError",142],[6,"ReceivedMessage",142,2018],[5,"Client",142],[1,"str"],[6,"SendMessage",142,2018],[5,"ClientSink",142],[5,"ClientStream",142],[5,"Error",2020],[6,"Error",2021],[6,"SendError",1041],[6,"RecvError",1041],[5,"Elapsed",2022],[6,"DnsError",530],[6,"SocketAddr",2023],[5,"ClientConfig",2024],[5,"SecretKey",2025],[5,"DnsResolver",530],[10,"Into",2026,null,1],[5,"Pin",2027],[5,"Context",2028],[6,"Poll",2029],[6,"Protocol",699],[5,"Url",2030],[6,"NotKeyed",2031],[5,"RateLimiter",2032],[5,"RatelimitedSink",2033],[10,"DirectStateStore",2031],[10,"ReasonablyRealtime",2034],[17,"NegativeOutcome"],[5,"NotUntil",2035],[10,"RateLimitingMiddleware",2036],[5,"Jitter",2037],[5,"RatelimitedStream",2038],[1,"tuple",null,null,1],[15,"InvalidWebsocketUrl",436],[15,"InvalidRelayUrl",436],[15,"Websocket",436],[15,"Handshake",436],[15,"Dial",436],[15,"UnexpectedUpgradeStatus",436],[15,"Upgrade",436],[15,"InvalidTlsServername",436],[15,"NoLocalAddr",436],[15,"Tls",436],[5,"StatusCode",2039],[5,"Error",2040],[5,"SpanTrace",2041],[15,"InvalidTargetPort",464],[15,"Dns",464],[15,"Timeout",464],[15,"Io",464],[15,"InvalidUrl",464],[15,"ProxyConnectInvalidStatus",464],[15,"ProxyInvalidUrl",464],[15,"ProxyConnect",464],[15,"ProxyInvalidTlsServername",464],[15,"ProxyInvalidTargetPort",464],[15,"ReceivedPacket",492],[5,"Bytes",2042],[15,"Health",492],[15,"ServerRestarting",492],[8,"NodeId",2025],[15,"Io",497],[15,"ProtocolSend",497],[15,"ProtocolRecv",497],[15,"Websocket",497],[15,"InvalidProtocolMessageEncoding",497],[15,"UnexpectedFrame",497],[6,"FrameType",1041],[5,"Utf8Error",2043],[15,"RelayIo",515],[15,"WebsocketIo",515],[15,"ExceedsMaxPacketSize",515],[5,"Error",530,2044],[5,"TxtLookup",530],[5,"TXT",530],[5,"ResolveError",2045],[8,"TokioResolver",2046],[5,"TxtLookup",2047],[6,"IpAddr",2048],[10,"ToString",2013],[1,"u64"],[1,"slice"],[5,"NodeInfo",732],[6,"LookupError",732],[5,"Name",2049],[8,"Resolving",2049],[5,"Box",2050,null,1],[15,"Timeout",680],[15,"NoResponse",680],[15,"ResolveBoth",680],[15,"MissingHost",680],[15,"Resolve",680],[15,"InvalidResponse",680],[15,"Staggered",680],[5,"Vec",2051],[5,"HeaderValue",2052],[5,"NodeData",732],[5,"UserData",732],[6,"EncodingError",732],[6,"DecodingError",732],[5,"MaxLengthExceededError",732],[6,"ParseError",732],[5,"BTreeSet",2053],[6,"SignedPacketBuildError",2054],[5,"NodeAddr",2055],[5,"SignedPacket",2054],[10,"Hasher",2056],[1,"u32"],[10,"NodeIdExt",732],[15,"InvalidEncodingZ32",994],[15,"InvalidLength",994],[15,"InvalidSignature",994],[6,"Z32Error",2057],[8,"SignatureError",2058],[15,"FailedBuildingPacket",1003],[15,"InvalidTxtEntry",1003],[6,"SimpleDnsError",2059],[15,"ParseError",1009],[15,"LookupFailed",1009],[15,"InvalidLabel",1009],[5,"ProtoError",2060],[15,"UnexpectedFormat",1018],[15,"AttrFromString",1018],[15,"NumLabels",1018],[15,"Utf8",1018],[15,"NotAnIrohRecord",1018],[15,"DecodingError",1018],[6,"Error",2061],[15,"Io",1154],[15,"UnexpectedFrame",1154],[15,"FrameTooLarge",1154],[15,"Timeout",1154],[15,"SerDe",1154],[15,"InvalidSignature",1154],[15,"InvalidFrame",1154],[15,"InvalidFrameType",1154],[15,"TooSmall",1154],[15,"Io",1180],[15,"Timeout",1180],[15,"ConnSend",1180],[15,"SerDe",1180],[6,"StunAttribute",1192,2062],[5,"AlternateServer",2063],[5,"StunError",2064],[5,"TransactionId",1192,2065],[5,"ErrorCode",2066],[6,"Fingerprint",2067],[5,"MappedAddress",2068],[6,"MessageIntegrity",2069],[6,"MessageIntegritySha256",2070],[5,"Nonce",2071],[5,"PasswordAlgorithm",2072],[5,"PasswordAlgorithms",2073],[5,"Realm",2074],[5,"Software",2075],[5,"Unknown",2076],[5,"UnknownAttributes",2077],[5,"UserHash",2078],[5,"UserName",2079],[5,"XorMappedAddress",2080],[5,"AttributeType",2062],[6,"StunError",1192],[5,"MessageDecoder",1192,2081],[6,"MessageClass",1192,2082],[5,"StunMessage",2082],[5,"StunDecodeError",1192,2064],[5,"Error",2007],[5,"DecoderContext",2081],[15,"InvalidMessage",1447],[15,"NotBinding",1447],[15,"NotSuccessResponse",1447],[15,"MalformedAttrs",1447],[15,"NoFingerprint",1447],[15,"InvalidFingerprint",1447],[5,"MessageMethod",2082],[5,"VarInt",2083],[6,"Error",1462],[5,"QuicClient",1462],[5,"RecvError",2084],[6,"ConnectError",2085],[6,"ConnectionError",2086],[5,"NoInitialCipherSuite",2087],[5,"Endpoint",2088],[15,"Connect",1517],[15,"Connection",1517],[15,"WatchRecv",1517],[15,"NoIntitialCipherSuite",1517],[5,"Limits",1529],[5,"Metrics",1529,2089],[5,"Counter",2090],[5,"RelayConfig",1529],[6,"AccessConfig",1529],[10,"Iterable",2091],[6,"SpawnError",1529],[6,"SupervisorError",1529],[5,"StunMetrics",1529,2089],[5,"StunConfig",1529],[5,"QuicConfig",1529],[5,"ClientRateLimit",1529],[8,"NonZeroU32",2092],[5,"TlsConfig",1529],[6,"CertConfig",1529],[5,"Server",1529],[5,"CertificateDer",2093],[5,"RelayMetrics",1529,2089],[6,"Access",1529],[5,"ServerConfig",1529],[10,"Default",2094],[10,"Debug",2007],[5,"ReloadingResolver",1529,2095],[5,"MetricItem",2096],[5,"JoinError",2097],[10,"MetricsGroup",2096],[17,"Value"],[5,"CertifiedKey",2098],[10,"Loader",2099],[5,"ClientHello",2100],[5,"ServerConfig",2100],[5,"AbortOnDropHandle",2101],[15,"Manual",1957],[15,"LetsEncrypt",1957],[5,"AcmeState",2102],[15,"BindTcpListener",1959],[15,"LocalAddr",1959],[15,"UdpSocketBind",1959],[15,"QuicSpawn",1959],[15,"TlsHeaderParse",1959],[15,"BindTlsListener",1959],[15,"NoLocalAddr",1959],[5,"InvalidHeaderValue",2052],[15,"Metrics",1980],[15,"AcmeEventStreamFinished",1980],[15,"JoinError",1980],[15,"NoRelayServicesEnabled",1980],[15,"TaskCancelled",1980]],"r":[[0,1041],[1,2003],[2,1999],[3,1999],[4,1999],[5,1999],[6,1999],[7,1999],[8,2003],[9,1999],[10,1999],[11,1999],[12,2003],[13,1999],[14,1999],[15,1999],[17,1999],[18,1999],[19,1999],[20,1999],[21,1999],[22,1999],[23,1999],[24,1999],[25,1999],[26,1999],[27,1999],[28,1999],[29,1999],[30,2003],[31,1999],[32,1999],[33,1999],[34,2003],[35,1999],[36,1999],[37,1999],[38,2003],[39,1999],[40,1999],[41,1999],[42,1999],[43,2003],[44,1999],[45,2003],[47,2003],[48,1999],[49,1999],[50,1999],[51,2003],[52,1999],[53,1999],[54,1999],[55,1999],[56,1999],[58,2003],[59,1999],[60,1999],[61,1999],[62,1999],[63,1999],[64,1999],[65,1999],[66,1999],[67,1999],[68,1999],[69,1999],[70,1999],[71,1999],[72,1999],[73,1999],[74,1999],[75,2003],[76,1999],[77,1999],[78,1999],[79,1999],[80,1999],[81,2003],[82,1999],[83,1999],[84,1999],[85,1999],[86,1999],[87,1999],[88,1999],[89,1999],[90,1999],[92,2003],[93,1999],[94,1999],[95,1999],[96,2003],[97,1999],[98,1999],[99,1999],[100,1999],[101,1999],[102,2003],[103,2003],[105,1999],[106,1999],[107,1999],[108,2003],[109,1999],[112,1999],[113,1999],[114,1999],[116,1999],[117,1999],[118,2003],[119,1999],[120,1999],[121,1999],[122,1999],[123,1999],[124,2003],[125,1999],[126,1999],[127,1999],[128,2003],[129,1999],[130,1999],[131,1999],[132,2003],[133,1999],[134,1999],[135,1999],[136,1999],[137,1999],[138,2003],[139,1999],[140,1999],[141,1999],[150,2018],[152,2018],[153,2018],[159,2018],[161,2018],[163,2018],[164,2018],[165,2018],[166,2018],[167,2018],[168,2018],[169,2018],[175,2018],[176,2018],[177,2018],[178,2018],[179,2018],[180,2018],[181,2018],[182,2018],[185,2018],[188,2018],[190,2018],[191,2018],[194,2018],[195,2018],[198,2018],[199,2018],[202,2018],[203,2018],[204,2018],[205,2018],[212,2018],[213,2018],[214,2018],[215,2018],[222,2018],[223,2018],[226,2018],[228,2018],[230,2018],[232,2018],[233,2018],[234,2018],[235,2018],[242,2018],[243,2018],[244,2018],[245,2018],[252,2018],[253,2018],[254,2018],[255,2018],[263,2018],[264,2018],[265,2018],[266,2018],[273,2018],[274,2018],[275,2018],[276,2018],[283,2018],[284,2018],[287,2018],[288,2018],[289,2018],[290,2018],[297,2018],[298,2018],[299,2018],[300,2018],[301,2018],[302,2018],[311,2018],[312,2018],[313,2018],[314,2018],[315,2018],[316,2018],[317,2018],[318,2018],[319,2018],[320,2018],[333,2018],[334,2018],[337,2018],[338,2018],[339,2018],[340,2018],[348,2018],[349,2018],[350,2018],[351,2018],[381,2018],[382,2018],[388,2018],[390,2018],[391,2018],[394,2018],[395,2018],[396,2018],[397,2018],[404,2018],[405,2018],[406,2018],[407,2018],[416,2018],[417,2018],[418,2018],[419,2018],[426,2018],[427,2018],[428,2018],[429,2018],[532,2044],[548,2044],[550,2044],[552,2044],[557,2044],[562,2044],[574,2044],[579,2044],[584,2044],[590,2044],[595,2044],[600,2044],[602,2044],[608,2044],[609,2044],[617,2044],[624,2044],[626,2044],[631,2044],[651,2044],[656,2044],[659,2044],[664,2044],[670,2044],[675,2044],[1192,2062],[1193,2062],[1194,2082],[1195,2062],[1196,2082],[1200,2062],[1201,2082],[1202,2081],[1203,2062],[1204,2062],[1206,2062],[1209,2062],[1210,2062],[1211,2062],[1212,2082],[1213,2062],[1214,2062],[1215,2064],[1217,2082],[1218,2065],[1219,2062],[1220,2062],[1221,2062],[1222,2062],[1223,2062],[1224,2081],[1225,2082],[1226,2065],[1227,2062],[1228,2062],[1229,2065],[1230,2062],[1231,2064],[1233,2062],[1234,2062],[1235,2062],[1236,2062],[1237,2062],[1238,2062],[1239,2062],[1240,2062],[1241,2065],[1242,2062],[1243,2062],[1244,2062],[1245,2062],[1246,2062],[1247,2062],[1248,2062],[1250,2081],[1251,2082],[1252,2065],[1253,2062],[1254,2064],[1256,2081],[1257,2082],[1258,2065],[1259,2062],[1260,2064],[1263,2081],[1264,2082],[1265,2065],[1266,2062],[1267,2081],[1268,2082],[1269,2065],[1270,2062],[1271,2081],[1272,2082],[1273,2065],[1274,2062],[1275,2065],[1276,2065],[1277,2081],[1278,2082],[1279,2065],[1280,2062],[1281,2064],[1283,2081],[1284,2082],[1285,2065],[1286,2062],[1287,2064],[1289,2081],[1290,2082],[1291,2065],[1292,2062],[1293,2064],[1295,2081],[1296,2081],[1297,2065],[1298,2081],[1299,2082],[1300,2065],[1301,2065],[1302,2062],[1303,2064],[1305,2081],[1306,2082],[1307,2065],[1308,2062],[1309,2064],[1312,2081],[1313,2082],[1314,2065],[1315,2062],[1316,2064],[1318,2082],[1319,2065],[1320,2082],[1321,2082],[1322,2082],[1323,2065],[1324,2065],[1325,2065],[1326,2062],[1327,2062],[1328,2062],[1329,2062],[1330,2062],[1331,2062],[1332,2062],[1333,2062],[1334,2062],[1335,2062],[1336,2062],[1337,2062],[1338,2062],[1339,2062],[1340,2062],[1341,2062],[1342,2081],[1343,2082],[1344,2065],[1345,2065],[1346,2062],[1347,2064],[1348,2064],[1351,2081],[1352,2082],[1353,2065],[1354,2065],[1355,2065],[1356,2062],[1357,2062],[1358,2062],[1359,2062],[1360,2062],[1361,2062],[1362,2062],[1363,2062],[1364,2062],[1365,2062],[1366,2062],[1367,2062],[1368,2062],[1369,2062],[1370,2062],[1371,2062],[1372,2062],[1373,2064],[1375,2081],[1376,2065],[1377,2064],[1379,2081],[1380,2082],[1381,2065],[1382,2062],[1383,2064],[1385,2081],[1386,2082],[1387,2065],[1388,2062],[1389,2064],[1392,2062],[1393,2062],[1394,2062],[1395,2062],[1396,2062],[1397,2062],[1398,2062],[1399,2062],[1400,2062],[1401,2062],[1402,2062],[1403,2062],[1404,2062],[1405,2062],[1406,2062],[1407,2062],[1408,2103],[1411,2065],[1415,2081],[1416,2082],[1417,2065],[1418,2062],[1419,2065],[1420,2064],[1422,2081],[1423,2082],[1424,2082],[1425,2065],[1426,2062],[1427,2064],[1429,2081],[1430,2082],[1431,2065],[1432,2062],[1433,2064],[1435,2081],[1436,2082],[1437,2065],[1438,2062],[1439,2064],[1441,2081],[1442,2082],[1443,2065],[1444,2062],[1445,2064],[1459,2104],[1460,2104],[1461,2104],[1537,2095],[1545,2089],[1552,2089],[1554,2095],[1560,2089],[1566,2089],[1571,2089],[1575,2089],[1576,2089],[1579,2089],[1582,2089],[1583,2089],[1584,2089],[1585,2095],[1599,2089],[1600,2089],[1601,2089],[1602,2095],[1617,2089],[1618,2089],[1624,2089],[1627,2089],[1630,2089],[1633,2089],[1634,2089],[1635,2089],[1636,2095],[1650,2089],[1651,2089],[1652,2089],[1653,2095],[1667,2089],[1668,2089],[1669,2089],[1670,2095],[1684,2089],[1685,2089],[1686,2089],[1687,2089],[1690,2089],[1691,2089],[1692,2089],[1693,2095],[1694,2095],[1708,2089],[1709,2089],[1710,2089],[1711,2095],[1727,2089],[1728,2089],[1729,2089],[1730,2089],[1731,2089],[1732,2089],[1733,2089],[1734,2095],[1752,2089],[1753,2089],[1754,2089],[1755,2089],[1756,2089],[1757,2089],[1758,2089],[1759,2089],[1760,2095],[1776,2089],[1777,2089],[1778,2089],[1779,2089],[1780,2095],[1795,2089],[1796,2089],[1797,2089],[1806,2089],[1807,2089],[1808,2089],[1809,2095],[1810,2095],[1824,2089],[1825,2089],[1826,2089],[1827,2095],[1841,2089],[1842,2089],[1849,2089],[1850,2089],[1851,2089],[1852,2089],[1853,2089],[1854,2089],[1859,2089],[1860,2095],[1861,2089],[1862,2095],[1863,2089],[1864,2089],[1865,2089],[1866,2089],[1867,2089],[1870,2095],[1875,2089],[1881,2089],[1886,2089],[1887,2089],[1888,2089],[1889,2095],[1903,2089],[1904,2089],[1905,2089],[1906,2095],[1920,2089],[1921,2089],[1922,2089],[1923,2095],[1937,2089],[1938,2089],[1939,2089],[1940,2089],[1941,2089],[1942,2095],[1956,2089]],"b":[[76,"impl-Display-for-RelayMap"],[77,"impl-Debug-for-RelayMap"],[78,"impl-Debug-for-RelayNode"],[79,"impl-Display-for-RelayNode"],[82,"impl-From%3CRelayNode%3E-for-RelayMap"],[84,"impl-From%3CRelayUrl%3E-for-RelayMap"],[88,"impl-FromIterator%3CRelayNode%3E-for-RelayMap"],[89,"impl-FromIterator%3CRelayUrl%3E-for-RelayMap"],[297,"impl-Debug-for-SendError"],[298,"impl-Display-for-SendError"],[299,"impl-Display-for-RecvError"],[300,"impl-Debug-for-RecvError"],[303,"impl-Debug-for-ConnectError"],[304,"impl-Display-for-ConnectError"],[305,"impl-Debug-for-DialError"],[306,"impl-Display-for-DialError"],[311,"impl-From%3CError%3E-for-SendError"],[312,"impl-From%3CError%3E-for-SendError"],[314,"impl-From%3CError%3E-for-RecvError"],[315,"impl-From%3CError%3E-for-RecvError"],[317,"impl-From%3CSendError%3E-for-RecvError"],[318,"impl-From%3CRecvError%3E-for-RecvError"],[321,"impl-From%3CSendError%3E-for-ConnectError"],[322,"impl-From%3CError%3E-for-ConnectError"],[324,"impl-From%3CDialError%3E-for-ConnectError"],[325,"impl-From%3CError%3E-for-DialError"],[327,"impl-From%3CElapsed%3E-for-DialError"],[328,"impl-From%3CDnsError%3E-for-DialError"],[606,"impl-Display-for-DnsError"],[607,"impl-Debug-for-DnsError"],[608,"impl-Debug-for-Error"],[609,"impl-Display-for-Error"],[612,"impl-Display-for-TXT"],[613,"impl-Debug-for-TXT"],[615,"impl-From%3CResolveError%3E-for-DnsError"],[616,"impl-From%3CElapsed%3E-for-DnsError"],[875,"impl-Debug-for-EncodingError"],[876,"impl-Display-for-EncodingError"],[877,"impl-Debug-for-DecodingError"],[878,"impl-Display-for-DecodingError"],[880,"impl-Display-for-UserData"],[881,"impl-Debug-for-UserData"],[882,"impl-Display-for-MaxLengthExceededError"],[883,"impl-Debug-for-MaxLengthExceededError"],[885,"impl-Display-for-LookupError"],[886,"impl-Debug-for-LookupError"],[887,"impl-Debug-for-ParseError"],[888,"impl-Display-for-ParseError"],[1109,"impl-Display-for-FrameType"],[1110,"impl-Debug-for-FrameType"],[1111,"impl-Debug-for-SendError"],[1112,"impl-Display-for-SendError"],[1113,"impl-Display-for-RecvError"],[1114,"impl-Debug-for-RecvError"],[1117,"impl-From%3CSendError%3E-for-SendError"],[1118,"impl-From%3CError%3E-for-SendError"],[1119,"impl-From%3CElapsed%3E-for-SendError"],[1120,"impl-From%3CError%3E-for-SendError"],[1123,"impl-From%3CError%3E-for-RecvError"],[1124,"impl-From%3CElapsed%3E-for-RecvError"],[1125,"impl-From%3CError%3E-for-RecvError"],[1126,"impl-From%3CError%3E-for-RecvError"],[1344,"impl-Display-for-TransactionId"],[1345,"impl-Debug-for-TransactionId"],[1347,"impl-Display-for-StunDecodeError"],[1348,"impl-Debug-for-StunDecodeError"],[1349,"impl-Display-for-StunError"],[1350,"impl-Debug-for-StunError"],[1354,"impl-From%3C%26%5Bu8;+stun_rs::::types::%7Bimpl%2313%7D::%7Bconstant%230%7D%5D%3E-for-TransactionId"],[1355,"impl-From%3C%5Bu8;+stun_rs::::types::%7Bimpl%2314%7D::%7Bconstant%230%7D%5D%3E-for-TransactionId"],[1356,"impl-From%3CMappedAddress%3E-for-StunAttribute"],[1357,"impl-From%3CMessageIntegritySha256%3E-for-StunAttribute"],[1358,"impl-From%3CXorMappedAddress%3E-for-StunAttribute"],[1359,"impl-From%3CUserHash%3E-for-StunAttribute"],[1360,"impl-From%3CUnknown%3E-for-StunAttribute"],[1362,"impl-From%3CAlternateServer%3E-for-StunAttribute"],[1363,"impl-From%3CErrorCode%3E-for-StunAttribute"],[1364,"impl-From%3CUnknownAttributes%3E-for-StunAttribute"],[1365,"impl-From%3CFingerprint%3E-for-StunAttribute"],[1366,"impl-From%3CMessageIntegrity%3E-for-StunAttribute"],[1367,"impl-From%3CSoftware%3E-for-StunAttribute"],[1368,"impl-From%3CRealm%3E-for-StunAttribute"],[1369,"impl-From%3CPasswordAlgorithms%3E-for-StunAttribute"],[1370,"impl-From%3CPasswordAlgorithm%3E-for-StunAttribute"],[1371,"impl-From%3CNonce%3E-for-StunAttribute"],[1372,"impl-From%3CUserName%3E-for-StunAttribute"],[1491,"impl-Display-for-Error"],[1492,"impl-Debug-for-Error"],[1494,"impl-From%3CRecvError%3E-for-Error"],[1496,"impl-From%3CConnectError%3E-for-Error"],[1497,"impl-From%3CConnectionError%3E-for-Error"],[1498,"impl-From%3CNoInitialCipherSuite%3E-for-Error"],[1772,"impl-Display-for-SpawnError"],[1773,"impl-Debug-for-SpawnError"],[1774,"impl-Debug-for-SupervisorError"],[1775,"impl-Display-for-SupervisorError"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAPoFegABAAAABgAKABIAGAAsAAEAMAAJADsAAwBAABEAUwAAAFcAAABZAAAAXQADAGsAAQByAAEAeAAQAIsAAwCUAAAAlgACAJoABwCjAAAAqQAGALMAAAC4AAkAwwBDAAgBMQA7AQEAPgEBAEIBAQBFAQEASAEBAE4BDQBsAQcAdgELAIMBaQDyARoAFgIBABoCAwAfAgAAIQISADUCMQBoAgEAawIAAG4CAABwAgYAfAIAAIkCAACLAhEAngIJAKkCEgDBAhEA1AIAANcCAwDcAgUA4wIGAO8CBAD1AgMA+gIfABsDIgA/AxcAWAMhAHsDAAB9AwAAgQMAAIUDAACIAwAAiwMNAKUDAACpAwQArwMCALMDBQC7AxgA1QMHAOMDKQATBAEAFwQEACcEBQAuBC0AXQQEAGQECQBxBDcAyQQDANAEAQDaBAAA4gQtABEFAAATBRsAPwUIAEsFBgBTBQoAYQUIAIQFAACHBSwAuAUBALsFAAC/BRgA2QUCAN4FAgDkBRUA/AUAAP4FAQAFBgAACAYAAAsGAgAPBgAAGwYAAB0GBAAmBgUALwYhAFQGAQBZBjsAlgYpAMQGFADaBhYAAgcAAAUHAQANBwUAFAcMADoHAgBHBwAAUQcBAFoHNwCUBxAAqAcgAA==","P":[[8,"T"],[17,""],[20,"T"],[23,""],[28,"K"],[30,"T"],[42,""],[47,"T"],[55,"__D"],[58,""],[66,"K"],[75,""],[81,"T"],[82,""],[83,"T"],[84,""],[85,"T"],[86,""],[87,"T"],[90,""],[96,"U"],[100,""],[113,"__S"],[116,""],[119,"T"],[122,""],[124,"U,T"],[128,"U"],[132,""],[138,"V"],[191,""],[193,"S"],[194,""],[202,"T"],[222,""],[228,"T"],[230,""],[232,"T"],[262,""],[263,"T"],[283,""],[313,"T"],[314,""],[316,"T"],[317,""],[319,"T"],[321,""],[323,"T"],[324,""],[326,"T"],[327,""],[329,"T"],[333,""],[348,"U"],[358,""],[362,""],[363,"Sink::Error"],[367,"Stream::Item"],[369,"Sink::Error"],[371,""],[373,"D,C,MW,Item,S"],[377,"D,C,MW,S"],[381,""],[386,"Sink::Error"],[388,"T"],[390,""],[394,"U,T"],[404,"U"],[414,"S"],[416,""],[426,"V"],[436,""],[551,"T"],[561,""],[567,"T"],[570,""],[573,"T"],[588,""],[589,"T"],[599,""],[614,"T"],[615,""],[617,"T"],[618,""],[619,"T"],[621,""],[622,"T"],[623,""],[630,"U"],[635,"IntoIterator::IntoIter"],[636,""],[642,""],[646,""],[647,""],[652,"T"],[655,""],[658,"U,T"],[663,"U"],[668,""],[674,"V"],[679,""],[705,"T"],[707,""],[708,"T"],[709,""],[710,"T"],[713,""],[714,"T"],[716,""],[718,"K"],[721,""],[722,"T"],[723,""],[724,"U"],[725,""],[726,"T"],[727,"U,T"],[728,"U"],[729,""],[731,"V"],[737,""],[760,""],[761,""],[772,"T"],[788,""],[797,"T"],[800,""],[804,"K"],[805,"T"],[829,""],[831,"T"],[836,"Deref::Target"],[837,"T"],[845,"Deref::Target"],[846,"T"],[849,""],[866,"K"],[875,""],[889,"T"],[890,""],[891,"T"],[892,""],[893,"T"],[896,""],[897,"T"],[900,""],[903,"FromStr::Err"],[904,""],[906,"__H"],[907,""],[920,"U"],[928,""],[942,"T"],[945,""],[954,"U,T"],[957,"TryFrom::Error"],[958,"U,T"],[963,"U"],[971,""],[980,"V"],[988,""],[1074,"T"],[1080,""],[1083,"T"],[1084,""],[1085,"T"],[1100,""],[1106,"K"],[1109,""],[1115,"T"],[1116,""],[1121,"T"],[1123,""],[1127,"FromPrimitive::Primitive"],[1128,""],[1133,"U"],[1136,""],[1138,"T"],[1139,""],[1142,"U,T"],[1145,"U"],[1148,""],[1151,"V"],[1154,""],[1250,"T"],[1262,""],[1267,"T"],[1271,""],[1276,"K"],[1277,"T"],[1295,""],[1298,"T"],[1300,""],[1301,"T"],[1311,""],[1320,"K"],[1326,""],[1351,"T"],[1354,""],[1361,"T"],[1362,""],[1373,"T"],[1375,""],[1376,"__H"],[1377,""],[1385,"U"],[1391,""],[1415,"T"],[1419,""],[1422,"U,T"],[1423,""],[1424,"U,T"],[1429,"U"],[1435,""],[1441,"V"],[1447,""],[1473,"T"],[1477,""],[1478,"T"],[1488,""],[1495,"T"],[1496,""],[1499,"T"],[1500,""],[1504,"U"],[1506,""],[1509,"U,T"],[1511,"U"],[1513,""],[1515,"V"],[1517,""],[1582,"T"],[1616,""],[1627,"T"],[1630,""],[1633,"T"],[1684,""],[1688,"EC,EA"],[1689,""],[1690,"T"],[1694,"Loader,Deref::Target"],[1695,"T"],[1725,""],[1749,"K"],[1752,""],[1760,"Loader"],[1761,"EC,EA"],[1763,""],[1767,"EC,EA"],[1768,""],[1770,"EC,EA"],[1771,""],[1777,"T"],[1793,""],[1794,"T"],[1795,""],[1810,"Loader"],[1811,""],[1824,"U"],[1841,""],[1860,"Loader"],[1861,""],[1862,"Loader"],[1863,""],[1870,"Loader"],[1871,""],[1874,"EC,EA"],[1875,""],[1881,"T"],[1884,""],[1886,"U,T"],[1903,"U"],[1920,""],[1939,"V"],[1956,""]]}]]')); +var searchIndex = new Map(JSON.parse('[["bulk",{"t":"HHHHH","n":["collect_and_print","main","run_iroh","run_quinn","run_s2n"],"q":[[0,"bulk"],[5,"iroh_metrics::base"],[6,"iroh_bench"],[7,"n0_snafu::error"],[8,"iroh_bench::s2n"]],"i":"`````","f":"{{{d{b}}{d{f}}}h}{{}h}{j{{l{h}}}}0{n{{l{h}}}}","D":"`","p":[[1,"str"],[1,"reference",null,null,1],[10,"MetricsGroup",5],[1,"unit"],[5,"Opt",6],[8,"Result",7],[5,"Opt",8]],"r":[],"b":[],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAAUAAQAAAAUA","P":[]}],["iroh",{"t":"PPEPGTFIFPFEFGFFFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNOCCNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCCNOCNNNNNNCNNONONNNNNNNNNOOCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNOOOOOOOOSSSSSCCSSSHHHHSSHHHPFPKFGFKGFTPPFFPPGPPPFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNCNNNNNONNCNNNNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOFFSSNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFFSNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNSSPPPPPSSGFFFFFPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOFFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNTFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFSSNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNTTFFFFPGKPGPFPGFTTTPFPFPPPGFGFFPFPGPPPPPPFGGKKFKPPPFFGPPPPPPSPPFFTTTPFGKTTPFFTPPTTPPFTTPPPPFFPTGFPPPPPFGPGGFPPGPFFPPGFTTPPGFFGPPGFPPTPPPFFPFPFPPPPFFPFGFFPPPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONONNNOOOMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNOOONNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNONNONOONOOOONNNONNNNNNNNNNNNNNNNNHNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNHOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNONNNNNNOOONOOONOOONNNONNNOOONNNNNNNNNNOONNOOONMNMNMNNNNNNNOOONNNONNNNNNNNNNNNNNNNNNNNNNNNNNOOONNNNNNNONNNNNNNOONMNNONMNNNNNNOONNNNNNNNNNNNNNNNNNNNNNNNNNNONMNNONOONOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOONNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOFFEFFNOOOOOOOOONNNNNNNNNNNOONNNNNNNNNNNNNNNOOONNNNNNNNNNNNNNNOOOONNNNONNNNNNNNNNONNNNNONNNNNNNNNNOOOONNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOONNNNNNNNNNNNNNNNOOOOOOONNNNOPPFPFFFFFFGNNNNNNNNNHNNNNNNNNNNNNNNNNONONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOONNNOONNNNNNNNNNNNNNNNNNOOOOOONOONNOOONNOOOOONNOOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNOOOOOOOPGPGPSPPPPPGPFFKFPPGPPFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNONNNNNNNNMNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOGFPPPKFFPNNMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOFFNNNNNNNNNNNNNNNNNNNNNNNNNNOONONHHHNNNNNNNNN","n":["Decode","DecodeInvalidLength","Endpoint","Key","KeyParsingError","LENGTH","NodeAddr","NodeId","PublicKey","Relay","RelayMap","RelayMode","RelayNode","RelayProtocol","RelayUrl","RelayUrlParseError","SecretKey","Websocket","__clone_box","","","","","","","as_bytes","as_error_source","","as_ref","backtrace","","borrow","","","","","","","","","","borrow_mut","","","","","","","","","cause","","clone","","","","","","","clone_into","","","","","","","clone_to_uninit","","","","","","","cmp","","","","compare","","","","compat","","","","","","","","","compat_mut","","","","","","","","","compat_ref","","","","","","","","","contains_node","default","defaults","deref","","","","","","","","","","deref_mut","","","","","","","","","description","","deserialize","","","","","direct_addresses","","discovery","dns","drop","","","","","","","","","empty","endpoint","eq","","","","","","equivalent","","","","","","","","","","","","","","","","","","fmt","","","","","","","","","","","","","","","","fmt_short","from","","","","","","","","","","","","","","","","","","","","","","","from_bytes","","from_iter","","from_parts","from_ref","","","","","","","from_str","","","from_z32","generate","get_node","hash","","in_current_span","","init","","","","","","","","","into","","","","","","","","","is_empty","","len","metrics","net_report","new","node_id","node_info","nodes","parse_header","partial_cmp","","","","protocol","public","","quic","relay_url","","secret","serialize","","","","","sign","source","","stun_only","stun_port","test_utils","to_bytes","to_owned","","","","","","","to_string","","","","","","","to_z32","try_from","","","","","","","","","","","","try_into","","","","","","","","","type_id","","","","","","","","","upgrade_header","url","urls","verify","vzip","","","","","","","","","with_direct_addresses","with_relay_url","backtrace","","","source","","span_trace","","","DEFAULT_HTTPS_PORT","DEFAULT_HTTP_PORT","DEFAULT_METRICS_PORT","DEFAULT_RELAY_QUIC_PORT","DEFAULT_STUN_PORT","prod","staging","AP_RELAY_HOSTNAME","EU_RELAY_HOSTNAME","NA_RELAY_HOSTNAME","default_ap_relay_node","default_eu_relay_node","default_na_relay_node","default_relay_map","EU_RELAY_HOSTNAME","NA_RELAY_HOSTNAME","default_eu_relay_node","default_na_relay_node","default_relay_map","AttrFromString","ConcurrentDiscovery","DecodingError","Discovery","DiscoveryContext","DiscoveryError","DiscoveryItem","IntoDiscovery","IntoDiscoveryError","Lagged","MAX_LENGTH","NoResults","NoServiceConfigured","NodeData","NodeInfo","NotAnIrohRecord","NumLabels","ParseError","UnexpectedFormat","User","","UserData","Utf8","__clone_box","","","","add","add_direct_addresses","as_error_source","","","","as_ref","backtrace","","","","borrow","","","","","","","","","","borrow_mut","","","","","","","","","","cause","","","","clear_direct_addresses","clone","","","","clone_into","","","","clone_to_uninit","","","","cmp","compare","compat","","","","","","","","","","compat_mut","","","","","","","","","","compat_ref","","","","","","","","","","data","default","","deref","","","","","","","","","","","","deref_mut","","","","","","","","","","","description","","","","direct_addresses","dns","dns_resolver","drop","","","","","","","","","","empty","eq","","","equivalent","","","","","","","","","fmt","","","","","","","","","","","","","","","from","","","","","","","","","","","","","","","","","","from_err","","from_err_box","","from_parts","from_pkarr_signed_packet","from_ref","","","","from_services","from_str","from_txt_lookup","hash","in_current_span","","","","init","","","","","","","","","","into","","","","","","","","","","into_discovery","","into_node_addr","","last_updated","mdns","new","","","node_id","","","node_info","partial_cmp","pkarr","provenance","publish","","relay_url","resolve","","secret_key","set_relay_url","set_user_data","source","","","","static_provider","subscribe","","to_node_addr","","to_owned","","","","to_pkarr_signed_packet","to_string","","","","","to_txt_strings","try_from","","","","","","","","","","","try_into","","","","","","","","","","type_id","","","","","","","","","","user_data","","val","vzip","","","","","","","","","","with_direct_addresses","","with_relay_url","","with_user_data","","backtrace","","","node_id","provenance","source","span_trace","","","backtrace","provenance","source","span_trace","backtrace","","","","","","key","label","num_labels","s","source","","span_trace","","","","","","DnsDiscovery","DnsDiscoveryBuilder","N0_DNS_NODE_ORIGIN_PROD","N0_DNS_NODE_ORIGIN_STAGING","borrow","","borrow_mut","","build","builder","compat","","compat_mut","","compat_ref","","deref","","deref_mut","","dns_resolver","drop","","fmt","","from","","init","","into","","into_discovery","","n0_dns","resolve","try_from","","try_into","","type_id","","vzip","","MdnsDiscovery","MdnsDiscoveryBuilder","NAME","borrow","","borrow_mut","","builder","compat","","compat_mut","","compat_ref","","deref","","deref_mut","","drop","","fmt","","from","","init","","into","","into_discovery","","new","publish","resolve","subscribe","try_from","","try_into","","type_id","","vzip","","DEFAULT_PKARR_TTL","DEFAULT_REPUBLISH_INTERVAL","Encoding","HttpPayload","HttpRequest","HttpSend","InvalidRelayUrl","N0_DNS_PKARR_RELAY_PROD","N0_DNS_PKARR_RELAY_STAGING","PkarrError","PkarrPublisher","PkarrPublisherBuilder","PkarrRelayClient","PkarrResolver","PkarrResolverBuilder","PublicKey","Verify","__clone_box","","","as_error_source","backtrace","borrow","","","","","","borrow_mut","","","","","","build","","builder","","cause","clone","","","clone_into","","","clone_to_uninit","","","compat","","","","","","compat_mut","","","","","","compat_ref","","","","","","deref","","","","","","deref_mut","","","","","","description","dht","dns_resolver","","drop","","","","","","fmt","","","","","","","from","","","","","","from_ref","","","in_current_span","init","","","","","","into","","","","","","into_discovery","","","","n0_dns","","new","publish","","republish_interval","resolve","","source","to_owned","","","to_string","try_from","","","","","","try_into","","","","","","ttl","type_id","","","","","","update_node_data","vzip","","","","","","with_dns_resolver","source","","","","","status","url","Builder","DhtDiscovery","__clone_box","borrow","","borrow_mut","","build","builder","client","clone","clone_into","clone_to_uninit","compat","","compat_mut","","compat_ref","","default","","deref","","deref_mut","","dht","drop","","fmt","","from","","from_ref","include_direct_addresses","init","","initial_publish_delay","into","","into_discovery","","n0_dns_pkarr_relay","no_publish","pkarr_relay","publish","republish_delay","resolve","secret_key","to_owned","try_from","","try_into","","ttl","type_id","","vzip","","PROVENANCE","StaticProvider","__clone_box","add_node_info","borrow","borrow_mut","clone","clone_into","clone_to_uninit","compat","compat_mut","compat_ref","default","deref","deref_mut","drop","fmt","from","from_node_info","from_ref","get_node_info","init","into","into_discovery","new","publish","remove_node_info","resolve","set_node_info","to_owned","try_from","try_into","type_id","vzip","DnsResolver","N0_DNS_NODE_ORIGIN_PROD","N0_DNS_NODE_ORIGIN_STAGING","__clone_box","borrow","borrow_mut","clear_cache","clone","clone_into","clone_to_uninit","compat","compat_mut","compat_ref","default","deref","deref_mut","drop","fmt","from","","from_ref","init","into","lookup_ipv4","lookup_ipv4_ipv6","lookup_ipv4_ipv6_staggered","lookup_ipv4_staggered","lookup_ipv6","lookup_ipv6_staggered","lookup_node_by_domain_name","lookup_node_by_domain_name_staggered","lookup_node_by_id","lookup_node_by_id_staggered","lookup_txt","new","resolve","resolve_host","to_owned","try_from","try_into","type_id","vzip","with_nameserver","AEAD_LIMIT_REACHED","APPLICATION_ERROR","Accept","AcceptBi","AcceptUni","AckFrequencyConfig","AddNodeAddr","AddNodeAddrError","AeadKey","All","AlpnError","App","ApplicationClose","ApplicationClosed","BindError","Builder","CONNECTION_ID_LIMIT_ERROR","CONNECTION_REFUSED","CRYPTO_BUFFER_EXCEEDED","CallMeMaybe","Chunk","CidsExhausted","ClosedStream","","","Connect","ConnectError","ConnectOptions","ConnectWithOptsError","Connecting","Connection","","ConnectionClose","ConnectionClosed","ConnectionError","","ConnectionLost","","","","","ConnectionStats","ConnectionType","ControlMsg","Controller","ControllerFactory","CryptoError","CryptoServerConfig","Custom","Default","Direct","DirectAddr","DirectAddrInfo","DirectAddrType","Disabled","","Discover","Discovery","","DiscoveryStart","ENV_FORCE_STAGING_RELAYS","Empty","EmptyPruned","Endpoint","ExportKeyingMaterialError","FINAL_SIZE_ERROR","FLOW_CONTROL_ERROR","FRAME_ENCODING_ERROR","FinishedEarly","FrameStats","GetMappingAddressError","HandshakeTokenKey","INTERNAL_ERROR","INVALID_TOKEN","IllegalOrderedRead","Incoming","IncomingFuture","KEY_UPDATE_ERROR","Local","LocallyClosed","MAX","MAX_SIZE","MagicSpawn","Mixed","MtuDiscoveryConfig","NO_ERROR","NO_VIABLE_PATH","NamedApp","NoAddress","","None","OpenBi","OpenUni","OwnAddress","PROTOCOL_VIOLATION","PathSelection","PathStats","Ping","Pong","Portmapped","Quinn","Read","ReadDatagram","ReadError","","ReadExactError","ReadToEndError","RecvStream","Relay","","RelayMode","RelayOnly","RemoteInfo","RemoteNodeIdError","Reset","","ResetError","RetryError","STREAM_LIMIT_ERROR","STREAM_STATE_ERROR","Saved","SelfConnect","SendDatagramError","SendStream","ServerConfig","Source","Staging","Stopped","StoppedError","StreamId","Stun","Stun4LocalPort","TRANSPORT_PARAMETER_ERROR","TimedOut","TooLarge","TooLong","TransportConfig","TransportError","","TransportErrorCode","Udp","UdpStats","Unavailable","Unknown","UnknownHandshake","UnsupportedByPeer","UnsupportedVersion","VarInt","VersionMismatch","WeakConnectionHandle","WriteError","Written","ZeroRttAccepted","ZeroRttRejected","","","","__clone_box","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","accept","","accept_bi","accept_uni","accept_with","ack_eliciting_threshold","ack_frequency","ack_frequency_config","acks","add_discovery","add_node_addr","add_node_addr_with_source","addr","","addrs","aead_from_hkdf","allow_spin","alpn","","alpns","as_error_source","","","","","","","","","","","","","","","","","","backtrace","","","","","","","bind","bind_addr_v4","bind_addr_v6","black_hole_cooldown","black_holes_detected","borrow","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","borrow_mut","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","bound_sockets","build","builder","bytes","","","cause","","","","","","","chunks","clear_discovery","clone","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","clone_box","clone_into","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","clone_to_uninit","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","close","","close_reason","closed","cmp","","","","code","compare","","","","compat","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","compat_mut","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","compat_ref","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","congestion_controller_factory","congestion_events","congestion_state","conn_type","","connect","connect_with_opts","connection_close","crypto","","","crypto_buffer_size","current_mtu","cwnd","data_blocked","datagram","datagram_receive_buffer_size","datagram_send_buffer_size","datagram_send_buffer_space","datagrams","decode","","","default","","","","","","","","","","","","","","default_relay_mode","deref","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","deref_mut","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","description","","","","","","","deserialize","","","","","dir","direct_addresses","discovery","","discovery_dht","discovery_local_network","discovery_n0","discovery_stream","dns_resolver","","drop","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","enable_segmentation_offload","encode","","","eq","","","","","","","","","","","","","","","","","","","","","","","","","","","equivalent","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","error_code","","export_keying_material","finish","fmt","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","force_staging_infra","frame","frame_rx","frame_tx","frame_type","from","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","from_ref","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","from_u32","from_u64","from_u64_unchecked","handshake_data","","handshake_done","has_send_address","hash","","","","","home_relay","id","","ignore","immediate_ack","in_current_span","","","","","","","","","","","","","","","","","","incoming_buffer_size","incoming_buffer_size_total","index","init","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","initial_keys","initial_mtu","initial_rtt","initial_window","initiator","insecure_skip_relay_cert_verify","interval","into","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","into_0rtt","into_any","into_future","","","","","","","","","","into_incoming","into_inner","ios","is_0rtt","is_alive","is_closed","keep_alive_interval","keylog","known_nodes","last_alive","last_control","last_payload","last_received","last_used","latency","","local_ip","lost_bytes","lost_packets","lost_plpmtud_probes","max_ack_delay","max_concurrent_bidi_streams","max_concurrent_uni_streams","max_data","max_datagram_size","max_idle_timeout","max_incoming","max_stream_data","max_streams_bidi","max_streams_uni","metrics","migration","min_mtu","minimum_change","mtu_discovery_config","network_change","network_path_changed","new","","","new_connection_id","new_token","node_addr","node_id","","observed_addr","offset","on_ack","on_congestion_event","on_end_acks","on_mtu_update","on_sent","open","open_bi","open_uni","packet_threshold","partial_cmp","","","","path","path_challenge","path_response","path_selection","peer_identity","persistent_congestion_threshold","ping","poll","","","","","","","","","poll_flush","poll_read","","poll_shutdown","poll_write","","preferred_address_v4","preferred_address_v6","priority","proxy_from_env","proxy_url","read","read_chunk","read_chunks","read_datagram","read_exact","read_to_end","reason","","","receive_observed_address_reports","receive_window","received_reset","refuse","relay_conn_protocol","relay_map","relay_mode","relay_url","remote_address","remote_address_validated","remote_info","remote_info_iter","remote_node_id","reordering_threshold","reset","reset_stream","retire_connection_id","retry","retry_tag","retry_token_lifetime","rtt","","saturating_add","seal","secret_key","","send_datagram","send_fairness","send_observed_address_reports","send_window","sent_packets","sent_plpmtud_probes","serialize","","","","","set_alpns","set_max_concurrent_bi_streams","set_max_concurrent_uni_streams","set_priority","set_receive_window","set_user_data_for_discovery","source","","","","","","","","","","","","","","","sources","","stable_id","start_session","stats","stop","stop_sending","stopped","stream","stream_data_blocked","stream_receive_window","streams_blocked_bidi","streams_blocked_uni","time_source","time_threshold","to_owned","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","to_string","","","","","","","","","","","","","","","","","","","","","","","","","","","token_key","transport","transport_config","","try_from","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","try_into","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","try_poll","","","","","","","typ","type_id","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","udp_rx","udp_tx","upper_bound","user_data_for_discovery","validation_token","validation_token_config","vzip","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","window","with_additional_alpns","with_crypto","with_single_cert","with_transport_config","write","write_all","write_all_chunks","write_chunk","write_chunks","backtrace","","","pruned","span_trace","","","backtrace","","","source","span_trace","","","backtrace","","source","","span_trace","","backtrace","","source","","span_trace","","backtrace","","","","source","","","span_trace","","","","backtrace","","","source","","span_trace","","","name","","EndpointMetrics","MagicsockMetrics","NetReportMetrics","PortmapMetrics","RelayMetrics","__clone_box","accepts","actor_link_change","actor_tick_direct_addr_heartbeat","actor_tick_direct_addr_update_receiver","actor_tick_main","actor_tick_msg","actor_tick_other","actor_tick_portmap_changed","actor_tick_re_stun","as_iterable","","","borrow","","","","borrow_mut","","","","bytes_recv","bytes_sent","clone","clone_into","clone_to_uninit","compat","","","","compat_mut","","","","compat_ref","","","","connection_became_direct","connection_handshake_success","conns_rx_ratelimited_total","default","","","","deref","","","","deref_mut","","","","deserialize","","","disco_packets_dropped","disco_packets_recv","disco_packets_sent","disconnects","drop","","","","external_address_updated","field_count","","","field_ref","","","fmt","","","","frames_rx_ratelimited_total","from","","","","from_ref","got_ping","groups","groups_cloned","init","","","","into","","","","local_port_updates","magicsock","mapping_attempts","mapping_failures","name","","","","net_report","nodes_contacted","nodes_contacted_directly","num_direct_conns_added","num_direct_conns_removed","num_relay_conns_added","num_relay_conns_removed","other_packets_dropped","other_packets_recv","other_packets_sent","pcp_available","pcp_probes","portmapper","probes_started","re_stun_calls","recv_data_ipv4","recv_data_ipv6","recv_data_relay","recv_datagrams","recv_disco_bad_key","recv_disco_bad_parse","recv_disco_call_me_maybe","recv_disco_call_me_maybe_bad_disco","recv_disco_ping","recv_disco_pong","recv_disco_relay","recv_disco_udp","recv_gro_datagrams","relay_accepts","relay_home_change","send_data","send_data_network_down","send_disco_relay","send_disco_udp","send_ipv4","send_ipv6","send_packets_dropped","send_packets_recv","send_packets_sent","send_relay","send_relay_error","sent_disco_call_me_maybe","sent_disco_ping","sent_disco_pong","sent_disco_relay","sent_disco_udp","sent_pong","serialize","","","to_owned","try_from","","","","try_into","","","","type_id","","","","unique_client_keys","unknown_frames","update_direct_addrs","upnp_available","upnp_gateway_updated","upnp_probes","upnp_probes_failed","vzip","","","","websocket_accepts","Abort","ActorGone","Addr","AlreadyRunning","Client","Metrics","Options","QuicConfig","RelayLatencies","Report","ReportError","__clone_box","","","","","addr","as_error_source","as_iterable","backtrace","bind_local_stun_socket","borrow","","","","","","","","borrow_mut","","","","","","","","captive_portal","cause","client_config","clone","","","","","clone_into","","","","","clone_to_uninit","","","","","compat","","","","","","","","compat_mut","","","","","","","","compat_ref","","","","","","","","default","","","","deref","","","","","","","","deref_mut","","","","","","","","description","deserialize","disabled","drop","","","","","","","","ep","eq","","equivalent","","","","","","field_count","field_ref","fmt","","","","","","","","","","from","","","","","","","","from_ref","","","","","get_report","global_v4","global_v6","hair_pinning","https","icmp_v4","icmp_v6","icmpv4","icmpv6","in_current_span","init","","","","","","","","insecure_skip_relay_cert_verify","into","","","","","","","","ipv4","","ipv4_can_send","ipv6","","ipv6_can_send","iter","mapping_varies_by_dest_ip","mapping_varies_by_dest_ipv6","name","new","os_has_ipv6","portmap_probe","preferred_relay","quic_config","receive_stun_packet","relay_latency","relay_v4_latency","relay_v6_latency","reports","reports_full","serialize","source","stun_packets_dropped","stun_packets_recv_ipv4","stun_packets_recv_ipv6","stun_packets_sent_ipv4","stun_packets_sent_ipv6","stun_v4","stun_v6","to_owned","","","","","to_string","","try_from","","","","","","","","try_into","","","","","","","","type_id","","","","","","","","udp","vzip","","","","","","","","backtrace","","","reason","span_trace","","","AttrFromString","DecodingError","","EncodingError","FailedBuildingPacket","IROH_TXT_NAME","InvalidEncodingZ32","InvalidLabel","InvalidLength","InvalidSignature","InvalidTxtEntry","LookupError","LookupFailed","MaxLengthExceededError","NodeData","NodeIdExt","NodeInfo","NotAnIrohRecord","NumLabels","ParseError","","UnexpectedFormat","UserData","Utf8","as_error_source","","","","backtrace","","","","borrow","","","","borrow_mut","","","","cause","","","","compat","","","","compat_mut","","","","compat_ref","","","","data","deref","","","","deref_mut","","","","description","","","","drop","","","","fmt","","","","","","","","from","","","","","from_z32","in_current_span","","","","init","","","","into","","","","node_id","source","","","","to_string","","","","to_z32","try_from","","","","try_into","","","","type_id","","","","vzip","","","","backtrace","","","len","source","","span_trace","","","backtrace","","source","","span_trace","","backtrace","","","source","","","span_trace","","","backtrace","","","","","","key","label","num_labels","s","source","","span_trace","","","","","","AcceptError","AccessLimit","Connection","MissingRemoteNodeId","NotAllowed","ProtocolHandler","Router","RouterBuilder","User","__clone_box","","accept","","","as_error_source","backtrace","borrow","","","","borrow_mut","","","","builder","cause","clone","","clone_into","","clone_to_uninit","","compat","","","","compat_mut","","","","compat_ref","","","","deref","","","","deref_mut","","","","description","drop","","","","endpoint","","fmt","","","","","from","","","","","","","","","from_err","from_ref","","in_current_span","init","","","","into","","","","is_shutdown","new","","on_connecting","","shutdown","","","source","spawn","to_owned","","to_string","try_from","","","","try_into","","","","type_id","","","","vzip","","","","backtrace","source","","","span_trace","CleanupDropGuard","DnsPkarrServer","borrow","","borrow_mut","","compat","","compat_mut","","compat_ref","","deref","","deref_mut","","discovery","dns_resolver","drop","","fmt","","from","","init","","into","","nameserver","node_origin","on_node","pkarr_url","run","run_relay_server","run_relay_server_with","run_relay_server_with_stun","run_with_origin","try_from","","try_into","","type_id","","vzip",""],"q":[[0,"iroh"],[349,"iroh::KeyParsingError"],[357,"iroh::defaults"],[364,"iroh::defaults::prod"],[371,"iroh::defaults::staging"],[376,"iroh::discovery"],[704,"iroh::discovery::DiscoveryError"],[713,"iroh::discovery::IntoDiscoveryError"],[717,"iroh::discovery::ParseError"],[735,"iroh::discovery::dns"],[778,"iroh::discovery::mdns"],[820,"iroh::discovery::pkarr"],[981,"iroh::discovery::pkarr::PkarrError"],[988,"iroh::discovery::pkarr::dht"],[1046,"iroh::discovery::static_provider"],[1080,"iroh::dns"],[1123,"iroh::endpoint"],[3078,"iroh::endpoint::AddNodeAddrError"],[3085,"iroh::endpoint::AlpnError"],[3092,"iroh::endpoint::BindError"],[3098,"iroh::endpoint::ConnectError"],[3104,"iroh::endpoint::ConnectWithOptsError"],[3115,"iroh::endpoint::GetMappingAddressError"],[3123,"iroh::endpoint::Source"],[3125,"iroh::metrics"],[3305,"iroh::net_report"],[3546,"iroh::net_report::ReportError"],[3553,"iroh::discovery"],[3554,"iroh::node_info"],[3555,"iroh::discovery"],[3556,"iroh::node_info"],[3570,"iroh::discovery"],[3572,"iroh::node_info"],[3574,"iroh::discovery"],[3575,"iroh::node_info"],[3576,"iroh::discovery"],[3577,"iroh::node_info"],[3609,"iroh::discovery"],[3610,"iroh::node_info"],[3652,"iroh::discovery"],[3653,"iroh::node_info"],[3678,"iroh::node_info::DecodingError"],[3687,"iroh::node_info::EncodingError"],[3693,"iroh::node_info::LookupError"],[3702,"iroh::discovery::ParseError"],[3720,"iroh::protocol"],[3834,"iroh::protocol::AcceptError"],[3839,"iroh::test_utils"],[3884,"dyn_clone::sealed"],[3885,"iroh_base::key"],[3886,"core::error"],[3887,"backtrace::capture"],[3888,"core::option"],[3889,"iroh_base::relay_url"],[3890,"iroh_base::node_addr"],[3891,"iroh_relay::relay_map"],[3892,"core::cmp"],[3893,"async_compat"],[3894,"core::result"],[3895,"serde::de"],[3896,"core::net::socket_addr"],[3897,"core::iter::traits::iterator"],[3898,"alloc::collections::btree::set"],[3899,"core::fmt"],[3900,"alloc::string"],[3901,"ed25519_dalek::verifying"],[3902,"data_encoding"],[3903,"signature::error"],[3904,"ed25519_dalek::signing"],[3905,"iroh_relay::node_info"],[3906,"iroh_base::ticket::node"],[3907,"iroh::magicsock::node_map::node_state"],[3908,"url"],[3909,"core::iter::traits::collect"],[3910,"rand_core"],[3911,"alloc::sync"],[3912,"core::hash"],[3913,"http::header::value"],[3914,"serde::ser"],[3915,"ed25519"],[3916,"core::any"],[3917,"n0_snafu::spantrace"],[3918,"iroh_relay::dns"],[3919,"alloc::boxed"],[3920,"core::marker"],[3921,"pkarr::signed_packet"],[3922,"alloc::vec"],[3923,"futures_lite::stream"],[3924,"core::str::error"],[3925,"core::time"],[3926,"pkarr::keys"],[3927,"reqwest::error"],[3928,"http::status"],[3929,"pkarr::client"],[3930,"core::convert"],[3931,"anyhow"],[3932,"hickory_proto::runtime::tokio_runtime"],[3933,"hickory_resolver::name_server::connection_provider"],[3934,"hickory_resolver::resolver"],[3935,"core::net::ip_addr"],[3936,"reqwest::dns::resolve"],[3937,"core::future::future"],[3938,"core::pin"],[3939,"iroh_quinn_proto::connection"],[3940,"iroh_quinn::connection"],[3941,"iroh_quinn_proto::config"],[3942,"iroh_quinn_proto::config::transport"],[3943,"iroh_quinn_proto::varint"],[3944,"iroh_quinn_proto::connection::stats"],[3945,"iroh::magicsock"],[3946,"iroh_quinn_proto::crypto"],[3947,"iroh_quinn_proto::congestion"],[3948,"std::time"],[3949,"iroh_quinn_proto::connection::assembler"],[3950,"bytes::bytes"],[3951,"iroh_quinn_proto::connection::streams::send"],[3952,"iroh_quinn::recv_stream"],[3953,"iroh_quinn::send_stream"],[3954,"iroh_quinn_proto::connection::streams"],[3955,"iroh::magicsock::node_map"],[3956,"iroh_quinn_proto::frame"],[3957,"iroh_quinn_proto"],[3958,"n0_watcher"],[3959,"iroh_quinn_proto::coding"],[3960,"bytes::buf::buf_impl"],[3961,"futures_core::stream"],[3962,"bytes::buf::buf_mut"],[3963,"iroh_quinn::incoming"],[3964,"iroh_quinn_proto::connection::streams::recv"],[3965,"ring::error::unspecified"],[3966,"iroh_quinn_proto::transport_parameters"],[3967,"iroh_quinn_proto::shared"],[3968,"iroh_quinn_proto::connection::paths"],[3969,"core::task::wake"],[3970,"core::task::poll"],[3971,"std::io::error"],[3972,"tokio::io::read_buf"],[3973,"std::collections::hash::map"],[3974,"rustls_pki_types"],[3975,"rustls::error"],[3976,"iroh_quinn_proto::endpoint"],[3977,"iroh_metrics::metrics"],[3978,"iroh_metrics::iterable"],[3979,"iroh_metrics::base"],[3980,"netwatch::ip_family"],[3981,"tokio_util::sync::cancellation_token"],[3982,"netwatch::udp"],[3983,"iroh::net_report::reportgen"],[3984,"rustls::client::client_conn"],[3985,"iroh::net_report::options::imp"],[3986,"iroh::net_report::metrics"],[3987,"iroh_quinn::endpoint"],[3988,"portmapper"],[3989,"z32"],[3990,"simple_dns::simple_dns_error"],[3991,"hickory_proto::error"],[3992,"core::clone"],[3993,"core::ops::function"],[3994,"tokio::runtime::task::error"],[3995,"iroh::test_utils::dns_and_pkarr_servers"],[3996,"iroh_relay::server"],[3997,"iroh_relay"],[3998,"iroh_relay::defaults"],[3999,"iroh::net_report::stun_utils"]],"i":"Ab0`0`h```Bb```````01AlAnB`3BdBf67Ah7807785430621785430621807543621754362175436217431743178543062178543062178543062126`7854330621785430621807543144``7854306212`74362177744433366622211177885543300622117778885554444443306222117522475436217537527380785430621785430621422``44`267431`7514457543158011`5754362178530217777855430621785430621785430621612778543062144FjFlFn21210```````````````````Gj`0```````GhGn0``22`2Gl1`3Gf3DlHbGb3745H`785604738Hd67321584906732196715584358435843885849067321584906732158490673214525844906733215844906732196715`05849067321258455588844458849906677321155844444990677322167674458432848967158490673215849067321Il3544`65414549`4Gd4704277;893`04657:656:;89367::6;2895437:6;2895437:6;2895437537:6;289543767676JhJjJl100210Jn000K`KbKdKfKhKj413520543210````L`Kn1001101010101001010101010101110101010```LdLb1011010101010101010101010111110101010``Hn0000````````00LjLnM`333Lh3Ll32514032104354324324325140325140325140325140325140325`105140325514032514032432551403251403214034324213254325514032514032151403245140322MbMfMjMnN`NbNf``Nj0Nh10010111101010101010010101010100101000010101101001010Nn`00000000000000000000000000000000```Hf000000000000000000000000000000000000000AG`0````ACb``AGf`AFh`AAb``444AFd`1`AEfAElACd`````0`4`AC`AEb4AEh4AEn```````AGj0AFf```41ACh40;ADnAB`ADbAF`AE`AFb>ABhEbAFfAFhAAbAAlAD`AAjAFjAFlAFnAG`AGbABjAGdAGfA@jAGhAAdAGj3A@n220?AB`ABb1ABd77ABh;EbABl4AA`94AEbAI`AEdAEfAEhAEjAElAEnAFbAAbAFnABfACbACdACfAChAC`ACj6543210ABd00AD`ADbAKnAKlAAhAAfALdAHnAEbAI`AHfAEdAEfAEhAEjAHhAElAEnABbAAnADjADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAHlAIbAIdAFjAFlAFnAG`ABfAGbABjAGdAGfABdA@jACbACdACfAChAGhA@lA@nAIfAA`AC`AIhAAdACjAGjAKnAKlAAhAAfALdAHnAEbAI`AHfAEdAEfAEhAEjAHhAElAEnABbAAnADjADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAHlAIbAIdAFjAFlAFnAG`ABfAGbABjAGdAGfABdA@jACbACdACfAChAGhA@lA@nAIfAA`AC`AIhAAdACjAGj>ADd?ADjADnAE`ABfACbACdACfACh=:5ABdAEbAEdAEfAEhAEjAElAEnAAn?AB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAFjAFlAFnAG`AGbABjAGdAGfA@jAGhAAdAGjADhAEbAEdAEfAEhAEjAElAEnAAnADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAFjAFlAFnAG`AGbABjAGdAGfA@jAGhAAdAGjAEbAEdAEfAEhAEjAElAEnAAnADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAFjAFlAFnAG`AGbABjAGdAGfA@jAGhAAdAGj3111AAn876:0876AKnAKlAAhAAfALdAHnAEbAI`AHfAEdAEfAEhAEjAHhAElAEnABbAAnADjADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAHlAIbAIdAFjAFlAFnAG`ABfAGbABjAGdAGfABdA@jACbACdACfAChAGhA@lA@nAIfAA`AC`AIhAAdACjAGjAKnAKlAAhAAfALdAHnAEbAI`AHfAEdAEfAEhAEjAHhAElAEnABbAAnADjADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAHlAIbAIdAFjAFlAFnAG`ABfAGbABjAGdAGfABdA@jACbACdACfAChAGhA@lA@nAIfAA`AC`AIhAAdACjAGjAKnAKlAAhAAfALdAHnAEbAI`AHfAEdAEfAEhAEjAHhAElAEnABbAAnADjADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAHlAIbAIdAFjAFlAFnAG`ABfAGbABjAGdAGfABdA@jACbACdACfAChAGhA@lA@nAIfAA`AC`AIhAAdACjAGjABbADb4A@jEb11AB`AG`1AAj65522669ADnAAn3AGb91258AF`AE`AFbAFfAAlAD`AGfABdAGh`AKnAKlAAhAAfALdAHnAEbAI`AHfAEdAEfAEhAEjAHhAElAEnABbAAnADjADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAHlAIbAIdAFjAFlAFnAG`ABfAGbABjAGdAGfABdA@jACbACdACfAChAGhA@lA@nAIfAA`AC`AIhAAdACjAGjAKnAKlAAhAAfALdAHnAEbAI`AHfAEdAEfAEhAEjAHhAElAEnABbAAnADjADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAHlAIbAIdAFjAFlAFnAG`ABfAGbABjAGdAGfABdA@jACbACdACfAChAGhA@lA@nAIfAA`AC`AIhAAdACjAGjABf>=<;52AFdABhEbAFfAFhAGbA@jABd1000101AKnAKlAAhAAfALdAHnAEbAI`AHf0AEdAEfAEhAEjAHh0AElAEnABbAAnADjADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAHlAIbAIdAFjAFlAFnAG`ABfAGbABjAGdAGfABdA@jACbACdACfAChAGhA@lA@nAIfAA`AC`AIhAAdACjAGjABbAAnAG`AGbAEbAEdAEfAEhAEjAElAEn9ADjAE`AFbAFdABhEbAFfAFhAAbAHlAFjAFlAFnAG`AGbABjAGdAGfAGjAEb00AEd00AEf00AEh00AEj00AEl00AEn00AAn00ADj00AE`00AFb00AFd00ABh00Eb00AFf00AFh00AAb00AHl00AFj00AFl00AFn00AG`00AGb00ABj00AGd00AGf00AGj0087AAdAHhAHnAEb0AI`0AHfAEd0AEf0AEh0AEj08AEl0AEn0ABbAAn0ADjADnAB`ADbAF`AE`AFb0AFd0ABhEbAFf0AFh0AAb0AAlAD`AAjAHlAIbAIdAFj0AFl0AFn0AG`0ABf0AGb0ABjAGd0AGfABdA@jACb0ACd0ACf0ACh0AGhA@lA@nAIfAA`AC`0AIhAAdACj0AGj`AFnAF`0AFjAKnAKlAAhAAfALdAHnAEb0AI`AHfAEd0AEf000AEh0AEj0AHhAEl000AEn0ABbAAn0000ADjADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAb00AAlAD`AAjAHlAIb0AIdAFj0AFlAFn000AG`ABfAGb0ABjAGdAGfABdA@jACb0ACd00ACf0AChAGhA@lA@nAIfAA`AC`0AIhAAdACjAGjAEbAEdAEfAEhAEjAElAEnAAnADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAFjAFlAFnAG`AGbABjAGdAGfA@jAGhAAdAGjAAn00AA`3AB`Eb3AFh<;:8AHfAHhA@n5AEbAI`AEdAEfAEhAEjAElAEnAFbAAbAFnABfACbACdACfAChAC`ACjAAj0AGbAKnAKlAAhAAfALdAHnAEbAI`AHfAEdAEfAEhAEjAHhAElAEnABbAAnADjADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAHlAIbAIdAFjAFlAFnAG`ABfAGbABjAGdAGfABdA@jACbACdACfAChAGhA@lA@nAIfAA`AC`AIhAAdACjAGjAJlABb0ADhAGbABdAD`AKnAKlAAhAAfALdAHnAEbAI`AHfAEdAEfAEhAEjAHhAElAEnABbAAnADjADnAB`ADbAF`AE`AFbAFdABhEbAFfAFhAAbAAlAD`AAjAHlAIbAIdAFjAFlAFnAG`ABfAGbABjAGdAGfABdA@jACbACdACfAChAGhA@lA@nAIfAA`AC`AIhAAdACjAGj5ADhAKnAKlAAhAAfALd>=<;9AI`AAnADnAHfAHnA@jABbABd0ABh00Eb010A@nADb00AAl66AB`AAd8AAj222:09AD`:;<1AGbAGh55==95ADjADh0000ABn77?AAn5ABjAGdAF`<AKnAKlAAhAAfALdA@lAIfAA`AIhAHhAHf0111AAj02==111AAd22AFjAFlAFnABb06A@nABdAGj1Eb33A@j09AAl=AB`06AJl={JdAAn}????????????{AIlAAb}{AFnAAb}{cc{}}00000{AInAIb}11{AFnAFj}2{AG`AFn}{AJ`AFn}4{AJbAFn}55{AAnAGb}666666{ABfACb}7{ACbACd}8{AAbACd}9{GlACf}:::::::{AAbAC`};;;;{{{b{c}}}c{}}0000000000000000000000000000000000?{In{{Cb{AAnAJd}}}}{InAAn}{{{b{AjAA`}}}{{Cb{{I`{AJf}}AAb}}}}{{{b{AAd}}}{{Af{{I`{AJf}}}}}}{AB`j}{{{b{Eb}}}Bl}{{{b{AAn}}{b{Ajc}}}fEn}{{{b{AFh}}{b{Ajc}}}fEn}{{{b{AGb}}{b{Ajc}}}fEn}{{{b{ABj}}{b{Ajc}}}fEn}{{{b{AGd}}{b{Ajc}}}fEn}{{{b{A@j}}}{{`{{AJj{}{{AJh{{Ih{B`}}}}}}}}}}{{{b{AHf}}}AGb}{{{b{AHh}}}AGb}{A@nf}{AB`In}{{}}00000000000000000{{{b{AjAAj}}In}{{b{AjAAj}}}}0{AGbIn}{{}Bn}0000000000000000000000000000000000000000000000000000000000000{{{b{AJl}}Jd{b{AJn}}}{{Cb{AK`AId}}}}{{{b{AjABb}}Ff}{{b{AjABb}}}}{{{b{AjABb}}Lf}{{b{AjABb}}}}{{{b{ADh}}}In}{AGbAKb}{{ABdBl}ABd}{{{b{AjAD`}}Lf}{{b{AjAD`}}}}{{}c{}}0000000000000000000000000000000000000000000000000000000000000{AA`{{Cb{{E`{AAdAIh}}AA`}}}}{{{I`{ADh}}}{{I`{AJf}}}}======{A@nc{}}>>>{AI`AKd}{AAnIn}{ADnIn}{{{b{AHf}}}Bl}{{{b{AHn}}}Bl}{{{b{A@j}}}Bl}{{{b{AjABb}}{Af{Lf}}}{{b{AjABb}}}}<{{ABd{Ih{An}}}ABd}{ABhAf}00{{{b{Eb}}}{{Af{Lf}}}}{EbAf}20{{{b{A@n}}}{{Af{Oj}}}}{ADbIn}00{{{b{AjAAl}}{Af{Lf}}}{{b{AjAAl}}}}{{{b{AjABb}}AAn}{{b{AjABb}}}}0{AB`In}{{{b{AAd}}}{{Af{Bn}}}}{{{b{AjABb}}{Af{AKf}}}{{b{AjABb}}}}{{{b{AjAAj}}Bn}{{b{AjAAj}}}}333{{{b{A@j}}}{{b{AKh}}}}{{{b{AjAAj}}Bl}{{b{AjAAj}}}}{{{b{AjABb}}Ff}{{b{AjABb}}}}{{{b{AjAD`}}Ff}{{b{AjAD`}}}}{{{b{AjABb}}{Af{AD`}}}{{b{AjABb}}}}{{{b{A@j}}}f}{{{b{AHn}}}Bl}{{{El{AJl}}{El{ABl}}}AAj}{{AKbAHbIn}AGb}{{}AGh}=={{{b{A@j}}}{{`{{AJj{}{{AJh{{Af{An}}}}}}}}}}{{{b{A@j}}}J`}{EbJ`}{AB`In}{ADjIn}{{{b{AjADh}}ADfADfInBl{b{AKj}}}f}{{{b{AjADh}}ADfADfBlIn}f}{{{b{AjADh}}ADfInBl{Af{In}}}f}{{{b{AjADh}}Ff}f}{{{b{AjADh}}ADfInIn}f}{{{b{ABn}}{b{Aj{A`{j}}}}{b{{A`{j}}}}}{{Cb{{b{Aj{A`{j}}}}AIb}}}}{{{b{AAd}}}AKl}{{{b{AAd}}}AKn}{{{b{AjABb}}Jd}{{b{AjABb}}}}{{{b{AAn}}{b{AAn}}}{{Af{Bh}}}}{{{b{AGb}}{b{AGb}}}{{Af{Bh}}}}{{{b{ABj}}{b{ABj}}}{{Af{Bh}}}}{{{b{AGd}}{b{AGd}}}{{Af{Bh}}}}{AF`ADb}??{{ABdAGf}ABd}{{{b{AAd}}}{{Af{{I`{AJf}}}}}}7{AB`In}{{{A@h{{b{AjAKn}}}}{b{AjAL`}}}ALb}{{{A@h{{b{AjAKl}}}}{b{AjAL`}}}ALb}{{{A@h{{b{AjAAh}}}}{b{AjAL`}}}ALb}{{{A@h{{b{AjAAf}}}}{b{AjAL`}}}ALb}{{{A@h{{b{AjALd}}}}{b{AjAL`}}}ALb}{{{A@h{{b{AjA@l}}}}{b{AjAL`}}}{{ALb{c}}}{}}{{{A@h{{b{AjAIf}}}}{b{AjAL`}}}{{ALb{c}}}{}}{{{A@h{{b{AjAA`}}}}{b{AjAL`}}}{{ALb{c}}}{}}{{{A@h{{b{AjAIh}}}}{b{AjAL`}}}{{ALb{c}}}{}}{{{A@h{{b{AjAHh}}}}{b{AjAL`}}}{{ALb{{Cb{fALf}}}}}}{{{b{AjAHf}}{b{AjAL`}}{b{Aj{A`{j}}}}}{{ALb{{Cb{BnAEf}}}}}}{{{A@h{{b{AjAHf}}}}{b{AjAL`}}{b{AjALh}}}{{ALb{{Cb{fALf}}}}}}2{{{A@h{{b{AjAHh}}}}{b{AjAL`}}{b{{A`{j}}}}}{{ALb{{Cb{BnALf}}}}}}{{{A@h{{b{AjAHh}}}}{b{AjAL`}}{b{{A`{j}}}}}{{ALb{{Cb{BnAEl}}}}}}{{{b{AjAAj}}{Af{ACl}}}{{b{AjAAj}}}}{{{b{AjAAj}}{Af{ACn}}}{{b{AjAAj}}}}{{{b{AHh}}}{{Cb{ALjAFb}}}}{ABdABd}{{ABdEd}ABd}{{{b{AjAHf}}{b{Aj{A`{j}}}}}{{Cb{{Af{Bn}}AEf}}}}{{{b{AjAHf}}BnBl}{{Cb{{Af{ADj}}AEf}}}}{{{b{AjAHf}}{b{Aj{A`{ADl}}}}}{{Cb{{Af{Bn}}AEf}}}}{{{b{AAd}}}ALd}{{{b{AjAHf}}{b{Aj{A`{j}}}}}{{Cb{fAEj}}}}{{{b{AjAHf}}Bn}{{Cb{{Ih{j}}AEd}}}}{AFjADl}{AFlADl}{AFnDb}{{{b{AjABb}}Bl}{{b{AjABb}}}}{{{b{AjABb}}AAn}{{b{AjABb}}}}{{{b{AjAHf}}}{{Cb{{Af{AAn}}AEh}}}}{A@nf}{{ABdBb}ABd}{{{b{AGj}}}Bd}{{ABdAGj}ABd}{EbAf}{{{b{A@n}}}Ch}{{{b{A@n}}}Bl}{{{b{A@j}}J`}{{Af{Eb}}}}{{{b{A@j}}}{{`{{Cj{}{{Cf{Eb}}}}}}}}{{{b{AAd}}}{{Cb{J`ACj}}}}{{{b{AjAAl}}AAn}{{b{AjAAl}}}}{{{b{AjAHh}}AAn}{{Cb{fAFb}}}}{AB`In}0{A@n{{Cb{fAI`}}}}{{{b{AJl}}Jd{b{AJn}}{b{{A`{j}}}}}{{l{j}}}}{{{b{AjAAj}}Lf}{{b{AjAAj}}}}{{{b{AAd}}}Lf}{ADbLf}{{AAnc}AAn{{O`{AAn}}}}{{{b{ABn}}{b{Aj{Ih{j}}}}{b{{A`{j}}}}}{{Cb{fAIb}}}}{{ABdAl}ABd}{{{b{A@j}}}{{b{Al}}}}{{{b{AAd}}ADl}{{Cb{fAEb}}}}{{{b{AjABb}}Bl}{{b{AjABb}}}}0{{{b{AjABb}}In}{{b{AjABb}}}}{ADbIn}0{{{b{AFd}}c}CbFb}{{{b{ABh}}c}CbFb}{{{b{Eb}}c}CbFb}{{{b{AFf}}c}CbFb}{{{b{AFh}}c}CbFb}{{{b{A@j}}{Ih{{Ih{j}}}}}f}{{{b{AAd}}AAn}f}0{{{b{AHh}}ALj}{{Cb{fAFb}}}}1{{{b{A@j}}{Af{Gh}}}f}{{{b{AEb}}}{{Af{{b{n}}}}}}{{{b{AEd}}}{{Af{{b{n}}}}}}{{{b{AEf}}}{{Af{{b{n}}}}}}{{{b{AEh}}}{{Af{{b{n}}}}}}{{{b{AEj}}}{{Af{{b{n}}}}}}{{{b{AEl}}}{{Af{{b{n}}}}}}{{{b{AEn}}}{{Af{{b{n}}}}}}{{{b{AAb}}}{{Af{{b{n}}}}}}{{{b{ABf}}}{{Af{{b{n}}}}}}{{{b{ACb}}}{{Af{{b{n}}}}}}{{{b{ACd}}}{{Af{{b{n}}}}}}{{{b{ACf}}}{{Af{{b{n}}}}}}{{{b{ACh}}}{{Af{{b{n}}}}}}{{{b{AC`}}}{{Af{{b{n}}}}}}{{{b{ACj}}}{{Af{{b{n}}}}}}{{{b{Eb}}}{{Ih{{E`{AFhLf}}}}}}{ABhALl}{{{b{AAd}}}Bn}{{{El{AJl}}Jd{b{ALn}}}{{I`{AM`}}}}{{{b{AAd}}}AF`}{{{b{AjAHf}}AAn}{{Cb{fAFb}}}}{AB`In}{{{b{AjAHh}}}{{Cb{{Af{AAn}}AEn}}}}11{{{b{AjABb}}AAn}{{b{AjABb}}}}22{{{b{AjAAj}}{El{AMb}}}{{b{AjAAj}}}}{{{b{AjABb}}AMd}{{b{AjABb}}}}{bc{}}0000000000000000000000000000000000{bDb}00000000000000000000000000{{{b{AjAAj}}{El{ABl}}}{{b{AjAAj}}}}{AAjEl}{{{b{AjAAj}}{El{ABb}}}{{b{AjAAj}}}}{{ABdABb}ABd}{c{{Cb{e}}}{}{}}0000000000000000{In{{Cb{AAnAJd}}}}1{AMf{{Cb{AAnAJd}}}}{Bn{{Cb{AAnAJd}}}}33333333333333333333333333333333333333333333{{}{{Cb{c}}}{}}0000000000000000000000000000000000000000000000000000000000000{{{A@h{{b{Ajc}}}}{b{AjAL`}}}ALb{}}000000{ABjAGd}{bFh}0000000000000000000000000000000000000000000000000000000000000{AF`ADn}0{{{b{AjAD`}}Ff}{{b{AjAD`}}}}{{ABdGh}ABd}{AAjAMh}{{{b{AjAAj}}AMh}{{b{AjAAj}}}}{{}c{}}0000000000000000000000000000000000000000000000000000000000000{{{b{ADh}}}In}{{AGh{Ih{{Ih{j}}}}}AGh}{{{El{AJl}}}AAj}{{{Ih{AMj}}AMl}{{Cb{AAjAMn}}}}{{AGh{El{ABb}}}AGh}{{{b{AjAHh}}{b{{A`{j}}}}}{{Cb{BnAEl}}}}{{{b{AjAHh}}{b{{A`{j}}}}}{{Cb{fAEl}}}}{{{b{AjAHh}}{b{Aj{A`{ADl}}}}}{{Cb{fAEl}}}}{{{b{AjAHh}}ADl}{{Cb{fAEl}}}}{{{b{AjAHh}}{b{Aj{A`{ADl}}}}}{{Cb{AE`AEl}}}}{AN`Af}{ANbAf}{ANdAf}{ANbBn}{AN`G`}{ANbG`}{ANdG`}{ANfAf}{ANhAf}{ANjAf}{ANfAAb}{ANfG`}{ANhG`}{ANjG`}{ANlAf}{ANnAf}`{ANnGl}{ANlG`}{ANnG`}{AO`Af}{AObAf}{AO`I`}{AObI`}{AO`G`}{AObG`}{AOdAf}{AOfAf}{AOhAf}{AOjAf}{AOdABf}{AOhACh}{AOjAOl}{AOdG`}{AOfG`}{AOhG`}{AOjG`}{AOnAf}{B@`Af}{B@bAf}{AOnGn}{B@`Gn}{AOnG`}{B@`G`}{B@bG`}{B@dDb}{B@fDb}`````{{bd}f}{B@hB@j}{B@lB@j}0000000{b{{b{B@n}}}}00{b{{b{c}}}{}}000{{{b{Aj}}}{{b{Ajc}}}{}}00044{{{b{AKh}}}AKh}{{b{b{Ajc}}}f{}}{{bj}f}{{}{{Bj{c}}}{}}000{{{b{Aj}}}{{Bj{{b{Ajc}}}}}{}}000{b{{Bj{{b{c}}}}}{}}00099:{{}BA`}{{}B@l}{{}B@h}{{}AKh}{Bn{{b{c}}}{}}000{Bn{{b{Ajc}}}{}}000{c{{Cb{BA`}}}Cd}{c{{Cb{B@l}}}Cd}{c{{Cb{AKh}}}Cd}{B@hB@j}000{Bnf}000{BA`B@j}{{{b{BA`}}}Bn}{{{b{B@l}}}Bn}{{{b{B@h}}}Bn}{{{b{BA`}}Bn}{{Af{BAb}}}}{{{b{B@l}}Bn}{{Af{BAb}}}}{{{b{B@h}}Bn}{{Af{BAb}}}}{{{b{BA`}}{b{AjCn}}}{{Cb{fD`}}}}{{{b{B@l}}{b{AjCn}}}Hh}{{{b{B@h}}{b{AjCn}}}{{Cb{fD`}}}}{{{b{AKh}}{b{AjCn}}}Hh}<{cc{}}000{{{b{c}}}c{}}>{{{b{AKh}}}{{`{{Cj{}{{Cf{{b{BAd}}}}}}}}}}{{{b{AKh}}}{{`{{Cj{}{{Cf{{El{BAd}}}}}}}}}}{{}Bn}000{{}c{}}000{BA`B@j}{AKhEl}11{{{b{BA`}}}{{b{C`}}}}{{{b{B@l}}}{{b{C`}}}}{{{b{B@h}}}{{b{C`}}}}{{{b{AKh}}}{{b{C`}}}}4{B@lB@j}00000{B@hB@j}007767111111111111110111111100011111110{{{b{BA`}}c}CbFb}{{{b{B@l}}c}CbFb}{{{b{AKh}}c}CbFb}{bc{}}{c{{Cb{e}}}{}{}}000{{}{{Cb{c}}}{}}000{bFh}000778>>>>{{}c{}}0008```````````{{bd}f}0000{{{b{BAf}}}BAh}{b{{b{n}}}}{b{{b{B@n}}}}{{{b{BAj}}}{{Af{{b{Ad}}}}}}{{BAlBAhBAn}{{Af{{El{BB`}}}}}}{b{{b{c}}}{}}0000000{{{b{Aj}}}{{b{Ajc}}}{}}0000000{BBbAf}{{{b{BAj}}}{{Af{{b{n}}}}}}{BBdBBf}{{{b{BBd}}}BBd}{{{b{BBh}}}BBh}{{{b{BBb}}}BBb}{{{b{BBj}}}BBj}{{{b{BAh}}}BAh}{{b{b{Ajc}}}f{}}0000{{bj}f}0000{{}{{Bj{c}}}{}}0000000{{{b{Aj}}}{{Bj{{b{Ajc}}}}}{}}0000000{b{{Bj{{b{c}}}}}{}}0000000{{}BBl}{{}BBh}{{}BBb}{{}BBj}{Bn{{b{c}}}{}}0000000{Bn{{b{Ajc}}}{}}0000000{{{b{BAj}}}{{b{C`}}}}{c{{Cb{BBl}}}Cd}6{Bnf}0000000{BBdBBn}{{{b{BBb}}{b{BBb}}}Bl}{{{b{BBj}}{b{BBj}}}Bl}{{b{b{c}}}Bl{}}00000{{{b{BBl}}}Bn}{{{b{BBl}}Bn}{{Af{BAb}}}}{{{b{BBl}}{b{AjCn}}}Hh}{{{b{BBd}}{b{AjCn}}}Hh}{{{b{BBh}}{b{AjCn}}}Hh}{{{b{BBb}}{b{AjCn}}}Hh}0{{{b{BBj}}{b{AjCn}}}Hh}{{{b{BAf}}{b{AjCn}}}Hh}{{{b{BAh}}{b{AjCn}}}Hh}{{{b{BAj}}{b{AjCn}}}Hh}0{cc{}}0000000{{{b{c}}}c{}}0000{{{b{AjBAf}}BdBBh}{{Cb{{El{BBb}}BAj}}}}{BBbAf}00{{BBhBl}BBh}0011{{}}{{}Bn}00000002{{}c{}}0000000{BBdBl}{BBbBl}0100{{{b{BBj}}}{{`{{Cj{}{{Cf{{E`{{b{B`}}Lf}}}}}}}}}}77{{{b{BBl}}}{{b{C`}}}}{{{Af{BC`}}Hf{Af{`}}{El{BBl}}}BAf}399{{BBh{Af{BBd}}}BBh}{{{b{BAh}}ADlCh}f}{BBbBBj}00{BBlB@j}0{{{b{BBl}}c}CbFb}{{{b{BAj}}}{{Af{{b{n}}}}}}22222{{BBh{Af{{El{BB`}}}}}BBh}0{bc{}}0000{bDb}0{c{{Cb{e}}}{}{}}0000000{{}{{Cb{c}}}{}}0000000{bFh}0000000?{{}c{}}0000000{BCbAf}{BCdAf}{BCfAf}`{BCbG`}{BCdG`}{BCfG`}`````{{}b}``````````````````{b{{b{n}}}}000{{{b{Jf}}}{{Af{{b{Ad}}}}}}{{{b{Eh}}}{{Af{{b{Ad}}}}}}{{{b{BCh}}}{{Af{{b{Ad}}}}}}{{{b{A@b}}}{{Af{{b{Ad}}}}}}{b{{b{c}}}{}}000{{{b{Aj}}}{{b{Ajc}}}{}}000{{{b{Jf}}}{{Af{{b{n}}}}}}{{{b{Eh}}}{{Af{{b{n}}}}}}{{{b{BCh}}}{{Af{{b{n}}}}}}{{{b{A@b}}}{{Af{{b{n}}}}}}{{}{{Bj{c}}}{}}000{{{b{Aj}}}{{Bj{{b{Ajc}}}}}{}}000{b{{Bj{{b{c}}}}}{}}000{DlGf}{Bn{{b{c}}}{}}000{Bn{{b{Ajc}}}{}}000{{{b{Jf}}}{{b{C`}}}}{{{b{Eh}}}{{b{C`}}}}{{{b{BCh}}}{{b{C`}}}}{{{b{A@b}}}{{b{C`}}}}{Bnf}000{{{b{Jf}}{b{AjCn}}}{{Cb{fD`}}}}0{{{b{Eh}}{b{AjCn}}}{{Cb{fD`}}}}0{{{b{BCh}}{b{AjCn}}}{{Cb{fD`}}}}0{{{b{A@b}}{b{AjCn}}}{{Cb{fD`}}}}0{BCjJf}{cc{}}000{{{b{C`}}}{{Cb{hEh}}}}{{}}000{{}Bn}000{{}c{}}000{Dlh}{{{b{Jf}}}{{Af{{b{n}}}}}}{{{b{Eh}}}{{Af{{b{n}}}}}}{{{b{BCh}}}{{Af{{b{n}}}}}}{{{b{A@b}}}{{Af{{b{n}}}}}}{bDb}000{{{b{BCl}}}Db}{c{{Cb{e}}}{}{}}000{{}{{Cb{c}}}{}}000{bFh}000{{}c{}}000{BCnAf}{BD`Af}{BDbAf}{BD`Bn}{BCnBDd}{BDbDh}{BCnG`}{BD`G`}{BDbG`}{BDfAf}{BDhAf}{BDfBCj}{BDhBDj}{BDfG`}{BDhG`}{BDlAf}{BDnAf}{BE`Af}{BDlI`}{BDnI`}{BE`BEb}{BDlG`}{BDnG`}{BE`G`}{K`Af}{KbAf}{KdAf}{KfAf}{KhAf}{KjAf}{KbDb}{KhDb}{KdBn}{K`Db}{KfKl}{KjI`}{K`G`}{KbG`}{KdG`}{KfG`}{KhG`}{KjG`}`````````{{bd}f}0{{{b{BEd}}AAd}{{`{{A@f{}{{BEf{{Cb{fBEh}}}}}}Ib}}}}{{BEjce}BEj{{BEl{{A`{j}}}}}BEd}{{{b{{BEn{c}}}}AAd}{{Cb{fBEh}}}{BEdBF`}}{b{{b{n}}}}{{{b{BEh}}}{{Af{{b{Ad}}}}}}{b{{b{c}}}{}}000{{{b{Aj}}}{{b{Ajc}}}{}}000{A@jBEj}{{{b{BEh}}}{{Af{{b{n}}}}}}{{{b{BFb}}}BFb}{{{b{{BEn{c}}}}}{{BEn{c}}}{BF`BEdBF`}}{{b{b{Ajc}}}f{}}0{{bj}f}0{{}{{Bj{c}}}{}}000{{{b{Aj}}}{{Bj{{b{Ajc}}}}}{}}000{b{{Bj{{b{c}}}}}{}}000{Bn{{b{c}}}{}}000{Bn{{b{Ajc}}}{}}000{{{b{BEh}}}{{b{C`}}}}{Bnf}000{{{b{BFb}}}{{b{A@j}}}}{{{b{BEj}}}{{b{A@j}}}}{{{b{BFb}}{b{AjCn}}}Hh}{{{b{BEj}}{b{AjCn}}}Hh}{{{b{BEh}}{b{AjCn}}}Hh}0{{{b{{BEn{c}}}}{b{AjCn}}}Hh{BFdBEdBF`}}{cc{}}0{{{I`{n}}}BEh}{AFbBEh}{ALfBEh}3{ACjBEh}{AAbBEh}5{cBEh{nIbId}}{{{b{c}}}c{}}0{{}}{{}Bn}000{{}c{}}000{{{b{BFb}}}Bl}{A@jBEj}{{ce}{{BEn{c}}}{BEdBF`}{{BFf{J`}{{BEf{Bl}}}}IbId}}{{{b{BEd}}AA`}{{`{{A@f{}{{BEf{{Cb{AAdBEh}}}}}}Ib}}}}{{{b{{BEn{c}}}}AA`}{{`{{A@f{}{{BEf{{Cb{AAdBEh}}}}}}Ib}}}{BEdBF`}}{{{b{BEd}}}{{`{{A@f{}{{BEf{f}}}}Ib}}}}{{{b{BFb}}}{{Cb{fBFh}}}}{{{b{{BEn{c}}}}}{{`{{A@f{}{{BEf{f}}}}Ib}}}{BEdBF`}}{{{b{BEh}}}{{Af{{b{n}}}}}}{BEjBFb}{bc{}}0{bDb}{c{{Cb{e}}}{}{}}000{{}{{Cb{c}}}{}}000{bFh}000{{}c{}}000{BFjAf}{BFjAAb}{BFlACj}{BFnI`}{BFjG`}``{b{{b{c}}}{}}0{{{b{Aj}}}{{b{Ajc}}}{}}0{{}{{Bj{c}}}{}}0{{{b{Aj}}}{{Bj{{b{Ajc}}}}}{}}0{b{{Bj{{b{c}}}}}{}}0{Bn{{b{c}}}{}}0{Bn{{b{Ajc}}}{}}0{{{b{BG`}}Al}Gb}{{{b{BG`}}}Hf}{Bnf}0{{{b{BGb}}{b{AjCn}}}Hh}{{{b{BG`}}{b{AjCn}}}Hh}{cc{}}0{{}Bn}0{{}c{}}0{BG`Ch}{BG`Db}{{{b{BG`}}{b{J`}}Lf}{{BGd{f}}}}{BG`Ed}{{}{{BGd{BG`}}}}{{}{{Cb{{E`{BdB`BGf}}BGh}}}}{{{Af{BGj}}Bl}{{Cb{{E`{BdB`BGf}}BGh}}}}1{Db{{BGd{BG`}}}}{c{{Cb{e}}}{}{}}0{{}{{Cb{c}}}{}}0{bFh}0{{}c{}}0","D":"GHn","p":[[1,"reference",null,null,1],[5,"Private",3884],[1,"unit"],[5,"PublicKey",0,3885],[1,"u8"],[1,"array"],[10,"Error",3886],[1,"slice"],[6,"KeyParsingError",0,3885],[5,"Backtrace",3887],[6,"Option",3888,null,1],[5,"RelayUrlParseError",0,3889],[0,"mut"],[5,"SecretKey",0,3885],[5,"NodeAddr",0,3890],[5,"RelayUrl",0,3889],[6,"RelayProtocol",0],[5,"RelayMap",0,3891],[5,"RelayNode",0,3891],[6,"Ordering",3892],[5,"Compat",3893],[1,"bool"],[1,"usize"],[1,"str"],[6,"Result",3894,null,1],[10,"Deserializer",3895],[17,"Item"],[6,"SocketAddr",3896],[10,"Iterator",3897],[5,"BTreeSet",3898],[5,"Formatter",3899],[5,"Error",3899],[5,"String",3900],[5,"VerifyingKey",3901],[5,"DecodeError",3902],[5,"Error",3903],[5,"SigningKey",3904],[5,"NodeInfo",3652,3905],[5,"NodeTicket",3906],[1,"tuple",null,null,1],[5,"RemoteInfo",1123,3907],[5,"Url",3908],[10,"IntoIterator",3909],[6,"DecodingError",3653,3905],[10,"CryptoRngCore",3910],[5,"Arc",3911,null,1],[10,"Hasher",3912],[5,"HeaderValue",3913],[10,"Serializer",3914],[5,"Signature",3915],[1,"u16"],[5,"TypeId",3916],[15,"Decode",349],[15,"Key",349],[15,"DecodeInvalidLength",349],[5,"SpanTrace",3917],[5,"ConcurrentDiscovery",3652],[10,"Discovery",3652],[5,"NodeData",3652,3905],[5,"UserData",3652,3905],[6,"ParseError",3652,3905],[6,"IntoDiscoveryError",3652],[6,"DiscoveryError",3652],[5,"Lagged",3652],[5,"DiscoveryItem",3652],[5,"DiscoveryContext",3652],[5,"DnsResolver",1080,3918],[8,"Result",3899],[6,"IrohAttr",3905],[5,"TxtAttrs",3905],[6,"PkarrError",820],[5,"Box",3919,null,1],[10,"Send",3920],[10,"Sync",3920],[5,"SignedPacket",3921],[5,"Vec",3922],[5,"TxtLookup",3918],[10,"IntoDiscovery",3652],[1,"u64"],[8,"NodeId",0,3885],[8,"Boxed",3923],[1,"u32"],[6,"EncodingError",3653,3905],[15,"NoServiceConfigured",704],[15,"NoResults",704],[15,"User",704],[15,"User",713],[15,"UnexpectedFormat",3702],[15,"AttrFromString",3702],[15,"NumLabels",3702],[15,"Utf8",3702],[15,"NotAnIrohRecord",3702],[15,"DecodingError",3702],[5,"Utf8Error",3924],[5,"DnsDiscoveryBuilder",735],[5,"DnsDiscovery",735],[5,"MdnsDiscoveryBuilder",778],[5,"MdnsDiscovery",778],[5,"Duration",3925],[5,"PkarrPublisherBuilder",820],[5,"PkarrPublisher",820],[5,"PkarrResolverBuilder",820],[5,"PkarrResolver",820],[5,"PkarrRelayClient",820],[15,"PublicKey",981],[6,"PublicKeyError",3926],[15,"Verify",981],[6,"SignedPacketVerifyError",3921],[15,"HttpSend",981],[5,"Error",3927],[15,"HttpPayload",981],[15,"Encoding",981],[15,"HttpRequest",981],[5,"StatusCode",3928],[15,"InvalidRelayUrl",981],[5,"Builder",988],[5,"DhtDiscovery",988],[5,"Client",3929],[5,"StaticProvider",1046],[10,"Into",3930,null,1],[8,"Result",3931],[5,"TokioRuntimeProvider",3932],[5,"GenericConnector",3933],[5,"Resolver",3934],[6,"IpAddr",3935],[6,"DnsError",3918],[10,"ToString",3900],[5,"StaggeredError",3918],[6,"LookupError",3653,3905],[5,"Name",3936],[10,"Future",3937,null,1],[5,"Pin",3938],[5,"Endpoint",1123],[5,"Accept",1123],[5,"Incoming",1123],[5,"Connecting",1123],[6,"ConnectionError",1123,3939],[5,"Connection",1123],[5,"AcceptBi",1123,3940],[5,"AcceptUni",1123,3940],[5,"ServerConfig",1123,3941],[5,"AckFrequencyConfig",1123,3942],[5,"VarInt",1123,3943],[5,"FrameStats",1123,3944],[5,"TransportConfig",1123,3942],[5,"Builder",1123],[6,"AddNodeAddrError",1123,3945],[5,"DirectAddrInfo",1123,3907],[5,"DirectAddr",1123,3945],[10,"HandshakeTokenKey",1123,3946],[10,"AeadKey",1123,3946],[6,"AlpnError",1123],[6,"ConnectWithOptsError",1123],[6,"ConnectError",1123],[6,"BindError",1123],[6,"GetMappingAddressError",1123],[5,"RemoteNodeIdError",1123],[5,"SocketAddrV4",3896],[5,"SocketAddrV6",3896],[5,"MtuDiscoveryConfig",1123,3942],[5,"PathStats",1123,3944],[10,"ControllerFactory",1123,3947],[5,"Instant",3948],[10,"Controller",1123,3947],[5,"Chunk",1123,3949],[5,"Bytes",3950],[5,"UdpStats",1123,3944],[5,"Written",1123,3951],[6,"SendDatagramError",1123,3940],[6,"ReadToEndError",1123,3952],[6,"ReadError",1123,3952],[6,"ResetError",1123,3952],[6,"ReadExactError",1123,3952],[6,"WriteError",1123,3953],[6,"StoppedError",1123,3953],[5,"ConnectionStats",1123,3944],[5,"ClosedStream",1123,3954],[6,"ControlMsg",1123,3907],[6,"ConnectionType",1123,3907],[6,"Source",1123,3955],[5,"ConnectionClose",1123,3956],[5,"ApplicationClose",1123,3956],[5,"TransportError",1123],[5,"TransportErrorCode",1123],[5,"StreamId",1123,3957],[6,"DirectAddrType",1123,3945],[6,"PathSelection",1123],[5,"ConnectOptions",1123],[6,"RelayMode",1123],[5,"Direct",3958],[5,"UnexpectedEnd",3959],[10,"Buf",3960],[6,"Dir",3957],[10,"Stream",3961],[5,"RecvStream",1123,3952],[5,"SendStream",1123,3953],[10,"BufMut",3962],[5,"ExportKeyingMaterialError",1123,3946],[5,"WeakConnectionHandle",1123,3940],[5,"RetryError",1123,3963],[5,"CryptoError",1123,3946],[5,"UnsupportedVersion",1123,3946],[5,"IncomingFuture",1123],[5,"ZeroRttAccepted",1123],[6,"ReadableError",3964],[6,"Close",3956],[5,"Unspecified",3965],[6,"Error",3966],[5,"InvalidFrame",3956],[5,"VarIntBoundsExceeded",3943],[10,"Any",3916],[17,"Value"],[10,"Watcher",3958],[10,"CryptoServerConfig",1123],[5,"ConnectionId",3967],[5,"Keys",3946],[6,"Side",3957],[5,"Incoming",3963],[5,"IdleTimeout",3942],[5,"EndpointMetrics",3125],[5,"RttEstimator",3968],[5,"OpenBi",1123,3940],[5,"OpenUni",1123,3940],[5,"Context",3969],[6,"Poll",3970],[5,"ReadDatagram",1123,3940],[5,"Error",3971],[5,"ReadBuf",3972],[1,"i32"],[5,"HashMap",3973],[5,"TransportParameters",3966],[10,"Session",3946],[10,"TimeSource",3941],[1,"f32"],[1,"u128"],[5,"ValidationTokenConfig",3941],[5,"CertificateDer",3974],[6,"PrivateKeyDer",3974],[6,"Error",3975],[15,"Empty",3078],[15,"EmptyPruned",3078],[15,"OwnAddress",3078],[15,"ConnectionError",3085],[15,"Unavailable",3085],[15,"UnknownHandshake",3085],[15,"MagicSpawn",3092],[15,"Discovery",3092],[15,"Connect",3098],[15,"Connection",3098],[15,"AddNodeAddr",3104],[15,"SelfConnect",3104],[15,"NoAddress",3104],[15,"Quinn",3104],[6,"ConnectError",3976],[15,"DiscoveryStart",3115],[15,"Discover",3115],[15,"NoAddress",3115],[15,"Discovery",3123],[15,"NamedApp",3123],[5,"RelayMetrics",3125],[5,"Counter",3977],[5,"MagicsockMetrics",3125],[10,"Iterable",3978],[5,"PortmapMetrics",3125],[5,"MetricItem",3979],[10,"MetricsGroup",3979],[5,"Client",3305],[5,"Addr",3305],[6,"ReportError",3305],[6,"IpFamily",3980],[5,"CancellationToken",3981],[5,"UdpSocket",3982],[5,"Report",3305],[5,"QuicConfig",3305,3983],[5,"ClientConfig",3984],[5,"Options",3305,3985],[5,"RelayLatencies",3305],[5,"Metrics",3305,3986],[5,"Endpoint",3987],[5,"Client",3988],[15,"Abort",3546],[15,"AlreadyRunning",3546],[15,"ActorGone",3546],[5,"MaxLengthExceededError",3653,3905],[6,"SignedPacketBuildError",3921],[10,"NodeIdExt",3653,3905],[15,"InvalidEncodingZ32",3678],[15,"InvalidLength",3678],[15,"InvalidSignature",3678],[6,"Z32Error",3989],[15,"FailedBuildingPacket",3687],[15,"InvalidTxtEntry",3687],[6,"SimpleDnsError",3990],[15,"ParseError",3693],[15,"LookupFailed",3693],[15,"InvalidLabel",3693],[5,"ProtoError",3991],[10,"ProtocolHandler",3720],[17,"Output"],[6,"AcceptError",3720],[5,"RouterBuilder",3720],[10,"AsRef",3930],[5,"AccessLimit",3720],[10,"Clone",3992],[5,"Router",3720],[10,"Debug",3899],[10,"Fn",3993],[5,"JoinError",3994],[15,"Connection",3834],[15,"MissingRemoteNodeId",3834],[15,"User",3834],[5,"DnsPkarrServer",3839,3995],[5,"CleanupDropGuard",3839],[8,"Result",3971],[5,"Server",3996],[6,"SpawnError",3996],[5,"StunConfig",3996]],"r":[[0,3885],[1,3885],[2,1123],[3,3885],[4,3885],[5,3885],[6,3890],[7,3885],[8,3885],[10,3891],[11,1123],[12,3891],[14,3889],[15,3889],[16,3885],[18,3885],[19,3885],[20,3890],[21,3889],[23,3891],[24,3891],[25,3885],[26,3885],[27,3889],[28,3885],[29,3885],[30,3889],[31,3885],[32,3885],[33,3885],[34,3885],[35,3890],[36,3889],[37,3889],[39,3891],[40,3891],[41,3885],[42,3885],[43,3885],[44,3890],[45,3889],[46,3889],[48,3891],[49,3891],[50,3885],[51,3889],[52,3885],[53,3885],[54,3890],[55,3889],[57,3891],[58,3891],[59,3885],[60,3885],[61,3890],[62,3889],[64,3891],[65,3891],[66,3885],[67,3885],[68,3890],[69,3889],[71,3891],[72,3891],[73,3885],[74,3890],[75,3889],[76,3891],[77,3885],[78,3890],[79,3889],[80,3891],[81,3885],[82,3885],[83,3885],[84,3890],[85,3889],[86,3889],[88,3891],[89,3891],[90,3885],[91,3885],[92,3885],[93,3890],[94,3889],[95,3889],[97,3891],[98,3891],[99,3885],[100,3885],[101,3885],[102,3890],[103,3889],[104,3889],[106,3891],[107,3891],[108,3891],[111,3885],[112,3885],[113,3885],[114,3890],[115,3889],[116,3889],[117,3889],[119,3891],[120,3891],[121,3885],[122,3885],[123,3885],[124,3890],[125,3889],[126,3889],[128,3891],[129,3891],[130,3885],[131,3889],[132,3885],[133,3885],[134,3890],[135,3889],[136,3891],[137,3890],[138,3890],[141,3885],[142,3885],[143,3885],[144,3890],[145,3889],[146,3889],[148,3891],[149,3891],[150,3891],[152,3885],[153,3890],[154,3889],[156,3891],[157,3891],[158,3885],[159,3885],[160,3885],[161,3890],[162,3890],[163,3890],[164,3889],[165,3889],[166,3889],[170,3891],[171,3891],[172,3891],[173,3891],[174,3891],[175,3891],[176,3885],[177,3885],[178,3885],[179,3885],[180,3885],[181,3885],[182,3890],[183,3889],[184,3889],[185,3889],[186,3889],[188,3891],[189,3891],[190,3891],[191,3891],[192,3885],[193,3885],[194,3885],[195,3885],[196,3885],[197,3885],[198,3885],[199,3885],[200,3885],[201,3890],[202,3890],[203,3890],[204,3890],[205,3890],[206,3890],[207,3889],[208,3889],[209,3889],[211,3891],[212,3891],[213,3891],[214,3891],[215,3891],[216,3885],[217,3885],[218,3891],[219,3891],[220,3890],[221,3885],[222,3885],[223,3890],[224,3889],[226,3891],[227,3891],[228,3885],[229,3885],[230,3889],[231,3885],[232,3885],[233,3891],[234,3885],[235,3889],[236,3885],[237,3889],[238,3885],[239,3885],[240,3885],[241,3890],[242,3889],[243,3889],[245,3891],[246,3891],[247,3885],[248,3885],[249,3885],[250,3890],[251,3889],[252,3889],[254,3891],[255,3891],[256,3890],[257,3891],[258,3891],[261,3890],[262,3890],[263,3997],[264,3891],[266,3885],[267,3890],[268,3889],[269,3891],[271,3885],[272,3885],[273,3891],[274,3890],[275,3890],[276,3885],[277,3885],[278,3885],[279,3890],[280,3889],[281,3891],[282,3885],[283,3885],[284,3889],[285,3891],[286,3891],[288,3885],[289,3885],[290,3885],[291,3890],[292,3889],[294,3891],[295,3891],[296,3885],[297,3885],[298,3885],[299,3889],[300,3889],[301,3891],[302,3891],[303,3885],[304,3885],[305,3885],[306,3885],[307,3885],[308,3885],[309,3885],[310,3890],[311,3889],[312,3889],[314,3891],[315,3891],[316,3885],[317,3885],[318,3885],[319,3890],[320,3889],[321,3889],[323,3891],[324,3891],[325,3885],[326,3885],[327,3885],[328,3890],[329,3889],[330,3889],[332,3891],[333,3891],[335,3891],[336,3891],[337,3885],[338,3885],[339,3885],[340,3885],[341,3890],[342,3889],[343,3889],[345,3891],[346,3891],[347,3890],[348,3890],[360,3998],[361,3998],[376,3905],[378,3905],[386,3905],[389,3905],[390,3905],[391,3905],[392,3905],[393,3905],[394,3905],[397,3905],[398,3905],[399,3905],[400,3905],[401,3905],[404,3905],[405,3905],[409,3905],[410,3905],[414,3905],[415,3905],[416,3905],[417,3905],[424,3905],[425,3905],[426,3905],[427,3905],[434,3905],[438,3905],[439,3905],[440,3905],[441,3905],[443,3905],[444,3905],[445,3905],[447,3905],[448,3905],[449,3905],[451,3905],[452,3905],[453,3905],[454,3905],[455,3905],[456,3905],[463,3905],[464,3905],[465,3905],[466,3905],[473,3905],[474,3905],[475,3905],[476,3905],[483,3905],[484,3905],[486,3905],[487,3905],[488,3905],[489,3905],[490,3905],[498,3905],[499,3905],[500,3905],[501,3905],[502,3905],[509,3905],[513,3905],[516,3905],[517,3905],[518,3905],[519,3905],[527,3905],[528,3905],[529,3905],[530,3905],[531,3905],[532,3905],[533,3905],[534,3905],[535,3905],[536,3905],[537,3905],[538,3905],[539,3905],[540,3905],[541,3905],[542,3905],[543,3905],[544,3905],[554,3905],[555,3905],[556,3905],[557,3905],[558,3905],[559,3905],[560,3905],[561,3905],[562,3905],[563,3905],[576,3905],[577,3905],[578,3905],[579,3905],[580,3905],[583,3905],[584,3905],[585,3905],[586,3905],[590,3905],[591,3905],[592,3905],[593,3905],[600,3905],[601,3905],[602,3905],[603,3905],[612,3905],[616,3905],[617,3905],[621,3905],[623,3905],[628,3905],[632,3905],[633,3905],[634,3905],[641,3905],[643,3905],[644,3905],[645,3905],[647,3905],[648,3905],[649,3905],[653,3905],[654,3905],[655,3905],[656,3905],[657,3905],[658,3905],[665,3905],[666,3905],[667,3905],[668,3905],[675,3905],[676,3905],[677,3905],[678,3905],[685,3905],[688,3905],[689,3905],[690,3905],[691,3905],[698,3905],[699,3905],[700,3905],[701,3905],[702,3905],[703,3905],[737,3918],[738,3918],[1080,3918],[1081,3918],[1082,3918],[1083,3918],[1084,3918],[1085,3918],[1086,3918],[1087,3918],[1088,3918],[1089,3918],[1090,3918],[1091,3918],[1092,3918],[1093,3918],[1094,3918],[1095,3918],[1096,3918],[1097,3918],[1098,3918],[1099,3918],[1100,3918],[1101,3918],[1102,3918],[1103,3918],[1104,3918],[1105,3918],[1106,3918],[1107,3918],[1108,3918],[1109,3918],[1110,3918],[1111,3918],[1112,3918],[1113,3918],[1114,3918],[1115,3918],[1116,3918],[1117,3918],[1118,3918],[1119,3918],[1120,3918],[1121,3918],[1122,3918],[1126,3940],[1127,3940],[1128,3942],[1130,3945],[1131,3946],[1134,3955],[1135,3956],[1136,3939],[1142,3907],[1143,3949],[1144,3939],[1145,3954],[1146,3952],[1147,3953],[1155,3956],[1156,3939],[1157,3939],[1159,3940],[1160,3952],[1161,3952],[1162,3953],[1163,3953],[1164,3944],[1165,3907],[1166,3907],[1167,3947],[1168,3947],[1169,3946],[1173,3907],[1174,3945],[1175,3907],[1176,3945],[1177,3940],[1180,3955],[1184,3945],[1185,3945],[1187,3946],[1191,3952],[1192,3944],[1194,3946],[1197,3952],[1201,3945],[1202,3939],[1203,3943],[1204,3943],[1206,3907],[1207,3942],[1210,3955],[1213,3907],[1214,3940],[1215,3940],[1216,3945],[1219,3944],[1220,3907],[1221,3907],[1222,3945],[1224,3952],[1225,3940],[1226,3952],[1227,3952],[1228,3952],[1229,3952],[1230,3952],[1231,3907],[1232,3955],[1235,3907],[1237,3952],[1238,3939],[1239,3952],[1240,3963],[1243,3955],[1245,3940],[1246,3953],[1247,3941],[1248,3955],[1250,3953],[1251,3953],[1252,3957],[1253,3945],[1254,3945],[1256,3939],[1257,3940],[1258,3952],[1259,3942],[1261,3939],[1263,3955],[1264,3944],[1266,3945],[1268,3940],[1269,3946],[1270,3943],[1271,3939],[1272,3940],[1273,3953],[1274,3951],[1276,3952],[1277,3952],[1278,3953],[1279,3953],[1280,3940],[1281,3952],[1282,3952],[1283,3952],[1284,3952],[1285,3953],[1286,3953],[1287,3943],[1288,3944],[1289,3944],[1290,3944],[1291,3944],[1292,3951],[1293,3954],[1294,3907],[1295,3907],[1296,3907],[1297,3907],[1298,3955],[1299,3939],[1300,3942],[1301,3942],[1302,3941],[1303,3956],[1304,3956],[1307,3957],[1308,3945],[1309,3945],[1320,3942],[1321,3944],[1322,3942],[1323,3944],[1327,3907],[1328,3945],[1329,3907],[1330,3946],[1331,3942],[1335,3940],[1336,3963],[1337,3952],[1338,3952],[1339,3952],[1340,3952],[1341,3953],[1342,3953],[1343,3954],[1344,3939],[1346,3945],[1353,3945],[1363,3942],[1364,3944],[1365,3940],[1366,3940],[1367,3940],[1368,3940],[1369,3940],[1370,3940],[1371,3940],[1372,3963],[1373,3952],[1374,3952],[1375,3952],[1376,3952],[1377,3952],[1378,3953],[1379,3953],[1380,3953],[1381,3942],[1382,3943],[1383,3949],[1384,3944],[1385,3944],[1386,3944],[1387,3944],[1388,3951],[1389,3954],[1390,3907],[1391,3907],[1392,3907],[1393,3907],[1394,3955],[1395,3939],[1396,3942],[1397,3942],[1398,3941],[1399,3946],[1400,3946],[1401,3946],[1402,3956],[1403,3956],[1406,3945],[1407,3957],[1408,3945],[1409,3945],[1427,3940],[1428,3940],[1429,3940],[1430,3940],[1431,3940],[1432,3940],[1433,3940],[1434,3963],[1435,3952],[1436,3952],[1437,3952],[1438,3952],[1439,3952],[1440,3953],[1441,3953],[1442,3953],[1443,3942],[1444,3943],[1445,3949],[1446,3944],[1447,3944],[1448,3944],[1449,3944],[1450,3951],[1451,3954],[1452,3907],[1453,3907],[1454,3907],[1455,3907],[1456,3955],[1457,3939],[1458,3942],[1459,3942],[1460,3941],[1461,3946],[1462,3946],[1463,3946],[1464,3956],[1465,3956],[1468,3945],[1469,3957],[1470,3945],[1471,3945],[1490,3947],[1492,3949],[1493,3944],[1494,3951],[1495,3945],[1502,3951],[1504,3940],[1505,3952],[1506,3952],[1507,3952],[1508,3952],[1509,3953],[1510,3953],[1511,3943],[1512,3944],[1513,3944],[1514,3944],[1515,3944],[1516,3951],[1517,3954],[1518,3907],[1519,3907],[1520,3907],[1521,3907],[1522,3955],[1523,3939],[1524,3942],[1525,3942],[1526,3941],[1527,3956],[1528,3956],[1531,3957],[1532,3945],[1533,3945],[1539,3947],[1540,3940],[1541,3952],[1542,3952],[1543,3952],[1544,3952],[1545,3953],[1546,3953],[1547,3943],[1548,3944],[1549,3944],[1550,3944],[1551,3944],[1552,3951],[1553,3954],[1554,3907],[1555,3907],[1556,3907],[1557,3907],[1558,3955],[1559,3939],[1560,3942],[1561,3942],[1562,3941],[1563,3956],[1564,3956],[1567,3957],[1568,3945],[1569,3945],[1575,3940],[1576,3952],[1577,3952],[1578,3952],[1579,3952],[1580,3953],[1581,3953],[1582,3943],[1583,3944],[1584,3944],[1585,3944],[1586,3944],[1587,3951],[1588,3954],[1589,3907],[1590,3907],[1591,3907],[1592,3907],[1593,3955],[1594,3939],[1595,3942],[1596,3942],[1597,3941],[1598,3956],[1599,3956],[1602,3957],[1603,3945],[1604,3945],[1614,3943],[1615,3957],[1616,3945],[1617,3945],[1619,3943],[1620,3957],[1621,3945],[1622,3945],[1623,3940],[1624,3940],[1625,3940],[1626,3940],[1627,3940],[1628,3940],[1629,3940],[1630,3963],[1631,3952],[1632,3952],[1633,3952],[1634,3952],[1635,3952],[1636,3953],[1637,3953],[1638,3953],[1639,3942],[1640,3943],[1641,3949],[1642,3944],[1643,3944],[1644,3944],[1645,3944],[1646,3951],[1647,3954],[1648,3907],[1649,3907],[1650,3907],[1651,3907],[1652,3955],[1653,3939],[1654,3942],[1655,3942],[1656,3941],[1657,3946],[1658,3946],[1659,3946],[1660,3956],[1661,3956],[1664,3945],[1665,3957],[1666,3945],[1667,3945],[1685,3940],[1686,3940],[1687,3940],[1688,3940],[1689,3940],[1690,3940],[1691,3940],[1692,3963],[1693,3952],[1694,3952],[1695,3952],[1696,3952],[1697,3952],[1698,3953],[1699,3953],[1700,3953],[1701,3942],[1702,3943],[1703,3949],[1704,3944],[1705,3944],[1706,3944],[1707,3944],[1708,3951],[1709,3954],[1710,3907],[1711,3907],[1712,3907],[1713,3907],[1714,3955],[1715,3939],[1716,3942],[1717,3942],[1718,3941],[1719,3946],[1720,3946],[1721,3946],[1722,3956],[1723,3956],[1726,3945],[1727,3957],[1728,3945],[1729,3945],[1747,3940],[1748,3940],[1749,3940],[1750,3940],[1751,3940],[1752,3940],[1753,3940],[1754,3963],[1755,3952],[1756,3952],[1757,3952],[1758,3952],[1759,3952],[1760,3953],[1761,3953],[1762,3953],[1763,3942],[1764,3943],[1765,3949],[1766,3944],[1767,3944],[1768,3944],[1769,3944],[1770,3951],[1771,3954],[1772,3907],[1773,3907],[1774,3907],[1775,3907],[1776,3955],[1777,3939],[1778,3942],[1779,3942],[1780,3941],[1781,3946],[1782,3946],[1783,3946],[1784,3956],[1785,3956],[1788,3945],[1789,3957],[1790,3945],[1791,3945],[1809,3942],[1810,3944],[1813,3907],[1816,3944],[1818,3944],[1819,3941],[1820,3942],[1821,3944],[1822,3944],[1823,3944],[1824,3944],[1825,3942],[1826,3942],[1828,3944],[1829,3943],[1831,3957],[1832,3942],[1833,3943],[1834,3944],[1835,3944],[1836,3944],[1837,3944],[1838,3951],[1839,3954],[1840,3907],[1841,3942],[1842,3942],[1847,3940],[1848,3940],[1849,3940],[1850,3940],[1851,3940],[1852,3940],[1853,3940],[1854,3963],[1855,3952],[1856,3952],[1857,3952],[1858,3952],[1859,3952],[1860,3953],[1861,3953],[1862,3953],[1863,3942],[1864,3943],[1865,3949],[1866,3944],[1867,3944],[1868,3944],[1869,3944],[1870,3951],[1871,3954],[1872,3907],[1873,3907],[1874,3907],[1875,3907],[1876,3955],[1877,3939],[1878,3942],[1879,3942],[1880,3941],[1881,3946],[1882,3946],[1883,3946],[1884,3956],[1885,3956],[1888,3945],[1889,3957],[1890,3945],[1891,3945],[1909,3940],[1910,3940],[1911,3940],[1912,3940],[1913,3940],[1914,3940],[1915,3940],[1916,3963],[1917,3952],[1918,3952],[1919,3952],[1920,3952],[1921,3952],[1922,3953],[1923,3953],[1924,3953],[1925,3942],[1926,3943],[1927,3949],[1928,3944],[1929,3944],[1930,3944],[1931,3944],[1932,3951],[1933,3954],[1934,3907],[1935,3907],[1936,3907],[1937,3907],[1938,3955],[1939,3939],[1940,3942],[1941,3942],[1942,3941],[1943,3946],[1944,3946],[1945,3946],[1946,3956],[1947,3956],[1950,3945],[1951,3957],[1952,3945],[1953,3945],[1971,3945],[1978,3907],[1979,3907],[1980,3907],[1981,3907],[1982,3955],[1983,3957],[1993,3940],[1994,3940],[1995,3940],[1996,3940],[1997,3940],[1998,3940],[1999,3940],[2000,3963],[2001,3952],[2002,3952],[2003,3952],[2004,3952],[2005,3952],[2006,3952],[2007,3953],[2008,3953],[2009,3953],[2010,3953],[2011,3942],[2012,3943],[2013,3949],[2014,3944],[2015,3944],[2016,3944],[2017,3944],[2018,3951],[2019,3954],[2020,3907],[2021,3907],[2022,3907],[2023,3907],[2024,3955],[2025,3939],[2026,3942],[2027,3942],[2028,3941],[2029,3946],[2030,3946],[2031,3946],[2032,3956],[2033,3956],[2036,3945],[2037,3957],[2038,3945],[2039,3945],[2057,3942],[2058,3943],[2060,3957],[2061,3940],[2062,3952],[2063,3952],[2064,3952],[2065,3952],[2066,3953],[2067,3953],[2068,3943],[2069,3949],[2070,3951],[2071,3954],[2072,3907],[2073,3907],[2074,3907],[2075,3907],[2076,3955],[2077,3939],[2078,3946],[2079,3956],[2080,3956],[2083,3957],[2084,3945],[2085,3945],[2088,3940],[2089,3940],[2090,3940],[2091,3952],[2092,3952],[2093,3952],[2094,3952],[2095,3952],[2096,3952],[2097,3952],[2098,3952],[2099,3952],[2100,3952],[2101,3952],[2102,3952],[2103,3953],[2104,3953],[2105,3953],[2106,3953],[2107,3953],[2108,3953],[2109,3943],[2110,3943],[2111,3943],[2112,3949],[2113,3949],[2114,3949],[2115,3951],[2116,3951],[2117,3951],[2118,3954],[2119,3954],[2120,3954],[2121,3907],[2122,3907],[2123,3907],[2124,3907],[2125,3907],[2126,3907],[2127,3907],[2128,3907],[2129,3907],[2130,3907],[2131,3907],[2132,3907],[2133,3955],[2134,3955],[2135,3955],[2136,3939],[2137,3939],[2138,3939],[2139,3946],[2140,3946],[2141,3946],[2142,3956],[2143,3956],[2144,3956],[2145,3956],[2146,3956],[2147,3956],[2154,3957],[2155,3957],[2156,3957],[2157,3945],[2158,3945],[2159,3945],[2160,3945],[2161,3945],[2162,3945],[2169,3956],[2170,3956],[2172,3953],[2173,3940],[2174,3940],[2175,3940],[2176,3963],[2177,3963],[2178,3952],[2179,3952],[2180,3952],[2181,3952],[2182,3952],[2183,3952],[2184,3952],[2185,3952],[2186,3952],[2187,3953],[2188,3953],[2189,3953],[2190,3953],[2191,3953],[2192,3942],[2193,3943],[2194,3943],[2195,3949],[2196,3944],[2197,3944],[2198,3944],[2199,3944],[2200,3951],[2201,3954],[2202,3954],[2203,3907],[2204,3907],[2205,3907],[2206,3907],[2207,3907],[2208,3907],[2209,3955],[2210,3955],[2211,3939],[2212,3939],[2213,3942],[2214,3942],[2215,3941],[2216,3946],[2217,3946],[2218,3946],[2219,3956],[2220,3956],[2221,3956],[2222,3956],[2227,3945],[2228,3945],[2229,3957],[2230,3957],[2231,3945],[2232,3945],[2233,3945],[2259,3944],[2260,3944],[2261,3956],[2262,3940],[2263,3940],[2264,3940],[2265,3940],[2266,3940],[2267,3940],[2268,3940],[2269,3940],[2270,3963],[2271,3952],[2272,3952],[2273,3952],[2274,3952],[2275,3952],[2276,3952],[2277,3952],[2278,3952],[2279,3952],[2280,3952],[2281,3952],[2282,3953],[2283,3953],[2284,3953],[2285,3953],[2286,3953],[2287,3953],[2288,3953],[2289,3942],[2290,3943],[2291,3943],[2292,3943],[2293,3943],[2294,3943],[2295,3949],[2296,3944],[2297,3944],[2298,3944],[2299,3944],[2300,3951],[2301,3954],[2302,3907],[2303,3907],[2304,3907],[2305,3907],[2306,3955],[2307,3939],[2308,3939],[2309,3939],[2310,3942],[2311,3942],[2312,3941],[2313,3946],[2314,3946],[2315,3946],[2316,3946],[2317,3956],[2318,3956],[2319,3956],[2325,3945],[2326,3957],[2327,3957],[2328,3945],[2329,3945],[2352,3940],[2353,3952],[2354,3952],[2355,3952],[2356,3952],[2357,3953],[2358,3953],[2359,3943],[2360,3944],[2361,3944],[2362,3944],[2363,3944],[2364,3951],[2365,3954],[2366,3907],[2367,3907],[2368,3907],[2369,3907],[2370,3955],[2371,3939],[2372,3942],[2373,3942],[2374,3941],[2375,3956],[2376,3956],[2379,3957],[2380,3945],[2381,3945],[2387,3943],[2388,3943],[2389,3943],[2392,3944],[2393,3907],[2394,3943],[2395,3955],[2396,3957],[2397,3945],[2398,3945],[2400,3952],[2401,3953],[2403,3944],[2404,3940],[2405,3963],[2406,3952],[2407,3952],[2408,3952],[2409,3952],[2410,3953],[2411,3953],[2412,3954],[2413,3939],[2415,3945],[2422,3941],[2423,3941],[2424,3957],[2425,3940],[2426,3940],[2427,3940],[2428,3940],[2429,3940],[2430,3940],[2431,3940],[2432,3963],[2433,3952],[2434,3952],[2435,3952],[2436,3952],[2437,3952],[2438,3953],[2439,3953],[2440,3953],[2441,3942],[2442,3943],[2443,3949],[2444,3944],[2445,3944],[2446,3944],[2447,3944],[2448,3951],[2449,3954],[2450,3907],[2451,3907],[2452,3907],[2453,3907],[2454,3955],[2455,3939],[2456,3942],[2457,3942],[2458,3941],[2459,3946],[2460,3946],[2461,3946],[2462,3956],[2463,3956],[2466,3945],[2467,3957],[2468,3945],[2469,3945],[2488,3942],[2489,3942],[2490,3947],[2491,3957],[2493,3942],[2494,3940],[2495,3940],[2496,3940],[2497,3940],[2498,3940],[2499,3940],[2500,3940],[2501,3963],[2502,3952],[2503,3952],[2504,3952],[2505,3952],[2506,3952],[2507,3953],[2508,3953],[2509,3953],[2510,3942],[2511,3943],[2512,3949],[2513,3944],[2514,3944],[2515,3944],[2516,3944],[2517,3951],[2518,3954],[2519,3907],[2520,3907],[2521,3907],[2522,3907],[2523,3955],[2524,3939],[2525,3942],[2526,3942],[2527,3941],[2528,3946],[2529,3946],[2530,3946],[2531,3956],[2532,3956],[2535,3945],[2536,3957],[2537,3945],[2538,3945],[2557,3947],[2558,3940],[2559,3940],[2560,3940],[2561,3940],[2562,3940],[2568,3963],[2569,3943],[2570,3944],[2571,3952],[2572,3940],[2574,3942],[2577,3907],[2578,3907],[2579,3907],[2580,3907],[2581,3907],[2582,3907],[2583,3907],[2585,3944],[2586,3944],[2587,3944],[2588,3942],[2589,3942],[2590,3942],[2591,3944],[2593,3942],[2594,3941],[2595,3944],[2596,3944],[2597,3944],[2599,3941],[2600,3942],[2601,3942],[2602,3942],[2604,3940],[2605,3941],[2606,3957],[2608,3944],[2609,3944],[2612,3907],[2613,3944],[2614,3949],[2615,3947],[2616,3947],[2617,3947],[2618,3947],[2619,3947],[2620,3946],[2623,3942],[2624,3943],[2625,3957],[2626,3945],[2627,3945],[2628,3944],[2629,3944],[2630,3944],[2633,3942],[2634,3944],[2635,3940],[2636,3940],[2637,3940],[2638,3940],[2639,3940],[2644,3953],[2645,3952],[2646,3952],[2647,3953],[2648,3953],[2649,3953],[2650,3941],[2651,3941],[2652,3953],[2655,3952],[2656,3952],[2657,3952],[2659,3952],[2660,3952],[2661,3956],[2662,3956],[2664,3942],[2665,3942],[2666,3952],[2671,3907],[2677,3942],[2678,3953],[2679,3944],[2680,3944],[2683,3941],[2685,3944],[2686,3943],[2687,3946],[2691,3942],[2692,3942],[2693,3942],[2694,3944],[2695,3944],[2696,3907],[2697,3907],[2698,3907],[2699,3907],[2700,3955],[2704,3953],[2707,3940],[2708,3952],[2709,3952],[2710,3952],[2711,3952],[2712,3953],[2713,3953],[2714,3939],[2715,3945],[2722,3907],[2723,3907],[2727,3952],[2728,3944],[2729,3953],[2730,3944],[2731,3944],[2732,3942],[2733,3944],[2734,3944],[2735,3941],[2736,3942],[2737,3940],[2738,3952],[2739,3952],[2740,3952],[2741,3952],[2742,3953],[2743,3953],[2744,3943],[2745,3944],[2746,3944],[2747,3944],[2748,3944],[2749,3951],[2750,3954],[2751,3907],[2752,3907],[2753,3907],[2754,3907],[2755,3955],[2756,3939],[2757,3942],[2758,3942],[2759,3941],[2760,3956],[2761,3956],[2764,3957],[2765,3945],[2766,3945],[2772,3940],[2773,3963],[2774,3952],[2775,3952],[2776,3952],[2777,3952],[2778,3953],[2779,3953],[2780,3943],[2781,3954],[2782,3907],[2783,3907],[2784,3955],[2785,3939],[2786,3956],[2787,3956],[2790,3945],[2791,3957],[2792,3945],[2799,3941],[2800,3941],[2801,3941],[2803,3940],[2804,3940],[2805,3940],[2806,3940],[2807,3940],[2808,3940],[2809,3940],[2810,3963],[2811,3952],[2812,3952],[2813,3952],[2814,3952],[2815,3952],[2816,3953],[2817,3953],[2818,3953],[2819,3942],[2820,3943],[2821,3943],[2822,3943],[2823,3943],[2824,3949],[2825,3944],[2826,3944],[2827,3944],[2828,3944],[2829,3951],[2830,3954],[2831,3907],[2832,3907],[2833,3907],[2834,3907],[2835,3955],[2836,3939],[2837,3942],[2838,3942],[2839,3941],[2840,3946],[2841,3946],[2842,3946],[2843,3956],[2844,3956],[2847,3945],[2848,3957],[2849,3945],[2850,3945],[2868,3940],[2869,3940],[2870,3940],[2871,3940],[2872,3940],[2873,3940],[2874,3940],[2875,3963],[2876,3952],[2877,3952],[2878,3952],[2879,3952],[2880,3952],[2881,3953],[2882,3953],[2883,3953],[2884,3942],[2885,3943],[2886,3949],[2887,3944],[2888,3944],[2889,3944],[2890,3944],[2891,3951],[2892,3954],[2893,3907],[2894,3907],[2895,3907],[2896,3907],[2897,3955],[2898,3939],[2899,3942],[2900,3942],[2901,3941],[2902,3946],[2903,3946],[2904,3946],[2905,3956],[2906,3956],[2909,3945],[2910,3957],[2911,3945],[2912,3945],[2930,3940],[2931,3940],[2932,3940],[2933,3940],[2934,3940],[2937,3945],[2938,3940],[2939,3940],[2940,3940],[2941,3940],[2942,3940],[2943,3940],[2944,3940],[2945,3963],[2946,3952],[2947,3952],[2948,3952],[2949,3952],[2950,3952],[2951,3953],[2952,3953],[2953,3953],[2954,3942],[2955,3943],[2956,3949],[2957,3944],[2958,3944],[2959,3944],[2960,3944],[2961,3951],[2962,3954],[2963,3907],[2964,3907],[2965,3907],[2966,3907],[2967,3955],[2968,3939],[2969,3942],[2970,3942],[2971,3941],[2972,3946],[2973,3946],[2974,3946],[2975,3956],[2976,3956],[2979,3945],[2980,3957],[2981,3945],[2982,3945],[3000,3944],[3001,3944],[3002,3942],[3004,3941],[3005,3941],[3006,3940],[3007,3940],[3008,3940],[3009,3940],[3010,3940],[3011,3940],[3012,3940],[3013,3963],[3014,3952],[3015,3952],[3016,3952],[3017,3952],[3018,3952],[3019,3953],[3020,3953],[3021,3953],[3022,3942],[3023,3943],[3024,3949],[3025,3944],[3026,3944],[3027,3944],[3028,3944],[3029,3951],[3030,3954],[3031,3907],[3032,3907],[3033,3907],[3034,3907],[3035,3955],[3036,3939],[3037,3942],[3038,3942],[3039,3941],[3040,3946],[3041,3946],[3042,3946],[3043,3956],[3044,3956],[3047,3945],[3048,3957],[3049,3945],[3050,3945],[3068,3947],[3070,3941],[3071,3941],[3073,3953],[3074,3953],[3075,3953],[3076,3953],[3077,3953],[3310,3986],[3311,3985],[3312,3983],[3316,3983],[3317,3985],[3323,3986],[3325,3999],[3326,3986],[3327,3983],[3328,3985],[3334,3986],[3335,3983],[3336,3985],[3344,3983],[3345,3983],[3346,3985],[3350,3983],[3351,3985],[3355,3983],[3356,3985],[3360,3986],[3361,3983],[3362,3985],[3368,3986],[3369,3983],[3370,3985],[3376,3986],[3377,3983],[3378,3985],[3384,3986],[3385,3985],[3388,3986],[3389,3983],[3390,3985],[3396,3986],[3397,3983],[3398,3985],[3405,3986],[3406,3985],[3407,3986],[3408,3983],[3409,3985],[3415,3983],[3424,3986],[3425,3986],[3426,3986],[3427,3983],[3428,3985],[3436,3986],[3437,3983],[3438,3985],[3444,3983],[3445,3985],[3453,3985],[3454,3985],[3455,3985],[3459,3986],[3460,3983],[3461,3985],[3467,3985],[3468,3986],[3469,3983],[3470,3985],[3476,3983],[3479,3983],[3485,3986],[3490,3985],[3495,3986],[3496,3986],[3497,3986],[3499,3986],[3500,3986],[3501,3986],[3502,3986],[3503,3986],[3504,3985],[3505,3985],[3506,3983],[3507,3985],[3513,3986],[3514,3983],[3515,3985],[3521,3986],[3522,3983],[3523,3985],[3529,3986],[3530,3983],[3531,3985],[3538,3986],[3539,3983],[3540,3985],[3553,3905],[3554,3905],[3555,3905],[3556,3905],[3557,3905],[3558,3905],[3559,3905],[3560,3905],[3561,3905],[3562,3905],[3563,3905],[3564,3905],[3565,3905],[3566,3905],[3567,3905],[3568,3905],[3569,3905],[3570,3905],[3571,3905],[3572,3905],[3573,3905],[3574,3905],[3575,3905],[3576,3905],[3577,3905],[3578,3905],[3579,3905],[3580,3905],[3581,3905],[3582,3905],[3583,3905],[3584,3905],[3585,3905],[3586,3905],[3587,3905],[3588,3905],[3589,3905],[3590,3905],[3591,3905],[3592,3905],[3593,3905],[3594,3905],[3595,3905],[3596,3905],[3597,3905],[3598,3905],[3599,3905],[3600,3905],[3601,3905],[3602,3905],[3603,3905],[3604,3905],[3605,3905],[3606,3905],[3607,3905],[3608,3905],[3609,3905],[3610,3905],[3611,3905],[3612,3905],[3613,3905],[3614,3905],[3615,3905],[3616,3905],[3617,3905],[3618,3905],[3619,3905],[3620,3905],[3621,3905],[3622,3905],[3623,3905],[3624,3905],[3625,3905],[3626,3905],[3627,3905],[3628,3905],[3629,3905],[3630,3905],[3631,3905],[3632,3905],[3633,3905],[3634,3905],[3635,3905],[3636,3905],[3637,3905],[3638,3905],[3639,3905],[3640,3905],[3641,3905],[3642,3905],[3643,3905],[3644,3905],[3645,3905],[3646,3905],[3647,3905],[3648,3905],[3649,3905],[3650,3905],[3651,3905],[3652,3905],[3653,3905],[3654,3905],[3655,3905],[3656,3905],[3657,3905],[3658,3905],[3659,3905],[3660,3905],[3661,3905],[3662,3905],[3663,3905],[3664,3905],[3665,3905],[3666,3905],[3667,3905],[3668,3905],[3669,3905],[3670,3905],[3671,3905],[3672,3905],[3673,3905],[3674,3905],[3675,3905],[3676,3905],[3677,3905],[3840,3995],[3842,3995],[3844,3995],[3846,3995],[3848,3995],[3850,3995],[3852,3995],[3854,3995],[3855,3995],[3856,3995],[3858,3995],[3860,3995],[3862,3995],[3864,3995],[3866,3995],[3867,3995],[3868,3995],[3869,3995],[3870,3995],[3871,3995],[3875,3995],[3877,3995],[3879,3995],[3881,3995],[3883,3995]],"b":[[176,"impl-Debug-for-PublicKey"],[177,"impl-Display-for-PublicKey"],[178,"impl-Display-for-KeyParsingError"],[179,"impl-Debug-for-KeyParsingError"],[180,"impl-Debug-for-SecretKey"],[181,"impl-Display-for-SecretKey"],[183,"impl-Debug-for-RelayUrl"],[184,"impl-Display-for-RelayUrl"],[185,"impl-Display-for-RelayUrlParseError"],[186,"impl-Debug-for-RelayUrlParseError"],[188,"impl-Display-for-RelayMap"],[189,"impl-Debug-for-RelayMap"],[190,"impl-Debug-for-RelayNode"],[191,"impl-Display-for-RelayNode"],[195,"impl-From%3CDecodeError%3E-for-KeyParsingError"],[197,"impl-From%3CError%3E-for-KeyParsingError"],[198,"impl-From%3CSigningKey%3E-for-SecretKey"],[200,"impl-From%3C%5Bu8;+32%5D%3E-for-SecretKey"],[201,"impl-From%3CNodeInfo%3E-for-NodeAddr"],[202,"impl-From%3CNodeTicket%3E-for-NodeAddr"],[203,"impl-From%3CPublicKey%3E-for-NodeAddr"],[204,"impl-From%3C(PublicKey,+Option%3CRelayUrl%3E,+%26%5BSocketAddr%5D)%3E-for-NodeAddr"],[206,"impl-From%3CRemoteInfo%3E-for-NodeAddr"],[211,"impl-From%3CRelayNode%3E-for-RelayMap"],[212,"impl-From%3CRelayUrl%3E-for-RelayMap"],[218,"impl-FromIterator%3CRelayUrl%3E-for-RelayMap"],[219,"impl-FromIterator%3CRelayNode%3E-for-RelayMap"],[305,"impl-TryFrom%3C%26%5Bu8;+32%5D%3E-for-PublicKey"],[306,"impl-TryFrom%3C%26%5Bu8%5D%3E-for-PublicKey"],[540,"impl-Debug-for-UserData"],[541,"impl-Display-for-UserData"],[543,"impl-Debug-for-ParseError"],[544,"impl-Display-for-ParseError"],[546,"impl-Debug-for-IntoDiscoveryError"],[547,"impl-Display-for-IntoDiscoveryError"],[548,"impl-Debug-for-DiscoveryError"],[549,"impl-Display-for-DiscoveryError"],[552,"impl-Debug-for-Lagged"],[553,"impl-Display-for-Lagged"],[557,"impl-From%3C%26TxtAttrs%3CIrohAttr%3E%3E-for-NodeInfo"],[558,"impl-From%3CNodeAddr%3E-for-NodeInfo"],[559,"impl-From%3CDiscoveryItem%3E-for-NodeInfo"],[560,"impl-From%3CTxtAttrs%3CIrohAttr%3E%3E-for-NodeInfo"],[908,"impl-Display-for-PkarrError"],[909,"impl-Debug-for-PkarrError"],[2174,"impl-Debug-for-SendDatagramError"],[2175,"impl-Display-for-SendDatagramError"],[2176,"impl-Debug-for-RetryError"],[2177,"impl-Display-for-RetryError"],[2179,"impl-Display-for-ReadToEndError"],[2180,"impl-Debug-for-ReadToEndError"],[2181,"impl-Display-for-ReadError"],[2182,"impl-Debug-for-ReadError"],[2183,"impl-Debug-for-ResetError"],[2184,"impl-Display-for-ResetError"],[2185,"impl-Display-for-ReadExactError"],[2186,"impl-Debug-for-ReadExactError"],[2188,"impl-Debug-for-WriteError"],[2189,"impl-Display-for-WriteError"],[2190,"impl-Display-for-StoppedError"],[2191,"impl-Debug-for-StoppedError"],[2193,"impl-Debug-for-VarInt"],[2194,"impl-Display-for-VarInt"],[2201,"impl-Debug-for-ClosedStream"],[2202,"impl-Display-for-ClosedStream"],[2203,"impl-Display-for-ControlMsg"],[2204,"impl-Debug-for-ControlMsg"],[2207,"impl-Display-for-ConnectionType"],[2208,"impl-Debug-for-ConnectionType"],[2209,"impl-Display-for-Source"],[2210,"impl-Debug-for-Source"],[2211,"impl-Debug-for-ConnectionError"],[2212,"impl-Display-for-ConnectionError"],[2219,"impl-Display-for-ConnectionClose"],[2220,"impl-Debug-for-ConnectionClose"],[2221,"impl-Debug-for-ApplicationClose"],[2222,"impl-Display-for-ApplicationClose"],[2223,"impl-Debug-for-TransportError"],[2224,"impl-Display-for-TransportError"],[2225,"impl-Debug-for-TransportErrorCode"],[2226,"impl-Display-for-TransportErrorCode"],[2227,"impl-Debug-for-AddNodeAddrError"],[2228,"impl-Display-for-AddNodeAddrError"],[2229,"impl-Debug-for-StreamId"],[2230,"impl-Display-for-StreamId"],[2232,"impl-Debug-for-DirectAddrType"],[2233,"impl-Display-for-DirectAddrType"],[2237,"impl-Display-for-ConnectWithOptsError"],[2238,"impl-Debug-for-ConnectWithOptsError"],[2239,"impl-Display-for-ConnectError"],[2240,"impl-Debug-for-ConnectError"],[2241,"impl-Display-for-BindError"],[2242,"impl-Debug-for-BindError"],[2243,"impl-Display-for-GetMappingAddressError"],[2244,"impl-Debug-for-GetMappingAddressError"],[2250,"impl-Display-for-AlpnError"],[2251,"impl-Debug-for-AlpnError"],[2254,"impl-Display-for-RemoteNodeIdError"],[2255,"impl-Debug-for-RemoteNodeIdError"],[2274,"impl-From%3CResetError%3E-for-ReadError"],[2276,"impl-From%3CReadableError%3E-for-ReadError"],[2277,"impl-From%3CConnectionError%3E-for-ReadError"],[2283,"impl-From%3CStoppedError%3E-for-WriteError"],[2284,"impl-From%3CClosedStream%3E-for-WriteError"],[2286,"impl-From%3CConnectionError%3E-for-WriteError"],[2290,"impl-From%3Cu16%3E-for-VarInt"],[2291,"impl-From%3Cu8%3E-for-VarInt"],[2292,"impl-From%3CStreamId%3E-for-VarInt"],[2294,"impl-From%3Cu32%3E-for-VarInt"],[2307,"impl-From%3CClose%3E-for-ConnectionError"],[2308,"impl-From%3CTransportError%3E-for-ConnectionError"],[2320,"impl-From%3CTransportErrorCode%3E-for-TransportError"],[2321,"impl-From%3CError%3E-for-TransportError"],[2323,"impl-From%3CInvalidFrame%3E-for-TransportError"],[2335,"impl-From%3CConnectWithOptsError%3E-for-ConnectError"],[2337,"impl-From%3CConnectionError%3E-for-ConnectError"],[2645,"impl-RecvStream"],[2646,"impl-AsyncRead-for-RecvStream"],[2648,"impl-AsyncWrite-for-SendStream"],[2649,"impl-SendStream"],[2820,"impl-TryFrom%3Cu64%3E-for-VarInt"],[2822,"impl-TryFrom%3Cu128%3E-for-VarInt"],[2823,"impl-TryFrom%3Cusize%3E-for-VarInt"],[3429,"impl-Display-for-Report"],[3430,"impl-Debug-for-Report"],[3434,"impl-Display-for-ReportError"],[3435,"impl-Debug-for-ReportError"],[3626,"impl-Debug-for-EncodingError"],[3627,"impl-Display-for-EncodingError"],[3628,"impl-Debug-for-DecodingError"],[3629,"impl-Display-for-DecodingError"],[3630,"impl-Debug-for-MaxLengthExceededError"],[3631,"impl-Display-for-MaxLengthExceededError"],[3632,"impl-Display-for-LookupError"],[3633,"impl-Debug-for-LookupError"],[3781,"impl-Display-for-AcceptError"],[3782,"impl-Debug-for-AcceptError"],[3786,"impl-From%3CBox%3Cdyn+Error+%2B+Send+%2B+Sync%3E%3E-for-AcceptError"],[3787,"impl-From%3CClosedStream%3E-for-AcceptError"],[3788,"impl-From%3CError%3E-for-AcceptError"],[3790,"impl-From%3CRemoteNodeIdError%3E-for-AcceptError"],[3791,"impl-From%3CConnectionError%3E-for-AcceptError"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAGUL7gADAAAADAAAABMABgAbAFEAbgAAAHAAGQCOAAgAmQAnAMIAAADEAAAAxgABAMkAAQDMAAEAzwAAANEAAADUAAAA2AAAANwAAADeAAoA6wAMAAsBAwAWAQQAHAEBACIBLABTAQgAXgEHAHkBAAB7AQAAhAEBAIgBBQCPAQQAlgEgALgBKwDlARwABQIJABACGwAuAgMAMwIAADcCAAA6AgAAQwIDAEgCAABKAg4AZAIAAHACAAB0AgAAdwIAAHsCAwCBAgAAhAIDAIkCBACPAh4AsQIJAMECHgDkAgMA6gIJAPUCAwD7AgEA/wIBAAIDCAAOAwMAEwMNACMDAQAnAwEAKgMKADcDBAA+AwAARAMSAFsDKACHAwwAmgMJAKoDAwCxAwAAtAMAALYDEADIAwUAzwMFANYDBgDfAwQA5wMOAPcDAwD9AwAA/wMBAAQEAQAJBAAACwQAAA0EBAATBAMAGQQAABsEDAAqBAAALAQAAC4EAAAwBAAAMgQAADQEBAA8BAIAQAQLAE0EAQBcBAAAXgQEAGoEAQBuBAAAcgQAAH0EAQCABAAAgwQAAIcEAACcBAAAngQBAKEEAQCqBAAAtgQAALwEAQDBBAAAyAQAANUEAADdBAAA8gQAAPQEAAABBSIAKgUAACwFAAA4BRgAVgV7ANgFBgDhBSIABQZFAE8GAwBUBr0AGQcAABsHAAAgBwEAJgcQADgHhwDKBz8ACwhuAH4IUwDeCAAA4ggBAOUIAgDpCAAA7AgBAO8IAQDzCAIA9wgAAAQJAQAMCQAADwkAABEJAQAUCQAAFwkAAB4JAAAgCQAAIgkAACQJAAAsCQAAMQkiAFkJAABbCQQAZAkSAHoJPQD/CQkAIAoAACQKAgAxCgEANgoAAEEKAwBGCgEASwoKAFcKAgB4CgEAiQoEAJQKDgCpCgAAqwoBAK4KAQCyCj0A9AoQAAYLAAAJC3AAews9AL8LPQAHDCwAOAwAADsMAAA9DBIAUgwOAGQMDgB3DAMAfAwJAIsMAACNDAUAmwwDAK0MAwCyDAcAvAwGAMYMBgDODA8A4AwAAOUMAwDqDAEA7QwAAPQMBQD7DAIA/wwPABANAAASDTwAUA0HAFkNEwB1DQQAgw0IAJ4NAACqDQEAsw0eANMNEwDoDQYA8w0EAPkNIAAbDhgAOQ4HAEYOBwBPDjoAiw4CAJEOAgCWDgoAog4fAMQOBADLDgIAzw4BANMOBgDiDgAA5Q4BAOgOFwACDw0AEg8DABgPAQAlDwcA","P":[[32,"T"],[50,""],[59,"T"],[66,""],[77,"K"],[81,"T"],[108,""],[111,"T"],[115,""],[116,"T"],[130,""],[132,"D"],[134,"__D"],[137,""],[158,"K"],[176,""],[194,"T"],[195,""],[196,"T"],[197,""],[199,"T"],[200,""],[205,"T"],[206,""],[207,"T"],[208,""],[209,"T"],[211,""],[213,"T"],[215,""],[218,"T"],[220,""],[221,"T"],[228,""],[232,"R"],[233,""],[234,"H"],[235,"__H"],[236,""],[247,"U"],[256,""],[277,"S"],[279,"__S"],[282,""],[289,"T"],[296,""],[304,"U,T"],[305,""],[307,"U,T"],[308,""],[309,"U,T"],[316,"U"],[325,""],[338,"V"],[347,""],[348,""],[403,""],[405,""],[414,"T"],[434,""],[443,"T"],[447,""],[452,"K"],[453,"T"],[483,""],[486,"T"],[488,""],[489,"T"],[494,"Deref::Target"],[495,"T"],[500,""],[501,"T"],[509,""],[530,"K"],[539,""],[555,"T"],[557,""],[561,"T"],[562,""],[563,"T"],[566,""],[567,"T"],[574,""],[578,"T"],[582,""],[585,"__H"],[586,""],[600,"U"],[610,""],[643,"T"],[647,""],[654,"U,T"],[656,""],[657,"U,T"],[665,"U"],[675,""],[688,"V"],[698,""],[739,"T"],[743,""],[745,"T"],[755,""],[760,"T"],[762,""],[764,"U"],[766,""],[770,"U,T"],[772,"U"],[774,""],[776,"V"],[780,""],[781,"T"],[785,""],[786,"T"],[796,""],[800,"T"],[802,""],[804,"U"],[806,""],[812,"U,T"],[814,"U"],[816,""],[818,"V"],[820,""],[842,"T"],[854,""],[862,"T"],[865,""],[868,"T"],[898,""],[915,"T"],[924,""],[931,"U"],[937,""],[950,"T"],[953,""],[954,"U,T"],[960,"U"],[966,""],[974,"V"],[980,""],[991,"T"],[995,""],[999,"T"],[1000,""],[1001,"T"],[1007,""],[1009,"T"],[1013,""],[1018,"T"],[1021,""],[1025,"U"],[1027,""],[1036,"T"],[1037,"U,T"],[1039,"U"],[1041,""],[1044,"V"],[1048,""],[1049,""],[1050,"T"],[1052,""],[1053,"T"],[1054,""],[1055,"T"],[1058,""],[1059,"T"],[1061,""],[1063,"T"],[1064,","],[1065,"T"],[1066,""],[1068,"U"],[1069,""],[1074,""],[1075,"T"],[1076,"U,T"],[1077,"U"],[1078,""],[1079,"V"],[1081,""],[1084,"T"],[1086,""],[1088,"T"],[1089,""],[1090,"T"],[1093,""],[1094,"T"],[1096,""],[1099,"T"],[1101,""],[1102,"U"],[1103,""],[1109,""],[1113,""],[1114,""],[1117,"T"],[1118,"U,T"],[1119,"U"],[1120,""],[1121,"V"],[1122,""],[1324,""],[1325,""],[1365,"T"],[1489,""],[1540,"T"],[1575,""],[1619,"K"],[1623,"T"],[1809,""],[1814,""],[1816,""],[1829,"B"],[1832,""],[1847,"T"],[1971,""],[1978,"__D"],[1983,""],[1985,""],[1986,""],[2058,"B"],[2061,""],[2088,"K"],[2169,""],[2262,"T"],[2269,""],[2270,"T"],[2273,""],[2275,"T"],[2276,""],[2279,"T"],[2280,""],[2281,"T"],[2283,""],[2285,"T"],[2286,""],[2288,"T"],[2290,""],[2293,"T"],[2294,""],[2295,"T"],[2307,""],[2309,"T"],[2315,""],[2316,"T"],[2318,""],[2319,"T"],[2320,""],[2322,"T"],[2323,""],[2324,"T"],[2326,""],[2327,"T"],[2333,""],[2334,"T"],[2335,""],[2336,"T"],[2337,""],[2338,"T"],[2339,""],[2340,"T"],[2347,""],[2348,"T"],[2387,""],[2394,"__H"],[2399,""],[2494,"U"],[2556,""],[2564,"IntoFuture::IntoFuture"],[2565,""],[2640,"Future::Output"],[2644,""],[2686,""],[2687,""],[2696,"__S"],[2701,""],[2737,"T"],[2772,""],[2803,"U,T"],[2820,""],[2821,"U,T"],[2822,""],[2824,"U,T"],[2868,"U"],[2930,"F"],[2937,""],[3006,"V"],[3068,""],[3143,"T"],[3151,""],[3154,"T"],[3155,""],[3156,"T"],[3168,""],[3175,"T"],[3183,"__D"],[3186,""],[3206,"T"],[3211,""],[3218,"U"],[3222,""],[3277,"__S"],[3280,"T"],[3281,"U,T"],[3285,"U"],[3289,""],[3300,"V"],[3304,""],[3326,"T"],[3342,""],[3350,"T"],[3355,""],[3360,"T"],[3384,""],[3388,"T"],[3404,""],[3405,"__D"],[3406,""],[3418,"K"],[3424,""],[3436,"T"],[3449,""],[3468,"U"],[3476,""],[3497,"__S"],[3498,""],[3506,"T"],[3511,""],[3513,"U,T"],[3521,"U"],[3529,""],[3538,"V"],[3546,""],[3585,"T"],[3593,""],[3597,"T"],[3609,""],[3610,"T"],[3618,""],[3635,"T"],[3639,""],[3648,"U"],[3652,""],[3662,"U,T"],[3666,"U"],[3670,""],[3674,"V"],[3678,""],[3732,","],[3733,"P"],[3734,""],[3736,"T"],[3744,""],[3747,"P"],[3748,"T"],[3750,""],[3752,"T"],[3772,""],[3783,"P"],[3784,"T"],[3786,""],[3789,"T"],[3790,""],[3792,"T"],[3796,""],[3801,"U"],[3805,""],[3807,"P,F"],[3808,""],[3809,"P"],[3810,""],[3812,"P"],[3813,""],[3815,"T"],[3817,""],[3818,"U,T"],[3822,"U"],[3826,""],[3830,"V"],[3834,""],[3841,"T"],[3855,""],[3861,"T"],[3863,""],[3865,"U"],[3867,""],[3876,"U,T"],[3878,"U"],[3880,""],[3882,"V"]]}],["iroh_base",{"t":"TPPPGTFIFFFFFINNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNONNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOPTPFGPKPNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNMNNNNNNNNNNOOOOOOOOOOOO","n":["BYTE_SIZE","Decode","DecodeInvalidLength","Key","KeyParsingError","LENGTH","NodeAddr","NodeId","PublicKey","RelayUrl","RelayUrlParseError","SecretKey","Signature","SignatureError","as_bytes","as_error_source","","as_ref","backtrace","","borrow","","","","","","","","borrow_mut","","","","","","","cause","","clone","","","","","clone_into","","","","","clone_to_uninit","","","","","cmp","","","deref","description","","deserialize","","","","","direct_addresses","","eq","","","","fmt","","","","","","","","","","","","","","","fmt_short","from","","","","","","","","","","","","","","","","","","","from_bytes","","","from_components","from_parts","from_slice","from_str","","","","generate","hash","","in_current_span","","into","","","","","","","is_empty","new","node_id","partial_cmp","","","public","","r_bytes","relay_url","","s_bytes","secret","serialize","","","","","sign","source","","ticket","to_bytes","","","to_owned","","","","","to_string","","","","","","to_vec","try_from","","","","","","","","","","","try_into","","","","","","","type_id","","","","","","","verify","with_direct_addresses","with_relay_url","backtrace","","","source","","span_trace","","","Encoding","KIND","Kind","NodeTicket","ParseError","Postcard","Ticket","Verify","as_error_source","backtrace","borrow","","borrow_mut","","cause","clone","clone_into","clone_to_uninit","description","deserialize","","eq","fmt","","","","from","","","","from_bytes","","from_str","in_current_span","into","","new","node_addr","serialize","","source","to_bytes","","to_owned","to_string","","try_from","","try_into","","type_id","","backtrace","","","","expected","message","source","","span_trace","","",""],"q":[[0,"iroh_base"],[191,"iroh_base::KeyParsingError"],[199,"iroh_base::ticket"],[251,"iroh_base::ticket::ParseError"],[263,"iroh_base::key"],[264,"core::error"],[265,"backtrace::capture"],[266,"core::option"],[267,"iroh_base::relay_url"],[268,"ed25519"],[269,"iroh_base::node_addr"],[270,"core::cmp"],[271,"core::result"],[272,"serde::de"],[273,"core::net::socket_addr"],[274,"core::iter::traits::iterator"],[275,"alloc::collections::btree::set"],[276,"core::fmt"],[277,"alloc::string"],[278,"ed25519_dalek::signature"],[279,"ed25519_dalek::verifying"],[280,"data_encoding"],[281,"ed25519_dalek::errors"],[282,"ed25519_dalek::signing"],[283,"iroh_base::ticket::node"],[284,"url"],[285,"core::iter::traits::collect"],[286,"signature::error"],[287,"rand_core"],[288,"core::hash"],[289,"serde::ser"],[290,"alloc::vec"],[291,"core::any"],[292,"n0_snafu::spantrace"],[293,"postcard::error"]],"i":"Ahn00`b````````01Ad1203112AjAlAn364521035364210642106421041005364210116410666644552210033466664455522211110036426166420240536452103111410426116264210253`6626421064520366644452210364521036452103411ElEnF`21210FdFf1``1`111Dj20220002100002200221002020010210002020202FhFjFlFn30213210","f":"``````````````{{{d{b}}}{{d{{h{f}}}}}}{d{{d{j}}}}0{{{d{b}}}{{d{{l{f}}}}}}{{{d{n}}}{{Ab{{d{A`}}}}}}{{{d{Ad}}}{{Ab{{d{A`}}}}}}{d{{d{c}}}{}}0500000{{{d{Af}}}{{d{Afc}}}{}}000000{{{d{n}}}{{Ab{{d{j}}}}}}{{{d{Ad}}}{{Ab{{d{j}}}}}}{{{d{Ah}}}Ah}{{{d{b}}}b}{{{d{Aj}}}Aj}{{{d{Al}}}Al}{{{d{An}}}An}{{d{d{Afc}}}B`{}}0000{{df}B`}0000{{{d{b}}{d{b}}}Bb}{{{d{Al}}{d{Al}}}Bb}{{{d{An}}{d{An}}}Bb}{{{d{An}}}{{d{c}}}{}}{{{d{n}}}{{d{Bd}}}}{{{d{Ad}}}{{d{Bd}}}}{c{{Bf{Ah}}}Bh}{c{{Bf{b}}}Bh}{c{{Bf{Aj}}}Bh}{c{{Bf{Al}}}Bh}{c{{Bf{An}}}Bh}{{{d{Al}}}{{`{{Bn{}{{Bj{{d{Bl}}}}}}}}}}{AlC`}{{{d{Ah}}{d{Ah}}}Cb}{{{d{b}}{d{b}}}Cb}{{{d{Al}}{d{Al}}}Cb}{{{d{An}}{d{An}}}Cb}{{{d{Ah}}{d{AfCd}}}{{Bf{B`Cf}}}}000{{{d{b}}{d{AfCd}}}Ch}0{{{d{n}}{d{AfCd}}}Ch}0{{{d{Aj}}{d{AfCd}}}Ch}0{{{d{Al}}{d{AfCd}}}Ch}{{{d{An}}{d{AfCd}}}Ch}0{{{d{Ad}}{d{AfCd}}}Ch}0{{{d{b}}}Cj}{cc{}}{{{d{{h{f}}}}}Ah}{{{h{f}}}Ah}{ClAh}{Cnb}4{D`n}5{Dbn}{DdAj}7{{{h{f}}}Aj}{DfAl}{{{Dh{b{Ab{An}}{d{{l{Bl}}}}}}}Al}:{DjAl};{DlAn}<;{{{d{{h{f}}}}}{{Bf{bDb}}}}{{{d{{h{f}}}}}Aj}{{{h{f}}{h{f}}}Ah}{{b{Ab{An}}c}Al{{Dn{}{{Bj{Bl}}}}}}{{{d{{l{f}}}}}{{Bf{AhE`}}}}{{{d{Bd}}}{{Bf{AhE`}}}}{{{d{Bd}}}{{Bf{bc}}}{}}{{{d{Bd}}}{{Bf{Ajc}}}{}}{{{d{Bd}}}{{Bf{Anc}}}{}}{cAjEb}{{{d{b}}{d{Afc}}}B`Ed}{{{d{An}}{d{Afc}}}B`Ed}{{}}0{{}c{}}000000{{{d{Al}}}Cb}{bAl}{AlDf}{{{d{b}}{d{b}}}{{Ab{Bb}}}}{{{d{Al}}{d{Al}}}{{Ab{Bb}}}}{{{d{An}}{d{An}}}{{Ab{Bb}}}}{{{d{b}}}Cn}{{{d{Aj}}}b}{{{d{Ah}}}{{d{{h{f}}}}}}{{{d{Al}}}{{Ab{{d{An}}}}}}{AlAb}2{{{d{Aj}}}{{d{Dd}}}}{{{d{Ah}}c}BfEf}{{{d{b}}c}BfEf}{{{d{Aj}}c}BfEf}{{{d{Al}}c}BfEf}{{{d{An}}c}BfEf}{{{d{Aj}}{d{{l{f}}}}}Ah}{{{d{n}}}{{Ab{{d{j}}}}}}{{{d{Ad}}}{{Ab{{d{j}}}}}}`{{{d{Ah}}}{{h{f}}}}0{{{d{Aj}}}{{h{f}}}}{dc{}}0000{dCj}00000{{{d{Ah}}}{{Eh{f}}}}{c{{Bf{e}}}{}{}}{{{d{{l{f}}}}}{{Bf{AhE`}}}}1{{{d{{l{f}}}}}{{Bf{bc}}}{}}{{{d{{h{f}}}}}{{Bf{bc}}}{}}3{{{d{{l{f}}}}}{{Bf{Ajc}}}{}}4444{{}{{Bf{c}}}{}}000000{dEj}000000{{{d{b}}{d{{l{f}}}}{d{Ah}}}{{Bf{B`Db}}}}{{Alc}Al{{Dn{}{{Bj{Bl}}}}}}{{AlAn}Al}{ElAb}{EnAb}{F`Ab}{ElD`}{EnDb}{ElFb}{EnFb}{F`Fb}````````{d{{d{j}}}}{{{d{Fd}}}{{Ab{{d{A`}}}}}}{d{{d{c}}}{}}0{{{d{Af}}}{{d{Afc}}}{}}0{{{d{Fd}}}{{Ab{{d{j}}}}}}{{{d{Dj}}}Dj}{{d{d{Afc}}}B`{}}{{df}B`}{{{d{Fd}}}{{d{Bd}}}}{{{d{Bd}}}{{Bf{FfFd}}}}{c{{Bf{Dj}}}Bh}{{{d{Dj}}{d{Dj}}}Cb}{{{d{Dj}}{d{AfCd}}}Ch}0{{{d{Fd}}{d{AfCd}}}Ch}0{cc{}}{AlDj}1{D`Fd}{{{d{{l{f}}}}}{{Bf{FfFd}}}}{{{d{{l{f}}}}}{{Bf{DjFd}}}}{{{d{Bd}}}{{Bf{Djc}}}{}}{{}}{{}c{}}06{{{d{Dj}}}{{d{Al}}}}{{{d{Ff}}}Cj}{{{d{Dj}}c}BfEf}{{{d{Fd}}}{{Ab{{d{j}}}}}}{{{d{Ff}}}{{Eh{f}}}}{{{d{Dj}}}{{Eh{f}}}}{dc{}}{dCj}0{c{{Bf{e}}}{}{}}0{{}{{Bf{c}}}{}}0{dEj}0{FhAb}{FjAb}{FlAb}{FnAb}{Fhd}{Fnd}{FjG`}{FlD`}{FhFb}{FjFb}{FlFb}{FnFb}","D":"In","p":[[5,"PublicKey",0,263],[1,"reference",null,null,1],[1,"u8"],[1,"array"],[10,"Error",264],[1,"slice"],[6,"KeyParsingError",0,263],[5,"Backtrace",265],[6,"Option",266,null,1],[5,"RelayUrlParseError",0,267],[0,"mut"],[5,"Signature",0,268],[5,"SecretKey",0,263],[5,"NodeAddr",0,269],[5,"RelayUrl",0,267],[1,"unit"],[6,"Ordering",270],[1,"str"],[6,"Result",271,null,1],[10,"Deserializer",272],[17,"Item"],[6,"SocketAddr",273],[10,"Iterator",274],[5,"BTreeSet",275],[1,"bool"],[5,"Formatter",276],[5,"Error",276],[8,"Result",276],[5,"String",277],[5,"InternalSignature",278],[5,"VerifyingKey",279],[5,"DecodeError",280],[8,"SignatureError",0,281],[5,"SigningKey",282],[8,"NodeId",0,263],[1,"tuple",null,null,1],[5,"NodeTicket",199,283],[5,"Url",284],[10,"IntoIterator",285],[5,"Error",286],[10,"CryptoRngCore",287],[10,"Hasher",288],[10,"Serializer",289],[5,"Vec",290],[5,"TypeId",291],[15,"Decode",191],[15,"Key",191],[15,"DecodeInvalidLength",191],[5,"SpanTrace",292],[6,"ParseError",199],[10,"Ticket",199],[15,"Kind",251],[15,"Postcard",251],[15,"Encoding",251],[15,"Verify",251],[6,"Error",293]],"r":[[0,268],[1,263],[2,263],[3,263],[4,263],[5,263],[6,269],[7,263],[8,263],[9,267],[10,267],[11,263],[12,268],[13,281],[14,263],[15,263],[16,267],[17,263],[18,263],[19,267],[20,268],[21,263],[22,263],[23,263],[24,263],[25,269],[26,267],[27,267],[28,268],[29,263],[30,263],[31,263],[32,269],[33,267],[34,267],[35,263],[36,267],[37,268],[38,263],[39,263],[40,269],[41,267],[42,268],[43,263],[44,263],[45,269],[46,267],[47,268],[48,263],[49,263],[50,269],[51,267],[52,263],[53,269],[54,267],[55,267],[56,263],[57,267],[58,268],[59,263],[60,263],[61,269],[62,267],[63,269],[64,269],[65,268],[66,263],[67,269],[68,267],[69,268],[70,268],[71,268],[72,268],[73,263],[74,263],[75,263],[76,263],[77,263],[78,263],[79,269],[80,267],[81,267],[82,267],[83,267],[84,263],[85,268],[86,268],[87,268],[88,268],[89,263],[90,263],[91,263],[92,263],[93,263],[94,263],[95,263],[96,263],[97,269],[98,269],[99,269],[100,269],[101,267],[102,267],[103,267],[104,268],[105,263],[106,263],[107,268],[108,269],[109,268],[110,268],[111,263],[112,263],[113,267],[114,263],[115,263],[116,267],[117,263],[118,267],[119,268],[120,263],[121,263],[122,263],[123,269],[124,267],[125,267],[126,269],[127,269],[128,269],[129,263],[130,269],[131,267],[132,263],[133,263],[134,268],[135,269],[136,269],[137,268],[138,263],[139,268],[140,263],[141,263],[142,269],[143,267],[144,263],[145,263],[146,267],[148,268],[149,268],[150,263],[151,268],[152,263],[153,263],[154,269],[155,267],[156,268],[157,263],[158,263],[159,263],[160,267],[161,267],[162,268],[163,268],[164,268],[165,263],[166,263],[167,263],[168,263],[169,263],[170,263],[171,269],[172,267],[173,267],[174,268],[175,263],[176,263],[177,263],[178,269],[179,267],[180,267],[181,268],[182,263],[183,263],[184,263],[185,269],[186,267],[187,267],[188,263],[189,269],[190,269],[202,283],[209,283],[211,283],[214,283],[215,283],[216,283],[219,283],[220,283],[221,283],[222,283],[225,283],[226,283],[230,283],[231,283],[233,283],[235,283],[236,283],[238,283],[241,283],[242,283],[243,283],[245,283],[247,283],[249,283]],"b":[[69,"impl-LowerHex-for-Signature"],[70,"impl-Display-for-Signature"],[71,"impl-Debug-for-Signature"],[72,"impl-UpperHex-for-Signature"],[73,"impl-Display-for-PublicKey"],[74,"impl-Debug-for-PublicKey"],[75,"impl-Display-for-KeyParsingError"],[76,"impl-Debug-for-KeyParsingError"],[77,"impl-Debug-for-SecretKey"],[78,"impl-Display-for-SecretKey"],[80,"impl-Debug-for-RelayUrl"],[81,"impl-Display-for-RelayUrl"],[82,"impl-Display-for-RelayUrlParseError"],[83,"impl-Debug-for-RelayUrlParseError"],[86,"impl-From%3C%26%5Bu8;+ed25519::::SignatureBytes::%7Bconstant%230%7D%5D%3E-for-Signature"],[87,"impl-From%3C%5Bu8;+ed25519::::SignatureBytes::%7Bconstant%230%7D%5D%3E-for-Signature"],[88,"impl-From%3CInternalSignature%3E-for-Signature"],[91,"impl-From%3CDecodeError%3E-for-KeyParsingError"],[93,"impl-From%3CError%3E-for-KeyParsingError"],[94,"impl-From%3CSigningKey%3E-for-SecretKey"],[96,"impl-From%3C%5Bu8;+32%5D%3E-for-SecretKey"],[97,"impl-From%3CPublicKey%3E-for-NodeAddr"],[98,"impl-From%3C(PublicKey,+Option%3CRelayUrl%3E,+%26%5BSocketAddr%5D)%3E-for-NodeAddr"],[100,"impl-From%3CNodeTicket%3E-for-NodeAddr"],[148,"impl-Signature"],[149,"impl-SignatureEncoding-for-Signature"],[166,"impl-TryFrom%3C%26%5Bu8%5D%3E-for-PublicKey"],[167,"impl-TryFrom%3C%26%5Bu8;+32%5D%3E-for-PublicKey"],[221,"impl-Debug-for-NodeTicket"],[222,"impl-Display-for-NodeTicket"],[223,"impl-Display-for-ParseError"],[224,"impl-Debug-for-ParseError"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAALgAFwAQAC8AQgASAFcAAwBcAAAAXgABAGEAAgBnAAAAbwADAHQAAwCCAAIAjAAEAJIAAQCWAAAAmAAKAKQAGADAAAcA0AAKANwABQDlAAAA5wACAO8AAQDyAA0AAQEGAA==","P":[[20,"T"],[22,""],[23,"T"],[35,""],[42,"T"],[47,""],[55,"Deref::Target"],[56,""],[58,"D"],[61,"__D"],[63,""],[85,"T"],[86,""],[90,"T"],[91,""],[92,"T"],[93,""],[95,"T"],[96,""],[99,"T"],[100,""],[101,"T"],[102,""],[103,"T"],[104,""],[108,""],[109,""],[111,"FromStr::Err"],[114,"R"],[115,"H"],[116,"__H"],[117,""],[119,"U"],[126,""],[139,"S"],[142,"__S"],[144,""],[151,"T"],[156,""],[163,"U,T"],[164,""],[165,"U,T"],[166,"TryFrom::Error"],[168,"U,T"],[169,"TryFrom::Error"],[170,"U,T"],[174,"U"],[181,""],[189,""],[190,""],[209,"T"],[213,""],[215,"T"],[216,""],[219,"D"],[220,""],[225,"T"],[226,""],[227,"T"],[228,""],[231,"FromStr::Err"],[232,""],[233,"U"],[235,""],[238,"S"],[239,""],[242,"T"],[243,""],[245,"U,T"],[247,"U"],[249,""]]}],["iroh_bench",{"t":"FGGGPPPFPPPPNNNNNNNNNNNNNNNNHONNNNNNNNNNNNNNNNNNNNNNNNNNNHNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNONNNNNCOOONCOHCCNOONNNNNNNNNNNNNNNNNNNNNONNNNNSHHHHHHSHHHHHHFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFFFONNNNNNOOOONNNNNNNNNNNNNNNNNNNNOONNNNNNNNNNNNNNONOOOHOOONNNNNNOONNNNNN","n":["ClientStats","Commands","ConnectionSelector","EndpointSelector","Iroh","","","Opt","Quinn","","","S2n","__clone_box","","augment_args","augment_args_for_update","augment_subcommands","augment_subcommands_for_update","borrow","","","","","borrow_mut","","","","","client_handler","clients","clone","","clone_into","","clone_to_uninit","","close","","command","","command_for_update","","compat","","","","","compat_mut","","","","","compat_ref","","","","","configure_tracing_subscriber","default","deref","","","","","deref_mut","","","","","download_size","drop","","","","","fmt","","from","","","","","from_arg_matches","","from_arg_matches_mut","","from_ref","","group_id","has_subcommand","init","","","","","initial_mtu","into","","","","","iroh","max_streams","metrics","only_relay","print","quinn","read_unordered","rt","s2n","stats","","","streams","to_owned","","try_from","","","","","try_into","","","","","type_id","","","","","update_from_arg_matches","","update_from_arg_matches_mut","","upload_size","vzip","","","","","ALPN","client","connect_client","handle_client_stream","server","server_endpoint","transport_config","ALPN","client","connect_client","handle_client_stream","server","server_endpoint","transport_config","Opt","__clone_box","augment_args","augment_args_for_update","borrow","borrow_mut","clone","clone_into","clone_to_uninit","command","command_for_update","compat","compat_mut","compat_ref","deref","deref_mut","drop","fmt","from","from_arg_matches","from_arg_matches_mut","from_ref","group_id","init","into","to_owned","try_from","try_into","type_id","update_from_arg_matches","update_from_arg_matches_mut","vzip","Stats","StreamStats","TransferResult","avg_chunk_size","borrow","","","borrow_mut","","","chunk_size","chunk_time","chunks","","compat","","","compat_mut","","","compat_ref","","","default","","deref","","","deref_mut","","","drop","","","duration","duration_hist","fmt","","","from","","","init","","","into","","","new","print","size","stream_finished","stream_stats","streams","throughput","throughput_bps","throughput_hist","total_duration","total_size","try_from","","","try_into","","","ttfb","ttfb_hist","type_id","","","vzip","",""],"q":[[0,"iroh_bench"],[141,"iroh_bench::iroh"],[148,"iroh_bench::quinn"],[155,"iroh_bench::s2n"],[187,"iroh_bench::stats"],[260,"dyn_clone::sealed"],[261,"clap_builder::builder::command"],[262,"n0_snafu::error"],[263,"async_compat"],[264,"core::fmt"],[265,"clap_builder::parser::matches::arg_matches"],[266,"clap_builder"],[267,"core::result"],[268,"clap_builder::util::id"],[269,"core::option"],[270,"tokio::runtime::runtime"],[271,"core::any"],[272,"iroh_base::node_addr"],[273,"iroh_base::relay_url"],[274,"iroh::endpoint"],[275,"iroh_quinn_proto::config::transport"],[276,"core::net::socket_addr"],[277,"rustls_pki_types"],[278,"iroh_quinn::endpoint"],[279,"iroh_quinn::connection"],[280,"hdrhistogram"],[281,"core::time"]],"i":"````lnAh`21000A`00113210Ab43210`1212121432121432104321043210`0432104321014321021432102121211243210143210`1110`1```311214321043210432102121143210```````````````Ed000000000000000000000000000000```DfEjEf2102000210210210210102102102201021021021022121112`01110210220102102","f":"````````````{{bd}f}0{hh}000{b{{b{c}}}{}}0000{{{b{j}}}{{b{jc}}}{}}0000{{lnA`}{{Ad{Ab}}}}{A`Af}{{{b{Ah}}}Ah}{{{b{A`}}}A`}{{b{b{jc}}}f{}}0{{bAj}f}0{lf}{{{b{n}}Al{b{{An{Aj}}}}}f}{{}h}000{{}{{B`{c}}}{}}0000{{{b{j}}}{{B`{{b{jc}}}}}{}}0000{b{{B`{{b{c}}}}}{}}0000{{}f}{{}Ab}{Af{{b{c}}}{}}0000{Af{{b{jc}}}{}}0000{A`Bb}{Aff}0000{{{b{Ah}}{b{jBd}}}Bf}{{{b{A`}}{b{jBd}}}Bf}{cc{}}0000{{{b{Bh}}}{{Bl{AhBj}}}}{{{b{Bh}}}{{Bl{A`Bj}}}}{{{b{jBh}}}{{Bl{AhBj}}}}{{{b{jBh}}}{{Bl{A`Bj}}}}{{{b{c}}}c{}}0{{}{{C`{Bn}}}}{{{b{Cb}}}Cd}{{}Af}0000{A`Cf}{{}c{}}0000`{A`Af}{A`Cd}0{{{b{Ab}}Af}f}`1{{}Ch}``{{{b{n}}}f}34{bc{}}0{c{{Bl{e}}}{}{}}0000{{}{{Bl{c}}}{}}0000{bCj}0000{{{b{jAh}}{b{Bh}}}{{Bl{fBj}}}}{{{b{jA`}}{b{Bh}}}{{Bl{fBj}}}}{{{b{jAh}}{b{jBh}}}{{Bl{fBj}}}}{{{b{jA`}}{b{jBh}}}{{Bl{fBj}}}}{A`Bb}{{}c{}}0000{{}b}{{Cl{C`{Cn}}A`}{{Ad{Ab}}}}{{Cl{C`{Cn}}A`}{{Ad{{Dd{D`Db}}}}}}{{{b{Db}}BbCd}{{Ad{{Dd{DfDf}}}}}}{{D`A`}{{Ad{f}}}}{{{b{Ch}}{b{{C`{Cn}}}}{b{A`}}}{{Dd{ClD`}}}}{{AfCf}Dh}6{{DjDlA`}{{Ad{Ab}}}}{{DjDlA`}{{Ad{{Dd{DnE`}}}}}}{{{b{E`}}BbCd}{{Ad{{Dd{DfDf}}}}}}{{DnA`}{{Ad{f}}}}{{{b{Ch}}DlEb{b{A`}}}{{Dd{DjDn}}}}5`{{bd}f}{hh}0{b{{b{c}}}{}}{{{b{j}}}{{b{jc}}}{}}{{{b{Ed}}}Ed}{{b{b{jc}}}f{}}{{bAj}f}{{}h}0{{}{{B`{c}}}{}}{{{b{j}}}{{B`{{b{jc}}}}}{}}{b{{B`{{b{c}}}}}{}}{Af{{b{c}}}{}}{Af{{b{jc}}}{}}{Aff}{{{b{Ed}}{b{jBd}}}Bf}{cc{}}{{{b{Bh}}}{{Bl{EdBj}}}}{{{b{jBh}}}{{Bl{EdBj}}}}{{{b{c}}}c{}}{{}{{C`{Bn}}}}{{}Af}{{}c{}}{bc{}}{c{{Bl{e}}}{}{}}{{}{{Bl{c}}}{}}{bCj}{{{b{jEd}}{b{Bh}}}{{Bl{fBj}}}}{{{b{jEd}}{b{jBh}}}{{Bl{fBj}}}}{{}c{}}```{DfBb}{b{{b{c}}}{}}00{{{b{j}}}{{b{jc}}}{}}00{EfEh}0{EfBb}4{{}{{B`{c}}}{}}00{{{b{j}}}{{B`{{b{jc}}}}}{}}00{b{{B`{{b{c}}}}}{}}00{{}Ej}{{}Ef}{Af{{b{c}}}{}}00{Af{{b{jc}}}{}}00{Aff}00{DfEl}:{{{b{Ej}}{b{jBd}}}Bf}{{{b{Ef}}{b{jBd}}}Bf}{{{b{Df}}{b{jBd}}}Bf}{cc{}}00{{}Af}00{{}c{}}00{{ElBbElBb}Df}{{{b{Ej}}{b{Cb}}}f}{DfBb}{{{b{jEj}}Df}f}{EjEf}{EjAf}{DfEn}{{ElBb}En}{EfEh}{EjEl}{EjBb}{c{{Bl{e}}}{}{}}00{{}{{Bl{c}}}{}}00{DfEl}5{bCj}00{{}c{}}00","D":"Dj","p":[[1,"reference",null,null,1],[5,"Private",260],[1,"unit"],[5,"Command",261],[0,"mut"],[6,"EndpointSelector",0],[6,"ConnectionSelector",0],[5,"Opt",0],[5,"ClientStats",0],[8,"Result",262],[1,"usize"],[6,"Commands",0],[1,"u8"],[1,"u32"],[1,"slice"],[5,"Compat",263],[1,"u64"],[5,"Formatter",264],[8,"Result",264],[5,"ArgMatches",265],[8,"Error",266],[6,"Result",267,null,1],[5,"Id",268],[6,"Option",269,null,1],[1,"str"],[1,"bool"],[1,"u16"],[5,"Runtime",270],[5,"TypeId",271],[5,"NodeAddr",272],[5,"RelayUrl",273],[5,"Endpoint",274],[5,"Connection",274],[1,"tuple",null,null,1],[5,"TransferResult",187],[5,"TransportConfig",275],[6,"SocketAddr",276],[5,"CertificateDer",277],[5,"Endpoint",278],[5,"Connection",279],[6,"PrivateKeyDer",277],[5,"Opt",155],[5,"StreamStats",187],[5,"Histogram",280],[5,"Stats",187],[5,"Duration",281],[1,"f64"]],"r":[],"b":[],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAN8AEQAAABwAHwAmAEcABgBTAAwAZgAAAGoAAQBtAAMAcwAUAIkABQCRAAAAlAABAJgAAACbABIArwAEALUALQDmAAIA7AAYAA==","P":[[18,"T"],[28,""],[32,"T"],[34,""],[42,"T"],[57,""],[59,"T"],[69,""],[77,"T"],[82,""],[86,"T"],[88,""],[96,"U"],[102,""],[114,"T"],[116,"U,T"],[121,"U"],[126,""],[136,"V"],[141,""],[159,"T"],[161,""],[162,"T"],[163,""],[166,"T"],[171,""],[173,"T"],[174,""],[176,"T"],[177,""],[179,"U"],[180,"T"],[181,"U,T"],[182,"U"],[183,""],[186,"V"],[190,""],[191,"T"],[197,""],[201,"T"],[210,""],[212,"T"],[218,""],[226,"T"],[229,""],[232,"U"],[235,""],[246,"U,T"],[249,"U"],[252,""],[257,"V"]]}],["iroh_dns_server",{"t":"FNNNNNNNNNCCNNNNCNNNCNNNCCNNNNNNGFPPFFFNOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOONNNNNNNNNNNOONNNNNNOOONNNNNNNNNNNNNNNNNNNNNNNNNNNOFFFFNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNOONNNNNNNNNNNNNNNNNNOOOOONNNNNNNNNNNNNNNNNNNNNNNNGPFFFPPGPPPNNNNOONNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNOOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNFNNNNNNNOOOOOONNNNOOOONNOOOOOONNNNFNNNNNNNNHNNNNNNFNNNNNNNNNONNNOONNNNN","n":["ZoneStore","__clone_box","borrow","borrow_mut","clone","clone_into","clone_to_uninit","compat","compat_mut","compat_ref","config","dns","fmt","from","from_ref","get_signed_packet","http","in_memory","insert","into","metrics","new","persistent","resolve","server","state","to_owned","try_from","try_into","type_id","vzip","with_mainline_fallback","BootstrapOption","Config","Custom","Default","MainlineConfig","MetricsConfig","StoreConfig","__clone_box","bind_addr","bootstrap","borrow","","","","","borrow_mut","","","","","clone","clone_into","clone_to_uninit","compat","","","","","compat_mut","","","","","compat_ref","","","","","data_dir","default","","","","deserialize","","","","","disabled","","dns","enabled","fmt","","","","","from","","","","","from_ref","http","https","into","","","","","load","mainline","metrics","pkarr_put_rate_limit","serialize","","","","","signed_packet_store_path","to_owned","try_from","","","","","try_into","","","","","type_id","","","","","vzip","","","","","zone_store","DnsConfig","DnsHandler","DnsServer","Handle","__clone_box","","","answer_request","bind_addr","borrow","","","","borrow_mut","","","","clone","","","clone_into","","","clone_to_uninit","","","compat","","","","compat_mut","","","","compat_ref","","","","default_soa","default_ttl","deserialize","fmt","","","from","","","","from_ref","","","handle_request","into","","","","local_addr","new","origins","port","rr_a","rr_aaaa","rr_ns","run_until_done","send_response","serialize","shutdown","spawn","to_owned","","","try_from","","","","try_into","","","","type_id","","","","vzip","","","","CertMode","Disabled","HttpConfig","HttpServer","HttpsConfig","LetsEncrypt","Manual","RateLimitConfig","SelfSigned","Simple","Smart","__clone_box","","","","bind_addr","","borrow","","","","","borrow_mut","","","","","cert_mode","clone","","","","clone_into","","","","clone_to_uninit","","","","compat","","","","","compat_mut","","","","","compat_ref","","","","","default","","deserialize","","","","domains","eq","equivalent","","","fmt","","","","","from","","","","","from_ref","","","","http_addr","https_addr","into","","","","","letsencrypt_contact","letsencrypt_prod","port","","run_until_done","serialize","","","","shutdown","spawn","to_owned","","","","to_string","try_from","","","","","try_into","","","","","type_id","","","","","vzip","","","","","Metrics","as_iterable","borrow","borrow_mut","compat","compat_mut","compat_ref","default","dns_lookup_error","dns_lookup_notfound","dns_lookup_success","dns_requests","dns_requests_https","dns_requests_udp","field_count","field_ref","fmt","from","http_requests","http_requests_duration_ms","http_requests_error","http_requests_success","into","name","pkarr_publish_noop","pkarr_publish_update","store_packets_expired","store_packets_inserted","store_packets_removed","store_packets_updated","try_from","try_into","type_id","vzip","Server","borrow","borrow_mut","compat","compat_mut","compat_ref","from","into","run_until_error","run_with_config_until_ctrl_c","shutdown","spawn","try_from","try_into","type_id","vzip","AppState","__clone_box","borrow","borrow_mut","clone","clone_into","clone_to_uninit","compat","compat_mut","compat_ref","dns_handler","from","from_ref","into","metrics","store","to_owned","try_from","try_into","type_id","vzip"],"q":[[0,"iroh_dns_server"],[32,"iroh_dns_server::config"],[134,"iroh_dns_server::dns"],[221,"iroh_dns_server::http"],[344,"iroh_dns_server::metrics"],[378,"iroh_dns_server::server"],[394,"iroh_dns_server::state"],[415,"dyn_clone::sealed"],[416,"iroh_dns_server::store"],[417,"async_compat"],[418,"core::fmt"],[419,"pkarr::signed_packet"],[420,"core::option"],[421,"n0_snafu::error"],[422,"alloc::sync"],[423,"std::path"],[424,"core::convert"],[425,"hickory_proto::rr::domain::name"],[426,"hickory_proto::rr::record_type"],[427,"hickory_proto::rr::rr_set"],[428,"core::result"],[429,"core::any"],[430,"serde::de"],[431,"iroh_dns_server::http::rate_limiting"],[432,"serde::ser"],[433,"hickory_server::server::request_handler"],[434,"bytes::bytes"],[435,"alloc::string"],[436,"core::future::future"],[437,"alloc::boxed"],[438,"core::pin"],[439,"hickory_server::server::response_handler"],[440,"core::net::socket_addr"],[441,"alloc::vec"],[442,"hickory_server::authority::message_response"],[443,"hickory_proto::rr::resource"],[444,"core::iter::traits::iterator"],[445,"core::marker"],[446,"iroh_dns_server::http::tls"],[447,"iroh_metrics::iterable"],[448,"iroh_metrics::metrics"],[449,"iroh_metrics::base"]],"i":"`j00000000``0000`000`000``000000``Bn0```CdC`CbCh3214032143330321403214032140031403214220103214032143000321400000321403032140321403214032140````ClDbDh12Ef32103213213213210321032103213333210321321203210233333013003210321032103210321`Cn```Fl0`01110FhFj10G`432104321143214321432104321043210432144432113333433210432143210004321112104321004321304321043210432104321`Aj00000000000000000000000000000000`Gn0000000`000000`Gb0000000000000000000","f":"`{{bd}f}{b{{b{c}}}{}}{{{b{h}}}{{b{hc}}}{}}{{{b{j}}}j}{{b{b{hc}}}f{}}{{bl}f}{{}{{n{c}}}{}}{{{b{h}}}{{n{{b{hc}}}}}{}}{b{{n{{b{c}}}}}{}}``{{{b{j}}{b{hA`}}}Ab}{cc{}}{{{b{c}}}c{}}{{{b{j}}{b{`}}}{{Ah{{Af{Ad}}}}}}```{{}c{}}```{{{b{j}}{b{`}}{b{Bd}}Bf}{{Ah{{Af{{Al{Bh}}}}}}}}``{bc{}}{c{{Bj{e}}}{}{}}{{}{{Bj{c}}}{}}{bBl}{{}c{}}{{jBn}j}```````{{bd}f}{C`Af}{CbAf}{b{{b{c}}}{}}0000{{{b{h}}}{{b{hc}}}{}}0000{{{b{Cd}}}Cd}{{b{b{hc}}}f{}}{{bl}f}{{}{{n{c}}}{}}0000{{{b{h}}}{{n{{b{hc}}}}}{}}0000{b{{n{{b{c}}}}}{}}0000{{}{{Ah{Cf}}}}{{}Ch}{{}Cd}{{}Cb}{{}Bn}{c{{Bj{Ch}}}Cj}{c{{Bj{Cd}}}Cj}{c{{Bj{C`}}}Cj}{c{{Bj{Cb}}}Cj}{c{{Bj{Bn}}}Cj}{{}C`}{C`An}{ChCl}{CbAn}{{{b{Ch}}{b{hA`}}}Ab}{{{b{Cd}}{b{hA`}}}Ab}{{{b{C`}}{b{hA`}}}Ab}{{{b{Cb}}{b{hA`}}}Ab}{{{b{Bn}}{b{hA`}}}Ab}{cc{}}0000{{{b{c}}}c{}}{ChAf}0{{}c{}}0000{c{{Ah{Ch}}}{{Bb{B`}}}}22{ChCn}{{{b{Ch}}c}BjD`}{{{b{Cd}}c}BjD`}{{{b{C`}}c}BjD`}{{{b{Cb}}c}BjD`}{{{b{Bn}}c}BjD`}{{}{{Ah{Cf}}}}{bc{}}{c{{Bj{e}}}{}{}}0000{{}{{Bj{c}}}{}}0000{bBl}0000{{}c{}}0000>````{{bd}f}00{{{b{Db}}Dd}{{Ah{Df}}}}{ClAf}{b{{b{c}}}{}}000{{{b{h}}}{{b{hc}}}{}}000{{{b{Cl}}}Cl}{{{b{Db}}}Db}{{{b{Dh}}}Dh}{{b{b{hc}}}f{}}00{{bl}f}00{{}{{n{c}}}{}}000{{{b{h}}}{{n{{b{hc}}}}}{}}000{b{{n{{b{c}}}}}{}}000{ClDj}{ClDl}{c{{Bj{Cl}}}Cj}{{{b{Cl}}{b{hA`}}}Ab}{{{b{Db}}{b{hA`}}}Ab}{{{b{Dh}}{b{hA`}}}Ab}{cc{}}000{{{b{c}}}c{}}00{{{b{Db}}{b{Dd}}c}{{Eb{{E`{Dn}}}}}Ed}{{}c{}}000{{{b{Ef}}}Eh}{{j{b{Cl}}{Al{Aj}}}{{Ah{Db}}}}{ClEj}{ClEl}{ClAf}00{Ef{{Ah{f}}}}{{{b{hDh}}{En{cegi}}}{{Eb{{E`{Dn}}}}}{{Fd{}{{F`{{b{Fb}}}}}}Ff}{{Fd{}{{F`{{b{Fb}}}}}}Ff}{{Fd{}{{F`{{b{Fb}}}}}}Ff}{{Fd{}{{F`{{b{Fb}}}}}}Ff}}{{{b{Cl}}c}BjD`}2{{ClDb}{{Ah{Ef}}}}{bc{}}00{c{{Bj{e}}}{}{}}000{{}{{Bj{c}}}{}}000{bBl}000{{}c{}}000```````````{{bd}f}000{FhAf}{FjAf}{b{{b{c}}}{}}0000{{{b{h}}}{{b{hc}}}{}}0000{FjFl}{{{b{Cn}}}Cn}{{{b{Fl}}}Fl}{{{b{Fh}}}Fh}{{{b{Fj}}}Fj}{{b{b{hc}}}f{}}000{{bl}f}000{{}{{n{c}}}{}}0000{{{b{h}}}{{n{{b{hc}}}}}{}}0000{b{{n{{b{c}}}}}{}}0000{{}Cn}{{}{{b{Cn}}}}{c{{Bj{Cn}}}Cj}{c{{Bj{Fl}}}Cj}{c{{Bj{Fh}}}Cj}{c{{Bj{Fj}}}Cj}{FjEj}{{{b{Fl}}{b{Fl}}}An}{{b{b{c}}}An{}}00{{{b{Cn}}{b{hA`}}}Ab}{{{b{Fl}}{b{hA`}}}{{Bj{fFn}}}}{{{b{Fl}}{b{hA`}}}Ab}{{{b{Fh}}{b{hA`}}}Ab}{{{b{Fj}}{b{hA`}}}Ab}{cc{}}0000{{{b{c}}}c{}}000{{{b{G`}}}{{Af{Eh}}}}0{{}c{}}0000{FjAf}0{FhEl}{FjEl}{G`{{Ah{f}}}}{{{b{Cn}}c}BjD`}{{{b{Fl}}c}BjD`}{{{b{Fh}}c}BjD`}{{{b{Fj}}c}BjD`}4{{{Af{Fh}}{Af{Fj}}CnGb}{{Ah{G`}}}}{bc{}}000{bDj}{c{{Bj{e}}}{}{}}0000{{}{{Bj{c}}}{}}0000{bBl}0000{{}c{}}0000`{b{{b{Gd}}}}{b{{b{c}}}{}}{{{b{h}}}{{b{hc}}}{}}{{}{{n{c}}}{}}{{{b{h}}}{{n{{b{hc}}}}}{}}{b{{n{{b{c}}}}}{}}{{}Aj}{AjGf}00000{{{b{Aj}}}Gh}{{{b{Aj}}Gh}{{Af{Gj}}}}{{{b{Aj}}{b{hA`}}}Ab}{cc{}}4444{{}c{}}{{{b{Aj}}}{{b{Gl}}}}666666{c{{Bj{e}}}{}{}}{{}{{Bj{c}}}{}}{bBl}{{}c{}}`{b{{b{c}}}{}}{{{b{h}}}{{b{hc}}}{}}{{}{{n{c}}}{}}{{{b{h}}}{{n{{b{hc}}}}}{}}{b{{n{{b{c}}}}}{}};:{Gn{{Ah{f}}}}{Ch{{Ah{f}}}}1{{Chj{Al{Aj}}}{{Ah{Gn}}}};:98`{{bd}f}87{{{b{Gb}}}Gb}{{b{b{hc}}}f{}}{{bl}f}987{GbDb}{cc{}}{{{b{c}}}c{}}{{}c{}}{GbAl}{Gbj}{bc{}}{c{{Bj{e}}}{}{}}{{}{{Bj{c}}}{}}{bBl}{{}c{}}","D":"AAj","p":[[1,"reference",null,null,1],[5,"Private",415],[1,"unit"],[0,"mut"],[5,"ZoneStore",0,416],[1,"u8"],[5,"Compat",417],[5,"Formatter",418],[8,"Result",418],[5,"SignedPacket",419],[6,"Option",420,null,1],[8,"Result",421],[5,"Metrics",344],[5,"Arc",422,null,1],[1,"bool"],[5,"Path",423],[10,"AsRef",424],[5,"Name",425],[6,"RecordType",426],[5,"RecordSet",427],[6,"Result",428,null,1],[5,"TypeId",429],[6,"BootstrapOption",32],[5,"MetricsConfig",32],[5,"MainlineConfig",32],[5,"StoreConfig",32],[5,"PathBuf",423],[5,"Config",32],[10,"Deserializer",430],[5,"DnsConfig",134],[6,"RateLimitConfig",221,431],[10,"Serializer",432],[5,"DnsHandler",134],[5,"Request",433],[5,"Bytes",434],[5,"Handle",134],[5,"String",435],[1,"u32"],[10,"Future",436,null,1],[5,"Box",437,null,1],[5,"Pin",438],[10,"ResponseHandler",439],[5,"DnsServer",134],[6,"SocketAddr",440],[5,"Vec",441],[1,"u16"],[5,"MessageResponse",442],[17,"Item"],[5,"Record",443],[10,"Iterator",444],[10,"Send",445],[5,"HttpConfig",221],[5,"HttpsConfig",221],[6,"CertMode",221,446],[5,"Error",418],[5,"HttpServer",221],[5,"AppState",394],[10,"Iterable",447],[5,"Counter",448],[1,"usize"],[5,"MetricItem",449],[1,"str"],[5,"Server",378]],"r":[[0,416],[1,416],[2,416],[3,416],[4,416],[5,416],[6,416],[7,416],[8,416],[9,416],[12,416],[13,416],[14,416],[15,416],[17,416],[18,416],[19,416],[21,416],[22,416],[23,416],[26,416],[27,416],[28,416],[29,416],[30,416],[31,416],[221,446],[222,431],[226,446],[227,446],[228,431],[229,446],[230,431],[231,431],[232,431],[233,446],[239,431],[240,446],[244,431],[245,446],[249,431],[250,446],[253,431],[254,446],[257,431],[258,446],[262,431],[263,446],[267,431],[268,446],[272,431],[273,446],[276,431],[277,431],[278,431],[279,446],[283,446],[284,446],[285,446],[286,446],[287,431],[288,446],[289,446],[293,431],[294,446],[297,431],[298,446],[304,431],[305,446],[313,431],[314,446],[319,431],[320,446],[323,446],[325,431],[326,446],[330,431],[331,446],[335,431],[336,446],[340,431],[341,446]],"b":[[276,"impl-Default-for-RateLimitConfig"],[277,"impl-Default-for-%26RateLimitConfig"],[288,"impl-Display-for-CertMode"],[289,"impl-Debug-for-CertMode"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAABIBIQACAAgADQAAAA8AAAAbAAQAKAAAACsAGwBIAAgAVQAEAF8AAABrAAQAcQAUAIsAAgCQABwArwADALcAAwDHAAEAywASAOkAAwDvAAkA+gAgABwBCAAqAQMAOgEDAEABGABaAQYAZwECAHABAAB3AQMAfAEEAIcBAwCMAQgAlwEAAJsBBAA=","P":[[2,"T"],[4,""],[5,"T"],[6,""],[7,"T"],[12,""],[13,"T"],[15,""],[19,"U"],[21,""],[22,""],[23,""],[26,"T"],[27,"U,T"],[28,"U"],[29,""],[30,"V"],[31,""],[42,"T"],[52,""],[53,"T"],[54,""],[55,"T"],[70,""],[75,"__D"],[80,""],[89,"T"],[95,""],[97,"U"],[102,""],[103,""],[106,"__S"],[111,""],[112,"T"],[113,"U,T"],[118,"U"],[123,""],[128,"V"],[133,""],[143,"T"],[151,""],[154,"T"],[157,""],[160,"T"],[172,""],[174,"__D"],[175,""],[178,"T"],[185,"R"],[186,"U"],[190,""],[198,",,,"],[199,"__S"],[200,""],[202,"T"],[205,"U,T"],[209,"U"],[213,""],[217,"V"],[232,""],[238,"T"],[248,""],[253,"T"],[257,""],[261,"T"],[276,""],[278,"__D"],[282,""],[284,"K"],[287,""],[292,"T"],[301,""],[303,"U"],[308,""],[313,"__S"],[317,""],[319,"T"],[323,""],[324,"U,T"],[329,"U"],[334,""],[339,"V"],[345,""],[346,"T"],[351,""],[361,"T"],[362,""],[366,"U"],[367,""],[374,"U,T"],[375,"U"],[376,""],[377,"V"],[379,"T"],[385,"U"],[386,""],[390,"U,T"],[391,"U"],[392,""],[393,"V"],[395,""],[396,"T"],[398,""],[399,"T"],[400,""],[401,"T"],[404,""],[405,"T"],[407,"U"],[408,""],[410,"T"],[411,"U,T"],[412,"U"],[413,""],[414,"V"]]}],["iroh_relay",{"t":"EFFFFNNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNCNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNCNNNNNNNNNNNNCNNNNOCCONNCOONNNNNNNNNNNNNNNNNNONNNNNFFFFGPGPPPPPPPPPPPPPPPPPPPPPPPPPPGPGPGGPPPPPPPPPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNHNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOSSSSSSGFPPSSPPPFFPFNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOGSSPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNPGPGPSPPPPPGPTFFKFPPGPPFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNMNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOCCCSHPPPGPPPPPPPSPPPPGPPGPPPPPPPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOPPPPPPPPPGFPPPPPPPPPPPGFGPFPPPPPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNHNNNNNNNNNNNNNNNNCHHNHHNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOSSSSPPGPSSFPNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOOOOOOOOOOGGPPPPGFSPPPPFPPFPPPFPFFPFPFFGFFGPFPPNNNOOOONNNNNNOOONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOONNONONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOOOONNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNNNNNNONNNNNNNNNNNNNNNNNNONNNONNONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOONOOONONNNOOOONOOONONOOOOOOONNNNNOONNCONNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNOONNNNNNNNNNNNNNNNNOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOHHHHHH","n":["MAX_PACKET_SIZE","PingTracker","RelayMap","RelayNode","RelayQuicConfig","__clone_box","","","borrow","","","","borrow_mut","","","","client","clone","","","clone_into","","","clone_to_uninit","","","cmp","","compare","","compat","","","","compat_mut","","","","compat_ref","","","","contains_node","default","","default_timeout","defaults","deref","","","","deref_mut","","","","deserialize","","dns","drop","","","","empty","eq","","","equivalent","","","","","","","","","fmt","","","","","","from","","","","","","","from_iter","","get_node","http","init","","","","into","","","","is_empty","len","new","new_ping","node_info","nodes","partial_cmp","","pong_received","port","protos","quic","","serialize","","server","stun_only","stun_port","timeout","to_owned","","","to_string","","try_from","","","","try_into","","","","type_id","","","","url","urls","vzip","","","","Client","ClientBuilder","ClientSink","ClientStream","ConnectError","Dial","DialError","Dns","ExceedsMaxPacketSize","Handshake","Health","InvalidProtocolMessageEncoding","InvalidRelayUrl","InvalidTargetPort","InvalidTlsServername","InvalidUrl","InvalidWebsocketUrl","Io","","KeepAlive","NoLocalAddr","NodeGone","Ping","","Pong","","ProtocolRecv","ProtocolSend","ProxyConnect","ProxyConnectInvalidStatus","ProxyInvalidTargetPort","ProxyInvalidTlsServername","ProxyInvalidUrl","ReceivedMessage","ReceivedPacket","RecvError","RelayIo","SendError","SendMessage","SendPacket","ServerRestarting","Timeout","Tls","UnexpectedFrame","UnexpectedUpgradeStatus","Upgrade","Websocket","","WebsocketIo","__clone_box","","address_family_selector","as_error_source","","","","backtrace","","","","borrow","","","","","","","","","","borrow_mut","","","","","","","","","","cause","","","","clone","","clone_into","","clone_to_uninit","","compat","","","","","","","","","","compat_mut","","","","","","","","","","compat_ref","","","","","","","","","","connect","deref","","","","","","","","","","deref_mut","","","","","","","","","","description","","","","drop","","","","","","","","","","fmt","","","","","","","","","","","","","","from","","","","","","","","","","","","","","","","","","","","","","in_current_span","","","","init","","","","","","","","","","insecure_skip_cert_verify","into","","","","","","","","","","is_prober","key_cache_capacity","local_addr","make_dangerous_client_config","new","poll_close","","poll_flush","","poll_next","","poll_ready","","protocol","proxy_url","ratelimit_sink","","ratelimit_sink_with_jitter","","ratelimit_stream","","ratelimit_stream_with_jitter","","source","","","","split","start_send","","to_owned","","to_string","","","","try_from","","","","","","","","","","try_into","","","","","","","","","","try_poll_next","","type_id","","","","","","","","","","vzip","","","","","","","","","","backtrace","","","","","","","","","","code","source","","","","","span_trace","","","","","","","","","","url","","backtrace","","","","","","","","","","proxy_hostname","proxy_url","source","","","","span_trace","","","","","","","","","","status","url","data","problem","reconnect_in","remote_node_id","try_for","backtrace","","","","","","frame_type","source","","","","","span_trace","","","","","","backtrace","","","size","source","","span_trace","","","DEFAULT_HTTPS_PORT","DEFAULT_HTTP_PORT","DEFAULT_KEY_CACHE_CAPACITY","DEFAULT_METRICS_PORT","DEFAULT_RELAY_QUIC_PORT","DEFAULT_STUN_PORT","DnsError","DnsResolver","InvalidResponse","MissingHost","N0_DNS_NODE_ORIGIN_PROD","N0_DNS_NODE_ORIGIN_STAGING","NoResponse","Resolve","ResolveBoth","StaggeredError","TXT","Timeout","TxtLookup","__clone_box","","","as_error_source","","backtrace","","borrow","","","","","borrow_mut","","","","","cause","","clear_cache","clone","","","clone_into","","","clone_to_uninit","","","compat","","","","","compat_mut","","","","","compat_ref","","","","","default","deref","","","","","deref_mut","","","","","description","","drop","","","","","fmt","","","","","","","","from","","","","","","","","","in_current_span","","init","","","","","into","","","","","into_iter","lookup_ipv4","lookup_ipv4_ipv6","lookup_ipv4_ipv6_staggered","lookup_ipv4_staggered","lookup_ipv6","lookup_ipv6_staggered","lookup_node_by_domain_name","lookup_node_by_domain_name_staggered","lookup_node_by_id","lookup_node_by_id_staggered","lookup_txt","new","resolve","resolve_host","source","","to_owned","","","to_string","","","try_from","","","","","try_into","","","","","txt_data","type_id","","","","","vzip","","","","","with_nameserver","backtrace","","","","","","ipv4","ipv6","source","","span_trace","","","","","","Protocol","RELAY_PATH","RELAY_PROBE_PATH","Relay","Websocket","__clone_box","borrow","borrow_mut","clone","clone_into","clone_to_uninit","compat","compat_mut","compat_ref","default","deref","deref_mut","drop","eq","equivalent","","","fmt","from","init","into","parse_header","to_owned","try_from","try_into","type_id","upgrade_header","vzip","AttrFromString","DecodingError","","EncodingError","FailedBuildingPacket","IROH_TXT_NAME","InvalidEncodingZ32","InvalidLabel","InvalidLength","InvalidSignature","InvalidTxtEntry","LookupError","LookupFailed","MAX_LENGTH","MaxLengthExceededError","NodeData","NodeIdExt","NodeInfo","NotAnIrohRecord","NumLabels","ParseError","","UnexpectedFormat","UserData","Utf8","__clone_box","","","add_direct_addresses","as_error_source","","","","","as_ref","backtrace","","","","","borrow","","","","","","","","borrow_mut","","","","","","","","cause","","","","","clear_direct_addresses","clone","","","clone_into","","","clone_to_uninit","","","cmp","compare","compat","","","","","","","","compat_mut","","","","","","","","compat_ref","","","","","","","","data","default","deref","","","","","","","","","deref_mut","","","","","","","","","description","","","","","direct_addresses","drop","","","","","","","","eq","","","equivalent","","","","","","","","","fmt","","","","","","","","","","","","","","from","","","","","","","","","","","","from_parts","from_pkarr_signed_packet","from_str","from_txt_lookup","from_z32","hash","in_current_span","","","","","init","","","","","","","","into","","","","","","","","into_node_addr","new","","node_id","partial_cmp","relay_url","set_relay_url","set_user_data","source","","","","","to_node_addr","to_owned","","","to_pkarr_signed_packet","to_string","","","","","","to_txt_strings","to_z32","try_from","","","","","","","","","try_into","","","","","","","","type_id","","","","","","","","user_data","vzip","","","","","","","","with_direct_addresses","","with_relay_url","","with_user_data","","backtrace","","","len","source","","span_trace","","","backtrace","","source","","span_trace","","backtrace","","","source","","","span_trace","","","backtrace","","","","","","key","label","num_labels","s","source","","span_trace","","","","","","disco","relay","stun","MAGIC","looks_like_disco_wrapper","ClientInfo","ConnSend","FrameTooLarge","FrameType","Health","InvalidFrame","InvalidFrameType","InvalidSignature","Io","","KeepAlive","MAX_PACKET_SIZE","NotePreferred","PeerGone","Ping","Pong","RecvError","RecvPacket","Restarting","SendError","SendPacket","SerDe","","Timeout","","TooSmall","UnexpectedFrame","Unknown","__clone_box","as_error_source","","backtrace","","borrow","","","borrow_mut","","","cause","","clone","clone_into","clone_to_uninit","compat","","","compat_mut","","","compat_ref","","","deref","","","deref_mut","","","description","","drop","","","eq","equivalent","","","fmt","","","","","","from","","","","","","","","","","","","from_primitive","in_current_span","","init","","","into","","","source","","to_owned","to_string","","","try_from","","","try_into","","","type_id","","","vzip","","","backtrace","","","","","","","","","expected","frame_len","frame_type","got","source","","","","span_trace","","","","","","","","","backtrace","","","","source","","","","span_trace","","","","AlternateServer","ErrorCode","ErrorResponse","Fingerprint","Indication","InvalidFingerprint","InvalidMessage","MalformedAttrs","MappedAddress","MessageClass","MessageDecoder","MessageIntegrity","MessageIntegritySha256","NoFingerprint","Nonce","NotBinding","NotSuccessResponse","PasswordAlgorithm","PasswordAlgorithms","Realm","Request","Software","StunAttribute","StunDecodeError","StunError","SuccessResponse","TransactionId","Unknown","UnknownAttributes","UserHash","UserName","XorMappedAddress","__clone_box","","","","as_alternate_server","as_bytes","as_error_code","as_error_source","","as_fingerprint","as_mapped_address","as_message_integrity","as_message_integrity_sha256","as_nonce","as_password_algorithm","as_password_algorithms","as_realm","as_ref","as_software","as_unknown","as_unknown_attributes","as_user_hash","as_user_name","as_xor_mapped_address","attribute_type","backtrace","borrow","","","","","","borrow_mut","","","","","","cause","clone","","","","clone_into","","","","clone_to_uninit","","","","cmp","compare","compat","","","","","","compat_mut","","","","","","compat_ref","","","","","","decode","default","","deref","","","","","","","deref_mut","","","","","","description","drop","","","","","","eq","","equivalent","","","","","","expect_alternate_server","expect_error_code","expect_fingerprint","expect_mapped_address","expect_message_integrity","expect_message_integrity_sha256","expect_nonce","expect_password_algorithm","expect_password_algorithms","expect_realm","expect_software","expect_unknown","expect_unknown_attributes","expect_user_hash","expect_user_name","expect_xor_mapped_address","fmt","","","","","","","","","from","","","","","","","","","","","","","","","","","","","","","","","","get_context","hash","in_current_span","","init","","","","","","into","","","","","","is","is_alternate_server","is_error_code","is_fingerprint","is_mapped_address","is_message_integrity","is_message_integrity_sha256","is_nonce","is_password_algorithm","is_password_algorithms","is_realm","is_software","is_unknown","is_unknown_attributes","is_user_hash","is_user_name","is_xor_mapped_address","methods","parse_binding_request","parse_response","partial_cmp","request","response","source","to_owned","","","","to_string","","","try_from","","","","","","","try_into","","","","","","type_id","","","","","","vzip","","","","","","backtrace","","","","","","span_trace","","","","","","BINDING","RESERVED","SHARED_SECRET","ALPN_QUIC_ADDR_DISC","Connect","Connection","Error","NoIntitialCipherSuite","QUIC_ADDR_DISC_CLOSE_CODE","QUIC_ADDR_DISC_CLOSE_REASON","QuicClient","WatchRecv","as_error_source","backtrace","borrow","","borrow_mut","","cause","compat","","compat_mut","","compat_ref","","deref","","deref_mut","","description","drop","","fmt","","","from","","","","","","get_addr_and_latency","in_current_span","init","","into","","new","source","to_string","try_from","","try_into","","type_id","","vzip","","backtrace","","","","source","","","","span_trace","","","","Access","AccessConfig","AcmeEventStreamFinished","Allow","BindTcpListener","BindTlsListener","CertConfig","ClientRateLimit","DEFAULT_CERT_RELOAD_INTERVAL","Deny","Everyone","JoinError","LetsEncrypt","Limits","LocalAddr","Manual","Metrics","","NoLocalAddr","NoRelayServicesEnabled","QuicConfig","QuicSpawn","RelayConfig","RelayMetrics","Reloading","ReloadingResolver","Restricted","Server","ServerConfig","SpawnError","StunConfig","StunMetrics","SupervisorError","TaskCancelled","TlsConfig","TlsHeaderParse","UdpSocketBind","__clone_box","","","accept_conn_burst","accept_conn_limit","accepts","access","as_error_source","","as_iterable","","backtrace","","bad_requests","bind_addr","","borrow","","","","","","","","","","","","","","","","","borrow_mut","","","","","","","","","","","","","","","","","bytes_per_second","bytes_recv","bytes_sent","cause","","cert","certificates","client_rx","clone","","","clone_into","","","clone_to_uninit","","","compat","","","","","","","","","","","","","","","","","compat_mut","","","","","","","","","","","","","","","","","compat_ref","","","","","","","","","","","","","","","","","conns_rx_ratelimited_total","default","","","","","deref","","","","","","","","","","","","","","","","","","deref_mut","","","","","","","","","","","","","","","","","description","","disco_packets_dropped","disco_packets_recv","disco_packets_sent","disconnects","drop","","","","","","","","","","","","","","","","","eq","equivalent","","","failures","field_count","","field_ref","","fmt","","","","","","","","","","","","","","","","","","","frames_rx_ratelimited_total","from","","","","","","","","","","","","","","","","","","got_ping","groups","groups_cloned","http_addr","http_bind_addr","http_url","https_addr","https_bind_addr","https_url","in_current_span","","init","","","","","","","","","","","","","","","","","","into","","","","","","","","","","","","","","","","","ipv4_success","ipv6_success","is_allowed","key_cache_capacity","limits","max_burst_bytes","metrics","metrics_addr","name","","","other_packets_dropped","other_packets_recv","other_packets_sent","quic","quic_addr","quic_bind_addr","relay","relay_accepts","reload","requests","resolve","send_packets_dropped","send_packets_recv","send_packets_sent","sent_pong","server","server_config","","shutdown","","source","","spawn","stun","","stun_addr","task_handle","testing","tls","to_owned","","","to_string","","try_from","","","","","","","","","","","","","","","","","try_into","","","","","","","","","","","","","","","","","type_id","","","","","","","","","","","","","","","","","unique_client_keys","unknown_frames","vzip","","","","","","","","","","","","","","","","","websocket_accepts","certs","state","addr","backtrace","","","","","","","source","","","","","","span_trace","","","","","","","backtrace","","","","","source","","span_trace","","","","","quic_config","relay_config","self_signed_tls_certs_and_config","server_config","stun_config","tls_config"],"q":[[0,"iroh_relay"],[142,"iroh_relay::client"],[436,"iroh_relay::client::ConnectError"],[464,"iroh_relay::client::DialError"],[492,"iroh_relay::client::ReceivedMessage"],[497,"iroh_relay::client::RecvError"],[515,"iroh_relay::client::SendError"],[524,"iroh_relay::defaults"],[530,"iroh_relay::dns"],[679,"iroh_relay::dns::DnsError"],[695,"iroh_relay::http"],[728,"iroh_relay::node_info"],[990,"iroh_relay::node_info::DecodingError"],[999,"iroh_relay::node_info::EncodingError"],[1005,"iroh_relay::node_info::LookupError"],[1014,"iroh_relay::node_info::ParseError"],[1032,"iroh_relay::protos"],[1035,"iroh_relay::protos::disco"],[1037,"iroh_relay::protos::relay"],[1150,"iroh_relay::protos::relay::RecvError"],[1176,"iroh_relay::protos::relay::SendError"],[1188,"iroh_relay::protos::stun"],[1443,"iroh_relay::protos::stun::StunError"],[1455,"iroh_relay::protos::stun::methods"],[1458,"iroh_relay::quic"],[1513,"iroh_relay::quic::Error"],[1525,"iroh_relay::server"],[1953,"iroh_relay::server::CertConfig"],[1955,"iroh_relay::server::SpawnError"],[1976,"iroh_relay::server::SupervisorError"],[1988,"iroh_relay::server::testing"],[1994,"dyn_clone::sealed"],[1995,"iroh_relay::relay_map"],[1996,"core::cmp"],[1997,"async_compat"],[1998,"iroh_base::relay_url"],[1999,"iroh_relay::ping_tracker"],[2000,"core::time"],[2001,"core::result"],[2002,"serde::de"],[2003,"core::fmt"],[2004,"core::iter::traits::collect"],[2005,"alloc::sync"],[2006,"core::option"],[2007,"core::iter::traits::iterator"],[2008,"serde::ser"],[2009,"alloc::string"],[2010,"core::any"],[2011,"core::ops::function"],[2012,"core::marker"],[2013,"core::error"],[2014,"iroh_relay::client::conn"],[2015,"backtrace::capture"],[2016,"tokio_websockets::error"],[2017,"std::io::error"],[2018,"tokio::time::error"],[2019,"core::net::socket_addr"],[2020,"rustls::client::client_conn"],[2021,"iroh_base::key"],[2022,"core::convert"],[2023,"core::pin"],[2024,"core::task::wake"],[2025,"core::task::poll"],[2026,"url"],[2027,"governor::state::direct"],[2028,"governor::state"],[2029,"governor::state::direct::sinks"],[2030,"governor::clock::with_std"],[2031,"governor::gcra"],[2032,"governor::middleware"],[2033,"governor::jitter"],[2034,"governor::state::direct::streams"],[2035,"http::status"],[2036,"hyper::error"],[2037,"n0_snafu::spantrace"],[2038,"bytes::bytes"],[2039,"core::str::error"],[2040,"hickory_resolver::error"],[2041,"hickory_resolver::resolver"],[2042,"hickory_resolver::lookup"],[2043,"core::net::ip_addr"],[2044,"reqwest::dns::resolve"],[2045,"alloc::boxed"],[2046,"http::header::value"],[2047,"alloc::collections::btree::set"],[2048,"pkarr::signed_packet"],[2049,"iroh_base::node_addr"],[2050,"core::hash"],[2051,"alloc::vec"],[2052,"z32"],[2053,"ed25519_dalek::errors"],[2054,"simple_dns::simple_dns_error"],[2055,"hickory_proto::error"],[2056,"postcard::error"],[2057,"stun_rs::attributes"],[2058,"stun_rs::attributes::stun::alternate_server"],[2059,"stun_rs::error"],[2060,"stun_rs::types"],[2061,"stun_rs::attributes::stun::error_code"],[2062,"stun_rs::attributes::stun::fingerprint"],[2063,"stun_rs::attributes::stun::mapped_address"],[2064,"stun_rs::attributes::stun::message_integrity"],[2065,"stun_rs::attributes::stun::message_integrity_sha256"],[2066,"stun_rs::attributes::stun::nonce"],[2067,"stun_rs::attributes::stun::password_algorithm"],[2068,"stun_rs::attributes::stun::password_algorithms"],[2069,"stun_rs::attributes::stun::realm"],[2070,"stun_rs::attributes::stun::software"],[2071,"stun_rs::attributes::unknown"],[2072,"stun_rs::attributes::stun::unknown_attributes"],[2073,"stun_rs::attributes::stun::user_hash"],[2074,"stun_rs::attributes::stun::user_name"],[2075,"stun_rs::attributes::stun::xor_mapped_address"],[2076,"stun_rs::context"],[2077,"stun_rs::message"],[2078,"iroh_quinn_proto::varint"],[2079,"iroh_quinn_proto::endpoint"],[2080,"iroh_quinn_proto::connection"],[2081,"tokio::sync::watch::error"],[2082,"iroh_quinn_proto::crypto::rustls"],[2083,"iroh_quinn::endpoint"],[2084,"iroh_relay::server::metrics"],[2085,"iroh_metrics::metrics"],[2086,"iroh_metrics::iterable"],[2087,"core::num::nonzero"],[2088,"rustls_pki_types"],[2089,"core::default"],[2090,"iroh_relay::server::resolver"],[2091,"iroh_metrics::base"],[2092,"tokio::runtime::task::error"],[2093,"rustls::crypto::signer"],[2094,"reloadable_core"],[2095,"rustls::server::server_conn"],[2096,"tokio_util::task::abort_on_drop"],[2097,"tokio_rustls_acme::state"],[2098,"stun_rs"],[2099,"stun_rs::methods"]],"i":"`````jlnAj3210321`32132132121210321032103213010`0321032121`032133213332221110332210333221333`032103213300`32101``221`22032132032103210321230321`````Dn`E`Dh2EbDl43434031411Eh201144444`2`3``02451551532Cl0426542654231650EdEjEl75649832107598636363756498321075649832107564983210375649832107564983210759875649832107755649988321077755555649999888832107598756498321037564983210330`32121202133212120207598221637598756498321075649832102075649832107564983210IdIfIhIjIlInJ`JbJdJf476530987654321098JnK`KbKdKfKhKjKlKnL`138762987654321045LbLfLh20LlLnM`MbMdMf054321543210MlMnN`021210````````Fh0``000``0`G`NhNj3Nb40403214032140332132132140321403214032134032140321404032144003211444033221404032140321233333333333333403214014032140321140321403213A@dA@fA@hA@jA@lA@n3351543210```Gj00000000000000000000000000000AAl`0`AAf`AAhOl112`0AAd````44`14`4AAb1Oj154AAj473650476523014765230147650472231231231336523014765230147652301471265230114765230114765047265230147231222333111665523300144776652230114771131ABl4761587634125876341258232243337615823422764158207634412587634125876341258376341258323232ABnAC`ACb120210AChACj1010ACnAD`ADb210210ADfADhADjADlADnAE`413520543210`````MhFdFb`2000102`2222`22`210100022101021021010222210210210210210102102222221100221111100000210210210102210210210210210AEdAEfAEhAEjAElAEnAF`AFbAFd76178543876543210AFfAFhAFjAFl32103210AFn0AIj10AIf002``22020022212```1`22222AIh2AGd4404AIn355555555155555553241503241503324152415241511241503241503241503221241150324150332415034144411155555555555555552411500332411155555555555555555032103241503241503`5555555555555555```1``324151032441503241503241503241503AJdAJfAJhAJjAJlAJn543210````AKd0`0```0000AKf101101010101011011011111001101001110101010ALbALdALfALh32103210``AMhANnAMf0```1AMb3ANf`20`424`2``0`1``````4`22ANl4AN`ALj0ALlAM`791AMj8:0AMlAMn427AOdAO`5;=32ANd89;ANh>AMh97<438>ANn763;<>2AMf2=;;0243<>1=>1=>1=;9>65:AMb2985=>ANf524=;ANl98=24;:7?AN`2746?=1:9>35<;8ALj13857ALl0?3;10?3<<;AM`68?>;235:791AMj5>=179AMlAMn>568=:<:<4444427AOdAO`5;=32ANd89;ANh>AMhANn0008:8:8:8=549?0763;<>2AMf022;;9>65:AMb2985=>ANf5244=ANl06=667635><0998=24;:7?AN`2746?=1:9>35<;8ALj13857>>4??18:ALl?3000;9:;0=179AMlAMn>568=:<427AOdAO`5;=32ANd89;ANh>AMh97<438>ANn763;<>2AMf2;;;9>65:AMb2985=>ANf524=B@hB@jB@nBA`BAbBAdBAfBAhBAj65432105432106BAnBB`BBbBBdBBf4243210``````","f":"`````{{bd}f}00{b{{b{c}}}{}}000{{{b{h}}}{{b{hc}}}{}}000`{{{b{j}}}j}{{{b{l}}}l}{{{b{n}}}n}{{b{b{hc}}}f{}}00{{bA`}f}00{{{b{l}}{b{l}}}Ab}{{{b{n}}{b{n}}}Ab}{{b{b{c}}}Ab{}}0{{}{{Ad{c}}}{}}000{{{b{h}}}{{Ad{{b{hc}}}}}{}}000{b{{Ad{{b{c}}}}}{}}000{{{b{j}}{b{Af}}}Ah}{{}Aj}{{}n}{{{b{Aj}}}Al}`{An{{b{c}}}{}}000{An{{b{hc}}}{}}000{c{{B`{l}}}Bb}{c{{B`{n}}}Bb}`{Anf}000{{}j}{{{b{j}}{b{j}}}Ah}{{{b{l}}{b{l}}}Ah}{{{b{n}}{b{n}}}Ah}{{b{b{c}}}Ah{}}00000000{{{b{Aj}}{b{hBd}}}Bf}{{{b{j}}{b{hBd}}}Bf}0{{{b{l}}{b{hBd}}}Bf}0{{{b{n}}{b{hBd}}}Bf}{cc{}}0{lj}{Afj}2{Afl}3{cj{{Bj{}{{Bh{Af}}}}}}{cj{{Bj{}{{Bh{l}}}}}}{{{b{j}}{b{Af}}}{{Bn{{b{{Bl{l}}}}}}}}`{{}An}000{{}c{}}000{{{b{j}}}Ah}{{{b{j}}}An}{AlAj}{{{b{hAj}}}{{C`{A`}}}}`{{{b{j}}}{{`{{Cb{}{{Bh{{b{{Bl{l}}}}}}}}}}}}{{{b{l}}{b{l}}}{{Bn{Ab}}}}{{{b{n}}{b{n}}}{{Bn{Ab}}}}{{{b{hAj}}{C`{A`}}}f}{nCd}``{lBn}{{{b{l}}c}B`Cf}{{{b{n}}c}B`Cf}`{lAh}{lCd}{{{b{hAj}}}f}{bc{}}00{bCh}0{c{{B`{e}}}{}{}}000{{}{{B`{c}}}{}}000{bCj}000{lAf}{{{b{j}}}{{`{{Cb{}{{Bh{{b{Af}}}}}}}}}}{{}c{}}000`````````````````````````````````````````````````{{bd}f}0{{Clc}Cl{{D`{}{{Cn{Ah}}}}DbDd}}{b{{b{Df}}}}000{{{b{Dh}}}{{Bn{{b{Dj}}}}}}{{{b{Dl}}}{{Bn{{b{Dj}}}}}}{{{b{Dn}}}{{Bn{{b{Dj}}}}}}{{{b{E`}}}{{Bn{{b{Dj}}}}}}{b{{b{c}}}{}}000000000{{{b{h}}}{{b{hc}}}{}}000000000{{{b{Dh}}}{{Bn{{b{Df}}}}}}{{{b{Dl}}}{{Bn{{b{Df}}}}}}{{{b{Dn}}}{{Bn{{b{Df}}}}}}{{{b{E`}}}{{Bn{{b{Df}}}}}}{{{b{Eb}}}Eb}{{{b{Cl}}}Cl}{{b{b{hc}}}f{}}0{{bA`}f}0{{}{{Ad{c}}}{}}000000000{{{b{h}}}{{Ad{{b{hc}}}}}{}}000000000{b{{Ad{{b{c}}}}}{}}000000000{{{b{Cl}}}{{B`{EdDn}}}}{An{{b{c}}}{}}000000000{An{{b{hc}}}{}}000000000{{{b{Dh}}}{{b{Ef}}}}{{{b{Dl}}}{{b{Ef}}}}{{{b{Dn}}}{{b{Ef}}}}{{{b{E`}}}{{b{Ef}}}}{Anf}000000000{{{b{Dh}}{b{hBd}}}Bf}0{{{b{Dl}}{b{hBd}}}Bf}0{{{b{Eb}}{b{hBd}}}Bf}{{{b{Eh}}{b{hBd}}}Bf}{{{b{Dn}}{b{hBd}}}Bf}0{{{b{E`}}{b{hBd}}}Bf}0{{{b{Cl}}{b{hBd}}}Bf}{{{b{Ed}}{b{hBd}}}Bf}{{{b{Ej}}{b{hBd}}}Bf}{{{b{El}}{b{hBd}}}Bf}{cc{}}{EnDh}{F`Dh}{F`Dl}{EnDl}4{FbDl}{FdDl}66{E`Dn}{FdDn}8{EnDn}{FfE`}{F`E`};{FhE`}<<<<{{}}000{{}An}000000000{{ClAh}Cl}{{}c{}}0000000001{{ClAn}Cl}{{{b{El}}}{{Bn{Fj}}}}{{}Fl}{{cFnG`}Cl{{Gb{Af}}}}{{{Gd{{b{hEd}}}}{b{hGf}}}{{Gh{{B`{fc}}}}}{}}{{{Gd{{b{hEj}}}}{b{hGf}}}{{Gh{{B`{fc}}}}}{}}10{{{Gd{{b{hEd}}}}{b{hGf}}}{{Gh{{Bn{c}}}}}{}}{{{Gd{{b{hEl}}}}{b{hGf}}}{{Gh{{Bn{c}}}}}{}}32{{ClGj}Cl}{{ClGl}Cl}{{{b{{H`{Gnceg}}}}}{{Hb{ikceg}}}HdHf{{Hl{}{{Hh{Hj}}}}}{}{}}0{{{b{{H`{Gnceg}}}}Hn}{{Hb{ikceg}}}HdHf{{Hl{}{{Hh{Hj}}}}}{}{}}0{{{b{{H`{Gnceg}}}}}{{I`{iceg}}}HdHfHl{}}0{{{b{{H`{Gnceg}}}}Hn}{{I`{iceg}}}HdHfHl{}}0{{{b{Dh}}}{{Bn{{b{Df}}}}}}{{{b{Dl}}}{{Bn{{b{Df}}}}}}{{{b{Dn}}}{{Bn{{b{Df}}}}}}{{{b{E`}}}{{Bn{{b{Df}}}}}}{Ed{{Ib{ElEj}}}}{{{Gd{{b{hEd}}}}Eh}{{B`{fc}}}{}}{{{Gd{{b{hEj}}}}Eh}{{B`{fc}}}{}}{bc{}}0{bCh}000{c{{B`{e}}}{}{}}000000000{{}{{B`{c}}}{}}000000000{{{Gd{{b{hc}}}}{b{hGf}}}{{Gh{{Bn{B`}}}}}{}}0{bCj}000000000{{}c{}}000000000{IdBn}{IfBn}{IhBn}{IjBn}{IlBn}{InBn}{J`Bn}{JbBn}{JdBn}{JfBn}{InJh}{IhEn}{IjFd}{IlE`}{J`Jj}{JfF`}{IdJl}{IfJl}{IhJl}{IjJl}{IlJl}{InJl}{J`Jl}{JbJl}{JdJl}{JfJl}{IdGl}{IfGl}{JnBn}{K`Bn}{KbBn}{KdBn}{KfBn}{KhBn}{KjBn}{KlBn}{KnBn}{L`Bn}{KnCh}{KjGl}{K`Fh}{KbFf}{KdF`}{KlJj}{JnJl}{K`Jl}{KbJl}{KdJl}{KfJl}{KhJl}{KjJl}{KlJl}{KnJl}{L`Jl}{KhJh}{KfGl}{LbLd}{LfBn}{LhAl}{LbLj}1{LlBn}{LnBn}{M`Bn}{MbBn}{MdBn}{MfBn}{MfMh}{LlF`}{LnFd}{M`Fb}{MbEn}{MdMj}{LlJl}{LnJl}{M`Jl}{MbJl}{MdJl}{MfJl}{MlBn}{MnBn}{N`Bn}{N`An}{MlF`}{MnEn}{MlJl}{MnJl}{N`Jl}{{}Cd}0{{}An}111````{{}b}0```````{{bd}f}00{b{{b{Df}}}}0{{{b{Fh}}}{{Bn{{b{Dj}}}}}}{{{b{{Nb{c}}}}}{{Bn{{b{Dj}}}}}{NdNf}}{b{{b{c}}}{}}0000{{{b{h}}}{{b{hc}}}{}}0000{{{b{Fh}}}{{Bn{{b{Df}}}}}}{{{b{{Nb{c}}}}}{{Bn{{b{Df}}}}}{NdNf}}{{{b{G`}}}f}{{{b{G`}}}G`}{{{b{Nh}}}Nh}{{{b{Nj}}}Nj}{{b{b{hc}}}f{}}00{{bA`}f}00{{}{{Ad{c}}}{}}0000{{{b{h}}}{{Ad{{b{hc}}}}}{}}0000{b{{Ad{{b{c}}}}}{}}0000{{}G`}{An{{b{c}}}{}}0000{An{{b{hc}}}{}}0000{{{b{Fh}}}{{b{Ef}}}}{{{b{{Nb{c}}}}}{{b{Ef}}}{NdNf}}{Anf}0000{{{b{Fh}}{b{hBd}}}Bf}0{{{b{{Nb{c}}}}{b{hBd}}}Bf{NdNdNf}}{{{b{{Nb{c}}}}{b{hBd}}}Bf{NdNf}}{{{b{G`}}{b{hBd}}}Bf}{{{b{Nh}}{b{hBd}}}Bf}{{{b{Nj}}{b{hBd}}}Bf}0{cc{}}{FfFh}{NlFh}2{NnG`}3{O`Nh}44{{}}0{{}An}0000{{}c{}}0000{Nhc{}}{{{b{G`}}cAl}{{B`{{`{{Cb{}{{Bh{Ob}}}}}}Fh}}}Od}0{{{b{G`}}cAl{b{{Oh{Of}}}}}{{B`{{`{{Cb{}{{Bh{Ob}}}}}}{Nb{Fh}}}}}Od}010{{{b{G`}}{b{Ef}}}{{B`{OjOl}}}}{{{b{G`}}{b{Ef}}{b{{Oh{Of}}}}}{{B`{Oj{Nb{Ol}}}}}}{{{b{G`}}{b{Lj}}{b{Ef}}}{{B`{OjOl}}}}{{{b{G`}}{b{Lj}}{b{Ef}}{b{{Oh{Of}}}}}{{B`{Oj{Nb{Ol}}}}}}{{{b{G`}}cAl}{{B`{NhFh}}}Od}{{}G`}{{{b{G`}}On}A@`}{{{b{G`}}{b{Gl}}AhAl}{{B`{ObFh}}}}{{{b{Fh}}}{{Bn{{b{Df}}}}}}{{{b{{Nb{c}}}}}{{Bn{{b{Df}}}}}{NdNf}}{bc{}}00{bCh}00{c{{B`{e}}}{}{}}0000{{}{{B`{c}}}{}}0000{{{b{Nj}}}{{b{{Oh{{A@b{{Oh{A`}}}}}}}}}}{bCj}0000{{}c{}}0000{FjG`}{A@dBn}{A@fBn}{A@hBn}{A@jBn}{A@lBn}{A@nBn}{A@hA@b}0{A@dFf}{A@lNl}{A@dJl}{A@fJl}{A@hJl}{A@jJl}{A@lJl}{A@nJl}`{{}b}0``{{bd}f}{b{{b{c}}}{}}{{{b{h}}}{{b{hc}}}{}}{{{b{Gj}}}Gj}{{b{b{hc}}}f{}}{{bA`}f}{{}{{Ad{c}}}{}}{{{b{h}}}{{Ad{{b{hc}}}}}{}}{b{{Ad{{b{c}}}}}{}}{{}Gj}{An{{b{c}}}{}}{An{{b{hc}}}{}}{Anf}{{{b{Gj}}{b{Gj}}}Ah}{{b{b{c}}}Ah{}}00{{{b{Gj}}{b{hBd}}}Bf}{cc{}}{{}An}{{}c{}}{{{b{AA`}}}{{Bn{Gj}}}}{bc{}}{c{{B`{e}}}{}{}}{{}{{B`{c}}}{}}{bCj}{{{b{Gj}}}{{b{Ef}}}}{{}c{}}`````{{}b}```````````````````{{bd}f}00{{{b{hAAb}}c}f{{Bj{}{{Bh{Fj}}}}}}{b{{b{Df}}}}0000{{{b{AAd}}}{{b{Ef}}}}{{{b{AAf}}}{{Bn{{b{Dj}}}}}}{{{b{AAh}}}{{Bn{{b{Dj}}}}}}{{{b{AAj}}}{{Bn{{b{Dj}}}}}}{{{b{Ol}}}{{Bn{{b{Dj}}}}}}{{{b{AAl}}}{{Bn{{b{Dj}}}}}}{b{{b{c}}}{}}0000000{{{b{h}}}{{b{hc}}}{}}0000000{{{b{AAf}}}{{Bn{{b{Df}}}}}}{{{b{AAh}}}{{Bn{{b{Df}}}}}}{{{b{AAj}}}{{Bn{{b{Df}}}}}}{{{b{Ol}}}{{Bn{{b{Df}}}}}}{{{b{AAl}}}{{Bn{{b{Df}}}}}}{{{b{hAAb}}}f}{{{b{AAb}}}AAb}{{{b{AAd}}}AAd}{{{b{Oj}}}Oj}{{b{b{hc}}}f{}}00{{bA`}f}00{{{b{AAd}}{b{AAd}}}Ab}{{b{b{c}}}Ab{}}{{}{{Ad{c}}}{}}0000000{{{b{h}}}{{Ad{{b{hc}}}}}{}}0000000{b{{Ad{{b{c}}}}}{}}0000000{OjAAb}{{}AAb}{An{{b{c}}}{}}0000{{{b{Oj}}}{{b{c}}}{}}111{An{{b{hc}}}{}}0000{{{b{hOj}}}{{b{hc}}}{}}111{{{b{AAf}}}{{b{Ef}}}}{{{b{AAh}}}{{b{Ef}}}}{{{b{AAj}}}{{b{Ef}}}}{{{b{Ol}}}{{b{Ef}}}}{{{b{AAl}}}{{b{Ef}}}}{{{b{AAb}}}{{b{{AAn{Fj}}}}}}{Anf}0000000{{{b{AAb}}{b{AAb}}}Ah}{{{b{AAd}}{b{AAd}}}Ah}{{{b{Oj}}{b{Oj}}}Ah}{{b{b{c}}}Ah{}}00000000{{{b{AAf}}{b{hBd}}}Bf}0{{{b{AAh}}{b{hBd}}}Bf}0{{{b{AAb}}{b{hBd}}}Bf}{{{b{AAd}}{b{hBd}}}Bf}0{{{b{AAj}}{b{hBd}}}Bf}0{{{b{Oj}}{b{hBd}}}Bf}{{{b{Ol}}{b{hBd}}}Bf}0{{{b{AAl}}{b{hBd}}}Bf}0{AB`AAf}{cc{}}0{ABbAAb}111{ABbOj}222{AAhAAl}{{LjAAb}Oj}{{{b{ABd}}}{{B`{OjAAl}}}}{{{b{Ef}}}{{B`{AAdc}}}{}}{Nh{{B`{OjAAl}}}}{{{b{Ef}}}{{B`{LjAAh}}}}{{{b{AAd}}{b{hc}}}fABf}{{}}0000{{}An}0000000{{}c{}}0000000{OjABb}{{{Bn{Af}}{AAn{Fj}}}AAb}{LjOj}{OjLj}{{{b{AAd}}{b{AAd}}}{{Bn{Ab}}}}{{{b{AAb}}}{{Bn{{b{Af}}}}}}{{{b{hAAb}}{Bn{Af}}}f}{{{b{hAAb}}{Bn{AAd}}}f}{{{b{AAf}}}{{Bn{{b{Df}}}}}}{{{b{AAh}}}{{Bn{{b{Df}}}}}}{{{b{AAj}}}{{Bn{{b{Df}}}}}}{{{b{Ol}}}{{Bn{{b{Df}}}}}}{{{b{AAl}}}{{Bn{{b{Df}}}}}}{{{b{Oj}}}ABb}{bc{}}00{{{b{Oj}}{b{Fn}}ABh}{{B`{ABdAAf}}}}{bCh}00000{{{b{Oj}}}{{ABj{Ch}}}}{{{b{ABl}}}Ch}{c{{B`{e}}}{}{}}000{Ch{{B`{AAdc}}}{}}1111{{}{{B`{c}}}{}}0000000{bCj}0000000{{{b{AAb}}}{{Bn{{b{AAd}}}}}}{{}c{}}0000000{{AAb{AAn{Fj}}}AAb}{{Oj{AAn{Fj}}}Oj}{{AAb{Bn{Af}}}AAb}{{Oj{Bn{Af}}}Oj}{{AAb{Bn{AAd}}}AAb}{{Oj{Bn{AAd}}}Oj}{ABnBn}{AC`Bn}{ACbBn}{AC`An}{ABnACd}{ACbACf}{ABnJl}{AC`Jl}{ACbJl}{AChBn}{ACjBn}{AChAB`}{ACjACl}{AChJl}{ACjJl}{ACnBn}{AD`Bn}{ADbBn}{ACnA@b}{AD`A@b}{ADbADd}{ACnJl}{AD`Jl}{ADbJl}{ADfBn}{ADhBn}{ADjBn}{ADlBn}{ADnBn}{AE`Bn}{ADhCh}{ADnCh}{ADjAn}{ADfCh}{ADlMj}{AE`A@b}{ADfJl}{ADhJl}{ADjJl}{ADlJl}{ADnJl}{AE`Jl}```{{}b}{{{b{{Oh{A`}}}}}Ah}```````````{{}An}````````````````{{bd}f}{b{{b{Df}}}}0{{{b{Fd}}}{{Bn{{b{Dj}}}}}}{{{b{Fb}}}{{Bn{{b{Dj}}}}}}{b{{b{c}}}{}}00{{{b{h}}}{{b{hc}}}{}}00{{{b{Fd}}}{{Bn{{b{Df}}}}}}{{{b{Fb}}}{{Bn{{b{Df}}}}}}{{{b{Mh}}}Mh}{{b{b{hc}}}f{}}{{bA`}f}{{}{{Ad{c}}}{}}00{{{b{h}}}{{Ad{{b{hc}}}}}{}}00{b{{Ad{{b{c}}}}}{}}00{An{{b{c}}}{}}00{An{{b{hc}}}{}}00{{{b{Fd}}}{{b{Ef}}}}{{{b{Fb}}}{{b{Ef}}}}{Anf}00{{{b{Mh}}{b{Mh}}}Ah}{{b{b{c}}}Ah{}}00{{{b{Mh}}{b{hBd}}}Bf}0{{{b{Fd}}{b{hBd}}}Bf}0{{{b{Fb}}{b{hBd}}}Bf}0{A`Mh}{cc{}}0{F`Fd}{FfFd}{DhFd}{AEbFd}4{ACfFb}{AEbFb}{FfFb}{F`Fb}{cMh{}}{{}}0{{}An}00{{}c{}}00{{{b{Fd}}}{{Bn{{b{Df}}}}}}{{{b{Fb}}}{{Bn{{b{Df}}}}}}{bc{}}{bCh}00{c{{B`{e}}}{}{}}00{{}{{B`{c}}}{}}00{bCj}00{{}c{}}00{AEdBn}{AEfBn}{AEhBn}{AEjBn}{AElBn}{AEnBn}{AF`Bn}{AFbBn}{AFdBn}{AEfMh}{AEhAn}{AFbMh}2{AEdF`}{AEjFf}{AElAEb}{AEnACf}{AEdJl}{AEfJl}{AEhJl}{AEjJl}{AElJl}{AEnJl}{AF`Jl}{AFbJl}{AFdJl}{AFfBn}{AFhBn}{AFjBn}{AFlBn}{AFfF`}{AFhFf}{AFjDh}{AFlAEb}{AFfJl}{AFhJl}{AFjJl}{AFlJl}````````````````````````````````{{bd}f}000{{{b{AFn}}}{{B`{{b{AG`}}AGb}}}}{{{b{AGd}}}{{b{{C`{A`}}}}}}{{{b{AFn}}}{{B`{{b{AGf}}AGb}}}}{b{{b{Df}}}}0{{{b{AFn}}}{{B`{{b{AGh}}AGb}}}}{{{b{AFn}}}{{B`{{b{AGj}}AGb}}}}{{{b{AFn}}}{{B`{{b{AGl}}AGb}}}}{{{b{AFn}}}{{B`{{b{AGn}}AGb}}}}{{{b{AFn}}}{{B`{{b{AH`}}AGb}}}}{{{b{AFn}}}{{B`{{b{AHb}}AGb}}}}{{{b{AFn}}}{{B`{{b{AHd}}AGb}}}}{{{b{AFn}}}{{B`{{b{AHf}}AGb}}}}{{{b{AGd}}}{{b{{Oh{A`}}}}}}{{{b{AFn}}}{{B`{{b{AHh}}AGb}}}}{{{b{AFn}}}{{B`{{b{AHj}}AGb}}}}{{{b{AFn}}}{{B`{{b{AHl}}AGb}}}}{{{b{AFn}}}{{B`{{b{AHn}}AGb}}}}{{{b{AFn}}}{{B`{{b{AI`}}AGb}}}}{{{b{AFn}}}{{B`{{b{AIb}}AGb}}}}{{{b{AFn}}}AId}{{{b{AIf}}}{{Bn{{b{Dj}}}}}}{b{{b{c}}}{}}00000{{{b{h}}}{{b{hc}}}{}}00000{{{b{AIf}}}{{Bn{{b{Df}}}}}}{{{b{AIh}}}AIh}{{{b{AIj}}}AIj}{{{b{AGd}}}AGd}{{{b{AFn}}}AFn}{{b{b{hc}}}f{}}000{{bA`}f}000{{{b{AGd}}{b{AGd}}}Ab}{{b{b{c}}}Ab{}}{{}{{Ad{c}}}{}}00000{{{b{h}}}{{Ad{{b{hc}}}}}{}}00000{b{{Ad{{b{c}}}}}{}}00000{{{b{AIh}}{b{{Oh{A`}}}}}{{B`{{Ib{AIlAn}}AIn}}}}{{}AIh}{{}AGd}{An{{b{c}}}{}}00{{{b{AGd}}}{{b{{Oh{A`}}}}}}111{An{{b{hc}}}{}}00000{{{b{AIf}}}{{b{Ef}}}}{Anf}00000{{{b{AIj}}{b{AIj}}}Ah}{{{b{AGd}}{b{AGd}}}Ah}{{b{b{c}}}Ah{}}00000{{{b{AFn}}}{{b{AG`}}}}{{{b{AFn}}}{{b{AGf}}}}{{{b{AFn}}}{{b{AGh}}}}{{{b{AFn}}}{{b{AGj}}}}{{{b{AFn}}}{{b{AGl}}}}{{{b{AFn}}}{{b{AGn}}}}{{{b{AFn}}}{{b{AH`}}}}{{{b{AFn}}}{{b{AHb}}}}{{{b{AFn}}}{{b{AHd}}}}{{{b{AFn}}}{{b{AHf}}}}{{{b{AFn}}}{{b{AHh}}}}{{{b{AFn}}}{{b{AHj}}}}{{{b{AFn}}}{{b{AHl}}}}{{{b{AFn}}}{{b{AHn}}}}{{{b{AFn}}}{{b{AI`}}}}{{{b{AFn}}}{{b{AIb}}}}{{{b{AIh}}{b{hBd}}}{{B`{fAJ`}}}}{{{b{AIj}}{b{hBd}}}{{B`{fAJ`}}}}{{{b{AGd}}{b{hBd}}}{{B`{fAJ`}}}}0{{{b{AFn}}{b{hBd}}}{{B`{fAJ`}}}}{{{b{AIn}}{b{hBd}}}{{B`{fAJ`}}}}0{{{b{AIf}}{b{hBd}}}Bf}0{cc{}}0{{{b{{C`{A`}}}}}AGd}{{{C`{A`}}}AGd}2{AHnAFn}{AGfAFn}{AIbAFn}{AI`AFn}{AHjAFn}{AHlAFn}{AHhAFn}{AG`AFn}{AHfAFn};{AHbAFn}{AH`AFn}{AGnAFn}{AGlAFn}{AGjAFn}{AGhAFn}{AHdAFn}{cc{}}0{{{b{AIh}}}{{Bn{{b{AJb}}}}}}{{{b{AGd}}{b{hc}}}fABf}{{}}0{{}An}00000{{}c{}}00000{{{b{{Oh{A`}}}}}Ah}{{{b{AFn}}}Ah}000000000000000`{{{b{{Oh{A`}}}}}{{B`{AGdAIf}}}}{{{b{{Oh{A`}}}}}{{B`{{Ib{AGdFj}}AIf}}}}{{{b{AGd}}{b{AGd}}}{{Bn{Ab}}}}{AGd{{ABj{A`}}}}{{AGdFj}{{ABj{A`}}}}{{{b{AIf}}}{{Bn{{b{Df}}}}}}{bc{}}000{bCh}00{c{{B`{e}}}{}{}}0{A`{{B`{AIj}}}}1111{{}{{B`{c}}}{}}00000{bCj}00000{{}c{}}00000{AJdBn}{AJfBn}{AJhBn}{AJjBn}{AJlBn}{AJnBn}{AJdJl}{AJfJl}{AJhJl}{AJjJl}{AJlJl}{AJnJl}{{}AK`}00{{}b}````{{}AKb}1``{b{{b{Df}}}}{{{b{AKd}}}{{Bn{{b{Dj}}}}}}{b{{b{c}}}{}}0{{{b{h}}}{{b{hc}}}{}}0{{{b{AKd}}}{{Bn{{b{Df}}}}}}{{}{{Ad{c}}}{}}0{{{b{h}}}{{Ad{{b{hc}}}}}{}}0{b{{Ad{{b{c}}}}}{}}0{An{{b{c}}}{}}0{An{{b{hc}}}{}}0{{{b{AKd}}}{{b{Ef}}}}{Anf}0{{{b{AKd}}{b{hBd}}}Bf}0{{{b{AKf}}{b{hBd}}}Bf}{AKhAKd}{AKjAKd}{AKlAKd}{cc{}}{AKnAKd}1{{{b{AKf}}Fj{b{Ef}}}{{B`{{Ib{FjAl}}AKd}}}}{{}}{{}An}0{{}c{}}0{{AL`Fl}{{B`{AKfAKd}}}}{{{b{AKd}}}{{Bn{{b{Df}}}}}}{bCh}{c{{B`{e}}}{}{}}0{{}{{B`{c}}}{}}0{bCj}0{{}c{}}0{ALbBn}{ALdBn}{ALfBn}{ALhBn}{ALbAKh}{ALdAKj}{ALfAKl}{ALhAKn}{ALbJl}{ALdJl}{ALfJl}{ALhJl}````````{{}Al}````````````````````````````{{bd}f}00{ALjBn}0{ALlALn}{AM`AMb}{b{{b{Df}}}}0{b{{b{AMd}}}}0{{{b{AMf}}}{{Bn{{b{Dj}}}}}}{{{b{AMh}}}{{Bn{{b{Dj}}}}}}{AMjALn}{AMlFj}{AMnFj}{b{{b{c}}}{}}0000000000000000{{{b{h}}}{{b{hc}}}{}}0000000000000000{AN`ANb};;{{{b{AMf}}}{{Bn{{b{Df}}}}}}{{{b{AMh}}}{{Bn{{b{Df}}}}}}{ANdANf}{{{b{ANh}}}{{Bn{{ABj{ANj}}}}}}{ALjBn}{{{b{ANl}}}ANl}{{{b{ANn}}}ANn}{{{b{AN`}}}AN`}{{b{b{hc}}}f{}}00{{bA`}f}00{{}{{Ad{c}}}{}}0000000000000000{{{b{h}}}{{Ad{{b{hc}}}}}{}}0000000000000000{b{{Ad{{b{c}}}}}{}}0000000000000000{ALlALn}{{}ALl}{{}AMj}{{}ANl}{{}{{AO`{ce}}}{AObNd}{AObNd}}{{}ALj}{An{{b{c}}}{}}000{{{b{{AOd{c}}}}}{{b{e}}}Db{}}1111111111111{An{{b{hc}}}{}}0000000000000000{{{b{AMf}}}{{b{Ef}}}}{{{b{AMh}}}{{b{Ef}}}}::::{Anf}0000000000000000{{{b{ANn}}{b{ANn}}}Ah}{{b{b{c}}}Ah{}}00{AMjALn}{{{b{ALl}}}An}{{{b{AMj}}}An}{{{b{ALl}}An}{{Bn{AOf}}}}{{{b{AMj}}An}{{Bn{AOf}}}}{{{b{ALl}}{b{hBd}}}Bf}{{{b{AMj}}{b{hBd}}}Bf}{{{b{ANl}}{b{hBd}}}Bf}{{{b{{AOd{c}}}}{b{hBd}}}Bf{NdDb}}{{{b{{AO`{ce}}}}{b{hBd}}}BfNdNd}{{{b{{AM`{ce}}}}{b{hBd}}}BfNdNd}{{{b{AMb}}{b{hBd}}}Bf}{{{b{ANn}}{b{hBd}}}Bf}{{{b{AMl}}{b{hBd}}}Bf}{{{b{AMn}}{b{hBd}}}Bf}{{{b{{ANd{ce}}}}{b{hBd}}}BfNdNd}{{{b{ALj}}{b{hBd}}}Bf}{{{b{AN`}}{b{hBd}}}Bf}{{{b{{ANf{ce}}}}{b{hBd}}}BfNdNd}{{{b{ANh}}{b{hBd}}}Bf}{{{b{AMf}}{b{hBd}}}Bf}0{{{b{AMh}}{b{hBd}}}Bf}0{ALlALn}{cc{}}000000000000000{AOhAMh}12{{{b{ANl}}}{{`{{Cb{}{{Bh{{b{AOj}}}}}}}}}}{{{b{ANl}}}{{`{{Cb{}{{Bh{{Bl{AOj}}}}}}}}}}{{{b{ANh}}}{{Bn{Fj}}}}{AM`Fj}{{{b{ANh}}}{{Bn{Af}}}}2{ANdFj}1{{}}0{{}An}00{{cAl}{{B`{{AOd{c}}}}}{Db{B@`{}{{AOl{AOn}}}}}}11111111111111{{}c{}}0000000000000000{AMjALn}0{{{b{AMb}}Lj}Ah}{AM`Bn}{AM`ALj}{AN`Bn}{{{b{ANh}}}{{b{ANl}}}}{AO`Bn}{{{b{ALl}}}{{b{Ef}}}}{{{b{AMj}}}{{b{Ef}}}}{{{b{ANl}}}{{b{Ef}}}}{ALlALn}004{{{b{ANh}}}{{Bn{Fj}}}}{ANdFj}62{{{b{{AOd{c}}}}}f{Db{B@`{}{{AOl{AOn}}}}}}={{{b{{AOd{c}}}}B@b}{{Bn{{Bl{AOn}}}}}{{B@`{}{{AOl{AOn}}}}DbNd}}4444{ANlBl}{AMnB@d}{ANdB@d}{{{AOd{c}}}f{Db{B@`{}{{AOl{AOn}}}}}}{ANh{{B`{fAMh}}}}{{{b{AMf}}}{{Bn{{b{Df}}}}}}{{{b{AMh}}}{{Bn{{b{Df}}}}}}{{{AO`{ce}}}{{B`{ANhAMf}}}NdNd}7{AO`Bn}<{{{b{hANh}}}{{b{h{B@f{{B`{fAMh}}}}}}}}`{AM`Bn}{bc{}}00{bCh}0{c{{B`{e}}}{}{}}0000000000000000{{}{{B`{c}}}{}}0000000000000000{bCj}0000000000000000{ALlALn}0{{}c{}}00000000000000001{B@hABj}{B@jB@l}{B@nFj}{BA`Bn}{BAbBn}{BAdBn}{BAfBn}{BAhBn}{BAjBn}{B@nBn}{BA`F`}{BAbF`}`{BAfBAl}{BAhF`}{BAjF`}{BA`Jl}{BAbJl}{BAdJl}{BAfJl}{BAhJl}{BAjJl}{B@nJl}{BAnBn}{BB`Bn}{BBbBn}{BBdBn}{BBfBn}{BAnF`}{BBbAOh}{BAnJl}{BB`Jl}{BBbJl}{BBdJl}{BBfJl}{{}AMn}{{}{{AM`{f}}}}{{}{{Ib{{ABj{ANj}}B@d}}}}{{}{{AO`{f}}}}{{}AMl}{{}{{ANd{f}}}}","D":"CJh","p":[[1,"reference",null,null,1],[5,"Private",1994],[1,"unit"],[0,"mut"],[5,"RelayMap",0,1995],[5,"RelayNode",0,1995],[5,"RelayQuicConfig",0,1995],[1,"u8"],[6,"Ordering",1996],[5,"Compat",1997],[5,"RelayUrl",1998],[1,"bool"],[5,"PingTracker",0,1999],[5,"Duration",2000],[1,"usize"],[6,"Result",2001,null,1],[10,"Deserializer",2002],[5,"Formatter",2003],[8,"Result",2003],[17,"Item"],[10,"IntoIterator",2004],[5,"Arc",2005,null,1],[6,"Option",2006,null,1],[1,"array"],[10,"Iterator",2007],[1,"u16"],[10,"Serializer",2008],[5,"String",2009],[5,"TypeId",2010],[5,"ClientBuilder",142],[17,"Output"],[10,"Fn",2011],[10,"Send",2012],[10,"Sync",2012],[10,"Error",2013],[6,"SendError",142,2014],[5,"Backtrace",2015],[6,"RecvError",142,2014],[6,"ConnectError",142],[6,"DialError",142],[6,"ReceivedMessage",142,2014],[5,"Client",142],[1,"str"],[6,"SendMessage",142,2014],[5,"ClientSink",142],[5,"ClientStream",142],[6,"Error",2016],[5,"Error",2017],[6,"RecvError",1037],[6,"SendError",1037],[5,"Elapsed",2018],[6,"DnsError",530],[6,"SocketAddr",2019],[5,"ClientConfig",2020],[5,"SecretKey",2021],[5,"DnsResolver",530],[10,"Into",2022,null,1],[5,"Pin",2023],[5,"Context",2024],[6,"Poll",2025],[6,"Protocol",695],[5,"Url",2026],[6,"NotKeyed",2027],[5,"RateLimiter",2028],[5,"RatelimitedSink",2029],[10,"DirectStateStore",2027],[10,"ReasonablyRealtime",2030],[17,"NegativeOutcome"],[5,"NotUntil",2031],[10,"RateLimitingMiddleware",2032],[5,"Jitter",2033],[5,"RatelimitedStream",2034],[1,"tuple",null,null,1],[15,"InvalidWebsocketUrl",436],[15,"InvalidRelayUrl",436],[15,"Websocket",436],[15,"Handshake",436],[15,"Dial",436],[15,"UnexpectedUpgradeStatus",436],[15,"Upgrade",436],[15,"InvalidTlsServername",436],[15,"NoLocalAddr",436],[15,"Tls",436],[5,"StatusCode",2035],[5,"Error",2036],[5,"SpanTrace",2037],[15,"InvalidTargetPort",464],[15,"Dns",464],[15,"Timeout",464],[15,"Io",464],[15,"InvalidUrl",464],[15,"ProxyConnectInvalidStatus",464],[15,"ProxyInvalidUrl",464],[15,"ProxyConnect",464],[15,"ProxyInvalidTlsServername",464],[15,"ProxyInvalidTargetPort",464],[15,"ReceivedPacket",492],[5,"Bytes",2038],[15,"Health",492],[15,"ServerRestarting",492],[8,"NodeId",2021],[15,"Io",497],[15,"ProtocolSend",497],[15,"ProtocolRecv",497],[15,"Websocket",497],[15,"InvalidProtocolMessageEncoding",497],[15,"UnexpectedFrame",497],[6,"FrameType",1037],[5,"Utf8Error",2039],[15,"RelayIo",515],[15,"WebsocketIo",515],[15,"ExceedsMaxPacketSize",515],[5,"StaggeredError",530],[10,"Debug",2003],[10,"Display",2003],[5,"TxtLookup",530],[5,"TXT",530],[5,"ResolveError",2040],[8,"TokioResolver",2041],[5,"TxtLookup",2042],[6,"IpAddr",2043],[10,"ToString",2009],[1,"u64"],[1,"slice"],[5,"NodeInfo",728],[6,"LookupError",728],[5,"Name",2044],[8,"Resolving",2044],[5,"Box",2045,null,1],[15,"Timeout",679],[15,"NoResponse",679],[15,"ResolveBoth",679],[15,"MissingHost",679],[15,"Resolve",679],[15,"InvalidResponse",679],[5,"HeaderValue",2046],[5,"NodeData",728],[5,"UserData",728],[6,"EncodingError",728],[6,"DecodingError",728],[5,"MaxLengthExceededError",728],[6,"ParseError",728],[5,"BTreeSet",2047],[6,"SignedPacketBuildError",2048],[5,"NodeAddr",2049],[5,"SignedPacket",2048],[10,"Hasher",2050],[1,"u32"],[5,"Vec",2051],[10,"NodeIdExt",728],[15,"InvalidEncodingZ32",990],[15,"InvalidLength",990],[15,"InvalidSignature",990],[6,"Z32Error",2052],[8,"SignatureError",2053],[15,"FailedBuildingPacket",999],[15,"InvalidTxtEntry",999],[6,"SimpleDnsError",2054],[15,"ParseError",1005],[15,"LookupFailed",1005],[15,"InvalidLabel",1005],[5,"ProtoError",2055],[15,"UnexpectedFormat",1014],[15,"AttrFromString",1014],[15,"NumLabels",1014],[15,"Utf8",1014],[15,"NotAnIrohRecord",1014],[15,"DecodingError",1014],[6,"Error",2056],[15,"Io",1150],[15,"UnexpectedFrame",1150],[15,"FrameTooLarge",1150],[15,"Timeout",1150],[15,"SerDe",1150],[15,"InvalidSignature",1150],[15,"InvalidFrame",1150],[15,"InvalidFrameType",1150],[15,"TooSmall",1150],[15,"Io",1176],[15,"Timeout",1176],[15,"ConnSend",1176],[15,"SerDe",1176],[6,"StunAttribute",1188,2057],[5,"AlternateServer",2058],[5,"StunError",2059],[5,"TransactionId",1188,2060],[5,"ErrorCode",2061],[6,"Fingerprint",2062],[5,"MappedAddress",2063],[6,"MessageIntegrity",2064],[6,"MessageIntegritySha256",2065],[5,"Nonce",2066],[5,"PasswordAlgorithm",2067],[5,"PasswordAlgorithms",2068],[5,"Realm",2069],[5,"Software",2070],[5,"Unknown",2071],[5,"UnknownAttributes",2072],[5,"UserHash",2073],[5,"UserName",2074],[5,"XorMappedAddress",2075],[5,"AttributeType",2057],[6,"StunError",1188],[5,"MessageDecoder",1188,2076],[6,"MessageClass",1188,2077],[5,"StunMessage",2077],[5,"StunDecodeError",1188,2059],[5,"Error",2003],[5,"DecoderContext",2076],[15,"InvalidMessage",1443],[15,"NotBinding",1443],[15,"NotSuccessResponse",1443],[15,"MalformedAttrs",1443],[15,"NoFingerprint",1443],[15,"InvalidFingerprint",1443],[5,"MessageMethod",2077],[5,"VarInt",2078],[6,"Error",1458],[5,"QuicClient",1458],[6,"ConnectError",2079],[6,"ConnectionError",2080],[5,"RecvError",2081],[5,"NoInitialCipherSuite",2082],[5,"Endpoint",2083],[15,"Connect",1513],[15,"Connection",1513],[15,"WatchRecv",1513],[15,"NoIntitialCipherSuite",1513],[5,"Limits",1525],[5,"Metrics",1525,2084],[5,"Counter",2085],[5,"RelayConfig",1525],[6,"AccessConfig",1525],[10,"Iterable",2086],[6,"SpawnError",1525],[6,"SupervisorError",1525],[5,"StunMetrics",1525,2084],[5,"StunConfig",1525],[5,"QuicConfig",1525],[5,"ClientRateLimit",1525],[8,"NonZeroU32",2087],[5,"TlsConfig",1525],[6,"CertConfig",1525],[5,"Server",1525],[5,"CertificateDer",2088],[5,"RelayMetrics",1525,2084],[6,"Access",1525],[5,"ServerConfig",1525],[10,"Default",2089],[5,"ReloadingResolver",1525,2090],[5,"MetricItem",2091],[5,"JoinError",2092],[10,"MetricsGroup",2091],[17,"Value"],[5,"CertifiedKey",2093],[10,"Loader",2094],[5,"ClientHello",2095],[5,"ServerConfig",2095],[5,"AbortOnDropHandle",2096],[15,"Manual",1953],[15,"LetsEncrypt",1953],[5,"AcmeState",2097],[15,"BindTcpListener",1955],[15,"LocalAddr",1955],[15,"UdpSocketBind",1955],[15,"QuicSpawn",1955],[15,"TlsHeaderParse",1955],[15,"BindTlsListener",1955],[15,"NoLocalAddr",1955],[5,"InvalidHeaderValue",2046],[15,"Metrics",1976],[15,"AcmeEventStreamFinished",1976],[15,"JoinError",1976],[15,"NoRelayServicesEnabled",1976],[15,"TaskCancelled",1976]],"r":[[0,1037],[1,1999],[2,1995],[3,1995],[4,1995],[5,1995],[6,1995],[7,1995],[8,1999],[9,1995],[10,1995],[11,1995],[12,1999],[13,1995],[14,1995],[15,1995],[17,1995],[18,1995],[19,1995],[20,1995],[21,1995],[22,1995],[23,1995],[24,1995],[25,1995],[26,1995],[27,1995],[28,1995],[29,1995],[30,1999],[31,1995],[32,1995],[33,1995],[34,1999],[35,1995],[36,1995],[37,1995],[38,1999],[39,1995],[40,1995],[41,1995],[42,1995],[43,1999],[44,1995],[45,1999],[47,1999],[48,1995],[49,1995],[50,1995],[51,1999],[52,1995],[53,1995],[54,1995],[55,1995],[56,1995],[58,1999],[59,1995],[60,1995],[61,1995],[62,1995],[63,1995],[64,1995],[65,1995],[66,1995],[67,1995],[68,1995],[69,1995],[70,1995],[71,1995],[72,1995],[73,1995],[74,1995],[75,1999],[76,1995],[77,1995],[78,1995],[79,1995],[80,1995],[81,1999],[82,1995],[83,1995],[84,1995],[85,1995],[86,1995],[87,1995],[88,1995],[89,1995],[90,1995],[92,1999],[93,1995],[94,1995],[95,1995],[96,1999],[97,1995],[98,1995],[99,1995],[100,1995],[101,1995],[102,1999],[103,1999],[105,1995],[106,1995],[107,1995],[108,1999],[109,1995],[112,1995],[113,1995],[114,1995],[116,1995],[117,1995],[118,1999],[119,1995],[120,1995],[121,1995],[122,1995],[123,1995],[124,1999],[125,1995],[126,1995],[127,1995],[128,1999],[129,1995],[130,1995],[131,1995],[132,1999],[133,1995],[134,1995],[135,1995],[136,1995],[137,1995],[138,1999],[139,1995],[140,1995],[141,1995],[150,2014],[152,2014],[153,2014],[159,2014],[161,2014],[163,2014],[164,2014],[165,2014],[166,2014],[167,2014],[168,2014],[169,2014],[175,2014],[176,2014],[177,2014],[178,2014],[179,2014],[180,2014],[181,2014],[182,2014],[185,2014],[188,2014],[190,2014],[191,2014],[194,2014],[195,2014],[198,2014],[199,2014],[202,2014],[203,2014],[204,2014],[205,2014],[212,2014],[213,2014],[214,2014],[215,2014],[222,2014],[223,2014],[226,2014],[228,2014],[230,2014],[232,2014],[233,2014],[234,2014],[235,2014],[242,2014],[243,2014],[244,2014],[245,2014],[252,2014],[253,2014],[254,2014],[255,2014],[263,2014],[264,2014],[265,2014],[266,2014],[273,2014],[274,2014],[275,2014],[276,2014],[283,2014],[284,2014],[287,2014],[288,2014],[289,2014],[290,2014],[297,2014],[298,2014],[299,2014],[300,2014],[301,2014],[302,2014],[311,2014],[312,2014],[313,2014],[314,2014],[315,2014],[316,2014],[317,2014],[318,2014],[319,2014],[320,2014],[333,2014],[334,2014],[337,2014],[338,2014],[339,2014],[340,2014],[348,2014],[349,2014],[350,2014],[351,2014],[381,2014],[382,2014],[388,2014],[390,2014],[391,2014],[394,2014],[395,2014],[396,2014],[397,2014],[404,2014],[405,2014],[406,2014],[407,2014],[416,2014],[417,2014],[418,2014],[419,2014],[426,2014],[427,2014],[428,2014],[429,2014],[1188,2057],[1189,2057],[1190,2077],[1191,2057],[1192,2077],[1196,2057],[1197,2077],[1198,2076],[1199,2057],[1200,2057],[1202,2057],[1205,2057],[1206,2057],[1207,2057],[1208,2077],[1209,2057],[1210,2057],[1211,2059],[1213,2077],[1214,2060],[1215,2057],[1216,2057],[1217,2057],[1218,2057],[1219,2057],[1220,2076],[1221,2077],[1222,2060],[1223,2057],[1224,2057],[1225,2060],[1226,2057],[1227,2059],[1229,2057],[1230,2057],[1231,2057],[1232,2057],[1233,2057],[1234,2057],[1235,2057],[1236,2057],[1237,2060],[1238,2057],[1239,2057],[1240,2057],[1241,2057],[1242,2057],[1243,2057],[1244,2057],[1246,2076],[1247,2077],[1248,2060],[1249,2057],[1250,2059],[1252,2076],[1253,2077],[1254,2060],[1255,2057],[1256,2059],[1259,2076],[1260,2077],[1261,2060],[1262,2057],[1263,2076],[1264,2077],[1265,2060],[1266,2057],[1267,2076],[1268,2077],[1269,2060],[1270,2057],[1271,2060],[1272,2060],[1273,2076],[1274,2077],[1275,2060],[1276,2057],[1277,2059],[1279,2076],[1280,2077],[1281,2060],[1282,2057],[1283,2059],[1285,2076],[1286,2077],[1287,2060],[1288,2057],[1289,2059],[1291,2076],[1292,2076],[1293,2060],[1294,2076],[1295,2077],[1296,2060],[1297,2060],[1298,2057],[1299,2059],[1301,2076],[1302,2077],[1303,2060],[1304,2057],[1305,2059],[1308,2076],[1309,2077],[1310,2060],[1311,2057],[1312,2059],[1314,2077],[1315,2060],[1316,2077],[1317,2077],[1318,2077],[1319,2060],[1320,2060],[1321,2060],[1322,2057],[1323,2057],[1324,2057],[1325,2057],[1326,2057],[1327,2057],[1328,2057],[1329,2057],[1330,2057],[1331,2057],[1332,2057],[1333,2057],[1334,2057],[1335,2057],[1336,2057],[1337,2057],[1338,2076],[1339,2077],[1340,2060],[1341,2060],[1342,2057],[1343,2059],[1344,2059],[1347,2076],[1348,2077],[1349,2060],[1350,2060],[1351,2060],[1352,2057],[1353,2057],[1354,2057],[1355,2057],[1356,2057],[1357,2057],[1358,2057],[1359,2057],[1360,2057],[1361,2057],[1362,2057],[1363,2057],[1364,2057],[1365,2057],[1366,2057],[1367,2057],[1368,2057],[1369,2059],[1371,2076],[1372,2060],[1373,2059],[1375,2076],[1376,2077],[1377,2060],[1378,2057],[1379,2059],[1381,2076],[1382,2077],[1383,2060],[1384,2057],[1385,2059],[1388,2057],[1389,2057],[1390,2057],[1391,2057],[1392,2057],[1393,2057],[1394,2057],[1395,2057],[1396,2057],[1397,2057],[1398,2057],[1399,2057],[1400,2057],[1401,2057],[1402,2057],[1403,2057],[1404,2098],[1407,2060],[1411,2076],[1412,2077],[1413,2060],[1414,2057],[1415,2060],[1416,2059],[1418,2076],[1419,2077],[1420,2077],[1421,2060],[1422,2057],[1423,2059],[1425,2076],[1426,2077],[1427,2060],[1428,2057],[1429,2059],[1431,2076],[1432,2077],[1433,2060],[1434,2057],[1435,2059],[1437,2076],[1438,2077],[1439,2060],[1440,2057],[1441,2059],[1455,2099],[1456,2099],[1457,2099],[1533,2090],[1541,2084],[1548,2084],[1550,2090],[1556,2084],[1562,2084],[1567,2084],[1571,2084],[1572,2084],[1575,2084],[1578,2084],[1579,2084],[1580,2084],[1581,2090],[1595,2084],[1596,2084],[1597,2084],[1598,2090],[1613,2084],[1614,2084],[1620,2084],[1623,2084],[1626,2084],[1629,2084],[1630,2084],[1631,2084],[1632,2090],[1646,2084],[1647,2084],[1648,2084],[1649,2090],[1663,2084],[1664,2084],[1665,2084],[1666,2090],[1680,2084],[1681,2084],[1682,2084],[1683,2084],[1686,2084],[1687,2084],[1688,2084],[1689,2090],[1690,2090],[1704,2084],[1705,2084],[1706,2084],[1707,2090],[1723,2084],[1724,2084],[1725,2084],[1726,2084],[1727,2084],[1728,2084],[1729,2084],[1730,2090],[1748,2084],[1749,2084],[1750,2084],[1751,2084],[1752,2084],[1753,2084],[1754,2084],[1755,2084],[1756,2090],[1772,2084],[1773,2084],[1774,2084],[1775,2084],[1776,2090],[1791,2084],[1792,2084],[1793,2084],[1802,2084],[1803,2084],[1804,2084],[1805,2090],[1806,2090],[1820,2084],[1821,2084],[1822,2084],[1823,2090],[1837,2084],[1838,2084],[1845,2084],[1846,2084],[1847,2084],[1848,2084],[1849,2084],[1850,2084],[1855,2084],[1856,2090],[1857,2084],[1858,2090],[1859,2084],[1860,2084],[1861,2084],[1862,2084],[1863,2084],[1866,2090],[1871,2084],[1877,2084],[1882,2084],[1883,2084],[1884,2084],[1885,2090],[1899,2084],[1900,2084],[1901,2084],[1902,2090],[1916,2084],[1917,2084],[1918,2084],[1919,2090],[1933,2084],[1934,2084],[1935,2084],[1936,2084],[1937,2084],[1938,2090],[1952,2084]],"b":[[76,"impl-Debug-for-RelayMap"],[77,"impl-Display-for-RelayMap"],[78,"impl-Debug-for-RelayNode"],[79,"impl-Display-for-RelayNode"],[83,"impl-From%3CRelayNode%3E-for-RelayMap"],[84,"impl-From%3CRelayUrl%3E-for-RelayMap"],[88,"impl-FromIterator%3CRelayUrl%3E-for-RelayMap"],[89,"impl-FromIterator%3CRelayNode%3E-for-RelayMap"],[297,"impl-Display-for-SendError"],[298,"impl-Debug-for-SendError"],[299,"impl-Display-for-RecvError"],[300,"impl-Debug-for-RecvError"],[303,"impl-Debug-for-ConnectError"],[304,"impl-Display-for-ConnectError"],[305,"impl-Display-for-DialError"],[306,"impl-Debug-for-DialError"],[312,"impl-From%3CError%3E-for-SendError"],[313,"impl-From%3CError%3E-for-SendError"],[314,"impl-From%3CError%3E-for-RecvError"],[315,"impl-From%3CError%3E-for-RecvError"],[317,"impl-From%3CRecvError%3E-for-RecvError"],[318,"impl-From%3CSendError%3E-for-RecvError"],[321,"impl-From%3CDialError%3E-for-ConnectError"],[322,"impl-From%3CSendError%3E-for-ConnectError"],[324,"impl-From%3CError%3E-for-ConnectError"],[325,"impl-From%3CElapsed%3E-for-DialError"],[326,"impl-From%3CError%3E-for-DialError"],[328,"impl-From%3CDnsError%3E-for-DialError"],[605,"impl-Debug-for-DnsError"],[606,"impl-Display-for-DnsError"],[607,"impl-Debug-for-StaggeredError%3CE%3E"],[608,"impl-Display-for-StaggeredError%3CE%3E"],[611,"impl-Display-for-TXT"],[612,"impl-Debug-for-TXT"],[614,"impl-From%3CElapsed%3E-for-DnsError"],[615,"impl-From%3CResolveError%3E-for-DnsError"],[871,"impl-Display-for-EncodingError"],[872,"impl-Debug-for-EncodingError"],[873,"impl-Debug-for-DecodingError"],[874,"impl-Display-for-DecodingError"],[876,"impl-Debug-for-UserData"],[877,"impl-Display-for-UserData"],[878,"impl-Debug-for-MaxLengthExceededError"],[879,"impl-Display-for-MaxLengthExceededError"],[881,"impl-Debug-for-LookupError"],[882,"impl-Display-for-LookupError"],[883,"impl-Debug-for-ParseError"],[884,"impl-Display-for-ParseError"],[1105,"impl-Debug-for-FrameType"],[1106,"impl-Display-for-FrameType"],[1107,"impl-Debug-for-SendError"],[1108,"impl-Display-for-SendError"],[1109,"impl-Debug-for-RecvError"],[1110,"impl-Display-for-RecvError"],[1114,"impl-From%3CError%3E-for-SendError"],[1115,"impl-From%3CElapsed%3E-for-SendError"],[1116,"impl-From%3CSendError%3E-for-SendError"],[1117,"impl-From%3CError%3E-for-SendError"],[1119,"impl-From%3CError%3E-for-RecvError"],[1120,"impl-From%3CError%3E-for-RecvError"],[1121,"impl-From%3CElapsed%3E-for-RecvError"],[1122,"impl-From%3CError%3E-for-RecvError"],[1340,"impl-Display-for-TransactionId"],[1341,"impl-Debug-for-TransactionId"],[1343,"impl-Debug-for-StunDecodeError"],[1344,"impl-Display-for-StunDecodeError"],[1345,"impl-Display-for-StunError"],[1346,"impl-Debug-for-StunError"],[1349,"impl-From%3C%26%5Bu8;+stun_rs::::types::%7Bimpl%2313%7D::%7Bconstant%230%7D%5D%3E-for-TransactionId"],[1350,"impl-From%3C%5Bu8;+stun_rs::::types::%7Bimpl%2314%7D::%7Bconstant%230%7D%5D%3E-for-TransactionId"],[1352,"impl-From%3CUserHash%3E-for-StunAttribute"],[1353,"impl-From%3CErrorCode%3E-for-StunAttribute"],[1354,"impl-From%3CXorMappedAddress%3E-for-StunAttribute"],[1355,"impl-From%3CUserName%3E-for-StunAttribute"],[1356,"impl-From%3CUnknown%3E-for-StunAttribute"],[1357,"impl-From%3CUnknownAttributes%3E-for-StunAttribute"],[1358,"impl-From%3CSoftware%3E-for-StunAttribute"],[1359,"impl-From%3CAlternateServer%3E-for-StunAttribute"],[1360,"impl-From%3CRealm%3E-for-StunAttribute"],[1362,"impl-From%3CPasswordAlgorithm%3E-for-StunAttribute"],[1363,"impl-From%3CNonce%3E-for-StunAttribute"],[1364,"impl-From%3CMessageIntegritySha256%3E-for-StunAttribute"],[1365,"impl-From%3CMessageIntegrity%3E-for-StunAttribute"],[1366,"impl-From%3CMappedAddress%3E-for-StunAttribute"],[1367,"impl-From%3CFingerprint%3E-for-StunAttribute"],[1368,"impl-From%3CPasswordAlgorithms%3E-for-StunAttribute"],[1487,"impl-Debug-for-Error"],[1488,"impl-Display-for-Error"],[1490,"impl-From%3CConnectError%3E-for-Error"],[1491,"impl-From%3CConnectionError%3E-for-Error"],[1492,"impl-From%3CRecvError%3E-for-Error"],[1494,"impl-From%3CNoInitialCipherSuite%3E-for-Error"],[1768,"impl-Debug-for-SpawnError"],[1769,"impl-Display-for-SpawnError"],[1770,"impl-Debug-for-SupervisorError"],[1771,"impl-Display-for-SupervisorError"]],"c":"OjAAAAAAAAA=","e":"OzAAAAEAAPYFegABAAAABgAKABIAGAAsAAEAMAAJADsAAwBAABEAVAAAAFcAAABaAAAAXQADAGsAAQByAAEAeAAQAIsAAwCUAAAAlgACAJoABwCjAAAAqQAGALMAAAC4AAkAwwBDAAgBLwA5AQMAPgEBAEIBAQBFAQIASQEAAE4BDQBsAQcAdgELAIMBaQDyARoAFQIBABkCAgAeAgAAIAISADQCMQBnAgEAagIAAGwCAABvAgYAewIAAIgCAACKAhEAnQIJAKgCDwC9AhEA0AIAANMCAwDYAgUA3wIGAOsCBADxAgMA9gIfABcDIgA7AxcAVAMiAHkDAAB9AwAAgQMAAIQDAACHAw0AoQMAAKUDBACrAwIArwMFALcDGADRAwcA3wMpAA8EAQATBAQAIwQFACoELgBbBAMAYAQJAG0ENwDFBAMAzAQBANYEAADeBC0ADQUAAA8FGwA7BQgARgUBAEkFCABTBQYAXQUIAIAFAACDBSwAtAUBALcFAAC7BRoA1wUAANoFAgDgBRUA+AUAAPoFAQABBgAABAYAAAcGAgALBgAAFwYAABkGBAAiBgUAKwYhAFAGAQBVBjsAkgYpAMAGFADWBhYA/gYAAAEHAQAJBwQADwcNADYHAgBDBwAATQcBAFYHNwCQBxAApAcgAA==","P":[[8,"T"],[17,""],[20,"T"],[23,""],[28,"K"],[30,"T"],[42,""],[47,"T"],[55,"__D"],[58,""],[66,"K"],[75,""],[81,"T"],[83,""],[85,"T"],[86,""],[87,"T"],[90,""],[96,"U"],[100,""],[113,"__S"],[116,""],[119,"T"],[122,""],[124,"U,T"],[128,"U"],[132,""],[138,"V"],[191,""],[193,"S"],[194,""],[202,"T"],[222,""],[228,"T"],[230,""],[232,"T"],[262,""],[263,"T"],[283,""],[311,"T"],[312,""],[316,"T"],[317,""],[319,"T"],[321,""],[323,"T"],[324,""],[327,"T"],[328,""],[329,"T"],[333,""],[348,"U"],[358,""],[362,""],[363,"Sink::Error"],[367,"Stream::Item"],[369,"Sink::Error"],[371,""],[373,"D,C,MW,Item,S"],[377,"D,C,MW,S"],[381,""],[386,"Sink::Error"],[388,"T"],[390,""],[394,"U,T"],[404,"U"],[414,"S"],[416,""],[426,"V"],[436,""],[549,"E"],[550,"T"],[560,""],[561,"E"],[562,""],[566,"T"],[569,""],[572,"T"],[587,""],[588,"T"],[598,""],[599,"E"],[600,""],[607,"E"],[609,""],[613,"T"],[614,""],[616,"T"],[617,""],[618,"T"],[619,""],[620,"T"],[622,""],[629,"U"],[634,"IntoIterator::IntoIter"],[635,""],[641,""],[645,""],[646,""],[650,"E"],[651,"T"],[654,""],[657,"U,T"],[662,"U"],[667,""],[673,"V"],[678,""],[701,"T"],[703,""],[704,"T"],[705,""],[706,"T"],[709,""],[710,"T"],[712,""],[714,"K"],[717,""],[718,"T"],[719,""],[720,"U"],[721,""],[722,"T"],[723,"U,T"],[724,"U"],[725,""],[727,"V"],[733,""],[756,""],[757,""],[768,"T"],[784,""],[793,"T"],[796,""],[800,"K"],[801,"T"],[825,""],[827,"T"],[832,"Deref::Target"],[833,"T"],[841,"Deref::Target"],[842,"T"],[845,""],[862,"K"],[871,""],[886,"T"],[888,""],[889,"T"],[892,""],[893,"T"],[896,""],[899,"FromStr::Err"],[900,""],[902,"__H"],[903,""],[916,"U"],[924,""],[938,"T"],[941,""],[950,"U,T"],[954,"TryFrom::Error"],[955,"U,T"],[959,"U"],[967,""],[976,"V"],[984,""],[1070,"T"],[1076,""],[1079,"T"],[1080,""],[1081,"T"],[1096,""],[1102,"K"],[1105,""],[1112,"T"],[1114,""],[1118,"T"],[1119,""],[1123,"FromPrimitive::Primitive"],[1124,""],[1129,"U"],[1132,""],[1134,"T"],[1135,""],[1138,"U,T"],[1141,"U"],[1144,""],[1147,"V"],[1150,""],[1246,"T"],[1258,""],[1263,"T"],[1267,""],[1272,"K"],[1273,"T"],[1291,""],[1294,"T"],[1297,""],[1298,"T"],[1307,""],[1316,"K"],[1322,""],[1347,"T"],[1349,""],[1351,"T"],[1352,""],[1361,"T"],[1362,""],[1369,"T"],[1371,""],[1372,"__H"],[1373,""],[1381,"U"],[1387,""],[1411,"T"],[1415,""],[1418,"U,T"],[1420,""],[1421,"U,T"],[1425,"U"],[1431,""],[1437,"V"],[1443,""],[1469,"T"],[1473,""],[1474,"T"],[1484,""],[1493,"T"],[1494,""],[1495,"T"],[1496,""],[1500,"U"],[1502,""],[1505,"U,T"],[1507,"U"],[1509,""],[1511,"V"],[1513,""],[1578,"T"],[1612,""],[1623,"T"],[1626,""],[1629,"T"],[1680,""],[1684,"EC,EA"],[1685,""],[1686,"T"],[1690,"Loader,Deref::Target"],[1691,"T"],[1721,""],[1745,"K"],[1748,""],[1756,"Loader"],[1757,"EC,EA"],[1759,""],[1763,"EC,EA"],[1764,""],[1766,"EC,EA"],[1767,""],[1773,"T"],[1789,""],[1790,"T"],[1791,""],[1805,"Loader"],[1806,""],[1820,"U"],[1837,""],[1856,"Loader"],[1857,""],[1858,"Loader"],[1859,""],[1866,"Loader"],[1867,""],[1870,"EC,EA"],[1871,""],[1877,"T"],[1880,""],[1882,"U,T"],[1899,"U"],[1916,""],[1935,"V"],[1952,""]]}]]')); if (typeof exports !== 'undefined') exports.searchIndex = searchIndex; else if (window.initSearch) window.initSearch(searchIndex); -//{"start":39,"fragment_lengths":[446,115576,11221,6900,11823,57560]} \ No newline at end of file +//{"start":39,"fragment_lengths":[446,110513,11221,6900,11823,57390]} \ No newline at end of file diff --git a/pr/3327/docs/search.desc/iroh/iroh-desc-0-.js b/pr/3327/docs/search.desc/iroh/iroh-desc-0-.js index ca48abff84..3012e20b6c 100644 --- a/pr/3327/docs/search.desc/iroh/iroh-desc-0-.js +++ b/pr/3327/docs/search.desc/iroh/iroh-desc-0-.js @@ -1 +1 @@ -searchState.loadedDescShard("iroh", 0, "Peer-to-peer QUIC connections.\nError when decoding.\nThe encoded information had the wrong length.\nError when decoding the public key.\nError when deserialising a PublicKey or a SecretKey.\nThe length of an ed25519 PublicKey, in bytes.\nNetwork-level addressing information for an iroh node.\nThe identifier for a node in the (iroh) network.\nA public key.\nRelays over the custom relaying protocol with a custom …\nConfiguration of all the relay servers that can be used.\nInformation on a specific relay server.\nThe HTTP upgrade protocol used for relaying.\nA URL identifying a relay server.\nCan occur when parsing a string into a RelayUrl.\nA secret key.\nRelays over websockets.\nGet this public key as a byte array.\nIs this a known node?\nDefault values used in iroh\nReturns the direct addresses of this peer.\nSocket addresses where the peer might be reached directly.\nNode address discovery.\nThis module exports a DNS resolver, which is also the …\nCreate an empty relay map.\nThe Endpoint allows establishing connections to other iroh …\nConvert to a hex string limited to the first 5 bytes for a …\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the addressing info from given ticket.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreates a RelayMap from a RelayUrl.\nReturns the argument unchanged.\nReturns the argument unchanged.\nConstruct a PublicKey from a slice of bytes.\nCreate a secret key from its byte representation.\nCreates a RelayMap from an iterator of RelayUrl.\nCreates a new NodeAddr from its parts.\nGenerate a new SecretKey with a randomness generator.\nGet the given node.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nReturns true, if only a NodeId is present.\nAre there any nodes in this map?\nHow many nodes are known?\nCo-locating all of the iroh metrics structs\nChecks the network conditions from the current host.\nCreates a new NodeAddr with no relay_url and no …\nThe node’s identifier.\nSupport for handling DNS resource records for dialing by …\nReturns an Iterator over all known nodes.\nTries to match the value of an HTTP upgrade header to …\nTools for spawning an accept loop that routes incoming …\nReturns the VerifyingKey for this PublicKey.\nThe public key of this SecretKey.\nConfiguration to speak to the QUIC endpoint on the relay …\nReturns the relay url of this peer.\nThe node’s home relay url.\nReturns the SigningKey for this SecretKey.\nSign the given message and return a digital signature\nWhether this relay server should only be used for STUN …\nThe stun port of the relay server.\nInternal utilities to support testing.\nConvert this to the bytes representing the secret part. …\nThe HTTP upgrade header used or expected.\nThe RelayUrl where this relay server can be dialed.\nReturns the sorted relay URLs.\nVerify a signature on a message with this secret key’s …\nWatchable values.\nAdds the given direct addresses.\nAdds a relay url.\nThe default HTTPS port used by the Relay server.\nThe default HTTP port used by the Relay server.\nThe default metrics port used by the Relay server.\nThe default QUIC port used by the Relay server to accept …\nThe default STUN port used by the Relay server.\nProduction configuration.\nStaging configuration.\nHostname of the default Asia-Pacific relay.\nHostname of the default EU relay.\nHostname of the default NA relay.\nGet the default RelayNode for Asia-Pacific\nGet the default RelayNode for EU.\nGet the default RelayNode for NA.\nGet the default RelayMap.\nHostname of the default EU relay.\nHostname of the default NA relay.\nGet the default RelayNode for EU.\nGet the default RelayNode for NA.\nGet the default RelayMap.\nA discovery service that combines multiple discovery …\nNode discovery for super::Endpoint.\nContext about the Endpoint for discovery services.\nDiscovery errors\nNode discovery results from Discovery services.\nTrait for structs that can be converted into Discovery.\nIntoDiscovery errors\nError returned when a discovery watch stream lagged too …\nThe max byte length allowed for user-defined data.\nData about a node that may be published to and resolved …\nInformation about a node that may be published to and …\nUnder the hood this is a UTF-8 String is no longer than …\nAdds a Discovery service.\nAdds direct addresses to the node data.\nRemoves all direct addresses from the node data.\nThe information published about the node.\nReturns the direct addresses of the node.\nDNS node discovery for iroh\nReturns the DnsResolver used by the endpoint.\nCreates an empty ConcurrentDiscovery.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreates a new user error from an arbitrary error type.\nCreates a new user error from an arbitrary error type.\nCreates a new user error from an arbitrary boxed error …\nCreates a new user error from an arbitrary boxed error …\nCreates a new NodeInfo from its parts.\nParses a NodeInfo from a pkarr::SignedPacket.\nCreates a new ConcurrentDiscovery.\nParses a NodeInfo from a TXT records lookup.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nTurns this discovery builder into a ready-to-use discovery …\nConverts into a NodeAddr without cloning.\nConverts into a NodeAddr without cloning.\nReturns the optional timestamp when this node info was …\nA discovery service that uses an mdns-like service to …\nCreates a new NodeData with a relay URL and a set of …\nCreates a new NodeInfo with an empty NodeData.\nCreates a new DiscoveryItem from a NodeInfo.\nReturns the NodeId of the endpoint.\nReturns the node id of the discovered node.\nThe NodeId of the node this is about.\nReturns the NodeInfo for the discovered node.\nA discovery service which publishes and resolves node …\nReturns the provenance of this discovery item.\nPublishes the given NodeData to the discovery mechanism.\nReturns the relay URL of the node.\nResolves the DiscoveryItem for the given NodeId.\nReturns the SecretKey of the endpoint.\nSets the relay URL of the node data.\nSets the user-defined data of the node data.\nA static node discovery to manually add node addressing …\nSubscribe to all addresses that get passively discovered.\nConverts into a NodeAddr by cloning the needed fields.\nConverts into a NodeAddr by cloning the needed fields.\nCreates a pkarr::SignedPacket.\nConverts into a list of {key}={value} strings.\nReturns the optional user-defined data of the node.\nReturns any user-defined data.\nThe number of skipped messages\nSets the direct addresses and returns the updated node …\nSets the direct addresses and returns the updated node …\nSets the relay URL and returns the updated node data.\nSets the relay URL and returns the updated node info.\nSets the user-defined data and returns the updated node …\nSets the user-defined data and returns the updated node …\nDNS node discovery\nBuilder for DnsDiscovery.\nThe n0 testing DNS node origin, for production.\nThe n0 testing DNS node origin, for testing.\nBuilds a DnsDiscovery with the passed DnsResolver.\nCreates a DnsDiscoveryBuilder that implements IntoDiscovery…\nSets the DNS resolver to use.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCreates a new DNS discovery using the iroh.link domain.\nDiscovery using swarm-discovery, a variation on mdns\nBuilder for MdnsDiscovery.\nName of this discovery service.\nReturns a MdnsDiscoveryBuilder that implements …\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCreate a new MdnsDiscovery Service.\nDefault TTL for the records in the pkarr signed packet.\nInterval in which to republish the node info even if …\nThe production pkarr relay run by number 0.\nThe testing pkarr relay run by number 0.\nPublisher of node discovery information to a pkarr relay.\nBuilder for PkarrPublisher.\nA pkarr client to publish pkarr::SignedPackets to a pkarr …\nResolver of node discovery information from a pkarr relay.\nBuilder for PkarrResolver.\nBuilds the PkarrPublisher with the passed secret key for …\nCreates a PkarrResolver from this builder.\nReturns a PkarrPublisherBuilder that publishes node info …\nCreates a new resolver builder using the pkarr relay …\nPkarr based node discovery for iroh, supporting both relay …\nSets the DNS resolver to use for resolving the pkarr relay …\nSets the DNS resolver to use for resolving the pkarr relay …\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCreates a pkarr publisher which uses the number 0 pkarr …\nCreates a pkarr resolver builder which uses the number 0 …\nCreates a new client.\nPublishes a SignedPacket.\nSets the interval after which packets are republished even …\nResolves a SignedPacket for the given NodeId.\nSets the TTL (time-to-live) for published packets.\nPublishes the addressing information about this node to a …\nCreates a new client while passing a DNS resolver to use.\nBuilder for DhtDiscovery.\nPkarr Mainline DHT and relay server node discovery.\nBuilds the discovery mechanism.\nCreates a new builder for DhtDiscovery.\nExplicitly sets the pkarr client to use.\nSets whether to publish to the Mainline DHT.\nReturns the argument unchanged.\nReturns the argument unchanged.\nSets whether to include the direct addresses in the DNS …\nSets the initial delay before the first publish.\nCalls U::from(self).\nCalls U::from(self).\nUses the default number 0 pkarr relay URL.\nDisables publishing even if a secret key is set.\nSets the pkarr relay URL to use.\nSets the republish delay for the DHT.\nSets the secret key to use for signing the DNS packets.\nSets the time-to-live value for the DNS packets.\nThe provenance string for this discovery implementation.\nA static node discovery to manually add node addressing …\nAugments node addressing information for the given node ID.\nReturns the argument unchanged.\nCreates a static discovery instance from node addresses.\nReturns node addressing information for the given node ID.\nCalls U::from(self).\nCreates a new static discovery instance.\nRemoves all node addressing information for the given node …\nSets node addressing information for the given node ID.\nThe DNS resolver used throughout iroh.\nThe n0 testing DNS node origin, for production.\nThe n0 testing DNS node origin, for testing.\nRemoves all entries from the cache.\nReturns the argument unchanged.\nCalls U::from(self).\nPerform an ipv4 lookup with a timeout.\nResolve IPv4 and IPv6 in parallel with a timeout.\nRace an ipv4 and ipv6 lookup with a timeout in a staggered …\nPerform an ipv4 lookup with a timeout in a staggered …\nPerform an ipv6 lookup with a timeout.\nPerform an ipv6 lookup with a timeout in a staggered …\nLooks up node info by DNS name.\nLooks up node info by DNS name in a staggered fashion.\nLooks up node info by NodeId and origin domain name.\nLooks up node info by NodeId and origin domain name.\nLookup a TXT record.\nCreate a new DNS resolver with sensible cross-platform …\nResolve a hostname from a URL to an IP address.\nCreate a new DNS resolver configured with a single UDP DNS …\nthe endpoint has reached the confidentiality or integrity …\nthe application or application protocol caused the …\nFuture produced by Endpoint::accept.\nFuture produced by Connection::accept_bi\nFuture produced by Connection::accept_uni\nParameters for controlling the peer’s acknowledgement …\nA key for sealing data with AEAD-based algorithms\nUses all available paths\nApplication layer added the address directly.\nReason given by an application for closing the connection\nThe peer closed the connection\nBuilder for Endpoint.\nthe number of connection IDs provided by the peer exceeds …\nthe server refused to accept a new connection\nreceived more data in CRYPTO frames than can be buffered\nWe received a CallMeMaybe.\nA chunk of data from the receive stream\nThe connection could not be created because not enough of …\nError indicating that a stream has not been opened or has …\nThe stream has already been stopped, finished, or reset\nThe stream has already been finished or reset\nOptions for the Endpoint::connect_with_opts function.\nIn-progress connection attempt future\nA QUIC connection.\nReason given by the transport for closing the connection\nThe peer’s QUIC stack aborted the connection …\nReasons why a connection might be lost\nThe connection was lost\nThe connection was lost\nThe connection was lost\nThe connection was lost\nThe connection was lost\nConnection statistics\nThe type of connection we have to the endpoint.\nThe type of control message we have received.\nCommon interface for different congestion controllers\nConstructs controllers on demand\nGeneric crypto errors\nServer-side configuration for the crypto protocol\nUse a custom relay map.\nUse the default relay map, with production relay servers …\nDirect UDP connection\nA direct address on which an iroh-node might be …\nInformation about a direct address.\nThe type of direct address.\nDatagram support is disabled locally\nDisable relay servers completely.\nThe address was discovered by a discovery service.\nEnvironment variable to force the use of staging relays.\nControls an iroh node, establishing connections with other …\nError returned by Session::export_keying_material.\nreceived a STREAM frame or a RESET_STREAM frame containing …\nreceived more data than permitted in advertised data limits\nreceived a frame that was badly formatted\nThe stream finished before all bytes were read\nNumber of frames transmitted of each frame type\nA pseudo random key for HKDF\nthe endpoint encountered an internal error and cannot …\nreceived an invalid Retry Token in a client Initial\nAttempted an ordered read following an unordered read\nAn incoming connection for which the server has not yet …\nAdaptor to let Incoming be awaited like a Connecting.\nkey update error\nA locally bound socket address.\nThe local application closed the connection\nThe largest representable value\nThe largest encoded value length\nBoth a UDP and a relay connection are used.\nParameters governing MTU discovery.\nthe connection is being closed abruptly in the absence of …\nno viable network path exists\nApplication layer with a specific name added the node …\nA type alias for the return value of Endpoint::node_addr.\nWe have no verified connection to this PublicKey\nFuture produced by Connection::open_bi\nFuture produced by Connection::open_uni\ndetected an error with protocol compliance that was not …\nDefines the mode of path selection for all traffic flowing …\nStatistics related to a transmission path\nWe received a Ping from the node.\nWe received a Pong from the node.\nAn address assigned by the router using port mapping.\nAn error occurred during reading\nFuture produced by Connection::read_datagram\nErrors that arise from reading from a stream.\nA read error occurred\nErrors that arise from reading from a stream.\nErrors from RecvStream::read_to_end\nA stream that can only be used to receive data\nRelay connection over relay\nA node communicated with us first via relay.\nConfiguration of the relay servers for an Endpoint.\nForces all traffic to go exclusively through relays\nDetails about a remote iroh node which is known to this …\nThe peer abandoned transmitting data on this stream\nThe peer is unable to continue processing this connection, …\nErrors that arise while waiting for a stream to be reset\nError for attempting to retry an Incoming which already …\nreceived a frame for a stream identifier that exceeded …\nreceived a frame for a stream that was not in a state that …\nAddress was loaded from the fs.\nErrors that can arise when sending a datagram\nA stream that can only be used to send data\nParameters governing incoming connections\nThe origin or source through which an address associated …\nUse the staging relay servers from n0.\nThe peer is no longer accepting data on this stream\nErrors that arise while monitoring for a send stream stop …\nIdentifier for a stream within a particular connection\nPublic internet address discovered via STUN.\nHard NAT: STUN’ed IPv4 address + local fixed port.\nreceived transport parameters that were badly formatted, …\nCommunication with the peer has lapsed for longer than the …\nThe datagram is larger than the connection can currently …\nThe stream is larger than the user-supplied limit\nParameters governing the core QUIC state machine\nTransport-level errors occur when a peer violates the …\nThe peer violated the QUIC specification as understood by …\nTransport-level error code\nA node communicated with us first via UDP.\nStatistics about UDP datagrams transmitted or received on …\nNot yet determined..\nThe peer does not support receiving datagram frames\nError indicating that the specified QUIC version is not …\nAn integer less than 2^62\nThe peer doesn’t implement any supported version\nA handle to some connection internals, use with care.\nErrors that arise from writing to a stream\nIndicates how many bytes and chunks had been transferred …\nFuture that completes when a connection is fully …\nThis was a 0-RTT stream and the server rejected it\nThis was a 0-RTT stream and the server rejected it\nThis was a 0-RTT stream and the server rejected it\nThis was a 0-RTT stream and the server rejected it\nAccepts an incoming connection on the endpoint.\nAttempts to accept this incoming connection (an error may …\nAccept the next incoming bidirectional stream.\nAccepts the next incoming uni-directional stream.\nAccepts this incoming connection using a custom …\nThe ack-eliciting threshold we will request the peer to use\nSpecifies the ACK frequency config (see AckFrequencyConfig …\nAdds a discovery mechanism for this endpoint.\nInforms this Endpoint about addresses of the iroh node.\nInforms this Endpoint about addresses of the iroh node, …\nThe UDP address reported by the remote node.\nThe address.\nThe addresses at which this node might be reachable.\nDerive AEAD using hkdf\nWhether the implementation is permitted to set the spin …\nExtracts the ALPN protocol from the peer’s handshake …\nExtracts the ALPN protocol from the peer’s handshake …\nSets the ALPN protocols that this endpoint will accept on …\nBinds the magic endpoint.\nSets the IPv4 bind address.\nSets the IPv6 bind address.\nSpecifies the amount of time that MTU discovery should …\nThe number of times a black hole was detected in the path\nReturns the local socket addresses on which the underlying …\nConstruct a fresh Controller\nReturns the builder for an Endpoint, with a production …\nThe contents of the chunk\nThe total amount of bytes which have been transferred …\nThe amount of bytes which had been written\nThe amount of full chunks which had been written\nRemoves all discovery services from the builder.\nDuplicate the controller’s state\nCloses the QUIC endpoint and the magic socket.\nCloses the connection immediately.\nIf the connection is closed, the reason why.\nWait for the connection to be closed for any reason.\nType of error\nHow to construct new congestion::Controllers\nCongestion events on the connection\nCurrent state of the congestion control algorithm, for …\nReturns a Watcher that reports the current connection type …\nThe type of connection we have to the node, either direct …\nConnects to a remote Endpoint.\nStarts a connection attempt with a remote Endpoint.\nCreate QUIC error code from TLS alert code\nTLS configuration used for incoming connections\nMaximum quantity of out-of-order crypto layer data to …\nLargest UDP payload size the path currently supports\nCurrent congestion window of the connection\nMaximum number of incoming application datagram bytes to …\nMaximum number of outgoing application datagram bytes to …\nBytes available in the outgoing datagram buffer.\nThe amount of UDP datagrams observed\nReturns the default relay mode.\nWhich directions data flows in\nReturns a Watcher for the direct addresses of this Endpoint…\nOptionally sets a discovery mechanism for this endpoint.\nReturns the discovery mechanism, if configured.\nConfigures the endpoint to also use the mainline DHT with …\nConfigures the endpoint to also use local network …\nConfigures the endpoint to use the default n0 DNS …\nReturns a stream of all remote nodes discovered through …\nOptionally sets a custom DNS resolver to use for this …\nReturns the DNS resolver used in this Endpoint.\nWhether to use “Generic Segmentation Offload” to …\nClass of error as encoded in the specification\nApplication-specific reason code\nDerives keying material from this connection’s TLS …\nNotify the peer that no more data will ever be written to …\nReturns true if the use of staging relays is forced.\nFrame type that triggered the error\nStatistics about frames received on a connection\nStatistics about frames transmitted on a connection\nType of frame that caused the close\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nConstruct a VarInt infallibly\nSucceeds iff x < 2^62\nCreate a VarInt without ensuring it’s in range\nParameters negotiated during the handshake\nParameters negotiated during the handshake.\nWhether there is a possible known network path to the …\nReturns a Watcher for the RelayUrl of the Relay server …\nGet the identity of this stream\nGet the identity of this stream\nIgnores this incoming connection attempt, not sending any …\nMaximum number of received bytes to buffer for each …\nMaximum number of received bytes to buffer for all Incoming\nDistinguishes streams of the same initiator and …\nCreate the initial set of keys given the client’s …\nThe initial value to be used as the maximum UDP payload …\nThe RTT used before an RTT sample is taken\nInitial congestion window\nWhich side of a connection initiated the stream\nSkip verification of SSL certificates from relay servers\nSpecifies the time to wait after completing MTU discovery …\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConverts this Connecting into a 0-RTT or 0.5-RTT …\nReturns Self for use in down-casting to extract …\nGet the Incoming\nExtract the integer value\nThe amount of I/O operations executed\nCheck if this stream has been opened during 0-RTT.\nReturns true if the Connection associated with this handle …\nCheck if this endpoint is still alive, or already closed.\nPeriod of inactivity before sending a keep-alive packet\nEnables saving the TLS pre-master key for connections.\nOptionally set a list of known nodes.\nElapsed time since this network path was known to exist.\nLast control message received by this node about this …\nElapsed time since the last payload message was received …\nGet the duration since the last activity we received from …\nTime elapsed time since last we have sent to or received …\nThe latency to the remote node over this network path.\nThe latency of the current network path to the remote node.\nReturns the local IP address which was used when the peer …\nThe amount of bytes lost on this path\nThe amount of packets lost on this path\nThe amount of PLPMTUD probe packets lost on this path …\nThe max_ack_delay we will request the peer to use\nMaximum number of incoming bidirectional streams that may …\nVariant of max_concurrent_bidi_streams affecting …\nComputes the maximum size of datagrams that may be passed …\nMaximum duration of inactivity to accept before timing out …\nMaximum number of Incoming to allow to exist at a time\nReturns metrics collected for this endpoint.\nWhether to allow clients to migrate to new addresses\nThe maximum UDP payload size guaranteed to be supported by …\nSpecifies the minimum MTU change to stop the MTU discovery …\nSpecifies the MTU discovery config (see MtuDiscoveryConfig …\nNotifies the system of potential network changes.\nResets path-specific state.\nCreate a default config with a particular handshake token …\nCreate a new StreamId\nInitializes new connection options.\nReturns a Watcher for the current NodeAddr for this …\nReturns the node id of this endpoint.\nThe globally unique identifier for this node.\nThe offset in the stream\nPacket deliveries were confirmed\nPackets were deemed lost or marked congested\nPackets are acked in batches, all with the same now …\nThe known MTU for the current network path has been updated\nOne or more packets were just sent\nMethod for opening a sealed message data\nInitiates a new outgoing bidirectional stream.\nInitiates a new outgoing unidirectional stream.\nMaximum reordering in packet number space before FACK …\nStatistics related to the current transmission path\nThis implies we only use the relay to communicate and do …\nCryptographic identity of the peer.\nNumber of consecutive PTOs after which network is …\nAttempts to read from the stream into buf.\nAttempt to write bytes from buf into the stream.\nThe preferred IPv4 address that will be communicated to …\nThe preferred IPv6 address that will be communicated to …\nGet the priority of the send stream\nSets the proxy url from the environment, in this order:\nSets an explicit proxy url to proxy all HTTP(S) traffic …\nRead data contiguously from the stream.\nRead the next segment of data\nRead the next segments of data\nReceives an application datagram.\nRead an exact number of bytes contiguously from the stream.\nConvenience method to read all remaining data into a buffer\nHuman-readable reason for the close\nHuman-readable reason for the close\nHuman-readable explanation of the reason\nWhether to receive observed address reports from other …\nMaximum number of bytes the peer may transmit across all …\nCompletes when the stream has been reset by the peer or …\nRejects this incoming connection attempt.\nSets the protocol to use for relay connections.\nReturns the relay map for this mode.\nSets the relay servers to assist in establishing …\nRelay server information, if available.\nReturns the peer’s UDP address.\nWhether the socket address that is initiating this …\nReturns information about the remote node identified by a …\nReturns information about all the remote nodes this …\nReturns the NodeId from the peer’s TLS certificate.\nThe reordering threshold we will request the peer to use\nClose the send stream immediately.\nResponds with a retry packet.\nGenerate the integrity tag for a retry packet\nDuration after a retry token was issued for which it’s …\nCurrent best estimate of this connection’s latency …\nCurrent best estimate of this connection’s latency …\nSaturating integer addition. Computes self + rhs, …\nMethod for sealing message data\nSets a secret key to authenticate with other peers.\nReturns the secret_key of this endpoint.\nTransmits data as an unreliable, unordered application …\nWhether to implement fair queuing for send streams having …\nWhether to send observed address reports to peers.\nMaximum number of bytes to transmit to a peer without …\nThe amount of packets sent on this path\nThe amount of PLPMTUD probe packets sent on this path …\nSets the list of accepted ALPN protocols.\nModifies the number of bidirectional streams that may be …\nModifies the number of unidirectional streams that may be …\nSet the priority of the send stream\nSee quinn_proto::TransportConfig::receive_window.\nSets the initial user-defined data to be published in …\nReturns a deduplicated list of Sources merged from all …\nA HashMap of Sources to Durations.\nA stable identifier for this connection.\nStart a server session with this configuration\nReturns connection statistics.\nStop accepting data\nCompletes when the peer stops the stream or reads the …\nMaximum number of bytes the peer may transmit without …\nObject to get current SystemTime\nMaximum reordering in time space before time based loss …\nPrivate key used to authenticate data included in …\nTransport configuration to use for incoming connections\nSet a custom TransportConfig\nSets a custom quinn::TransportConfig for this endpoint.\nSucceeds iff x < 2^62\nSucceeds iff x < 2^62\nSucceeds iff x < 2^62\nThe origin of this direct address.\nStatistics about UDP datagrams received on a connection\nStatistics about UDP datagrams transmitted on a connection\nSpecifies the upper bound to the max UDP payload size that …\nSets the initial user-defined data to be published in …\nConfiguration for sending and handling validation tokens\nSet a custom ValidationTokenConfig\nNumber of ack-eliciting bytes that may be in flight\nSets ALPN identifiers that should be signaled as supported …\nCreate a server config with the given crypto::ServerConfig\nCreate a server config with the given certificate chain to …\nSets the QUIC transport config options for this connection.\nWrite bytes to the stream\nConvenience method to write an entire buffer to the stream\nConvenience method to write an entire list of chunks to …\nConvenience method to write a single chunk in its entirety …\nWrite chunks to the stream\nThe name of the discovery service that discovered the …\nThe name of the application that added the node\nMetrics collected by an crate::endpoint::Endpoint.\nEnum of metrics for the module\nEnum of metrics for the module\nMetrics tracked for the relay server\nNumber of times this server has accepted a connection.\nBytes received from a FrameType::SendPacket\nBytes sent from a FrameType::SendPacket\nNumber of connections with a successful handshake that …\nNumber of connections with a successful handshake.\nNumber of client connections which have had any frames …\nFrameType::SendPacket dropped that are disco messages\nFrameType::SendPacket received that are disco messages\nFrameType::SendPacket sent that are disco messages\nNumber of connections we have removed because of an error\nNumber of times the external address obtained via port …\nNumber of frames received from client connection which …\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nNumber of FrameType::Pings received\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nNumber of updates to the local port.\nMetrics collected by the endpoint’s socket.\nNumber of mapping tasks started.\nNumber of failed mapping tasks.\nMetrics collected by net reports.\nNumber of nodes we have attempted to contact.\nNumber of nodes we have managed to contact directly.\nThe number of direct connections we have made to peers.\nThe number of direct connections we have lost to peers.\nThe number of connections to peers we have added over …\nThe number of connections to peers we have removed over …\nPackets of other FrameTypes dropped\nPackets of other FrameTypes received\nPackets of other FrameTypes sent\nNumber of PCP probes that found it available.\nNumber of PCP probes executed.\nMetrics collected by the portmapper service.\nNumber of probing tasks started.\nNumber of QUIC datagrams received.\nNumber of datagrams received using GRO\nNumber of accepted ‘iroh derp http’ connection upgrades\nFrameType::SendPacket dropped, that are not disco messages\nFrameType::SendPacket received, that are not disco messages\nFrameType::SendPacket sent, that are not disco messages\nNumber of FrameType::Pongs sent\nNumber of unique client keys per day\nNumber of FrameType::Unknown received\nNumber of UPnP probes that found it available.\nNumber of UPnP probes that resulted in a gateway different …\nNumber of UPnP probes executed.\nNumber of failed Upnp probes.\nNumber of accepted websocket connections\nSender to the main service.\nClient to run net_reports.\nEnum of metrics for the module\nOptions for running probes\nPieces needed to do QUIC address discovery.\nLatencies per relay node.\nA net_report report.\nReturns a new address to send messages to this actor.\nAttempts to bind a local socket to send STUN packets from.\nCaptivePortal is set when we think there’s a captive …\nA client config.\nCreate an Options that disables all probes\nA QUIC Endpoint\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nRuns a net_report, returning the report.\nip:port of global IPv4\n[ip]:port of global IPv6\nWhether the router supports communicating between two …\nEnable or disable https probe\nEnable or disable icmp_v4 probe\nEnable or disable icmp_v6 probe\nAn ICMPv4 round trip completed, None if not checked.\nAn ICMPv6 round trip completed, None if not checked.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nEnable ipv4 QUIC address discovery probes\nAn IPv4 STUN round trip completed.\nan IPv4 packet was able to be sent\nEnable ipv6 QUIC address discovery probes\nAn IPv6 STUN round trip completed.\nAn IPv6 packet was able to be sent\nReturns an iterator over all the relays and their …\nWhether STUN results depend on which STUN server you’re …\nWhether STUN results depend on which STUN server you’re …\nCreates a new net_report client.\ncould bind a socket to ::1\nProbe indicating the presence of port mapping protocols on …\nNone for unknown\nEnable quic probes\nPass a received STUN packet to the net_reporter.\nkeyed by relay Url\nkeyed by relay Url\nkeyed by relay Url\nNumber of reports executed by net_report, including full …\nNumber of full reports executed by net_report\nIncoming STUN packets dropped due to a full receiving …\nNumber of IPv4 STUN packets received.\nNumber of IPv6 STUN packets received.\nNumber of IPv4 STUN packets sent.\nNumber of IPv6 STUN packets sent.\nSet the ipv4 stun socket and enable ipv4 stun probes\nSet the ipv6 stun socket and enable ipv6 stun probes\nA UDP STUN round trip completed.\nThe DNS name for the iroh TXT record.\nError returned when an input value is too long for UserData…\nData about a node that may be published to and resolved …\nExtension methods for NodeId to encode to and decode from …\nInformation about a node that may be published to and …\nUnder the hood this is a UTF-8 String is no longer than …\nThe information published about the node.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nParses a NodeId from [z-base-32] encoding.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nThe NodeId of the node this is about.\nEncodes a NodeId in [z-base-32] encoding.\nWraps an existing protocol, limiting its access, based on …\nHandler for incoming connections.\nThe built router.\nBuilder for creating a Router for accepting protocols.\nHandle an incoming connection.\nConfigures the router to accept the ProtocolHandler when …\nCreates a new Router using given Endpoint.\nReturns the Endpoint stored in this router.\nReturns the Endpoint of the node.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreates a new user error from an arbitrary error type.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nChecks if the router is already shutdown.\nCreates a new router builder using given Endpoint.\nCreate a new AccessLimit.\nOptional interception point to handle the Connecting state.\nCalled when the router shuts down.\nShuts down the accept loop cleanly.\nSpawns an accept loop and returns a handle to it …\nA drop guard to clean up test infrastructure.\nHandle and drop guard for test DNS and Pkarr servers.\nCreate a ConcurrentDiscovery with DnsDiscovery and …\nCreate a DnsResolver configured to use the test DNS server.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nThe socket address of the DNS server.\nThe node origin domain.\nWait until a Pkarr announce for a node is published to the …\nThe HTTP URL of the Pkarr server.\nRun DNS and Pkarr servers on localhost.\nRuns a relay server with STUN and QUIC enabled suitable …\nRuns a relay server.\nRuns a relay server with STUN enabled suitable for tests.\nRun DNS and Pkarr servers on localhost with the specified …\nThe immediate, direct observer of a Watchable value.\nThe error for when a Watcher is disconnected from its …\nFuture returning the current or next value that’s Some …\nWraps a Watcher to allow observing a derived value.\nFuture returning the next item after the current one in a …\nA stream for a Watcher’s next values.\nThe type of value that can change.\nA wrapper around a value that notifies Watchers when the …\nA handle to a value that’s represented by one or more …\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the current state of the underlying value, or …\nReturns the currently stored value.\nReturns a future completing once the value is set to Some …\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nMaps this watcher with a function that transforms the …\nCreates a Watchable initialized to given value.\nReturns a watcher that updates every time this or the …\nPolls for the next value, or returns Disconnected if one …\nSets a new value.\nReturns a stream which will yield the most recent values …\nReturns a stream which will yield the most recent values …\nReturns a future completing with Ok(value) once a new …\nCreates a Direct Watcher, allowing the value to be …") \ No newline at end of file +searchState.loadedDescShard("iroh", 0, "Peer-to-peer QUIC connections.\nError when decoding.\nThe encoded information had the wrong length.\nError when decoding the public key.\nError when deserialising a PublicKey or a SecretKey.\nThe length of an ed25519 PublicKey, in bytes.\nNetwork-level addressing information for an iroh node.\nThe identifier for a node in the (iroh) network.\nA public key.\nRelays over the custom relaying protocol with a custom …\nConfiguration of all the relay servers that can be used.\nInformation on a specific relay server.\nThe HTTP upgrade protocol used for relaying.\nA URL identifying a relay server.\nCan occur when parsing a string into a RelayUrl.\nA secret key.\nRelays over websockets.\nGet this public key as a byte array.\nIs this a known node?\nDefault values used in iroh\nReturns the direct addresses of this peer.\nSocket addresses where the peer might be reached directly.\nNode address discovery.\nThis module exports a DNS resolver, which is also the …\nCreate an empty relay map.\nThe Endpoint allows establishing connections to other iroh …\nConvert to a hex string limited to the first 5 bytes for a …\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the addressing info from given ticket.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreates a RelayMap from a RelayUrl.\nReturns the argument unchanged.\nReturns the argument unchanged.\nConstruct a PublicKey from a slice of bytes.\nCreate a secret key from its byte representation.\nCreates a RelayMap from an iterator of RelayUrl.\nCreates a new NodeAddr from its parts.\nGenerate a new SecretKey with a randomness generator.\nGet the given node.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nReturns true, if only a NodeId is present.\nAre there any nodes in this map?\nHow many nodes are known?\nCo-locating all of the iroh metrics structs\nChecks the network conditions from the current host.\nCreates a new NodeAddr with no relay_url and no …\nThe node’s identifier.\nSupport for handling DNS resource records for dialing by …\nReturns an Iterator over all known nodes.\nTries to match the value of an HTTP upgrade header to …\nTools for spawning an accept loop that routes incoming …\nReturns the VerifyingKey for this PublicKey.\nThe public key of this SecretKey.\nConfiguration to speak to the QUIC endpoint on the relay …\nReturns the relay url of this peer.\nThe node’s home relay url.\nReturns the SigningKey for this SecretKey.\nSign the given message and return a digital signature\nWhether this relay server should only be used for STUN …\nThe stun port of the relay server.\nInternal utilities to support testing.\nConvert this to the bytes representing the secret part. …\nThe HTTP upgrade header used or expected.\nThe RelayUrl where this relay server can be dialed.\nReturns the sorted relay URLs.\nVerify a signature on a message with this secret key’s …\nAdds the given direct addresses.\nAdds a relay url.\nThe default HTTPS port used by the Relay server.\nThe default HTTP port used by the Relay server.\nThe default metrics port used by the Relay server.\nThe default QUIC port used by the Relay server to accept …\nThe default STUN port used by the Relay server.\nProduction configuration.\nStaging configuration.\nHostname of the default Asia-Pacific relay.\nHostname of the default EU relay.\nHostname of the default NA relay.\nGet the default RelayNode for Asia-Pacific\nGet the default RelayNode for EU.\nGet the default RelayNode for NA.\nGet the default RelayMap.\nHostname of the default EU relay.\nHostname of the default NA relay.\nGet the default RelayNode for EU.\nGet the default RelayNode for NA.\nGet the default RelayMap.\nA discovery service that combines multiple discovery …\nNode discovery for super::Endpoint.\nContext about the Endpoint for discovery services.\nDiscovery errors\nNode discovery results from Discovery services.\nTrait for structs that can be converted into Discovery.\nIntoDiscovery errors\nError returned when a discovery watch stream lagged too …\nThe max byte length allowed for user-defined data.\nData about a node that may be published to and resolved …\nInformation about a node that may be published to and …\nUnder the hood this is a UTF-8 String is no longer than …\nAdds a Discovery service.\nAdds direct addresses to the node data.\nRemoves all direct addresses from the node data.\nThe information published about the node.\nReturns the direct addresses of the node.\nDNS node discovery for iroh\nReturns the DnsResolver used by the endpoint.\nCreates an empty ConcurrentDiscovery.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreates a new user error from an arbitrary error type.\nCreates a new user error from an arbitrary error type.\nCreates a new user error from an arbitrary boxed error …\nCreates a new user error from an arbitrary boxed error …\nCreates a new NodeInfo from its parts.\nParses a NodeInfo from a pkarr::SignedPacket.\nCreates a new ConcurrentDiscovery.\nParses a NodeInfo from a TXT records lookup.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nTurns this discovery builder into a ready-to-use discovery …\nConverts into a NodeAddr without cloning.\nConverts into a NodeAddr without cloning.\nReturns the optional timestamp when this node info was …\nA discovery service that uses an mdns-like service to …\nCreates a new NodeData with a relay URL and a set of …\nCreates a new NodeInfo with an empty NodeData.\nCreates a new DiscoveryItem from a NodeInfo.\nReturns the NodeId of the endpoint.\nReturns the node id of the discovered node.\nThe NodeId of the node this is about.\nReturns the NodeInfo for the discovered node.\nA discovery service which publishes and resolves node …\nReturns the provenance of this discovery item.\nPublishes the given NodeData to the discovery mechanism.\nReturns the relay URL of the node.\nResolves the DiscoveryItem for the given NodeId.\nReturns the SecretKey of the endpoint.\nSets the relay URL of the node data.\nSets the user-defined data of the node data.\nA static node discovery to manually add node addressing …\nSubscribe to all addresses that get passively discovered.\nConverts into a NodeAddr by cloning the needed fields.\nConverts into a NodeAddr by cloning the needed fields.\nCreates a pkarr::SignedPacket.\nConverts into a list of {key}={value} strings.\nReturns the optional user-defined data of the node.\nReturns any user-defined data.\nThe number of skipped messages\nSets the direct addresses and returns the updated node …\nSets the direct addresses and returns the updated node …\nSets the relay URL and returns the updated node data.\nSets the relay URL and returns the updated node info.\nSets the user-defined data and returns the updated node …\nSets the user-defined data and returns the updated node …\nDNS node discovery\nBuilder for DnsDiscovery.\nThe n0 testing DNS node origin, for production.\nThe n0 testing DNS node origin, for testing.\nBuilds a DnsDiscovery with the passed DnsResolver.\nCreates a DnsDiscoveryBuilder that implements IntoDiscovery…\nSets the DNS resolver to use.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCreates a new DNS discovery using the iroh.link domain.\nDiscovery using swarm-discovery, a variation on mdns\nBuilder for MdnsDiscovery.\nName of this discovery service.\nReturns a MdnsDiscoveryBuilder that implements …\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCreate a new MdnsDiscovery Service.\nDefault TTL for the records in the pkarr signed packet.\nInterval in which to republish the node info even if …\nThe production pkarr relay run by number 0.\nThe testing pkarr relay run by number 0.\nPublisher of node discovery information to a pkarr relay.\nBuilder for PkarrPublisher.\nA pkarr client to publish pkarr::SignedPackets to a pkarr …\nResolver of node discovery information from a pkarr relay.\nBuilder for PkarrResolver.\nBuilds the PkarrPublisher with the passed secret key for …\nCreates a PkarrResolver from this builder.\nReturns a PkarrPublisherBuilder that publishes node info …\nCreates a new resolver builder using the pkarr relay …\nPkarr based node discovery for iroh, supporting both relay …\nSets the DNS resolver to use for resolving the pkarr relay …\nSets the DNS resolver to use for resolving the pkarr relay …\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCreates a pkarr publisher which uses the number 0 pkarr …\nCreates a pkarr resolver builder which uses the number 0 …\nCreates a new client.\nPublishes a SignedPacket.\nSets the interval after which packets are republished even …\nResolves a SignedPacket for the given NodeId.\nSets the TTL (time-to-live) for published packets.\nPublishes the addressing information about this node to a …\nCreates a new client while passing a DNS resolver to use.\nBuilder for DhtDiscovery.\nPkarr Mainline DHT and relay server node discovery.\nBuilds the discovery mechanism.\nCreates a new builder for DhtDiscovery.\nExplicitly sets the pkarr client to use.\nSets whether to publish to the Mainline DHT.\nReturns the argument unchanged.\nReturns the argument unchanged.\nSets whether to include the direct addresses in the DNS …\nSets the initial delay before the first publish.\nCalls U::from(self).\nCalls U::from(self).\nUses the default number 0 pkarr relay URL.\nDisables publishing even if a secret key is set.\nSets the pkarr relay URL to use.\nSets the republish delay for the DHT.\nSets the secret key to use for signing the DNS packets.\nSets the time-to-live value for the DNS packets.\nThe provenance string for this discovery implementation.\nA static node discovery to manually add node addressing …\nAugments node addressing information for the given node ID.\nReturns the argument unchanged.\nCreates a static discovery instance from node addresses.\nReturns node addressing information for the given node ID.\nCalls U::from(self).\nCreates a new static discovery instance.\nRemoves all node addressing information for the given node …\nSets node addressing information for the given node ID.\nThe DNS resolver used throughout iroh.\nThe n0 testing DNS node origin, for production.\nThe n0 testing DNS node origin, for testing.\nRemoves all entries from the cache.\nReturns the argument unchanged.\nCalls U::from(self).\nPerform an ipv4 lookup with a timeout.\nResolve IPv4 and IPv6 in parallel with a timeout.\nRace an ipv4 and ipv6 lookup with a timeout in a staggered …\nPerform an ipv4 lookup with a timeout in a staggered …\nPerform an ipv6 lookup with a timeout.\nPerform an ipv6 lookup with a timeout in a staggered …\nLooks up node info by DNS name.\nLooks up node info by DNS name in a staggered fashion.\nLooks up node info by NodeId and origin domain name.\nLooks up node info by NodeId and origin domain name.\nLookup a TXT record.\nCreate a new DNS resolver with sensible cross-platform …\nResolve a hostname from a URL to an IP address.\nCreate a new DNS resolver configured with a single UDP DNS …\nthe endpoint has reached the confidentiality or integrity …\nthe application or application protocol caused the …\nFuture produced by Endpoint::accept.\nFuture produced by Connection::accept_bi\nFuture produced by Connection::accept_uni\nParameters for controlling the peer’s acknowledgement …\nA key for sealing data with AEAD-based algorithms\nUses all available paths\nApplication layer added the address directly.\nReason given by an application for closing the connection\nThe peer closed the connection\nBuilder for Endpoint.\nthe number of connection IDs provided by the peer exceeds …\nthe server refused to accept a new connection\nreceived more data in CRYPTO frames than can be buffered\nWe received a CallMeMaybe.\nA chunk of data from the receive stream\nThe connection could not be created because not enough of …\nError indicating that a stream has not been opened or has …\nThe stream has already been stopped, finished, or reset\nThe stream has already been finished or reset\nOptions for the Endpoint::connect_with_opts function.\nIn-progress connection attempt future\nA QUIC connection.\nReason given by the transport for closing the connection\nThe peer’s QUIC stack aborted the connection …\nReasons why a connection might be lost\nThe connection was lost\nThe connection was lost\nThe connection was lost\nThe connection was lost\nThe connection was lost\nConnection statistics\nThe type of connection we have to the endpoint.\nThe type of control message we have received.\nCommon interface for different congestion controllers\nConstructs controllers on demand\nGeneric crypto errors\nServer-side configuration for the crypto protocol\nUse a custom relay map.\nUse the default relay map, with production relay servers …\nDirect UDP connection\nA direct address on which an iroh-node might be …\nInformation about a direct address.\nThe type of direct address.\nDatagram support is disabled locally\nDisable relay servers completely.\nThe address was discovered by a discovery service.\nEnvironment variable to force the use of staging relays.\nControls an iroh node, establishing connections with other …\nError returned by Session::export_keying_material.\nreceived a STREAM frame or a RESET_STREAM frame containing …\nreceived more data than permitted in advertised data limits\nreceived a frame that was badly formatted\nThe stream finished before all bytes were read\nNumber of frames transmitted of each frame type\nA pseudo random key for HKDF\nthe endpoint encountered an internal error and cannot …\nreceived an invalid Retry Token in a client Initial\nAttempted an ordered read following an unordered read\nAn incoming connection for which the server has not yet …\nAdaptor to let Incoming be awaited like a Connecting.\nkey update error\nA locally bound socket address.\nThe local application closed the connection\nThe largest representable value\nThe largest encoded value length\nBoth a UDP and a relay connection are used.\nParameters governing MTU discovery.\nthe connection is being closed abruptly in the absence of …\nno viable network path exists\nApplication layer with a specific name added the node …\nWe have no verified connection to this PublicKey\nFuture produced by Connection::open_bi\nFuture produced by Connection::open_uni\ndetected an error with protocol compliance that was not …\nDefines the mode of path selection for all traffic flowing …\nStatistics related to a transmission path\nWe received a Ping from the node.\nWe received a Pong from the node.\nAn address assigned by the router using port mapping.\nAn error occurred during reading\nFuture produced by Connection::read_datagram\nErrors that arise from reading from a stream.\nA read error occurred\nErrors that arise from reading from a stream.\nErrors from RecvStream::read_to_end\nA stream that can only be used to receive data\nRelay connection over relay\nA node communicated with us first via relay.\nConfiguration of the relay servers for an Endpoint.\nForces all traffic to go exclusively through relays\nDetails about a remote iroh node which is known to this …\nThe peer abandoned transmitting data on this stream\nThe peer is unable to continue processing this connection, …\nErrors that arise while waiting for a stream to be reset\nError for attempting to retry an Incoming which already …\nreceived a frame for a stream identifier that exceeded …\nreceived a frame for a stream that was not in a state that …\nAddress was loaded from the fs.\nErrors that can arise when sending a datagram\nA stream that can only be used to send data\nParameters governing incoming connections\nThe origin or source through which an address associated …\nUse the staging relay servers from n0.\nThe peer is no longer accepting data on this stream\nErrors that arise while monitoring for a send stream stop …\nIdentifier for a stream within a particular connection\nPublic internet address discovered via STUN.\nHard NAT: STUN’ed IPv4 address + local fixed port.\nreceived transport parameters that were badly formatted, …\nCommunication with the peer has lapsed for longer than the …\nThe datagram is larger than the connection can currently …\nThe stream is larger than the user-supplied limit\nParameters governing the core QUIC state machine\nTransport-level errors occur when a peer violates the …\nThe peer violated the QUIC specification as understood by …\nTransport-level error code\nA node communicated with us first via UDP.\nStatistics about UDP datagrams transmitted or received on …\nNot yet determined..\nThe peer does not support receiving datagram frames\nError indicating that the specified QUIC version is not …\nAn integer less than 2^62\nThe peer doesn’t implement any supported version\nA handle to some connection internals, use with care.\nErrors that arise from writing to a stream\nIndicates how many bytes and chunks had been transferred …\nFuture that completes when a connection is fully …\nThis was a 0-RTT stream and the server rejected it\nThis was a 0-RTT stream and the server rejected it\nThis was a 0-RTT stream and the server rejected it\nThis was a 0-RTT stream and the server rejected it\nAccepts an incoming connection on the endpoint.\nAttempts to accept this incoming connection (an error may …\nAccept the next incoming bidirectional stream.\nAccepts the next incoming uni-directional stream.\nAccepts this incoming connection using a custom …\nThe ack-eliciting threshold we will request the peer to use\nSpecifies the ACK frequency config (see AckFrequencyConfig …\nAdds a discovery mechanism for this endpoint.\nInforms this Endpoint about addresses of the iroh node.\nInforms this Endpoint about addresses of the iroh node, …\nThe UDP address reported by the remote node.\nThe address.\nThe addresses at which this node might be reachable.\nDerive AEAD using hkdf\nWhether the implementation is permitted to set the spin …\nExtracts the ALPN protocol from the peer’s handshake …\nExtracts the ALPN protocol from the peer’s handshake …\nSets the ALPN protocols that this endpoint will accept on …\nBinds the magic endpoint.\nSets the IPv4 bind address.\nSets the IPv6 bind address.\nSpecifies the amount of time that MTU discovery should …\nThe number of times a black hole was detected in the path\nReturns the local socket addresses on which the underlying …\nConstruct a fresh Controller\nReturns the builder for an Endpoint, with a production …\nThe contents of the chunk\nThe total amount of bytes which have been transferred …\nThe amount of bytes which had been written\nThe amount of full chunks which had been written\nRemoves all discovery services from the builder.\nDuplicate the controller’s state\nCloses the QUIC endpoint and the magic socket.\nCloses the connection immediately.\nIf the connection is closed, the reason why.\nWait for the connection to be closed for any reason.\nType of error\nHow to construct new congestion::Controllers\nCongestion events on the connection\nCurrent state of the congestion control algorithm, for …\nReturns a Watcher that reports the current connection type …\nThe type of connection we have to the node, either direct …\nConnects to a remote Endpoint.\nStarts a connection attempt with a remote Endpoint.\nCreate QUIC error code from TLS alert code\nTLS configuration used for incoming connections\nMaximum quantity of out-of-order crypto layer data to …\nLargest UDP payload size the path currently supports\nCurrent congestion window of the connection\nMaximum number of incoming application datagram bytes to …\nMaximum number of outgoing application datagram bytes to …\nBytes available in the outgoing datagram buffer.\nThe amount of UDP datagrams observed\nReturns the default relay mode.\nWhich directions data flows in\nReturns a Watcher for the direct addresses of this Endpoint…\nOptionally sets a discovery mechanism for this endpoint.\nReturns the discovery mechanism, if configured.\nConfigures the endpoint to also use the mainline DHT with …\nConfigures the endpoint to also use local network …\nConfigures the endpoint to use the default n0 DNS …\nReturns a stream of all remote nodes discovered through …\nOptionally sets a custom DNS resolver to use for this …\nReturns the DNS resolver used in this Endpoint.\nWhether to use “Generic Segmentation Offload” to …\nClass of error as encoded in the specification\nApplication-specific reason code\nDerives keying material from this connection’s TLS …\nNotify the peer that no more data will ever be written to …\nReturns true if the use of staging relays is forced.\nFrame type that triggered the error\nStatistics about frames received on a connection\nStatistics about frames transmitted on a connection\nType of frame that caused the close\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nConstruct a VarInt infallibly\nSucceeds iff x < 2^62\nCreate a VarInt without ensuring it’s in range\nParameters negotiated during the handshake\nParameters negotiated during the handshake.\nWhether there is a possible known network path to the …\nReturns a Watcher for the RelayUrl of the Relay server …\nGet the identity of this stream\nGet the identity of this stream\nIgnores this incoming connection attempt, not sending any …\nMaximum number of received bytes to buffer for each …\nMaximum number of received bytes to buffer for all Incoming\nDistinguishes streams of the same initiator and …\nCreate the initial set of keys given the client’s …\nThe initial value to be used as the maximum UDP payload …\nThe RTT used before an RTT sample is taken\nInitial congestion window\nWhich side of a connection initiated the stream\nSkip verification of SSL certificates from relay servers\nSpecifies the time to wait after completing MTU discovery …\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConverts this Connecting into a 0-RTT or 0.5-RTT …\nReturns Self for use in down-casting to extract …\nGet the Incoming\nExtract the integer value\nThe amount of I/O operations executed\nCheck if this stream has been opened during 0-RTT.\nReturns true if the Connection associated with this handle …\nCheck if this endpoint is still alive, or already closed.\nPeriod of inactivity before sending a keep-alive packet\nEnables saving the TLS pre-master key for connections.\nOptionally set a list of known nodes.\nElapsed time since this network path was known to exist.\nLast control message received by this node about this …\nElapsed time since the last payload message was received …\nGet the duration since the last activity we received from …\nTime elapsed time since last we have sent to or received …\nThe latency to the remote node over this network path.\nThe latency of the current network path to the remote node.\nReturns the local IP address which was used when the peer …\nThe amount of bytes lost on this path\nThe amount of packets lost on this path\nThe amount of PLPMTUD probe packets lost on this path …\nThe max_ack_delay we will request the peer to use\nMaximum number of incoming bidirectional streams that may …\nVariant of max_concurrent_bidi_streams affecting …\nComputes the maximum size of datagrams that may be passed …\nMaximum duration of inactivity to accept before timing out …\nMaximum number of Incoming to allow to exist at a time\nReturns metrics collected for this endpoint.\nWhether to allow clients to migrate to new addresses\nThe maximum UDP payload size guaranteed to be supported by …\nSpecifies the minimum MTU change to stop the MTU discovery …\nSpecifies the MTU discovery config (see MtuDiscoveryConfig …\nNotifies the system of potential network changes.\nResets path-specific state.\nCreate a default config with a particular handshake token …\nCreate a new StreamId\nInitializes new connection options.\nReturns a Watcher for the current NodeAddr for this …\nReturns the node id of this endpoint.\nThe globally unique identifier for this node.\nThe offset in the stream\nPacket deliveries were confirmed\nPackets were deemed lost or marked congested\nPackets are acked in batches, all with the same now …\nThe known MTU for the current network path has been updated\nOne or more packets were just sent\nMethod for opening a sealed message data\nInitiates a new outgoing bidirectional stream.\nInitiates a new outgoing unidirectional stream.\nMaximum reordering in packet number space before FACK …\nStatistics related to the current transmission path\nThis implies we only use the relay to communicate and do …\nCryptographic identity of the peer.\nNumber of consecutive PTOs after which network is …\nAttempts to read from the stream into buf.\nAttempt to write bytes from buf into the stream.\nThe preferred IPv4 address that will be communicated to …\nThe preferred IPv6 address that will be communicated to …\nGet the priority of the send stream\nSets the proxy url from the environment, in this order:\nSets an explicit proxy url to proxy all HTTP(S) traffic …\nRead data contiguously from the stream.\nRead the next segment of data\nRead the next segments of data\nReceives an application datagram.\nRead an exact number of bytes contiguously from the stream.\nConvenience method to read all remaining data into a buffer\nHuman-readable reason for the close\nHuman-readable reason for the close\nHuman-readable explanation of the reason\nWhether to receive observed address reports from other …\nMaximum number of bytes the peer may transmit across all …\nCompletes when the stream has been reset by the peer or …\nRejects this incoming connection attempt.\nSets the protocol to use for relay connections.\nReturns the relay map for this mode.\nSets the relay servers to assist in establishing …\nRelay server information, if available.\nReturns the peer’s UDP address.\nWhether the socket address that is initiating this …\nReturns information about the remote node identified by a …\nReturns information about all the remote nodes this …\nReturns the NodeId from the peer’s TLS certificate.\nThe reordering threshold we will request the peer to use\nClose the send stream immediately.\nResponds with a retry packet.\nGenerate the integrity tag for a retry packet\nDuration after a retry token was issued for which it’s …\nCurrent best estimate of this connection’s latency …\nCurrent best estimate of this connection’s latency …\nSaturating integer addition. Computes self + rhs, …\nMethod for sealing message data\nSets a secret key to authenticate with other peers.\nReturns the secret_key of this endpoint.\nTransmits data as an unreliable, unordered application …\nWhether to implement fair queuing for send streams having …\nWhether to send observed address reports to peers.\nMaximum number of bytes to transmit to a peer without …\nThe amount of packets sent on this path\nThe amount of PLPMTUD probe packets sent on this path …\nSets the list of accepted ALPN protocols.\nModifies the number of bidirectional streams that may be …\nModifies the number of unidirectional streams that may be …\nSet the priority of the send stream\nSee quinn_proto::TransportConfig::receive_window.\nSets the initial user-defined data to be published in …\nReturns a deduplicated list of Sources merged from all …\nA HashMap of Sources to Durations.\nA stable identifier for this connection.\nStart a server session with this configuration\nReturns connection statistics.\nStop accepting data\nCompletes when the peer stops the stream or reads the …\nMaximum number of bytes the peer may transmit without …\nObject to get current SystemTime\nMaximum reordering in time space before time based loss …\nPrivate key used to authenticate data included in …\nTransport configuration to use for incoming connections\nSet a custom TransportConfig\nSets a custom quinn::TransportConfig for this endpoint.\nSucceeds iff x < 2^62\nSucceeds iff x < 2^62\nSucceeds iff x < 2^62\nThe origin of this direct address.\nStatistics about UDP datagrams received on a connection\nStatistics about UDP datagrams transmitted on a connection\nSpecifies the upper bound to the max UDP payload size that …\nSets the initial user-defined data to be published in …\nConfiguration for sending and handling validation tokens\nSet a custom ValidationTokenConfig\nNumber of ack-eliciting bytes that may be in flight\nSets ALPN identifiers that should be signaled as supported …\nCreate a server config with the given crypto::ServerConfig\nCreate a server config with the given certificate chain to …\nSets the QUIC transport config options for this connection.\nWrite bytes to the stream\nConvenience method to write an entire buffer to the stream\nConvenience method to write an entire list of chunks to …\nConvenience method to write a single chunk in its entirety …\nWrite chunks to the stream\nThe name of the discovery service that discovered the …\nThe name of the application that added the node\nMetrics collected by an crate::endpoint::Endpoint.\nEnum of metrics for the module\nEnum of metrics for the module\nMetrics tracked for the relay server\nNumber of times this server has accepted a connection.\nBytes received from a FrameType::SendPacket\nBytes sent from a FrameType::SendPacket\nNumber of connections with a successful handshake that …\nNumber of connections with a successful handshake.\nNumber of client connections which have had any frames …\nFrameType::SendPacket dropped that are disco messages\nFrameType::SendPacket received that are disco messages\nFrameType::SendPacket sent that are disco messages\nNumber of connections we have removed because of an error\nNumber of times the external address obtained via port …\nNumber of frames received from client connection which …\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nNumber of FrameType::Pings received\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nNumber of updates to the local port.\nMetrics collected by the endpoint’s socket.\nNumber of mapping tasks started.\nNumber of failed mapping tasks.\nMetrics collected by net reports.\nNumber of nodes we have attempted to contact.\nNumber of nodes we have managed to contact directly.\nThe number of direct connections we have made to peers.\nThe number of direct connections we have lost to peers.\nThe number of connections to peers we have added over …\nThe number of connections to peers we have removed over …\nPackets of other FrameTypes dropped\nPackets of other FrameTypes received\nPackets of other FrameTypes sent\nNumber of PCP probes that found it available.\nNumber of PCP probes executed.\nMetrics collected by the portmapper service.\nNumber of probing tasks started.\nNumber of QUIC datagrams received.\nNumber of datagrams received using GRO\nNumber of accepted ‘iroh derp http’ connection upgrades\nFrameType::SendPacket dropped, that are not disco messages\nFrameType::SendPacket received, that are not disco messages\nFrameType::SendPacket sent, that are not disco messages\nNumber of FrameType::Pongs sent\nNumber of unique client keys per day\nNumber of FrameType::Unknown received\nNumber of UPnP probes that found it available.\nNumber of UPnP probes that resulted in a gateway different …\nNumber of UPnP probes executed.\nNumber of failed Upnp probes.\nNumber of accepted websocket connections\nSender to the main service.\nClient to run net_reports.\nEnum of metrics for the module\nOptions for running probes\nPieces needed to do QUIC address discovery.\nLatencies per relay node.\nA net_report report.\nReturns a new address to send messages to this actor.\nAttempts to bind a local socket to send STUN packets from.\nCaptivePortal is set when we think there’s a captive …\nA client config.\nCreate an Options that disables all probes\nA QUIC Endpoint\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nRuns a net_report, returning the report.\nip:port of global IPv4\n[ip]:port of global IPv6\nWhether the router supports communicating between two …\nEnable or disable https probe\nEnable or disable icmp_v4 probe\nEnable or disable icmp_v6 probe\nAn ICMPv4 round trip completed, None if not checked.\nAn ICMPv6 round trip completed, None if not checked.\nSkip cert verification\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nEnable ipv4 QUIC address discovery probes\nAn IPv4 STUN round trip completed.\nan IPv4 packet was able to be sent\nEnable ipv6 QUIC address discovery probes\nAn IPv6 STUN round trip completed.\nAn IPv6 packet was able to be sent\nReturns an iterator over all the relays and their …\nWhether STUN results depend on which STUN server you’re …\nWhether STUN results depend on which STUN server you’re …\nCreates a new net_report client.\ncould bind a socket to ::1\nProbe indicating the presence of port mapping protocols on …\nNone for unknown\nEnable quic probes\nPass a received STUN packet to the net_reporter.\nkeyed by relay Url\nkeyed by relay Url\nkeyed by relay Url\nNumber of reports executed by net_report, including full …\nNumber of full reports executed by net_report\nIncoming STUN packets dropped due to a full receiving …\nNumber of IPv4 STUN packets received.\nNumber of IPv6 STUN packets received.\nNumber of IPv4 STUN packets sent.\nNumber of IPv6 STUN packets sent.\nSet the ipv4 stun socket and enable ipv4 stun probes\nSet the ipv6 stun socket and enable ipv6 stun probes\nA UDP STUN round trip completed.\nThe DNS name for the iroh TXT record.\nError returned when an input value is too long for UserData…\nData about a node that may be published to and resolved …\nExtension methods for NodeId to encode to and decode from …\nInformation about a node that may be published to and …\nUnder the hood this is a UTF-8 String is no longer than …\nThe information published about the node.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nParses a NodeId from [z-base-32] encoding.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nThe NodeId of the node this is about.\nEncodes a NodeId in [z-base-32] encoding.\nWraps an existing protocol, limiting its access, based on …\nHandler for incoming connections.\nThe built router.\nBuilder for creating a Router for accepting protocols.\nHandle an incoming connection.\nConfigures the router to accept the ProtocolHandler when …\nCreates a new Router using given Endpoint.\nReturns the Endpoint stored in this router.\nReturns the Endpoint of the node.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreates a new user error from an arbitrary error type.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nChecks if the router is already shutdown.\nCreates a new router builder using given Endpoint.\nCreate a new AccessLimit.\nOptional interception point to handle the Connecting state.\nCalled when the router shuts down.\nShuts down the accept loop cleanly.\nSpawns an accept loop and returns a handle to it …\nA drop guard to clean up test infrastructure.\nHandle and drop guard for test DNS and Pkarr servers.\nCreate a ConcurrentDiscovery with DnsDiscovery and …\nCreate a DnsResolver configured to use the test DNS server.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nThe socket address of the DNS server.\nThe node origin domain.\nWait until a Pkarr announce for a node is published to the …\nThe HTTP URL of the Pkarr server.\nRun DNS and Pkarr servers on localhost.\nRuns a relay server with STUN and QUIC enabled suitable …\nRuns a relay server.\nRuns a relay server with STUN enabled suitable for tests.\nRun DNS and Pkarr servers on localhost with the specified …") \ No newline at end of file diff --git a/pr/3327/docs/search.desc/iroh_relay/iroh_relay-desc-0-.js b/pr/3327/docs/search.desc/iroh_relay/iroh_relay-desc-0-.js index d31149c4a8..22da50dc67 100644 --- a/pr/3327/docs/search.desc/iroh_relay/iroh_relay-desc-0-.js +++ b/pr/3327/docs/search.desc/iroh_relay/iroh_relay-desc-0-.js @@ -1 +1 @@ -searchState.loadedDescShard("iroh_relay", 0, "Iroh’s relay is a feature within iroh, a peer-to-peer …\nTracks pings on a single relay connection.\nConfiguration of all the relay servers that can be used.\nInformation on a specific relay server.\nConfiguration for speaking to the QUIC endpoint on the …\nExposes Client, which allows to establish connections to a …\nIs this a known node?\nReturns the current timeout set for pings.\nDefault values used in the relay.\nDNS resolver\nCreate an empty relay map.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreates a RelayMap from a RelayUrl.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreates a RelayMap from an iterator of RelayUrl.\nGet the given node.\nHTTP-specific constants for the relay server and client.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nAre there any nodes in this map?\nHow many nodes are known?\nCreates a new ping tracker, setting the ping timeout for …\nStarts a new ping.\nSupport for handling DNS resource records for dialing by …\nReturns an Iterator over all known nodes.\nUpdates the ping tracker with a received pong.\nThe port on which the connection should be bound to.\nProtocols used by the iroh-relay\nCreate a QUIC server that accepts connections for QUIC …\nConfiguration to speak to the QUIC endpoint on the relay …\nA fully-fledged iroh-relay server over HTTP or HTTPS.\nWhether this relay server should only be used for STUN …\nThe stun port of the relay server.\nCancel-safe waiting for a ping timeout.\nThe RelayUrl where this relay server can be dialed.\nReturns the sorted relay URLs.\nA relay client.\nBuild a Client.\nThe send half of a relay client.\nThe receive half of a relay client.\nConnection errors.\nErrors that can occur while dialing the relay server.\nA one-way message from server to client, declaring the …\nA one-way empty message from server to client, just to …\nIndicates that the client identified by the underlying …\nRequest from a client or server to reply to the other side …\nSends a ping message to the connected relay server.\nReply to a ReceivedMessage::Ping from a client or server …\nSends a pong message to the connected relay server.\nThe messages received from a framed relay stream.\nRepresents an incoming packet.\nErrors when receiving messages from the relay server.\nError for sending messages to the relay server.\nMessages we can send to a relay server.\nSend a packet of data to the NodeId.\nA one-way message from server to client, advertising that …\nReturns if we should prefer ipv6 it replaces the …\nEstablishes a new connection to the relay server.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nSkip the verification of the relay server’s SSL …\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nIndicates this client is a prober\nSet the capacity of the cache for public keys.\nReturns the local address of the client.\nCreates a client config that trusts any servers without …\nCreate a new ClientBuilder\nSets whether to connect to the relay via websockets or not.\nSet an explicit proxy url to proxy all HTTP(S) traffic …\nSplits the client into a sink and a stream.\nThe received packet bytes.\nIf set, is a description of why the connection is …\nAn advisory duration that the client should wait before …\nThe NodeId of the packet sender.\nAn advisory duration for how long the client should …\nThe default HTTPS port used by the Relay server.\nThe default HTTP port used by the Relay server.\nThe default capacity of the key cache for the relay server.\nThe default metrics port used by the Relay server.\nThe default QUIC port used by the Relay server to accept …\nThe default STUN port used by the Relay server.\nPotential errors related to dns.\nThe DNS resolver used throughout iroh.\nError returned when an input value is too long for …\nThe n0 testing DNS node origin, for production.\nThe n0 testing DNS node origin, for testing.\nRecord data for a TXT record\nTXT records returned from DnsResolver::lookup_txt\nRemoves all entries from the cache.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nPerform an ipv4 lookup with a timeout.\nResolve IPv4 and IPv6 in parallel with a timeout.\nRace an ipv4 and ipv6 lookup with a timeout in a staggered …\nPerform an ipv4 lookup with a timeout in a staggered …\nPerform an ipv6 lookup with a timeout.\nPerform an ipv6 lookup with a timeout in a staggered …\nLooks up node info by DNS name.\nLooks up node info by DNS name in a staggered fashion.\nLooks up node info by NodeId and origin domain name.\nLooks up node info by NodeId and origin domain name.\nLookup a TXT record.\nCreate a new DNS resolver with sensible cross-platform …\nResolve a hostname from a URL to an IP address.\nReturns the raw character strings of this TXT record.\nCreate a new DNS resolver configured with a single UDP DNS …\nThe HTTP upgrade protocol used for relaying.\nThe HTTP path under which the relay accepts relaying …\nThe HTTP path under which the relay allows doing latency …\nRelays over the custom relaying protocol with a custom …\nRelays over websockets.\nReturns the argument unchanged.\nCalls U::from(self).\nTries to match the value of an HTTP upgrade header to …\nThe HTTP upgrade header used or expected.\nThe DNS name for the iroh TXT record.\nThe max byte length allowed for user-defined data.\nError returned when an input value is too long for UserData…\nData about a node that may be published to and resolved …\nExtension methods for NodeId to encode to and decode from …\nInformation about a node that may be published to and …\nUnder the hood this is a UTF-8 String is no longer than …\nAdds direct addresses to the node data.\nRemoves all direct addresses from the node data.\nThe information published about the node.\nReturns the direct addresses of the node.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreates a new NodeInfo from its parts.\nParses a NodeInfo from a pkarr::SignedPacket.\nParses a NodeInfo from a TXT records lookup.\nParses a NodeId from [z-base-32] encoding.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConverts into a NodeAddr without cloning.\nCreates a new NodeData with a relay URL and a set of …\nCreates a new NodeInfo with an empty NodeData.\nThe NodeId of the node this is about.\nReturns the relay URL of the node.\nSets the relay URL of the node data.\nSets the user-defined data of the node data.\nConverts into a NodeAddr by cloning the needed fields.\nCreates a pkarr::SignedPacket.\nConverts into a list of {key}={value} strings.\nEncodes a NodeId in [z-base-32] encoding.\nReturns the optional user-defined data of the node.\nSets the direct addresses and returns the updated node …\nSets the direct addresses and returns the updated node …\nSets the relay URL and returns the updated node data.\nSets the relay URL and returns the updated node info.\nSets the user-defined data and returns the updated node …\nSets the user-defined data and returns the updated node …\nThis module exports looks_like_disco_wrapper as the only …\nThis module implements the relaying protocol used by the …\nSTUN packets sending and receiving.\nThe 6 byte header of all discovery messages.\nReports whether p looks like it’s a packet containing an …\nmagic + 32b pub key + 24B nonce + bytes\nThe one byte frame type at the beginning of the frame …\nSent from server to client to tell the client if their …\nno payload, no-op (to be replaced with ping/pong)\nThe maximum size of a packet sent over relay. (This only …\n1 byte payload: 0x01 or 0x00 for whether this is client’…\nSent from server to client to signal that a previous …\nFrames 9-11 concern meshing, which we have eliminated from …\n8 byte payload, the contents of ping being replied to\nProtocol send errors.\nv0/1 packet bytes, v2: 32B src pub key + packet bytes\nSent from server to client for the server to declare that …\nProtocol send errors.\n32B dest pub key + packet bytes\nUnknown frame type\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nThe AlternateServeratribute\nThe ErrorCodeatribute\nerror response\nThe Fingerprintatribute\nindication\nSTUN request had bogus fingerprint.\nThe STUN message could not be parsed or is otherwise …\nSTUN response has malformed attributes.\nThe MappedAddressatribute\nThe STUN message class. Although there are four message …\nClass used to decode STUN messages\nThe MessageIntegrityatribute\nThe MessageIntegritySha256atribute\nSTUN request didn’t end in fingerprint.\nThe Nonceatribute\nSTUN request is not a binding request when it should be.\nSTUN packet is not a response when it should be.\nThe PasswordAlgorithmatribute\nThe PasswordAlgorithmsatribute\nThe Realmatribute\nrequest\nThe Softwareatribute\nSTUN Attributes that can be attached to a StunMessage\nDescribes an error decoding a StunMessage\nErrors that can occur when handling a STUN packet.\nsuccess response\nThe transaction ID is a 96-bit identifier, used to …\nThe Unknownatribute\nThe UnknownAttributesatribute\nThe UserHashatribute\nThe UserNameatribute\nThe XorMappedAddressatribute\nReturns a reference to the internal attribute value or an …\nReturns a reference to the bytes that represents the …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns the STUN attribute type of this instance.\nDecodes the STUN raw buffer\nCreates a cryptographically random transaction ID chosen …\nReturns a reference to the AlternateServer attribute.\nReturns a reference to the ErrorCode attribute.\nReturns a reference to the Fingerprint attribute.\nReturns a reference to the MappedAddress attribute.\nReturns a reference to the MessageIntegrity attribute.\nReturns a reference to the MessageIntegritySha256 …\nReturns a reference to the Nonce attribute.\nReturns a reference to the PasswordAlgorithm attribute.\nReturns a reference to the PasswordAlgorithms attribute.\nReturns a reference to the Realm attribute.\nReturns a reference to the Software attribute.\nReturns a reference to the Unknown attribute.\nReturns a reference to the UnknownAttributes attribute.\nReturns a reference to the UserHash attribute.\nReturns a reference to the UserName attribute.\nReturns a reference to the XorMappedAddress attribute.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nGets the context associated to this decoder\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nReports whether b is a STUN message.\nReturns true if this StunAttribute is AlternateServer\nReturns true if this StunAttribute is ErrorCode\nReturns true if this StunAttribute is Fingerprint\nReturns true if this StunAttribute is MappedAddress\nReturns true if this StunAttribute is MessageIntegrity\nReturns true if this StunAttribute is …\nReturns true if this StunAttribute is Nonce\nReturns true if this StunAttribute is PasswordAlgorithm\nReturns true if this StunAttribute is PasswordAlgorithms\nReturns true if this StunAttribute is Realm\nReturns true if this StunAttribute is Software\nReturns true if this StunAttribute is Unknown\nReturns true if this StunAttribute is UnknownAttributes\nReturns true if this StunAttribute is UserHash\nReturns true if this StunAttribute is UserName\nReturns true if this StunAttribute is XorMappedAddress\nSTUN Methods Registry\nParses a STUN binding request.\nParses a successful binding response STUN packet. The IP …\nGenerates a binding request STUN packet.\nGenerates a binding response.\nBinding\nReserved\nShared secret\nALPN for our quic addr discovery\nQuic client related errors.\nEndpoint close error code\nEndpoint close reason\nHandles the client side of QUIC address discovery.\nReturns the argument unchanged.\nReturns the argument unchanged.\nClient side of QUIC address discovery.\nCalls U::from(self).\nCalls U::from(self).\nCreate a new QuicClient to handle the client side of QUIC …\nAccess restriction for a node.\nControls which nodes are allowed to use the relay.\nAccess is allowed.\nTLS certificate configuration.\nPer-client rate limit configuration.\nThe default certificate reload interval.\nAccess is denied.\nEveryone\nUse Let’s Encrypt.\nRate limits.\nUse a static TLS key and certificate chain.\nMetrics tracked for the relay server\nConfiguration for the QUIC server.\nConfiguration for the Relay HTTP and HTTPS server.\nAll metrics tracked in the relay server.\nUse a TLS key and certificate chain that can be reloaded.\nA Certificate resolver that reloads the certificate every …\nOnly nodes for which the function returns Access::Allow.\nA running Relay + STUN server.\nConfiguration for the full Relay & STUN server.\nServer spawn errors\nConfiguration for the STUN server.\nMetrics tracked for the STUN server.\nServer task errors\nTLS configuration for Relay server.\nBurst limit for accepting new connection. Unlimited if not …\nRate limit for accepting new connection. Unlimited if not …\nNumber of times this server has accepted a connection.\nAccess configuration.\nNumber of bad requests made to the STUN endpoint.\nThe socket address on which the STUN server should bind.\nThe socket address on which the QUIC server should bind.\nMax number of bytes per second to read from the client …\nBytes received from a FrameType::SendPacket\nBytes sent from a FrameType::SendPacket\nMode for getting a cert.\nThe certificates chain if configured with manual TLS …\nRate limits for incoming traffic from a client connection.\nNumber of client connections which have had any frames …\nFrameType::SendPacket dropped that are disco messages\nFrameType::SendPacket received that are disco messages\nFrameType::SendPacket sent that are disco messages\nNumber of connections we have removed because of an error\nNumber of STUN requests that end in failure.\nNumber of frames received from client connection which …\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nNumber of FrameType::Pings received\nThe socket address the HTTP server is listening on.\nThe socket address on which the Relay HTTP server should …\nGet the server’s http RelayUrl.\nThe socket address the HTTPS server is listening on.\nThe socket address on which to serve the HTTPS server.\nGet the server’s https RelayUrl.\nPerform the initial load and construct the …\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nNumber of successful ipv4 STUN requests served.\nNumber of successful ipv6 STUN requests served.\nIs this node allowed?\nKey cache capacity.\nRate limits.\nMax number of bytes to read in a single burst.\nReturns the metrics collected in the relay server.\nSocket to serve metrics on.\nPackets of other FrameTypes dropped\nPackets of other FrameTypes received\nPackets of other FrameTypes sent\nConfiguration for the QUIC server, disabled if None.\nThe socket address the QUIC server is listening on.\nThe socket address on which to server the QUIC server is …\nConfiguration for the Relay server, disabled if None.\nNumber of accepted ‘iroh derp http’ connection upgrades\nReload the certificate.\nNumber of STUN requests made to the server.\nFrameType::SendPacket dropped, that are not disco messages\nFrameType::SendPacket received, that are not disco messages\nFrameType::SendPacket sent, that are not disco messages\nNumber of FrameType::Pongs sent\nMetrics tracked for the relay server.\nThe TLS server configuration for the QUIC server.\nThe server configuration.\nShutdown the resolver.\nRequests graceful shutdown.\nStarts the server.\nMetrics tracked for the STUN server.\nConfiguration for the STUN server, disabled if None.\nThe socket address the STUN server is listening on.\nReturns the handle for the task.\nExposes functions to quickly configure a server suitable …\nTLS configuration for the HTTPS server.\nNumber of unique client keys per day\nNumber of FrameType::Unknown received\nNumber of accepted websocket connections\nThe TLS certificate chain.\nState for Let’s Encrypt certificates.\nCreates a QuicConfig suitable for testing.\nCreates a RelayConfig suitable for testing.\nCreates a rustls::ServerConfig and certificates suitable …\nCreates a ServerConfig suitable for testing.\nCreates a StunConfig suitable for testing.\nCreates a TlsConfig suitable for testing.") \ No newline at end of file +searchState.loadedDescShard("iroh_relay", 0, "Iroh’s relay is a feature within iroh, a peer-to-peer …\nTracks pings on a single relay connection.\nConfiguration of all the relay servers that can be used.\nInformation on a specific relay server.\nConfiguration for speaking to the QUIC endpoint on the …\nExposes Client, which allows to establish connections to a …\nIs this a known node?\nReturns the current timeout set for pings.\nDefault values used in the relay.\nDNS resolver\nCreate an empty relay map.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreates a RelayMap from a RelayUrl.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreates a RelayMap from an iterator of RelayUrl.\nGet the given node.\nHTTP-specific constants for the relay server and client.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nAre there any nodes in this map?\nHow many nodes are known?\nCreates a new ping tracker, setting the ping timeout for …\nStarts a new ping.\nSupport for handling DNS resource records for dialing by …\nReturns an Iterator over all known nodes.\nUpdates the ping tracker with a received pong.\nThe port on which the connection should be bound to.\nProtocols used by the iroh-relay\nCreate a QUIC server that accepts connections for QUIC …\nConfiguration to speak to the QUIC endpoint on the relay …\nA fully-fledged iroh-relay server over HTTP or HTTPS.\nWhether this relay server should only be used for STUN …\nThe stun port of the relay server.\nCancel-safe waiting for a ping timeout.\nThe RelayUrl where this relay server can be dialed.\nReturns the sorted relay URLs.\nA relay client.\nBuild a Client.\nThe send half of a relay client.\nThe receive half of a relay client.\nConnection errors.\nErrors that can occur while dialing the relay server.\nA one-way message from server to client, declaring the …\nA one-way empty message from server to client, just to …\nIndicates that the client identified by the underlying …\nRequest from a client or server to reply to the other side …\nSends a ping message to the connected relay server.\nReply to a ReceivedMessage::Ping from a client or server …\nSends a pong message to the connected relay server.\nThe messages received from a framed relay stream.\nRepresents an incoming packet.\nErrors when receiving messages from the relay server.\nError for sending messages to the relay server.\nMessages we can send to a relay server.\nSend a packet of data to the NodeId.\nA one-way message from server to client, advertising that …\nReturns if we should prefer ipv6 it replaces the …\nEstablishes a new connection to the relay server.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nSkip the verification of the relay server’s SSL …\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nIndicates this client is a prober\nSet the capacity of the cache for public keys.\nReturns the local address of the client.\nCreates a client config that trusts any servers without …\nCreate a new ClientBuilder\nSets whether to connect to the relay via websockets or not.\nSet an explicit proxy url to proxy all HTTP(S) traffic …\nSplits the client into a sink and a stream.\nThe received packet bytes.\nIf set, is a description of why the connection is …\nAn advisory duration that the client should wait before …\nThe NodeId of the packet sender.\nAn advisory duration for how long the client should …\nThe default HTTPS port used by the Relay server.\nThe default HTTP port used by the Relay server.\nThe default capacity of the key cache for the relay server.\nThe default metrics port used by the Relay server.\nThe default QUIC port used by the Relay server to accept …\nThe default STUN port used by the Relay server.\nPotential errors related to dns.\nThe DNS resolver used throughout iroh.\nThe n0 testing DNS node origin, for production.\nThe n0 testing DNS node origin, for testing.\nError returned when an input value is too long for …\nRecord data for a TXT record\nTXT records returned from DnsResolver::lookup_txt\nRemoves all entries from the cache.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nPerform an ipv4 lookup with a timeout.\nResolve IPv4 and IPv6 in parallel with a timeout.\nRace an ipv4 and ipv6 lookup with a timeout in a staggered …\nPerform an ipv4 lookup with a timeout in a staggered …\nPerform an ipv6 lookup with a timeout.\nPerform an ipv6 lookup with a timeout in a staggered …\nLooks up node info by DNS name.\nLooks up node info by DNS name in a staggered fashion.\nLooks up node info by NodeId and origin domain name.\nLooks up node info by NodeId and origin domain name.\nLookup a TXT record.\nCreate a new DNS resolver with sensible cross-platform …\nResolve a hostname from a URL to an IP address.\nReturns the raw character strings of this TXT record.\nCreate a new DNS resolver configured with a single UDP DNS …\nThe HTTP upgrade protocol used for relaying.\nThe HTTP path under which the relay accepts relaying …\nThe HTTP path under which the relay allows doing latency …\nRelays over the custom relaying protocol with a custom …\nRelays over websockets.\nReturns the argument unchanged.\nCalls U::from(self).\nTries to match the value of an HTTP upgrade header to …\nThe HTTP upgrade header used or expected.\nThe DNS name for the iroh TXT record.\nThe max byte length allowed for user-defined data.\nError returned when an input value is too long for UserData…\nData about a node that may be published to and resolved …\nExtension methods for NodeId to encode to and decode from …\nInformation about a node that may be published to and …\nUnder the hood this is a UTF-8 String is no longer than …\nAdds direct addresses to the node data.\nRemoves all direct addresses from the node data.\nThe information published about the node.\nReturns the direct addresses of the node.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCreates a new NodeInfo from its parts.\nParses a NodeInfo from a pkarr::SignedPacket.\nParses a NodeInfo from a TXT records lookup.\nParses a NodeId from [z-base-32] encoding.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nConverts into a NodeAddr without cloning.\nCreates a new NodeData with a relay URL and a set of …\nCreates a new NodeInfo with an empty NodeData.\nThe NodeId of the node this is about.\nReturns the relay URL of the node.\nSets the relay URL of the node data.\nSets the user-defined data of the node data.\nConverts into a NodeAddr by cloning the needed fields.\nCreates a pkarr::SignedPacket.\nConverts into a list of {key}={value} strings.\nEncodes a NodeId in [z-base-32] encoding.\nReturns the optional user-defined data of the node.\nSets the direct addresses and returns the updated node …\nSets the direct addresses and returns the updated node …\nSets the relay URL and returns the updated node data.\nSets the relay URL and returns the updated node info.\nSets the user-defined data and returns the updated node …\nSets the user-defined data and returns the updated node …\nThis module exports looks_like_disco_wrapper as the only …\nThis module implements the relaying protocol used by the …\nSTUN packets sending and receiving.\nThe 6 byte header of all discovery messages.\nReports whether p looks like it’s a packet containing an …\nmagic + 32b pub key + 24B nonce + bytes\nThe one byte frame type at the beginning of the frame …\nSent from server to client to tell the client if their …\nno payload, no-op (to be replaced with ping/pong)\nThe maximum size of a packet sent over relay. (This only …\n1 byte payload: 0x01 or 0x00 for whether this is client’…\nSent from server to client to signal that a previous …\nFrames 9-11 concern meshing, which we have eliminated from …\n8 byte payload, the contents of ping being replied to\nProtocol send errors.\nv0/1 packet bytes, v2: 32B src pub key + packet bytes\nSent from server to client for the server to declare that …\nProtocol send errors.\n32B dest pub key + packet bytes\nUnknown frame type\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nThe AlternateServeratribute\nThe ErrorCodeatribute\nerror response\nThe Fingerprintatribute\nindication\nSTUN request had bogus fingerprint.\nThe STUN message could not be parsed or is otherwise …\nSTUN response has malformed attributes.\nThe MappedAddressatribute\nThe STUN message class. Although there are four message …\nClass used to decode STUN messages\nThe MessageIntegrityatribute\nThe MessageIntegritySha256atribute\nSTUN request didn’t end in fingerprint.\nThe Nonceatribute\nSTUN request is not a binding request when it should be.\nSTUN packet is not a response when it should be.\nThe PasswordAlgorithmatribute\nThe PasswordAlgorithmsatribute\nThe Realmatribute\nrequest\nThe Softwareatribute\nSTUN Attributes that can be attached to a StunMessage\nDescribes an error decoding a StunMessage\nErrors that can occur when handling a STUN packet.\nsuccess response\nThe transaction ID is a 96-bit identifier, used to …\nThe Unknownatribute\nThe UnknownAttributesatribute\nThe UserHashatribute\nThe UserNameatribute\nThe XorMappedAddressatribute\nReturns a reference to the internal attribute value or an …\nReturns a reference to the bytes that represents the …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns a reference to the internal attribute value or an …\nReturns the STUN attribute type of this instance.\nDecodes the STUN raw buffer\nCreates a cryptographically random transaction ID chosen …\nReturns a reference to the AlternateServer attribute.\nReturns a reference to the ErrorCode attribute.\nReturns a reference to the Fingerprint attribute.\nReturns a reference to the MappedAddress attribute.\nReturns a reference to the MessageIntegrity attribute.\nReturns a reference to the MessageIntegritySha256 …\nReturns a reference to the Nonce attribute.\nReturns a reference to the PasswordAlgorithm attribute.\nReturns a reference to the PasswordAlgorithms attribute.\nReturns a reference to the Realm attribute.\nReturns a reference to the Software attribute.\nReturns a reference to the Unknown attribute.\nReturns a reference to the UnknownAttributes attribute.\nReturns a reference to the UserHash attribute.\nReturns a reference to the UserName attribute.\nReturns a reference to the XorMappedAddress attribute.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nGets the context associated to this decoder\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nReports whether b is a STUN message.\nReturns true if this StunAttribute is AlternateServer\nReturns true if this StunAttribute is ErrorCode\nReturns true if this StunAttribute is Fingerprint\nReturns true if this StunAttribute is MappedAddress\nReturns true if this StunAttribute is MessageIntegrity\nReturns true if this StunAttribute is …\nReturns true if this StunAttribute is Nonce\nReturns true if this StunAttribute is PasswordAlgorithm\nReturns true if this StunAttribute is PasswordAlgorithms\nReturns true if this StunAttribute is Realm\nReturns true if this StunAttribute is Software\nReturns true if this StunAttribute is Unknown\nReturns true if this StunAttribute is UnknownAttributes\nReturns true if this StunAttribute is UserHash\nReturns true if this StunAttribute is UserName\nReturns true if this StunAttribute is XorMappedAddress\nSTUN Methods Registry\nParses a STUN binding request.\nParses a successful binding response STUN packet. The IP …\nGenerates a binding request STUN packet.\nGenerates a binding response.\nBinding\nReserved\nShared secret\nALPN for our quic addr discovery\nQuic client related errors.\nEndpoint close error code\nEndpoint close reason\nHandles the client side of QUIC address discovery.\nReturns the argument unchanged.\nReturns the argument unchanged.\nClient side of QUIC address discovery.\nCalls U::from(self).\nCalls U::from(self).\nCreate a new QuicClient to handle the client side of QUIC …\nAccess restriction for a node.\nControls which nodes are allowed to use the relay.\nAccess is allowed.\nTLS certificate configuration.\nPer-client rate limit configuration.\nThe default certificate reload interval.\nAccess is denied.\nEveryone\nUse Let’s Encrypt.\nRate limits.\nUse a static TLS key and certificate chain.\nMetrics tracked for the relay server\nConfiguration for the QUIC server.\nConfiguration for the Relay HTTP and HTTPS server.\nAll metrics tracked in the relay server.\nUse a TLS key and certificate chain that can be reloaded.\nA Certificate resolver that reloads the certificate every …\nOnly nodes for which the function returns Access::Allow.\nA running Relay + STUN server.\nConfiguration for the full Relay & STUN server.\nServer spawn errors\nConfiguration for the STUN server.\nMetrics tracked for the STUN server.\nServer task errors\nTLS configuration for Relay server.\nBurst limit for accepting new connection. Unlimited if not …\nRate limit for accepting new connection. Unlimited if not …\nNumber of times this server has accepted a connection.\nAccess configuration.\nNumber of bad requests made to the STUN endpoint.\nThe socket address on which the STUN server should bind.\nThe socket address on which the QUIC server should bind.\nMax number of bytes per second to read from the client …\nBytes received from a FrameType::SendPacket\nBytes sent from a FrameType::SendPacket\nMode for getting a cert.\nThe certificates chain if configured with manual TLS …\nRate limits for incoming traffic from a client connection.\nNumber of client connections which have had any frames …\nFrameType::SendPacket dropped that are disco messages\nFrameType::SendPacket received that are disco messages\nFrameType::SendPacket sent that are disco messages\nNumber of connections we have removed because of an error\nNumber of STUN requests that end in failure.\nNumber of frames received from client connection which …\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nReturns the argument unchanged.\nNumber of FrameType::Pings received\nThe socket address the HTTP server is listening on.\nThe socket address on which the Relay HTTP server should …\nGet the server’s http RelayUrl.\nThe socket address the HTTPS server is listening on.\nThe socket address on which to serve the HTTPS server.\nGet the server’s https RelayUrl.\nPerform the initial load and construct the …\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nCalls U::from(self).\nNumber of successful ipv4 STUN requests served.\nNumber of successful ipv6 STUN requests served.\nIs this node allowed?\nKey cache capacity.\nRate limits.\nMax number of bytes to read in a single burst.\nReturns the metrics collected in the relay server.\nSocket to serve metrics on.\nPackets of other FrameTypes dropped\nPackets of other FrameTypes received\nPackets of other FrameTypes sent\nConfiguration for the QUIC server, disabled if None.\nThe socket address the QUIC server is listening on.\nThe socket address on which to server the QUIC server is …\nConfiguration for the Relay server, disabled if None.\nNumber of accepted ‘iroh derp http’ connection upgrades\nReload the certificate.\nNumber of STUN requests made to the server.\nFrameType::SendPacket dropped, that are not disco messages\nFrameType::SendPacket received, that are not disco messages\nFrameType::SendPacket sent, that are not disco messages\nNumber of FrameType::Pongs sent\nMetrics tracked for the relay server.\nThe TLS server configuration for the QUIC server.\nThe server configuration.\nShutdown the resolver.\nRequests graceful shutdown.\nStarts the server.\nMetrics tracked for the STUN server.\nConfiguration for the STUN server, disabled if None.\nThe socket address the STUN server is listening on.\nReturns the handle for the task.\nExposes functions to quickly configure a server suitable …\nTLS configuration for the HTTPS server.\nNumber of unique client keys per day\nNumber of FrameType::Unknown received\nNumber of accepted websocket connections\nThe TLS certificate chain.\nState for Let’s Encrypt certificates.\nCreates a QuicConfig suitable for testing.\nCreates a RelayConfig suitable for testing.\nCreates a rustls::ServerConfig and certificates suitable …\nCreates a ServerConfig suitable for testing.\nCreates a StunConfig suitable for testing.\nCreates a TlsConfig suitable for testing.") \ No newline at end of file diff --git a/pr/3327/docs/src-files.js b/pr/3327/docs/src-files.js index f637aa97a9..cb65f63e3e 100644 --- a/pr/3327/docs/src-files.js +++ b/pr/3327/docs/src-files.js @@ -1,3 +1,3 @@ -var srcIndex = new Map(JSON.parse('[["bulk",["",[],["bulk.rs"]]],["iroh",["",[["discovery",[["pkarr",[],["dht.rs"]]],["dns.rs","mdns.rs","pkarr.rs","static_provider.rs"]],["endpoint",[],["rtt_actor.rs"]],["magicsock",[["node_map",[],["best_addr.rs","node_state.rs","path_state.rs","udp_paths.rs"]]],["metrics.rs","node_map.rs","relay_actor.rs","udp_conn.rs"]],["net_report",[["reportgen",[],["hairpin.rs","probes.rs"]]],["defaults.rs","dns.rs","ip_mapped_addrs.rs","metrics.rs","options.rs","ping.rs","reportgen.rs"]],["tls",[],["name.rs","resolver.rs","verifier.rs"]]],["defaults.rs","disco.rs","discovery.rs","dns.rs","endpoint.rs","key.rs","lib.rs","magicsock.rs","metrics.rs","net_report.rs","protocol.rs","test_utils.rs","tls.rs","util.rs","watcher.rs"]]],["iroh_base",["",[["ticket",[],["node.rs"]]],["key.rs","lib.rs","node_addr.rs","relay_url.rs","ticket.rs"]]],["iroh_bench",["",[],["iroh.rs","lib.rs","quinn.rs","s2n.rs","stats.rs"]]],["iroh_dns_server",["",[["dns",[],["node_authority.rs"]],["http",[["doh",[],["extract.rs","response.rs"]]],["doh.rs","error.rs","pkarr.rs","rate_limiting.rs","tls.rs"]],["store",[],["signed_packets.rs"]]],["config.rs","dns.rs","http.rs","lib.rs","metrics.rs","server.rs","state.rs","store.rs","util.rs"]]],["iroh_relay",["",[["client",[],["conn.rs","streams.rs","tls.rs","util.rs"]],["protos",[],["disco.rs","relay.rs","stun.rs"]],["server",[],["client.rs","clients.rs","http_server.rs","metrics.rs","resolver.rs","streams.rs","testing.rs"]]],["client.rs","defaults.rs","dns.rs","http.rs","key_cache.rs","lib.rs","node_info.rs","ping_tracker.rs","protos.rs","quic.rs","relay_map.rs","server.rs"]]]]')); +var srcIndex = new Map(JSON.parse('[["bulk",["",[],["bulk.rs"]]],["iroh",["",[["discovery",[["pkarr",[],["dht.rs"]]],["dns.rs","mdns.rs","pkarr.rs","static_provider.rs"]],["endpoint",[],["rtt_actor.rs"]],["magicsock",[["node_map",[],["best_addr.rs","node_state.rs","path_state.rs","udp_paths.rs"]],["transports",[["relay",[],["actor.rs"]]],["ip.rs","relay.rs"]]],["metrics.rs","node_map.rs","transports.rs"]],["net_report",[["reportgen",[],["hairpin.rs","probes.rs"]]],["defaults.rs","dns.rs","ip_mapped_addrs.rs","metrics.rs","options.rs","ping.rs","reportgen.rs"]],["tls",[],["name.rs","resolver.rs","verifier.rs"]]],["defaults.rs","disco.rs","discovery.rs","dns.rs","endpoint.rs","key.rs","lib.rs","magicsock.rs","metrics.rs","net_report.rs","protocol.rs","test_utils.rs","tls.rs","util.rs"]]],["iroh_base",["",[["ticket",[],["node.rs"]]],["key.rs","lib.rs","node_addr.rs","relay_url.rs","ticket.rs"]]],["iroh_bench",["",[],["iroh.rs","lib.rs","quinn.rs","s2n.rs","stats.rs"]]],["iroh_dns_server",["",[["dns",[],["node_authority.rs"]],["http",[["doh",[],["extract.rs","response.rs"]]],["doh.rs","error.rs","pkarr.rs","rate_limiting.rs","tls.rs"]],["store",[],["signed_packets.rs"]]],["config.rs","dns.rs","http.rs","lib.rs","metrics.rs","server.rs","state.rs","store.rs","util.rs"]]],["iroh_relay",["",[["client",[],["conn.rs","streams.rs","tls.rs","util.rs"]],["protos",[],["disco.rs","relay.rs","stun.rs"]],["server",[],["client.rs","clients.rs","http_server.rs","metrics.rs","resolver.rs","streams.rs","testing.rs"]]],["client.rs","defaults.rs","dns.rs","http.rs","key_cache.rs","lib.rs","node_info.rs","ping_tracker.rs","protos.rs","quic.rs","relay_map.rs","server.rs"]]]]')); createSrcSidebar(); -//{"start":36,"fragment_lengths":[28,696,109,75,306,392]} \ No newline at end of file +//{"start":36,"fragment_lengths":[28,732,109,75,306,392]} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/disco.rs.html b/pr/3327/docs/src/iroh/disco.rs.html index bf5ce9a43c..31db6d9591 100644 --- a/pr/3327/docs/src/iroh/disco.rs.html +++ b/pr/3327/docs/src/iroh/disco.rs.html @@ -30,498 +30,509 @@ 30use snafu::{ensure, Snafu}; 31use url::Url; 32 -33// TODO: custom magicn -34/// The 6 byte header of all discovery messages. -35pub const MAGIC: &str = "TS💬"; // 6 bytes: 0x54 53 f0 9f 92 ac -36pub const MAGIC_LEN: usize = MAGIC.len(); -37 -38/// Current Version. -39const V0: u8 = 0; -40 -41pub(crate) const KEY_LEN: usize = 32; -42const TX_LEN: usize = 12; -43 -44// Sizes for the inner message structure. +33use crate::magicsock::transports; +34 +35// TODO: custom magicn +36/// The 6 byte header of all discovery messages. +37pub const MAGIC: &str = "TS💬"; // 6 bytes: 0x54 53 f0 9f 92 ac +38pub const MAGIC_LEN: usize = MAGIC.len(); +39 +40/// Current Version. +41const V0: u8 = 0; +42 +43pub(crate) const KEY_LEN: usize = 32; +44const TX_LEN: usize = 12; 45 -46/// Header: Type | Version -47const HEADER_LEN: usize = 2; -48 -49const PING_LEN: usize = TX_LEN + iroh_base::PublicKey::LENGTH; -50const EP_LENGTH: usize = 16 + 2; // 16 byte IP address + 2 byte port -51 -52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -53#[repr(u8)] -54pub enum MessageType { -55 Ping = 0x01, -56 Pong = 0x02, -57 CallMeMaybe = 0x03, -58} -59 -60impl TryFrom<u8> for MessageType { -61 type Error = u8; -62 -63 fn try_from(value: u8) -> std::result::Result<Self, Self::Error> { -64 match value { -65 0x01 => Ok(MessageType::Ping), -66 0x02 => Ok(MessageType::Pong), -67 0x03 => Ok(MessageType::CallMeMaybe), -68 _ => Err(value), -69 } -70 } -71} -72 -73const MESSAGE_HEADER_LEN: usize = MAGIC_LEN + KEY_LEN; +46// Sizes for the inner message structure. +47 +48/// Header: Type | Version +49const HEADER_LEN: usize = 2; +50 +51const PING_LEN: usize = TX_LEN + iroh_base::PublicKey::LENGTH; +52const EP_LENGTH: usize = 16 + 2; // 16 byte IP address + 2 byte port +53 +54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +55#[repr(u8)] +56pub enum MessageType { +57 Ping = 0x01, +58 Pong = 0x02, +59 CallMeMaybe = 0x03, +60} +61 +62impl TryFrom<u8> for MessageType { +63 type Error = u8; +64 +65 fn try_from(value: u8) -> std::result::Result<Self, Self::Error> { +66 match value { +67 0x01 => Ok(MessageType::Ping), +68 0x02 => Ok(MessageType::Pong), +69 0x03 => Ok(MessageType::CallMeMaybe), +70 _ => Err(value), +71 } +72 } +73} 74 -75pub fn encode_message(sender: &PublicKey, seal: Vec<u8>) -> Vec<u8> { -76 let mut out = Vec::with_capacity(MESSAGE_HEADER_LEN); -77 out.extend_from_slice(MAGIC.as_bytes()); -78 out.extend_from_slice(sender.as_bytes()); -79 out.extend(seal); -80 -81 out -82} -83 -84/// Reports whether p looks like it's a packet containing an encrypted disco message. -85pub fn looks_like_disco_wrapper(p: &[u8]) -> bool { -86 if p.len() < MESSAGE_HEADER_LEN { -87 return false; -88 } -89 -90 &p[..MAGIC_LEN] == MAGIC.as_bytes() -91} -92 -93/// If `p` looks like a disco message it returns the slice of `p` that represents the disco public key source, -94/// and the part that is the box. -95pub fn source_and_box(p: &[u8]) -> Option<(PublicKey, &[u8])> { -96 if !looks_like_disco_wrapper(p) { -97 return None; -98 } -99 -100 let source = &p[MAGIC_LEN..MAGIC_LEN + KEY_LEN]; -101 let sender = PublicKey::try_from(source).ok()?; -102 let sealed_box = &p[MAGIC_LEN + KEY_LEN..]; -103 Some((sender, sealed_box)) -104} -105 -106/// A discovery message. -107#[derive(Debug, Clone, PartialEq, Eq)] -108pub enum Message { -109 Ping(Ping), -110 Pong(Pong), -111 CallMeMaybe(CallMeMaybe), -112} -113 -114#[derive(Debug, Clone, PartialEq, Eq)] -115pub struct Ping { -116 /// Random client-generated per-ping transaction ID. -117 pub tx_id: stun_rs::TransactionId, -118 -119 /// Allegedly the ping sender's wireguard public key. -120 /// It shouldn't be trusted by itself, but can be combined with -121 /// netmap data to reduce the discokey:nodekey relation from 1:N to 1:1. -122 pub node_key: PublicKey, -123} -124 -125/// A response a Ping. -126/// -127/// It includes the sender's source IP + port, so it's effectively a STUN response. -128#[derive(Debug, Clone, PartialEq, Eq)] -129pub struct Pong { -130 pub tx_id: stun_rs::TransactionId, -131 /// The observed address off the ping sender. -132 /// -133 /// 18 bytes (16+2) on the wire; v4-mapped ipv6 for IPv4. -134 pub ping_observed_addr: SendAddr, -135} -136 -137/// Addresses to which we can send. This is either a UDP or a relay address. -138#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] -139pub enum SendAddr { -140 /// UDP, the ip addr. -141 Udp(SocketAddr), -142 /// Relay Url. -143 Relay(RelayUrl), -144} -145 -146impl SendAddr { -147 /// Returns if this is a `relay` addr. -148 pub fn is_relay(&self) -> bool { -149 matches!(self, Self::Relay(_)) -150 } -151 -152 /// Returns the `Some(Url)` if it is a relay addr. -153 pub fn relay_url(&self) -> Option<RelayUrl> { -154 match self { -155 Self::Relay(url) => Some(url.clone()), -156 Self::Udp(_) => None, -157 } -158 } -159} -160 -161impl From<SocketAddr> for SendAddr { -162 fn from(source: SocketAddr) -> Self { -163 SendAddr::Udp(source) -164 } -165} -166 -167impl From<RelayUrl> for SendAddr { -168 fn from(source: RelayUrl) -> Self { -169 SendAddr::Relay(source) -170 } -171} -172 -173impl PartialEq<SocketAddr> for SendAddr { -174 fn eq(&self, other: &SocketAddr) -> bool { -175 match self { -176 Self::Relay(_) => false, -177 Self::Udp(addr) => addr.eq(other), -178 } -179 } -180} -181 -182impl Display for SendAddr { -183 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { -184 match self { -185 SendAddr::Relay(id) => write!(f, "Relay({})", id), -186 SendAddr::Udp(addr) => write!(f, "UDP({})", addr), -187 } -188 } -189} -190 -191/// Message sent only over the relay to request that the recipient try -192/// to open up a magicsock path back to the sender. -193/// -194/// The sender should've already sent UDP packets to the peer to open -195/// up the stateful firewall mappings inbound. -196/// -197/// The recipient may choose to not open a path back, if it's already happy with its path. -198/// But usually it will. -199#[derive(Debug, Clone, PartialEq, Eq)] -200pub struct CallMeMaybe { -201 /// What the peer believes its endpoints are. -202 pub my_numbers: Vec<SocketAddr>, -203} -204 -205impl Ping { -206 fn from_bytes(p: &[u8]) -> Result<Self, ParseError> { -207 // Deliberately lax on longer-than-expected messages, for future compatibility. -208 ensure!(p.len() >= PING_LEN, TooShortSnafu); -209 let tx_id: [u8; TX_LEN] = p[..TX_LEN].try_into().expect("length checked"); -210 let raw_key = &p[TX_LEN..TX_LEN + iroh_base::PublicKey::LENGTH]; -211 let node_key = PublicKey::try_from(raw_key).map_err(|_| InvalidEncodingSnafu.build())?; -212 let tx_id = stun_rs::TransactionId::from(tx_id); -213 -214 Ok(Ping { tx_id, node_key }) -215 } -216 -217 fn as_bytes(&self) -> Vec<u8> { -218 let header = msg_header(MessageType::Ping, V0); -219 let mut out = vec![0u8; PING_LEN + HEADER_LEN]; -220 -221 out[..HEADER_LEN].copy_from_slice(&header); -222 out[HEADER_LEN..HEADER_LEN + TX_LEN].copy_from_slice(&self.tx_id); -223 out[HEADER_LEN + TX_LEN..].copy_from_slice(self.node_key.as_ref()); +75const MESSAGE_HEADER_LEN: usize = MAGIC_LEN + KEY_LEN; +76 +77pub fn encode_message(sender: &PublicKey, seal: Vec<u8>) -> Vec<u8> { +78 let mut out = Vec::with_capacity(MESSAGE_HEADER_LEN); +79 out.extend_from_slice(MAGIC.as_bytes()); +80 out.extend_from_slice(sender.as_bytes()); +81 out.extend(seal); +82 +83 out +84} +85 +86/// Reports whether p looks like it's a packet containing an encrypted disco message. +87pub fn looks_like_disco_wrapper(p: &[u8]) -> bool { +88 if p.len() < MESSAGE_HEADER_LEN { +89 return false; +90 } +91 +92 &p[..MAGIC_LEN] == MAGIC.as_bytes() +93} +94 +95/// If `p` looks like a disco message it returns the slice of `p` that represents the disco public key source, +96/// and the part that is the box. +97pub fn source_and_box(p: &[u8]) -> Option<(PublicKey, &[u8])> { +98 if !looks_like_disco_wrapper(p) { +99 return None; +100 } +101 +102 let source = &p[MAGIC_LEN..MAGIC_LEN + KEY_LEN]; +103 let sender = PublicKey::try_from(source).ok()?; +104 let sealed_box = &p[MAGIC_LEN + KEY_LEN..]; +105 Some((sender, sealed_box)) +106} +107 +108/// A discovery message. +109#[derive(Debug, Clone, PartialEq, Eq)] +110pub enum Message { +111 Ping(Ping), +112 Pong(Pong), +113 CallMeMaybe(CallMeMaybe), +114} +115 +116#[derive(Debug, Clone, PartialEq, Eq)] +117pub struct Ping { +118 /// Random client-generated per-ping transaction ID. +119 pub tx_id: stun_rs::TransactionId, +120 +121 /// Allegedly the ping sender's wireguard public key. +122 /// It shouldn't be trusted by itself, but can be combined with +123 /// netmap data to reduce the discokey:nodekey relation from 1:N to 1:1. +124 pub node_key: PublicKey, +125} +126 +127/// A response a Ping. +128/// +129/// It includes the sender's source IP + port, so it's effectively a STUN response. +130#[derive(Debug, Clone, PartialEq, Eq)] +131pub struct Pong { +132 pub tx_id: stun_rs::TransactionId, +133 /// The observed address off the ping sender. +134 /// +135 /// 18 bytes (16+2) on the wire; v4-mapped ipv6 for IPv4. +136 pub ping_observed_addr: SendAddr, +137} +138 +139/// Addresses to which we can send. This is either a UDP or a relay address. +140#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +141pub enum SendAddr { +142 /// UDP, the ip addr. +143 Udp(SocketAddr), +144 /// Relay Url. +145 Relay(RelayUrl), +146} +147 +148impl SendAddr { +149 /// Returns if this is a `relay` addr. +150 pub fn is_relay(&self) -> bool { +151 matches!(self, Self::Relay(_)) +152 } +153 +154 /// Returns the `Some(Url)` if it is a relay addr. +155 pub fn relay_url(&self) -> Option<RelayUrl> { +156 match self { +157 Self::Relay(url) => Some(url.clone()), +158 Self::Udp(_) => None, +159 } +160 } +161} +162 +163impl From<transports::Addr> for SendAddr { +164 fn from(addr: transports::Addr) -> Self { +165 match addr { +166 transports::Addr::Ip(addr) => SendAddr::Udp(addr), +167 transports::Addr::Relay(url, _) => SendAddr::Relay(url), +168 } +169 } +170} +171 +172impl From<SocketAddr> for SendAddr { +173 fn from(source: SocketAddr) -> Self { +174 SendAddr::Udp(source) +175 } +176} +177 +178impl From<RelayUrl> for SendAddr { +179 fn from(source: RelayUrl) -> Self { +180 SendAddr::Relay(source) +181 } +182} +183 +184impl PartialEq<SocketAddr> for SendAddr { +185 fn eq(&self, other: &SocketAddr) -> bool { +186 match self { +187 Self::Relay(_) => false, +188 Self::Udp(addr) => addr.eq(other), +189 } +190 } +191} +192 +193impl Display for SendAddr { +194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +195 match self { +196 SendAddr::Relay(id) => write!(f, "Relay({})", id), +197 SendAddr::Udp(addr) => write!(f, "UDP({})", addr), +198 } +199 } +200} +201 +202/// Message sent only over the relay to request that the recipient try +203/// to open up a magicsock path back to the sender. +204/// +205/// The sender should've already sent UDP packets to the peer to open +206/// up the stateful firewall mappings inbound. +207/// +208/// The recipient may choose to not open a path back, if it's already happy with its path. +209/// But usually it will. +210#[derive(Debug, Clone, PartialEq, Eq)] +211pub struct CallMeMaybe { +212 /// What the peer believes its endpoints are. +213 pub my_numbers: Vec<SocketAddr>, +214} +215 +216impl Ping { +217 fn from_bytes(p: &[u8]) -> Result<Self, ParseError> { +218 // Deliberately lax on longer-than-expected messages, for future compatibility. +219 ensure!(p.len() >= PING_LEN, TooShortSnafu); +220 let tx_id: [u8; TX_LEN] = p[..TX_LEN].try_into().expect("length checked"); +221 let raw_key = &p[TX_LEN..TX_LEN + iroh_base::PublicKey::LENGTH]; +222 let node_key = PublicKey::try_from(raw_key).map_err(|_| InvalidEncodingSnafu.build())?; +223 let tx_id = stun_rs::TransactionId::from(tx_id); 224 -225 out +225 Ok(Ping { tx_id, node_key }) 226 } -227} -228 -229#[allow(missing_docs)] -230#[common_fields({ -231 backtrace: Option<snafu::Backtrace>, -232 #[snafu(implicit)] -233 span_trace: n0_snafu::SpanTrace, -234})] -235#[derive(Debug, Snafu)] -236#[non_exhaustive] -237pub enum ParseError { -238 #[snafu(display("message is too short"))] -239 TooShort {}, -240 #[snafu(display("invalid encoding"))] -241 InvalidEncoding {}, -242 #[snafu(display("unknown format"))] -243 UnknownFormat {}, -244} -245 -246fn send_addr_from_bytes(p: &[u8]) -> Result<SendAddr, ParseError> { -247 ensure!(p.len() > 2, TooShortSnafu); -248 match p[0] { -249 0u8 => { -250 let bytes: [u8; EP_LENGTH] = p[1..].try_into().map_err(|_| TooShortSnafu.build())?; -251 let addr = socket_addr_from_bytes(bytes); -252 Ok(SendAddr::Udp(addr)) -253 } -254 1u8 => { -255 let s = std::str::from_utf8(&p[1..]).map_err(|_| InvalidEncodingSnafu.build())?; -256 let u: Url = s.parse().map_err(|_| InvalidEncodingSnafu.build())?; -257 Ok(SendAddr::Relay(u.into())) -258 } -259 _ => Err(UnknownFormatSnafu.build()), -260 } -261} -262 -263fn send_addr_to_vec(addr: &SendAddr) -> Vec<u8> { -264 match addr { -265 SendAddr::Relay(url) => { -266 let mut out = vec![1u8]; -267 out.extend_from_slice(url.to_string().as_bytes()); -268 out +227 +228 fn as_bytes(&self) -> Vec<u8> { +229 let header = msg_header(MessageType::Ping, V0); +230 let mut out = vec![0u8; PING_LEN + HEADER_LEN]; +231 +232 out[..HEADER_LEN].copy_from_slice(&header); +233 out[HEADER_LEN..HEADER_LEN + TX_LEN].copy_from_slice(&self.tx_id); +234 out[HEADER_LEN + TX_LEN..].copy_from_slice(self.node_key.as_ref()); +235 +236 out +237 } +238} +239 +240#[allow(missing_docs)] +241#[common_fields({ +242 backtrace: Option<snafu::Backtrace>, +243 #[snafu(implicit)] +244 span_trace: n0_snafu::SpanTrace, +245})] +246#[derive(Debug, Snafu)] +247#[non_exhaustive] +248pub enum ParseError { +249 #[snafu(display("message is too short"))] +250 TooShort {}, +251 #[snafu(display("invalid encoding"))] +252 InvalidEncoding {}, +253 #[snafu(display("unknown format"))] +254 UnknownFormat {}, +255} +256 +257fn send_addr_from_bytes(p: &[u8]) -> Result<SendAddr, ParseError> { +258 ensure!(p.len() > 2, TooShortSnafu); +259 match p[0] { +260 0u8 => { +261 let bytes: [u8; EP_LENGTH] = p[1..].try_into().map_err(|_| TooShortSnafu.build())?; +262 let addr = socket_addr_from_bytes(bytes); +263 Ok(SendAddr::Udp(addr)) +264 } +265 1u8 => { +266 let s = std::str::from_utf8(&p[1..]).map_err(|_| InvalidEncodingSnafu.build())?; +267 let u: Url = s.parse().map_err(|_| InvalidEncodingSnafu.build())?; +268 Ok(SendAddr::Relay(u.into())) 269 } -270 SendAddr::Udp(ip) => { -271 let mut out = vec![0u8]; -272 out.extend_from_slice(&socket_addr_as_bytes(ip)); -273 out -274 } -275 } -276} -277 -278// Assumes p.len() == EP_LENGTH -279fn socket_addr_from_bytes(p: [u8; EP_LENGTH]) -> SocketAddr { -280 debug_assert_eq!(EP_LENGTH, 16 + 2); -281 -282 let raw_src_ip: [u8; 16] = p[..16].try_into().expect("array long enough"); -283 let raw_port: [u8; 2] = p[16..].try_into().expect("array long enough"); -284 -285 let src_ip = IpAddr::from(raw_src_ip).to_canonical(); -286 let src_port = u16::from_le_bytes(raw_port); -287 -288 SocketAddr::new(src_ip, src_port) -289} -290 -291fn socket_addr_as_bytes(addr: &SocketAddr) -> [u8; EP_LENGTH] { -292 let mut out = [0u8; EP_LENGTH]; -293 let ipv6 = match addr.ip() { -294 IpAddr::V4(v4) => v4.to_ipv6_mapped(), -295 IpAddr::V6(v6) => v6, -296 }; -297 out[..16].copy_from_slice(&ipv6.octets()); -298 out[16..].copy_from_slice(&addr.port().to_le_bytes()); -299 -300 out -301} -302 -303impl Pong { -304 fn from_bytes(p: &[u8]) -> Result<Self, ParseError> { -305 let tx_id: [u8; TX_LEN] = p[..TX_LEN].try_into().map_err(|_| TooShortSnafu.build())?; -306 -307 let tx_id = stun_rs::TransactionId::from(tx_id); -308 let src = send_addr_from_bytes(&p[TX_LEN..])?; -309 -310 Ok(Pong { -311 tx_id, -312 ping_observed_addr: src, -313 }) -314 } -315 -316 fn as_bytes(&self) -> Vec<u8> { -317 let header = msg_header(MessageType::Pong, V0); -318 let mut out = header.to_vec(); -319 out.extend_from_slice(&self.tx_id); +270 _ => Err(UnknownFormatSnafu.build()), +271 } +272} +273 +274fn send_addr_to_vec(addr: &SendAddr) -> Vec<u8> { +275 match addr { +276 SendAddr::Relay(url) => { +277 let mut out = vec![1u8]; +278 out.extend_from_slice(url.to_string().as_bytes()); +279 out +280 } +281 SendAddr::Udp(ip) => { +282 let mut out = vec![0u8]; +283 out.extend_from_slice(&socket_addr_as_bytes(ip)); +284 out +285 } +286 } +287} +288 +289// Assumes p.len() == EP_LENGTH +290fn socket_addr_from_bytes(p: [u8; EP_LENGTH]) -> SocketAddr { +291 debug_assert_eq!(EP_LENGTH, 16 + 2); +292 +293 let raw_src_ip: [u8; 16] = p[..16].try_into().expect("array long enough"); +294 let raw_port: [u8; 2] = p[16..].try_into().expect("array long enough"); +295 +296 let src_ip = IpAddr::from(raw_src_ip).to_canonical(); +297 let src_port = u16::from_le_bytes(raw_port); +298 +299 SocketAddr::new(src_ip, src_port) +300} +301 +302fn socket_addr_as_bytes(addr: &SocketAddr) -> [u8; EP_LENGTH] { +303 let mut out = [0u8; EP_LENGTH]; +304 let ipv6 = match addr.ip() { +305 IpAddr::V4(v4) => v4.to_ipv6_mapped(), +306 IpAddr::V6(v6) => v6, +307 }; +308 out[..16].copy_from_slice(&ipv6.octets()); +309 out[16..].copy_from_slice(&addr.port().to_le_bytes()); +310 +311 out +312} +313 +314impl Pong { +315 fn from_bytes(p: &[u8]) -> Result<Self, ParseError> { +316 let tx_id: [u8; TX_LEN] = p[..TX_LEN].try_into().map_err(|_| TooShortSnafu.build())?; +317 +318 let tx_id = stun_rs::TransactionId::from(tx_id); +319 let src = send_addr_from_bytes(&p[TX_LEN..])?; 320 -321 let src_bytes = send_addr_to_vec(&self.ping_observed_addr); -322 out.extend(src_bytes); -323 out -324 } -325} +321 Ok(Pong { +322 tx_id, +323 ping_observed_addr: src, +324 }) +325 } 326 -327impl CallMeMaybe { -328 fn from_bytes(p: &[u8]) -> Result<Self, ParseError> { -329 ensure!(p.len() % EP_LENGTH == 0, InvalidEncodingSnafu); -330 -331 let num_entries = p.len() / EP_LENGTH; -332 let mut m = CallMeMaybe { -333 my_numbers: Vec::with_capacity(num_entries), -334 }; -335 -336 for chunk in p.chunks_exact(EP_LENGTH) { -337 let bytes: [u8; EP_LENGTH] = -338 chunk.try_into().map_err(|_| InvalidEncodingSnafu.build())?; -339 let src = socket_addr_from_bytes(bytes); -340 m.my_numbers.push(src); -341 } -342 -343 Ok(m) -344 } -345 -346 fn as_bytes(&self) -> Vec<u8> { -347 let header = msg_header(MessageType::CallMeMaybe, V0); -348 let mut out = vec![0u8; HEADER_LEN + self.my_numbers.len() * EP_LENGTH]; -349 out[..HEADER_LEN].copy_from_slice(&header); -350 -351 for (m, chunk) in self -352 .my_numbers -353 .iter() -354 .zip(out[HEADER_LEN..].chunks_exact_mut(EP_LENGTH)) -355 { -356 let raw = socket_addr_as_bytes(m); -357 chunk.copy_from_slice(&raw); -358 } -359 -360 out -361 } -362} -363 -364impl Message { -365 /// Parses the encrypted part of the message from inside the nacl secretbox. -366 pub fn from_bytes(p: &[u8]) -> Result<Self, ParseError> { -367 ensure!(p.len() >= 2, TooShortSnafu); -368 -369 let t = MessageType::try_from(p[0]).map_err(|_| UnknownFormatSnafu.build())?; -370 let version = p[1]; -371 ensure!(version == V0, UnknownFormatSnafu); -372 -373 let p = &p[2..]; -374 match t { -375 MessageType::Ping => { -376 let ping = Ping::from_bytes(p)?; -377 Ok(Message::Ping(ping)) -378 } -379 MessageType::Pong => { -380 let pong = Pong::from_bytes(p)?; -381 Ok(Message::Pong(pong)) -382 } -383 MessageType::CallMeMaybe => { -384 let cm = CallMeMaybe::from_bytes(p)?; -385 Ok(Message::CallMeMaybe(cm)) -386 } -387 } -388 } -389 -390 /// Serialize this message to bytes. -391 pub fn as_bytes(&self) -> Vec<u8> { -392 match self { -393 Message::Ping(ping) => ping.as_bytes(), -394 Message::Pong(pong) => pong.as_bytes(), -395 Message::CallMeMaybe(cm) => cm.as_bytes(), -396 } -397 } -398} -399 -400impl Display for Message { -401 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { -402 match self { -403 Message::Ping(ping) => { -404 write!(f, "Ping(tx={})", HEXLOWER.encode(&ping.tx_id)) -405 } -406 Message::Pong(pong) => { -407 write!(f, "Pong(tx={})", HEXLOWER.encode(&pong.tx_id)) -408 } -409 Message::CallMeMaybe(_) => { -410 write!(f, "CallMeMaybe") -411 } -412 } -413 } -414} -415 -416const fn msg_header(t: MessageType, ver: u8) -> [u8; HEADER_LEN] { -417 [t as u8, ver] -418} -419 -420#[cfg(test)] -421mod tests { -422 use iroh_base::SecretKey; -423 -424 use super::*; -425 use crate::key::{public_ed_box, secret_ed_box, SharedSecret}; +327 fn as_bytes(&self) -> Vec<u8> { +328 let header = msg_header(MessageType::Pong, V0); +329 let mut out = header.to_vec(); +330 out.extend_from_slice(&self.tx_id); +331 +332 let src_bytes = send_addr_to_vec(&self.ping_observed_addr); +333 out.extend(src_bytes); +334 out +335 } +336} +337 +338impl CallMeMaybe { +339 fn from_bytes(p: &[u8]) -> Result<Self, ParseError> { +340 ensure!(p.len() % EP_LENGTH == 0, InvalidEncodingSnafu); +341 +342 let num_entries = p.len() / EP_LENGTH; +343 let mut m = CallMeMaybe { +344 my_numbers: Vec::with_capacity(num_entries), +345 }; +346 +347 for chunk in p.chunks_exact(EP_LENGTH) { +348 let bytes: [u8; EP_LENGTH] = +349 chunk.try_into().map_err(|_| InvalidEncodingSnafu.build())?; +350 let src = socket_addr_from_bytes(bytes); +351 m.my_numbers.push(src); +352 } +353 +354 Ok(m) +355 } +356 +357 fn as_bytes(&self) -> Vec<u8> { +358 let header = msg_header(MessageType::CallMeMaybe, V0); +359 let mut out = vec![0u8; HEADER_LEN + self.my_numbers.len() * EP_LENGTH]; +360 out[..HEADER_LEN].copy_from_slice(&header); +361 +362 for (m, chunk) in self +363 .my_numbers +364 .iter() +365 .zip(out[HEADER_LEN..].chunks_exact_mut(EP_LENGTH)) +366 { +367 let raw = socket_addr_as_bytes(m); +368 chunk.copy_from_slice(&raw); +369 } +370 +371 out +372 } +373} +374 +375impl Message { +376 /// Parses the encrypted part of the message from inside the nacl secretbox. +377 pub fn from_bytes(p: &[u8]) -> Result<Self, ParseError> { +378 ensure!(p.len() >= 2, TooShortSnafu); +379 +380 let t = MessageType::try_from(p[0]).map_err(|_| UnknownFormatSnafu.build())?; +381 let version = p[1]; +382 ensure!(version == V0, UnknownFormatSnafu); +383 +384 let p = &p[2..]; +385 match t { +386 MessageType::Ping => { +387 let ping = Ping::from_bytes(p)?; +388 Ok(Message::Ping(ping)) +389 } +390 MessageType::Pong => { +391 let pong = Pong::from_bytes(p)?; +392 Ok(Message::Pong(pong)) +393 } +394 MessageType::CallMeMaybe => { +395 let cm = CallMeMaybe::from_bytes(p)?; +396 Ok(Message::CallMeMaybe(cm)) +397 } +398 } +399 } +400 +401 /// Serialize this message to bytes. +402 pub fn as_bytes(&self) -> Vec<u8> { +403 match self { +404 Message::Ping(ping) => ping.as_bytes(), +405 Message::Pong(pong) => pong.as_bytes(), +406 Message::CallMeMaybe(cm) => cm.as_bytes(), +407 } +408 } +409} +410 +411impl Display for Message { +412 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +413 match self { +414 Message::Ping(ping) => { +415 write!(f, "Ping(tx={})", HEXLOWER.encode(&ping.tx_id)) +416 } +417 Message::Pong(pong) => { +418 write!(f, "Pong(tx={})", HEXLOWER.encode(&pong.tx_id)) +419 } +420 Message::CallMeMaybe(_) => { +421 write!(f, "CallMeMaybe") +422 } +423 } +424 } +425} 426 -427 #[test] -428 fn test_to_from_bytes() { -429 struct Test { -430 name: &'static str, -431 m: Message, -432 want: &'static str, -433 } -434 let tests = [ -435 Test { -436 name: "ping_with_nodekey_src", -437 m: Message::Ping(Ping { -438 tx_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].into(), -439 node_key: PublicKey::try_from(&[ -440 190, 243, 65, 104, 37, 102, 175, 75, 243, 22, 69, 200, 167, 107, 24, 63, 216, 140, 120, 43, 4, 112, 16, 62, 117, 155, 45, 215, 72, 175, 40, 189][..]).unwrap(), -441 }), -442 want: "01 00 01 02 03 04 05 06 07 08 09 0a 0b 0c be f3 41 68 25 66 af 4b f3 16 45 c8 a7 6b 18 3f d8 8c 78 2b 04 70 10 3e 75 9b 2d d7 48 af 28 bd", -443 }, -444 Test { -445 name: "pong", -446 m: Message::Pong(Pong{ -447 tx_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].into(), -448 ping_observed_addr: SendAddr::Udp("2.3.4.5:1234".parse().unwrap()), -449 }), -450 want: "02 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 00 00 00 00 00 00 00 00 00 00 00 ff ff 02 03 04 05 d2 04", -451 }, -452 Test { -453 name: "pongv6", -454 m: Message::Pong(Pong { -455 tx_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].into(), -456 ping_observed_addr: SendAddr::Udp("[fed0::12]:6666".parse().unwrap()), -457 }), -458 want: "02 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 00 fe d0 00 00 00 00 00 00 00 00 00 00 00 00 00 12 0a 1a", -459 }, -460 Test { -461 name: "call_me_maybe", -462 m: Message::CallMeMaybe(CallMeMaybe { my_numbers: Vec::new() }), -463 want: "03 00", -464 }, -465 Test { -466 name: "call_me_maybe_endpoints", -467 m: Message::CallMeMaybe(CallMeMaybe { -468 my_numbers: vec![ -469 "1.2.3.4:567".parse().unwrap(), -470 "[2001::3456]:789".parse().unwrap(), -471 ], -472 }), -473 want: "03 00 00 00 00 00 00 00 00 00 00 00 ff ff 01 02 03 04 37 02 20 01 00 00 00 00 00 00 00 00 00 00 00 00 34 56 15 03", -474 }, -475 ]; -476 for test in tests { -477 println!("{}", test.name); -478 -479 let got = test.m.as_bytes(); -480 assert_eq!( -481 got, -482 data_encoding::HEXLOWER -483 .decode(test.want.replace(' ', "").as_bytes()) -484 .unwrap(), -485 "wrong as_bytes" -486 ); -487 -488 let back = Message::from_bytes(&got).expect("failed to parse"); -489 assert_eq!(test.m, back, "wrong from_bytes"); -490 } -491 } -492 -493 #[test] -494 fn test_extraction() { -495 let sender_key = SecretKey::generate(rand::thread_rng()); -496 let recv_key = SecretKey::generate(rand::thread_rng()); -497 -498 let msg = Message::Ping(Ping { -499 tx_id: stun_rs::TransactionId::default(), -500 node_key: sender_key.public(), -501 }); -502 -503 let sender_secret = secret_ed_box(sender_key.secret()); -504 let shared = SharedSecret::new(&sender_secret, &public_ed_box(&recv_key.public().public())); -505 let mut seal = msg.as_bytes(); -506 shared.seal(&mut seal); -507 -508 let bytes = encode_message(&sender_key.public(), seal.clone()); -509 -510 assert!(looks_like_disco_wrapper(&bytes)); -511 assert_eq!(source_and_box(&bytes).unwrap().0, sender_key.public()); -512 -513 let (raw_key, seal_back) = source_and_box(&bytes).unwrap(); -514 assert_eq!(raw_key, sender_key.public()); -515 assert_eq!(seal_back, seal); -516 -517 let recv_secret = secret_ed_box(recv_key.secret()); -518 let shared_recv = -519 SharedSecret::new(&recv_secret, &public_ed_box(&sender_key.public().public())); -520 let mut open_seal = seal_back.to_vec(); -521 shared_recv -522 .open(&mut open_seal) -523 .expect("failed to open seal_back"); -524 let msg_back = Message::from_bytes(&open_seal).unwrap(); -525 assert_eq!(msg_back, msg); -526 } -527}
    \ No newline at end of file +427const fn msg_header(t: MessageType, ver: u8) -> [u8; HEADER_LEN] { +428 [t as u8, ver] +429} +430 +431#[cfg(test)] +432mod tests { +433 use iroh_base::SecretKey; +434 +435 use super::*; +436 use crate::key::{public_ed_box, secret_ed_box, SharedSecret}; +437 +438 #[test] +439 fn test_to_from_bytes() { +440 struct Test { +441 name: &'static str, +442 m: Message, +443 want: &'static str, +444 } +445 let tests = [ +446 Test { +447 name: "ping_with_nodekey_src", +448 m: Message::Ping(Ping { +449 tx_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].into(), +450 node_key: PublicKey::try_from(&[ +451 190, 243, 65, 104, 37, 102, 175, 75, 243, 22, 69, 200, 167, 107, 24, 63, 216, 140, 120, 43, 4, 112, 16, 62, 117, 155, 45, 215, 72, 175, 40, 189][..]).unwrap(), +452 }), +453 want: "01 00 01 02 03 04 05 06 07 08 09 0a 0b 0c be f3 41 68 25 66 af 4b f3 16 45 c8 a7 6b 18 3f d8 8c 78 2b 04 70 10 3e 75 9b 2d d7 48 af 28 bd", +454 }, +455 Test { +456 name: "pong", +457 m: Message::Pong(Pong{ +458 tx_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].into(), +459 ping_observed_addr: SendAddr::Udp("2.3.4.5:1234".parse().unwrap()), +460 }), +461 want: "02 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 00 00 00 00 00 00 00 00 00 00 00 ff ff 02 03 04 05 d2 04", +462 }, +463 Test { +464 name: "pongv6", +465 m: Message::Pong(Pong { +466 tx_id: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12].into(), +467 ping_observed_addr: SendAddr::Udp("[fed0::12]:6666".parse().unwrap()), +468 }), +469 want: "02 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 00 fe d0 00 00 00 00 00 00 00 00 00 00 00 00 00 12 0a 1a", +470 }, +471 Test { +472 name: "call_me_maybe", +473 m: Message::CallMeMaybe(CallMeMaybe { my_numbers: Vec::new() }), +474 want: "03 00", +475 }, +476 Test { +477 name: "call_me_maybe_endpoints", +478 m: Message::CallMeMaybe(CallMeMaybe { +479 my_numbers: vec![ +480 "1.2.3.4:567".parse().unwrap(), +481 "[2001::3456]:789".parse().unwrap(), +482 ], +483 }), +484 want: "03 00 00 00 00 00 00 00 00 00 00 00 ff ff 01 02 03 04 37 02 20 01 00 00 00 00 00 00 00 00 00 00 00 00 34 56 15 03", +485 }, +486 ]; +487 for test in tests { +488 println!("{}", test.name); +489 +490 let got = test.m.as_bytes(); +491 assert_eq!( +492 got, +493 data_encoding::HEXLOWER +494 .decode(test.want.replace(' ', "").as_bytes()) +495 .unwrap(), +496 "wrong as_bytes" +497 ); +498 +499 let back = Message::from_bytes(&got).expect("failed to parse"); +500 assert_eq!(test.m, back, "wrong from_bytes"); +501 } +502 } +503 +504 #[test] +505 fn test_extraction() { +506 let sender_key = SecretKey::generate(rand::thread_rng()); +507 let recv_key = SecretKey::generate(rand::thread_rng()); +508 +509 let msg = Message::Ping(Ping { +510 tx_id: stun_rs::TransactionId::default(), +511 node_key: sender_key.public(), +512 }); +513 +514 let sender_secret = secret_ed_box(sender_key.secret()); +515 let shared = SharedSecret::new(&sender_secret, &public_ed_box(&recv_key.public().public())); +516 let mut seal = msg.as_bytes(); +517 shared.seal(&mut seal); +518 +519 let bytes = encode_message(&sender_key.public(), seal.clone()); +520 +521 assert!(looks_like_disco_wrapper(&bytes)); +522 assert_eq!(source_and_box(&bytes).unwrap().0, sender_key.public()); +523 +524 let (raw_key, seal_back) = source_and_box(&bytes).unwrap(); +525 assert_eq!(raw_key, sender_key.public()); +526 assert_eq!(seal_back, seal); +527 +528 let recv_secret = secret_ed_box(recv_key.secret()); +529 let shared_recv = +530 SharedSecret::new(&recv_secret, &public_ed_box(&sender_key.public().public())); +531 let mut open_seal = seal_back.to_vec(); +532 shared_recv +533 .open(&mut open_seal) +534 .expect("failed to open seal_back"); +535 let msg_back = Message::from_bytes(&open_seal).unwrap(); +536 assert_eq!(msg_back, msg); +537 } +538}

    \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/discovery.rs.html b/pr/3327/docs/src/iroh/discovery.rs.html index edd6e9c066..80439a4ac3 100644 --- a/pr/3327/docs/src/iroh/discovery.rs.html +++ b/pr/3327/docs/src/iroh/discovery.rs.html @@ -111,1135 +111,1122 @@ 111 112use std::sync::Arc; 113 -114use iroh_base::{NodeAddr, NodeId, PublicKey}; -115use iroh_relay::node_info::EncodingError; -116use n0_future::{ -117 boxed::BoxStream, -118 stream::StreamExt, -119 task::{self, AbortOnDropHandle}, -120 time::{self, Duration}, -121 Stream, TryStreamExt, -122}; -123use nested_enum_utils::common_fields; -124use snafu::{ensure, IntoError, Snafu}; -125use tokio::sync::oneshot; -126use tracing::{debug, error_span, warn, Instrument}; -127 -128#[cfg(not(wasm_browser))] -129use crate::dns::DnsResolver; -130pub use crate::node_info::{NodeData, NodeInfo, ParseError, UserData}; -131use crate::{Endpoint, SecretKey}; -132 -133#[cfg(not(wasm_browser))] -134pub mod dns; -135 -136#[cfg(feature = "discovery-local-network")] -137pub mod mdns; -138pub mod pkarr; -139pub mod static_provider; -140 -141/// Trait for structs that can be converted into [`Discovery`]. -142/// -143/// This trait is implemented on builders for discovery services. Any type that implements this -144/// trait can be added as a discovery service in [`Builder::add_discovery`]. -145/// -146/// Any type that implements [`Discovery`] also implements [`IntoDiscovery`]. -147/// -148/// Iroh uses this trait to allow configuring the set of discovery services on the endpoint -149/// builder, while providing the discovery services access to information about the endpoint -150/// creation via the [`DiscoveryContext`] parameter to [`IntoDiscovery::into_discovery`]. -151/// -152/// [`Builder::add_discovery`]: crate::endpoint::Builder::add_discovery -153pub trait IntoDiscovery: Send + Sync + 'static { -154 /// Turns this discovery builder into a ready-to-use discovery service. -155 /// -156 /// The [`DiscoveryContext`] contains information about the [`Endpoint`] onto which this -157 /// discovery service is being added. It can be used by discovery services that need -158 /// a DNS resolver, or the endpoint's secret key to sign messages. -159 /// -160 /// If an error is returned, building the endpoint will fail with this error. -161 fn into_discovery( -162 self, -163 context: &DiscoveryContext, -164 ) -> Result<impl Discovery, IntoDiscoveryError>; -165} -166 -167/// Blanket no-op impl of `IntoDiscovery` for `T: Discovery`. -168impl<T: Discovery> IntoDiscovery for T { -169 fn into_discovery( -170 self, -171 _context: &DiscoveryContext, -172 ) -> Result<impl Discovery, IntoDiscoveryError> { -173 Ok(self) -174 } -175} -176 -177/// Non-public dyn-compatible version of [`IntoDiscovery`], used in [`crate::endpoint::Builder`]. -178pub(crate) trait DynIntoDiscovery: Send + Sync + 'static { -179 /// See [`IntoDiscovery::into_discovery`] -180 fn into_discovery( -181 self: Box<Self>, -182 context: &DiscoveryContext, -183 ) -> Result<Box<dyn Discovery>, IntoDiscoveryError>; -184} -185 -186impl<T: IntoDiscovery> DynIntoDiscovery for T { -187 fn into_discovery( -188 self: Box<Self>, -189 context: &DiscoveryContext, -190 ) -> Result<Box<dyn Discovery>, IntoDiscoveryError> { -191 let disco: Box<dyn Discovery> = Box::new(IntoDiscovery::into_discovery(*self, context)?); -192 Ok(disco) -193 } -194} -195 -196/// Context about the [`Endpoint`] for discovery services. -197#[derive(Debug)] -198pub struct DiscoveryContext<'a> { -199 #[cfg(not(wasm_browser))] -200 pub(crate) dns_resolver: &'a DnsResolver, -201 pub(crate) secret_key: &'a SecretKey, -202} -203 -204impl<'a> DiscoveryContext<'a> { -205 /// Returns the [`NodeId`] of the endpoint. -206 pub fn node_id(&self) -> NodeId { -207 self.secret_key.public() -208 } -209 -210 /// Returns the [`SecretKey`] of the endpoint. -211 pub fn secret_key(&self) -> &SecretKey { -212 self.secret_key -213 } -214 -215 /// Returns the [`DnsResolver`] used by the endpoint. -216 #[cfg(not(wasm_browser))] -217 pub fn dns_resolver(&self) -> &DnsResolver { -218 self.dns_resolver -219 } -220} -221 -222/// IntoDiscovery errors -223#[common_fields({ -224 backtrace: Option<snafu::Backtrace>, -225 #[snafu(implicit)] -226 span_trace: n0_snafu::SpanTrace, -227})] -228#[allow(missing_docs)] -229#[derive(Debug, Snafu)] -230#[non_exhaustive] -231#[snafu(module)] -232pub enum IntoDiscoveryError { -233 #[snafu(display("Service '{provenance}' error"))] -234 User { -235 provenance: &'static str, -236 source: Box<dyn std::error::Error + Send + Sync + 'static>, -237 }, -238} -239 -240impl IntoDiscoveryError { -241 /// Creates a new user error from an arbitrary error type. -242 pub fn from_err<T: std::error::Error + Send + Sync + 'static>( -243 provenance: &'static str, -244 source: T, -245 ) -> Self { -246 into_discovery_error::UserSnafu { provenance }.into_error(Box::new(source)) -247 } -248 -249 /// Creates a new user error from an arbitrary boxed error type. -250 pub fn from_err_box( -251 provenance: &'static str, -252 source: Box<dyn std::error::Error + Send + Sync + 'static>, -253 ) -> Self { -254 into_discovery_error::UserSnafu { provenance }.into_error(source) -255 } -256} -257 -258/// Discovery errors -259#[common_fields({ -260 backtrace: Option<snafu::Backtrace>, -261 #[snafu(implicit)] -262 span_trace: n0_snafu::SpanTrace, -263})] -264#[allow(missing_docs)] -265#[derive(Debug, Snafu)] -266#[non_exhaustive] -267pub enum DiscoveryError { -268 #[snafu(display("No discovery service configured"))] -269 NoServiceConfigured {}, -270 #[snafu(display("Cannot resolve node id"))] -271 NodeId { node_id: PublicKey }, -272 #[snafu(display("Discovery produced no results"))] -273 NoResults { node_id: PublicKey }, -274 #[snafu(display("Error encoding the signed packet"))] -275 SignedPacket { -276 #[snafu(source(from(EncodingError, Box::new)))] -277 source: Box<EncodingError>, -278 }, -279 #[snafu(display("Error parsing the signed packet"))] -280 ParsePacket { -281 #[snafu(source(from(ParseError, Box::new)))] -282 source: Box<ParseError>, -283 }, -284 #[snafu(display("Service '{provenance}' error"))] -285 User { -286 provenance: &'static str, -287 source: Box<dyn std::error::Error + Send + Sync + 'static>, -288 }, -289} -290 -291impl DiscoveryError { -292 /// Creates a new user error from an arbitrary error type. -293 pub fn from_err<T: std::error::Error + Send + Sync + 'static>( -294 provenance: &'static str, -295 source: T, -296 ) -> Self { -297 UserSnafu { provenance }.into_error(Box::new(source)) -298 } -299 -300 /// Creates a new user error from an arbitrary boxed error type. -301 pub fn from_err_box( -302 provenance: &'static str, -303 source: Box<dyn std::error::Error + Send + Sync + 'static>, -304 ) -> Self { -305 UserSnafu { provenance }.into_error(source) -306 } -307} -308 -309/// Node discovery for [`super::Endpoint`]. +114use iroh_base::{NodeAddr, NodeId}; +115use n0_future::{ +116 boxed::BoxStream, +117 stream::StreamExt, +118 task::{self, AbortOnDropHandle}, +119 time::{self, Duration}, +120 Stream, TryStreamExt, +121}; +122use nested_enum_utils::common_fields; +123use snafu::{ensure, IntoError, Snafu}; +124use tokio::sync::oneshot; +125use tracing::{debug, error_span, warn, Instrument}; +126 +127#[cfg(not(wasm_browser))] +128use crate::dns::DnsResolver; +129pub use crate::node_info::{NodeData, NodeInfo, ParseError, UserData}; +130use crate::{Endpoint, SecretKey}; +131 +132#[cfg(not(wasm_browser))] +133pub mod dns; +134 +135#[cfg(feature = "discovery-local-network")] +136pub mod mdns; +137pub mod pkarr; +138pub mod static_provider; +139 +140/// Trait for structs that can be converted into [`Discovery`]. +141/// +142/// This trait is implemented on builders for discovery services. Any type that implements this +143/// trait can be added as a discovery service in [`Builder::add_discovery`]. +144/// +145/// Any type that implements [`Discovery`] also implements [`IntoDiscovery`]. +146/// +147/// Iroh uses this trait to allow configuring the set of discovery services on the endpoint +148/// builder, while providing the discovery services access to information about the endpoint +149/// creation via the [`DiscoveryContext`] parameter to [`IntoDiscovery::into_discovery`]. +150/// +151/// [`Builder::add_discovery`]: crate::endpoint::Builder::add_discovery +152pub trait IntoDiscovery: Send + Sync + std::fmt::Debug + 'static { +153 /// Turns this discovery builder into a ready-to-use discovery service. +154 /// +155 /// The [`DiscoveryContext`] contains information about the [`Endpoint`] onto which this +156 /// discovery service is being added. It can be used by discovery services that need +157 /// a DNS resolver, or the endpoint's secret key to sign messages. +158 /// +159 /// If an error is returned, building the endpoint will fail with this error. +160 fn into_discovery( +161 self, +162 context: &DiscoveryContext, +163 ) -> Result<impl Discovery, IntoDiscoveryError>; +164} +165 +166/// Blanket no-op impl of `IntoDiscovery` for `T: Discovery`. +167impl<T: Discovery> IntoDiscovery for T { +168 fn into_discovery( +169 self, +170 _context: &DiscoveryContext, +171 ) -> Result<impl Discovery, IntoDiscoveryError> { +172 Ok(self) +173 } +174} +175 +176/// Non-public dyn-compatible version of [`IntoDiscovery`], used in [`crate::endpoint::Builder`]. +177pub(crate) trait DynIntoDiscovery: Send + Sync + std::fmt::Debug + 'static { +178 /// See [`IntoDiscovery::into_discovery`] +179 fn into_discovery( +180 self: Box<Self>, +181 context: &DiscoveryContext, +182 ) -> Result<Box<dyn Discovery>, IntoDiscoveryError>; +183} +184 +185impl<T: IntoDiscovery> DynIntoDiscovery for T { +186 fn into_discovery( +187 self: Box<Self>, +188 context: &DiscoveryContext, +189 ) -> Result<Box<dyn Discovery>, IntoDiscoveryError> { +190 let disco: Box<dyn Discovery> = Box::new(IntoDiscovery::into_discovery(*self, context)?); +191 Ok(disco) +192 } +193} +194 +195/// Context about the [`Endpoint`] for discovery services. +196#[derive(Debug)] +197pub struct DiscoveryContext<'a> { +198 #[cfg(not(wasm_browser))] +199 pub(crate) dns_resolver: &'a DnsResolver, +200 pub(crate) secret_key: &'a SecretKey, +201} +202 +203impl<'a> DiscoveryContext<'a> { +204 /// Returns the [`NodeId`] of the endpoint. +205 pub fn node_id(&self) -> NodeId { +206 self.secret_key.public() +207 } +208 +209 /// Returns the [`SecretKey`] of the endpoint. +210 pub fn secret_key(&self) -> &SecretKey { +211 self.secret_key +212 } +213 +214 /// Returns the [`DnsResolver`] used by the endpoint. +215 #[cfg(not(wasm_browser))] +216 pub fn dns_resolver(&self) -> &DnsResolver { +217 self.dns_resolver +218 } +219} +220 +221/// IntoDiscovery errors +222#[common_fields({ +223 backtrace: Option<snafu::Backtrace>, +224 #[snafu(implicit)] +225 span_trace: n0_snafu::SpanTrace, +226})] +227#[allow(missing_docs)] +228#[derive(Debug, Snafu)] +229#[non_exhaustive] +230#[snafu(module)] +231pub enum IntoDiscoveryError { +232 #[snafu(display("Service '{provenance}' error"))] +233 User { +234 provenance: &'static str, +235 source: Box<dyn std::error::Error + Send + Sync + 'static>, +236 }, +237} +238 +239impl IntoDiscoveryError { +240 /// Creates a new user error from an arbitrary error type. +241 pub fn from_err<T: std::error::Error + Send + Sync + 'static>( +242 provenance: &'static str, +243 source: T, +244 ) -> Self { +245 into_discovery_error::UserSnafu { provenance }.into_error(Box::new(source)) +246 } +247 +248 /// Creates a new user error from an arbitrary boxed error type. +249 pub fn from_err_box( +250 provenance: &'static str, +251 source: Box<dyn std::error::Error + Send + Sync + 'static>, +252 ) -> Self { +253 into_discovery_error::UserSnafu { provenance }.into_error(source) +254 } +255} +256 +257/// Discovery errors +258#[common_fields({ +259 backtrace: Option<snafu::Backtrace>, +260 #[snafu(implicit)] +261 span_trace: n0_snafu::SpanTrace, +262})] +263#[allow(missing_docs)] +264#[derive(Debug, Snafu)] +265#[non_exhaustive] +266pub enum DiscoveryError { +267 #[snafu(display("No discovery service configured"))] +268 NoServiceConfigured {}, +269 #[snafu(display("Discovery produced no results for {}", node_id.fmt_short()))] +270 NoResults { node_id: NodeId }, +271 #[snafu(display("Service '{provenance}' error"))] +272 User { +273 provenance: &'static str, +274 source: Box<dyn std::error::Error + Send + Sync + 'static>, +275 }, +276} +277 +278impl DiscoveryError { +279 /// Creates a new user error from an arbitrary error type. +280 pub fn from_err<T: std::error::Error + Send + Sync + 'static>( +281 provenance: &'static str, +282 source: T, +283 ) -> Self { +284 UserSnafu { provenance }.into_error(Box::new(source)) +285 } +286 +287 /// Creates a new user error from an arbitrary boxed error type. +288 pub fn from_err_box( +289 provenance: &'static str, +290 source: Box<dyn std::error::Error + Send + Sync + 'static>, +291 ) -> Self { +292 UserSnafu { provenance }.into_error(source) +293 } +294} +295 +296/// Node discovery for [`super::Endpoint`]. +297/// +298/// This trait defines publishing and resolving addressing information for a [`NodeId`]. +299/// This enables connecting to other nodes with only knowing the [`NodeId`], by using this +300/// [`Discovery`] system to look up the actual addressing information. It is common for +301/// implementations to require each node to publish their own information before it can be +302/// looked up by other nodes. +303/// +304/// The published addressing information can include both a [`RelayUrl`] and/or direct +305/// addresses. See [`NodeData`] for details. +306/// +307/// To allow for discovery, the [`super::Endpoint`] will call `publish` whenever +308/// discovery information changes. If a discovery mechanism requires a periodic +309/// refresh, it should start its own task. 310/// -311/// This trait defines publishing and resolving addressing information for a [`NodeId`]. -312/// This enables connecting to other nodes with only knowing the [`NodeId`], by using this -313/// [`Discovery`] system to look up the actual addressing information. It is common for -314/// implementations to require each node to publish their own information before it can be -315/// looked up by other nodes. -316/// -317/// The published addressing information can include both a [`RelayUrl`] and/or direct -318/// addresses. See [`NodeData`] for details. -319/// -320/// To allow for discovery, the [`super::Endpoint`] will call `publish` whenever -321/// discovery information changes. If a discovery mechanism requires a periodic -322/// refresh, it should start its own task. -323/// -324/// [`RelayUrl`]: crate::RelayUrl -325pub trait Discovery: std::fmt::Debug + Send + Sync + 'static { -326 /// Publishes the given [`NodeData`] to the discovery mechanism. -327 /// -328 /// This is fire and forget, since the [`Endpoint`] can not wait for successful -329 /// publishing. If publishing is async, the implementation should start it's own task. -330 /// -331 /// This will be called from a tokio task, so it is safe to spawn new tasks. -332 /// These tasks will be run on the runtime of the [`super::Endpoint`]. -333 fn publish(&self, _data: &NodeData) {} -334 -335 /// Resolves the [`DiscoveryItem`] for the given [`NodeId`]. -336 /// -337 /// Once the returned [`BoxStream`] is dropped, the service should stop any pending -338 /// work. -339 fn resolve( -340 &self, -341 _node_id: NodeId, -342 ) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { -343 None -344 } -345 -346 /// Subscribe to all addresses that get *passively* discovered. -347 /// -348 /// An implementation may choose to defer emitting passively discovered nodes -349 /// until the stream is actually polled. To avoid missing discovered nodes, -350 /// poll the stream as soon as possible. +311/// [`RelayUrl`]: crate::RelayUrl +312pub trait Discovery: std::fmt::Debug + Send + Sync + 'static { +313 /// Publishes the given [`NodeData`] to the discovery mechanism. +314 /// +315 /// This is fire and forget, since the [`Endpoint`] can not wait for successful +316 /// publishing. If publishing is async, the implementation should start it's own task. +317 /// +318 /// This will be called from a tokio task, so it is safe to spawn new tasks. +319 /// These tasks will be run on the runtime of the [`super::Endpoint`]. +320 fn publish(&self, _data: &NodeData) {} +321 +322 /// Resolves the [`DiscoveryItem`] for the given [`NodeId`]. +323 /// +324 /// Once the returned [`BoxStream`] is dropped, the service should stop any pending +325 /// work. +326 fn resolve( +327 &self, +328 _node_id: NodeId, +329 ) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { +330 None +331 } +332 +333 /// Subscribe to all addresses that get *passively* discovered. +334 /// +335 /// An implementation may choose to defer emitting passively discovered nodes +336 /// until the stream is actually polled. To avoid missing discovered nodes, +337 /// poll the stream as soon as possible. +338 /// +339 /// If you do not regularly poll the stream, you may miss discovered nodes. +340 /// +341 /// Any discovery systems that only discover when explicitly resolving a +342 /// specific [`NodeId`] do not need to implement this method. Any nodes or +343 /// addresses that are discovered by calling `resolve` should NOT be added +344 /// to the `subscribe` stream. +345 /// +346 /// Discovery systems that are capable of receiving information about [`NodeId`]s +347 /// and their addressing information without explicitly calling `resolve`, i.e., +348 /// systems that do "passive" discovery, should implement this method. If +349 /// `subscribe` is called multiple times, the passively discovered addresses +350 /// should be sent on all streams. 351 /// -352 /// If you do not regularly poll the stream, you may miss discovered nodes. -353 /// -354 /// Any discovery systems that only discover when explicitly resolving a -355 /// specific [`NodeId`] do not need to implement this method. Any nodes or -356 /// addresses that are discovered by calling `resolve` should NOT be added -357 /// to the `subscribe` stream. -358 /// -359 /// Discovery systems that are capable of receiving information about [`NodeId`]s -360 /// and their addressing information without explicitly calling `resolve`, i.e., -361 /// systems that do "passive" discovery, should implement this method. If -362 /// `subscribe` is called multiple times, the passively discovered addresses -363 /// should be sent on all streams. -364 /// -365 /// The [`crate::endpoint::Endpoint`] will `subscribe` to the discovery system -366 /// and add the discovered addresses to the internal address book as they arrive -367 /// on this stream. -368 fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>> { -369 None -370 } -371} -372 -373impl<T: Discovery> Discovery for Arc<T> {} -374 -375/// Node discovery results from [`Discovery`] services. -376/// -377/// This is the item in the streams returned from [`Discovery::resolve`] and -378/// [`Discovery::subscribe`]. It contains the [`NodeData`] about the discovered node, -379/// and some additional metadata about the discovery. -380/// -381/// This struct derefs to [`NodeData`], so you can access the methods from [`NodeData`] -382/// directly from [`DiscoveryItem`]. -383#[derive(Debug, Clone)] -384pub struct DiscoveryItem { -385 /// The node info for the node, as discovered by the the discovery service. -386 node_info: NodeInfo, -387 /// A static string to identify the discovery source. -388 /// -389 /// Should be uniform per discovery service. -390 provenance: &'static str, -391 /// Optional timestamp when this node address info was last updated. -392 /// -393 /// Must be microseconds since the unix epoch. -394 // TODO(ramfox): this is currently unused. As we develop more `DiscoveryService`s, we may discover that we do not need this. It is only truly relevant when comparing `relay_urls`, since we can attempt to dial any number of socket addresses, but expect each node to have one "home relay" that we will attempt to contact them on. This means we would need some way to determine which relay url to choose between, if more than one relay url is reported. -395 last_updated: Option<u64>, -396} -397 -398impl DiscoveryItem { -399 /// Creates a new [`DiscoveryItem`] from a [`NodeInfo`]. -400 pub fn new(node_info: NodeInfo, provenance: &'static str, last_updated: Option<u64>) -> Self { -401 Self { -402 node_info, -403 provenance, -404 last_updated, -405 } -406 } -407 -408 /// Returns the node id of the discovered node. -409 pub fn node_id(&self) -> NodeId { -410 self.node_info.node_id +352 /// The [`crate::endpoint::Endpoint`] will `subscribe` to the discovery system +353 /// and add the discovered addresses to the internal address book as they arrive +354 /// on this stream. +355 fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>> { +356 None +357 } +358} +359 +360impl<T: Discovery> Discovery for Arc<T> {} +361 +362/// Node discovery results from [`Discovery`] services. +363/// +364/// This is the item in the streams returned from [`Discovery::resolve`] and +365/// [`Discovery::subscribe`]. It contains the [`NodeData`] about the discovered node, +366/// and some additional metadata about the discovery. +367/// +368/// This struct derefs to [`NodeData`], so you can access the methods from [`NodeData`] +369/// directly from [`DiscoveryItem`]. +370#[derive(Debug, Clone)] +371pub struct DiscoveryItem { +372 /// The node info for the node, as discovered by the the discovery service. +373 node_info: NodeInfo, +374 /// A static string to identify the discovery source. +375 /// +376 /// Should be uniform per discovery service. +377 provenance: &'static str, +378 /// Optional timestamp when this node address info was last updated. +379 /// +380 /// Must be microseconds since the unix epoch. +381 // TODO(ramfox): this is currently unused. As we develop more `DiscoveryService`s, we may discover that we do not need this. It is only truly relevant when comparing `relay_urls`, since we can attempt to dial any number of socket addresses, but expect each node to have one "home relay" that we will attempt to contact them on. This means we would need some way to determine which relay url to choose between, if more than one relay url is reported. +382 last_updated: Option<u64>, +383} +384 +385impl DiscoveryItem { +386 /// Creates a new [`DiscoveryItem`] from a [`NodeInfo`]. +387 pub fn new(node_info: NodeInfo, provenance: &'static str, last_updated: Option<u64>) -> Self { +388 Self { +389 node_info, +390 provenance, +391 last_updated, +392 } +393 } +394 +395 /// Returns the node id of the discovered node. +396 pub fn node_id(&self) -> NodeId { +397 self.node_info.node_id +398 } +399 +400 /// Returns the [`NodeInfo`] for the discovered node. +401 pub fn node_info(&self) -> &NodeInfo { +402 &self.node_info +403 } +404 +405 /// Returns the provenance of this discovery item. +406 /// +407 /// The provenance is a static string which identifies the discovery service that produced +408 /// this discovery item. +409 pub fn provenance(&self) -> &'static str { +410 self.provenance 411 } 412 -413 /// Returns the [`NodeInfo`] for the discovered node. -414 pub fn node_info(&self) -> &NodeInfo { -415 &self.node_info -416 } -417 -418 /// Returns the provenance of this discovery item. -419 /// -420 /// The provenance is a static string which identifies the discovery service that produced -421 /// this discovery item. -422 pub fn provenance(&self) -> &'static str { -423 self.provenance -424 } -425 -426 /// Returns the optional timestamp when this node info was last updated. -427 /// -428 /// The value is microseconds since the unix epoch. -429 pub fn last_updated(&self) -> Option<u64> { -430 self.last_updated -431 } -432 -433 /// Converts into a [`NodeAddr`] by cloning the needed fields. -434 pub fn to_node_addr(&self) -> NodeAddr { -435 self.node_info.to_node_addr() -436 } -437 -438 /// Converts into a [`NodeAddr`] without cloning. -439 pub fn into_node_addr(self) -> NodeAddr { -440 self.node_info.into_node_addr() -441 } +413 /// Returns the optional timestamp when this node info was last updated. +414 /// +415 /// The value is microseconds since the unix epoch. +416 pub fn last_updated(&self) -> Option<u64> { +417 self.last_updated +418 } +419 +420 /// Converts into a [`NodeAddr`] by cloning the needed fields. +421 pub fn to_node_addr(&self) -> NodeAddr { +422 self.node_info.to_node_addr() +423 } +424 +425 /// Converts into a [`NodeAddr`] without cloning. +426 pub fn into_node_addr(self) -> NodeAddr { +427 self.node_info.into_node_addr() +428 } +429 +430 /// Returns any user-defined data. +431 pub fn user_data(&self) -> Option<UserData> { +432 self.node_info().data.user_data().cloned() +433 } +434} +435 +436impl std::ops::Deref for DiscoveryItem { +437 type Target = NodeData; +438 fn deref(&self) -> &Self::Target { +439 &self.node_info.data +440 } +441} 442 -443 /// Returns any user-defined data. -444 pub fn user_data(&self) -> Option<UserData> { -445 self.node_info().data.user_data().cloned() +443impl From<DiscoveryItem> for NodeInfo { +444 fn from(item: DiscoveryItem) -> Self { +445 item.node_info 446 } 447} 448 -449impl std::ops::Deref for DiscoveryItem { -450 type Target = NodeData; -451 fn deref(&self) -> &Self::Target { -452 &self.node_info.data -453 } -454} -455 -456impl From<DiscoveryItem> for NodeInfo { -457 fn from(item: DiscoveryItem) -> Self { -458 item.node_info -459 } -460} -461 -462/// A discovery service that combines multiple discovery sources. -463/// -464/// The discovery services will resolve concurrently. -465#[derive(Debug, Default)] -466pub struct ConcurrentDiscovery { -467 services: Vec<Box<dyn Discovery>>, -468} -469 -470impl ConcurrentDiscovery { -471 /// Creates an empty [`ConcurrentDiscovery`]. -472 pub fn empty() -> Self { -473 Self::default() -474 } -475 -476 /// Creates a new [`ConcurrentDiscovery`]. -477 pub fn from_services(services: Vec<Box<dyn Discovery>>) -> Self { -478 Self { services } -479 } -480 -481 /// Adds a [`Discovery`] service. -482 pub fn add(&mut self, service: impl Discovery + 'static) { -483 self.services.push(Box::new(service)); -484 } -485} -486 -487impl<T> From<T> for ConcurrentDiscovery -488where -489 T: IntoIterator<Item = Box<dyn Discovery>>, -490{ -491 fn from(iter: T) -> Self { -492 let services = iter.into_iter().collect::<Vec<_>>(); -493 Self { services } -494 } -495} +449/// A discovery service that combines multiple discovery sources. +450/// +451/// The discovery services will resolve concurrently. +452#[derive(Debug, Default)] +453pub struct ConcurrentDiscovery { +454 services: Vec<Box<dyn Discovery>>, +455} +456 +457impl ConcurrentDiscovery { +458 /// Creates an empty [`ConcurrentDiscovery`]. +459 pub fn empty() -> Self { +460 Self::default() +461 } +462 +463 /// Creates a new [`ConcurrentDiscovery`]. +464 pub fn from_services(services: Vec<Box<dyn Discovery>>) -> Self { +465 Self { services } +466 } +467 +468 /// Adds a [`Discovery`] service. +469 pub fn add(&mut self, service: impl Discovery + 'static) { +470 self.services.push(Box::new(service)); +471 } +472} +473 +474impl<T> From<T> for ConcurrentDiscovery +475where +476 T: IntoIterator<Item = Box<dyn Discovery>>, +477{ +478 fn from(iter: T) -> Self { +479 let services = iter.into_iter().collect::<Vec<_>>(); +480 Self { services } +481 } +482} +483 +484impl Discovery for ConcurrentDiscovery { +485 fn publish(&self, data: &NodeData) { +486 for service in &self.services { +487 service.publish(data); +488 } +489 } +490 +491 fn resolve(&self, node_id: NodeId) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { +492 let streams = self +493 .services +494 .iter() +495 .filter_map(|service| service.resolve(node_id)); 496 -497impl Discovery for ConcurrentDiscovery { -498 fn publish(&self, data: &NodeData) { -499 for service in &self.services { -500 service.publish(data); -501 } -502 } -503 -504 fn resolve(&self, node_id: NodeId) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { -505 let streams = self -506 .services -507 .iter() -508 .filter_map(|service| service.resolve(node_id)); -509 -510 let streams = n0_future::MergeBounded::from_iter(streams); -511 Some(Box::pin(streams)) -512 } +497 let streams = n0_future::MergeBounded::from_iter(streams); +498 Some(Box::pin(streams)) +499 } +500 +501 fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>> { +502 let mut streams = vec![]; +503 for service in self.services.iter() { +504 if let Some(stream) = service.subscribe() { +505 streams.push(stream) +506 } +507 } +508 +509 let streams = n0_future::MergeBounded::from_iter(streams); +510 Some(Box::pin(streams)) +511 } +512} 513 -514 fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>> { -515 let mut streams = vec![]; -516 for service in self.services.iter() { -517 if let Some(stream) = service.subscribe() { -518 streams.push(stream) -519 } -520 } -521 -522 let streams = n0_future::MergeBounded::from_iter(streams); -523 Some(Box::pin(streams)) -524 } -525} -526 -527/// Maximum duration since the last control or data message received from an endpoint to make us -528/// start a discovery task. -529const MAX_AGE: Duration = Duration::from_secs(10); -530 -531/// A wrapper around a tokio task which runs a node discovery. -532pub(super) struct DiscoveryTask { -533 on_first_rx: oneshot::Receiver<Result<(), DiscoveryError>>, -534 _task: AbortOnDropHandle<()>, -535} -536 -537impl DiscoveryTask { -538 /// Starts a discovery task. -539 pub(super) fn start(ep: Endpoint, node_id: NodeId) -> Result<Self, DiscoveryError> { -540 ensure!(ep.discovery().is_some(), NoServiceConfiguredSnafu); -541 let (on_first_tx, on_first_rx) = oneshot::channel(); -542 let me = ep.node_id(); -543 let task = task::spawn( -544 async move { Self::run(ep, node_id, on_first_tx).await }.instrument( -545 error_span!("discovery", me = %me.fmt_short(), node = %node_id.fmt_short()), -546 ), -547 ); -548 Ok(Self { -549 _task: AbortOnDropHandle::new(task), -550 on_first_rx, -551 }) -552 } -553 -554 /// Starts a discovery task after a delay and only if no path to the node was recently active. -555 /// -556 /// This returns `None` if we received data or control messages from the remote endpoint -557 /// recently enough. If not it returns a [`DiscoveryTask`]. -558 /// -559 /// If `delay` is set, the [`DiscoveryTask`] will first wait for `delay` and then check again -560 /// if we recently received messages from remote endpoint. If true, the task will abort. -561 /// Otherwise, or if no `delay` is set, the discovery will be started. -562 pub(super) fn maybe_start_after_delay( -563 ep: &Endpoint, -564 node_id: NodeId, -565 delay: Option<Duration>, -566 ) -> Result<Option<Self>, DiscoveryError> { -567 // If discovery is not needed, don't even spawn a task. -568 if !Self::needs_discovery(ep, node_id) { -569 return Ok(None); -570 } -571 ensure!(ep.discovery().is_some(), NoServiceConfiguredSnafu); -572 let (on_first_tx, on_first_rx) = oneshot::channel(); -573 let ep = ep.clone(); -574 let me = ep.node_id(); -575 let task = task::spawn( -576 async move { -577 // If delay is set, wait and recheck if discovery is needed. If not, early-exit. -578 if let Some(delay) = delay { -579 time::sleep(delay).await; -580 if !Self::needs_discovery(&ep, node_id) { -581 debug!("no discovery needed, abort"); -582 on_first_tx.send(Ok(())).ok(); -583 return; -584 } -585 } -586 Self::run(ep, node_id, on_first_tx).await -587 } -588 .instrument( -589 error_span!("discovery", me = %me.fmt_short(), node = %node_id.fmt_short()), -590 ), -591 ); -592 Ok(Some(Self { -593 _task: AbortOnDropHandle::new(task), -594 on_first_rx, -595 })) -596 } -597 -598 /// Waits until the discovery task produced at least one result. -599 pub(super) async fn first_arrived(&mut self) -> Result<(), DiscoveryError> { -600 let fut = &mut self.on_first_rx; -601 fut.await.expect("sender dropped")?; -602 Ok(()) -603 } -604 -605 fn create_stream( -606 ep: &Endpoint, -607 node_id: NodeId, -608 ) -> Result<BoxStream<Result<DiscoveryItem, DiscoveryError>>, DiscoveryError> { -609 let discovery = ep.discovery().ok_or(NoServiceConfiguredSnafu.build())?; -610 let stream = discovery -611 .resolve(node_id) -612 .ok_or(NodeIdSnafu { node_id }.build())?; -613 Ok(stream) -614 } -615 -616 /// We need discovery if we have no paths to the node, or if the paths we do have -617 /// have timed out. -618 fn needs_discovery(ep: &Endpoint, node_id: NodeId) -> bool { -619 match ep.remote_info(node_id) { -620 // No info means no path to node -> start discovery. -621 None => true, -622 Some(info) => { -623 match ( -624 info.last_received(), -625 info.relay_url.as_ref().and_then(|r| r.last_alive), -626 ) { -627 // No path to node -> start discovery. -628 (None, None) => true, -629 // If we haven't received on direct addresses or the relay for MAX_AGE, -630 // start discovery. -631 (Some(elapsed), Some(elapsed_relay)) => { -632 elapsed > MAX_AGE && elapsed_relay > MAX_AGE -633 } -634 (Some(elapsed), _) | (_, Some(elapsed)) => elapsed > MAX_AGE, -635 } -636 } -637 } -638 } -639 -640 async fn run( -641 ep: Endpoint, -642 node_id: NodeId, -643 on_first_tx: oneshot::Sender<Result<(), DiscoveryError>>, -644 ) { -645 let mut stream = match Self::create_stream(&ep, node_id) { -646 Ok(stream) => stream, -647 Err(err) => { -648 on_first_tx.send(Err(err)).ok(); -649 return; -650 } -651 }; -652 let mut on_first_tx = Some(on_first_tx); -653 debug!("starting"); -654 loop { -655 match stream.next().await { -656 Some(Ok(r)) => { -657 let provenance = r.provenance; -658 let node_addr = r.to_node_addr(); -659 if node_addr.is_empty() { -660 debug!(%provenance, "empty address found"); -661 continue; -662 } -663 debug!(%provenance, addr = ?node_addr, "new address found"); -664 ep.add_node_addr_with_source(node_addr, provenance).ok(); -665 if let Some(tx) = on_first_tx.take() { -666 tx.send(Ok(())).ok(); -667 } -668 // Send the discovery item to the subscribers of the discovery broadcast stream. -669 ep.discovery_subscribers().send(r); -670 } -671 Some(Err(err)) => { -672 warn!(?err, "discovery service produced error"); -673 break; -674 } -675 None => break, -676 } -677 } -678 if let Some(tx) = on_first_tx.take() { -679 tx.send(Err(NoResultsSnafu { node_id }.build())).ok(); -680 } -681 } -682} -683 -684/// Error returned when a discovery watch stream lagged too far behind. -685/// -686/// The stream returned from [`Endpoint::discovery_stream`] yields this error -687/// if the loop in which the stream is processed cannot keep up with the emitted -688/// discovery events. Attempting to read the next item from the channel afterwards -689/// will return the oldest [`DiscoveryItem`] that is still retained. -690/// -691/// Includes the number of skipped messages. -692#[derive(Debug, Snafu)] -693#[snafu(display("channel lagged by {val}"))] -694pub struct Lagged { -695 /// The number of skipped messages -696 pub val: u64, -697} -698 -699#[derive(Clone, Debug)] -700pub(super) struct DiscoverySubscribers { -701 inner: tokio::sync::broadcast::Sender<DiscoveryItem>, -702} -703 -704impl DiscoverySubscribers { -705 pub(crate) fn new() -> Self { -706 // TODO: Make capacity configurable from the endpoint builder? -707 // This is the maximum number of [`DiscoveryItem`]s held by the channel if -708 // subscribers are stalled. -709 const CAPACITY: usize = 128; -710 Self { -711 inner: tokio::sync::broadcast::Sender::new(CAPACITY), -712 } -713 } +514/// Maximum duration since the last control or data message received from an endpoint to make us +515/// start a discovery task. +516const MAX_AGE: Duration = Duration::from_secs(10); +517 +518/// A wrapper around a tokio task which runs a node discovery. +519pub(super) struct DiscoveryTask { +520 on_first_rx: oneshot::Receiver<Result<(), DiscoveryError>>, +521 _task: AbortOnDropHandle<()>, +522} +523 +524impl DiscoveryTask { +525 /// Starts a discovery task. +526 pub(super) fn start(ep: Endpoint, node_id: NodeId) -> Result<Self, DiscoveryError> { +527 ensure!(ep.discovery().is_some(), NoServiceConfiguredSnafu); +528 let (on_first_tx, on_first_rx) = oneshot::channel(); +529 let me = ep.node_id(); +530 let task = task::spawn( +531 async move { Self::run(ep, node_id, on_first_tx).await }.instrument( +532 error_span!("discovery", me = %me.fmt_short(), node = %node_id.fmt_short()), +533 ), +534 ); +535 Ok(Self { +536 _task: AbortOnDropHandle::new(task), +537 on_first_rx, +538 }) +539 } +540 +541 /// Starts a discovery task after a delay and only if no path to the node was recently active. +542 /// +543 /// This returns `None` if we received data or control messages from the remote endpoint +544 /// recently enough. If not it returns a [`DiscoveryTask`]. +545 /// +546 /// If `delay` is set, the [`DiscoveryTask`] will first wait for `delay` and then check again +547 /// if we recently received messages from remote endpoint. If true, the task will abort. +548 /// Otherwise, or if no `delay` is set, the discovery will be started. +549 pub(super) fn maybe_start_after_delay( +550 ep: &Endpoint, +551 node_id: NodeId, +552 delay: Option<Duration>, +553 ) -> Result<Option<Self>, DiscoveryError> { +554 // If discovery is not needed, don't even spawn a task. +555 if !Self::needs_discovery(ep, node_id) { +556 return Ok(None); +557 } +558 ensure!(ep.discovery().is_some(), NoServiceConfiguredSnafu); +559 let (on_first_tx, on_first_rx) = oneshot::channel(); +560 let ep = ep.clone(); +561 let me = ep.node_id(); +562 let task = task::spawn( +563 async move { +564 // If delay is set, wait and recheck if discovery is needed. If not, early-exit. +565 if let Some(delay) = delay { +566 time::sleep(delay).await; +567 if !Self::needs_discovery(&ep, node_id) { +568 debug!("no discovery needed, abort"); +569 on_first_tx.send(Ok(())).ok(); +570 return; +571 } +572 } +573 Self::run(ep, node_id, on_first_tx).await +574 } +575 .instrument( +576 error_span!("discovery", me = %me.fmt_short(), node = %node_id.fmt_short()), +577 ), +578 ); +579 Ok(Some(Self { +580 _task: AbortOnDropHandle::new(task), +581 on_first_rx, +582 })) +583 } +584 +585 /// Waits until the discovery task produced at least one result. +586 pub(super) async fn first_arrived(&mut self) -> Result<(), DiscoveryError> { +587 let fut = &mut self.on_first_rx; +588 fut.await.expect("sender dropped")?; +589 Ok(()) +590 } +591 +592 fn create_stream( +593 ep: &Endpoint, +594 node_id: NodeId, +595 ) -> Result<BoxStream<Result<DiscoveryItem, DiscoveryError>>, DiscoveryError> { +596 let discovery = ep.discovery().ok_or(NoServiceConfiguredSnafu.build())?; +597 let stream = discovery +598 .resolve(node_id) +599 .ok_or(NoResultsSnafu { node_id }.build())?; +600 Ok(stream) +601 } +602 +603 /// We need discovery if we have no paths to the node, or if the paths we do have +604 /// have timed out. +605 fn needs_discovery(ep: &Endpoint, node_id: NodeId) -> bool { +606 match ep.remote_info(node_id) { +607 // No info means no path to node -> start discovery. +608 None => true, +609 Some(info) => { +610 match ( +611 info.last_received(), +612 info.relay_url.as_ref().and_then(|r| r.last_alive), +613 ) { +614 // No path to node -> start discovery. +615 (None, None) => true, +616 // If we haven't received on direct addresses or the relay for MAX_AGE, +617 // start discovery. +618 (Some(elapsed), Some(elapsed_relay)) => { +619 elapsed > MAX_AGE && elapsed_relay > MAX_AGE +620 } +621 (Some(elapsed), _) | (_, Some(elapsed)) => elapsed > MAX_AGE, +622 } +623 } +624 } +625 } +626 +627 async fn run( +628 ep: Endpoint, +629 node_id: NodeId, +630 on_first_tx: oneshot::Sender<Result<(), DiscoveryError>>, +631 ) { +632 let mut stream = match Self::create_stream(&ep, node_id) { +633 Ok(stream) => stream, +634 Err(err) => { +635 on_first_tx.send(Err(err)).ok(); +636 return; +637 } +638 }; +639 let mut on_first_tx = Some(on_first_tx); +640 debug!("starting"); +641 loop { +642 match stream.next().await { +643 Some(Ok(r)) => { +644 let provenance = r.provenance; +645 let node_addr = r.to_node_addr(); +646 if node_addr.is_empty() { +647 debug!(%provenance, "empty address found"); +648 continue; +649 } +650 debug!(%provenance, addr = ?node_addr, "new address found"); +651 ep.add_node_addr_with_source(node_addr, provenance).ok(); +652 if let Some(tx) = on_first_tx.take() { +653 tx.send(Ok(())).ok(); +654 } +655 // Send the discovery item to the subscribers of the discovery broadcast stream. +656 ep.discovery_subscribers().send(r); +657 } +658 Some(Err(err)) => { +659 warn!(?err, "discovery service produced error"); +660 break; +661 } +662 None => break, +663 } +664 } +665 if let Some(tx) = on_first_tx.take() { +666 tx.send(Err(NoResultsSnafu { node_id }.build())).ok(); +667 } +668 } +669} +670 +671/// Error returned when a discovery watch stream lagged too far behind. +672/// +673/// The stream returned from [`Endpoint::discovery_stream`] yields this error +674/// if the loop in which the stream is processed cannot keep up with the emitted +675/// discovery events. Attempting to read the next item from the channel afterwards +676/// will return the oldest [`DiscoveryItem`] that is still retained. +677/// +678/// Includes the number of skipped messages. +679#[derive(Debug, Snafu)] +680#[snafu(display("channel lagged by {val}"))] +681pub struct Lagged { +682 /// The number of skipped messages +683 pub val: u64, +684} +685 +686#[derive(Clone, Debug)] +687pub(super) struct DiscoverySubscribers { +688 inner: tokio::sync::broadcast::Sender<DiscoveryItem>, +689} +690 +691impl DiscoverySubscribers { +692 pub(crate) fn new() -> Self { +693 // TODO: Make capacity configurable from the endpoint builder? +694 // This is the maximum number of [`DiscoveryItem`]s held by the channel if +695 // subscribers are stalled. +696 const CAPACITY: usize = 128; +697 Self { +698 inner: tokio::sync::broadcast::Sender::new(CAPACITY), +699 } +700 } +701 +702 pub(crate) fn subscribe(&self) -> impl Stream<Item = Result<DiscoveryItem, Lagged>> { +703 use tokio_stream::wrappers::{errors::BroadcastStreamRecvError, BroadcastStream}; +704 let recv = self.inner.subscribe(); +705 BroadcastStream::new(recv).map_err(|BroadcastStreamRecvError::Lagged(n)| Lagged { val: n }) +706 } +707 +708 pub(crate) fn send(&self, item: DiscoveryItem) { +709 // `broadcast::Sender::send` returns an error if the channel has no subscribers, +710 // which we don't care about. +711 self.inner.send(item).ok(); +712 } +713} 714 -715 pub(crate) fn subscribe(&self) -> impl Stream<Item = Result<DiscoveryItem, Lagged>> { -716 use tokio_stream::wrappers::{errors::BroadcastStreamRecvError, BroadcastStream}; -717 let recv = self.inner.subscribe(); -718 BroadcastStream::new(recv).map_err(|BroadcastStreamRecvError::Lagged(n)| Lagged { val: n }) -719 } -720 -721 pub(crate) fn send(&self, item: DiscoveryItem) { -722 // `broadcast::Sender::send` returns an error if the channel has no subscribers, -723 // which we don't care about. -724 self.inner.send(item).ok(); -725 } -726} -727 -728#[cfg(test)] -729mod tests { -730 use std::{ -731 collections::{BTreeSet, HashMap}, -732 net::SocketAddr, -733 sync::{Arc, Mutex}, -734 time::SystemTime, -735 }; +715#[cfg(test)] +716mod tests { +717 use std::{ +718 collections::{BTreeSet, HashMap}, +719 net::SocketAddr, +720 sync::{Arc, Mutex}, +721 time::SystemTime, +722 }; +723 +724 use iroh_base::{NodeAddr, SecretKey}; +725 use n0_snafu::{Error, Result, ResultExt}; +726 use n0_watcher::Watcher as _; +727 use quinn::{IdleTimeout, TransportConfig}; +728 use rand::Rng; +729 use tokio_util::task::AbortOnDropHandle; +730 use tracing_test::traced_test; +731 +732 use super::*; +733 use crate::{endpoint::ConnectOptions, Endpoint, RelayMode}; +734 +735 type InfoStore = HashMap<NodeId, (NodeData, u64)>; 736 -737 use iroh_base::{NodeAddr, SecretKey}; -738 use n0_snafu::{Error, Result, ResultExt}; -739 use quinn::{IdleTimeout, TransportConfig}; -740 use rand::Rng; -741 use tokio_util::task::AbortOnDropHandle; -742 use tracing_test::traced_test; -743 -744 use super::*; -745 use crate::{endpoint::ConnectOptions, watcher::Watcher as _, Endpoint, RelayMode}; -746 -747 type InfoStore = HashMap<NodeId, (NodeData, u64)>; -748 -749 #[derive(Debug, Clone)] -750 struct TestDiscoveryShared { -751 nodes: Arc<Mutex<InfoStore>>, -752 watchers: tokio::sync::broadcast::Sender<DiscoveryItem>, -753 } -754 -755 impl Default for TestDiscoveryShared { -756 fn default() -> Self { -757 Self { -758 nodes: Default::default(), -759 watchers: tokio::sync::broadcast::Sender::new(1024), +737 #[derive(Debug, Clone)] +738 struct TestDiscoveryShared { +739 nodes: Arc<Mutex<InfoStore>>, +740 watchers: tokio::sync::broadcast::Sender<DiscoveryItem>, +741 } +742 +743 impl Default for TestDiscoveryShared { +744 fn default() -> Self { +745 Self { +746 nodes: Default::default(), +747 watchers: tokio::sync::broadcast::Sender::new(1024), +748 } +749 } +750 } +751 +752 impl TestDiscoveryShared { +753 pub fn create_discovery(&self, node_id: NodeId) -> TestDiscovery { +754 TestDiscovery { +755 node_id, +756 shared: self.clone(), +757 publish: true, +758 resolve_wrong: false, +759 delay: Duration::from_millis(200), 760 } 761 } -762 } -763 -764 impl TestDiscoveryShared { -765 pub fn create_discovery(&self, node_id: NodeId) -> TestDiscovery { -766 TestDiscovery { -767 node_id, -768 shared: self.clone(), -769 publish: true, -770 resolve_wrong: false, -771 delay: Duration::from_millis(200), -772 } -773 } -774 -775 pub fn create_lying_discovery(&self, node_id: NodeId) -> TestDiscovery { -776 TestDiscovery { -777 node_id, -778 shared: self.clone(), -779 publish: false, -780 resolve_wrong: true, -781 delay: Duration::from_millis(100), -782 } -783 } -784 -785 pub fn send_passive(&self, item: DiscoveryItem) { -786 self.watchers.send(item).ok(); -787 } -788 } -789 -790 #[derive(Debug)] -791 struct TestDiscovery { -792 node_id: NodeId, -793 shared: TestDiscoveryShared, -794 publish: bool, -795 resolve_wrong: bool, -796 delay: Duration, -797 } -798 -799 impl Discovery for TestDiscovery { -800 fn publish(&self, data: &NodeData) { -801 if !self.publish { -802 return; -803 } -804 let now = system_time_now(); -805 self.shared -806 .nodes -807 .lock() -808 .unwrap() -809 .insert(self.node_id, (data.clone(), now)); -810 } -811 -812 fn resolve( -813 &self, -814 node_id: NodeId, -815 ) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { -816 let addr_info = if self.resolve_wrong { -817 let ts = system_time_now() - 100_000; -818 let port: u16 = rand::thread_rng().gen_range(10_000..20_000); -819 // "240.0.0.0/4" is reserved and unreachable -820 let addr: SocketAddr = format!("240.0.0.1:{port}").parse().unwrap(); -821 let data = NodeData::new(None, BTreeSet::from([addr])); -822 Some((data, ts)) -823 } else { -824 self.shared.nodes.lock().unwrap().get(&node_id).cloned() -825 }; -826 let stream = match addr_info { -827 Some((data, ts)) => { -828 let item = DiscoveryItem::new( -829 NodeInfo::from_parts(node_id, data), -830 "test-disco", -831 Some(ts), -832 ); -833 let delay = self.delay; -834 let fut = async move { -835 time::sleep(delay).await; -836 tracing::debug!("resolve: {} = {item:?}", node_id.fmt_short()); -837 Ok(item) -838 }; -839 n0_future::stream::once_future(fut).boxed() -840 } -841 None => n0_future::stream::empty().boxed(), -842 }; -843 Some(stream) -844 } -845 -846 fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>> { -847 let recv = self.shared.watchers.subscribe(); -848 let stream = -849 tokio_stream::wrappers::BroadcastStream::new(recv).filter_map(|item| item.ok()); -850 Some(Box::pin(stream)) -851 } -852 } -853 -854 #[derive(Debug, Clone)] -855 struct EmptyDiscovery; -856 -857 impl Discovery for EmptyDiscovery { -858 fn publish(&self, _data: &NodeData) {} -859 -860 fn resolve( -861 &self, -862 _node_id: NodeId, -863 ) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { -864 Some(n0_future::stream::empty().boxed()) -865 } -866 } -867 -868 const TEST_ALPN: &[u8] = b"n0/iroh/test"; -869 -870 /// This is a smoke test for our discovery mechanism. -871 #[tokio::test] -872 #[traced_test] -873 async fn endpoint_discovery_simple_shared() -> Result { -874 let disco_shared = TestDiscoveryShared::default(); -875 let (ep1, _guard1) = { -876 let secret = SecretKey::generate(rand::thread_rng()); -877 let disco = disco_shared.create_discovery(secret.public()); -878 new_endpoint(secret, disco).await -879 }; -880 let (ep2, _guard2) = { -881 let secret = SecretKey::generate(rand::thread_rng()); -882 let disco = disco_shared.create_discovery(secret.public()); -883 new_endpoint(secret, disco).await -884 }; -885 let ep1_addr = NodeAddr::new(ep1.node_id()); -886 // wait for our address to be updated and thus published at least once -887 ep1.node_addr().initialized().await?; -888 let _conn = ep2.connect(ep1_addr, TEST_ALPN).await?; -889 Ok(()) -890 } -891 -892 /// This test adds an empty discovery which provides no addresses. -893 #[tokio::test] -894 #[traced_test] -895 async fn endpoint_discovery_combined_with_empty() -> Result { -896 let disco_shared = TestDiscoveryShared::default(); -897 let (ep1, _guard1) = { -898 let secret = SecretKey::generate(rand::thread_rng()); -899 let disco = disco_shared.create_discovery(secret.public()); -900 new_endpoint(secret, disco).await -901 }; -902 let (ep2, _guard2) = { -903 let secret = SecretKey::generate(rand::thread_rng()); -904 let disco1 = EmptyDiscovery; -905 let disco2 = disco_shared.create_discovery(secret.public()); -906 let mut disco = ConcurrentDiscovery::empty(); -907 disco.add(disco1); -908 disco.add(disco2); -909 new_endpoint(secret, disco).await -910 }; -911 let ep1_addr = NodeAddr::new(ep1.node_id()); -912 // wait for out address to be updated and thus published at least once -913 ep1.node_addr() -914 .initialized() -915 .await -916 .context("waiting for NodeAddr")?; -917 let _conn = ep2 -918 .connect(ep1_addr, TEST_ALPN) -919 .await -920 .context("connecting")?; -921 Ok(()) -922 } -923 -924 /// This test adds a "lying" discovery which provides a wrong address. -925 /// This is to make sure that as long as one of the discoveries returns a working address, we -926 /// will connect successfully. -927 #[tokio::test] -928 #[traced_test] -929 async fn endpoint_discovery_combined_with_empty_and_wrong() -> Result { -930 let disco_shared = TestDiscoveryShared::default(); -931 let (ep1, _guard1) = { -932 let secret = SecretKey::generate(rand::thread_rng()); -933 let disco = disco_shared.create_discovery(secret.public()); -934 new_endpoint(secret, disco).await -935 }; -936 let (ep2, _guard2) = { -937 let secret = SecretKey::generate(rand::thread_rng()); -938 let disco1 = EmptyDiscovery; -939 let disco2 = disco_shared.create_lying_discovery(secret.public()); -940 let disco3 = disco_shared.create_discovery(secret.public()); -941 let mut disco = ConcurrentDiscovery::empty(); -942 disco.add(disco1); -943 disco.add(disco2); -944 disco.add(disco3); -945 new_endpoint(secret, disco).await -946 }; -947 // wait for out address to be updated and thus published at least once -948 ep1.node_addr().initialized().await?; -949 let _conn = ep2.connect(ep1.node_id(), TEST_ALPN).await?; -950 Ok(()) -951 } -952 -953 /// This test only has the "lying" discovery. It is here to make sure that this actually fails. -954 #[tokio::test] -955 #[traced_test] -956 async fn endpoint_discovery_combined_wrong_only() -> Result { -957 let disco_shared = TestDiscoveryShared::default(); -958 let (ep1, _guard1) = { -959 let secret = SecretKey::generate(rand::thread_rng()); -960 let disco = disco_shared.create_discovery(secret.public()); -961 new_endpoint(secret, disco).await -962 }; -963 let (ep2, _guard2) = { -964 let secret = SecretKey::generate(rand::thread_rng()); -965 let disco1 = disco_shared.create_lying_discovery(secret.public()); -966 let disco = ConcurrentDiscovery::from_services(vec![Box::new(disco1)]); -967 new_endpoint(secret, disco).await -968 }; -969 // wait for out address to be updated and thus published at least once -970 ep1.node_addr().initialized().await?; -971 -972 // 10x faster test via a 3s idle timeout instead of the 30s default -973 let mut config = TransportConfig::default(); -974 config.keep_alive_interval(Some(Duration::from_secs(1))); -975 config.max_idle_timeout(Some(IdleTimeout::try_from(Duration::from_secs(3)).unwrap())); -976 let opts = ConnectOptions::new().with_transport_config(Arc::new(config)); -977 -978 let res = ep2 -979 .connect_with_opts(ep1.node_id(), TEST_ALPN, opts) -980 .await? // -> Connecting works -981 .await; // -> Connection is expected to fail -982 assert!(res.is_err()); -983 Ok(()) -984 } -985 -986 /// This test first adds a wrong address manually (e.g. from an outdated&node_id ticket). -987 /// Connect should still succeed because the discovery service will be invoked (after a delay). -988 #[tokio::test] -989 #[traced_test] -990 async fn endpoint_discovery_with_wrong_existing_addr() -> Result { -991 let disco_shared = TestDiscoveryShared::default(); -992 let (ep1, _guard1) = { -993 let secret = SecretKey::generate(rand::thread_rng()); -994 let disco = disco_shared.create_discovery(secret.public()); -995 new_endpoint(secret, disco).await -996 }; -997 let (ep2, _guard2) = { -998 let secret = SecretKey::generate(rand::thread_rng()); -999 let disco = disco_shared.create_discovery(secret.public()); -1000 new_endpoint(secret, disco).await -1001 }; -1002 // wait for out address to be updated and thus published at least once -1003 ep1.node_addr().initialized().await?; -1004 let ep1_wrong_addr = NodeAddr { -1005 node_id: ep1.node_id(), -1006 relay_url: None, -1007 direct_addresses: BTreeSet::from(["240.0.0.1:1000".parse().unwrap()]), -1008 }; -1009 let _conn = ep2.connect(ep1_wrong_addr, TEST_ALPN).await?; -1010 Ok(()) -1011 } -1012 -1013 #[tokio::test] -1014 #[traced_test] -1015 async fn endpoint_discovery_watch() -> Result { -1016 let disco_shared = TestDiscoveryShared::default(); -1017 let (ep1, _guard1) = { -1018 let secret = SecretKey::generate(rand::thread_rng()); -1019 let disco = disco_shared.create_discovery(secret.public()); -1020 new_endpoint(secret, disco).await -1021 }; -1022 let (ep2, _guard2) = { -1023 let secret = SecretKey::generate(rand::thread_rng()); -1024 let disco = disco_shared.create_discovery(secret.public()); -1025 new_endpoint(secret, disco).await -1026 }; -1027 -1028 let mut stream = ep1.discovery_stream(); +762 +763 pub fn create_lying_discovery(&self, node_id: NodeId) -> TestDiscovery { +764 TestDiscovery { +765 node_id, +766 shared: self.clone(), +767 publish: false, +768 resolve_wrong: true, +769 delay: Duration::from_millis(100), +770 } +771 } +772 +773 pub fn send_passive(&self, item: DiscoveryItem) { +774 self.watchers.send(item).ok(); +775 } +776 } +777 +778 #[derive(Debug)] +779 struct TestDiscovery { +780 node_id: NodeId, +781 shared: TestDiscoveryShared, +782 publish: bool, +783 resolve_wrong: bool, +784 delay: Duration, +785 } +786 +787 impl Discovery for TestDiscovery { +788 fn publish(&self, data: &NodeData) { +789 if !self.publish { +790 return; +791 } +792 let now = system_time_now(); +793 self.shared +794 .nodes +795 .lock() +796 .unwrap() +797 .insert(self.node_id, (data.clone(), now)); +798 } +799 +800 fn resolve( +801 &self, +802 node_id: NodeId, +803 ) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { +804 let addr_info = if self.resolve_wrong { +805 let ts = system_time_now() - 100_000; +806 let port: u16 = rand::thread_rng().gen_range(10_000..20_000); +807 // "240.0.0.0/4" is reserved and unreachable +808 let addr: SocketAddr = format!("240.0.0.1:{port}").parse().unwrap(); +809 let data = NodeData::new(None, BTreeSet::from([addr])); +810 Some((data, ts)) +811 } else { +812 self.shared.nodes.lock().unwrap().get(&node_id).cloned() +813 }; +814 let stream = match addr_info { +815 Some((data, ts)) => { +816 let item = DiscoveryItem::new( +817 NodeInfo::from_parts(node_id, data), +818 "test-disco", +819 Some(ts), +820 ); +821 let delay = self.delay; +822 let fut = async move { +823 time::sleep(delay).await; +824 tracing::debug!("resolve: {} = {item:?}", node_id.fmt_short()); +825 Ok(item) +826 }; +827 n0_future::stream::once_future(fut).boxed() +828 } +829 None => n0_future::stream::empty().boxed(), +830 }; +831 Some(stream) +832 } +833 +834 fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>> { +835 let recv = self.shared.watchers.subscribe(); +836 let stream = +837 tokio_stream::wrappers::BroadcastStream::new(recv).filter_map(|item| item.ok()); +838 Some(Box::pin(stream)) +839 } +840 } +841 +842 #[derive(Debug, Clone)] +843 struct EmptyDiscovery; +844 +845 impl Discovery for EmptyDiscovery { +846 fn publish(&self, _data: &NodeData) {} +847 +848 fn resolve( +849 &self, +850 _node_id: NodeId, +851 ) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { +852 Some(n0_future::stream::empty().boxed()) +853 } +854 } +855 +856 const TEST_ALPN: &[u8] = b"n0/iroh/test"; +857 +858 /// This is a smoke test for our discovery mechanism. +859 #[tokio::test] +860 #[traced_test] +861 async fn endpoint_discovery_simple_shared() -> Result { +862 let disco_shared = TestDiscoveryShared::default(); +863 let (ep1, _guard1) = { +864 let secret = SecretKey::generate(rand::thread_rng()); +865 let disco = disco_shared.create_discovery(secret.public()); +866 new_endpoint(secret, disco).await +867 }; +868 let (ep2, _guard2) = { +869 let secret = SecretKey::generate(rand::thread_rng()); +870 let disco = disco_shared.create_discovery(secret.public()); +871 new_endpoint(secret, disco).await +872 }; +873 let ep1_addr = NodeAddr::new(ep1.node_id()); +874 // wait for our address to be updated and thus published at least once +875 ep1.node_addr().initialized().await?; +876 let _conn = ep2.connect(ep1_addr, TEST_ALPN).await?; +877 Ok(()) +878 } +879 +880 /// This test adds an empty discovery which provides no addresses. +881 #[tokio::test] +882 #[traced_test] +883 async fn endpoint_discovery_combined_with_empty() -> Result { +884 let disco_shared = TestDiscoveryShared::default(); +885 let (ep1, _guard1) = { +886 let secret = SecretKey::generate(rand::thread_rng()); +887 let disco = disco_shared.create_discovery(secret.public()); +888 new_endpoint(secret, disco).await +889 }; +890 let (ep2, _guard2) = { +891 let secret = SecretKey::generate(rand::thread_rng()); +892 let disco1 = EmptyDiscovery; +893 let disco2 = disco_shared.create_discovery(secret.public()); +894 let mut disco = ConcurrentDiscovery::empty(); +895 disco.add(disco1); +896 disco.add(disco2); +897 new_endpoint(secret, disco).await +898 }; +899 let ep1_addr = NodeAddr::new(ep1.node_id()); +900 // wait for out address to be updated and thus published at least once +901 ep1.node_addr() +902 .initialized() +903 .await +904 .context("waiting for NodeAddr")?; +905 let _conn = ep2 +906 .connect(ep1_addr, TEST_ALPN) +907 .await +908 .context("connecting")?; +909 Ok(()) +910 } +911 +912 /// This test adds a "lying" discovery which provides a wrong address. +913 /// This is to make sure that as long as one of the discoveries returns a working address, we +914 /// will connect successfully. +915 #[tokio::test] +916 #[traced_test] +917 async fn endpoint_discovery_combined_with_empty_and_wrong() -> Result { +918 let disco_shared = TestDiscoveryShared::default(); +919 let (ep1, _guard1) = { +920 let secret = SecretKey::generate(rand::thread_rng()); +921 let disco = disco_shared.create_discovery(secret.public()); +922 new_endpoint(secret, disco).await +923 }; +924 let (ep2, _guard2) = { +925 let secret = SecretKey::generate(rand::thread_rng()); +926 let disco1 = EmptyDiscovery; +927 let disco2 = disco_shared.create_lying_discovery(secret.public()); +928 let disco3 = disco_shared.create_discovery(secret.public()); +929 let mut disco = ConcurrentDiscovery::empty(); +930 disco.add(disco1); +931 disco.add(disco2); +932 disco.add(disco3); +933 new_endpoint(secret, disco).await +934 }; +935 // wait for out address to be updated and thus published at least once +936 ep1.node_addr().initialized().await?; +937 let _conn = ep2.connect(ep1.node_id(), TEST_ALPN).await?; +938 Ok(()) +939 } +940 +941 /// This test only has the "lying" discovery. It is here to make sure that this actually fails. +942 #[tokio::test] +943 #[traced_test] +944 async fn endpoint_discovery_combined_wrong_only() -> Result { +945 let disco_shared = TestDiscoveryShared::default(); +946 let (ep1, _guard1) = { +947 let secret = SecretKey::generate(rand::thread_rng()); +948 let disco = disco_shared.create_discovery(secret.public()); +949 new_endpoint(secret, disco).await +950 }; +951 let (ep2, _guard2) = { +952 let secret = SecretKey::generate(rand::thread_rng()); +953 let disco1 = disco_shared.create_lying_discovery(secret.public()); +954 let disco = ConcurrentDiscovery::from_services(vec![Box::new(disco1)]); +955 new_endpoint(secret, disco).await +956 }; +957 // wait for out address to be updated and thus published at least once +958 ep1.node_addr().initialized().await?; +959 +960 // 10x faster test via a 3s idle timeout instead of the 30s default +961 let mut config = TransportConfig::default(); +962 config.keep_alive_interval(Some(Duration::from_secs(1))); +963 config.max_idle_timeout(Some(IdleTimeout::try_from(Duration::from_secs(3)).unwrap())); +964 let opts = ConnectOptions::new().with_transport_config(Arc::new(config)); +965 +966 let res = ep2 +967 .connect_with_opts(ep1.node_id(), TEST_ALPN, opts) +968 .await? // -> Connecting works +969 .await; // -> Connection is expected to fail +970 assert!(res.is_err()); +971 Ok(()) +972 } +973 +974 /// This test first adds a wrong address manually (e.g. from an outdated&node_id ticket). +975 /// Connect should still succeed because the discovery service will be invoked (after a delay). +976 #[tokio::test] +977 #[traced_test] +978 async fn endpoint_discovery_with_wrong_existing_addr() -> Result { +979 let disco_shared = TestDiscoveryShared::default(); +980 let (ep1, _guard1) = { +981 let secret = SecretKey::generate(rand::thread_rng()); +982 let disco = disco_shared.create_discovery(secret.public()); +983 new_endpoint(secret, disco).await +984 }; +985 let (ep2, _guard2) = { +986 let secret = SecretKey::generate(rand::thread_rng()); +987 let disco = disco_shared.create_discovery(secret.public()); +988 new_endpoint(secret, disco).await +989 }; +990 // wait for out address to be updated and thus published at least once +991 ep1.node_addr().initialized().await?; +992 let ep1_wrong_addr = NodeAddr { +993 node_id: ep1.node_id(), +994 relay_url: None, +995 direct_addresses: BTreeSet::from(["240.0.0.1:1000".parse().unwrap()]), +996 }; +997 let _conn = ep2.connect(ep1_wrong_addr, TEST_ALPN).await?; +998 Ok(()) +999 } +1000 +1001 #[tokio::test] +1002 #[traced_test] +1003 async fn endpoint_discovery_watch() -> Result { +1004 let disco_shared = TestDiscoveryShared::default(); +1005 let (ep1, _guard1) = { +1006 let secret = SecretKey::generate(rand::thread_rng()); +1007 let disco = disco_shared.create_discovery(secret.public()); +1008 new_endpoint(secret, disco).await +1009 }; +1010 let (ep2, _guard2) = { +1011 let secret = SecretKey::generate(rand::thread_rng()); +1012 let disco = disco_shared.create_discovery(secret.public()); +1013 new_endpoint(secret, disco).await +1014 }; +1015 +1016 let mut stream = ep1.discovery_stream(); +1017 +1018 // wait for ep2 node addr to be updated and connect from ep1 -> discovery via resolve +1019 ep2.node_addr().initialized().await?; +1020 let _ = ep1.connect(ep2.node_id(), TEST_ALPN).await?; +1021 +1022 let item = tokio::time::timeout(Duration::from_secs(1), stream.next()) +1023 .await +1024 .expect("timeout") +1025 .expect("stream closed") +1026 .expect("stream lagged"); +1027 assert_eq!(item.node_id(), ep2.node_id()); +1028 assert_eq!(item.provenance(), "test-disco"); 1029 -1030 // wait for ep2 node addr to be updated and connect from ep1 -> discovery via resolve -1031 ep2.node_addr().initialized().await?; -1032 let _ = ep1.connect(ep2.node_id(), TEST_ALPN).await?; -1033 -1034 let item = tokio::time::timeout(Duration::from_secs(1), stream.next()) -1035 .await -1036 .expect("timeout") -1037 .expect("stream closed") -1038 .expect("stream lagged"); -1039 assert_eq!(item.node_id(), ep2.node_id()); -1040 assert_eq!(item.provenance(), "test-disco"); -1041 -1042 // inject item into discovery passively -1043 let passive_node_id = SecretKey::generate(rand::thread_rng()).public(); -1044 let node_info = NodeInfo::new(passive_node_id); -1045 let passive_item = DiscoveryItem::new(node_info, "test-disco-passive", None); -1046 disco_shared.send_passive(passive_item.clone()); -1047 -1048 let item = tokio::time::timeout(Duration::from_secs(1), stream.next()) -1049 .await -1050 .expect("timeout") -1051 .expect("stream closed") -1052 .expect("stream lagged"); -1053 assert_eq!(item.node_id(), passive_node_id); -1054 assert_eq!(item.provenance(), "test-disco-passive"); -1055 -1056 Ok(()) -1057 } -1058 -1059 async fn new_endpoint( -1060 secret: SecretKey, -1061 disco: impl IntoDiscovery + 'static, -1062 ) -> (Endpoint, AbortOnDropHandle<Result<()>>) { -1063 let ep = Endpoint::builder() -1064 .secret_key(secret) -1065 .discovery(disco) -1066 .relay_mode(RelayMode::Disabled) -1067 .alpns(vec![TEST_ALPN.to_vec()]) -1068 .bind() -1069 .await -1070 .unwrap(); +1030 // inject item into discovery passively +1031 let passive_node_id = SecretKey::generate(rand::thread_rng()).public(); +1032 let node_info = NodeInfo::new(passive_node_id); +1033 let passive_item = DiscoveryItem::new(node_info, "test-disco-passive", None); +1034 disco_shared.send_passive(passive_item.clone()); +1035 +1036 let item = tokio::time::timeout(Duration::from_secs(1), stream.next()) +1037 .await +1038 .expect("timeout") +1039 .expect("stream closed") +1040 .expect("stream lagged"); +1041 assert_eq!(item.node_id(), passive_node_id); +1042 assert_eq!(item.provenance(), "test-disco-passive"); +1043 +1044 Ok(()) +1045 } +1046 +1047 async fn new_endpoint( +1048 secret: SecretKey, +1049 disco: impl IntoDiscovery + 'static, +1050 ) -> (Endpoint, AbortOnDropHandle<Result<()>>) { +1051 let ep = Endpoint::builder() +1052 .secret_key(secret) +1053 .discovery(disco) +1054 .relay_mode(RelayMode::Disabled) +1055 .alpns(vec![TEST_ALPN.to_vec()]) +1056 .bind() +1057 .await +1058 .unwrap(); +1059 +1060 let handle = tokio::spawn({ +1061 let ep = ep.clone(); +1062 async move { +1063 // Keep connections alive until the task is dropped. +1064 let mut connections = Vec::new(); +1065 // we skip accept() errors, they can be caused by retransmits +1066 while let Some(connecting) = ep.accept().await.and_then(|inc| inc.accept().ok()) { +1067 // Just accept incoming connections, but don't do anything with them. +1068 let conn = connecting.await.context("connecting")?; +1069 connections.push(conn); +1070 } 1071 -1072 let handle = tokio::spawn({ -1073 let ep = ep.clone(); -1074 async move { -1075 // Keep connections alive until the task is dropped. -1076 let mut connections = Vec::new(); -1077 // we skip accept() errors, they can be caused by retransmits -1078 while let Some(connecting) = ep.accept().await.and_then(|inc| inc.accept().ok()) { -1079 // Just accept incoming connections, but don't do anything with them. -1080 let conn = connecting.await.context("connecting")?; -1081 connections.push(conn); -1082 } -1083 -1084 Ok::<_, Error>(()) -1085 } -1086 }); -1087 -1088 (ep, AbortOnDropHandle::new(handle)) -1089 } -1090 -1091 fn system_time_now() -> u64 { -1092 SystemTime::now() -1093 .duration_since(SystemTime::UNIX_EPOCH) -1094 .expect("time drift") -1095 .as_micros() as u64 -1096 } -1097} -1098 -1099/// This module contains end-to-end tests for DNS node discovery. -1100/// -1101/// The tests run a minimal test DNS server to resolve against, and a minimal pkarr relay to -1102/// publish to. The DNS and pkarr servers share their state. -1103#[cfg(test)] -1104mod test_dns_pkarr { -1105 use iroh_base::{NodeAddr, SecretKey}; -1106 use iroh_relay::{node_info::UserData, RelayMap}; -1107 use n0_future::time::Duration; -1108 use n0_snafu::{Error, Result, ResultExt}; -1109 use tokio_util::task::AbortOnDropHandle; -1110 use tracing_test::traced_test; +1072 Ok::<_, Error>(()) +1073 } +1074 }); +1075 +1076 (ep, AbortOnDropHandle::new(handle)) +1077 } +1078 +1079 fn system_time_now() -> u64 { +1080 SystemTime::now() +1081 .duration_since(SystemTime::UNIX_EPOCH) +1082 .expect("time drift") +1083 .as_micros() as u64 +1084 } +1085} +1086 +1087/// This module contains end-to-end tests for DNS node discovery. +1088/// +1089/// The tests run a minimal test DNS server to resolve against, and a minimal pkarr relay to +1090/// publish to. The DNS and pkarr servers share their state. +1091#[cfg(test)] +1092mod test_dns_pkarr { +1093 use iroh_base::{NodeAddr, SecretKey}; +1094 use iroh_relay::{node_info::UserData, RelayMap}; +1095 use n0_future::time::Duration; +1096 use n0_snafu::{Error, Result, ResultExt}; +1097 use tokio_util::task::AbortOnDropHandle; +1098 use tracing_test::traced_test; +1099 +1100 use crate::{ +1101 discovery::{pkarr::PkarrPublisher, NodeData}, +1102 dns::DnsResolver, +1103 node_info::NodeInfo, +1104 test_utils::{ +1105 dns_server::run_dns_server, pkarr_dns_state::State, run_relay_server, DnsPkarrServer, +1106 }, +1107 Endpoint, RelayMode, +1108 }; +1109 +1110 const PUBLISH_TIMEOUT: Duration = Duration::from_secs(10); 1111 -1112 use crate::{ -1113 discovery::{pkarr::PkarrPublisher, NodeData}, -1114 dns::DnsResolver, -1115 node_info::NodeInfo, -1116 test_utils::{ -1117 dns_server::run_dns_server, pkarr_dns_state::State, run_relay_server, DnsPkarrServer, -1118 }, -1119 Endpoint, RelayMode, -1120 }; -1121 -1122 const PUBLISH_TIMEOUT: Duration = Duration::from_secs(10); -1123 -1124 #[tokio::test] -1125 #[traced_test] -1126 async fn dns_resolve() -> Result<()> { -1127 let origin = "testdns.example".to_string(); -1128 let state = State::new(origin.clone()); -1129 let (nameserver, _dns_drop_guard) = run_dns_server(state.clone()) -1130 .await -1131 .context("Running DNS server")?; -1132 -1133 let secret_key = SecretKey::generate(rand::thread_rng()); -1134 let node_info = NodeInfo::new(secret_key.public()) -1135 .with_relay_url(Some("https://relay.example".parse().unwrap())); -1136 let signed_packet = node_info.to_pkarr_signed_packet(&secret_key, 30)?; -1137 state -1138 .upsert(signed_packet) -1139 .context("update and insert signed packet")?; -1140 -1141 let resolver = DnsResolver::with_nameserver(nameserver); -1142 let resolved = resolver -1143 .lookup_node_by_id(&node_info.node_id, &origin) -1144 .await?; -1145 -1146 assert_eq!(resolved, node_info); +1112 #[tokio::test] +1113 #[traced_test] +1114 async fn dns_resolve() -> Result<()> { +1115 let origin = "testdns.example".to_string(); +1116 let state = State::new(origin.clone()); +1117 let (nameserver, _dns_drop_guard) = run_dns_server(state.clone()) +1118 .await +1119 .context("Running DNS server")?; +1120 +1121 let secret_key = SecretKey::generate(rand::thread_rng()); +1122 let node_info = NodeInfo::new(secret_key.public()) +1123 .with_relay_url(Some("https://relay.example".parse().unwrap())); +1124 let signed_packet = node_info.to_pkarr_signed_packet(&secret_key, 30)?; +1125 state +1126 .upsert(signed_packet) +1127 .context("update and insert signed packet")?; +1128 +1129 let resolver = DnsResolver::with_nameserver(nameserver); +1130 let resolved = resolver +1131 .lookup_node_by_id(&node_info.node_id, &origin) +1132 .await?; +1133 +1134 assert_eq!(resolved, node_info); +1135 +1136 Ok(()) +1137 } +1138 +1139 #[tokio::test] +1140 #[traced_test] +1141 async fn pkarr_publish_dns_resolve() -> Result<()> { +1142 let origin = "testdns.example".to_string(); +1143 +1144 let dns_pkarr_server = DnsPkarrServer::run_with_origin(origin.clone()) +1145 .await +1146 .context("DnsPkarrServer")?; 1147 -1148 Ok(()) -1149 } +1148 let secret_key = SecretKey::generate(rand::thread_rng()); +1149 let node_id = secret_key.public(); 1150 -1151 #[tokio::test] -1152 #[traced_test] -1153 async fn pkarr_publish_dns_resolve() -> Result<()> { -1154 let origin = "testdns.example".to_string(); -1155 -1156 let dns_pkarr_server = DnsPkarrServer::run_with_origin(origin.clone()) -1157 .await -1158 .context("DnsPkarrServer")?; -1159 -1160 let secret_key = SecretKey::generate(rand::thread_rng()); -1161 let node_id = secret_key.public(); -1162 -1163 let relay_url = Some("https://relay.example".parse().unwrap()); -1164 -1165 let resolver = DnsResolver::with_nameserver(dns_pkarr_server.nameserver); -1166 let publisher = -1167 PkarrPublisher::builder(dns_pkarr_server.pkarr_url.clone()).build(secret_key); -1168 let user_data: UserData = "foobar".parse().unwrap(); -1169 let data = NodeData::new(relay_url.clone(), Default::default()) -1170 .with_user_data(Some(user_data.clone())); -1171 // does not block, update happens in background task -1172 publisher.update_node_data(&data); -1173 // wait until our shared state received the update from pkarr publishing -1174 dns_pkarr_server -1175 .on_node(&node_id, PUBLISH_TIMEOUT) -1176 .await -1177 .context("wait for on node update")?; -1178 let resolved = resolver.lookup_node_by_id(&node_id, &origin).await?; -1179 println!("resolved {resolved:?}"); -1180 -1181 let expected_addr = NodeAddr { -1182 node_id, -1183 relay_url, -1184 direct_addresses: Default::default(), -1185 }; -1186 -1187 assert_eq!(resolved.to_node_addr(), expected_addr); -1188 assert_eq!(resolved.user_data(), Some(&user_data)); -1189 Ok(()) -1190 } -1191 -1192 const TEST_ALPN: &[u8] = b"TEST"; -1193 -1194 #[tokio::test] -1195 #[traced_test] -1196 async fn pkarr_publish_dns_discover() -> Result<()> { -1197 let dns_pkarr_server = DnsPkarrServer::run().await.context("DnsPkarrServer run")?; -1198 let (relay_map, _relay_url, _relay_guard) = run_relay_server().await?; -1199 -1200 let (ep1, _guard1) = ep_with_discovery(&relay_map, &dns_pkarr_server).await?; -1201 let (ep2, _guard2) = ep_with_discovery(&relay_map, &dns_pkarr_server).await?; -1202 -1203 // wait until our shared state received the update from pkarr publishing -1204 dns_pkarr_server -1205 .on_node(&ep1.node_id(), PUBLISH_TIMEOUT) -1206 .await -1207 .context("wait for on node update")?; -1208 -1209 // we connect only by node id! -1210 let res = ep2.connect(ep1.node_id(), TEST_ALPN).await; -1211 assert!(res.is_ok(), "connection established"); -1212 Ok(()) -1213 } -1214 -1215 async fn ep_with_discovery( -1216 relay_map: &RelayMap, -1217 dns_pkarr_server: &DnsPkarrServer, -1218 ) -> Result<(Endpoint, AbortOnDropHandle<Result<()>>)> { -1219 let secret_key = SecretKey::generate(rand::thread_rng()); -1220 let ep = Endpoint::builder() -1221 .relay_mode(RelayMode::Custom(relay_map.clone())) -1222 .insecure_skip_relay_cert_verify(true) -1223 .secret_key(secret_key.clone()) -1224 .alpns(vec![TEST_ALPN.to_vec()]) -1225 .dns_resolver(dns_pkarr_server.dns_resolver()) -1226 .discovery(dns_pkarr_server.discovery(secret_key)) -1227 .bind() -1228 .await?; +1151 let relay_url = Some("https://relay.example".parse().unwrap()); +1152 +1153 let resolver = DnsResolver::with_nameserver(dns_pkarr_server.nameserver); +1154 let publisher = +1155 PkarrPublisher::builder(dns_pkarr_server.pkarr_url.clone()).build(secret_key); +1156 let user_data: UserData = "foobar".parse().unwrap(); +1157 let data = NodeData::new(relay_url.clone(), Default::default()) +1158 .with_user_data(Some(user_data.clone())); +1159 // does not block, update happens in background task +1160 publisher.update_node_data(&data); +1161 // wait until our shared state received the update from pkarr publishing +1162 dns_pkarr_server +1163 .on_node(&node_id, PUBLISH_TIMEOUT) +1164 .await +1165 .context("wait for on node update")?; +1166 let resolved = resolver.lookup_node_by_id(&node_id, &origin).await?; +1167 println!("resolved {resolved:?}"); +1168 +1169 let expected_addr = NodeAddr { +1170 node_id, +1171 relay_url, +1172 direct_addresses: Default::default(), +1173 }; +1174 +1175 assert_eq!(resolved.to_node_addr(), expected_addr); +1176 assert_eq!(resolved.user_data(), Some(&user_data)); +1177 Ok(()) +1178 } +1179 +1180 const TEST_ALPN: &[u8] = b"TEST"; +1181 +1182 #[tokio::test] +1183 #[traced_test] +1184 async fn pkarr_publish_dns_discover() -> Result<()> { +1185 let dns_pkarr_server = DnsPkarrServer::run().await.context("DnsPkarrServer run")?; +1186 let (relay_map, _relay_url, _relay_guard) = run_relay_server().await?; +1187 +1188 let (ep1, _guard1) = ep_with_discovery(&relay_map, &dns_pkarr_server).await?; +1189 let (ep2, _guard2) = ep_with_discovery(&relay_map, &dns_pkarr_server).await?; +1190 +1191 // wait until our shared state received the update from pkarr publishing +1192 dns_pkarr_server +1193 .on_node(&ep1.node_id(), PUBLISH_TIMEOUT) +1194 .await +1195 .context("wait for on node update")?; +1196 +1197 // we connect only by node id! +1198 let _conn = ep2.connect(ep1.node_id(), TEST_ALPN).await?; +1199 Ok(()) +1200 } +1201 +1202 async fn ep_with_discovery( +1203 relay_map: &RelayMap, +1204 dns_pkarr_server: &DnsPkarrServer, +1205 ) -> Result<(Endpoint, AbortOnDropHandle<Result<()>>)> { +1206 let secret_key = SecretKey::generate(rand::thread_rng()); +1207 let ep = Endpoint::builder() +1208 .relay_mode(RelayMode::Custom(relay_map.clone())) +1209 .insecure_skip_relay_cert_verify(true) +1210 .secret_key(secret_key.clone()) +1211 .alpns(vec![TEST_ALPN.to_vec()]) +1212 .dns_resolver(dns_pkarr_server.dns_resolver()) +1213 .discovery(dns_pkarr_server.discovery(secret_key)) +1214 .bind() +1215 .await?; +1216 +1217 let handle = tokio::spawn({ +1218 let ep = ep.clone(); +1219 async move { +1220 // we skip accept() errors, they can be caused by retransmits +1221 while let Some(connecting) = ep.accept().await.and_then(|inc| inc.accept().ok()) { +1222 let _conn = connecting.await.context("connecting")?; +1223 // Just accept incoming connections, but don't do anything with them. +1224 } +1225 +1226 Ok::<_, Error>(()) +1227 } +1228 }); 1229 -1230 let handle = tokio::spawn({ -1231 let ep = ep.clone(); -1232 async move { -1233 // we skip accept() errors, they can be caused by retransmits -1234 while let Some(connecting) = ep.accept().await.and_then(|inc| inc.accept().ok()) { -1235 let _conn = connecting.await.context("connecting")?; -1236 // Just accept incoming connections, but don't do anything with them. -1237 } -1238 -1239 Ok::<_, Error>(()) -1240 } -1241 }); -1242 -1243 Ok((ep, AbortOnDropHandle::new(handle))) -1244 } -1245}
    \ No newline at end of file +1230 Ok((ep, AbortOnDropHandle::new(handle))) +1231 } +1232}
    \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/discovery/mdns.rs.html b/pr/3327/docs/src/iroh/discovery/mdns.rs.html index e08cc3c609..8a3098d061 100644 --- a/pr/3327/docs/src/iroh/discovery/mdns.rs.html +++ b/pr/3327/docs/src/iroh/discovery/mdns.rs.html @@ -42,482 +42,480 @@ 42 task::{self, AbortOnDropHandle, JoinSet}, 43 time::{self, Duration}, 44}; -45use swarm_discovery::{Discoverer, DropGuard, IpClass, Peer}; -46use tokio::sync::mpsc::{self, error::TrySendError}; -47use tracing::{debug, error, info_span, trace, warn, Instrument}; -48 -49use super::{DiscoveryContext, DiscoveryError, IntoDiscovery, IntoDiscoveryError}; -50use crate::{ -51 discovery::{Discovery, DiscoveryItem, NodeData, NodeInfo}, -52 watcher::{Watchable, Watcher as _}, -53}; -54 -55/// The n0 local swarm node discovery name -56const N0_LOCAL_SWARM: &str = "iroh.local.swarm"; -57 -58/// Name of this discovery service. +45use n0_watcher::{Watchable, Watcher as _}; +46use swarm_discovery::{Discoverer, DropGuard, IpClass, Peer}; +47use tokio::sync::mpsc::{self, error::TrySendError}; +48use tracing::{debug, error, info_span, trace, warn, Instrument}; +49 +50use super::{DiscoveryContext, DiscoveryError, IntoDiscovery, IntoDiscoveryError}; +51use crate::discovery::{Discovery, DiscoveryItem, NodeData, NodeInfo}; +52 +53/// The n0 local swarm node discovery name +54const N0_LOCAL_SWARM: &str = "iroh.local.swarm"; +55 +56/// Name of this discovery service. +57/// +58/// Used as the `provenance` field in [`DiscoveryItem`]s. 59/// -60/// Used as the `provenance` field in [`DiscoveryItem`]s. -61/// -62/// Used in the [`crate::endpoint::Source::Discovery`] enum variant as the `name`. -63pub const NAME: &str = "local.swarm.discovery"; -64 -65/// The key of the attribute under which the `UserData` is stored in -66/// the TXT record supported by swarm-discovery. -67const USER_DATA_ATTRIBUTE: &str = "user-data"; -68 -69/// How long we will wait before we stop sending discovery items -70const DISCOVERY_DURATION: Duration = Duration::from_secs(10); -71 -72/// Discovery using `swarm-discovery`, a variation on mdns -73#[derive(Debug)] -74pub struct MdnsDiscovery { -75 #[allow(dead_code)] -76 handle: AbortOnDropHandle<()>, -77 sender: mpsc::Sender<Message>, -78 /// When `local_addrs` changes, we re-publish our info. -79 local_addrs: Watchable<Option<NodeData>>, -80} -81 -82#[derive(Debug)] -83enum Message { -84 Discovery(String, Peer), -85 Resolve(NodeId, mpsc::Sender<Result<DiscoveryItem, DiscoveryError>>), -86 Timeout(NodeId, usize), -87 Subscribe(mpsc::Sender<DiscoveryItem>), -88} -89 -90/// Manages the list of subscribers that are subscribed to this discovery service. -91#[derive(Debug)] -92struct Subscribers(Vec<mpsc::Sender<DiscoveryItem>>); -93 -94impl Subscribers { -95 fn new() -> Self { -96 Self(vec![]) -97 } -98 -99 /// Add the subscriber to the list of subscribers -100 fn push(&mut self, subscriber: mpsc::Sender<DiscoveryItem>) { -101 self.0.push(subscriber); -102 } -103 -104 /// Sends the `node_id` and `item` to each subscriber. -105 /// -106 /// Cleans up any subscribers that have been dropped. -107 fn send(&mut self, item: DiscoveryItem) { -108 let mut clean_up = vec![]; -109 for (i, subscriber) in self.0.iter().enumerate() { -110 // assume subscriber was dropped -111 if let Err(err) = subscriber.try_send(item.clone()) { -112 match err { -113 TrySendError::Full(_) => { -114 warn!( -115 ?item, -116 idx = i, -117 "local swarm discovery subscriber is blocked, dropping item" -118 ) -119 } -120 TrySendError::Closed(_) => clean_up.push(i), -121 } -122 } -123 } -124 for i in clean_up.into_iter().rev() { -125 self.0.swap_remove(i); -126 } -127 } -128} -129 -130/// Builder for [`MdnsDiscovery`]. -131#[derive(Debug)] -132pub struct MdnsDiscoveryBuilder; -133 -134impl IntoDiscovery for MdnsDiscoveryBuilder { -135 fn into_discovery( -136 self, -137 context: &DiscoveryContext, -138 ) -> Result<impl Discovery, IntoDiscoveryError> { -139 MdnsDiscovery::new(context.node_id()) -140 } -141} -142 -143impl MdnsDiscovery { -144 /// Returns a [`MdnsDiscoveryBuilder`] that implements [`IntoDiscovery`]. -145 pub fn builder() -> MdnsDiscoveryBuilder { -146 MdnsDiscoveryBuilder -147 } -148 -149 /// Create a new [`MdnsDiscovery`] Service. +60/// Used in the [`crate::endpoint::Source::Discovery`] enum variant as the `name`. +61pub const NAME: &str = "local.swarm.discovery"; +62 +63/// The key of the attribute under which the `UserData` is stored in +64/// the TXT record supported by swarm-discovery. +65const USER_DATA_ATTRIBUTE: &str = "user-data"; +66 +67/// How long we will wait before we stop sending discovery items +68const DISCOVERY_DURATION: Duration = Duration::from_secs(10); +69 +70/// Discovery using `swarm-discovery`, a variation on mdns +71#[derive(Debug)] +72pub struct MdnsDiscovery { +73 #[allow(dead_code)] +74 handle: AbortOnDropHandle<()>, +75 sender: mpsc::Sender<Message>, +76 /// When `local_addrs` changes, we re-publish our info. +77 local_addrs: Watchable<Option<NodeData>>, +78} +79 +80#[derive(Debug)] +81enum Message { +82 Discovery(String, Peer), +83 Resolve(NodeId, mpsc::Sender<Result<DiscoveryItem, DiscoveryError>>), +84 Timeout(NodeId, usize), +85 Subscribe(mpsc::Sender<DiscoveryItem>), +86} +87 +88/// Manages the list of subscribers that are subscribed to this discovery service. +89#[derive(Debug)] +90struct Subscribers(Vec<mpsc::Sender<DiscoveryItem>>); +91 +92impl Subscribers { +93 fn new() -> Self { +94 Self(vec![]) +95 } +96 +97 /// Add the subscriber to the list of subscribers +98 fn push(&mut self, subscriber: mpsc::Sender<DiscoveryItem>) { +99 self.0.push(subscriber); +100 } +101 +102 /// Sends the `node_id` and `item` to each subscriber. +103 /// +104 /// Cleans up any subscribers that have been dropped. +105 fn send(&mut self, item: DiscoveryItem) { +106 let mut clean_up = vec![]; +107 for (i, subscriber) in self.0.iter().enumerate() { +108 // assume subscriber was dropped +109 if let Err(err) = subscriber.try_send(item.clone()) { +110 match err { +111 TrySendError::Full(_) => { +112 warn!( +113 ?item, +114 idx = i, +115 "local swarm discovery subscriber is blocked, dropping item" +116 ) +117 } +118 TrySendError::Closed(_) => clean_up.push(i), +119 } +120 } +121 } +122 for i in clean_up.into_iter().rev() { +123 self.0.swap_remove(i); +124 } +125 } +126} +127 +128/// Builder for [`MdnsDiscovery`]. +129#[derive(Debug)] +130pub struct MdnsDiscoveryBuilder; +131 +132impl IntoDiscovery for MdnsDiscoveryBuilder { +133 fn into_discovery( +134 self, +135 context: &DiscoveryContext, +136 ) -> Result<impl Discovery, IntoDiscoveryError> { +137 MdnsDiscovery::new(context.node_id()) +138 } +139} +140 +141impl MdnsDiscovery { +142 /// Returns a [`MdnsDiscoveryBuilder`] that implements [`IntoDiscovery`]. +143 pub fn builder() -> MdnsDiscoveryBuilder { +144 MdnsDiscoveryBuilder +145 } +146 +147 /// Create a new [`MdnsDiscovery`] Service. +148 /// +149 /// This starts a [`Discoverer`] that broadcasts your addresses and receives addresses from other nodes in your local network. 150 /// -151 /// This starts a [`Discoverer`] that broadcasts your addresses and receives addresses from other nodes in your local network. -152 /// -153 /// # Errors -154 /// Returns an error if the network does not allow ipv4 OR ipv6. -155 /// -156 /// # Panics -157 /// This relies on [`tokio::runtime::Handle::current`] and will panic if called outside of the context of a tokio runtime. -158 pub fn new(node_id: NodeId) -> Result<Self, IntoDiscoveryError> { -159 debug!("Creating new MdnsDiscovery service"); -160 let (send, mut recv) = mpsc::channel(64); -161 let task_sender = send.clone(); -162 let rt = tokio::runtime::Handle::current(); -163 let discovery = -164 MdnsDiscovery::spawn_discoverer(node_id, task_sender.clone(), BTreeSet::new(), &rt)?; -165 -166 let local_addrs: Watchable<Option<NodeData>> = Watchable::default(); -167 let mut addrs_change = local_addrs.watch(); -168 let discovery_fut = async move { -169 let mut node_addrs: HashMap<PublicKey, Peer> = HashMap::default(); -170 let mut subscribers = Subscribers::new(); -171 let mut last_id = 0; -172 let mut senders: HashMap< -173 PublicKey, -174 HashMap<usize, mpsc::Sender<Result<DiscoveryItem, DiscoveryError>>>, -175 > = HashMap::default(); -176 let mut timeouts = JoinSet::new(); -177 loop { -178 trace!(?node_addrs, "MdnsDiscovery Service loop tick"); -179 let msg = tokio::select! { -180 msg = recv.recv() => { -181 msg -182 } -183 Ok(Some(data)) = addrs_change.updated() => { -184 tracing::trace!(?data, "MdnsDiscovery address changed"); -185 discovery.remove_all(); -186 let addrs = -187 MdnsDiscovery::socketaddrs_to_addrs(data.direct_addresses()); -188 for addr in addrs { -189 discovery.add(addr.0, addr.1) -190 } -191 if let Some(user_data) = data.user_data() { -192 if let Err(err) = discovery.set_txt_attribute(USER_DATA_ATTRIBUTE.to_string(), Some(user_data.to_string())) { -193 warn!("Failed to set the user-defined data in local swarm discovery: {err:?}"); -194 } -195 } -196 continue; -197 } -198 }; -199 let msg = match msg { -200 None => { -201 error!("MdnsDiscovery channel closed"); -202 error!("closing MdnsDiscovery"); -203 timeouts.abort_all(); -204 return; -205 } -206 Some(msg) => msg, -207 }; -208 match msg { -209 Message::Discovery(discovered_node_id, peer_info) => { -210 trace!( -211 ?discovered_node_id, -212 ?peer_info, -213 "MdnsDiscovery Message::Discovery" -214 ); -215 let discovered_node_id = match PublicKey::from_str(&discovered_node_id) { -216 Ok(node_id) => node_id, -217 Err(e) => { -218 warn!( -219 discovered_node_id, -220 "couldn't parse node_id from mdns discovery service: {e:?}" -221 ); -222 continue; -223 } -224 }; -225 -226 if discovered_node_id == node_id { -227 continue; -228 } -229 -230 if peer_info.is_expiry() { -231 trace!( -232 ?discovered_node_id, -233 "removing node from MdnsDiscovery address book" -234 ); -235 node_addrs.remove(&discovered_node_id); -236 continue; -237 } -238 -239 let entry = node_addrs.entry(discovered_node_id); -240 if let std::collections::hash_map::Entry::Occupied(ref entry) = entry { -241 if entry.get() == &peer_info { -242 // this is a republish we already know about -243 continue; -244 } -245 } -246 -247 debug!( -248 ?discovered_node_id, -249 ?peer_info, -250 "adding node to MdnsDiscovery address book" -251 ); -252 -253 let mut resolved = false; -254 let item = peer_to_discovery_item(&peer_info, &discovered_node_id); -255 if let Some(senders) = senders.get(&discovered_node_id) { -256 trace!(?item, senders = senders.len(), "sending DiscoveryItem"); -257 resolved = true; -258 for sender in senders.values() { -259 sender.send(Ok(item.clone())).await.ok(); -260 } -261 } -262 entry.or_insert(peer_info); -263 -264 // only send nodes to the `subscriber` if they weren't explicitly resolved -265 // in other words, nodes sent to the `subscribers` should only be the ones that -266 // have been "passively" discovered -267 if !resolved { -268 subscribers.send(item); -269 } -270 } -271 Message::Resolve(node_id, sender) => { -272 let id = last_id + 1; -273 last_id = id; -274 trace!(?node_id, "MdnsDiscovery Message::SendAddrs"); -275 if let Some(peer_info) = node_addrs.get(&node_id) { -276 let item = peer_to_discovery_item(peer_info, &node_id); -277 debug!(?item, "sending DiscoveryItem"); -278 sender.send(Ok(item)).await.ok(); -279 } -280 if let Some(senders_for_node_id) = senders.get_mut(&node_id) { -281 senders_for_node_id.insert(id, sender); -282 } else { -283 let mut senders_for_node_id = HashMap::new(); -284 senders_for_node_id.insert(id, sender); -285 senders.insert(node_id, senders_for_node_id); -286 } -287 let timeout_sender = task_sender.clone(); -288 timeouts.spawn(async move { -289 time::sleep(DISCOVERY_DURATION).await; -290 trace!(?node_id, "discovery timeout"); -291 timeout_sender -292 .send(Message::Timeout(node_id, id)) -293 .await -294 .ok(); -295 }); -296 } -297 Message::Timeout(node_id, id) => { -298 trace!(?node_id, "MdnsDiscovery Message::Timeout"); -299 if let Some(senders_for_node_id) = senders.get_mut(&node_id) { -300 senders_for_node_id.remove(&id); -301 if senders_for_node_id.is_empty() { -302 senders.remove(&node_id); -303 } -304 } -305 } -306 Message::Subscribe(subscriber) => { -307 trace!("MdnsDiscovery Message::Subscribe"); -308 subscribers.push(subscriber); -309 } -310 } -311 } -312 }; -313 let handle = task::spawn(discovery_fut.instrument(info_span!("swarm-discovery.actor"))); -314 Ok(Self { -315 handle: AbortOnDropHandle::new(handle), -316 sender: send, -317 local_addrs, -318 }) -319 } -320 -321 fn spawn_discoverer( -322 node_id: PublicKey, -323 sender: mpsc::Sender<Message>, -324 socketaddrs: BTreeSet<SocketAddr>, -325 rt: &tokio::runtime::Handle, -326 ) -> Result<DropGuard, IntoDiscoveryError> { -327 let spawn_rt = rt.clone(); -328 let callback = move |node_id: &str, peer: &Peer| { -329 trace!( -330 node_id, -331 ?peer, -332 "Received peer information from MdnsDiscovery" -333 ); -334 -335 let sender = sender.clone(); -336 let node_id = node_id.to_string(); -337 let peer = peer.clone(); -338 spawn_rt.spawn(async move { -339 sender.send(Message::Discovery(node_id, peer)).await.ok(); -340 }); -341 }; -342 let addrs = MdnsDiscovery::socketaddrs_to_addrs(&socketaddrs); -343 let node_id_str = data_encoding::BASE32_NOPAD -344 .encode(node_id.as_bytes()) -345 .to_ascii_lowercase(); -346 let mut discoverer = Discoverer::new_interactive(N0_LOCAL_SWARM.to_string(), node_id_str) -347 .with_callback(callback) -348 .with_ip_class(IpClass::Auto); -349 for addr in addrs { -350 discoverer = discoverer.with_addrs(addr.0, addr.1); -351 } -352 discoverer -353 .spawn(rt) -354 .map_err(|e| IntoDiscoveryError::from_err_box("mdns", e.into_boxed_dyn_error())) -355 } -356 -357 fn socketaddrs_to_addrs(socketaddrs: &BTreeSet<SocketAddr>) -> HashMap<u16, Vec<IpAddr>> { -358 let mut addrs: HashMap<u16, Vec<IpAddr>> = HashMap::default(); -359 for socketaddr in socketaddrs { -360 addrs -361 .entry(socketaddr.port()) -362 .and_modify(|a| a.push(socketaddr.ip())) -363 .or_insert(vec![socketaddr.ip()]); -364 } -365 addrs -366 } -367} -368 -369fn peer_to_discovery_item(peer: &Peer, node_id: &NodeId) -> DiscoveryItem { -370 let direct_addresses: BTreeSet<SocketAddr> = peer -371 .addrs() -372 .iter() -373 .map(|(ip, port)| SocketAddr::new(*ip, *port)) -374 .collect(); -375 // Get the user-defined data from the resolved peer info. We expect an attribute with a value -376 // that parses as `UserData`. Otherwise, omit. -377 let user_data = if let Some(Some(user_data)) = peer.txt_attribute(USER_DATA_ATTRIBUTE) { -378 match user_data.parse() { -379 Err(err) => { -380 debug!("failed to parse user data from TXT attribute: {err}"); -381 None -382 } -383 Ok(data) => Some(data), -384 } -385 } else { -386 None -387 }; -388 let node_info = NodeInfo::new(*node_id) -389 .with_direct_addresses(direct_addresses) -390 .with_user_data(user_data); -391 DiscoveryItem::new(node_info, NAME, None) -392} -393 -394impl Discovery for MdnsDiscovery { -395 fn resolve(&self, node_id: NodeId) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { -396 use futures_util::FutureExt; -397 -398 let (send, recv) = mpsc::channel(20); -399 let discovery_sender = self.sender.clone(); -400 let stream = async move { -401 discovery_sender -402 .send(Message::Resolve(node_id, send)) -403 .await -404 .ok(); -405 tokio_stream::wrappers::ReceiverStream::new(recv) -406 }; -407 Some(Box::pin(stream.flatten_stream())) -408 } -409 -410 fn publish(&self, data: &NodeData) { -411 self.local_addrs.set(Some(data.clone())).ok(); -412 } -413 -414 fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>> { -415 use futures_util::FutureExt; -416 -417 let (sender, recv) = mpsc::channel(20); -418 let discovery_sender = self.sender.clone(); -419 let stream = async move { -420 discovery_sender.send(Message::Subscribe(sender)).await.ok(); -421 tokio_stream::wrappers::ReceiverStream::new(recv) -422 }; -423 Some(Box::pin(stream.flatten_stream())) -424 } -425} -426 -427#[cfg(test)] -428mod tests { -429 -430 /// This module's name signals nextest to run test in a single thread (no other concurrent -431 /// tests) -432 mod run_in_isolation { -433 use iroh_base::SecretKey; -434 use n0_future::StreamExt; -435 use n0_snafu::{Error, Result, ResultExt}; -436 use snafu::whatever; -437 use tracing_test::traced_test; -438 -439 use super::super::*; -440 use crate::discovery::UserData; -441 -442 #[tokio::test] -443 #[traced_test] -444 async fn mdns_publish_resolve() -> Result { -445 let (_, discovery_a) = make_discoverer()?; -446 let (node_id_b, discovery_b) = make_discoverer()?; -447 -448 // make addr info for discoverer b -449 let user_data: UserData = "foobar".parse()?; -450 let node_data = NodeData::new(None, BTreeSet::from(["0.0.0.0:11111".parse().unwrap()])) -451 .with_user_data(Some(user_data.clone())); -452 println!("info {node_data:?}"); -453 -454 // resolve twice to ensure we can create separate streams for the same node_id -455 let mut s1 = discovery_a.resolve(node_id_b).unwrap(); -456 let mut s2 = discovery_a.resolve(node_id_b).unwrap(); -457 -458 tracing::debug!(?node_id_b, "Discovering node id b"); -459 // publish discovery_b's address -460 discovery_b.publish(&node_data); -461 let s1_res = tokio::time::timeout(Duration::from_secs(5), s1.next()) -462 .await -463 .context("timeout")? -464 .unwrap()?; -465 let s2_res = tokio::time::timeout(Duration::from_secs(5), s2.next()) -466 .await -467 .context("timeout")? -468 .unwrap()?; -469 assert_eq!(s1_res.node_info().data, node_data); -470 assert_eq!(s2_res.node_info().data, node_data); -471 -472 Ok(()) -473 } -474 -475 #[tokio::test] -476 #[traced_test] -477 async fn mdns_subscribe() -> Result { -478 let num_nodes = 5; -479 let mut node_ids = BTreeSet::new(); -480 let mut discoverers = vec![]; -481 -482 let (_, discovery) = make_discoverer()?; -483 let node_data = NodeData::new(None, BTreeSet::from(["0.0.0.0:11111".parse().unwrap()])); -484 -485 for i in 0..num_nodes { -486 let (node_id, discovery) = make_discoverer()?; -487 let user_data: UserData = format!("node{i}").parse()?; -488 let node_data = node_data.clone().with_user_data(Some(user_data.clone())); -489 node_ids.insert((node_id, Some(user_data))); -490 discovery.publish(&node_data); -491 discoverers.push(discovery); -492 } +151 /// # Errors +152 /// Returns an error if the network does not allow ipv4 OR ipv6. +153 /// +154 /// # Panics +155 /// This relies on [`tokio::runtime::Handle::current`] and will panic if called outside of the context of a tokio runtime. +156 pub fn new(node_id: NodeId) -> Result<Self, IntoDiscoveryError> { +157 debug!("Creating new MdnsDiscovery service"); +158 let (send, mut recv) = mpsc::channel(64); +159 let task_sender = send.clone(); +160 let rt = tokio::runtime::Handle::current(); +161 let discovery = +162 MdnsDiscovery::spawn_discoverer(node_id, task_sender.clone(), BTreeSet::new(), &rt)?; +163 +164 let local_addrs: Watchable<Option<NodeData>> = Watchable::default(); +165 let mut addrs_change = local_addrs.watch(); +166 let discovery_fut = async move { +167 let mut node_addrs: HashMap<PublicKey, Peer> = HashMap::default(); +168 let mut subscribers = Subscribers::new(); +169 let mut last_id = 0; +170 let mut senders: HashMap< +171 PublicKey, +172 HashMap<usize, mpsc::Sender<Result<DiscoveryItem, DiscoveryError>>>, +173 > = HashMap::default(); +174 let mut timeouts = JoinSet::new(); +175 loop { +176 trace!(?node_addrs, "MdnsDiscovery Service loop tick"); +177 let msg = tokio::select! { +178 msg = recv.recv() => { +179 msg +180 } +181 Ok(Some(data)) = addrs_change.updated() => { +182 tracing::trace!(?data, "MdnsDiscovery address changed"); +183 discovery.remove_all(); +184 let addrs = +185 MdnsDiscovery::socketaddrs_to_addrs(data.direct_addresses()); +186 for addr in addrs { +187 discovery.add(addr.0, addr.1) +188 } +189 if let Some(user_data) = data.user_data() { +190 if let Err(err) = discovery.set_txt_attribute(USER_DATA_ATTRIBUTE.to_string(), Some(user_data.to_string())) { +191 warn!("Failed to set the user-defined data in local swarm discovery: {err:?}"); +192 } +193 } +194 continue; +195 } +196 }; +197 let msg = match msg { +198 None => { +199 error!("MdnsDiscovery channel closed"); +200 error!("closing MdnsDiscovery"); +201 timeouts.abort_all(); +202 return; +203 } +204 Some(msg) => msg, +205 }; +206 match msg { +207 Message::Discovery(discovered_node_id, peer_info) => { +208 trace!( +209 ?discovered_node_id, +210 ?peer_info, +211 "MdnsDiscovery Message::Discovery" +212 ); +213 let discovered_node_id = match PublicKey::from_str(&discovered_node_id) { +214 Ok(node_id) => node_id, +215 Err(e) => { +216 warn!( +217 discovered_node_id, +218 "couldn't parse node_id from mdns discovery service: {e:?}" +219 ); +220 continue; +221 } +222 }; +223 +224 if discovered_node_id == node_id { +225 continue; +226 } +227 +228 if peer_info.is_expiry() { +229 trace!( +230 ?discovered_node_id, +231 "removing node from MdnsDiscovery address book" +232 ); +233 node_addrs.remove(&discovered_node_id); +234 continue; +235 } +236 +237 let entry = node_addrs.entry(discovered_node_id); +238 if let std::collections::hash_map::Entry::Occupied(ref entry) = entry { +239 if entry.get() == &peer_info { +240 // this is a republish we already know about +241 continue; +242 } +243 } +244 +245 debug!( +246 ?discovered_node_id, +247 ?peer_info, +248 "adding node to MdnsDiscovery address book" +249 ); +250 +251 let mut resolved = false; +252 let item = peer_to_discovery_item(&peer_info, &discovered_node_id); +253 if let Some(senders) = senders.get(&discovered_node_id) { +254 trace!(?item, senders = senders.len(), "sending DiscoveryItem"); +255 resolved = true; +256 for sender in senders.values() { +257 sender.send(Ok(item.clone())).await.ok(); +258 } +259 } +260 entry.or_insert(peer_info); +261 +262 // only send nodes to the `subscriber` if they weren't explicitly resolved +263 // in other words, nodes sent to the `subscribers` should only be the ones that +264 // have been "passively" discovered +265 if !resolved { +266 subscribers.send(item); +267 } +268 } +269 Message::Resolve(node_id, sender) => { +270 let id = last_id + 1; +271 last_id = id; +272 trace!(?node_id, "MdnsDiscovery Message::SendAddrs"); +273 if let Some(peer_info) = node_addrs.get(&node_id) { +274 let item = peer_to_discovery_item(peer_info, &node_id); +275 debug!(?item, "sending DiscoveryItem"); +276 sender.send(Ok(item)).await.ok(); +277 } +278 if let Some(senders_for_node_id) = senders.get_mut(&node_id) { +279 senders_for_node_id.insert(id, sender); +280 } else { +281 let mut senders_for_node_id = HashMap::new(); +282 senders_for_node_id.insert(id, sender); +283 senders.insert(node_id, senders_for_node_id); +284 } +285 let timeout_sender = task_sender.clone(); +286 timeouts.spawn(async move { +287 time::sleep(DISCOVERY_DURATION).await; +288 trace!(?node_id, "discovery timeout"); +289 timeout_sender +290 .send(Message::Timeout(node_id, id)) +291 .await +292 .ok(); +293 }); +294 } +295 Message::Timeout(node_id, id) => { +296 trace!(?node_id, "MdnsDiscovery Message::Timeout"); +297 if let Some(senders_for_node_id) = senders.get_mut(&node_id) { +298 senders_for_node_id.remove(&id); +299 if senders_for_node_id.is_empty() { +300 senders.remove(&node_id); +301 } +302 } +303 } +304 Message::Subscribe(subscriber) => { +305 trace!("MdnsDiscovery Message::Subscribe"); +306 subscribers.push(subscriber); +307 } +308 } +309 } +310 }; +311 let handle = task::spawn(discovery_fut.instrument(info_span!("swarm-discovery.actor"))); +312 Ok(Self { +313 handle: AbortOnDropHandle::new(handle), +314 sender: send, +315 local_addrs, +316 }) +317 } +318 +319 fn spawn_discoverer( +320 node_id: PublicKey, +321 sender: mpsc::Sender<Message>, +322 socketaddrs: BTreeSet<SocketAddr>, +323 rt: &tokio::runtime::Handle, +324 ) -> Result<DropGuard, IntoDiscoveryError> { +325 let spawn_rt = rt.clone(); +326 let callback = move |node_id: &str, peer: &Peer| { +327 trace!( +328 node_id, +329 ?peer, +330 "Received peer information from MdnsDiscovery" +331 ); +332 +333 let sender = sender.clone(); +334 let node_id = node_id.to_string(); +335 let peer = peer.clone(); +336 spawn_rt.spawn(async move { +337 sender.send(Message::Discovery(node_id, peer)).await.ok(); +338 }); +339 }; +340 let addrs = MdnsDiscovery::socketaddrs_to_addrs(&socketaddrs); +341 let node_id_str = data_encoding::BASE32_NOPAD +342 .encode(node_id.as_bytes()) +343 .to_ascii_lowercase(); +344 let mut discoverer = Discoverer::new_interactive(N0_LOCAL_SWARM.to_string(), node_id_str) +345 .with_callback(callback) +346 .with_ip_class(IpClass::Auto); +347 for addr in addrs { +348 discoverer = discoverer.with_addrs(addr.0, addr.1); +349 } +350 discoverer +351 .spawn(rt) +352 .map_err(|e| IntoDiscoveryError::from_err_box("mdns", e.into_boxed_dyn_error())) +353 } +354 +355 fn socketaddrs_to_addrs(socketaddrs: &BTreeSet<SocketAddr>) -> HashMap<u16, Vec<IpAddr>> { +356 let mut addrs: HashMap<u16, Vec<IpAddr>> = HashMap::default(); +357 for socketaddr in socketaddrs { +358 addrs +359 .entry(socketaddr.port()) +360 .and_modify(|a| a.push(socketaddr.ip())) +361 .or_insert(vec![socketaddr.ip()]); +362 } +363 addrs +364 } +365} +366 +367fn peer_to_discovery_item(peer: &Peer, node_id: &NodeId) -> DiscoveryItem { +368 let direct_addresses: BTreeSet<SocketAddr> = peer +369 .addrs() +370 .iter() +371 .map(|(ip, port)| SocketAddr::new(*ip, *port)) +372 .collect(); +373 // Get the user-defined data from the resolved peer info. We expect an attribute with a value +374 // that parses as `UserData`. Otherwise, omit. +375 let user_data = if let Some(Some(user_data)) = peer.txt_attribute(USER_DATA_ATTRIBUTE) { +376 match user_data.parse() { +377 Err(err) => { +378 debug!("failed to parse user data from TXT attribute: {err}"); +379 None +380 } +381 Ok(data) => Some(data), +382 } +383 } else { +384 None +385 }; +386 let node_info = NodeInfo::new(*node_id) +387 .with_direct_addresses(direct_addresses) +388 .with_user_data(user_data); +389 DiscoveryItem::new(node_info, NAME, None) +390} +391 +392impl Discovery for MdnsDiscovery { +393 fn resolve(&self, node_id: NodeId) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { +394 use futures_util::FutureExt; +395 +396 let (send, recv) = mpsc::channel(20); +397 let discovery_sender = self.sender.clone(); +398 let stream = async move { +399 discovery_sender +400 .send(Message::Resolve(node_id, send)) +401 .await +402 .ok(); +403 tokio_stream::wrappers::ReceiverStream::new(recv) +404 }; +405 Some(Box::pin(stream.flatten_stream())) +406 } +407 +408 fn publish(&self, data: &NodeData) { +409 self.local_addrs.set(Some(data.clone())).ok(); +410 } +411 +412 fn subscribe(&self) -> Option<BoxStream<DiscoveryItem>> { +413 use futures_util::FutureExt; +414 +415 let (sender, recv) = mpsc::channel(20); +416 let discovery_sender = self.sender.clone(); +417 let stream = async move { +418 discovery_sender.send(Message::Subscribe(sender)).await.ok(); +419 tokio_stream::wrappers::ReceiverStream::new(recv) +420 }; +421 Some(Box::pin(stream.flatten_stream())) +422 } +423} +424 +425#[cfg(test)] +426mod tests { +427 +428 /// This module's name signals nextest to run test in a single thread (no other concurrent +429 /// tests) +430 mod run_in_isolation { +431 use iroh_base::SecretKey; +432 use n0_future::StreamExt; +433 use n0_snafu::{Error, Result, ResultExt}; +434 use snafu::whatever; +435 use tracing_test::traced_test; +436 +437 use super::super::*; +438 use crate::discovery::UserData; +439 +440 #[tokio::test] +441 #[traced_test] +442 async fn mdns_publish_resolve() -> Result { +443 let (_, discovery_a) = make_discoverer()?; +444 let (node_id_b, discovery_b) = make_discoverer()?; +445 +446 // make addr info for discoverer b +447 let user_data: UserData = "foobar".parse()?; +448 let node_data = NodeData::new(None, BTreeSet::from(["0.0.0.0:11111".parse().unwrap()])) +449 .with_user_data(Some(user_data.clone())); +450 println!("info {node_data:?}"); +451 +452 // resolve twice to ensure we can create separate streams for the same node_id +453 let mut s1 = discovery_a.resolve(node_id_b).unwrap(); +454 let mut s2 = discovery_a.resolve(node_id_b).unwrap(); +455 +456 tracing::debug!(?node_id_b, "Discovering node id b"); +457 // publish discovery_b's address +458 discovery_b.publish(&node_data); +459 let s1_res = tokio::time::timeout(Duration::from_secs(5), s1.next()) +460 .await +461 .context("timeout")? +462 .unwrap()?; +463 let s2_res = tokio::time::timeout(Duration::from_secs(5), s2.next()) +464 .await +465 .context("timeout")? +466 .unwrap()?; +467 assert_eq!(s1_res.node_info().data, node_data); +468 assert_eq!(s2_res.node_info().data, node_data); +469 +470 Ok(()) +471 } +472 +473 #[tokio::test] +474 #[traced_test] +475 async fn mdns_subscribe() -> Result { +476 let num_nodes = 5; +477 let mut node_ids = BTreeSet::new(); +478 let mut discoverers = vec![]; +479 +480 let (_, discovery) = make_discoverer()?; +481 let node_data = NodeData::new(None, BTreeSet::from(["0.0.0.0:11111".parse().unwrap()])); +482 +483 for i in 0..num_nodes { +484 let (node_id, discovery) = make_discoverer()?; +485 let user_data: UserData = format!("node{i}").parse()?; +486 let node_data = node_data.clone().with_user_data(Some(user_data.clone())); +487 node_ids.insert((node_id, Some(user_data))); +488 discovery.publish(&node_data); +489 discoverers.push(discovery); +490 } +491 +492 let mut events = discovery.subscribe().unwrap(); 493 -494 let mut events = discovery.subscribe().unwrap(); -495 -496 let test = async move { -497 let mut got_ids = BTreeSet::new(); -498 while got_ids.len() != num_nodes { -499 if let Some(item) = events.next().await { -500 if node_ids.contains(&(item.node_id(), item.user_data())) { -501 got_ids.insert((item.node_id(), item.user_data())); -502 } -503 } else { -504 whatever!( -505 "no more events, only got {} ids, expected {num_nodes}\n", -506 got_ids.len() -507 ); -508 } -509 } -510 assert_eq!(got_ids, node_ids); -511 Ok::<_, Error>(()) -512 }; -513 tokio::time::timeout(Duration::from_secs(5), test) -514 .await -515 .context("timeout")? -516 } -517 -518 fn make_discoverer() -> Result<(PublicKey, MdnsDiscovery)> { -519 let node_id = SecretKey::generate(rand::thread_rng()).public(); -520 Ok((node_id, MdnsDiscovery::new(node_id)?)) -521 } -522 } -523}
    \ No newline at end of file +494 let test = async move { +495 let mut got_ids = BTreeSet::new(); +496 while got_ids.len() != num_nodes { +497 if let Some(item) = events.next().await { +498 if node_ids.contains(&(item.node_id(), item.user_data())) { +499 got_ids.insert((item.node_id(), item.user_data())); +500 } +501 } else { +502 whatever!( +503 "no more events, only got {} ids, expected {num_nodes}\n", +504 got_ids.len() +505 ); +506 } +507 } +508 assert_eq!(got_ids, node_ids); +509 Ok::<_, Error>(()) +510 }; +511 tokio::time::timeout(Duration::from_secs(5), test) +512 .await +513 .context("timeout")? +514 } +515 +516 fn make_discoverer() -> Result<(PublicKey, MdnsDiscovery)> { +517 let node_id = SecretKey::generate(rand::thread_rng()).public(); +518 Ok((node_id, MdnsDiscovery::new(node_id)?)) +519 } +520 } +521}
    \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/discovery/pkarr.rs.html b/pr/3327/docs/src/iroh/discovery/pkarr.rs.html index 822a9a2ef4..0376004b77 100644 --- a/pr/3327/docs/src/iroh/discovery/pkarr.rs.html +++ b/pr/3327/docs/src/iroh/discovery/pkarr.rs.html @@ -47,27 +47,27 @@ 47use std::sync::Arc; 48 49use iroh_base::{NodeId, RelayUrl, SecretKey}; -50use iroh_relay::node_info::NodeInfo; +50use iroh_relay::node_info::{EncodingError, NodeInfo}; 51use n0_future::{ 52 boxed::BoxStream, 53 task::{self, AbortOnDropHandle}, 54 time::{self, Duration, Instant}, 55}; -56use pkarr::{ -57 errors::{PublicKeyError, SignedPacketVerifyError}, -58 SignedPacket, -59}; -60use snafu::{ResultExt, Snafu}; -61use tracing::{debug, error_span, warn, Instrument}; -62use url::Url; -63 -64use super::{DiscoveryContext, DiscoveryError, IntoDiscovery, IntoDiscoveryError}; -65#[cfg(not(wasm_browser))] -66use crate::dns::DnsResolver; -67use crate::{ -68 discovery::{Discovery, DiscoveryItem, NodeData, ParsePacketSnafu, SignedPacketSnafu}, -69 endpoint::force_staging_infra, -70 watcher::{self, Disconnected, Watchable, Watcher as _}, +56use n0_watcher::{Disconnected, Watchable, Watcher as _}; +57use pkarr::{ +58 errors::{PublicKeyError, SignedPacketVerifyError}, +59 SignedPacket, +60}; +61use snafu::{ResultExt, Snafu}; +62use tracing::{debug, error_span, warn, Instrument}; +63use url::Url; +64 +65use super::{DiscoveryContext, DiscoveryError, IntoDiscovery, IntoDiscoveryError}; +66#[cfg(not(wasm_browser))] +67use crate::dns::DnsResolver; +68use crate::{ +69 discovery::{Discovery, DiscoveryItem, NodeData}, +70 endpoint::force_staging_infra, 71}; 72 73#[cfg(feature = "discovery-pkarr-dht")] @@ -89,522 +89,523 @@ 89 HttpRequest { status: reqwest::StatusCode }, 90 #[snafu(display("Http payload error"))] 91 HttpPayload { source: reqwest::Error }, -92} -93 -94impl From<PkarrError> for DiscoveryError { -95 fn from(err: PkarrError) -> Self { -96 DiscoveryError::from_err("pkarr", err) -97 } -98} -99 -100/// The production pkarr relay run by [number 0]. -101/// -102/// This server is both a pkarr relay server as well as a DNS resolver, see the [module -103/// documentation]. However it does not interact with the Mainline DHT, so is a more -104/// central service. It is a reliable service to use for node discovery. -105/// -106/// [number 0]: https://n0.computer -107/// [module documentation]: crate::discovery::pkarr -108pub const N0_DNS_PKARR_RELAY_PROD: &str = "https://dns.iroh.link/pkarr"; -109/// The testing pkarr relay run by [number 0]. -110/// -111/// This server operates similarly to [`N0_DNS_PKARR_RELAY_PROD`] but is not as reliable. -112/// It is meant for more experimental use and testing purposes. -113/// -114/// [number 0]: https://n0.computer -115pub const N0_DNS_PKARR_RELAY_STAGING: &str = "https://staging-dns.iroh.link/pkarr"; -116 -117/// Default TTL for the records in the pkarr signed packet. -118/// -119/// The Time To Live (TTL) tells DNS caches how long to store a record. It is ignored by the -120/// `iroh-dns-server`, e.g. as running on [`N0_DNS_PKARR_RELAY_PROD`], as the home server -121/// keeps the records for the domain. When using the pkarr relay no DNS is involved and the -122/// setting is ignored. -123// TODO(flub): huh? -124pub const DEFAULT_PKARR_TTL: u32 = 30; -125 -126/// Interval in which to republish the node info even if unchanged: 5 minutes. -127pub const DEFAULT_REPUBLISH_INTERVAL: Duration = Duration::from_secs(60 * 5); -128 -129/// Builder for [`PkarrPublisher`]. -130/// -131/// See [`PkarrPublisher::builder`]. -132#[derive(Debug)] -133pub struct PkarrPublisherBuilder { -134 pkarr_relay: Url, -135 ttl: u32, -136 republish_interval: Duration, -137 #[cfg(not(wasm_browser))] -138 dns_resolver: Option<DnsResolver>, -139} -140 -141impl PkarrPublisherBuilder { -142 /// See [`PkarrPublisher::builder`]. -143 fn new(pkarr_relay: Url) -> Self { -144 Self { -145 pkarr_relay, -146 ttl: DEFAULT_PKARR_TTL, -147 republish_interval: DEFAULT_REPUBLISH_INTERVAL, -148 #[cfg(not(wasm_browser))] -149 dns_resolver: None, -150 } -151 } -152 -153 /// See [`PkarrPublisher::n0_dns`]. -154 fn n0_dns() -> Self { -155 let pkarr_relay = match force_staging_infra() { -156 true => N0_DNS_PKARR_RELAY_STAGING, -157 false => N0_DNS_PKARR_RELAY_PROD, -158 }; -159 -160 let pkarr_relay: Url = pkarr_relay.parse().expect("url is valid"); -161 Self::new(pkarr_relay) -162 } -163 -164 /// Sets the TTL (time-to-live) for published packets. -165 /// -166 /// Default is [`DEFAULT_PKARR_TTL`]. -167 pub fn ttl(mut self, ttl: u32) -> Self { -168 self.ttl = ttl; -169 self -170 } -171 -172 /// Sets the interval after which packets are republished even if our node info did not change. -173 /// -174 /// Default is [`DEFAULT_REPUBLISH_INTERVAL`]. -175 pub fn republish_interval(mut self, republish_interval: Duration) -> Self { -176 self.republish_interval = republish_interval; -177 self -178 } -179 -180 /// Sets the DNS resolver to use for resolving the pkarr relay URL. -181 #[cfg(not(wasm_browser))] -182 pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self { -183 self.dns_resolver = Some(dns_resolver); -184 self -185 } -186 -187 /// Builds the [`PkarrPublisher`] with the passed secret key for signing packets. -188 /// -189 /// This publisher will be able to publish [pkarr] records for [`SecretKey`]. -190 pub fn build(self, secret_key: SecretKey) -> PkarrPublisher { -191 PkarrPublisher::new( -192 secret_key, -193 self.pkarr_relay, -194 self.ttl, -195 self.republish_interval, -196 #[cfg(not(wasm_browser))] -197 self.dns_resolver, -198 ) -199 } -200} -201 -202impl IntoDiscovery for PkarrPublisherBuilder { -203 fn into_discovery( -204 mut self, -205 context: &DiscoveryContext, -206 ) -> Result<impl Discovery, IntoDiscoveryError> { -207 #[cfg(not(wasm_browser))] -208 if self.dns_resolver.is_none() { -209 self.dns_resolver = Some(context.dns_resolver().clone()); -210 } -211 -212 Ok(self.build(context.secret_key().clone())) -213 } -214} -215 -216/// Publisher of node discovery information to a [pkarr] relay. -217/// -218/// This publisher uses HTTP to publish node discovery information to a pkarr relay -219/// server, see the [module docs] for details. -220/// -221/// This implements the [`Discovery`] trait to be used as a node discovery service. Note -222/// that it only publishes node discovery information, for the corresponding resolver use -223/// the [`PkarrResolver`] together with [`ConcurrentDiscovery`]. -224/// -225/// This publisher will **only** publish the [`RelayUrl`] if it is set, otherwise the *direct addresses* are published instead. +92 #[snafu(display("EncodingError"))] +93 Encoding { source: EncodingError }, +94} +95 +96impl From<PkarrError> for DiscoveryError { +97 fn from(err: PkarrError) -> Self { +98 DiscoveryError::from_err("pkarr", err) +99 } +100} +101 +102/// The production pkarr relay run by [number 0]. +103/// +104/// This server is both a pkarr relay server as well as a DNS resolver, see the [module +105/// documentation]. However it does not interact with the Mainline DHT, so is a more +106/// central service. It is a reliable service to use for node discovery. +107/// +108/// [number 0]: https://n0.computer +109/// [module documentation]: crate::discovery::pkarr +110pub const N0_DNS_PKARR_RELAY_PROD: &str = "https://dns.iroh.link/pkarr"; +111/// The testing pkarr relay run by [number 0]. +112/// +113/// This server operates similarly to [`N0_DNS_PKARR_RELAY_PROD`] but is not as reliable. +114/// It is meant for more experimental use and testing purposes. +115/// +116/// [number 0]: https://n0.computer +117pub const N0_DNS_PKARR_RELAY_STAGING: &str = "https://staging-dns.iroh.link/pkarr"; +118 +119/// Default TTL for the records in the pkarr signed packet. +120/// +121/// The Time To Live (TTL) tells DNS caches how long to store a record. It is ignored by the +122/// `iroh-dns-server`, e.g. as running on [`N0_DNS_PKARR_RELAY_PROD`], as the home server +123/// keeps the records for the domain. When using the pkarr relay no DNS is involved and the +124/// setting is ignored. +125// TODO(flub): huh? +126pub const DEFAULT_PKARR_TTL: u32 = 30; +127 +128/// Interval in which to republish the node info even if unchanged: 5 minutes. +129pub const DEFAULT_REPUBLISH_INTERVAL: Duration = Duration::from_secs(60 * 5); +130 +131/// Builder for [`PkarrPublisher`]. +132/// +133/// See [`PkarrPublisher::builder`]. +134#[derive(Debug)] +135pub struct PkarrPublisherBuilder { +136 pkarr_relay: Url, +137 ttl: u32, +138 republish_interval: Duration, +139 #[cfg(not(wasm_browser))] +140 dns_resolver: Option<DnsResolver>, +141} +142 +143impl PkarrPublisherBuilder { +144 /// See [`PkarrPublisher::builder`]. +145 fn new(pkarr_relay: Url) -> Self { +146 Self { +147 pkarr_relay, +148 ttl: DEFAULT_PKARR_TTL, +149 republish_interval: DEFAULT_REPUBLISH_INTERVAL, +150 #[cfg(not(wasm_browser))] +151 dns_resolver: None, +152 } +153 } +154 +155 /// See [`PkarrPublisher::n0_dns`]. +156 fn n0_dns() -> Self { +157 let pkarr_relay = match force_staging_infra() { +158 true => N0_DNS_PKARR_RELAY_STAGING, +159 false => N0_DNS_PKARR_RELAY_PROD, +160 }; +161 +162 let pkarr_relay: Url = pkarr_relay.parse().expect("url is valid"); +163 Self::new(pkarr_relay) +164 } +165 +166 /// Sets the TTL (time-to-live) for published packets. +167 /// +168 /// Default is [`DEFAULT_PKARR_TTL`]. +169 pub fn ttl(mut self, ttl: u32) -> Self { +170 self.ttl = ttl; +171 self +172 } +173 +174 /// Sets the interval after which packets are republished even if our node info did not change. +175 /// +176 /// Default is [`DEFAULT_REPUBLISH_INTERVAL`]. +177 pub fn republish_interval(mut self, republish_interval: Duration) -> Self { +178 self.republish_interval = republish_interval; +179 self +180 } +181 +182 /// Sets the DNS resolver to use for resolving the pkarr relay URL. +183 #[cfg(not(wasm_browser))] +184 pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self { +185 self.dns_resolver = Some(dns_resolver); +186 self +187 } +188 +189 /// Builds the [`PkarrPublisher`] with the passed secret key for signing packets. +190 /// +191 /// This publisher will be able to publish [pkarr] records for [`SecretKey`]. +192 pub fn build(self, secret_key: SecretKey) -> PkarrPublisher { +193 PkarrPublisher::new( +194 secret_key, +195 self.pkarr_relay, +196 self.ttl, +197 self.republish_interval, +198 #[cfg(not(wasm_browser))] +199 self.dns_resolver, +200 ) +201 } +202} +203 +204impl IntoDiscovery for PkarrPublisherBuilder { +205 fn into_discovery( +206 mut self, +207 context: &DiscoveryContext, +208 ) -> Result<impl Discovery, IntoDiscoveryError> { +209 #[cfg(not(wasm_browser))] +210 if self.dns_resolver.is_none() { +211 self.dns_resolver = Some(context.dns_resolver().clone()); +212 } +213 +214 Ok(self.build(context.secret_key().clone())) +215 } +216} +217 +218/// Publisher of node discovery information to a [pkarr] relay. +219/// +220/// This publisher uses HTTP to publish node discovery information to a pkarr relay +221/// server, see the [module docs] for details. +222/// +223/// This implements the [`Discovery`] trait to be used as a node discovery service. Note +224/// that it only publishes node discovery information, for the corresponding resolver use +225/// the [`PkarrResolver`] together with [`ConcurrentDiscovery`]. 226/// -227/// [pkarr]: https://pkarr.org -228/// [module docs]: crate::discovery::pkarr -229/// [`RelayUrl`]: crate::RelayUrl -230/// [`ConcurrentDiscovery`]: super::ConcurrentDiscovery -231#[derive(derive_more::Debug, Clone)] -232pub struct PkarrPublisher { -233 node_id: NodeId, -234 watchable: Watchable<Option<NodeInfo>>, -235 _drop_guard: Arc<AbortOnDropHandle<()>>, -236} -237 -238impl PkarrPublisher { -239 /// Returns a [`PkarrPublisherBuilder`] that publishes node info to a [pkarr] relay at `pkarr_relay`. -240 /// -241 /// If no further options are set, the pkarr publisher will use [`DEFAULT_PKARR_TTL`] as the -242 /// time-to-live value for the published packets, and it will republish discovery information -243 /// every [`DEFAULT_REPUBLISH_INTERVAL`], even if the information is unchanged. -244 /// -245 /// [`PkarrPublisherBuilder`] implements [`IntoDiscovery`], so it can be passed to [`add_discovery`]. -246 /// It will then use the endpoint's secret key to sign published packets. -247 /// -248 /// [`add_discovery`]: crate::endpoint::Builder::add_discovery -249 /// [pkarr]: https://pkarr.org -250 pub fn builder(pkarr_relay: Url) -> PkarrPublisherBuilder { -251 PkarrPublisherBuilder::new(pkarr_relay) -252 } -253 -254 /// Creates a new [`PkarrPublisher`] with a custom TTL and republish intervals. -255 /// -256 /// This allows creating the publisher with custom time-to-live values of the -257 /// [`pkarr::SignedPacket`]s and well as a custom republish interval. -258 fn new( -259 secret_key: SecretKey, -260 pkarr_relay: Url, -261 ttl: u32, -262 republish_interval: Duration, -263 #[cfg(not(wasm_browser))] dns_resolver: Option<DnsResolver>, -264 ) -> Self { -265 debug!("creating pkarr publisher that publishes to {pkarr_relay}"); -266 let node_id = secret_key.public(); -267 -268 #[cfg(wasm_browser)] -269 let pkarr_client = PkarrRelayClient::new(pkarr_relay); -270 -271 #[cfg(not(wasm_browser))] -272 let pkarr_client = if let Some(dns_resolver) = dns_resolver { -273 PkarrRelayClient::with_dns_resolver(pkarr_relay, dns_resolver) -274 } else { -275 PkarrRelayClient::new(pkarr_relay) -276 }; -277 -278 let watchable = Watchable::default(); -279 let service = PublisherService { -280 ttl, -281 watcher: watchable.watch(), -282 secret_key, -283 pkarr_client, -284 republish_interval, -285 }; -286 let join_handle = task::spawn( -287 service -288 .run() -289 .instrument(error_span!("pkarr_publish", me=%node_id.fmt_short())), -290 ); -291 Self { -292 watchable, -293 node_id, -294 _drop_guard: Arc::new(AbortOnDropHandle::new(join_handle)), -295 } -296 } -297 -298 /// Creates a pkarr publisher which uses the [number 0] pkarr relay server. -299 /// -300 /// This uses the pkarr relay server operated by [number 0], at -301 /// [`N0_DNS_PKARR_RELAY_PROD`]. -302 /// -303 /// When running with the environment variable -304 /// `IROH_FORCE_STAGING_RELAYS` set to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`] -305 /// server is used instead. -306 /// -307 /// [number 0]: https://n0.computer -308 pub fn n0_dns() -> PkarrPublisherBuilder { -309 PkarrPublisherBuilder::n0_dns() -310 } -311 -312 /// Publishes the addressing information about this node to a pkarr relay. -313 /// -314 /// This is a nonblocking function, the actual update is performed in the background. -315 pub fn update_node_data(&self, data: &NodeData) { -316 let mut data = data.clone(); -317 if data.relay_url().is_some() { -318 // If relay url is set: only publish relay url, and no direct addrs. -319 data.clear_direct_addresses(); -320 } -321 let info = NodeInfo::from_parts(self.node_id, data); -322 self.watchable.set(Some(info)).ok(); -323 } -324} -325 -326impl Discovery for PkarrPublisher { -327 fn publish(&self, data: &NodeData) { -328 self.update_node_data(data); -329 } -330} -331 -332/// Publish node info to a pkarr relay. -333#[derive(derive_more::Debug, Clone)] -334struct PublisherService { -335 #[debug("SecretKey")] -336 secret_key: SecretKey, -337 #[debug("PkarrClient")] -338 pkarr_client: PkarrRelayClient, -339 watcher: watcher::Direct<Option<NodeInfo>>, -340 ttl: u32, -341 republish_interval: Duration, -342} -343 -344impl PublisherService { -345 async fn run(mut self) { -346 let mut failed_attempts = 0; -347 let republish = time::sleep(Duration::MAX); -348 tokio::pin!(republish); -349 loop { -350 let Ok(info) = self.watcher.get() else { -351 break; // disconnected -352 }; -353 if let Some(info) = info { -354 if let Err(err) = self.publish_current(info).await { -355 failed_attempts += 1; -356 // Retry after increasing timeout -357 let retry_after = Duration::from_secs(failed_attempts); -358 republish.as_mut().reset(Instant::now() + retry_after); -359 warn!( -360 err = %format!("{err:#}"), -361 url = %self.pkarr_client.pkarr_relay_url , -362 ?retry_after, -363 %failed_attempts, -364 "Failed to publish to pkarr", -365 ); -366 } else { -367 failed_attempts = 0; -368 // Republish after fixed interval -369 republish -370 .as_mut() -371 .reset(Instant::now() + self.republish_interval); -372 } -373 } -374 // Wait until either the retry/republish timeout is reached, or the node info changed. -375 tokio::select! { -376 res = self.watcher.updated() => match res { -377 Ok(_) => debug!("Publish node info to pkarr (info changed)"), -378 Err(Disconnected { .. }) => break, -379 }, -380 _ = &mut republish => debug!("Publish node info to pkarr (interval elapsed)"), -381 } -382 } -383 } -384 -385 async fn publish_current(&self, info: NodeInfo) -> Result<(), DiscoveryError> { -386 debug!( -387 data = ?info.data, -388 pkarr_relay = %self.pkarr_client.pkarr_relay_url, -389 "Publish node info to pkarr" -390 ); -391 let signed_packet = info -392 .to_pkarr_signed_packet(&self.secret_key, self.ttl) -393 .context(SignedPacketSnafu)?; -394 self.pkarr_client.publish(&signed_packet).await?; -395 Ok(()) -396 } -397} -398 -399/// Builder for [`PkarrResolver`]. -400/// -401/// See [`PkarrResolver::builder`]. -402#[derive(Debug)] -403pub struct PkarrResolverBuilder { -404 pkarr_relay: Url, -405 #[cfg(not(wasm_browser))] -406 dns_resolver: Option<DnsResolver>, -407} -408 -409impl PkarrResolverBuilder { -410 /// Sets the DNS resolver to use for resolving the pkarr relay URL. -411 #[cfg(not(wasm_browser))] -412 pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self { -413 self.dns_resolver = Some(dns_resolver); -414 self -415 } -416 -417 /// Creates a [`PkarrResolver`] from this builder. -418 pub fn build(self) -> PkarrResolver { -419 #[cfg(wasm_browser)] -420 let pkarr_client = PkarrRelayClient::new(self.pkarr_relay); -421 -422 #[cfg(not(wasm_browser))] -423 let pkarr_client = if let Some(dns_resolver) = self.dns_resolver { -424 PkarrRelayClient::with_dns_resolver(self.pkarr_relay, dns_resolver) -425 } else { -426 PkarrRelayClient::new(self.pkarr_relay) -427 }; -428 -429 PkarrResolver { pkarr_client } -430 } -431} -432 -433impl IntoDiscovery for PkarrResolverBuilder { -434 fn into_discovery( -435 mut self, -436 context: &DiscoveryContext, -437 ) -> Result<impl Discovery, IntoDiscoveryError> { -438 #[cfg(not(wasm_browser))] -439 if self.dns_resolver.is_none() { -440 self.dns_resolver = Some(context.dns_resolver().clone()); -441 } -442 -443 Ok(self.build()) -444 } -445} -446 -447/// Resolver of node discovery information from a [pkarr] relay. -448/// -449/// The resolver uses HTTP to query node discovery information from a pkarr relay server, -450/// see the [module docs] for details. -451/// -452/// This implements the [`Discovery`] trait to be used as a node discovery service. Note -453/// that it only resolves node discovery information, for the corresponding publisher use -454/// the [`PkarrPublisher`] together with [`ConcurrentDiscovery`]. -455/// -456/// [pkarr]: https://pkarr.org -457/// [module docs]: crate::discovery::pkarr -458/// [`ConcurrentDiscovery`]: super::ConcurrentDiscovery -459#[derive(derive_more::Debug, Clone)] -460pub struct PkarrResolver { -461 pkarr_client: PkarrRelayClient, -462} -463 -464impl PkarrResolver { -465 /// Creates a new resolver builder using the pkarr relay server at the URL. -466 /// -467 /// The builder implements [`IntoDiscovery`]. -468 pub fn builder(pkarr_relay: Url) -> PkarrResolverBuilder { -469 PkarrResolverBuilder { -470 pkarr_relay, -471 #[cfg(not(wasm_browser))] -472 dns_resolver: None, -473 } -474 } -475 -476 /// Creates a pkarr resolver builder which uses the [number 0] pkarr relay server. -477 /// -478 /// This uses the pkarr relay server operated by [number 0] at -479 /// [`N0_DNS_PKARR_RELAY_PROD`]. -480 /// -481 /// When running with the environment variable `IROH_FORCE_STAGING_RELAYS` -482 /// set to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`] -483 /// server is used instead. -484 /// -485 /// [number 0]: https://n0.computer -486 pub fn n0_dns() -> PkarrResolverBuilder { -487 let pkarr_relay = match force_staging_infra() { -488 true => N0_DNS_PKARR_RELAY_STAGING, -489 false => N0_DNS_PKARR_RELAY_PROD, -490 }; -491 -492 let pkarr_relay: Url = pkarr_relay.parse().expect("url is valid"); -493 Self::builder(pkarr_relay) -494 } -495} -496 -497impl Discovery for PkarrResolver { -498 fn resolve(&self, node_id: NodeId) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { -499 let pkarr_client = self.pkarr_client.clone(); -500 let fut = async move { -501 let signed_packet = pkarr_client.resolve(node_id).await?; -502 let info = -503 NodeInfo::from_pkarr_signed_packet(&signed_packet).context(ParsePacketSnafu)?; -504 let item = DiscoveryItem::new(info, "pkarr", None); -505 Ok(item) -506 }; -507 let stream = n0_future::stream::once_future(fut); -508 Some(Box::pin(stream)) -509 } -510} -511 -512/// A [pkarr] client to publish [`pkarr::SignedPacket`]s to a pkarr relay. -513/// -514/// [pkarr]: https://pkarr.org -515#[derive(Debug, Clone)] -516pub struct PkarrRelayClient { -517 http_client: reqwest::Client, -518 pkarr_relay_url: Url, -519} -520 -521impl PkarrRelayClient { -522 /// Creates a new client. -523 pub fn new(pkarr_relay_url: Url) -> Self { -524 Self { -525 http_client: reqwest::Client::new(), -526 pkarr_relay_url, -527 } -528 } -529 -530 /// Creates a new client while passing a DNS resolver to use. -531 #[cfg(not(wasm_browser))] -532 pub fn with_dns_resolver(pkarr_relay_url: Url, dns_resolver: crate::dns::DnsResolver) -> Self { -533 let http_client = reqwest::Client::builder() -534 .dns_resolver(Arc::new(dns_resolver)) -535 .build() -536 .expect("failed to create request client"); -537 Self { -538 http_client, -539 pkarr_relay_url, -540 } -541 } -542 -543 /// Resolves a [`SignedPacket`] for the given [`NodeId`]. -544 pub async fn resolve(&self, node_id: NodeId) -> Result<SignedPacket, DiscoveryError> { -545 // We map the error to string, as in browsers the error is !Send -546 let public_key = pkarr::PublicKey::try_from(node_id.as_bytes()).context(PublicKeySnafu)?; -547 -548 let mut url = self.pkarr_relay_url.clone(); -549 url.path_segments_mut() -550 .map_err(|_| { -551 InvalidRelayUrlSnafu { -552 url: self.pkarr_relay_url.clone(), -553 } -554 .build() -555 })? -556 .push(&public_key.to_z32()); -557 -558 let response = self -559 .http_client -560 .get(url) -561 .send() -562 .await -563 .context(HttpSendSnafu)?; -564 -565 if !response.status().is_success() { -566 return Err(HttpRequestSnafu { -567 status: response.status(), -568 } -569 .build() -570 .into()); -571 } -572 -573 let payload = response.bytes().await.context(HttpPayloadSnafu)?; -574 // We map the error to string, as in browsers the error is !Send -575 let packet = -576 SignedPacket::from_relay_payload(&public_key, &payload).context(VerifySnafu)?; -577 Ok(packet) -578 } -579 -580 /// Publishes a [`SignedPacket`]. -581 pub async fn publish(&self, signed_packet: &SignedPacket) -> Result<(), DiscoveryError> { -582 let mut url = self.pkarr_relay_url.clone(); -583 url.path_segments_mut() -584 .map_err(|_| { -585 InvalidRelayUrlSnafu { -586 url: self.pkarr_relay_url.clone(), -587 } -588 .build() -589 })? -590 .push(&signed_packet.public_key().to_z32()); -591 -592 let response = self -593 .http_client -594 .put(url) -595 .body(signed_packet.to_relay_payload()) -596 .send() -597 .await -598 .context(HttpSendSnafu)?; -599 -600 if !response.status().is_success() { -601 return Err(HttpRequestSnafu { -602 status: response.status(), -603 } -604 .build() -605 .into()); -606 } -607 -608 Ok(()) -609 } -610} \ No newline at end of file +227/// This publisher will **only** publish the [`RelayUrl`] if it is set, otherwise the *direct addresses* are published instead. +228/// +229/// [pkarr]: https://pkarr.org +230/// [module docs]: crate::discovery::pkarr +231/// [`RelayUrl`]: crate::RelayUrl +232/// [`ConcurrentDiscovery`]: super::ConcurrentDiscovery +233#[derive(derive_more::Debug, Clone)] +234pub struct PkarrPublisher { +235 node_id: NodeId, +236 watchable: Watchable<Option<NodeInfo>>, +237 _drop_guard: Arc<AbortOnDropHandle<()>>, +238} +239 +240impl PkarrPublisher { +241 /// Returns a [`PkarrPublisherBuilder`] that publishes node info to a [pkarr] relay at `pkarr_relay`. +242 /// +243 /// If no further options are set, the pkarr publisher will use [`DEFAULT_PKARR_TTL`] as the +244 /// time-to-live value for the published packets, and it will republish discovery information +245 /// every [`DEFAULT_REPUBLISH_INTERVAL`], even if the information is unchanged. +246 /// +247 /// [`PkarrPublisherBuilder`] implements [`IntoDiscovery`], so it can be passed to [`add_discovery`]. +248 /// It will then use the endpoint's secret key to sign published packets. +249 /// +250 /// [`add_discovery`]: crate::endpoint::Builder::add_discovery +251 /// [pkarr]: https://pkarr.org +252 pub fn builder(pkarr_relay: Url) -> PkarrPublisherBuilder { +253 PkarrPublisherBuilder::new(pkarr_relay) +254 } +255 +256 /// Creates a new [`PkarrPublisher`] with a custom TTL and republish intervals. +257 /// +258 /// This allows creating the publisher with custom time-to-live values of the +259 /// [`pkarr::SignedPacket`]s and well as a custom republish interval. +260 fn new( +261 secret_key: SecretKey, +262 pkarr_relay: Url, +263 ttl: u32, +264 republish_interval: Duration, +265 #[cfg(not(wasm_browser))] dns_resolver: Option<DnsResolver>, +266 ) -> Self { +267 debug!("creating pkarr publisher that publishes to {pkarr_relay}"); +268 let node_id = secret_key.public(); +269 +270 #[cfg(wasm_browser)] +271 let pkarr_client = PkarrRelayClient::new(pkarr_relay); +272 +273 #[cfg(not(wasm_browser))] +274 let pkarr_client = if let Some(dns_resolver) = dns_resolver { +275 PkarrRelayClient::with_dns_resolver(pkarr_relay, dns_resolver) +276 } else { +277 PkarrRelayClient::new(pkarr_relay) +278 }; +279 +280 let watchable = Watchable::default(); +281 let service = PublisherService { +282 ttl, +283 watcher: watchable.watch(), +284 secret_key, +285 pkarr_client, +286 republish_interval, +287 }; +288 let join_handle = task::spawn( +289 service +290 .run() +291 .instrument(error_span!("pkarr_publish", me=%node_id.fmt_short())), +292 ); +293 Self { +294 watchable, +295 node_id, +296 _drop_guard: Arc::new(AbortOnDropHandle::new(join_handle)), +297 } +298 } +299 +300 /// Creates a pkarr publisher which uses the [number 0] pkarr relay server. +301 /// +302 /// This uses the pkarr relay server operated by [number 0], at +303 /// [`N0_DNS_PKARR_RELAY_PROD`]. +304 /// +305 /// When running with the environment variable +306 /// `IROH_FORCE_STAGING_RELAYS` set to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`] +307 /// server is used instead. +308 /// +309 /// [number 0]: https://n0.computer +310 pub fn n0_dns() -> PkarrPublisherBuilder { +311 PkarrPublisherBuilder::n0_dns() +312 } +313 +314 /// Publishes the addressing information about this node to a pkarr relay. +315 /// +316 /// This is a nonblocking function, the actual update is performed in the background. +317 pub fn update_node_data(&self, data: &NodeData) { +318 let mut data = data.clone(); +319 if data.relay_url().is_some() { +320 // If relay url is set: only publish relay url, and no direct addrs. +321 data.clear_direct_addresses(); +322 } +323 let info = NodeInfo::from_parts(self.node_id, data); +324 self.watchable.set(Some(info)).ok(); +325 } +326} +327 +328impl Discovery for PkarrPublisher { +329 fn publish(&self, data: &NodeData) { +330 self.update_node_data(data); +331 } +332} +333 +334/// Publish node info to a pkarr relay. +335#[derive(derive_more::Debug, Clone)] +336struct PublisherService { +337 #[debug("SecretKey")] +338 secret_key: SecretKey, +339 #[debug("PkarrClient")] +340 pkarr_client: PkarrRelayClient, +341 watcher: n0_watcher::Direct<Option<NodeInfo>>, +342 ttl: u32, +343 republish_interval: Duration, +344} +345 +346impl PublisherService { +347 async fn run(mut self) { +348 let mut failed_attempts = 0; +349 let republish = time::sleep(Duration::MAX); +350 tokio::pin!(republish); +351 loop { +352 let Ok(info) = self.watcher.get() else { +353 break; // disconnected +354 }; +355 if let Some(info) = info { +356 if let Err(err) = self.publish_current(info).await { +357 failed_attempts += 1; +358 // Retry after increasing timeout +359 let retry_after = Duration::from_secs(failed_attempts); +360 republish.as_mut().reset(Instant::now() + retry_after); +361 warn!( +362 err = %format!("{err:#}"), +363 url = %self.pkarr_client.pkarr_relay_url , +364 ?retry_after, +365 %failed_attempts, +366 "Failed to publish to pkarr", +367 ); +368 } else { +369 failed_attempts = 0; +370 // Republish after fixed interval +371 republish +372 .as_mut() +373 .reset(Instant::now() + self.republish_interval); +374 } +375 } +376 // Wait until either the retry/republish timeout is reached, or the node info changed. +377 tokio::select! { +378 res = self.watcher.updated() => match res { +379 Ok(_) => debug!("Publish node info to pkarr (info changed)"), +380 Err(Disconnected { .. }) => break, +381 }, +382 _ = &mut republish => debug!("Publish node info to pkarr (interval elapsed)"), +383 } +384 } +385 } +386 +387 async fn publish_current(&self, info: NodeInfo) -> Result<(), PkarrError> { +388 debug!( +389 data = ?info.data, +390 pkarr_relay = %self.pkarr_client.pkarr_relay_url, +391 "Publish node info to pkarr" +392 ); +393 let signed_packet = info +394 .to_pkarr_signed_packet(&self.secret_key, self.ttl) +395 .context(EncodingSnafu)?; +396 self.pkarr_client.publish(&signed_packet).await?; +397 Ok(()) +398 } +399} +400 +401/// Builder for [`PkarrResolver`]. +402/// +403/// See [`PkarrResolver::builder`]. +404#[derive(Debug)] +405pub struct PkarrResolverBuilder { +406 pkarr_relay: Url, +407 #[cfg(not(wasm_browser))] +408 dns_resolver: Option<DnsResolver>, +409} +410 +411impl PkarrResolverBuilder { +412 /// Sets the DNS resolver to use for resolving the pkarr relay URL. +413 #[cfg(not(wasm_browser))] +414 pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self { +415 self.dns_resolver = Some(dns_resolver); +416 self +417 } +418 +419 /// Creates a [`PkarrResolver`] from this builder. +420 pub fn build(self) -> PkarrResolver { +421 #[cfg(wasm_browser)] +422 let pkarr_client = PkarrRelayClient::new(self.pkarr_relay); +423 +424 #[cfg(not(wasm_browser))] +425 let pkarr_client = if let Some(dns_resolver) = self.dns_resolver { +426 PkarrRelayClient::with_dns_resolver(self.pkarr_relay, dns_resolver) +427 } else { +428 PkarrRelayClient::new(self.pkarr_relay) +429 }; +430 +431 PkarrResolver { pkarr_client } +432 } +433} +434 +435impl IntoDiscovery for PkarrResolverBuilder { +436 fn into_discovery( +437 mut self, +438 context: &DiscoveryContext, +439 ) -> Result<impl Discovery, IntoDiscoveryError> { +440 #[cfg(not(wasm_browser))] +441 if self.dns_resolver.is_none() { +442 self.dns_resolver = Some(context.dns_resolver().clone()); +443 } +444 +445 Ok(self.build()) +446 } +447} +448 +449/// Resolver of node discovery information from a [pkarr] relay. +450/// +451/// The resolver uses HTTP to query node discovery information from a pkarr relay server, +452/// see the [module docs] for details. +453/// +454/// This implements the [`Discovery`] trait to be used as a node discovery service. Note +455/// that it only resolves node discovery information, for the corresponding publisher use +456/// the [`PkarrPublisher`] together with [`ConcurrentDiscovery`]. +457/// +458/// [pkarr]: https://pkarr.org +459/// [module docs]: crate::discovery::pkarr +460/// [`ConcurrentDiscovery`]: super::ConcurrentDiscovery +461#[derive(derive_more::Debug, Clone)] +462pub struct PkarrResolver { +463 pkarr_client: PkarrRelayClient, +464} +465 +466impl PkarrResolver { +467 /// Creates a new resolver builder using the pkarr relay server at the URL. +468 /// +469 /// The builder implements [`IntoDiscovery`]. +470 pub fn builder(pkarr_relay: Url) -> PkarrResolverBuilder { +471 PkarrResolverBuilder { +472 pkarr_relay, +473 #[cfg(not(wasm_browser))] +474 dns_resolver: None, +475 } +476 } +477 +478 /// Creates a pkarr resolver builder which uses the [number 0] pkarr relay server. +479 /// +480 /// This uses the pkarr relay server operated by [number 0] at +481 /// [`N0_DNS_PKARR_RELAY_PROD`]. +482 /// +483 /// When running with the environment variable `IROH_FORCE_STAGING_RELAYS` +484 /// set to any non empty value [`N0_DNS_PKARR_RELAY_STAGING`] +485 /// server is used instead. +486 /// +487 /// [number 0]: https://n0.computer +488 pub fn n0_dns() -> PkarrResolverBuilder { +489 let pkarr_relay = match force_staging_infra() { +490 true => N0_DNS_PKARR_RELAY_STAGING, +491 false => N0_DNS_PKARR_RELAY_PROD, +492 }; +493 +494 let pkarr_relay: Url = pkarr_relay.parse().expect("url is valid"); +495 Self::builder(pkarr_relay) +496 } +497} +498 +499impl Discovery for PkarrResolver { +500 fn resolve(&self, node_id: NodeId) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { +501 let pkarr_client = self.pkarr_client.clone(); +502 let fut = async move { +503 let signed_packet = pkarr_client.resolve(node_id).await?; +504 let info = NodeInfo::from_pkarr_signed_packet(&signed_packet) +505 .map_err(|err| DiscoveryError::from_err("pkarr", err))?; +506 let item = DiscoveryItem::new(info, "pkarr", None); +507 Ok(item) +508 }; +509 let stream = n0_future::stream::once_future(fut); +510 Some(Box::pin(stream)) +511 } +512} +513 +514/// A [pkarr] client to publish [`pkarr::SignedPacket`]s to a pkarr relay. +515/// +516/// [pkarr]: https://pkarr.org +517#[derive(Debug, Clone)] +518pub struct PkarrRelayClient { +519 http_client: reqwest::Client, +520 pkarr_relay_url: Url, +521} +522 +523impl PkarrRelayClient { +524 /// Creates a new client. +525 pub fn new(pkarr_relay_url: Url) -> Self { +526 Self { +527 http_client: reqwest::Client::new(), +528 pkarr_relay_url, +529 } +530 } +531 +532 /// Creates a new client while passing a DNS resolver to use. +533 #[cfg(not(wasm_browser))] +534 pub fn with_dns_resolver(pkarr_relay_url: Url, dns_resolver: crate::dns::DnsResolver) -> Self { +535 let http_client = reqwest::Client::builder() +536 .dns_resolver(Arc::new(dns_resolver)) +537 .build() +538 .expect("failed to create request client"); +539 Self { +540 http_client, +541 pkarr_relay_url, +542 } +543 } +544 +545 /// Resolves a [`SignedPacket`] for the given [`NodeId`]. +546 pub async fn resolve(&self, node_id: NodeId) -> Result<SignedPacket, DiscoveryError> { +547 // We map the error to string, as in browsers the error is !Send +548 let public_key = pkarr::PublicKey::try_from(node_id.as_bytes()).context(PublicKeySnafu)?; +549 +550 let mut url = self.pkarr_relay_url.clone(); +551 url.path_segments_mut() +552 .map_err(|_| { +553 InvalidRelayUrlSnafu { +554 url: self.pkarr_relay_url.clone(), +555 } +556 .build() +557 })? +558 .push(&public_key.to_z32()); +559 +560 let response = self +561 .http_client +562 .get(url) +563 .send() +564 .await +565 .context(HttpSendSnafu)?; +566 +567 if !response.status().is_success() { +568 return Err(HttpRequestSnafu { +569 status: response.status(), +570 } +571 .build() +572 .into()); +573 } +574 +575 let payload = response.bytes().await.context(HttpPayloadSnafu)?; +576 // We map the error to string, as in browsers the error is !Send +577 let packet = +578 SignedPacket::from_relay_payload(&public_key, &payload).context(VerifySnafu)?; +579 Ok(packet) +580 } +581 +582 /// Publishes a [`SignedPacket`]. +583 pub async fn publish(&self, signed_packet: &SignedPacket) -> Result<(), PkarrError> { +584 let mut url = self.pkarr_relay_url.clone(); +585 url.path_segments_mut() +586 .map_err(|_| { +587 InvalidRelayUrlSnafu { +588 url: self.pkarr_relay_url.clone(), +589 } +590 .build() +591 })? +592 .push(&signed_packet.public_key().to_z32()); +593 +594 let response = self +595 .http_client +596 .put(url) +597 .body(signed_packet.to_relay_payload()) +598 .send() +599 .await +600 .context(HttpSendSnafu)?; +601 +602 if !response.status().is_success() { +603 return Err(HttpRequestSnafu { +604 status: response.status(), +605 } +606 .build()); +607 } +608 +609 Ok(()) +610 } +611} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/discovery/pkarr/dht.rs.html b/pr/3327/docs/src/iroh/discovery/pkarr/dht.rs.html index a573ecff57..f24490a071 100644 --- a/pr/3327/docs/src/iroh/discovery/pkarr/dht.rs.html +++ b/pr/3327/docs/src/iroh/discovery/pkarr/dht.rs.html @@ -19,7 +19,7 @@ 19 20use crate::{ 21 discovery::{ -22 pkarr::{DEFAULT_PKARR_TTL, N0_DNS_PKARR_RELAY_PROD}, +22 pkarr::{DEFAULT_PKARR_TTL, N0_DNS_PKARR_RELAY_PROD, N0_DNS_PKARR_RELAY_STAGING}, 23 Discovery, DiscoveryContext, DiscoveryError, DiscoveryItem, IntoDiscovery, 24 IntoDiscoveryError, NodeData, 25 }, @@ -173,219 +173,224 @@ 173 /// 174 /// [number 0]: https://n0.computer 175 pub fn n0_dns_pkarr_relay(mut self) -> Self { -176 self.pkarr_relay = Some(N0_DNS_PKARR_RELAY_PROD.parse().expect("valid URL")); -177 self -178 } -179 -180 /// Sets whether to publish to the Mainline DHT. -181 pub fn dht(mut self, dht: bool) -> Self { -182 self.dht = dht; -183 self -184 } -185 -186 /// Sets whether to include the direct addresses in the DNS packet. -187 pub fn include_direct_addresses(mut self, include_direct_addresses: bool) -> Self { -188 self.include_direct_addresses = include_direct_addresses; -189 self -190 } -191 -192 /// Sets the initial delay before the first publish. -193 pub fn initial_publish_delay(mut self, initial_publish_delay: Duration) -> Self { -194 self.initial_publish_delay = initial_publish_delay; -195 self -196 } -197 -198 /// Sets the republish delay for the DHT. -199 pub fn republish_delay(mut self, republish_delay: Duration) -> Self { -200 self.republish_delay = republish_delay; -201 self -202 } -203 -204 /// Disables publishing even if a secret key is set. -205 pub fn no_publish(mut self) -> Self { -206 self.enable_publish = false; -207 self -208 } -209 -210 /// Builds the discovery mechanism. -211 pub fn build(self) -> Result<DhtDiscovery, IntoDiscoveryError> { -212 if !(self.dht || self.pkarr_relay.is_some()) { -213 return Err(IntoDiscoveryError::from_err( -214 "pkarr", -215 std::io::Error::other("at least one of DHT or relay must be enabled"), -216 )); -217 } -218 let pkarr = match self.client { -219 Some(client) => client, -220 None => { -221 let mut builder = PkarrClient::builder(); -222 builder.no_default_network(); -223 if self.dht { -224 builder.dht(|x| x); -225 } -226 if let Some(url) = &self.pkarr_relay { -227 builder -228 .relays(&[url.clone()]) -229 .map_err(|e| IntoDiscoveryError::from_err("pkarr", e))?; +176 let url = if crate::endpoint::force_staging_infra() { +177 N0_DNS_PKARR_RELAY_STAGING +178 } else { +179 N0_DNS_PKARR_RELAY_PROD +180 }; +181 self.pkarr_relay = Some(url.parse().expect("valid URL")); +182 self +183 } +184 +185 /// Sets whether to publish to the Mainline DHT. +186 pub fn dht(mut self, dht: bool) -> Self { +187 self.dht = dht; +188 self +189 } +190 +191 /// Sets whether to include the direct addresses in the DNS packet. +192 pub fn include_direct_addresses(mut self, include_direct_addresses: bool) -> Self { +193 self.include_direct_addresses = include_direct_addresses; +194 self +195 } +196 +197 /// Sets the initial delay before the first publish. +198 pub fn initial_publish_delay(mut self, initial_publish_delay: Duration) -> Self { +199 self.initial_publish_delay = initial_publish_delay; +200 self +201 } +202 +203 /// Sets the republish delay for the DHT. +204 pub fn republish_delay(mut self, republish_delay: Duration) -> Self { +205 self.republish_delay = republish_delay; +206 self +207 } +208 +209 /// Disables publishing even if a secret key is set. +210 pub fn no_publish(mut self) -> Self { +211 self.enable_publish = false; +212 self +213 } +214 +215 /// Builds the discovery mechanism. +216 pub fn build(self) -> Result<DhtDiscovery, IntoDiscoveryError> { +217 if !(self.dht || self.pkarr_relay.is_some()) { +218 return Err(IntoDiscoveryError::from_err( +219 "pkarr", +220 std::io::Error::other("at least one of DHT or relay must be enabled"), +221 )); +222 } +223 let pkarr = match self.client { +224 Some(client) => client, +225 None => { +226 let mut builder = PkarrClient::builder(); +227 builder.no_default_network(); +228 if self.dht { +229 builder.dht(|x| x); 230 } -231 builder -232 .build() -233 .map_err(|e| IntoDiscoveryError::from_err("pkarr", e))? -234 } -235 }; -236 let ttl = self.ttl.unwrap_or(DEFAULT_PKARR_TTL); -237 let include_direct_addresses = self.include_direct_addresses; -238 let secret_key = self.secret_key.filter(|_| self.enable_publish); -239 -240 Ok(DhtDiscovery(Arc::new(Inner { -241 pkarr, -242 ttl, -243 relay_url: self.pkarr_relay, -244 include_direct_addresses, -245 secret_key, -246 initial_publish_delay: self.initial_publish_delay, -247 republish_delay: self.republish_delay, -248 task: Default::default(), -249 }))) -250 } -251} -252 -253impl IntoDiscovery for Builder { -254 fn into_discovery( -255 self, -256 context: &DiscoveryContext, -257 ) -> Result<impl Discovery, IntoDiscoveryError> { -258 self.secret_key(context.secret_key().clone()).build() -259 } -260} -261 -262impl DhtDiscovery { -263 /// Creates a new builder for [`DhtDiscovery`]. -264 pub fn builder() -> Builder { -265 Builder::default() -266 } -267 -268 /// Periodically publishes the node address to the DHT and/or relay. -269 async fn publish_loop(self, keypair: SecretKey, signed_packet: SignedPacket) { -270 let this = self; -271 let z32 = pkarr::PublicKey::try_from(keypair.public().as_bytes()) -272 .expect("valid public key") -273 .to_z32(); -274 // initial delay. If the task gets aborted before this delay is over, -275 // we have not published anything to the DHT yet. -276 time::sleep(this.0.initial_publish_delay).await; -277 loop { -278 // TODO: publish takes a compare-and-swap timestamp, make use of that. -279 let res = this.0.pkarr.publish(&signed_packet, None).await; -280 match res { -281 Ok(()) => { -282 tracing::debug!("pkarr publish success. published under {z32}",); -283 } -284 Err(e) => { -285 // we could do a smaller delay here, but in general DHT publish -286 // not working is due to a network issue, and if the network changes -287 // the task will be restarted anyway. -288 // -289 // Being unable to publish to the DHT is something that is expected -290 // to happen from time to time, so this does not warrant a error log. -291 tracing::warn!("pkarr publish error: {}", e); -292 } -293 } -294 time::sleep(this.0.republish_delay).await; -295 } -296 } -297} -298 -299impl Discovery for DhtDiscovery { -300 fn publish(&self, data: &NodeData) { -301 let Some(keypair) = &self.0.secret_key else { -302 tracing::debug!("no keypair set, not publishing"); -303 return; -304 }; -305 tracing::debug!("publishing {data:?}"); -306 let mut info = NodeInfo::from_parts(keypair.public(), data.clone()); -307 if !self.0.include_direct_addresses { -308 info.clear_direct_addresses(); -309 } -310 let Ok(signed_packet) = info.to_pkarr_signed_packet(keypair, self.0.ttl) else { -311 tracing::warn!("failed to create signed packet"); -312 return; -313 }; -314 let this = self.clone(); -315 let curr = task::spawn(this.publish_loop(keypair.clone(), signed_packet)); -316 let mut task = self.0.task.lock().expect("poisoned"); -317 *task = Some(AbortOnDropHandle::new(curr)); -318 } -319 -320 fn resolve(&self, node_id: NodeId) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { -321 let pkarr_public_key = -322 pkarr::PublicKey::try_from(node_id.as_bytes()).expect("valid public key"); -323 tracing::info!("resolving {} as {}", node_id, pkarr_public_key.to_z32()); -324 let discovery = self.0.clone(); -325 let stream = n0_future::stream::once_future(async move { -326 discovery.resolve_pkarr(pkarr_public_key).await -327 }) -328 .filter_map(|x| x) -329 .boxed(); -330 Some(stream) -331 } -332} -333 -334#[cfg(test)] -335mod tests { -336 use std::collections::BTreeSet; -337 -338 use iroh_base::RelayUrl; -339 use n0_snafu::{Result, ResultExt}; -340 use tracing_test::traced_test; -341 -342 use super::*; -343 use crate::Endpoint; -344 -345 #[tokio::test] -346 #[ignore = "flaky"] -347 #[traced_test] -348 async fn dht_discovery_smoke() -> Result { -349 let ep = Endpoint::builder().bind().await?; -350 let secret = ep.secret_key().clone(); -351 let testnet = pkarr::mainline::Testnet::new_async(3).await.e()?; -352 let client = pkarr::Client::builder() -353 .dht(|builder| builder.bootstrap(&testnet.bootstrap)) -354 .build() -355 .e()?; -356 let discovery = DhtDiscovery::builder() -357 .secret_key(secret.clone()) -358 .initial_publish_delay(Duration::ZERO) -359 .client(client) -360 .build()?; -361 -362 let relay_url: RelayUrl = Url::parse("https://example.com").e()?.into(); -363 -364 let data = NodeData::default().with_relay_url(Some(relay_url.clone())); -365 discovery.publish(&data); +231 if let Some(url) = &self.pkarr_relay { +232 builder +233 .relays(&[url.clone()]) +234 .map_err(|e| IntoDiscoveryError::from_err("pkarr", e))?; +235 } +236 builder +237 .build() +238 .map_err(|e| IntoDiscoveryError::from_err("pkarr", e))? +239 } +240 }; +241 let ttl = self.ttl.unwrap_or(DEFAULT_PKARR_TTL); +242 let include_direct_addresses = self.include_direct_addresses; +243 let secret_key = self.secret_key.filter(|_| self.enable_publish); +244 +245 Ok(DhtDiscovery(Arc::new(Inner { +246 pkarr, +247 ttl, +248 relay_url: self.pkarr_relay, +249 include_direct_addresses, +250 secret_key, +251 initial_publish_delay: self.initial_publish_delay, +252 republish_delay: self.republish_delay, +253 task: Default::default(), +254 }))) +255 } +256} +257 +258impl IntoDiscovery for Builder { +259 fn into_discovery( +260 self, +261 context: &DiscoveryContext, +262 ) -> Result<impl Discovery, IntoDiscoveryError> { +263 self.secret_key(context.secret_key().clone()).build() +264 } +265} +266 +267impl DhtDiscovery { +268 /// Creates a new builder for [`DhtDiscovery`]. +269 pub fn builder() -> Builder { +270 Builder::default() +271 } +272 +273 /// Periodically publishes the node address to the DHT and/or relay. +274 async fn publish_loop(self, keypair: SecretKey, signed_packet: SignedPacket) { +275 let this = self; +276 let z32 = pkarr::PublicKey::try_from(keypair.public().as_bytes()) +277 .expect("valid public key") +278 .to_z32(); +279 // initial delay. If the task gets aborted before this delay is over, +280 // we have not published anything to the DHT yet. +281 time::sleep(this.0.initial_publish_delay).await; +282 loop { +283 // TODO: publish takes a compare-and-swap timestamp, make use of that. +284 let res = this.0.pkarr.publish(&signed_packet, None).await; +285 match res { +286 Ok(()) => { +287 tracing::debug!("pkarr publish success. published under {z32}",); +288 } +289 Err(e) => { +290 // we could do a smaller delay here, but in general DHT publish +291 // not working is due to a network issue, and if the network changes +292 // the task will be restarted anyway. +293 // +294 // Being unable to publish to the DHT is something that is expected +295 // to happen from time to time, so this does not warrant a error log. +296 tracing::warn!("pkarr publish error: {}", e); +297 } +298 } +299 time::sleep(this.0.republish_delay).await; +300 } +301 } +302} +303 +304impl Discovery for DhtDiscovery { +305 fn publish(&self, data: &NodeData) { +306 let Some(keypair) = &self.0.secret_key else { +307 tracing::debug!("no keypair set, not publishing"); +308 return; +309 }; +310 tracing::debug!("publishing {data:?}"); +311 let mut info = NodeInfo::from_parts(keypair.public(), data.clone()); +312 if !self.0.include_direct_addresses { +313 info.clear_direct_addresses(); +314 } +315 let Ok(signed_packet) = info.to_pkarr_signed_packet(keypair, self.0.ttl) else { +316 tracing::warn!("failed to create signed packet"); +317 return; +318 }; +319 let this = self.clone(); +320 let curr = task::spawn(this.publish_loop(keypair.clone(), signed_packet)); +321 let mut task = self.0.task.lock().expect("poisoned"); +322 *task = Some(AbortOnDropHandle::new(curr)); +323 } +324 +325 fn resolve(&self, node_id: NodeId) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { +326 let pkarr_public_key = +327 pkarr::PublicKey::try_from(node_id.as_bytes()).expect("valid public key"); +328 tracing::info!("resolving {} as {}", node_id, pkarr_public_key.to_z32()); +329 let discovery = self.0.clone(); +330 let stream = n0_future::stream::once_future(async move { +331 discovery.resolve_pkarr(pkarr_public_key).await +332 }) +333 .filter_map(|x| x) +334 .boxed(); +335 Some(stream) +336 } +337} +338 +339#[cfg(test)] +340mod tests { +341 use std::collections::BTreeSet; +342 +343 use iroh_base::RelayUrl; +344 use n0_snafu::{Result, ResultExt}; +345 use tracing_test::traced_test; +346 +347 use super::*; +348 use crate::Endpoint; +349 +350 #[tokio::test] +351 #[ignore = "flaky"] +352 #[traced_test] +353 async fn dht_discovery_smoke() -> Result { +354 let ep = Endpoint::builder().bind().await?; +355 let secret = ep.secret_key().clone(); +356 let testnet = pkarr::mainline::Testnet::new_async(3).await.e()?; +357 let client = pkarr::Client::builder() +358 .dht(|builder| builder.bootstrap(&testnet.bootstrap)) +359 .build() +360 .e()?; +361 let discovery = DhtDiscovery::builder() +362 .secret_key(secret.clone()) +363 .initial_publish_delay(Duration::ZERO) +364 .client(client) +365 .build()?; 366 -367 // publish is fire and forget, so we have no way to wait until it is done. -368 tokio::time::timeout(Duration::from_secs(30), async move { -369 loop { -370 tokio::time::sleep(Duration::from_millis(200)).await; -371 let mut found_relay_urls = BTreeSet::new(); -372 let items = discovery -373 .resolve(secret.public()) -374 .unwrap() -375 .collect::<Vec<_>>() -376 .await; -377 for item in items.into_iter().flatten() { -378 if let Some(url) = item.relay_url() { -379 found_relay_urls.insert(url.clone()); -380 } -381 } -382 if found_relay_urls.contains(&relay_url) { -383 break; -384 } -385 } -386 }) -387 .await -388 .expect("timeout, relay_url not found on DHT"); -389 Ok(()) -390 } -391} \ No newline at end of file +367 let relay_url: RelayUrl = Url::parse("https://example.com").e()?.into(); +368 +369 let data = NodeData::default().with_relay_url(Some(relay_url.clone())); +370 discovery.publish(&data); +371 +372 // publish is fire and forget, so we have no way to wait until it is done. +373 tokio::time::timeout(Duration::from_secs(30), async move { +374 loop { +375 tokio::time::sleep(Duration::from_millis(200)).await; +376 let mut found_relay_urls = BTreeSet::new(); +377 let items = discovery +378 .resolve(secret.public()) +379 .unwrap() +380 .collect::<Vec<_>>() +381 .await; +382 for item in items.into_iter().flatten() { +383 if let Some(url) = item.relay_url() { +384 found_relay_urls.insert(url.clone()); +385 } +386 } +387 if found_relay_urls.contains(&relay_url) { +388 break; +389 } +390 } +391 }) +392 .await +393 .expect("timeout, relay_url not found on DHT"); +394 Ok(()) +395 } +396} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/endpoint.rs.html b/pr/3327/docs/src/iroh/endpoint.rs.html index 27660bec6d..f583ed127e 100644 --- a/pr/3327/docs/src/iroh/endpoint.rs.html +++ b/pr/3327/docs/src/iroh/endpoint.rs.html @@ -25,3212 +25,3194 @@ 25use iroh_base::{NodeAddr, NodeId, RelayUrl, SecretKey}; 26use iroh_relay::RelayMap; 27use n0_future::{time::Duration, Stream}; -28use nested_enum_utils::common_fields; -29use pin_project::pin_project; -30use snafu::{ensure, ResultExt, Snafu}; -31use tracing::{debug, instrument, trace, warn}; -32use url::Url; -33 -34#[cfg(wasm_browser)] -35use crate::discovery::pkarr::PkarrResolver; -36#[cfg(not(wasm_browser))] -37use crate::{discovery::dns::DnsDiscovery, dns::DnsResolver}; -38use crate::{ -39 discovery::{ -40 pkarr::PkarrPublisher, ConcurrentDiscovery, Discovery, DiscoveryContext, DiscoveryError, -41 DiscoveryItem, DiscoverySubscribers, DiscoveryTask, DynIntoDiscovery, IntoDiscovery, -42 IntoDiscoveryError, Lagged, UserData, -43 }, -44 magicsock::{self, Handle, NodeIdMappedAddr, OwnAddressSnafu}, -45 metrics::EndpointMetrics, -46 net_report::Report, -47 tls, -48 watcher::{self, Watcher}, -49 RelayProtocol, -50}; -51 -52mod rtt_actor; -53 -54// Missing still: SendDatagram and ConnectionClose::frame_type's Type. -55pub use quinn::{ -56 AcceptBi, AcceptUni, AckFrequencyConfig, ApplicationClose, Chunk, ClosedStream, -57 ConnectionClose, ConnectionError, ConnectionStats, MtuDiscoveryConfig, OpenBi, OpenUni, -58 ReadDatagram, ReadError, ReadExactError, ReadToEndError, RecvStream, ResetError, RetryError, -59 SendDatagramError, SendStream, ServerConfig, StoppedError, StreamId, TransportConfig, VarInt, -60 WeakConnectionHandle, WriteError, -61}; -62pub use quinn_proto::{ -63 congestion::{Controller, ControllerFactory}, -64 crypto::{ -65 AeadKey, CryptoError, ExportKeyingMaterialError, HandshakeTokenKey, -66 ServerConfig as CryptoServerConfig, UnsupportedVersion, -67 }, -68 FrameStats, PathStats, TransportError, TransportErrorCode, UdpStats, Written, -69}; -70 -71use self::rtt_actor::RttMessage; -72pub use super::magicsock::{ -73 AddNodeAddrError, ConnectionType, ControlMsg, DirectAddr, DirectAddrInfo, DirectAddrType, -74 RemoteInfo, Source, -75}; -76 -77/// The delay to fall back to discovery when direct addresses fail. -78/// -79/// When a connection is attempted with a [`NodeAddr`] containing direct addresses the -80/// [`Endpoint`] assumes one of those addresses probably works. If after this delay there -81/// is still no connection the configured [`Discovery`] will be used however. -82const DISCOVERY_WAIT_PERIOD: Duration = Duration::from_millis(500); -83 -84/// A type alias for the return value of [`Endpoint::node_addr`]. -85/// -86/// This type implements [`Watcher`] with `Value` being an optional [`NodeAddr`]. -87/// -88/// We return a named type instead of `impl Watcher<Value = NodeAddr>`, as this allows -89/// you to e.g. store the watcher in a struct. -90#[cfg(not(wasm_browser))] -91pub type NodeAddrWatcher = watcher::Map< -92 ( -93 watcher::Direct<Option<BTreeSet<DirectAddr>>>, -94 watcher::Direct<Option<RelayUrl>>, -95 ), -96 Option<NodeAddr>, -97>; -98/// A type alias for the return value of [`Endpoint::node_addr`]. +28use n0_watcher::Watcher; +29use nested_enum_utils::common_fields; +30use pin_project::pin_project; +31use snafu::{ensure, ResultExt, Snafu}; +32use tracing::{debug, instrument, trace, warn}; +33use url::Url; +34 +35#[cfg(wasm_browser)] +36use crate::discovery::pkarr::PkarrResolver; +37#[cfg(not(wasm_browser))] +38use crate::{discovery::dns::DnsDiscovery, dns::DnsResolver}; +39use crate::{ +40 discovery::{ +41 pkarr::PkarrPublisher, ConcurrentDiscovery, Discovery, DiscoveryContext, DiscoveryError, +42 DiscoveryItem, DiscoverySubscribers, DiscoveryTask, DynIntoDiscovery, IntoDiscovery, +43 IntoDiscoveryError, Lagged, UserData, +44 }, +45 magicsock::{self, Handle, NodeIdMappedAddr, OwnAddressSnafu}, +46 metrics::EndpointMetrics, +47 net_report::Report, +48 tls, RelayProtocol, +49}; +50 +51mod rtt_actor; +52 +53// Missing still: SendDatagram and ConnectionClose::frame_type's Type. +54pub use quinn::{ +55 AcceptBi, AcceptUni, AckFrequencyConfig, ApplicationClose, Chunk, ClosedStream, +56 ConnectionClose, ConnectionError, ConnectionStats, MtuDiscoveryConfig, OpenBi, OpenUni, +57 ReadDatagram, ReadError, ReadExactError, ReadToEndError, RecvStream, ResetError, RetryError, +58 SendDatagramError, SendStream, ServerConfig, StoppedError, StreamId, TransportConfig, VarInt, +59 WeakConnectionHandle, WriteError, +60}; +61pub use quinn_proto::{ +62 congestion::{Controller, ControllerFactory}, +63 crypto::{ +64 AeadKey, CryptoError, ExportKeyingMaterialError, HandshakeTokenKey, +65 ServerConfig as CryptoServerConfig, UnsupportedVersion, +66 }, +67 FrameStats, PathStats, TransportError, TransportErrorCode, UdpStats, Written, +68}; +69 +70use self::rtt_actor::RttMessage; +71pub use super::magicsock::{ +72 AddNodeAddrError, ConnectionType, ControlMsg, DirectAddr, DirectAddrInfo, DirectAddrType, +73 RemoteInfo, Source, +74}; +75 +76/// The delay to fall back to discovery when direct addresses fail. +77/// +78/// When a connection is attempted with a [`NodeAddr`] containing direct addresses the +79/// [`Endpoint`] assumes one of those addresses probably works. If after this delay there +80/// is still no connection the configured [`Discovery`] will be used however. +81const DISCOVERY_WAIT_PERIOD: Duration = Duration::from_millis(500); +82 +83/// Defines the mode of path selection for all traffic flowing through +84/// the endpoint. +85#[cfg(any(test, feature = "test-utils"))] +86#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] +87pub enum PathSelection { +88 /// Uses all available paths +89 #[default] +90 All, +91 /// Forces all traffic to go exclusively through relays +92 RelayOnly, +93} +94 +95/// Builder for [`Endpoint`]. +96/// +97/// By default the endpoint will generate a new random [`SecretKey`], which will result in a +98/// new [`NodeId`]. 99/// -100/// This type implements [`Watcher`] with `Value` being an optional [`NodeAddr`]. -101/// -102/// We return a named type instead of `impl Watcher<Value = NodeAddr>`, as this allows -103/// you to e.g. store the watcher in a struct. -104#[cfg(wasm_browser)] -105pub type NodeAddrWatcher = watcher::Map<watcher::Direct<Option<RelayUrl>>, Option<NodeAddr>>; -106 -107/// Defines the mode of path selection for all traffic flowing through -108/// the endpoint. -109#[cfg(any(test, feature = "test-utils"))] -110#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] -111pub enum PathSelection { -112 /// Uses all available paths -113 #[default] -114 All, -115 /// Forces all traffic to go exclusively through relays -116 RelayOnly, -117} -118 -119/// Builder for [`Endpoint`]. -120/// -121/// By default the endpoint will generate a new random [`SecretKey`], which will result in a -122/// new [`NodeId`]. -123/// -124/// To create the [`Endpoint`] call [`Builder::bind`]. -125#[derive(derive_more::Debug)] -126pub struct Builder { -127 secret_key: Option<SecretKey>, -128 relay_mode: RelayMode, -129 relay_protocol: iroh_relay::http::Protocol, -130 alpn_protocols: Vec<Vec<u8>>, -131 transport_config: quinn::TransportConfig, -132 keylog: bool, -133 #[debug(skip)] -134 discovery: Vec<Box<dyn DynIntoDiscovery>>, -135 discovery_user_data: Option<UserData>, -136 proxy_url: Option<Url>, -137 /// List of known nodes. See [`Builder::known_nodes`]. -138 node_map: Option<Vec<NodeAddr>>, -139 #[cfg(not(wasm_browser))] -140 dns_resolver: Option<DnsResolver>, -141 #[cfg(any(test, feature = "test-utils"))] -142 insecure_skip_relay_cert_verify: bool, -143 addr_v4: Option<SocketAddrV4>, -144 addr_v6: Option<SocketAddrV6>, -145 #[cfg(any(test, feature = "test-utils"))] -146 path_selection: PathSelection, -147} -148 -149impl Default for Builder { -150 fn default() -> Self { -151 let mut transport_config = quinn::TransportConfig::default(); -152 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); -153 Self { -154 secret_key: Default::default(), -155 relay_mode: default_relay_mode(), -156 relay_protocol: iroh_relay::http::Protocol::default(), -157 alpn_protocols: Default::default(), -158 transport_config, -159 keylog: Default::default(), -160 discovery: Default::default(), -161 discovery_user_data: Default::default(), -162 proxy_url: None, -163 node_map: None, -164 #[cfg(not(wasm_browser))] -165 dns_resolver: None, -166 #[cfg(any(test, feature = "test-utils"))] -167 insecure_skip_relay_cert_verify: false, -168 addr_v4: None, -169 addr_v6: None, -170 #[cfg(any(test, feature = "test-utils"))] -171 path_selection: PathSelection::default(), -172 } -173 } -174} -175 -176impl Builder { -177 // The ordering of public methods is reflected directly in the documentation. This is -178 // roughly ordered by what is most commonly needed by users. -179 -180 // # The final constructor that everyone needs. -181 -182 /// Binds the magic endpoint. -183 pub async fn bind(self) -> Result<Endpoint, BindError> { -184 let relay_map = self.relay_mode.relay_map(); -185 let secret_key = self -186 .secret_key -187 .unwrap_or_else(|| SecretKey::generate(rand::rngs::OsRng)); -188 let static_config = StaticConfig { -189 transport_config: Arc::new(self.transport_config), -190 tls_config: tls::TlsConfig::new(secret_key.clone()), -191 keylog: self.keylog, -192 }; -193 let server_config = static_config.create_server_config(self.alpn_protocols); -194 -195 #[cfg(not(wasm_browser))] -196 let dns_resolver = self.dns_resolver.unwrap_or_default(); -197 -198 let discovery: Option<Box<dyn Discovery>> = { -199 let context = DiscoveryContext { -200 secret_key: &secret_key, -201 #[cfg(not(wasm_browser))] -202 dns_resolver: &dns_resolver, -203 }; -204 let discovery = self -205 .discovery -206 .into_iter() -207 .map(|builder| builder.into_discovery(&context)) -208 .collect::<Result<Vec<_>, IntoDiscoveryError>>()?; -209 match discovery.len() { -210 0 => None, -211 1 => Some(discovery.into_iter().next().expect("checked length")), -212 _ => Some(Box::new(ConcurrentDiscovery::from_services(discovery))), -213 } -214 }; +100/// To create the [`Endpoint`] call [`Builder::bind`]. +101#[derive(Debug)] +102pub struct Builder { +103 secret_key: Option<SecretKey>, +104 relay_mode: RelayMode, +105 relay_protocol: iroh_relay::http::Protocol, +106 alpn_protocols: Vec<Vec<u8>>, +107 transport_config: quinn::TransportConfig, +108 keylog: bool, +109 discovery: Vec<Box<dyn DynIntoDiscovery>>, +110 discovery_user_data: Option<UserData>, +111 proxy_url: Option<Url>, +112 /// List of known nodes. See [`Builder::known_nodes`]. +113 node_map: Option<Vec<NodeAddr>>, +114 #[cfg(not(wasm_browser))] +115 dns_resolver: Option<DnsResolver>, +116 #[cfg(any(test, feature = "test-utils"))] +117 insecure_skip_relay_cert_verify: bool, +118 addr_v4: Option<SocketAddrV4>, +119 addr_v6: Option<SocketAddrV6>, +120 #[cfg(any(test, feature = "test-utils"))] +121 path_selection: PathSelection, +122} +123 +124impl Default for Builder { +125 fn default() -> Self { +126 let mut transport_config = quinn::TransportConfig::default(); +127 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); +128 Self { +129 secret_key: Default::default(), +130 relay_mode: default_relay_mode(), +131 relay_protocol: iroh_relay::http::Protocol::default(), +132 alpn_protocols: Default::default(), +133 transport_config, +134 keylog: Default::default(), +135 discovery: Default::default(), +136 discovery_user_data: Default::default(), +137 proxy_url: None, +138 node_map: None, +139 #[cfg(not(wasm_browser))] +140 dns_resolver: None, +141 #[cfg(any(test, feature = "test-utils"))] +142 insecure_skip_relay_cert_verify: false, +143 addr_v4: None, +144 addr_v6: None, +145 #[cfg(any(test, feature = "test-utils"))] +146 path_selection: PathSelection::default(), +147 } +148 } +149} +150 +151impl Builder { +152 // The ordering of public methods is reflected directly in the documentation. This is +153 // roughly ordered by what is most commonly needed by users. +154 +155 // # The final constructor that everyone needs. +156 +157 /// Binds the magic endpoint. +158 pub async fn bind(self) -> Result<Endpoint, BindError> { +159 let relay_map = self.relay_mode.relay_map(); +160 let secret_key = self +161 .secret_key +162 .unwrap_or_else(|| SecretKey::generate(rand::rngs::OsRng)); +163 let static_config = StaticConfig { +164 transport_config: Arc::new(self.transport_config), +165 tls_config: tls::TlsConfig::new(secret_key.clone()), +166 keylog: self.keylog, +167 }; +168 let server_config = static_config.create_server_config(self.alpn_protocols); +169 +170 #[cfg(not(wasm_browser))] +171 let dns_resolver = self.dns_resolver.unwrap_or_default(); +172 +173 let discovery: Option<Box<dyn Discovery>> = { +174 let context = DiscoveryContext { +175 secret_key: &secret_key, +176 #[cfg(not(wasm_browser))] +177 dns_resolver: &dns_resolver, +178 }; +179 let discovery = self +180 .discovery +181 .into_iter() +182 .map(|builder| builder.into_discovery(&context)) +183 .collect::<Result<Vec<_>, IntoDiscoveryError>>()?; +184 match discovery.len() { +185 0 => None, +186 1 => Some(discovery.into_iter().next().expect("checked length")), +187 _ => Some(Box::new(ConcurrentDiscovery::from_services(discovery))), +188 } +189 }; +190 +191 let metrics = EndpointMetrics::default(); +192 +193 let msock_opts = magicsock::Options { +194 addr_v4: self.addr_v4, +195 addr_v6: self.addr_v6, +196 secret_key, +197 relay_map, +198 relay_protocol: self.relay_protocol, +199 node_map: self.node_map, +200 discovery, +201 discovery_user_data: self.discovery_user_data, +202 proxy_url: self.proxy_url, +203 #[cfg(not(wasm_browser))] +204 dns_resolver, +205 server_config, +206 #[cfg(any(test, feature = "test-utils"))] +207 insecure_skip_relay_cert_verify: self.insecure_skip_relay_cert_verify, +208 #[cfg(any(test, feature = "test-utils"))] +209 path_selection: self.path_selection, +210 metrics, +211 }; +212 +213 Endpoint::bind(static_config, msock_opts).await +214 } 215 -216 let metrics = EndpointMetrics::default(); +216 // # The very common methods everyone basically needs. 217 -218 let msock_opts = magicsock::Options { -219 addr_v4: self.addr_v4, -220 addr_v6: self.addr_v6, -221 secret_key, -222 relay_map, -223 relay_protocol: self.relay_protocol, -224 node_map: self.node_map, -225 discovery, -226 discovery_user_data: self.discovery_user_data, -227 proxy_url: self.proxy_url, -228 #[cfg(not(wasm_browser))] -229 dns_resolver, -230 server_config, -231 #[cfg(any(test, feature = "test-utils"))] -232 insecure_skip_relay_cert_verify: self.insecure_skip_relay_cert_verify, -233 #[cfg(any(test, feature = "test-utils"))] -234 path_selection: self.path_selection, -235 metrics, -236 }; -237 -238 Endpoint::bind(static_config, msock_opts).await -239 } -240 -241 // # The very common methods everyone basically needs. -242 -243 /// Sets the IPv4 bind address. +218 /// Sets the IPv4 bind address. +219 /// +220 /// Setting the port to `0` will use a random port. +221 /// If the port specified is already in use, it will fallback to choosing a random port. +222 /// +223 /// By default will use `0.0.0.0:0` to bind to. +224 pub fn bind_addr_v4(mut self, addr: SocketAddrV4) -> Self { +225 self.addr_v4.replace(addr); +226 self +227 } +228 +229 /// Sets the IPv6 bind address. +230 /// +231 /// Setting the port to `0` will use a random port. +232 /// If the port specified is already in use, it will fallback to choosing a random port. +233 /// +234 /// By default will use `[::]:0` to bind to. +235 pub fn bind_addr_v6(mut self, addr: SocketAddrV6) -> Self { +236 self.addr_v6.replace(addr); +237 self +238 } +239 +240 /// Sets a secret key to authenticate with other peers. +241 /// +242 /// This secret key's public key will be the [`PublicKey`] of this endpoint and thus +243 /// also its [`NodeId`] 244 /// -245 /// Setting the port to `0` will use a random port. -246 /// If the port specified is already in use, it will fallback to choosing a random port. -247 /// -248 /// By default will use `0.0.0.0:0` to bind to. -249 pub fn bind_addr_v4(mut self, addr: SocketAddrV4) -> Self { -250 self.addr_v4.replace(addr); -251 self -252 } -253 -254 /// Sets the IPv6 bind address. -255 /// -256 /// Setting the port to `0` will use a random port. -257 /// If the port specified is already in use, it will fallback to choosing a random port. -258 /// -259 /// By default will use `[::]:0` to bind to. -260 pub fn bind_addr_v6(mut self, addr: SocketAddrV6) -> Self { -261 self.addr_v6.replace(addr); -262 self -263 } -264 -265 /// Sets a secret key to authenticate with other peers. -266 /// -267 /// This secret key's public key will be the [`PublicKey`] of this endpoint and thus -268 /// also its [`NodeId`] -269 /// -270 /// If not set, a new secret key will be generated. +245 /// If not set, a new secret key will be generated. +246 /// +247 /// [`PublicKey`]: iroh_base::PublicKey +248 pub fn secret_key(mut self, secret_key: SecretKey) -> Self { +249 self.secret_key = Some(secret_key); +250 self +251 } +252 +253 /// Sets the [ALPN] protocols that this endpoint will accept on incoming connections. +254 /// +255 /// Not setting this will still allow creating connections, but to accept incoming +256 /// connections at least one [ALPN] must be set. +257 /// +258 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation +259 pub fn alpns(mut self, alpn_protocols: Vec<Vec<u8>>) -> Self { +260 self.alpn_protocols = alpn_protocols; +261 self +262 } +263 +264 // # Methods for common customisation items. +265 +266 /// Sets the relay servers to assist in establishing connectivity. +267 /// +268 /// Relay servers are used to establish initial connection with another iroh node. +269 /// They also perform various functions related to hole punching, see the [crate docs] +270 /// for more details. 271 /// -272 /// [`PublicKey`]: iroh_base::PublicKey -273 pub fn secret_key(mut self, secret_key: SecretKey) -> Self { -274 self.secret_key = Some(secret_key); -275 self -276 } -277 -278 /// Sets the [ALPN] protocols that this endpoint will accept on incoming connections. -279 /// -280 /// Not setting this will still allow creating connections, but to accept incoming -281 /// connections at least one [ALPN] must be set. -282 /// -283 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation -284 pub fn alpns(mut self, alpn_protocols: Vec<Vec<u8>>) -> Self { -285 self.alpn_protocols = alpn_protocols; -286 self -287 } -288 -289 // # Methods for common customisation items. -290 -291 /// Sets the relay servers to assist in establishing connectivity. +272 /// By default the [number 0] relay servers are used, see [`RelayMode::Default`]. +273 /// +274 /// When using [RelayMode::Custom], the provided `relay_map` must contain at least one +275 /// configured relay node. If an invalid RelayMap is provided [`bind`] +276 /// will result in an error. +277 /// +278 /// [`bind`]: Builder::bind +279 /// [crate docs]: crate +280 /// [number 0]: https://n0.computer +281 pub fn relay_mode(mut self, relay_mode: RelayMode) -> Self { +282 self.relay_mode = relay_mode; +283 self +284 } +285 +286 /// Sets the protocol to use for relay connections. +287 /// +288 /// Options are either [`RelayProtocol::Websocket`] or [`RelayProtocol::Relay`]. +289 /// +290 /// `Websocket` is considered unstable between iroh versions at the moment. +291 /// The protocol can change in compatibility-breaking ways before iroh 1.0. 292 /// -293 /// Relay servers are used to establish initial connection with another iroh node. -294 /// They also perform various functions related to hole punching, see the [crate docs] -295 /// for more details. -296 /// -297 /// By default the [number 0] relay servers are used, see [`RelayMode::Default`]. -298 /// -299 /// When using [RelayMode::Custom], the provided `relay_map` must contain at least one -300 /// configured relay node. If an invalid RelayMap is provided [`bind`] -301 /// will result in an error. -302 /// -303 /// [`bind`]: Builder::bind -304 /// [crate docs]: crate -305 /// [number 0]: https://n0.computer -306 pub fn relay_mode(mut self, relay_mode: RelayMode) -> Self { -307 self.relay_mode = relay_mode; -308 self -309 } -310 -311 /// Sets the protocol to use for relay connections. -312 /// -313 /// Options are either [`RelayProtocol::Websocket`] or [`RelayProtocol::Relay`]. -314 /// -315 /// `Websocket` is considered unstable between iroh versions at the moment. -316 /// The protocol can change in compatibility-breaking ways before iroh 1.0. -317 /// -318 /// Default is set to `Relay` at the moment, until we've stabilized the websocket protocol. -319 pub fn relay_conn_protocol(mut self, protocol: RelayProtocol) -> Self { -320 self.relay_protocol = protocol; -321 self -322 } -323 -324 /// Removes all discovery services from the builder. -325 pub fn clear_discovery(mut self) -> Self { -326 self.discovery.clear(); -327 self -328 } -329 -330 /// Optionally sets a discovery mechanism for this endpoint. -331 /// -332 /// If you want to combine multiple discovery services, you can use -333 /// [`Builder::add_discovery`] instead. This will internally create a -334 /// [`crate::discovery::ConcurrentDiscovery`]. +293 /// Default is set to `Relay` at the moment, until we've stabilized the websocket protocol. +294 pub fn relay_conn_protocol(mut self, protocol: RelayProtocol) -> Self { +295 self.relay_protocol = protocol; +296 self +297 } +298 +299 /// Removes all discovery services from the builder. +300 pub fn clear_discovery(mut self) -> Self { +301 self.discovery.clear(); +302 self +303 } +304 +305 /// Optionally sets a discovery mechanism for this endpoint. +306 /// +307 /// If you want to combine multiple discovery services, you can use +308 /// [`Builder::add_discovery`] instead. This will internally create a +309 /// [`crate::discovery::ConcurrentDiscovery`]. +310 /// +311 /// If no discovery service is set, connecting to a node without providing its +312 /// direct addresses or relay URLs will fail. +313 /// +314 /// See the documentation of the [`Discovery`] trait for details. +315 pub fn discovery(mut self, discovery: impl IntoDiscovery) -> Self { +316 self.discovery.clear(); +317 self.discovery.push(Box::new(discovery)); +318 self +319 } +320 +321 /// Adds a discovery mechanism for this endpoint. +322 /// +323 /// The function `discovery` +324 /// will be called on endpoint creation with the configured secret key of +325 /// the endpoint. Discovery services that need to publish information need +326 /// to use this secret key to sign the information. +327 /// +328 /// If you add multiple discovery services, they will be combined using a +329 /// [`crate::discovery::ConcurrentDiscovery`]. +330 /// +331 /// If no discovery service is set, connecting to a node without providing its +332 /// direct addresses or relay URLs will fail. +333 /// +334 /// To clear all discovery services, use [`Builder::clear_discovery`]. 335 /// -336 /// If no discovery service is set, connecting to a node without providing its -337 /// direct addresses or relay URLs will fail. -338 /// -339 /// See the documentation of the [`Discovery`] trait for details. -340 pub fn discovery(mut self, discovery: impl IntoDiscovery) -> Self { -341 self.discovery.clear(); -342 self.discovery.push(Box::new(discovery)); -343 self -344 } -345 -346 /// Adds a discovery mechanism for this endpoint. -347 /// -348 /// The function `discovery` -349 /// will be called on endpoint creation with the configured secret key of -350 /// the endpoint. Discovery services that need to publish information need -351 /// to use this secret key to sign the information. -352 /// -353 /// If you add multiple discovery services, they will be combined using a -354 /// [`crate::discovery::ConcurrentDiscovery`]. -355 /// -356 /// If no discovery service is set, connecting to a node without providing its -357 /// direct addresses or relay URLs will fail. -358 /// -359 /// To clear all discovery services, use [`Builder::clear_discovery`]. -360 /// -361 /// See the documentation of the [`Discovery`] trait for details. -362 pub fn add_discovery(mut self, discovery: impl IntoDiscovery) -> Self { -363 self.discovery.push(Box::new(discovery)); -364 self -365 } -366 -367 /// Configures the endpoint to use the default n0 DNS discovery service. -368 /// -369 /// The default discovery service publishes to and resolves from the -370 /// n0.computer dns server `iroh.link`. -371 /// -372 /// This is equivalent to adding both a [`crate::discovery::pkarr::PkarrPublisher`] -373 /// and a [`crate::discovery::dns::DnsDiscovery`], both configured to use the -374 /// n0.computer dns server. -375 /// -376 /// This will by default use [`N0_DNS_PKARR_RELAY_PROD`]. -377 /// When in tests, or when the `test-utils` feature is enabled, this will use the -378 /// [`N0_DNS_PKARR_RELAY_STAGING`]. -379 /// -380 /// [`N0_DNS_PKARR_RELAY_PROD`]: crate::discovery::pkarr::N0_DNS_PKARR_RELAY_PROD -381 /// [`N0_DNS_PKARR_RELAY_STAGING`]: crate::discovery::pkarr::N0_DNS_PKARR_RELAY_STAGING -382 pub fn discovery_n0(mut self) -> Self { -383 self = self.add_discovery(PkarrPublisher::n0_dns()); -384 // Resolve using HTTPS requests to our DNS server's /pkarr path in browsers -385 #[cfg(wasm_browser)] -386 { -387 self = self.add_discovery(PkarrResolver::n0_dns()); -388 } -389 // Resolve using DNS queries outside browsers. -390 #[cfg(not(wasm_browser))] -391 { -392 self = self.add_discovery(DnsDiscovery::n0_dns()); -393 } -394 self -395 } -396 -397 #[cfg(feature = "discovery-pkarr-dht")] -398 /// Configures the endpoint to also use the mainline DHT with default settings. -399 /// -400 /// This is equivalent to adding a [`crate::discovery::pkarr::dht::DhtDiscovery`] -401 /// with default settings. Note that DhtDiscovery has various more advanced -402 /// configuration options. If you need any of those, you should manually -403 /// create a DhtDiscovery and add it with [`Builder::add_discovery`]. -404 pub fn discovery_dht(mut self) -> Self { -405 self = self.add_discovery(crate::discovery::pkarr::dht::DhtDiscovery::builder()); +336 /// See the documentation of the [`Discovery`] trait for details. +337 pub fn add_discovery(mut self, discovery: impl IntoDiscovery) -> Self { +338 self.discovery.push(Box::new(discovery)); +339 self +340 } +341 +342 /// Configures the endpoint to use the default n0 DNS discovery service. +343 /// +344 /// The default discovery service publishes to and resolves from the +345 /// n0.computer dns server `iroh.link`. +346 /// +347 /// This is equivalent to adding both a [`crate::discovery::pkarr::PkarrPublisher`] +348 /// and a [`crate::discovery::dns::DnsDiscovery`], both configured to use the +349 /// n0.computer dns server. +350 /// +351 /// This will by default use [`N0_DNS_PKARR_RELAY_PROD`]. +352 /// When in tests, or when the `test-utils` feature is enabled, this will use the +353 /// [`N0_DNS_PKARR_RELAY_STAGING`]. +354 /// +355 /// [`N0_DNS_PKARR_RELAY_PROD`]: crate::discovery::pkarr::N0_DNS_PKARR_RELAY_PROD +356 /// [`N0_DNS_PKARR_RELAY_STAGING`]: crate::discovery::pkarr::N0_DNS_PKARR_RELAY_STAGING +357 pub fn discovery_n0(mut self) -> Self { +358 self = self.add_discovery(PkarrPublisher::n0_dns()); +359 // Resolve using HTTPS requests to our DNS server's /pkarr path in browsers +360 #[cfg(wasm_browser)] +361 { +362 self = self.add_discovery(PkarrResolver::n0_dns()); +363 } +364 // Resolve using DNS queries outside browsers. +365 #[cfg(not(wasm_browser))] +366 { +367 self = self.add_discovery(DnsDiscovery::n0_dns()); +368 } +369 self +370 } +371 +372 #[cfg(feature = "discovery-pkarr-dht")] +373 /// Configures the endpoint to also use the mainline DHT with default settings. +374 /// +375 /// This is equivalent to adding a [`crate::discovery::pkarr::dht::DhtDiscovery`] +376 /// with default settings. Note that DhtDiscovery has various more advanced +377 /// configuration options. If you need any of those, you should manually +378 /// create a DhtDiscovery and add it with [`Builder::add_discovery`]. +379 pub fn discovery_dht(mut self) -> Self { +380 self = self.add_discovery(crate::discovery::pkarr::dht::DhtDiscovery::builder()); +381 self +382 } +383 +384 #[cfg(feature = "discovery-local-network")] +385 /// Configures the endpoint to also use local network discovery. +386 /// +387 /// This is equivalent to adding a [`crate::discovery::mdns::MdnsDiscovery`] +388 /// with default settings. Note that MdnsDiscovery has various more advanced +389 /// configuration options. If you need any of those, you should manually +390 /// create a MdnsDiscovery and add it with [`Builder::add_discovery`]. +391 pub fn discovery_local_network(mut self) -> Self { +392 self = self.add_discovery(crate::discovery::mdns::MdnsDiscovery::builder()); +393 self +394 } +395 +396 /// Sets the initial user-defined data to be published in discovery services for this node. +397 /// +398 /// When using discovery services, this string of [`UserData`] will be published together +399 /// with the node's addresses and relay URL. When other nodes discover this node, +400 /// they retrieve the [`UserData`] in addition to the addressing info. +401 /// +402 /// Iroh itself does not interpret the user-defined data in any way, it is purely left +403 /// for applications to parse and use. +404 pub fn user_data_for_discovery(mut self, user_data: UserData) -> Self { +405 self.discovery_user_data = Some(user_data); 406 self 407 } 408 -409 #[cfg(feature = "discovery-local-network")] -410 /// Configures the endpoint to also use local network discovery. -411 /// -412 /// This is equivalent to adding a [`crate::discovery::mdns::MdnsDiscovery`] -413 /// with default settings. Note that MdnsDiscovery has various more advanced -414 /// configuration options. If you need any of those, you should manually -415 /// create a MdnsDiscovery and add it with [`Builder::add_discovery`]. -416 pub fn discovery_local_network(mut self) -> Self { -417 self = self.add_discovery(crate::discovery::mdns::MdnsDiscovery::builder()); -418 self -419 } -420 -421 /// Sets the initial user-defined data to be published in discovery services for this node. -422 /// -423 /// When using discovery services, this string of [`UserData`] will be published together -424 /// with the node's addresses and relay URL. When other nodes discover this node, -425 /// they retrieve the [`UserData`] in addition to the addressing info. -426 /// -427 /// Iroh itself does not interpret the user-defined data in any way, it is purely left -428 /// for applications to parse and use. -429 pub fn user_data_for_discovery(mut self, user_data: UserData) -> Self { -430 self.discovery_user_data = Some(user_data); -431 self -432 } -433 -434 /// Optionally set a list of known nodes. -435 pub fn known_nodes(mut self, nodes: Vec<NodeAddr>) -> Self { -436 self.node_map = Some(nodes); -437 self -438 } -439 -440 // # Methods for more specialist customisation. -441 -442 /// Sets a custom [`quinn::TransportConfig`] for this endpoint. -443 /// -444 /// The transport config contains parameters governing the QUIC state machine. -445 /// -446 /// If unset, the default config is used. Default values should be suitable for most -447 /// internet applications. Applications protocols which forbid remotely-initiated -448 /// streams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to -449 /// zero. -450 /// -451 /// Please be aware that changing some settings may have adverse effects on establishing -452 /// and maintaining direct connections. -453 pub fn transport_config(mut self, transport_config: quinn::TransportConfig) -> Self { -454 self.transport_config = transport_config; -455 self -456 } -457 -458 /// Optionally sets a custom DNS resolver to use for this endpoint. -459 /// -460 /// The DNS resolver is used to resolve relay hostnames, and node addresses if -461 /// [`crate::discovery::dns::DnsDiscovery`] is configured. -462 /// -463 /// By default, a new DNS resolver is created which is configured to use the -464 /// host system's DNS configuration. You can pass a custom instance of [`DnsResolver`] -465 /// here to use a differently configured DNS resolver for this endpoint, or to share -466 /// a [`DnsResolver`] between multiple endpoints. -467 #[cfg(not(wasm_browser))] -468 pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self { -469 self.dns_resolver = Some(dns_resolver); -470 self -471 } -472 -473 /// Sets an explicit proxy url to proxy all HTTP(S) traffic through. -474 pub fn proxy_url(mut self, url: Url) -> Self { -475 self.proxy_url.replace(url); -476 self -477 } -478 -479 /// Sets the proxy url from the environment, in this order: -480 /// -481 /// - `HTTP_PROXY` -482 /// - `http_proxy` -483 /// - `HTTPS_PROXY` -484 /// - `https_proxy` -485 pub fn proxy_from_env(mut self) -> Self { -486 self.proxy_url = proxy_url_from_env(); -487 self -488 } -489 -490 /// Enables saving the TLS pre-master key for connections. -491 /// -492 /// This key should normally remain secret but can be useful to debug networking issues -493 /// by decrypting captured traffic. -494 /// -495 /// If *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a -496 /// filename will result in this file being used to log the TLS pre-master keys. -497 pub fn keylog(mut self, keylog: bool) -> Self { -498 self.keylog = keylog; -499 self -500 } -501 -502 /// Skip verification of SSL certificates from relay servers -503 /// -504 /// May only be used in tests. -505 #[cfg(any(test, feature = "test-utils"))] -506 pub fn insecure_skip_relay_cert_verify(mut self, skip_verify: bool) -> Self { -507 self.insecure_skip_relay_cert_verify = skip_verify; -508 self -509 } -510 -511 /// This implies we only use the relay to communicate -512 /// and do not attempt to do any hole punching. -513 #[cfg(any(test, feature = "test-utils"))] -514 pub fn path_selection(mut self, path_selection: PathSelection) -> Self { -515 self.path_selection = path_selection; -516 self -517 } -518} -519 -520/// Configuration for a [`quinn::Endpoint`] that cannot be changed at runtime. -521#[derive(Debug)] -522struct StaticConfig { -523 tls_config: tls::TlsConfig, -524 transport_config: Arc<quinn::TransportConfig>, -525 keylog: bool, -526} -527 -528impl StaticConfig { -529 /// Create a [`quinn::ServerConfig`] with the specified ALPN protocols. -530 fn create_server_config(&self, alpn_protocols: Vec<Vec<u8>>) -> ServerConfig { -531 let quic_server_config = self -532 .tls_config -533 .make_server_config(alpn_protocols, self.keylog); -534 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); -535 server_config.transport_config(self.transport_config.clone()); -536 -537 server_config -538 } -539} -540 -541/// Controls an iroh node, establishing connections with other nodes. -542/// -543/// This is the main API interface to create connections to, and accept connections from -544/// other iroh nodes. The connections are peer-to-peer and encrypted, a Relay server is -545/// used to make the connections reliable. See the [crate docs] for a more detailed -546/// overview of iroh. -547/// -548/// It is recommended to only create a single instance per application. This ensures all -549/// the connections made share the same peer-to-peer connections to other iroh nodes, -550/// while still remaining independent connections. This will result in more optimal network -551/// behaviour. -552/// -553/// The endpoint is created using the [`Builder`], which can be created using -554/// [`Endpoint::builder`]. -555/// -556/// Once an endpoint exists, new connections are typically created using the -557/// [`Endpoint::connect`] and [`Endpoint::accept`] methods. Once established, the -558/// [`Connection`] gives access to most [QUIC] features. Individual streams to send data to -559/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`], -560/// [`Connection::open_uni`] and [`Connection::open_bi`] functions. -561/// -562/// Note that due to the light-weight properties of streams a stream will only be accepted -563/// once the initiating peer has sent some data on it. -564/// -565/// [QUIC]: https://quicwg.org -566#[derive(Clone, Debug)] -567pub struct Endpoint { -568 /// Handle to the magicsocket/actor -569 msock: Handle, -570 /// Handle to the actor that resets the quinn RTT estimator -571 rtt_actor: Arc<rtt_actor::RttHandle>, -572 /// Configuration structs for quinn, holds the transport config, certificate setup, secret key etc. -573 static_config: Arc<StaticConfig>, -574} -575 -576#[allow(missing_docs)] -577#[common_fields({ -578 backtrace: Option<snafu::Backtrace>, -579 #[snafu(implicit)] -580 span_trace: n0_snafu::SpanTrace, -581})] -582#[derive(Debug, Snafu)] -583#[non_exhaustive] -584pub enum ConnectWithOptsError { -585 #[snafu(transparent)] -586 AddNodeAddr { source: AddNodeAddrError }, -587 #[snafu(display("Connecting to ourself is not supported"))] -588 SelfConnect {}, -589 #[snafu(display("No addressing information available"))] -590 NoAddress { source: GetMappingAddressError }, -591 #[snafu(display("Unable to connect to remote"))] -592 Quinn { source: quinn::ConnectError }, -593} -594 -595#[allow(missing_docs)] -596#[common_fields({ -597 backtrace: Option<snafu::Backtrace>, -598 #[snafu(implicit)] -599 span_trace: n0_snafu::SpanTrace, -600})] -601#[derive(Debug, Snafu)] -602#[non_exhaustive] -603pub enum ConnectError { +409 /// Optionally set a list of known nodes. +410 pub fn known_nodes(mut self, nodes: Vec<NodeAddr>) -> Self { +411 self.node_map = Some(nodes); +412 self +413 } +414 +415 // # Methods for more specialist customisation. +416 +417 /// Sets a custom [`quinn::TransportConfig`] for this endpoint. +418 /// +419 /// The transport config contains parameters governing the QUIC state machine. +420 /// +421 /// If unset, the default config is used. Default values should be suitable for most +422 /// internet applications. Applications protocols which forbid remotely-initiated +423 /// streams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to +424 /// zero. +425 /// +426 /// Please be aware that changing some settings may have adverse effects on establishing +427 /// and maintaining direct connections. +428 pub fn transport_config(mut self, transport_config: quinn::TransportConfig) -> Self { +429 self.transport_config = transport_config; +430 self +431 } +432 +433 /// Optionally sets a custom DNS resolver to use for this endpoint. +434 /// +435 /// The DNS resolver is used to resolve relay hostnames, and node addresses if +436 /// [`crate::discovery::dns::DnsDiscovery`] is configured. +437 /// +438 /// By default, a new DNS resolver is created which is configured to use the +439 /// host system's DNS configuration. You can pass a custom instance of [`DnsResolver`] +440 /// here to use a differently configured DNS resolver for this endpoint, or to share +441 /// a [`DnsResolver`] between multiple endpoints. +442 #[cfg(not(wasm_browser))] +443 pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self { +444 self.dns_resolver = Some(dns_resolver); +445 self +446 } +447 +448 /// Sets an explicit proxy url to proxy all HTTP(S) traffic through. +449 pub fn proxy_url(mut self, url: Url) -> Self { +450 self.proxy_url.replace(url); +451 self +452 } +453 +454 /// Sets the proxy url from the environment, in this order: +455 /// +456 /// - `HTTP_PROXY` +457 /// - `http_proxy` +458 /// - `HTTPS_PROXY` +459 /// - `https_proxy` +460 pub fn proxy_from_env(mut self) -> Self { +461 self.proxy_url = proxy_url_from_env(); +462 self +463 } +464 +465 /// Enables saving the TLS pre-master key for connections. +466 /// +467 /// This key should normally remain secret but can be useful to debug networking issues +468 /// by decrypting captured traffic. +469 /// +470 /// If *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a +471 /// filename will result in this file being used to log the TLS pre-master keys. +472 pub fn keylog(mut self, keylog: bool) -> Self { +473 self.keylog = keylog; +474 self +475 } +476 +477 /// Skip verification of SSL certificates from relay servers +478 /// +479 /// May only be used in tests. +480 #[cfg(any(test, feature = "test-utils"))] +481 pub fn insecure_skip_relay_cert_verify(mut self, skip_verify: bool) -> Self { +482 self.insecure_skip_relay_cert_verify = skip_verify; +483 self +484 } +485 +486 /// This implies we only use the relay to communicate +487 /// and do not attempt to do any hole punching. +488 #[cfg(any(test, feature = "test-utils"))] +489 pub fn path_selection(mut self, path_selection: PathSelection) -> Self { +490 self.path_selection = path_selection; +491 self +492 } +493} +494 +495/// Configuration for a [`quinn::Endpoint`] that cannot be changed at runtime. +496#[derive(Debug)] +497struct StaticConfig { +498 tls_config: tls::TlsConfig, +499 transport_config: Arc<quinn::TransportConfig>, +500 keylog: bool, +501} +502 +503impl StaticConfig { +504 /// Create a [`quinn::ServerConfig`] with the specified ALPN protocols. +505 fn create_server_config(&self, alpn_protocols: Vec<Vec<u8>>) -> ServerConfig { +506 let quic_server_config = self +507 .tls_config +508 .make_server_config(alpn_protocols, self.keylog); +509 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); +510 server_config.transport_config(self.transport_config.clone()); +511 +512 server_config +513 } +514} +515 +516/// Controls an iroh node, establishing connections with other nodes. +517/// +518/// This is the main API interface to create connections to, and accept connections from +519/// other iroh nodes. The connections are peer-to-peer and encrypted, a Relay server is +520/// used to make the connections reliable. See the [crate docs] for a more detailed +521/// overview of iroh. +522/// +523/// It is recommended to only create a single instance per application. This ensures all +524/// the connections made share the same peer-to-peer connections to other iroh nodes, +525/// while still remaining independent connections. This will result in more optimal network +526/// behaviour. +527/// +528/// The endpoint is created using the [`Builder`], which can be created using +529/// [`Endpoint::builder`]. +530/// +531/// Once an endpoint exists, new connections are typically created using the +532/// [`Endpoint::connect`] and [`Endpoint::accept`] methods. Once established, the +533/// [`Connection`] gives access to most [QUIC] features. Individual streams to send data to +534/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`], +535/// [`Connection::open_uni`] and [`Connection::open_bi`] functions. +536/// +537/// Note that due to the light-weight properties of streams a stream will only be accepted +538/// once the initiating peer has sent some data on it. +539/// +540/// [QUIC]: https://quicwg.org +541#[derive(Clone, Debug)] +542pub struct Endpoint { +543 /// Handle to the magicsocket/actor +544 msock: Handle, +545 /// Handle to the actor that resets the quinn RTT estimator +546 rtt_actor: Arc<rtt_actor::RttHandle>, +547 /// Configuration structs for quinn, holds the transport config, certificate setup, secret key etc. +548 static_config: Arc<StaticConfig>, +549} +550 +551#[allow(missing_docs)] +552#[common_fields({ +553 backtrace: Option<snafu::Backtrace>, +554 #[snafu(implicit)] +555 span_trace: n0_snafu::SpanTrace, +556})] +557#[derive(Debug, Snafu)] +558#[non_exhaustive] +559pub enum ConnectWithOptsError { +560 #[snafu(transparent)] +561 AddNodeAddr { source: AddNodeAddrError }, +562 #[snafu(display("Connecting to ourself is not supported"))] +563 SelfConnect {}, +564 #[snafu(display("No addressing information available"))] +565 NoAddress { source: GetMappingAddressError }, +566 #[snafu(display("Unable to connect to remote"))] +567 Quinn { source: quinn::ConnectError }, +568} +569 +570#[allow(missing_docs)] +571#[common_fields({ +572 backtrace: Option<snafu::Backtrace>, +573 #[snafu(implicit)] +574 span_trace: n0_snafu::SpanTrace, +575})] +576#[derive(Debug, Snafu)] +577#[non_exhaustive] +578pub enum ConnectError { +579 #[snafu(transparent)] +580 Connect { +581 #[snafu(source(from(ConnectWithOptsError, Box::new)))] +582 source: Box<ConnectWithOptsError>, +583 }, +584 #[snafu(transparent)] +585 Connection { +586 #[snafu(source(from(ConnectionError, Box::new)))] +587 source: Box<ConnectionError>, +588 }, +589} +590 +591#[allow(missing_docs)] +592#[common_fields({ +593 backtrace: Option<snafu::Backtrace>, +594 #[snafu(implicit)] +595 span_trace: n0_snafu::SpanTrace, +596})] +597#[derive(Debug, Snafu)] +598#[non_exhaustive] +599pub enum BindError { +600 #[snafu(transparent)] +601 MagicSpawn { +602 source: magicsock::CreateHandleError, +603 }, 604 #[snafu(transparent)] -605 Connect { -606 #[snafu(source(from(ConnectWithOptsError, Box::new)))] -607 source: Box<ConnectWithOptsError>, -608 }, -609 #[snafu(transparent)] -610 Connection { -611 #[snafu(source(from(ConnectionError, Box::new)))] -612 source: Box<ConnectionError>, -613 }, -614} -615 -616#[allow(missing_docs)] -617#[common_fields({ -618 backtrace: Option<snafu::Backtrace>, -619 #[snafu(implicit)] -620 span_trace: n0_snafu::SpanTrace, -621})] -622#[derive(Debug, Snafu)] -623#[non_exhaustive] -624pub enum BindError { -625 #[snafu(transparent)] -626 MagicSpawn { -627 source: magicsock::CreateHandleError, -628 }, -629 #[snafu(transparent)] -630 Discovery { -631 source: crate::discovery::IntoDiscoveryError, -632 }, -633} +605 Discovery { +606 source: crate::discovery::IntoDiscoveryError, +607 }, +608} +609 +610#[allow(missing_docs)] +611#[common_fields({ +612 backtrace: Option<snafu::Backtrace>, +613 #[snafu(implicit)] +614 span_trace: n0_snafu::SpanTrace, +615})] +616#[derive(Debug, Snafu)] +617#[snafu(module)] +618#[non_exhaustive] +619pub enum GetMappingAddressError { +620 #[snafu(display("Discovery service required due to missing addressing information"))] +621 DiscoveryStart { source: DiscoveryError }, +622 #[snafu(display("Discovery service failed"))] +623 Discover { source: DiscoveryError }, +624 #[snafu(display("No addressing information found"))] +625 NoAddress {}, +626} +627 +628impl Endpoint { +629 // The ordering of public methods is reflected directly in the documentation. This is +630 // roughly ordered by what is most commonly needed by users, but grouped in similar +631 // items. +632 +633 // # Methods relating to construction. 634 -635#[allow(missing_docs)] -636#[common_fields({ -637 backtrace: Option<snafu::Backtrace>, -638 #[snafu(implicit)] -639 span_trace: n0_snafu::SpanTrace, -640})] -641#[derive(Debug, Snafu)] -642#[snafu(module)] -643#[non_exhaustive] -644pub enum GetMappingAddressError { -645 #[snafu(display("Discovery service required due to missing addressing information"))] -646 DiscoveryStart { source: DiscoveryError }, -647 #[snafu(display("Discovery service failed"))] -648 Discover { source: DiscoveryError }, -649 #[snafu(display("No addressing information found"))] -650 NoAddress {}, -651} +635 /// Returns the builder for an [`Endpoint`], with a production configuration. +636 pub fn builder() -> Builder { +637 Builder::default() +638 } +639 +640 /// Creates a quinn endpoint backed by a magicsock. +641 /// +642 /// This is for internal use, the public interface is the [`Builder`] obtained from +643 /// [Self::builder]. See the methods on the builder for documentation of the parameters. +644 #[instrument("ep", skip_all, fields(me = %static_config.tls_config.secret_key.public().fmt_short()))] +645 async fn bind( +646 static_config: StaticConfig, +647 msock_opts: magicsock::Options, +648 ) -> Result<Self, BindError> { +649 let msock = magicsock::MagicSock::spawn(msock_opts).await?; +650 trace!("created magicsock"); +651 debug!(version = env!("CARGO_PKG_VERSION"), "iroh Endpoint created"); 652 -653impl Endpoint { -654 // The ordering of public methods is reflected directly in the documentation. This is -655 // roughly ordered by what is most commonly needed by users, but grouped in similar -656 // items. -657 -658 // # Methods relating to construction. -659 -660 /// Returns the builder for an [`Endpoint`], with a production configuration. -661 pub fn builder() -> Builder { -662 Builder::default() -663 } -664 -665 /// Creates a quinn endpoint backed by a magicsock. -666 /// -667 /// This is for internal use, the public interface is the [`Builder`] obtained from -668 /// [Self::builder]. See the methods on the builder for documentation of the parameters. -669 #[instrument("ep", skip_all, fields(me = %static_config.tls_config.secret_key.public().fmt_short()))] -670 async fn bind( -671 static_config: StaticConfig, -672 msock_opts: magicsock::Options, -673 ) -> Result<Self, BindError> { -674 let msock = magicsock::MagicSock::spawn(msock_opts).await?; -675 trace!("created magicsock"); -676 debug!(version = env!("CARGO_PKG_VERSION"), "iroh Endpoint created"); -677 -678 let ep = Self { -679 msock: msock.clone(), -680 rtt_actor: Arc::new(rtt_actor::RttHandle::new(msock.metrics.magicsock.clone())), -681 static_config: Arc::new(static_config), -682 }; -683 Ok(ep) -684 } -685 -686 /// Sets the list of accepted ALPN protocols. -687 /// -688 /// This will only affect new incoming connections. -689 /// Note that this *overrides* the current list of ALPNs. -690 pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) { -691 let server_config = self.static_config.create_server_config(alpns); -692 self.msock.endpoint().set_server_config(Some(server_config)); -693 } -694 -695 // # Methods for establishing connectivity. -696 -697 /// Connects to a remote [`Endpoint`]. -698 /// -699 /// A value that can be converted into a [`NodeAddr`] is required. This can be either a -700 /// [`NodeAddr`], a [`NodeId`] or a [`iroh_base::ticket::NodeTicket`]. -701 /// -702 /// The [`NodeAddr`] must contain the [`NodeId`] to dial and may also contain a [`RelayUrl`] -703 /// and direct addresses. If direct addresses are provided, they will be used to try and -704 /// establish a direct connection without involving a relay server. -705 /// -706 /// If neither a [`RelayUrl`] or direct addresses are configured in the [`NodeAddr`] it -707 /// may still be possible a connection can be established. This depends on other calls -708 /// to [`Endpoint::add_node_addr`] which may provide contact information, or via the -709 /// [`Discovery`] service configured using [`Builder::discovery`]. The discovery -710 /// service will also be used if the remote node is not reachable on the provided direct -711 /// addresses and there is no [`RelayUrl`]. -712 /// -713 /// If addresses or relay servers are neither provided nor can be discovered, the -714 /// connection attempt will fail with an error. -715 /// -716 /// The `alpn`, or application-level protocol identifier, is also required. The remote -717 /// endpoint must support this `alpn`, otherwise the connection attempt will fail with -718 /// an error. -719 pub async fn connect( -720 &self, -721 node_addr: impl Into<NodeAddr>, -722 alpn: &[u8], -723 ) -> Result<Connection, ConnectError> { -724 let node_addr = node_addr.into(); -725 let remote = node_addr.node_id; -726 let connecting = self -727 .connect_with_opts(node_addr, alpn, Default::default()) -728 .await?; -729 let conn = connecting.await?; -730 -731 debug!( -732 me = %self.node_id().fmt_short(), -733 remote = %remote.fmt_short(), -734 alpn = %String::from_utf8_lossy(alpn), -735 "Connection established." -736 ); -737 Ok(conn) -738 } -739 -740 /// Starts a connection attempt with a remote [`Endpoint`]. -741 /// -742 /// Like [`Endpoint::connect`] (see also its docs for general details), but allows for a more -743 /// advanced connection setup with more customization in two aspects: -744 /// 1. The returned future resolves to a [`Connecting`], which can be further processed into -745 /// a [`Connection`] by awaiting, or alternatively allows connecting with 0RTT via -746 /// [`Connecting::into_0rtt`]. -747 /// **Note:** Please read the documentation for `into_0rtt` carefully to assess -748 /// security concerns. -749 /// 2. The [`TransportConfig`] for the connection can be modified via the provided -750 /// [`ConnectOptions`]. -751 /// **Note:** Please be aware that changing transport config settings may have adverse effects on -752 /// establishing and maintaining direct connections. Carefully test settings you use and -753 /// consider this currently as still rather experimental. -754 #[instrument(name = "connect", skip_all, fields( -755 me = self.node_id().fmt_short(), -756 remote = tracing::field::Empty, -757 alpn = String::from_utf8_lossy(alpn).to_string(), -758 ))] -759 pub async fn connect_with_opts( -760 &self, -761 node_addr: impl Into<NodeAddr>, -762 alpn: &[u8], -763 options: ConnectOptions, -764 ) -> Result<Connecting, ConnectWithOptsError> { -765 let node_addr: NodeAddr = node_addr.into(); -766 tracing::Span::current().record("remote", node_addr.node_id.fmt_short()); -767 -768 // Connecting to ourselves is not supported. -769 ensure!(node_addr.node_id != self.node_id(), SelfConnectSnafu); -770 -771 if !node_addr.is_empty() { -772 self.add_node_addr(node_addr.clone())?; -773 } -774 let node_id = node_addr.node_id; -775 let direct_addresses = node_addr.direct_addresses.clone(); -776 let relay_url = node_addr.relay_url.clone(); -777 -778 // Get the mapped IPv6 address from the magic socket. Quinn will connect to this -779 // address. Start discovery for this node if it's enabled and we have no valid or -780 // verified address information for this node. Dropping the discovery cancels any -781 // still running task. -782 let (mapped_addr, _discovery_drop_guard) = self -783 .get_mapping_addr_and_maybe_start_discovery(node_addr) -784 .await -785 .context(NoAddressSnafu)?; -786 -787 let transport_config = options -788 .transport_config -789 .unwrap_or(self.static_config.transport_config.clone()); -790 -791 // Start connecting via quinn. This will time out after 10 seconds if no reachable -792 // address is available. -793 -794 debug!( -795 ?mapped_addr, -796 ?direct_addresses, -797 ?relay_url, -798 "Attempting connection..." -799 ); -800 let client_config = { -801 let mut alpn_protocols = vec![alpn.to_vec()]; -802 alpn_protocols.extend(options.additional_alpns); -803 let quic_client_config = self -804 .static_config -805 .tls_config -806 .make_client_config(alpn_protocols, self.static_config.keylog); -807 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); -808 client_config.transport_config(transport_config); -809 client_config -810 }; -811 -812 let server_name = &tls::name::encode(node_id); -813 let connect = self -814 .msock -815 .endpoint() -816 .connect_with( -817 client_config, -818 mapped_addr.private_socket_addr(), -819 server_name, -820 ) -821 .context(QuinnSnafu)?; -822 -823 Ok(Connecting { -824 inner: connect, -825 ep: self.clone(), -826 remote_node_id: Some(node_id), -827 _discovery_drop_guard, -828 }) -829 } -830 -831 /// Accepts an incoming connection on the endpoint. -832 /// -833 /// Only connections with the ALPNs configured in [`Builder::alpns`] will be accepted. -834 /// If multiple ALPNs have been configured the ALPN can be inspected before accepting -835 /// the connection using [`Connecting::alpn`]. -836 /// -837 /// The returned future will yield `None` if the endpoint is closed by calling -838 /// [`Endpoint::close`]. -839 pub fn accept(&self) -> Accept<'_> { -840 Accept { -841 inner: self.msock.endpoint().accept(), -842 ep: self.clone(), -843 } -844 } -845 -846 // # Methods for manipulating the internal state about other nodes. -847 -848 /// Informs this [`Endpoint`] about addresses of the iroh node. -849 /// -850 /// This updates the local state for the remote node. If the provided [`NodeAddr`] -851 /// contains a [`RelayUrl`] this will be used as the new relay server for this node. If -852 /// it contains any new IP endpoints they will also be stored and tried when next -853 /// connecting to this node. Any address that matches this node's direct addresses will be -854 /// silently ignored. -855 /// -856 /// See also [`Endpoint::add_node_addr_with_source`]. -857 /// -858 /// # Using node discovery instead -859 /// -860 /// It is strongly advised to use node discovery using the [`StaticProvider`] instead. -861 /// This provides more flexibility and future proofing. -862 /// -863 /// # Errors -864 /// -865 /// Will return an error if we attempt to add our own [`NodeId`] to the node map or -866 /// if the direct addresses are a subset of ours. -867 /// -868 /// [`StaticProvider`]: crate::discovery::static_provider::StaticProvider -869 pub fn add_node_addr(&self, node_addr: NodeAddr) -> Result<(), AddNodeAddrError> { -870 self.add_node_addr_inner(node_addr, magicsock::Source::App) -871 } -872 -873 /// Informs this [`Endpoint`] about addresses of the iroh node, noting the source. -874 /// -875 /// This updates the local state for the remote node. If the provided [`NodeAddr`] contains a -876 /// [`RelayUrl`] this will be used as the new relay server for this node. If it contains any -877 /// new IP endpoints they will also be stored and tried when next connecting to this node. Any -878 /// address that matches this node's direct addresses will be silently ignored. The *source* is -879 /// used for logging exclusively and will not be stored. -880 /// -881 /// # Using node discovery instead -882 /// -883 /// It is strongly advised to use node discovery using the [`StaticProvider`] instead. -884 /// This provides more flexibility and future proofing. -885 /// -886 /// # Errors -887 /// -888 /// Will return an error if we attempt to add our own [`NodeId`] to the node map or -889 /// if the direct addresses are a subset of ours. -890 /// -891 /// [`StaticProvider`]: crate::discovery::static_provider::StaticProvider -892 pub fn add_node_addr_with_source( -893 &self, -894 node_addr: NodeAddr, -895 source: &'static str, -896 ) -> Result<(), AddNodeAddrError> { -897 self.add_node_addr_inner( -898 node_addr, -899 magicsock::Source::NamedApp { -900 name: source.into(), -901 }, -902 ) -903 } -904 -905 fn add_node_addr_inner( -906 &self, -907 node_addr: NodeAddr, -908 source: magicsock::Source, -909 ) -> Result<(), AddNodeAddrError> { -910 // Connecting to ourselves is not supported. -911 snafu::ensure!(node_addr.node_id != self.node_id(), OwnAddressSnafu); -912 self.msock.add_node_addr(node_addr, source) -913 } -914 -915 // # Getter methods for properties of this Endpoint itself. -916 -917 /// Returns the secret_key of this endpoint. -918 pub fn secret_key(&self) -> &SecretKey { -919 &self.static_config.tls_config.secret_key -920 } -921 -922 /// Returns the node id of this endpoint. -923 /// -924 /// This ID is the unique addressing information of this node and other peers must know -925 /// it to be able to connect to this node. -926 pub fn node_id(&self) -> NodeId { -927 self.static_config.tls_config.secret_key.public() -928 } -929 -930 /// Returns a [`Watcher`] for the current [`NodeAddr`] for this endpoint. -931 /// -932 /// The observed [`NodeAddr`] will have the current [`RelayUrl`] and direct addresses -933 /// as they would be returned by [`Endpoint::home_relay`] and [`Endpoint::direct_addresses`]. -934 /// -935 /// Use [`Watcher::initialized`] to wait for a [`NodeAddr`] that is ready to be connected to: -936 /// -937 /// ```no_run -938 /// # async fn wrapper() -> n0_snafu::Result { -939 /// use iroh::{watcher::Watcher, Endpoint}; -940 /// -941 /// let endpoint = Endpoint::builder() -942 /// .alpns(vec![b"my-alpn".to_vec()]) -943 /// .bind() -944 /// .await?; -945 /// let node_addr = endpoint.node_addr().initialized().await?; -946 /// # let _ = node_addr; -947 /// # Ok(()) -948 /// # } -949 /// ``` -950 #[cfg(not(wasm_browser))] -951 pub fn node_addr(&self) -> NodeAddrWatcher { -952 let watch_addrs = self.direct_addresses(); -953 let watch_relay = self.home_relay(); -954 let node_id = self.node_id(); -955 -956 watch_addrs -957 .or(watch_relay) -958 .map(move |(addrs, relay)| match (addrs, relay) { -959 (Some(addrs), relay) => Some(NodeAddr::from_parts( -960 node_id, -961 relay, -962 addrs.into_iter().map(|x| x.addr), -963 )), -964 (None, Some(relay)) => Some(NodeAddr::from_parts( -965 node_id, -966 Some(relay), -967 std::iter::empty(), -968 )), -969 (None, None) => None, -970 }) -971 .expect("watchable is alive - cannot be disconnected yet") -972 } -973 -974 /// Returns a [`Watcher`] for the current [`NodeAddr`] for this endpoint. +653 let metrics = msock.metrics.magicsock.clone(); +654 let ep = Self { +655 msock, +656 rtt_actor: Arc::new(rtt_actor::RttHandle::new(metrics)), +657 static_config: Arc::new(static_config), +658 }; +659 Ok(ep) +660 } +661 +662 /// Sets the list of accepted ALPN protocols. +663 /// +664 /// This will only affect new incoming connections. +665 /// Note that this *overrides* the current list of ALPNs. +666 pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) { +667 let server_config = self.static_config.create_server_config(alpns); +668 self.msock.endpoint().set_server_config(Some(server_config)); +669 } +670 +671 // # Methods for establishing connectivity. +672 +673 /// Connects to a remote [`Endpoint`]. +674 /// +675 /// A value that can be converted into a [`NodeAddr`] is required. This can be either a +676 /// [`NodeAddr`], a [`NodeId`] or a [`iroh_base::ticket::NodeTicket`]. +677 /// +678 /// The [`NodeAddr`] must contain the [`NodeId`] to dial and may also contain a [`RelayUrl`] +679 /// and direct addresses. If direct addresses are provided, they will be used to try and +680 /// establish a direct connection without involving a relay server. +681 /// +682 /// If neither a [`RelayUrl`] or direct addresses are configured in the [`NodeAddr`] it +683 /// may still be possible a connection can be established. This depends on other calls +684 /// to [`Endpoint::add_node_addr`] which may provide contact information, or via the +685 /// [`Discovery`] service configured using [`Builder::discovery`]. The discovery +686 /// service will also be used if the remote node is not reachable on the provided direct +687 /// addresses and there is no [`RelayUrl`]. +688 /// +689 /// If addresses or relay servers are neither provided nor can be discovered, the +690 /// connection attempt will fail with an error. +691 /// +692 /// The `alpn`, or application-level protocol identifier, is also required. The remote +693 /// endpoint must support this `alpn`, otherwise the connection attempt will fail with +694 /// an error. +695 pub async fn connect( +696 &self, +697 node_addr: impl Into<NodeAddr>, +698 alpn: &[u8], +699 ) -> Result<Connection, ConnectError> { +700 let node_addr = node_addr.into(); +701 let remote = node_addr.node_id; +702 let connecting = self +703 .connect_with_opts(node_addr, alpn, Default::default()) +704 .await?; +705 let conn = connecting.await?; +706 +707 debug!( +708 me = %self.node_id().fmt_short(), +709 remote = %remote.fmt_short(), +710 alpn = %String::from_utf8_lossy(alpn), +711 "Connection established." +712 ); +713 Ok(conn) +714 } +715 +716 /// Starts a connection attempt with a remote [`Endpoint`]. +717 /// +718 /// Like [`Endpoint::connect`] (see also its docs for general details), but allows for a more +719 /// advanced connection setup with more customization in two aspects: +720 /// 1. The returned future resolves to a [`Connecting`], which can be further processed into +721 /// a [`Connection`] by awaiting, or alternatively allows connecting with 0RTT via +722 /// [`Connecting::into_0rtt`]. +723 /// **Note:** Please read the documentation for `into_0rtt` carefully to assess +724 /// security concerns. +725 /// 2. The [`TransportConfig`] for the connection can be modified via the provided +726 /// [`ConnectOptions`]. +727 /// **Note:** Please be aware that changing transport config settings may have adverse effects on +728 /// establishing and maintaining direct connections. Carefully test settings you use and +729 /// consider this currently as still rather experimental. +730 #[instrument(name = "connect", skip_all, fields( +731 me = self.node_id().fmt_short(), +732 remote = tracing::field::Empty, +733 alpn = String::from_utf8_lossy(alpn).to_string(), +734 ))] +735 pub async fn connect_with_opts( +736 &self, +737 node_addr: impl Into<NodeAddr>, +738 alpn: &[u8], +739 options: ConnectOptions, +740 ) -> Result<Connecting, ConnectWithOptsError> { +741 let node_addr: NodeAddr = node_addr.into(); +742 tracing::Span::current().record("remote", node_addr.node_id.fmt_short()); +743 +744 // Connecting to ourselves is not supported. +745 ensure!(node_addr.node_id != self.node_id(), SelfConnectSnafu); +746 +747 if !node_addr.is_empty() { +748 self.add_node_addr(node_addr.clone())?; +749 } +750 let node_id = node_addr.node_id; +751 let direct_addresses = node_addr.direct_addresses.clone(); +752 let relay_url = node_addr.relay_url.clone(); +753 +754 // Get the mapped IPv6 address from the magic socket. Quinn will connect to this +755 // address. Start discovery for this node if it's enabled and we have no valid or +756 // verified address information for this node. Dropping the discovery cancels any +757 // still running task. +758 let (mapped_addr, _discovery_drop_guard) = self +759 .get_mapping_addr_and_maybe_start_discovery(node_addr) +760 .await +761 .context(NoAddressSnafu)?; +762 +763 let transport_config = options +764 .transport_config +765 .unwrap_or(self.static_config.transport_config.clone()); +766 +767 // Start connecting via quinn. This will time out after 10 seconds if no reachable +768 // address is available. +769 +770 debug!( +771 ?mapped_addr, +772 ?direct_addresses, +773 ?relay_url, +774 "Attempting connection..." +775 ); +776 let client_config = { +777 let mut alpn_protocols = vec![alpn.to_vec()]; +778 alpn_protocols.extend(options.additional_alpns); +779 let quic_client_config = self +780 .static_config +781 .tls_config +782 .make_client_config(alpn_protocols, self.static_config.keylog); +783 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); +784 client_config.transport_config(transport_config); +785 client_config +786 }; +787 +788 let server_name = &tls::name::encode(node_id); +789 let connect = self +790 .msock +791 .endpoint() +792 .connect_with( +793 client_config, +794 mapped_addr.private_socket_addr(), +795 server_name, +796 ) +797 .context(QuinnSnafu)?; +798 +799 Ok(Connecting { +800 inner: connect, +801 ep: self.clone(), +802 remote_node_id: Some(node_id), +803 _discovery_drop_guard, +804 }) +805 } +806 +807 /// Accepts an incoming connection on the endpoint. +808 /// +809 /// Only connections with the ALPNs configured in [`Builder::alpns`] will be accepted. +810 /// If multiple ALPNs have been configured the ALPN can be inspected before accepting +811 /// the connection using [`Connecting::alpn`]. +812 /// +813 /// The returned future will yield `None` if the endpoint is closed by calling +814 /// [`Endpoint::close`]. +815 pub fn accept(&self) -> Accept<'_> { +816 Accept { +817 inner: self.msock.endpoint().accept(), +818 ep: self.clone(), +819 } +820 } +821 +822 // # Methods for manipulating the internal state about other nodes. +823 +824 /// Informs this [`Endpoint`] about addresses of the iroh node. +825 /// +826 /// This updates the local state for the remote node. If the provided [`NodeAddr`] +827 /// contains a [`RelayUrl`] this will be used as the new relay server for this node. If +828 /// it contains any new IP endpoints they will also be stored and tried when next +829 /// connecting to this node. Any address that matches this node's direct addresses will be +830 /// silently ignored. +831 /// +832 /// See also [`Endpoint::add_node_addr_with_source`]. +833 /// +834 /// # Using node discovery instead +835 /// +836 /// It is strongly advised to use node discovery using the [`StaticProvider`] instead. +837 /// This provides more flexibility and future proofing. +838 /// +839 /// # Errors +840 /// +841 /// Will return an error if we attempt to add our own [`NodeId`] to the node map or +842 /// if the direct addresses are a subset of ours. +843 /// +844 /// [`StaticProvider`]: crate::discovery::static_provider::StaticProvider +845 pub fn add_node_addr(&self, node_addr: NodeAddr) -> Result<(), AddNodeAddrError> { +846 self.add_node_addr_inner(node_addr, magicsock::Source::App) +847 } +848 +849 /// Informs this [`Endpoint`] about addresses of the iroh node, noting the source. +850 /// +851 /// This updates the local state for the remote node. If the provided [`NodeAddr`] contains a +852 /// [`RelayUrl`] this will be used as the new relay server for this node. If it contains any +853 /// new IP endpoints they will also be stored and tried when next connecting to this node. Any +854 /// address that matches this node's direct addresses will be silently ignored. The *source* is +855 /// used for logging exclusively and will not be stored. +856 /// +857 /// # Using node discovery instead +858 /// +859 /// It is strongly advised to use node discovery using the [`StaticProvider`] instead. +860 /// This provides more flexibility and future proofing. +861 /// +862 /// # Errors +863 /// +864 /// Will return an error if we attempt to add our own [`NodeId`] to the node map or +865 /// if the direct addresses are a subset of ours. +866 /// +867 /// [`StaticProvider`]: crate::discovery::static_provider::StaticProvider +868 pub fn add_node_addr_with_source( +869 &self, +870 node_addr: NodeAddr, +871 source: &'static str, +872 ) -> Result<(), AddNodeAddrError> { +873 self.add_node_addr_inner( +874 node_addr, +875 magicsock::Source::NamedApp { +876 name: source.into(), +877 }, +878 ) +879 } +880 +881 fn add_node_addr_inner( +882 &self, +883 node_addr: NodeAddr, +884 source: magicsock::Source, +885 ) -> Result<(), AddNodeAddrError> { +886 // Connecting to ourselves is not supported. +887 snafu::ensure!(node_addr.node_id != self.node_id(), OwnAddressSnafu); +888 self.msock.add_node_addr(node_addr, source) +889 } +890 +891 // # Getter methods for properties of this Endpoint itself. +892 +893 /// Returns the secret_key of this endpoint. +894 pub fn secret_key(&self) -> &SecretKey { +895 &self.static_config.tls_config.secret_key +896 } +897 +898 /// Returns the node id of this endpoint. +899 /// +900 /// This ID is the unique addressing information of this node and other peers must know +901 /// it to be able to connect to this node. +902 pub fn node_id(&self) -> NodeId { +903 self.static_config.tls_config.secret_key.public() +904 } +905 +906 /// Returns a [`Watcher`] for the current [`NodeAddr`] for this endpoint. +907 /// +908 /// The observed [`NodeAddr`] will have the current [`RelayUrl`] and direct addresses +909 /// as they would be returned by [`Endpoint::home_relay`] and [`Endpoint::direct_addresses`]. +910 /// +911 /// Use [`Watcher::initialized`] to wait for a [`NodeAddr`] that is ready to be connected to: +912 /// +913 /// ```no_run +914 /// # async fn wrapper() -> n0_snafu::Result { +915 /// use iroh::Endpoint; +916 /// use n0_watcher::Watcher; +917 /// +918 /// let endpoint = Endpoint::builder() +919 /// .alpns(vec![b"my-alpn".to_vec()]) +920 /// .bind() +921 /// .await?; +922 /// let node_addr = endpoint.node_addr().initialized().await?; +923 /// # let _ = node_addr; +924 /// # Ok(()) +925 /// # } +926 /// ``` +927 #[cfg(not(wasm_browser))] +928 pub fn node_addr(&self) -> impl n0_watcher::Watcher<Value = Option<NodeAddr>> { +929 let watch_addrs = self.direct_addresses(); +930 let watch_relay = self.home_relay(); +931 let node_id = self.node_id(); +932 +933 watch_addrs +934 .or(watch_relay) +935 .map(move |(addrs, mut relays)| match addrs { +936 Some(addrs) => Some(NodeAddr::from_parts( +937 node_id, +938 relays.pop(), +939 addrs.into_iter().map(|x| x.addr), +940 )), +941 None => relays.pop().map(|relay_url| { +942 NodeAddr::from_parts(node_id, Some(relay_url), std::iter::empty()) +943 }), +944 }) +945 .expect("watchable is alive - cannot be disconnected yet") +946 } +947 +948 /// Returns a [`Watcher`] for the current [`NodeAddr`] for this endpoint. +949 /// +950 /// When compiled to Wasm, this function returns a watcher that initializes +951 /// with a [`NodeAddr`] that only contains a relay URL, but no direct addresses, +952 /// as there are no APIs for directly using sockets in browsers. +953 #[cfg(wasm_browser)] +954 pub fn node_addr(&self) -> impl n0_watcher::Watcher<Value = Option<NodeAddr>> + '_ { +955 // In browsers, there will never be any direct addresses, so we wait +956 // for the home relay instead. This makes the `NodeAddr` have *some* way +957 // of connecting to us. +958 let watch_relay = self.home_relay(); +959 let node_id = self.node_id(); +960 watch_relay +961 .map(move |mut relays| { +962 relays.pop().map(|relay_url| { +963 NodeAddr::from_parts(node_id, Some(relay_url), std::iter::empty()) +964 }) +965 }) +966 .expect("watchable is alive - cannot be disconnected yet") +967 } +968 +969 /// Returns a [`Watcher`] for the [`RelayUrl`] of the Relay server used as home relay. +970 /// +971 /// Every endpoint has a home Relay server which it chooses as the server with the +972 /// lowest latency out of the configured servers provided by [`Builder::relay_mode`]. +973 /// This is the server other iroh nodes can use to reliably establish a connection +974 /// to this node. 975 /// -976 /// When compiled to Wasm, this function returns a watcher that initializes -977 /// with a [`NodeAddr`] that only contains a relay URL, but no direct addresses, -978 /// as there are no APIs for directly using sockets in browsers. -979 #[cfg(wasm_browser)] -980 pub fn node_addr(&self) -> NodeAddrWatcher { -981 // In browsers, there will never be any direct addresses, so we wait -982 // for the home relay instead. This makes the `NodeAddr` have *some* way -983 // of connecting to us. -984 let watch_relay = self.home_relay(); -985 let node_id = self.node_id(); -986 watch_relay -987 .map(move |relay| { -988 relay.map(|relay| NodeAddr::from_parts(node_id, Some(relay), std::iter::empty())) -989 }) -990 .expect("watchable is alive - cannot be disconnected yet") -991 } -992 -993 /// Returns a [`Watcher`] for the [`RelayUrl`] of the Relay server used as home relay. -994 /// -995 /// Every endpoint has a home Relay server which it chooses as the server with the -996 /// lowest latency out of the configured servers provided by [`Builder::relay_mode`]. -997 /// This is the server other iroh nodes can use to reliably establish a connection -998 /// to this node. -999 /// -1000 /// The watcher stores `None` if we are not connected to any Relay server. -1001 /// -1002 /// Note that this will store `None` right after the [`Endpoint`] is created since it takes -1003 /// some time to connect to find and connect to the home relay server. -1004 /// -1005 /// # Examples -1006 /// -1007 /// To wait for a home relay connection to be established, use [`Watcher::initialized`]: -1008 /// ```no_run -1009 /// use futures_lite::StreamExt; -1010 /// use iroh::{watcher::Watcher, Endpoint}; +976 /// The watcher stores `None` if we are not connected to any Relay server. +977 /// +978 /// Note that this will store `None` right after the [`Endpoint`] is created since it takes +979 /// some time to connect to find and connect to the home relay server. +980 /// +981 /// # Examples +982 /// +983 /// To wait for a home relay connection to be established, use [`Watcher::initialized`]: +984 /// ```no_run +985 /// use iroh::Endpoint; +986 /// use n0_future::StreamExt; +987 /// use n0_watcher::Watcher as _; +988 /// +989 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); +990 /// # rt.block_on(async move { +991 /// let mep = Endpoint::builder().bind().await.unwrap(); +992 /// let _relay_url = mep.home_relay().initialized().await.unwrap(); +993 /// # }); +994 /// ``` +995 pub fn home_relay(&self) -> impl n0_watcher::Watcher<Value = Vec<RelayUrl>> { +996 self.msock.home_relay() +997 } +998 +999 /// Returns a [`Watcher`] for the direct addresses of this [`Endpoint`]. +1000 /// +1001 /// The direct addresses of the [`Endpoint`] are those that could be used by other +1002 /// iroh nodes to establish direct connectivity, depending on the network +1003 /// situation. The yielded lists of direct addresses contain both the locally-bound +1004 /// addresses and the [`Endpoint`]'s publicly reachable addresses discovered through +1005 /// mechanisms such as [STUN] and port mapping. Hence usually only a subset of these +1006 /// will be applicable to a certain remote iroh node. +1007 /// +1008 /// The [`Endpoint`] continuously monitors the direct addresses for changes as its own +1009 /// location in the network might change. Whenever changes are detected this stream +1010 /// will yield a new list of direct addresses. 1011 /// -1012 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); -1013 /// # rt.block_on(async move { -1014 /// let mep = Endpoint::builder().bind().await.unwrap(); -1015 /// let _relay_url = mep.home_relay().initialized().await.unwrap(); -1016 /// # }); -1017 /// ``` -1018 pub fn home_relay(&self) -> watcher::Direct<Option<RelayUrl>> { -1019 self.msock.home_relay() -1020 } -1021 -1022 /// Returns a [`Watcher`] for the direct addresses of this [`Endpoint`]. -1023 /// -1024 /// The direct addresses of the [`Endpoint`] are those that could be used by other -1025 /// iroh nodes to establish direct connectivity, depending on the network -1026 /// situation. The yielded lists of direct addresses contain both the locally-bound -1027 /// addresses and the [`Endpoint`]'s publicly reachable addresses discovered through -1028 /// mechanisms such as [STUN] and port mapping. Hence usually only a subset of these -1029 /// will be applicable to a certain remote iroh node. -1030 /// -1031 /// The [`Endpoint`] continuously monitors the direct addresses for changes as its own -1032 /// location in the network might change. Whenever changes are detected this stream -1033 /// will yield a new list of direct addresses. -1034 /// -1035 /// When issuing the first call to this method the first direct address discovery might -1036 /// still be underway, in this case the [`Watcher`] might not be initialized with [`Some`] -1037 /// value yet. Once the first set of local direct addresses are discovered the [`Watcher`] -1038 /// will always return [`Some`] set of direct addresses immediately, which are the most -1039 /// recently discovered direct addresses. -1040 /// -1041 /// # Examples -1042 /// -1043 /// To get the first set of direct addresses use [`Watcher::initialized`]: -1044 /// ```no_run -1045 /// use futures_lite::StreamExt; -1046 /// use iroh::{watcher::Watcher, Endpoint}; +1012 /// When issuing the first call to this method the first direct address discovery might +1013 /// still be underway, in this case the [`Watcher`] might not be initialized with [`Some`] +1014 /// value yet. Once the first set of local direct addresses are discovered the [`Watcher`] +1015 /// will always return [`Some`] set of direct addresses immediately, which are the most +1016 /// recently discovered direct addresses. +1017 /// +1018 /// # Examples +1019 /// +1020 /// To get the first set of direct addresses use [`Watcher::initialized`]: +1021 /// ```no_run +1022 /// use iroh::Endpoint; +1023 /// use n0_future::StreamExt; +1024 /// use n0_watcher::Watcher as _; +1025 /// +1026 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); +1027 /// # rt.block_on(async move { +1028 /// let mep = Endpoint::builder().bind().await.unwrap(); +1029 /// let _addrs = mep.direct_addresses().initialized().await.unwrap(); +1030 /// # }); +1031 /// ``` +1032 /// +1033 /// [STUN]: https://en.wikipedia.org/wiki/STUN +1034 pub fn direct_addresses(&self) -> n0_watcher::Direct<Option<BTreeSet<DirectAddr>>> { +1035 self.msock.direct_addresses() +1036 } +1037 +1038 /// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`]. +1039 /// +1040 /// A `net-report` checks the network conditions of the [`Endpoint`], such as +1041 /// whether it is connected to the internet via Ipv4 and/or Ipv6, its NAT +1042 /// status, its latency to the relay servers, and its public addresses. +1043 /// +1044 /// The [`Endpoint`] continuously runs `net-reports` to monitor if network +1045 /// conditions have changed. This [`Watcher`] will return the latest result +1046 /// of the `net-report`. 1047 /// -1048 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); -1049 /// # rt.block_on(async move { -1050 /// let mep = Endpoint::builder().bind().await.unwrap(); -1051 /// let _addrs = mep.direct_addresses().initialized().await.unwrap(); -1052 /// # }); -1053 /// ``` -1054 /// -1055 /// [STUN]: https://en.wikipedia.org/wiki/STUN -1056 pub fn direct_addresses(&self) -> watcher::Direct<Option<BTreeSet<DirectAddr>>> { -1057 self.msock.direct_addresses() -1058 } -1059 -1060 /// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`]. +1048 /// When issuing the first call to this method the first report might +1049 /// still be underway, in this case the [`Watcher`] might not be initialized +1050 /// with [`Some`] value yet. Once the net-report has been successfully +1051 /// run, the [`Watcher`] will always return [`Some`] report immediately, which +1052 /// is the most recently run `net-report`. +1053 /// +1054 /// # Examples +1055 /// +1056 /// To get the first report use [`Watcher::initialized`]: +1057 /// ```no_run +1058 /// use iroh::Endpoint; +1059 /// use n0_future::StreamExt; +1060 /// use n0_watcher::Watcher as _; 1061 /// -1062 /// A `net-report` checks the network conditions of the [`Endpoint`], such as -1063 /// whether it is connected to the internet via Ipv4 and/or Ipv6, its NAT -1064 /// status, its latency to the relay servers, and its public addresses. -1065 /// -1066 /// The [`Endpoint`] continuously runs `net-reports` to monitor if network -1067 /// conditions have changed. This [`Watcher`] will return the latest result -1068 /// of the `net-report`. -1069 /// -1070 /// When issuing the first call to this method the first report might -1071 /// still be underway, in this case the [`Watcher`] might not be initialized -1072 /// with [`Some`] value yet. Once the net-report has been successfully -1073 /// run, the [`Watcher`] will always return [`Some`] report immediately, which -1074 /// is the most recently run `net-report`. -1075 /// -1076 /// # Examples -1077 /// -1078 /// To get the first report use [`Watcher::initialized`]: -1079 /// ```no_run -1080 /// use futures_lite::StreamExt; -1081 /// use iroh::{watcher::Watcher, Endpoint}; -1082 /// -1083 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); -1084 /// # rt.block_on(async move { -1085 /// let ep = Endpoint::builder().bind().await.unwrap(); -1086 /// let _report = ep.net_report().initialized().await.unwrap(); -1087 /// # }); -1088 /// ``` -1089 #[doc(hidden)] -1090 pub fn net_report(&self) -> watcher::Direct<Option<Arc<Report>>> { -1091 self.msock.net_report() -1092 } -1093 -1094 /// Returns the local socket addresses on which the underlying sockets are bound. +1062 /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap(); +1063 /// # rt.block_on(async move { +1064 /// let ep = Endpoint::builder().bind().await.unwrap(); +1065 /// let _report = ep.net_report().initialized().await.unwrap(); +1066 /// # }); +1067 /// ``` +1068 #[doc(hidden)] +1069 pub fn net_report(&self) -> n0_watcher::Direct<Option<Arc<Report>>> { +1070 self.msock.net_report() +1071 } +1072 +1073 /// Returns the local socket addresses on which the underlying sockets are bound. +1074 /// +1075 /// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6 +1076 /// address if available. +1077 pub fn bound_sockets(&self) -> Vec<SocketAddr> { +1078 self.msock +1079 .local_addr() +1080 .into_iter() +1081 .filter_map(|addr| addr.into_socket_addr()) +1082 .collect() +1083 } +1084 +1085 // # Getter methods for information about other nodes. +1086 +1087 /// Returns information about the remote node identified by a [`NodeId`]. +1088 /// +1089 /// The [`Endpoint`] keeps some information about remote iroh nodes, which it uses to find +1090 /// the best path to a node. Having information on a remote node, however, does not mean we have +1091 /// ever connected to it to or even whether a connection is even possible. The information about a +1092 /// remote node will change over time, as the [`Endpoint`] learns more about the node. Future +1093 /// calls may return different information. Furthermore, node information may even be +1094 /// completely evicted as it becomes stale. 1095 /// -1096 /// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6 -1097 /// address if available. -1098 #[cfg(not(wasm_browser))] -1099 pub fn bound_sockets(&self) -> (SocketAddr, Option<SocketAddr>) { -1100 self.msock.local_addr() -1101 } -1102 -1103 // # Getter methods for information about other nodes. -1104 -1105 /// Returns information about the remote node identified by a [`NodeId`]. +1096 /// See also [`Endpoint::remote_info_iter`] which returns information on all nodes known +1097 /// by this [`Endpoint`]. +1098 pub fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo> { +1099 self.msock.remote_info(node_id) +1100 } +1101 +1102 /// Returns information about all the remote nodes this [`Endpoint`] knows about. +1103 /// +1104 /// This returns the same information as [`Endpoint::remote_info`] for each node known to this +1105 /// [`Endpoint`]. 1106 /// 1107 /// The [`Endpoint`] keeps some information about remote iroh nodes, which it uses to find -1108 /// the best path to a node. Having information on a remote node, however, does not mean we have -1109 /// ever connected to it to or even whether a connection is even possible. The information about a -1110 /// remote node will change over time, as the [`Endpoint`] learns more about the node. Future -1111 /// calls may return different information. Furthermore, node information may even be -1112 /// completely evicted as it becomes stale. -1113 /// -1114 /// See also [`Endpoint::remote_info_iter`] which returns information on all nodes known -1115 /// by this [`Endpoint`]. -1116 pub fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo> { -1117 self.msock.remote_info(node_id) -1118 } -1119 -1120 /// Returns information about all the remote nodes this [`Endpoint`] knows about. -1121 /// -1122 /// This returns the same information as [`Endpoint::remote_info`] for each node known to this -1123 /// [`Endpoint`]. +1108 /// the best path to a node. This returns all the nodes it knows about, regardless of whether a +1109 /// connection was ever made or is even possible. +1110 /// +1111 /// See also [`Endpoint::remote_info`] to only retrieve information about a single node. +1112 pub fn remote_info_iter(&self) -> impl Iterator<Item = RemoteInfo> { +1113 self.msock.list_remote_infos().into_iter() +1114 } +1115 +1116 /// Returns a stream of all remote nodes discovered through the endpoint's discovery services. +1117 /// +1118 /// Whenever a node is discovered via the endpoint's discovery service, the corresponding +1119 /// [`DiscoveryItem`] is yielded from this stream. This includes nodes discovered actively +1120 /// through [`Discovery::resolve`], which is invoked automatically when calling +1121 /// [`Endpoint::connect`] for a [`NodeId`] unknown to the endpoint. It also includes +1122 /// nodes that the endpoint discovers passively from discovery services that implement +1123 /// [`Discovery::subscribe`], which e.g. [`MdnsDiscovery`] does. 1124 /// -1125 /// The [`Endpoint`] keeps some information about remote iroh nodes, which it uses to find -1126 /// the best path to a node. This returns all the nodes it knows about, regardless of whether a -1127 /// connection was ever made or is even possible. -1128 /// -1129 /// See also [`Endpoint::remote_info`] to only retrieve information about a single node. -1130 pub fn remote_info_iter(&self) -> impl Iterator<Item = RemoteInfo> { -1131 self.msock.list_remote_infos().into_iter() -1132 } -1133 -1134 /// Returns a stream of all remote nodes discovered through the endpoint's discovery services. -1135 /// -1136 /// Whenever a node is discovered via the endpoint's discovery service, the corresponding -1137 /// [`DiscoveryItem`] is yielded from this stream. This includes nodes discovered actively -1138 /// through [`Discovery::resolve`], which is invoked automatically when calling -1139 /// [`Endpoint::connect`] for a [`NodeId`] unknown to the endpoint. It also includes -1140 /// nodes that the endpoint discovers passively from discovery services that implement -1141 /// [`Discovery::subscribe`], which e.g. [`MdnsDiscovery`] does. -1142 /// -1143 /// The stream does not yield information about nodes that are added manually to the endpoint's -1144 /// addressbook by calling [`Endpoint::add_node_addr`] or by supplying a full [`NodeAddr`] to -1145 /// [`Endpoint::connect`]. It also does not yield information about nodes that we only -1146 /// know about because they connected to us. When using the [`StaticProvider`] discovery, -1147 /// discovery info is only emitted once connecting to a node added to the static provider, not -1148 /// at the time of adding it to the static provider. -1149 /// -1150 /// The stream should be processed in a loop. If the stream is not processed fast enough, -1151 /// [`Lagged`] may be yielded, indicating that items were missed. -1152 /// -1153 /// See also [`Endpoint::remote_info_iter`], which returns an iterator over all remotes -1154 /// the endpoint knows about at a specific point in time. +1125 /// The stream does not yield information about nodes that are added manually to the endpoint's +1126 /// addressbook by calling [`Endpoint::add_node_addr`] or by supplying a full [`NodeAddr`] to +1127 /// [`Endpoint::connect`]. It also does not yield information about nodes that we only +1128 /// know about because they connected to us. When using the [`StaticProvider`] discovery, +1129 /// discovery info is only emitted once connecting to a node added to the static provider, not +1130 /// at the time of adding it to the static provider. +1131 /// +1132 /// The stream should be processed in a loop. If the stream is not processed fast enough, +1133 /// [`Lagged`] may be yielded, indicating that items were missed. +1134 /// +1135 /// See also [`Endpoint::remote_info_iter`], which returns an iterator over all remotes +1136 /// the endpoint knows about at a specific point in time. +1137 /// +1138 /// [`MdnsDiscovery`]: crate::discovery::mdns::MdnsDiscovery +1139 /// [`StaticProvider`]: crate::discovery::static_provider::StaticProvider +1140 pub fn discovery_stream(&self) -> impl Stream<Item = Result<DiscoveryItem, Lagged>> { +1141 self.msock.discovery_subscribers().subscribe() +1142 } +1143 +1144 // # Methods for less common getters. +1145 // +1146 // Partially they return things passed into the builder. +1147 +1148 /// Returns a [`Watcher`] that reports the current connection type and any changes for +1149 /// given remote node. +1150 /// +1151 /// This watcher allows observing a stream of [`ConnectionType`] items by calling +1152 /// [`Watcher::stream()`]. If the underlying connection to a remote node changes, it will +1153 /// yield a new item. These connection changes are when the connection switches between +1154 /// using the Relay server and a direct connection. 1155 /// -1156 /// [`MdnsDiscovery`]: crate::discovery::mdns::MdnsDiscovery -1157 /// [`StaticProvider`]: crate::discovery::static_provider::StaticProvider -1158 pub fn discovery_stream(&self) -> impl Stream<Item = Result<DiscoveryItem, Lagged>> { -1159 self.msock.discovery_subscribers().subscribe() -1160 } -1161 -1162 // # Methods for less common getters. -1163 // -1164 // Partially they return things passed into the builder. -1165 -1166 /// Returns a [`Watcher`] that reports the current connection type and any changes for -1167 /// given remote node. -1168 /// -1169 /// This watcher allows observing a stream of [`ConnectionType`] items by calling -1170 /// [`Watcher::stream()`]. If the underlying connection to a remote node changes, it will -1171 /// yield a new item. These connection changes are when the connection switches between -1172 /// using the Relay server and a direct connection. -1173 /// -1174 /// Note that this does not guarantee each connection change is yielded in the stream. -1175 /// If the connection type changes several times before this stream is polled, only the -1176 /// last recorded state is returned. This can be observed e.g. right at the start of a -1177 /// connection when the switch from a relayed to a direct connection can be so fast that -1178 /// the relayed state is never exposed. -1179 /// -1180 /// If there is currently a connection with the remote node, then using [`Watcher::get`] -1181 /// will immediately return either [`ConnectionType::Relay`], [`ConnectionType::Direct`] -1182 /// or [`ConnectionType::Mixed`]. -1183 /// -1184 /// It is possible for the connection type to be [`ConnectionType::None`] if you've -1185 /// recently connected to this node id but previous methods of reaching the node have -1186 /// become inaccessible. -1187 /// -1188 /// # Errors -1189 /// -1190 /// Will return `None` if we do not have any address information for the given `node_id`. -1191 pub fn conn_type(&self, node_id: NodeId) -> Option<watcher::Direct<ConnectionType>> { -1192 self.msock.conn_type(node_id) -1193 } -1194 -1195 /// Returns the DNS resolver used in this [`Endpoint`]. -1196 /// -1197 /// See [`Builder::dns_resolver`]. -1198 #[cfg(not(wasm_browser))] -1199 pub fn dns_resolver(&self) -> &DnsResolver { -1200 self.msock.dns_resolver() -1201 } -1202 -1203 /// Returns the discovery mechanism, if configured. -1204 /// -1205 /// See [`Builder::discovery`]. -1206 pub fn discovery(&self) -> Option<&dyn Discovery> { -1207 self.msock.discovery() -1208 } -1209 -1210 /// Returns metrics collected for this endpoint. +1156 /// Note that this does not guarantee each connection change is yielded in the stream. +1157 /// If the connection type changes several times before this stream is polled, only the +1158 /// last recorded state is returned. This can be observed e.g. right at the start of a +1159 /// connection when the switch from a relayed to a direct connection can be so fast that +1160 /// the relayed state is never exposed. +1161 /// +1162 /// If there is currently a connection with the remote node, then using [`Watcher::get`] +1163 /// will immediately return either [`ConnectionType::Relay`], [`ConnectionType::Direct`] +1164 /// or [`ConnectionType::Mixed`]. +1165 /// +1166 /// It is possible for the connection type to be [`ConnectionType::None`] if you've +1167 /// recently connected to this node id but previous methods of reaching the node have +1168 /// become inaccessible. +1169 /// +1170 /// Will return `None` if we do not have any address information for the given `node_id`. +1171 pub fn conn_type(&self, node_id: NodeId) -> Option<n0_watcher::Direct<ConnectionType>> { +1172 self.msock.conn_type(node_id) +1173 } +1174 +1175 /// Returns the DNS resolver used in this [`Endpoint`]. +1176 /// +1177 /// See [`Builder::dns_resolver`]. +1178 #[cfg(not(wasm_browser))] +1179 pub fn dns_resolver(&self) -> &DnsResolver { +1180 self.msock.dns_resolver() +1181 } +1182 +1183 /// Returns the discovery mechanism, if configured. +1184 /// +1185 /// See [`Builder::discovery`]. +1186 pub fn discovery(&self) -> Option<&dyn Discovery> { +1187 self.msock.discovery() +1188 } +1189 +1190 /// Returns metrics collected for this endpoint. +1191 /// +1192 /// The endpoint internally collects various metrics about its operation. +1193 /// The returned [`EndpointMetrics`] struct contains all of these metrics. +1194 /// +1195 /// You can access individual metrics directly by using the public fields: +1196 /// ```rust +1197 /// # use std::collections::BTreeMap; +1198 /// # use iroh::endpoint::Endpoint; +1199 /// # async fn wrapper() -> n0_snafu::Result { +1200 /// let endpoint = Endpoint::builder().bind().await?; +1201 /// assert_eq!(endpoint.metrics().magicsock.recv_datagrams.get(), 0); +1202 /// # Ok(()) +1203 /// # } +1204 /// ``` +1205 /// +1206 /// [`EndpointMetrics`] implements [`MetricsGroupSet`], and each field +1207 /// implements [`MetricsGroup`]. These traits provide methods to iterate over +1208 /// the groups in the set, and over the individual metrics in each group, without having +1209 /// to access each field manually. With these methods, it is straightforward to collect +1210 /// all metrics into a map or push their values to a metrics collector. 1211 /// -1212 /// The endpoint internally collects various metrics about its operation. -1213 /// The returned [`EndpointMetrics`] struct contains all of these metrics. -1214 /// -1215 /// You can access individual metrics directly by using the public fields: -1216 /// ```rust -1217 /// # use std::collections::BTreeMap; -1218 /// # use iroh::endpoint::Endpoint; -1219 /// # async fn wrapper() -> n0_snafu::Result { -1220 /// let endpoint = Endpoint::builder().bind().await?; -1221 /// assert_eq!(endpoint.metrics().magicsock.recv_datagrams.get(), 0); -1222 /// # Ok(()) -1223 /// # } -1224 /// ``` -1225 /// -1226 /// [`EndpointMetrics`] implements [`MetricsGroupSet`], and each field -1227 /// implements [`MetricsGroup`]. These traits provide methods to iterate over -1228 /// the groups in the set, and over the individual metrics in each group, without having -1229 /// to access each field manually. With these methods, it is straightforward to collect -1230 /// all metrics into a map or push their values to a metrics collector. -1231 /// -1232 /// For example, the following snippet collects all metrics into a map: -1233 /// ```rust -1234 /// # use std::collections::BTreeMap; -1235 /// # use iroh_metrics::{Metric, MetricsGroup, MetricValue, MetricsGroupSet}; -1236 /// # use iroh::endpoint::Endpoint; -1237 /// # async fn wrapper() -> n0_snafu::Result { -1238 /// let endpoint = Endpoint::builder().bind().await?; -1239 /// let metrics: BTreeMap<String, MetricValue> = endpoint -1240 /// .metrics() -1241 /// .iter() -1242 /// .map(|(group, metric)| { -1243 /// let name = [group, metric.name()].join(":"); -1244 /// (name, metric.value()) -1245 /// }) -1246 /// .collect(); -1247 /// -1248 /// assert_eq!(metrics["magicsock:recv_datagrams"], MetricValue::Counter(0)); -1249 /// # Ok(()) -1250 /// # } -1251 /// ``` -1252 /// -1253 /// The metrics can also be encoded into the OpenMetrics text format, as used by Prometheus. -1254 /// To do so, use the [`iroh_metrics::Registry`], add the endpoint metrics to the -1255 /// registry with [`Registry::register_all`], and encode the metrics to a string with -1256 /// [`encode_openmetrics_to_string`]: -1257 /// ```rust -1258 /// # use iroh_metrics::{Registry, MetricsSource}; -1259 /// # use iroh::endpoint::Endpoint; -1260 /// # async fn wrapper() -> n0_snafu::Result { -1261 /// let endpoint = Endpoint::builder().bind().await?; -1262 /// let mut registry = Registry::default(); -1263 /// registry.register_all(endpoint.metrics()); -1264 /// let s = registry.encode_openmetrics_to_string()?; -1265 /// assert!(s.contains(r#"TYPE magicsock_recv_datagrams counter"#)); -1266 /// assert!(s.contains(r#"magicsock_recv_datagrams_total 0"#)); -1267 /// # Ok(()) -1268 /// # } -1269 /// ``` -1270 /// -1271 /// Through a registry, you can also add labels or prefixes to metrics with -1272 /// [`Registry::sub_registry_with_label`] or [`Registry::sub_registry_with_prefix`]. -1273 /// Furthermore, [`iroh_metrics::service`] provides functions to easily start services -1274 /// to serve the metrics with a HTTP server, dump them to a file, or push them -1275 /// to a Prometheus gateway. +1212 /// For example, the following snippet collects all metrics into a map: +1213 /// ```rust +1214 /// # use std::collections::BTreeMap; +1215 /// # use iroh_metrics::{Metric, MetricsGroup, MetricValue, MetricsGroupSet}; +1216 /// # use iroh::endpoint::Endpoint; +1217 /// # async fn wrapper() -> n0_snafu::Result { +1218 /// let endpoint = Endpoint::builder().bind().await?; +1219 /// let metrics: BTreeMap<String, MetricValue> = endpoint +1220 /// .metrics() +1221 /// .iter() +1222 /// .map(|(group, metric)| { +1223 /// let name = [group, metric.name()].join(":"); +1224 /// (name, metric.value()) +1225 /// }) +1226 /// .collect(); +1227 /// +1228 /// assert_eq!(metrics["magicsock:recv_datagrams"], MetricValue::Counter(0)); +1229 /// # Ok(()) +1230 /// # } +1231 /// ``` +1232 /// +1233 /// The metrics can also be encoded into the OpenMetrics text format, as used by Prometheus. +1234 /// To do so, use the [`iroh_metrics::Registry`], add the endpoint metrics to the +1235 /// registry with [`Registry::register_all`], and encode the metrics to a string with +1236 /// [`encode_openmetrics_to_string`]: +1237 /// ```rust +1238 /// # use iroh_metrics::{Registry, MetricsSource}; +1239 /// # use iroh::endpoint::Endpoint; +1240 /// # async fn wrapper() -> n0_snafu::Result { +1241 /// let endpoint = Endpoint::builder().bind().await?; +1242 /// let mut registry = Registry::default(); +1243 /// registry.register_all(endpoint.metrics()); +1244 /// let s = registry.encode_openmetrics_to_string()?; +1245 /// assert!(s.contains(r#"TYPE magicsock_recv_datagrams counter"#)); +1246 /// assert!(s.contains(r#"magicsock_recv_datagrams_total 0"#)); +1247 /// # Ok(()) +1248 /// # } +1249 /// ``` +1250 /// +1251 /// Through a registry, you can also add labels or prefixes to metrics with +1252 /// [`Registry::sub_registry_with_label`] or [`Registry::sub_registry_with_prefix`]. +1253 /// Furthermore, [`iroh_metrics::service`] provides functions to easily start services +1254 /// to serve the metrics with a HTTP server, dump them to a file, or push them +1255 /// to a Prometheus gateway. +1256 /// +1257 /// For example, the following snippet launches an HTTP server that serves the metrics in the +1258 /// OpenMetrics text format: +1259 /// ```no_run +1260 /// # use std::{sync::{Arc, RwLock}, time::Duration}; +1261 /// # use iroh_metrics::{Registry, MetricsSource}; +1262 /// # use iroh::endpoint::Endpoint; +1263 /// # use n0_snafu::ResultExt; +1264 /// # async fn wrapper() -> n0_snafu::Result { +1265 /// // Create a registry, wrapped in a read-write lock so that we can register and serve +1266 /// // the metrics independently. +1267 /// let registry = Arc::new(RwLock::new(Registry::default())); +1268 /// // Spawn a task to serve the metrics on an OpenMetrics HTTP endpoint. +1269 /// let metrics_task = tokio::task::spawn({ +1270 /// let registry = registry.clone(); +1271 /// async move { +1272 /// let addr = "0.0.0.0:9100".parse().unwrap(); +1273 /// iroh_metrics::service::start_metrics_server(addr, registry).await +1274 /// } +1275 /// }); 1276 /// -1277 /// For example, the following snippet launches an HTTP server that serves the metrics in the -1278 /// OpenMetrics text format: -1279 /// ```no_run -1280 /// # use std::{sync::{Arc, RwLock}, time::Duration}; -1281 /// # use iroh_metrics::{Registry, MetricsSource}; -1282 /// # use iroh::endpoint::Endpoint; -1283 /// # use n0_snafu::ResultExt; -1284 /// # async fn wrapper() -> n0_snafu::Result { -1285 /// // Create a registry, wrapped in a read-write lock so that we can register and serve -1286 /// // the metrics independently. -1287 /// let registry = Arc::new(RwLock::new(Registry::default())); -1288 /// // Spawn a task to serve the metrics on an OpenMetrics HTTP endpoint. -1289 /// let metrics_task = tokio::task::spawn({ -1290 /// let registry = registry.clone(); -1291 /// async move { -1292 /// let addr = "0.0.0.0:9100".parse().unwrap(); -1293 /// iroh_metrics::service::start_metrics_server(addr, registry).await -1294 /// } -1295 /// }); +1277 /// // Spawn an endpoint and add the metrics to the registry. +1278 /// let endpoint = Endpoint::builder().bind().await?; +1279 /// registry.write().unwrap().register_all(endpoint.metrics()); +1280 /// +1281 /// // Wait for the metrics server to bind, then fetch the metrics via HTTP. +1282 /// tokio::time::sleep(Duration::from_millis(500)); +1283 /// let res = reqwest::get("http://localhost:9100/metrics") +1284 /// .await +1285 /// .context("get")? +1286 /// .text() +1287 /// .await +1288 /// .context("text")?; +1289 /// +1290 /// assert!(res.contains(r#"TYPE magicsock_recv_datagrams counter"#)); +1291 /// assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#)); +1292 /// # metrics_task.abort(); +1293 /// # Ok(()) +1294 /// # } +1295 /// ``` 1296 /// -1297 /// // Spawn an endpoint and add the metrics to the registry. -1298 /// let endpoint = Endpoint::builder().bind().await?; -1299 /// registry.write().unwrap().register_all(endpoint.metrics()); -1300 /// -1301 /// // Wait for the metrics server to bind, then fetch the metrics via HTTP. -1302 /// tokio::time::sleep(Duration::from_millis(500)); -1303 /// let res = reqwest::get("http://localhost:9100/metrics") -1304 /// .await -1305 /// .context("get")? -1306 /// .text() -1307 /// .await -1308 /// .context("text")?; -1309 /// -1310 /// assert!(res.contains(r#"TYPE magicsock_recv_datagrams counter"#)); -1311 /// assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#)); -1312 /// # metrics_task.abort(); -1313 /// # Ok(()) -1314 /// # } -1315 /// ``` -1316 /// -1317 /// [`Registry`]: iroh_metrics::Registry -1318 /// [`Registry::register_all`]: iroh_metrics::Registry::register_all -1319 /// [`Registry::sub_registry_with_label`]: iroh_metrics::Registry::sub_registry_with_label -1320 /// [`Registry::sub_registry_with_prefix`]: iroh_metrics::Registry::sub_registry_with_prefix -1321 /// [`encode_openmetrics_to_string`]: iroh_metrics::MetricsSource::encode_openmetrics_to_string -1322 /// [`MetricsGroup`]: iroh_metrics::MetricsGroup -1323 /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet -1324 #[cfg(feature = "metrics")] -1325 pub fn metrics(&self) -> &EndpointMetrics { -1326 &self.msock.metrics -1327 } -1328 -1329 // # Methods for less common state updates. -1330 -1331 /// Notifies the system of potential network changes. -1332 /// -1333 /// On many systems iroh is able to detect network changes by itself, however -1334 /// some systems like android do not expose this functionality to native code. -1335 /// Android does however provide this functionality to Java code. This -1336 /// function allows for notifying iroh of any potential network changes like -1337 /// this. -1338 /// -1339 /// Even when the network did not change, or iroh was already able to detect -1340 /// the network change itself, there is no harm in calling this function. -1341 pub async fn network_change(&self) { -1342 self.msock.network_change().await; -1343 } -1344 -1345 // # Methods to update internal state. -1346 -1347 /// Sets the initial user-defined data to be published in discovery services for this node. -1348 /// -1349 /// If the user-defined data passed to this function is different to the previous one, -1350 /// the endpoint will republish its node info to the configured discovery services. +1297 /// [`Registry`]: iroh_metrics::Registry +1298 /// [`Registry::register_all`]: iroh_metrics::Registry::register_all +1299 /// [`Registry::sub_registry_with_label`]: iroh_metrics::Registry::sub_registry_with_label +1300 /// [`Registry::sub_registry_with_prefix`]: iroh_metrics::Registry::sub_registry_with_prefix +1301 /// [`encode_openmetrics_to_string`]: iroh_metrics::MetricsSource::encode_openmetrics_to_string +1302 /// [`MetricsGroup`]: iroh_metrics::MetricsGroup +1303 /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet +1304 #[cfg(feature = "metrics")] +1305 pub fn metrics(&self) -> &EndpointMetrics { +1306 &self.msock.metrics +1307 } +1308 +1309 // # Methods for less common state updates. +1310 +1311 /// Notifies the system of potential network changes. +1312 /// +1313 /// On many systems iroh is able to detect network changes by itself, however +1314 /// some systems like android do not expose this functionality to native code. +1315 /// Android does however provide this functionality to Java code. This +1316 /// function allows for notifying iroh of any potential network changes like +1317 /// this. +1318 /// +1319 /// Even when the network did not change, or iroh was already able to detect +1320 /// the network change itself, there is no harm in calling this function. +1321 pub async fn network_change(&self) { +1322 self.msock.network_change().await; +1323 } +1324 +1325 // # Methods to update internal state. +1326 +1327 /// Sets the initial user-defined data to be published in discovery services for this node. +1328 /// +1329 /// If the user-defined data passed to this function is different to the previous one, +1330 /// the endpoint will republish its node info to the configured discovery services. +1331 /// +1332 /// See also [`Builder::user_data_for_discovery`] for setting an initial value when +1333 /// building the endpoint. +1334 pub fn set_user_data_for_discovery(&self, user_data: Option<UserData>) { +1335 self.msock.set_user_data_for_discovery(user_data); +1336 } +1337 +1338 // # Methods for terminating the endpoint. +1339 +1340 /// Closes the QUIC endpoint and the magic socket. +1341 /// +1342 /// This will close any remaining open [`Connection`]s with an error code +1343 /// of `0` and an empty reason. Though it is best practice to close those +1344 /// explicitly before with a custom error code and reason. +1345 /// +1346 /// It will then make a best effort to wait for all close notifications to be +1347 /// acknowledged by the peers, re-transmitting them if needed. This ensures the +1348 /// peers are aware of the closed connections instead of having to wait for a timeout +1349 /// on the connection. Once all connections are closed or timed out, the future +1350 /// finishes. 1351 /// -1352 /// See also [`Builder::user_data_for_discovery`] for setting an initial value when -1353 /// building the endpoint. -1354 pub fn set_user_data_for_discovery(&self, user_data: Option<UserData>) { -1355 self.msock.set_user_data_for_discovery(user_data); -1356 } -1357 -1358 // # Methods for terminating the endpoint. -1359 -1360 /// Closes the QUIC endpoint and the magic socket. -1361 /// -1362 /// This will close any remaining open [`Connection`]s with an error code -1363 /// of `0` and an empty reason. Though it is best practice to close those -1364 /// explicitly before with a custom error code and reason. -1365 /// -1366 /// It will then make a best effort to wait for all close notifications to be -1367 /// acknowledged by the peers, re-transmitting them if needed. This ensures the -1368 /// peers are aware of the closed connections instead of having to wait for a timeout -1369 /// on the connection. Once all connections are closed or timed out, the future -1370 /// finishes. -1371 /// -1372 /// The maximum time-out that this future will wait for depends on QUIC transport -1373 /// configurations of non-drained connections at the time of calling, and their current -1374 /// estimates of round trip time. With default parameters and a conservative estimate -1375 /// of round trip time, this call's future should take 3 seconds to resolve in cases of -1376 /// bad connectivity or failed connections. In the usual case, this call's future should -1377 /// return much more quickly. -1378 /// -1379 /// It is highly recommended you *do* wait for this close call to finish, if possible. -1380 /// Not doing so will make connections that were still open while closing the endpoint -1381 /// time out on the remote end. Thus remote ends will assume connections to have failed -1382 /// even if all application data was transmitted successfully. -1383 /// -1384 /// Note: Someone used to closing TCP sockets might wonder why it is necessary to wait -1385 /// for timeouts when closing QUIC endpoints, while they don't have to do this for TCP -1386 /// sockets. This is due to QUIC and its acknowledgments being implemented in user-land, -1387 /// while TCP sockets usually get closed and drained by the operating system in the -1388 /// kernel during the "Time-Wait" period of the TCP socket. -1389 /// -1390 /// Be aware however that the underlying UDP sockets are only closed once all clones of -1391 /// the the respective [`Endpoint`] are dropped. -1392 pub async fn close(&self) { -1393 if self.is_closed() { -1394 return; -1395 } -1396 -1397 tracing::debug!("Connections closed"); -1398 self.msock.close().await; -1399 } -1400 -1401 /// Check if this endpoint is still alive, or already closed. -1402 pub fn is_closed(&self) -> bool { -1403 self.msock.is_closed() -1404 } -1405 -1406 // # Remaining private methods -1407 -1408 /// Return the quic mapped address for this `node_id` and possibly start discovery -1409 /// services if discovery is enabled on this magic endpoint. -1410 /// -1411 /// This will launch discovery in all cases except if: -1412 /// 1) we do not have discovery enabled -1413 /// 2) we have discovery enabled, but already have at least one verified, unexpired -1414 /// addresses for this `node_id` -1415 /// -1416 /// # Errors -1417 /// -1418 /// This method may fail if we have no way of dialing the node. This can occur if -1419 /// we were given no dialing information in the [`NodeAddr`] and no discovery -1420 /// services were configured or if discovery failed to fetch any dialing information. -1421 async fn get_mapping_addr_and_maybe_start_discovery( -1422 &self, -1423 node_addr: NodeAddr, -1424 ) -> Result<(NodeIdMappedAddr, Option<DiscoveryTask>), GetMappingAddressError> { -1425 let node_id = node_addr.node_id; -1426 -1427 // Only return a mapped addr if we have some way of dialing this node, in other -1428 // words, we have either a relay URL or at least one direct address. -1429 let addr = if self.msock.has_send_address(node_id) { -1430 self.msock.get_mapping_addr(node_id) -1431 } else { -1432 None -1433 }; -1434 match addr { -1435 Some(addr) => { -1436 // We have some way of dialing this node, but that doesn't actually mean -1437 // we can actually connect to any of these addresses. -1438 // Therefore, we will invoke the discovery service if we haven't received from the -1439 // endpoint on any of the existing paths recently. -1440 // If the user provided addresses in this connect call, we will add a delay -1441 // followed by a recheck before starting the discovery, to give the magicsocket a -1442 // chance to test the newly provided addresses. -1443 let delay = (!node_addr.is_empty()).then_some(DISCOVERY_WAIT_PERIOD); -1444 let discovery = DiscoveryTask::maybe_start_after_delay(self, node_id, delay) -1445 .ok() -1446 .flatten(); -1447 Ok((addr, discovery)) -1448 } +1352 /// The maximum time-out that this future will wait for depends on QUIC transport +1353 /// configurations of non-drained connections at the time of calling, and their current +1354 /// estimates of round trip time. With default parameters and a conservative estimate +1355 /// of round trip time, this call's future should take 3 seconds to resolve in cases of +1356 /// bad connectivity or failed connections. In the usual case, this call's future should +1357 /// return much more quickly. +1358 /// +1359 /// It is highly recommended you *do* wait for this close call to finish, if possible. +1360 /// Not doing so will make connections that were still open while closing the endpoint +1361 /// time out on the remote end. Thus remote ends will assume connections to have failed +1362 /// even if all application data was transmitted successfully. +1363 /// +1364 /// Note: Someone used to closing TCP sockets might wonder why it is necessary to wait +1365 /// for timeouts when closing QUIC endpoints, while they don't have to do this for TCP +1366 /// sockets. This is due to QUIC and its acknowledgments being implemented in user-land, +1367 /// while TCP sockets usually get closed and drained by the operating system in the +1368 /// kernel during the "Time-Wait" period of the TCP socket. +1369 /// +1370 /// Be aware however that the underlying UDP sockets are only closed once all clones of +1371 /// the the respective [`Endpoint`] are dropped. +1372 pub async fn close(&self) { +1373 if self.is_closed() { +1374 return; +1375 } +1376 +1377 tracing::debug!("Connections closed"); +1378 self.msock.close().await; +1379 } +1380 +1381 /// Check if this endpoint is still alive, or already closed. +1382 pub fn is_closed(&self) -> bool { +1383 self.msock.is_closed() +1384 } +1385 +1386 // # Remaining private methods +1387 +1388 /// Return the quic mapped address for this `node_id` and possibly start discovery +1389 /// services if discovery is enabled on this magic endpoint. +1390 /// +1391 /// This will launch discovery in all cases except if: +1392 /// 1) we do not have discovery enabled +1393 /// 2) we have discovery enabled, but already have at least one verified, unexpired +1394 /// addresses for this `node_id` +1395 /// +1396 /// # Errors +1397 /// +1398 /// This method may fail if we have no way of dialing the node. This can occur if +1399 /// we were given no dialing information in the [`NodeAddr`] and no discovery +1400 /// services were configured or if discovery failed to fetch any dialing information. +1401 async fn get_mapping_addr_and_maybe_start_discovery( +1402 &self, +1403 node_addr: NodeAddr, +1404 ) -> Result<(NodeIdMappedAddr, Option<DiscoveryTask>), GetMappingAddressError> { +1405 let node_id = node_addr.node_id; +1406 +1407 // Only return a mapped addr if we have some way of dialing this node, in other +1408 // words, we have either a relay URL or at least one direct address. +1409 let addr = if self.msock.has_send_address(node_id) { +1410 self.msock.get_mapping_addr(node_id) +1411 } else { +1412 None +1413 }; +1414 match addr { +1415 Some(addr) => { +1416 // We have some way of dialing this node, but that doesn't actually mean +1417 // we can actually connect to any of these addresses. +1418 // Therefore, we will invoke the discovery service if we haven't received from the +1419 // endpoint on any of the existing paths recently. +1420 // If the user provided addresses in this connect call, we will add a delay +1421 // followed by a recheck before starting the discovery, to give the magicsocket a +1422 // chance to test the newly provided addresses. +1423 let delay = (!node_addr.is_empty()).then_some(DISCOVERY_WAIT_PERIOD); +1424 let discovery = DiscoveryTask::maybe_start_after_delay(self, node_id, delay) +1425 .ok() +1426 .flatten(); +1427 Ok((addr, discovery)) +1428 } +1429 +1430 None => { +1431 // We have no known addresses or relay URLs for this node. +1432 // So, we start a discovery task and wait for the first result to arrive, and +1433 // only then continue, because otherwise we wouldn't have any +1434 // path to the remote endpoint. +1435 let res = DiscoveryTask::start(self.clone(), node_id); +1436 let mut discovery = res.context(get_mapping_address_error::DiscoveryStartSnafu)?; +1437 discovery +1438 .first_arrived() +1439 .await +1440 .context(get_mapping_address_error::DiscoverSnafu)?; +1441 if let Some(addr) = self.msock.get_mapping_addr(node_id) { +1442 Ok((addr, Some(discovery))) +1443 } else { +1444 Err(get_mapping_address_error::NoAddressSnafu.build()) +1445 } +1446 } +1447 } +1448 } 1449 -1450 None => { -1451 // We have no known addresses or relay URLs for this node. -1452 // So, we start a discovery task and wait for the first result to arrive, and -1453 // only then continue, because otherwise we wouldn't have any -1454 // path to the remote endpoint. -1455 let res = DiscoveryTask::start(self.clone(), node_id); -1456 let mut discovery = res.context(get_mapping_address_error::DiscoveryStartSnafu)?; -1457 discovery -1458 .first_arrived() -1459 .await -1460 .context(get_mapping_address_error::DiscoverSnafu)?; -1461 if let Some(addr) = self.msock.get_mapping_addr(node_id) { -1462 Ok((addr, Some(discovery))) -1463 } else { -1464 Err(get_mapping_address_error::NoAddressSnafu.build()) -1465 } -1466 } -1467 } -1468 } -1469 -1470 /// Returns a reference to the subscribers channel for discovery events. -1471 pub(crate) fn discovery_subscribers(&self) -> &DiscoverySubscribers { -1472 self.msock.discovery_subscribers() -1473 } -1474 -1475 #[cfg(test)] -1476 pub(crate) fn magic_sock(&self) -> Handle { -1477 self.msock.clone() -1478 } -1479 #[cfg(test)] -1480 pub(crate) fn endpoint(&self) -> &quinn::Endpoint { -1481 self.msock.endpoint() -1482 } -1483} -1484 -1485/// Options for the [`Endpoint::connect_with_opts`] function. -1486#[derive(Default, Debug, Clone)] -1487pub struct ConnectOptions { -1488 transport_config: Option<Arc<TransportConfig>>, -1489 additional_alpns: Vec<Vec<u8>>, -1490} -1491 -1492impl ConnectOptions { -1493 /// Initializes new connection options. -1494 /// -1495 /// By default, the connection will use the same options -1496 /// as [`Endpoint::connect`], e.g. a default [`TransportConfig`]. -1497 pub fn new() -> Self { -1498 Self::default() -1499 } -1500 -1501 /// Sets the QUIC transport config options for this connection. -1502 pub fn with_transport_config(mut self, transport_config: Arc<TransportConfig>) -> Self { -1503 self.transport_config = Some(transport_config); -1504 self -1505 } -1506 -1507 /// Sets [ALPN] identifiers that should be signaled as supported on connection, *in -1508 /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`]. -1509 /// -1510 /// This allows connecting to servers that may only support older versions of your -1511 /// protocol. In this case, you would add the older [ALPN] identifiers with this -1512 /// function. -1513 /// -1514 /// You'll know the final negotiated [ALPN] identifier once your connection was -1515 /// established using [`Connection::alpn`], or even slightly earlier in the -1516 /// handshake by using [`Connecting::alpn`]. -1517 /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this -1518 /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`]. -1519 /// -1520 /// The [ALPN] identifier order on the connect side doesn't matter, since it's the -1521 /// accept side that determines the protocol. -1522 /// -1523 /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint -1524 /// builder's [`Builder::alpns`] function. -1525 /// -1526 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation -1527 pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self { -1528 self.additional_alpns = alpns; -1529 self -1530 } -1531} -1532 -1533/// Future produced by [`Endpoint::accept`]. -1534#[derive(derive_more::Debug)] -1535#[pin_project] -1536pub struct Accept<'a> { -1537 #[pin] -1538 #[debug("quinn::Accept")] -1539 inner: quinn::Accept<'a>, -1540 ep: Endpoint, -1541} -1542 -1543impl Future for Accept<'_> { -1544 type Output = Option<Incoming>; -1545 -1546 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { -1547 let this = self.project(); -1548 match this.inner.poll(cx) { -1549 Poll::Pending => Poll::Pending, -1550 Poll::Ready(None) => Poll::Ready(None), -1551 Poll::Ready(Some(inner)) => Poll::Ready(Some(Incoming { -1552 inner, -1553 ep: this.ep.clone(), -1554 })), -1555 } -1556 } -1557} -1558 -1559/// An incoming connection for which the server has not yet begun its parts of the -1560/// handshake. -1561#[derive(Debug)] -1562pub struct Incoming { -1563 inner: quinn::Incoming, -1564 ep: Endpoint, -1565} -1566 -1567impl Incoming { -1568 /// Attempts to accept this incoming connection (an error may still occur). +1450 /// Returns a reference to the subscribers channel for discovery events. +1451 pub(crate) fn discovery_subscribers(&self) -> &DiscoverySubscribers { +1452 self.msock.discovery_subscribers() +1453 } +1454 +1455 #[cfg(test)] +1456 pub(crate) fn magic_sock(&self) -> Handle { +1457 self.msock.clone() +1458 } +1459 #[cfg(test)] +1460 pub(crate) fn endpoint(&self) -> &quinn::Endpoint { +1461 self.msock.endpoint() +1462 } +1463} +1464 +1465/// Options for the [`Endpoint::connect_with_opts`] function. +1466#[derive(Default, Debug, Clone)] +1467pub struct ConnectOptions { +1468 transport_config: Option<Arc<TransportConfig>>, +1469 additional_alpns: Vec<Vec<u8>>, +1470} +1471 +1472impl ConnectOptions { +1473 /// Initializes new connection options. +1474 /// +1475 /// By default, the connection will use the same options +1476 /// as [`Endpoint::connect`], e.g. a default [`TransportConfig`]. +1477 pub fn new() -> Self { +1478 Self::default() +1479 } +1480 +1481 /// Sets the QUIC transport config options for this connection. +1482 pub fn with_transport_config(mut self, transport_config: Arc<TransportConfig>) -> Self { +1483 self.transport_config = Some(transport_config); +1484 self +1485 } +1486 +1487 /// Sets [ALPN] identifiers that should be signaled as supported on connection, *in +1488 /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`]. +1489 /// +1490 /// This allows connecting to servers that may only support older versions of your +1491 /// protocol. In this case, you would add the older [ALPN] identifiers with this +1492 /// function. +1493 /// +1494 /// You'll know the final negotiated [ALPN] identifier once your connection was +1495 /// established using [`Connection::alpn`], or even slightly earlier in the +1496 /// handshake by using [`Connecting::alpn`]. +1497 /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this +1498 /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`]. +1499 /// +1500 /// The [ALPN] identifier order on the connect side doesn't matter, since it's the +1501 /// accept side that determines the protocol. +1502 /// +1503 /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint +1504 /// builder's [`Builder::alpns`] function. +1505 /// +1506 /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation +1507 pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self { +1508 self.additional_alpns = alpns; +1509 self +1510 } +1511} +1512 +1513/// Future produced by [`Endpoint::accept`]. +1514#[derive(derive_more::Debug)] +1515#[pin_project] +1516pub struct Accept<'a> { +1517 #[pin] +1518 #[debug("quinn::Accept")] +1519 inner: quinn::Accept<'a>, +1520 ep: Endpoint, +1521} +1522 +1523impl Future for Accept<'_> { +1524 type Output = Option<Incoming>; +1525 +1526 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { +1527 let this = self.project(); +1528 match this.inner.poll(cx) { +1529 Poll::Pending => Poll::Pending, +1530 Poll::Ready(None) => Poll::Ready(None), +1531 Poll::Ready(Some(inner)) => Poll::Ready(Some(Incoming { +1532 inner, +1533 ep: this.ep.clone(), +1534 })), +1535 } +1536 } +1537} +1538 +1539/// An incoming connection for which the server has not yet begun its parts of the +1540/// handshake. +1541#[derive(Debug)] +1542pub struct Incoming { +1543 inner: quinn::Incoming, +1544 ep: Endpoint, +1545} +1546 +1547impl Incoming { +1548 /// Attempts to accept this incoming connection (an error may still occur). +1549 /// +1550 /// Errors occurring here are likely not caused by the application or remote. The QUIC +1551 /// connection listens on a normal UDP socket and any reachable network endpoint can +1552 /// send datagrams to it, solicited or not. Even if the first few bytes look like a +1553 /// QUIC packet, it might not even be a QUIC packet that is being received. +1554 /// +1555 /// Thus it is common to simply log the errors here and accept them as something which +1556 /// can happen. +1557 pub fn accept(self) -> Result<Connecting, ConnectionError> { +1558 self.inner.accept().map(|conn| Connecting { +1559 inner: conn, +1560 ep: self.ep, +1561 remote_node_id: None, +1562 _discovery_drop_guard: None, +1563 }) +1564 } +1565 +1566 /// Accepts this incoming connection using a custom configuration. +1567 /// +1568 /// See [`accept()`] for more details. 1569 /// -1570 /// Errors occurring here are likely not caused by the application or remote. The QUIC -1571 /// connection listens on a normal UDP socket and any reachable network endpoint can -1572 /// send datagrams to it, solicited or not. Even if the first few bytes look like a -1573 /// QUIC packet, it might not even be a QUIC packet that is being received. -1574 /// -1575 /// Thus it is common to simply log the errors here and accept them as something which -1576 /// can happen. -1577 pub fn accept(self) -> Result<Connecting, ConnectionError> { -1578 self.inner.accept().map(|conn| Connecting { -1579 inner: conn, -1580 ep: self.ep, -1581 remote_node_id: None, -1582 _discovery_drop_guard: None, -1583 }) -1584 } -1585 -1586 /// Accepts this incoming connection using a custom configuration. -1587 /// -1588 /// See [`accept()`] for more details. -1589 /// -1590 /// [`accept()`]: Incoming::accept -1591 pub fn accept_with( -1592 self, -1593 server_config: Arc<ServerConfig>, -1594 ) -> Result<Connecting, ConnectionError> { -1595 self.inner -1596 .accept_with(server_config) -1597 .map(|conn| Connecting { -1598 inner: conn, -1599 ep: self.ep, -1600 remote_node_id: None, -1601 _discovery_drop_guard: None, -1602 }) +1570 /// [`accept()`]: Incoming::accept +1571 pub fn accept_with( +1572 self, +1573 server_config: Arc<ServerConfig>, +1574 ) -> Result<Connecting, ConnectionError> { +1575 self.inner +1576 .accept_with(server_config) +1577 .map(|conn| Connecting { +1578 inner: conn, +1579 ep: self.ep, +1580 remote_node_id: None, +1581 _discovery_drop_guard: None, +1582 }) +1583 } +1584 +1585 /// Rejects this incoming connection attempt. +1586 pub fn refuse(self) { +1587 self.inner.refuse() +1588 } +1589 +1590 /// Responds with a retry packet. +1591 /// +1592 /// This requires the client to retry with address validation. +1593 /// +1594 /// Errors if `remote_address_validated()` is true. +1595 #[allow(clippy::result_large_err)] +1596 pub fn retry(self) -> Result<(), RetryError> { +1597 self.inner.retry() +1598 } +1599 +1600 /// Ignores this incoming connection attempt, not sending any packet in response. +1601 pub fn ignore(self) { +1602 self.inner.ignore() 1603 } 1604 -1605 /// Rejects this incoming connection attempt. -1606 pub fn refuse(self) { -1607 self.inner.refuse() -1608 } -1609 -1610 /// Responds with a retry packet. -1611 /// -1612 /// This requires the client to retry with address validation. -1613 /// -1614 /// Errors if `remote_address_validated()` is true. -1615 #[allow(clippy::result_large_err)] -1616 pub fn retry(self) -> Result<(), RetryError> { -1617 self.inner.retry() -1618 } -1619 -1620 /// Ignores this incoming connection attempt, not sending any packet in response. -1621 pub fn ignore(self) { -1622 self.inner.ignore() -1623 } +1605 /// Returns the local IP address which was used when the peer established the +1606 /// connection. +1607 pub fn local_ip(&self) -> Option<IpAddr> { +1608 self.inner.local_ip() +1609 } +1610 +1611 /// Returns the peer's UDP address. +1612 pub fn remote_address(&self) -> SocketAddr { +1613 self.inner.remote_address() +1614 } +1615 +1616 /// Whether the socket address that is initiating this connection has been validated. +1617 /// +1618 /// This means that the sender of the initial packet has proved that they can receive +1619 /// traffic sent to `self.remote_address()`. +1620 pub fn remote_address_validated(&self) -> bool { +1621 self.inner.remote_address_validated() +1622 } +1623} 1624 -1625 /// Returns the local IP address which was used when the peer established the -1626 /// connection. -1627 pub fn local_ip(&self) -> Option<IpAddr> { -1628 self.inner.local_ip() -1629 } -1630 -1631 /// Returns the peer's UDP address. -1632 pub fn remote_address(&self) -> SocketAddr { -1633 self.inner.remote_address() +1625impl IntoFuture for Incoming { +1626 type Output = Result<Connection, ConnectionError>; +1627 type IntoFuture = IncomingFuture; +1628 +1629 fn into_future(self) -> Self::IntoFuture { +1630 IncomingFuture { +1631 inner: self.inner.into_future(), +1632 ep: self.ep, +1633 } 1634 } -1635 -1636 /// Whether the socket address that is initiating this connection has been validated. -1637 /// -1638 /// This means that the sender of the initial packet has proved that they can receive -1639 /// traffic sent to `self.remote_address()`. -1640 pub fn remote_address_validated(&self) -> bool { -1641 self.inner.remote_address_validated() -1642 } -1643} -1644 -1645impl IntoFuture for Incoming { -1646 type Output = Result<Connection, ConnectionError>; -1647 type IntoFuture = IncomingFuture; +1635} +1636 +1637/// Adaptor to let [`Incoming`] be `await`ed like a [`Connecting`]. +1638#[derive(Debug)] +1639#[pin_project] +1640pub struct IncomingFuture { +1641 #[pin] +1642 inner: quinn::IncomingFuture, +1643 ep: Endpoint, +1644} +1645 +1646impl Future for IncomingFuture { +1647 type Output = Result<Connection, ConnectionError>; 1648 -1649 fn into_future(self) -> Self::IntoFuture { -1650 IncomingFuture { -1651 inner: self.inner.into_future(), -1652 ep: self.ep, -1653 } -1654 } -1655} -1656 -1657/// Adaptor to let [`Incoming`] be `await`ed like a [`Connecting`]. -1658#[derive(Debug)] -1659#[pin_project] -1660pub struct IncomingFuture { -1661 #[pin] -1662 inner: quinn::IncomingFuture, -1663 ep: Endpoint, -1664} -1665 -1666impl Future for IncomingFuture { -1667 type Output = Result<Connection, ConnectionError>; -1668 -1669 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { -1670 let this = self.project(); -1671 match this.inner.poll(cx) { -1672 Poll::Pending => Poll::Pending, -1673 Poll::Ready(Err(err)) => Poll::Ready(Err(err)), -1674 Poll::Ready(Ok(inner)) => { -1675 let conn = Connection { inner }; -1676 try_send_rtt_msg(&conn, this.ep, None); -1677 Poll::Ready(Ok(conn)) -1678 } -1679 } -1680 } -1681} -1682 -1683/// In-progress connection attempt future -1684#[derive(derive_more::Debug)] -1685#[pin_project] -1686pub struct Connecting { -1687 #[pin] -1688 inner: quinn::Connecting, -1689 ep: Endpoint, -1690 remote_node_id: Option<NodeId>, -1691 /// We run discovery as long as we haven't established a connection yet. -1692 #[debug("Option<DiscoveryTask>")] -1693 _discovery_drop_guard: Option<DiscoveryTask>, -1694} -1695 -1696#[allow(missing_docs)] -1697#[common_fields({ -1698 backtrace: Option<snafu::Backtrace>, -1699 #[snafu(implicit)] -1700 span_trace: n0_snafu::SpanTrace, -1701})] -1702#[derive(Debug, Snafu)] -1703#[non_exhaustive] -1704pub enum AlpnError { -1705 #[snafu(transparent)] -1706 ConnectionError { source: ConnectionError }, -1707 #[snafu(display("No ALPN available"))] -1708 Unavailable {}, -1709 #[snafu(display("Unknown handshake type"))] -1710 UnknownHandshake {}, -1711} -1712 -1713impl Connecting { -1714 /// Converts this [`Connecting`] into a 0-RTT or 0.5-RTT connection at the cost of weakened -1715 /// security. -1716 /// -1717 /// Returns `Ok` immediately if the local endpoint is able to attempt sending 0/0.5-RTT data. -1718 /// If so, the returned [`Connection`] can be used to send application data without waiting for -1719 /// the rest of the handshake to complete, at the cost of weakened cryptographic security -1720 /// guarantees. The returned [`ZeroRttAccepted`] future resolves when the handshake does -1721 /// complete, at which point subsequently opened streams and written data will have full -1722 /// cryptographic protection. -1723 /// -1724 /// Once the [`ZeroRttAccepted`] future completed, a full handshake has been carried through -1725 /// and any data sent and any streams opened on the [`Connection`] will operate with the same -1726 /// security as on normal 1-RTT connections. +1649 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { +1650 let this = self.project(); +1651 match this.inner.poll(cx) { +1652 Poll::Pending => Poll::Pending, +1653 Poll::Ready(Err(err)) => Poll::Ready(Err(err)), +1654 Poll::Ready(Ok(inner)) => { +1655 let conn = Connection { inner }; +1656 try_send_rtt_msg(&conn, this.ep, None); +1657 Poll::Ready(Ok(conn)) +1658 } +1659 } +1660 } +1661} +1662 +1663/// In-progress connection attempt future +1664#[derive(derive_more::Debug)] +1665#[pin_project] +1666pub struct Connecting { +1667 #[pin] +1668 inner: quinn::Connecting, +1669 ep: Endpoint, +1670 remote_node_id: Option<NodeId>, +1671 /// We run discovery as long as we haven't established a connection yet. +1672 #[debug("Option<DiscoveryTask>")] +1673 _discovery_drop_guard: Option<DiscoveryTask>, +1674} +1675 +1676#[allow(missing_docs)] +1677#[common_fields({ +1678 backtrace: Option<snafu::Backtrace>, +1679 #[snafu(implicit)] +1680 span_trace: n0_snafu::SpanTrace, +1681})] +1682#[derive(Debug, Snafu)] +1683#[non_exhaustive] +1684pub enum AlpnError { +1685 #[snafu(transparent)] +1686 ConnectionError { source: ConnectionError }, +1687 #[snafu(display("No ALPN available"))] +1688 Unavailable {}, +1689 #[snafu(display("Unknown handshake type"))] +1690 UnknownHandshake {}, +1691} +1692 +1693impl Connecting { +1694 /// Converts this [`Connecting`] into a 0-RTT or 0.5-RTT connection at the cost of weakened +1695 /// security. +1696 /// +1697 /// Returns `Ok` immediately if the local endpoint is able to attempt sending 0/0.5-RTT data. +1698 /// If so, the returned [`Connection`] can be used to send application data without waiting for +1699 /// the rest of the handshake to complete, at the cost of weakened cryptographic security +1700 /// guarantees. The returned [`ZeroRttAccepted`] future resolves when the handshake does +1701 /// complete, at which point subsequently opened streams and written data will have full +1702 /// cryptographic protection. +1703 /// +1704 /// Once the [`ZeroRttAccepted`] future completed, a full handshake has been carried through +1705 /// and any data sent and any streams opened on the [`Connection`] will operate with the same +1706 /// security as on normal 1-RTT connections. +1707 /// +1708 /// ## Outgoing +1709 /// +1710 /// For outgoing connections, the initial attempt to convert to a [`Connection`] which sends +1711 /// 0-RTT data will attempt to resume a previous TLS session. However, **the remote endpoint +1712 /// may not actually _accept_ the 0-RTT data**--yet still accept the connection attempt in +1713 /// general. This possibility is conveyed through the [`ZeroRttAccepted`] future--when the +1714 /// handshake completes, it resolves to true if the 0-RTT data was accepted and false if it was +1715 /// rejected. If it was rejected, the existence of streams opened and other application data +1716 /// sent prior to the handshake completing will not be conveyed to the remote application, and +1717 /// local operations on them will return `ZeroRttRejected` errors. +1718 /// +1719 /// A server may reject 0-RTT data at its discretion, but accepting 0-RTT data requires the +1720 /// relevant resumption state to be stored in the server, which servers may limit or lose for +1721 /// various reasons including not persisting resumption state across server restarts. +1722 /// +1723 /// ## Incoming +1724 /// +1725 /// For incoming connections, conversion to 0.5-RTT will always fully succeed. `into_0rtt` will +1726 /// always return `Ok` and the [`ZeroRttAccepted`] will always resolve to true. 1727 /// -1728 /// ## Outgoing +1728 /// ## Security 1729 /// -1730 /// For outgoing connections, the initial attempt to convert to a [`Connection`] which sends -1731 /// 0-RTT data will attempt to resume a previous TLS session. However, **the remote endpoint -1732 /// may not actually _accept_ the 0-RTT data**--yet still accept the connection attempt in -1733 /// general. This possibility is conveyed through the [`ZeroRttAccepted`] future--when the -1734 /// handshake completes, it resolves to true if the 0-RTT data was accepted and false if it was -1735 /// rejected. If it was rejected, the existence of streams opened and other application data -1736 /// sent prior to the handshake completing will not be conveyed to the remote application, and -1737 /// local operations on them will return `ZeroRttRejected` errors. -1738 /// -1739 /// A server may reject 0-RTT data at its discretion, but accepting 0-RTT data requires the -1740 /// relevant resumption state to be stored in the server, which servers may limit or lose for -1741 /// various reasons including not persisting resumption state across server restarts. -1742 /// -1743 /// ## Incoming -1744 /// -1745 /// For incoming connections, conversion to 0.5-RTT will always fully succeed. `into_0rtt` will -1746 /// always return `Ok` and the [`ZeroRttAccepted`] will always resolve to true. -1747 /// -1748 /// ## Security -1749 /// -1750 /// On outgoing connections, this enables transmission of 0-RTT data, which is vulnerable to -1751 /// replay attacks, and should therefore never invoke non-idempotent operations. -1752 /// -1753 /// On incoming connections, this enables transmission of 0.5-RTT data, which may be sent -1754 /// before TLS client authentication has occurred, and should therefore not be used to send -1755 /// data for which client authentication is being used. -1756 /// -1757 /// You can use [`RecvStream::is_0rtt`] to check whether a stream has been opened in 0-RTT -1758 /// and thus whether parts of the stream are operating under this reduced security level. -1759 #[allow(clippy::result_large_err)] -1760 pub fn into_0rtt(self) -> Result<(Connection, ZeroRttAccepted), Self> { -1761 match self.inner.into_0rtt() { -1762 Ok((inner, zrtt_accepted)) => { -1763 let conn = Connection { inner }; -1764 let zrtt_accepted = ZeroRttAccepted { -1765 inner: zrtt_accepted, -1766 _discovery_drop_guard: self._discovery_drop_guard, -1767 }; -1768 // This call is why `self.remote_node_id` was introduced. -1769 // When we `Connecting::into_0rtt`, then we don't yet have `handshake_data` -1770 // in our `Connection`, thus `try_send_rtt_msg` won't be able to pick up -1771 // `Connection::remote_node_id`. -1772 // Instead, we provide `self.remote_node_id` here - we know it in advance, -1773 // after all. -1774 try_send_rtt_msg(&conn, &self.ep, self.remote_node_id); -1775 Ok((conn, zrtt_accepted)) -1776 } -1777 Err(inner) => Err(Self { -1778 inner, -1779 ep: self.ep, -1780 remote_node_id: self.remote_node_id, -1781 _discovery_drop_guard: self._discovery_drop_guard, -1782 }), -1783 } -1784 } -1785 -1786 /// Parameters negotiated during the handshake -1787 pub async fn handshake_data(&mut self) -> Result<Box<dyn Any>, ConnectionError> { -1788 self.inner.handshake_data().await -1789 } -1790 -1791 /// Extracts the ALPN protocol from the peer's handshake data. -1792 pub async fn alpn(&mut self) -> Result<Vec<u8>, AlpnError> { -1793 let data = self.handshake_data().await?; -1794 match data.downcast::<quinn::crypto::rustls::HandshakeData>() { -1795 Ok(data) => match data.protocol { -1796 Some(protocol) => Ok(protocol), -1797 None => Err(UnavailableSnafu.build()), -1798 }, -1799 Err(_) => Err(UnknownHandshakeSnafu.build()), -1800 } -1801 } -1802} -1803 -1804impl Future for Connecting { -1805 type Output = Result<Connection, ConnectionError>; -1806 -1807 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { -1808 let this = self.project(); -1809 match this.inner.poll(cx) { -1810 Poll::Pending => Poll::Pending, -1811 Poll::Ready(Err(err)) => Poll::Ready(Err(err)), -1812 Poll::Ready(Ok(inner)) => { -1813 let conn = Connection { inner }; -1814 try_send_rtt_msg(&conn, this.ep, *this.remote_node_id); -1815 Poll::Ready(Ok(conn)) -1816 } -1817 } -1818 } -1819} -1820 -1821/// Future that completes when a connection is fully established. -1822/// -1823/// For clients, the resulting value indicates if 0-RTT was accepted. For servers, the resulting -1824/// value is meaningless. -1825#[derive(derive_more::Debug)] -1826#[debug("ZeroRttAccepted")] -1827pub struct ZeroRttAccepted { -1828 inner: quinn::ZeroRttAccepted, -1829 /// When we call `Connecting::into_0rtt`, we don't want to stop discovery, so we transfer the task -1830 /// to this future. -1831 /// When `quinn::ZeroRttAccepted` resolves, we've successfully received data from the remote. -1832 /// Thus, that's the right time to drop discovery to preserve the behaviour similar to -1833 /// `Connecting` -> `Connection` without 0-RTT. -1834 /// Should we eventually decide to keep the discovery task alive for the duration of the whole -1835 /// `Connection`, then this task should be transferred to the `Connection` instead of here. -1836 _discovery_drop_guard: Option<DiscoveryTask>, -1837} -1838 -1839impl Future for ZeroRttAccepted { -1840 type Output = bool; -1841 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { -1842 Pin::new(&mut self.inner).poll(cx) -1843 } -1844} -1845 -1846/// A QUIC connection. -1847/// -1848/// If all references to a connection (including every clone of the Connection handle, -1849/// streams of incoming streams, and the various stream types) have been dropped, then the -1850/// connection will be automatically closed with an error_code of 0 and an empty reason. You -1851/// can also close the connection explicitly by calling [`Connection::close`]. -1852/// -1853/// Closing the connection immediately abandons efforts to deliver data to the peer. Upon -1854/// receiving CONNECTION_CLOSE the peer may drop any stream data not yet delivered to the -1855/// application. [`Connection::close`] describes in more detail how to gracefully close a -1856/// connection without losing application data. -1857/// -1858/// May be cloned to obtain another handle to the same connection. -1859#[derive(Debug, Clone)] -1860pub struct Connection { -1861 inner: quinn::Connection, -1862} -1863 -1864#[allow(missing_docs)] -1865#[derive(Debug, Snafu)] -1866#[snafu(display("Protocol error: no remote id available"))] -1867pub struct RemoteNodeIdError { -1868 backtrace: Option<snafu::Backtrace>, -1869} -1870 -1871impl Connection { -1872 /// Initiates a new outgoing unidirectional stream. -1873 /// -1874 /// Streams are cheap and instantaneous to open unless blocked by flow control. As a -1875 /// consequence, the peer won’t be notified that a stream has been opened until the -1876 /// stream is actually used. -1877 #[inline] -1878 pub fn open_uni(&self) -> OpenUni<'_> { -1879 self.inner.open_uni() -1880 } -1881 -1882 /// Initiates a new outgoing bidirectional stream. -1883 /// -1884 /// Streams are cheap and instantaneous to open unless blocked by flow control. As a -1885 /// consequence, the peer won't be notified that a stream has been opened until the -1886 /// stream is actually used. Calling [`open_bi`] then waiting on the [`RecvStream`] -1887 /// without writing anything to [`SendStream`] will never succeed. -1888 /// -1889 /// [`open_bi`]: Connection::open_bi -1890 #[inline] -1891 pub fn open_bi(&self) -> OpenBi<'_> { -1892 self.inner.open_bi() -1893 } -1894 -1895 /// Accepts the next incoming uni-directional stream. -1896 #[inline] -1897 pub fn accept_uni(&self) -> AcceptUni<'_> { -1898 self.inner.accept_uni() -1899 } -1900 -1901 /// Accept the next incoming bidirectional stream. -1902 /// -1903 /// **Important Note**: The peer that calls [`open_bi`] must write to its [`SendStream`] -1904 /// before the peer `Connection` is able to accept the stream using -1905 /// `accept_bi()`. Calling [`open_bi`] then waiting on the [`RecvStream`] without -1906 /// writing anything to the connected [`SendStream`] will never succeed. -1907 /// -1908 /// [`open_bi`]: Connection::open_bi -1909 #[inline] -1910 pub fn accept_bi(&self) -> AcceptBi<'_> { -1911 self.inner.accept_bi() -1912 } -1913 -1914 /// Receives an application datagram. -1915 #[inline] -1916 pub fn read_datagram(&self) -> ReadDatagram<'_> { -1917 self.inner.read_datagram() -1918 } -1919 -1920 /// Wait for the connection to be closed for any reason. -1921 /// -1922 /// Despite the return type's name, closed connections are often not an error condition -1923 /// at the application layer. Cases that might be routine include -1924 /// [`ConnectionError::LocallyClosed`] and [`ConnectionError::ApplicationClosed`]. -1925 #[inline] -1926 pub async fn closed(&self) -> ConnectionError { -1927 self.inner.closed().await -1928 } -1929 -1930 /// If the connection is closed, the reason why. +1730 /// On outgoing connections, this enables transmission of 0-RTT data, which is vulnerable to +1731 /// replay attacks, and should therefore never invoke non-idempotent operations. +1732 /// +1733 /// On incoming connections, this enables transmission of 0.5-RTT data, which may be sent +1734 /// before TLS client authentication has occurred, and should therefore not be used to send +1735 /// data for which client authentication is being used. +1736 /// +1737 /// You can use [`RecvStream::is_0rtt`] to check whether a stream has been opened in 0-RTT +1738 /// and thus whether parts of the stream are operating under this reduced security level. +1739 #[allow(clippy::result_large_err)] +1740 pub fn into_0rtt(self) -> Result<(Connection, ZeroRttAccepted), Self> { +1741 match self.inner.into_0rtt() { +1742 Ok((inner, zrtt_accepted)) => { +1743 let conn = Connection { inner }; +1744 let zrtt_accepted = ZeroRttAccepted { +1745 inner: zrtt_accepted, +1746 _discovery_drop_guard: self._discovery_drop_guard, +1747 }; +1748 // This call is why `self.remote_node_id` was introduced. +1749 // When we `Connecting::into_0rtt`, then we don't yet have `handshake_data` +1750 // in our `Connection`, thus `try_send_rtt_msg` won't be able to pick up +1751 // `Connection::remote_node_id`. +1752 // Instead, we provide `self.remote_node_id` here - we know it in advance, +1753 // after all. +1754 try_send_rtt_msg(&conn, &self.ep, self.remote_node_id); +1755 Ok((conn, zrtt_accepted)) +1756 } +1757 Err(inner) => Err(Self { +1758 inner, +1759 ep: self.ep, +1760 remote_node_id: self.remote_node_id, +1761 _discovery_drop_guard: self._discovery_drop_guard, +1762 }), +1763 } +1764 } +1765 +1766 /// Parameters negotiated during the handshake +1767 pub async fn handshake_data(&mut self) -> Result<Box<dyn Any>, ConnectionError> { +1768 self.inner.handshake_data().await +1769 } +1770 +1771 /// Extracts the ALPN protocol from the peer's handshake data. +1772 pub async fn alpn(&mut self) -> Result<Vec<u8>, AlpnError> { +1773 let data = self.handshake_data().await?; +1774 match data.downcast::<quinn::crypto::rustls::HandshakeData>() { +1775 Ok(data) => match data.protocol { +1776 Some(protocol) => Ok(protocol), +1777 None => Err(UnavailableSnafu.build()), +1778 }, +1779 Err(_) => Err(UnknownHandshakeSnafu.build()), +1780 } +1781 } +1782} +1783 +1784impl Future for Connecting { +1785 type Output = Result<Connection, ConnectionError>; +1786 +1787 fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { +1788 let this = self.project(); +1789 match this.inner.poll(cx) { +1790 Poll::Pending => Poll::Pending, +1791 Poll::Ready(Err(err)) => Poll::Ready(Err(err)), +1792 Poll::Ready(Ok(inner)) => { +1793 let conn = Connection { inner }; +1794 try_send_rtt_msg(&conn, this.ep, *this.remote_node_id); +1795 Poll::Ready(Ok(conn)) +1796 } +1797 } +1798 } +1799} +1800 +1801/// Future that completes when a connection is fully established. +1802/// +1803/// For clients, the resulting value indicates if 0-RTT was accepted. For servers, the resulting +1804/// value is meaningless. +1805#[derive(derive_more::Debug)] +1806#[debug("ZeroRttAccepted")] +1807pub struct ZeroRttAccepted { +1808 inner: quinn::ZeroRttAccepted, +1809 /// When we call `Connecting::into_0rtt`, we don't want to stop discovery, so we transfer the task +1810 /// to this future. +1811 /// When `quinn::ZeroRttAccepted` resolves, we've successfully received data from the remote. +1812 /// Thus, that's the right time to drop discovery to preserve the behaviour similar to +1813 /// `Connecting` -> `Connection` without 0-RTT. +1814 /// Should we eventually decide to keep the discovery task alive for the duration of the whole +1815 /// `Connection`, then this task should be transferred to the `Connection` instead of here. +1816 _discovery_drop_guard: Option<DiscoveryTask>, +1817} +1818 +1819impl Future for ZeroRttAccepted { +1820 type Output = bool; +1821 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> { +1822 Pin::new(&mut self.inner).poll(cx) +1823 } +1824} +1825 +1826/// A QUIC connection. +1827/// +1828/// If all references to a connection (including every clone of the Connection handle, +1829/// streams of incoming streams, and the various stream types) have been dropped, then the +1830/// connection will be automatically closed with an error_code of 0 and an empty reason. You +1831/// can also close the connection explicitly by calling [`Connection::close`]. +1832/// +1833/// Closing the connection immediately abandons efforts to deliver data to the peer. Upon +1834/// receiving CONNECTION_CLOSE the peer may drop any stream data not yet delivered to the +1835/// application. [`Connection::close`] describes in more detail how to gracefully close a +1836/// connection without losing application data. +1837/// +1838/// May be cloned to obtain another handle to the same connection. +1839#[derive(Debug, Clone)] +1840pub struct Connection { +1841 inner: quinn::Connection, +1842} +1843 +1844#[allow(missing_docs)] +1845#[derive(Debug, Snafu)] +1846#[snafu(display("Protocol error: no remote id available"))] +1847pub struct RemoteNodeIdError { +1848 backtrace: Option<snafu::Backtrace>, +1849} +1850 +1851impl Connection { +1852 /// Initiates a new outgoing unidirectional stream. +1853 /// +1854 /// Streams are cheap and instantaneous to open unless blocked by flow control. As a +1855 /// consequence, the peer won’t be notified that a stream has been opened until the +1856 /// stream is actually used. +1857 #[inline] +1858 pub fn open_uni(&self) -> OpenUni<'_> { +1859 self.inner.open_uni() +1860 } +1861 +1862 /// Initiates a new outgoing bidirectional stream. +1863 /// +1864 /// Streams are cheap and instantaneous to open unless blocked by flow control. As a +1865 /// consequence, the peer won't be notified that a stream has been opened until the +1866 /// stream is actually used. Calling [`open_bi`] then waiting on the [`RecvStream`] +1867 /// without writing anything to [`SendStream`] will never succeed. +1868 /// +1869 /// [`open_bi`]: Connection::open_bi +1870 #[inline] +1871 pub fn open_bi(&self) -> OpenBi<'_> { +1872 self.inner.open_bi() +1873 } +1874 +1875 /// Accepts the next incoming uni-directional stream. +1876 #[inline] +1877 pub fn accept_uni(&self) -> AcceptUni<'_> { +1878 self.inner.accept_uni() +1879 } +1880 +1881 /// Accept the next incoming bidirectional stream. +1882 /// +1883 /// **Important Note**: The peer that calls [`open_bi`] must write to its [`SendStream`] +1884 /// before the peer `Connection` is able to accept the stream using +1885 /// `accept_bi()`. Calling [`open_bi`] then waiting on the [`RecvStream`] without +1886 /// writing anything to the connected [`SendStream`] will never succeed. +1887 /// +1888 /// [`open_bi`]: Connection::open_bi +1889 #[inline] +1890 pub fn accept_bi(&self) -> AcceptBi<'_> { +1891 self.inner.accept_bi() +1892 } +1893 +1894 /// Receives an application datagram. +1895 #[inline] +1896 pub fn read_datagram(&self) -> ReadDatagram<'_> { +1897 self.inner.read_datagram() +1898 } +1899 +1900 /// Wait for the connection to be closed for any reason. +1901 /// +1902 /// Despite the return type's name, closed connections are often not an error condition +1903 /// at the application layer. Cases that might be routine include +1904 /// [`ConnectionError::LocallyClosed`] and [`ConnectionError::ApplicationClosed`]. +1905 #[inline] +1906 pub async fn closed(&self) -> ConnectionError { +1907 self.inner.closed().await +1908 } +1909 +1910 /// If the connection is closed, the reason why. +1911 /// +1912 /// Returns `None` if the connection is still open. +1913 #[inline] +1914 pub fn close_reason(&self) -> Option<ConnectionError> { +1915 self.inner.close_reason() +1916 } +1917 +1918 /// Closes the connection immediately. +1919 /// +1920 /// Pending operations will fail immediately with [`ConnectionError::LocallyClosed`]. No +1921 /// more data is sent to the peer and the peer may drop buffered data upon receiving the +1922 /// CONNECTION_CLOSE frame. +1923 /// +1924 /// `error_code` and `reason` are not interpreted, and are provided directly to the +1925 /// peer. +1926 /// +1927 /// `reason` will be truncated to fit in a single packet with overhead; to improve odds +1928 /// that it is preserved in full, it should be kept under 1KiB. +1929 /// +1930 /// # Gracefully closing a connection 1931 /// -1932 /// Returns `None` if the connection is still open. -1933 #[inline] -1934 pub fn close_reason(&self) -> Option<ConnectionError> { -1935 self.inner.close_reason() -1936 } -1937 -1938 /// Closes the connection immediately. -1939 /// -1940 /// Pending operations will fail immediately with [`ConnectionError::LocallyClosed`]. No -1941 /// more data is sent to the peer and the peer may drop buffered data upon receiving the -1942 /// CONNECTION_CLOSE frame. -1943 /// -1944 /// `error_code` and `reason` are not interpreted, and are provided directly to the -1945 /// peer. -1946 /// -1947 /// `reason` will be truncated to fit in a single packet with overhead; to improve odds -1948 /// that it is preserved in full, it should be kept under 1KiB. -1949 /// -1950 /// # Gracefully closing a connection -1951 /// -1952 /// Only the peer last receiving application data can be certain that all data is -1953 /// delivered. The only reliable action it can then take is to close the connection, -1954 /// potentially with a custom error code. The delivery of the final CONNECTION_CLOSE -1955 /// frame is very likely if both endpoints stay online long enough, calling -1956 /// [`Endpoint::close`] will wait to provide sufficient time. Otherwise, the remote peer -1957 /// will time out the connection, provided that the idle timeout is not disabled. -1958 /// -1959 /// The sending side can not guarantee all stream data is delivered to the remote -1960 /// application. It only knows the data is delivered to the QUIC stack of the remote -1961 /// endpoint. Once the local side sends a CONNECTION_CLOSE frame in response to calling -1962 /// [`close`] the remote endpoint may drop any data it received but is as yet -1963 /// undelivered to the application, including data that was acknowledged as received to -1964 /// the local endpoint. -1965 /// -1966 /// [`close`]: Connection::close -1967 #[inline] -1968 pub fn close(&self, error_code: VarInt, reason: &[u8]) { -1969 self.inner.close(error_code, reason) -1970 } -1971 -1972 /// Transmits `data` as an unreliable, unordered application datagram. -1973 /// -1974 /// Application datagrams are a low-level primitive. They may be lost or delivered out -1975 /// of order, and `data` must both fit inside a single QUIC packet and be smaller than -1976 /// the maximum dictated by the peer. -1977 #[inline] -1978 pub fn send_datagram(&self, data: bytes::Bytes) -> Result<(), SendDatagramError> { -1979 self.inner.send_datagram(data) -1980 } -1981 -1982 // TODO: It seems `SendDatagram` is not yet exposed by quinn. This has been fixed -1983 // upstream and will be in the next release. -1984 // /// Transmits `data` as an unreliable, unordered application datagram -1985 // /// -1986 // /// Unlike [`send_datagram()`], this method will wait for buffer space during congestion -1987 // /// conditions, which effectively prioritizes old datagrams over new datagrams. -1988 // /// -1989 // /// See [`send_datagram()`] for details. -1990 // /// -1991 // /// [`send_datagram()`]: Connection::send_datagram -1992 // #[inline] -1993 // pub fn send_datagram_wait(&self, data: bytes::Bytes) -> SendDatagram<'_> { -1994 // self.inner.send_datagram_wait(data) -1995 // } -1996 -1997 /// Computes the maximum size of datagrams that may be passed to [`send_datagram`]. +1932 /// Only the peer last receiving application data can be certain that all data is +1933 /// delivered. The only reliable action it can then take is to close the connection, +1934 /// potentially with a custom error code. The delivery of the final CONNECTION_CLOSE +1935 /// frame is very likely if both endpoints stay online long enough, calling +1936 /// [`Endpoint::close`] will wait to provide sufficient time. Otherwise, the remote peer +1937 /// will time out the connection, provided that the idle timeout is not disabled. +1938 /// +1939 /// The sending side can not guarantee all stream data is delivered to the remote +1940 /// application. It only knows the data is delivered to the QUIC stack of the remote +1941 /// endpoint. Once the local side sends a CONNECTION_CLOSE frame in response to calling +1942 /// [`close`] the remote endpoint may drop any data it received but is as yet +1943 /// undelivered to the application, including data that was acknowledged as received to +1944 /// the local endpoint. +1945 /// +1946 /// [`close`]: Connection::close +1947 #[inline] +1948 pub fn close(&self, error_code: VarInt, reason: &[u8]) { +1949 self.inner.close(error_code, reason) +1950 } +1951 +1952 /// Transmits `data` as an unreliable, unordered application datagram. +1953 /// +1954 /// Application datagrams are a low-level primitive. They may be lost or delivered out +1955 /// of order, and `data` must both fit inside a single QUIC packet and be smaller than +1956 /// the maximum dictated by the peer. +1957 #[inline] +1958 pub fn send_datagram(&self, data: bytes::Bytes) -> Result<(), SendDatagramError> { +1959 self.inner.send_datagram(data) +1960 } +1961 +1962 // TODO: It seems `SendDatagram` is not yet exposed by quinn. This has been fixed +1963 // upstream and will be in the next release. +1964 // /// Transmits `data` as an unreliable, unordered application datagram +1965 // /// +1966 // /// Unlike [`send_datagram()`], this method will wait for buffer space during congestion +1967 // /// conditions, which effectively prioritizes old datagrams over new datagrams. +1968 // /// +1969 // /// See [`send_datagram()`] for details. +1970 // /// +1971 // /// [`send_datagram()`]: Connection::send_datagram +1972 // #[inline] +1973 // pub fn send_datagram_wait(&self, data: bytes::Bytes) -> SendDatagram<'_> { +1974 // self.inner.send_datagram_wait(data) +1975 // } +1976 +1977 /// Computes the maximum size of datagrams that may be passed to [`send_datagram`]. +1978 /// +1979 /// Returns `None` if datagrams are unsupported by the peer or disabled locally. +1980 /// +1981 /// This may change over the lifetime of a connection according to variation in the path +1982 /// MTU estimate. The peer can also enforce an arbitrarily small fixed limit, but if the +1983 /// peer's limit is large this is guaranteed to be a little over a kilobyte at minimum. +1984 /// +1985 /// Not necessarily the maximum size of received datagrams. +1986 /// +1987 /// [`send_datagram`]: Self::send_datagram +1988 #[inline] +1989 pub fn max_datagram_size(&self) -> Option<usize> { +1990 self.inner.max_datagram_size() +1991 } +1992 +1993 /// Bytes available in the outgoing datagram buffer. +1994 /// +1995 /// When greater than zero, calling [`send_datagram`] with a +1996 /// datagram of at most this size is guaranteed not to cause older datagrams to be +1997 /// dropped. 1998 /// -1999 /// Returns `None` if datagrams are unsupported by the peer or disabled locally. -2000 /// -2001 /// This may change over the lifetime of a connection according to variation in the path -2002 /// MTU estimate. The peer can also enforce an arbitrarily small fixed limit, but if the -2003 /// peer's limit is large this is guaranteed to be a little over a kilobyte at minimum. -2004 /// -2005 /// Not necessarily the maximum size of received datagrams. -2006 /// -2007 /// [`send_datagram`]: Self::send_datagram -2008 #[inline] -2009 pub fn max_datagram_size(&self) -> Option<usize> { -2010 self.inner.max_datagram_size() -2011 } -2012 -2013 /// Bytes available in the outgoing datagram buffer. -2014 /// -2015 /// When greater than zero, calling [`send_datagram`] with a -2016 /// datagram of at most this size is guaranteed not to cause older datagrams to be -2017 /// dropped. -2018 /// -2019 /// [`send_datagram`]: Self::send_datagram -2020 #[inline] -2021 pub fn datagram_send_buffer_space(&self) -> usize { -2022 self.inner.datagram_send_buffer_space() -2023 } -2024 -2025 /// Current best estimate of this connection's latency (round-trip-time). -2026 #[inline] -2027 pub fn rtt(&self) -> Duration { -2028 self.inner.rtt() -2029 } -2030 -2031 /// Returns connection statistics. -2032 #[inline] -2033 pub fn stats(&self) -> ConnectionStats { -2034 self.inner.stats() -2035 } -2036 -2037 /// Current state of the congestion control algorithm, for debugging purposes. -2038 #[inline] -2039 pub fn congestion_state(&self) -> Box<dyn quinn_proto::congestion::Controller> { -2040 self.inner.congestion_state() -2041 } -2042 -2043 /// Parameters negotiated during the handshake. -2044 /// -2045 /// Guaranteed to return `Some` on fully established connections or after -2046 /// [`Connecting::handshake_data()`] succeeds. See that method's documentations for -2047 /// details on the returned value. -2048 /// -2049 /// [`Connection::handshake_data()`]: crate::endpoint::Connecting::handshake_data -2050 #[inline] -2051 pub fn handshake_data(&self) -> Option<Box<dyn Any>> { -2052 self.inner.handshake_data() -2053 } -2054 -2055 /// Extracts the ALPN protocol from the peer's handshake data. -2056 pub fn alpn(&self) -> Option<Vec<u8>> { -2057 let data = self.handshake_data()?; -2058 match data.downcast::<quinn::crypto::rustls::HandshakeData>() { -2059 Ok(data) => data.protocol, -2060 Err(_) => None, -2061 } -2062 } -2063 -2064 /// Cryptographic identity of the peer. -2065 /// -2066 /// The dynamic type returned is determined by the configured [`Session`]. For the -2067 /// default `rustls` session, the return value can be [`downcast`] to a -2068 /// <code>Vec<[rustls::pki_types::CertificateDer]></code> -2069 /// -2070 /// [`Session`]: quinn_proto::crypto::Session -2071 /// [`downcast`]: Box::downcast -2072 #[inline] -2073 pub fn peer_identity(&self) -> Option<Box<dyn Any>> { -2074 self.inner.peer_identity() -2075 } -2076 -2077 /// Returns the [`NodeId`] from the peer's TLS certificate. -2078 /// -2079 /// The [`PublicKey`] of a node is also known as a [`NodeId`]. This [`PublicKey`] is -2080 /// included in the TLS certificate presented during the handshake when connecting. -2081 /// This function allows you to get the [`NodeId`] of the remote node of this -2082 /// connection. -2083 /// -2084 /// [`PublicKey`]: iroh_base::PublicKey -2085 // TODO: Would be nice if this could be infallible. -2086 pub fn remote_node_id(&self) -> Result<NodeId, RemoteNodeIdError> { -2087 let data = self.peer_identity(); -2088 match data { -2089 None => { -2090 warn!("no peer certificate found"); -2091 Err(RemoteNodeIdSnafu.build()) -2092 } -2093 Some(data) => match data.downcast::<Vec<rustls::pki_types::CertificateDer>>() { -2094 Ok(certs) => { -2095 if certs.len() != 1 { -2096 warn!( -2097 "expected a single peer certificate, but {} found", -2098 certs.len() -2099 ); -2100 return Err(RemoteNodeIdSnafu.build()); -2101 } -2102 -2103 let peer_id = VerifyingKey::from_public_key_der(&certs[0]) -2104 .map_err(|_| RemoteNodeIdSnafu.build())? -2105 .into(); -2106 Ok(peer_id) -2107 } -2108 Err(err) => { -2109 warn!("invalid peer certificate: {:?}", err); -2110 Err(RemoteNodeIdSnafu.build()) -2111 } -2112 }, -2113 } -2114 } -2115 -2116 /// A stable identifier for this connection. -2117 /// -2118 /// Peer addresses and connection IDs can change, but this value will remain fixed for -2119 /// the lifetime of the connection. -2120 #[inline] -2121 pub fn stable_id(&self) -> usize { -2122 self.inner.stable_id() -2123 } -2124 -2125 /// Derives keying material from this connection's TLS session secrets. -2126 /// -2127 /// When both peers call this method with the same `label` and `context` -2128 /// arguments and `output` buffers of equal length, they will get the -2129 /// same sequence of bytes in `output`. These bytes are cryptographically -2130 /// strong and pseudorandom, and are suitable for use as keying material. -2131 /// -2132 /// See [RFC5705](https://tools.ietf.org/html/rfc5705) for more information. +1999 /// [`send_datagram`]: Self::send_datagram +2000 #[inline] +2001 pub fn datagram_send_buffer_space(&self) -> usize { +2002 self.inner.datagram_send_buffer_space() +2003 } +2004 +2005 /// Current best estimate of this connection's latency (round-trip-time). +2006 #[inline] +2007 pub fn rtt(&self) -> Duration { +2008 self.inner.rtt() +2009 } +2010 +2011 /// Returns connection statistics. +2012 #[inline] +2013 pub fn stats(&self) -> ConnectionStats { +2014 self.inner.stats() +2015 } +2016 +2017 /// Current state of the congestion control algorithm, for debugging purposes. +2018 #[inline] +2019 pub fn congestion_state(&self) -> Box<dyn quinn_proto::congestion::Controller> { +2020 self.inner.congestion_state() +2021 } +2022 +2023 /// Parameters negotiated during the handshake. +2024 /// +2025 /// Guaranteed to return `Some` on fully established connections or after +2026 /// [`Connecting::handshake_data()`] succeeds. See that method's documentations for +2027 /// details on the returned value. +2028 /// +2029 /// [`Connection::handshake_data()`]: crate::endpoint::Connecting::handshake_data +2030 #[inline] +2031 pub fn handshake_data(&self) -> Option<Box<dyn Any>> { +2032 self.inner.handshake_data() +2033 } +2034 +2035 /// Extracts the ALPN protocol from the peer's handshake data. +2036 pub fn alpn(&self) -> Option<Vec<u8>> { +2037 let data = self.handshake_data()?; +2038 match data.downcast::<quinn::crypto::rustls::HandshakeData>() { +2039 Ok(data) => data.protocol, +2040 Err(_) => None, +2041 } +2042 } +2043 +2044 /// Cryptographic identity of the peer. +2045 /// +2046 /// The dynamic type returned is determined by the configured [`Session`]. For the +2047 /// default `rustls` session, the return value can be [`downcast`] to a +2048 /// <code>Vec<[rustls::pki_types::CertificateDer]></code> +2049 /// +2050 /// [`Session`]: quinn_proto::crypto::Session +2051 /// [`downcast`]: Box::downcast +2052 #[inline] +2053 pub fn peer_identity(&self) -> Option<Box<dyn Any>> { +2054 self.inner.peer_identity() +2055 } +2056 +2057 /// Returns the [`NodeId`] from the peer's TLS certificate. +2058 /// +2059 /// The [`PublicKey`] of a node is also known as a [`NodeId`]. This [`PublicKey`] is +2060 /// included in the TLS certificate presented during the handshake when connecting. +2061 /// This function allows you to get the [`NodeId`] of the remote node of this +2062 /// connection. +2063 /// +2064 /// [`PublicKey`]: iroh_base::PublicKey +2065 // TODO: Would be nice if this could be infallible. +2066 pub fn remote_node_id(&self) -> Result<NodeId, RemoteNodeIdError> { +2067 let data = self.peer_identity(); +2068 match data { +2069 None => { +2070 warn!("no peer certificate found"); +2071 Err(RemoteNodeIdSnafu.build()) +2072 } +2073 Some(data) => match data.downcast::<Vec<rustls::pki_types::CertificateDer>>() { +2074 Ok(certs) => { +2075 if certs.len() != 1 { +2076 warn!( +2077 "expected a single peer certificate, but {} found", +2078 certs.len() +2079 ); +2080 return Err(RemoteNodeIdSnafu.build()); +2081 } +2082 +2083 let peer_id = VerifyingKey::from_public_key_der(&certs[0]) +2084 .map_err(|_| RemoteNodeIdSnafu.build())? +2085 .into(); +2086 Ok(peer_id) +2087 } +2088 Err(err) => { +2089 warn!("invalid peer certificate: {:?}", err); +2090 Err(RemoteNodeIdSnafu.build()) +2091 } +2092 }, +2093 } +2094 } +2095 +2096 /// A stable identifier for this connection. +2097 /// +2098 /// Peer addresses and connection IDs can change, but this value will remain fixed for +2099 /// the lifetime of the connection. +2100 #[inline] +2101 pub fn stable_id(&self) -> usize { +2102 self.inner.stable_id() +2103 } +2104 +2105 /// Derives keying material from this connection's TLS session secrets. +2106 /// +2107 /// When both peers call this method with the same `label` and `context` +2108 /// arguments and `output` buffers of equal length, they will get the +2109 /// same sequence of bytes in `output`. These bytes are cryptographically +2110 /// strong and pseudorandom, and are suitable for use as keying material. +2111 /// +2112 /// See [RFC5705](https://tools.ietf.org/html/rfc5705) for more information. +2113 #[inline] +2114 pub fn export_keying_material( +2115 &self, +2116 output: &mut [u8], +2117 label: &[u8], +2118 context: &[u8], +2119 ) -> Result<(), quinn_proto::crypto::ExportKeyingMaterialError> { +2120 self.inner.export_keying_material(output, label, context) +2121 } +2122 +2123 /// Modifies the number of unidirectional streams that may be concurrently opened. +2124 /// +2125 /// No streams may be opened by the peer unless fewer than `count` are already +2126 /// open. Large `count`s increase both minimum and worst-case memory consumption. +2127 #[inline] +2128 pub fn set_max_concurrent_uni_streams(&self, count: VarInt) { +2129 self.inner.set_max_concurrent_uni_streams(count) +2130 } +2131 +2132 /// See [`quinn_proto::TransportConfig::receive_window`]. 2133 #[inline] -2134 pub fn export_keying_material( -2135 &self, -2136 output: &mut [u8], -2137 label: &[u8], -2138 context: &[u8], -2139 ) -> Result<(), quinn_proto::crypto::ExportKeyingMaterialError> { -2140 self.inner.export_keying_material(output, label, context) -2141 } -2142 -2143 /// Modifies the number of unidirectional streams that may be concurrently opened. -2144 /// -2145 /// No streams may be opened by the peer unless fewer than `count` are already -2146 /// open. Large `count`s increase both minimum and worst-case memory consumption. -2147 #[inline] -2148 pub fn set_max_concurrent_uni_streams(&self, count: VarInt) { -2149 self.inner.set_max_concurrent_uni_streams(count) -2150 } -2151 -2152 /// See [`quinn_proto::TransportConfig::receive_window`]. -2153 #[inline] -2154 pub fn set_receive_window(&self, receive_window: VarInt) { -2155 self.inner.set_receive_window(receive_window) -2156 } -2157 -2158 /// Modifies the number of bidirectional streams that may be concurrently opened. -2159 /// -2160 /// No streams may be opened by the peer unless fewer than `count` are already -2161 /// open. Large `count`s increase both minimum and worst-case memory consumption. -2162 #[inline] -2163 pub fn set_max_concurrent_bi_streams(&self, count: VarInt) { -2164 self.inner.set_max_concurrent_bi_streams(count) -2165 } -2166} -2167 -2168/// Try send a message to the rtt-actor. -2169/// -2170/// If we can't notify the actor that will impact performance a little, but we can still -2171/// function. -2172fn try_send_rtt_msg(conn: &Connection, magic_ep: &Endpoint, remote_node_id: Option<NodeId>) { -2173 // If we can't notify the rtt-actor that's not great but not critical. -2174 let Some(node_id) = remote_node_id.or_else(|| conn.remote_node_id().ok()) else { -2175 warn!(?conn, "failed to get remote node id"); -2176 return; -2177 }; -2178 let Some(conn_type_changes) = magic_ep.conn_type(node_id) else { -2179 warn!(?conn, "failed to create conn_type stream"); -2180 return; -2181 }; -2182 let rtt_msg = RttMessage::NewConnection { -2183 connection: conn.inner.weak_handle(), -2184 conn_type_changes: conn_type_changes.stream(), -2185 node_id, -2186 }; -2187 if let Err(err) = magic_ep.rtt_actor.msg_tx.try_send(rtt_msg) { -2188 warn!(?conn, "rtt-actor not reachable: {err:#}"); -2189 } -2190} -2191 -2192/// Read a proxy url from the environment, in this order -2193/// -2194/// - `HTTP_PROXY` -2195/// - `http_proxy` -2196/// - `HTTPS_PROXY` -2197/// - `https_proxy` -2198fn proxy_url_from_env() -> Option<Url> { -2199 if let Some(url) = std::env::var("HTTP_PROXY") -2200 .ok() -2201 .and_then(|s| s.parse::<Url>().ok()) -2202 { -2203 if is_cgi() { -2204 warn!("HTTP_PROXY environment variable ignored in CGI"); -2205 } else { -2206 return Some(url); -2207 } -2208 } -2209 if let Some(url) = std::env::var("http_proxy") -2210 .ok() -2211 .and_then(|s| s.parse::<Url>().ok()) -2212 { -2213 return Some(url); -2214 } -2215 if let Some(url) = std::env::var("HTTPS_PROXY") -2216 .ok() -2217 .and_then(|s| s.parse::<Url>().ok()) -2218 { -2219 return Some(url); -2220 } -2221 if let Some(url) = std::env::var("https_proxy") -2222 .ok() -2223 .and_then(|s| s.parse::<Url>().ok()) -2224 { -2225 return Some(url); -2226 } -2227 -2228 None -2229} -2230 -2231/// Configuration of the relay servers for an [`Endpoint`]. -2232#[derive(Debug, Clone, PartialEq, Eq)] -2233pub enum RelayMode { -2234 /// Disable relay servers completely. -2235 Disabled, -2236 /// Use the default relay map, with production relay servers from n0. -2237 /// -2238 /// See [`crate::defaults::prod`] for the severs used. -2239 Default, -2240 /// Use the staging relay servers from n0. -2241 Staging, -2242 /// Use a custom relay map. -2243 Custom(RelayMap), +2134 pub fn set_receive_window(&self, receive_window: VarInt) { +2135 self.inner.set_receive_window(receive_window) +2136 } +2137 +2138 /// Modifies the number of bidirectional streams that may be concurrently opened. +2139 /// +2140 /// No streams may be opened by the peer unless fewer than `count` are already +2141 /// open. Large `count`s increase both minimum and worst-case memory consumption. +2142 #[inline] +2143 pub fn set_max_concurrent_bi_streams(&self, count: VarInt) { +2144 self.inner.set_max_concurrent_bi_streams(count) +2145 } +2146} +2147 +2148/// Try send a message to the rtt-actor. +2149/// +2150/// If we can't notify the actor that will impact performance a little, but we can still +2151/// function. +2152fn try_send_rtt_msg(conn: &Connection, magic_ep: &Endpoint, remote_node_id: Option<NodeId>) { +2153 // If we can't notify the rtt-actor that's not great but not critical. +2154 let Some(node_id) = remote_node_id.or_else(|| conn.remote_node_id().ok()) else { +2155 warn!(?conn, "failed to get remote node id"); +2156 return; +2157 }; +2158 let Some(conn_type_changes) = magic_ep.conn_type(node_id) else { +2159 warn!(?conn, "failed to create conn_type stream"); +2160 return; +2161 }; +2162 let rtt_msg = RttMessage::NewConnection { +2163 connection: conn.inner.weak_handle(), +2164 conn_type_changes: conn_type_changes.stream(), +2165 node_id, +2166 }; +2167 if let Err(err) = magic_ep.rtt_actor.msg_tx.try_send(rtt_msg) { +2168 warn!(?conn, "rtt-actor not reachable: {err:#}"); +2169 } +2170} +2171 +2172/// Read a proxy url from the environment, in this order +2173/// +2174/// - `HTTP_PROXY` +2175/// - `http_proxy` +2176/// - `HTTPS_PROXY` +2177/// - `https_proxy` +2178fn proxy_url_from_env() -> Option<Url> { +2179 if let Some(url) = std::env::var("HTTP_PROXY") +2180 .ok() +2181 .and_then(|s| s.parse::<Url>().ok()) +2182 { +2183 if is_cgi() { +2184 warn!("HTTP_PROXY environment variable ignored in CGI"); +2185 } else { +2186 return Some(url); +2187 } +2188 } +2189 if let Some(url) = std::env::var("http_proxy") +2190 .ok() +2191 .and_then(|s| s.parse::<Url>().ok()) +2192 { +2193 return Some(url); +2194 } +2195 if let Some(url) = std::env::var("HTTPS_PROXY") +2196 .ok() +2197 .and_then(|s| s.parse::<Url>().ok()) +2198 { +2199 return Some(url); +2200 } +2201 if let Some(url) = std::env::var("https_proxy") +2202 .ok() +2203 .and_then(|s| s.parse::<Url>().ok()) +2204 { +2205 return Some(url); +2206 } +2207 +2208 None +2209} +2210 +2211/// Configuration of the relay servers for an [`Endpoint`]. +2212#[derive(Debug, Clone, PartialEq, Eq)] +2213pub enum RelayMode { +2214 /// Disable relay servers completely. +2215 Disabled, +2216 /// Use the default relay map, with production relay servers from n0. +2217 /// +2218 /// See [`crate::defaults::prod`] for the severs used. +2219 Default, +2220 /// Use the staging relay servers from n0. +2221 Staging, +2222 /// Use a custom relay map. +2223 Custom(RelayMap), +2224} +2225 +2226impl RelayMode { +2227 /// Returns the relay map for this mode. +2228 pub fn relay_map(&self) -> RelayMap { +2229 match self { +2230 RelayMode::Disabled => RelayMap::empty(), +2231 RelayMode::Default => crate::defaults::prod::default_relay_map(), +2232 RelayMode::Staging => crate::defaults::staging::default_relay_map(), +2233 RelayMode::Custom(relay_map) => relay_map.clone(), +2234 } +2235 } +2236} +2237 +2238/// Environment variable to force the use of staging relays. +2239pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS"; +2240 +2241/// Returns `true` if the use of staging relays is forced. +2242pub fn force_staging_infra() -> bool { +2243 matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty()) 2244} 2245 -2246impl RelayMode { -2247 /// Returns the relay map for this mode. -2248 pub fn relay_map(&self) -> RelayMap { -2249 match self { -2250 RelayMode::Disabled => RelayMap::empty(), -2251 RelayMode::Default => crate::defaults::prod::default_relay_map(), -2252 RelayMode::Staging => crate::defaults::staging::default_relay_map(), -2253 RelayMode::Custom(relay_map) => relay_map.clone(), -2254 } +2246/// Returns the default relay mode. +2247/// +2248/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`. +2249/// Otherwise, it will return `RelayMode::Default`. +2250pub fn default_relay_mode() -> RelayMode { +2251 // Use staging in testing +2252 match force_staging_infra() { +2253 true => RelayMode::Staging, +2254 false => RelayMode::Default, 2255 } 2256} 2257 -2258/// Environment variable to force the use of staging relays. -2259pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS"; -2260 -2261/// Returns `true` if the use of staging relays is forced. -2262pub fn force_staging_infra() -> bool { -2263 matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty()) +2258/// Check if we are being executed in a CGI context. +2259/// +2260/// If so, a malicious client can send the `Proxy:` header, and it will +2261/// be in the `HTTP_PROXY` env var. So we don't use it :) +2262fn is_cgi() -> bool { +2263 std::env::var_os("REQUEST_METHOD").is_some() 2264} 2265 -2266/// Returns the default relay mode. -2267/// -2268/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`. -2269/// Otherwise, it will return `RelayMode::Default`. -2270pub fn default_relay_mode() -> RelayMode { -2271 // Use staging in testing -2272 match force_staging_infra() { -2273 true => RelayMode::Staging, -2274 false => RelayMode::Default, -2275 } -2276} -2277 -2278/// Check if we are being executed in a CGI context. -2279/// -2280/// If so, a malicious client can send the `Proxy:` header, and it will -2281/// be in the `HTTP_PROXY` env var. So we don't use it :) -2282fn is_cgi() -> bool { -2283 std::env::var_os("REQUEST_METHOD").is_some() -2284} -2285 -2286// TODO: These tests could still be flaky, lets fix that: -2287// https://github.com/n0-computer/iroh/issues/1183 -2288#[cfg(test)] -2289mod tests { -2290 use std::{ -2291 net::SocketAddr, -2292 time::{Duration, Instant}, -2293 }; -2294 -2295 use iroh_base::{NodeAddr, NodeId, SecretKey}; -2296 use iroh_relay::http::Protocol; -2297 use n0_future::{task::AbortOnDropHandle, StreamExt}; -2298 use n0_snafu::{Error, Result, ResultExt}; -2299 use quinn::ConnectionError; -2300 use rand::SeedableRng; -2301 use tracing::{error_span, info, info_span, Instrument}; -2302 use tracing_test::traced_test; -2303 -2304 use super::Endpoint; -2305 use crate::{ -2306 endpoint::{ConnectOptions, Connection, ConnectionType, RemoteInfo}, -2307 test_utils::{run_relay_server, run_relay_server_with}, -2308 watcher::Watcher, -2309 RelayMode, -2310 }; -2311 -2312 const TEST_ALPN: &[u8] = b"n0/iroh/test"; -2313 -2314 #[tokio::test] -2315 #[traced_test] -2316 async fn test_connect_self() -> Result { -2317 let ep = Endpoint::builder() -2318 .alpns(vec![TEST_ALPN.to_vec()]) -2319 .bind() -2320 .await -2321 .unwrap(); -2322 let my_addr = ep.node_addr().initialized().await.unwrap(); -2323 let res = ep.connect(my_addr.clone(), TEST_ALPN).await; -2324 assert!(res.is_err()); -2325 let err = res.err().unwrap(); -2326 assert!(err.to_string().starts_with("Connecting to ourself")); -2327 -2328 let res = ep.add_node_addr(my_addr); -2329 assert!(res.is_err()); -2330 let err = res.err().unwrap(); -2331 assert!(err.to_string().starts_with("Adding our own address")); -2332 Ok(()) -2333 } -2334 -2335 #[tokio::test] -2336 #[traced_test] -2337 async fn endpoint_connect_close() -> Result { -2338 let (relay_map, relay_url, _guard) = run_relay_server().await?; -2339 let server_secret_key = SecretKey::generate(rand::thread_rng()); -2340 let server_peer_id = server_secret_key.public(); -2341 -2342 let server = { -2343 let relay_map = relay_map.clone(); -2344 tokio::spawn( -2345 async move { -2346 let ep = Endpoint::builder() -2347 .secret_key(server_secret_key) -2348 .alpns(vec![TEST_ALPN.to_vec()]) -2349 .relay_mode(RelayMode::Custom(relay_map)) -2350 .insecure_skip_relay_cert_verify(true) -2351 .bind() -2352 .await?; -2353 info!("accepting connection"); -2354 let incoming = ep.accept().await.e()?; -2355 let conn = incoming.await.e()?; -2356 let mut stream = conn.accept_uni().await.e()?; -2357 let mut buf = [0u8; 5]; -2358 stream.read_exact(&mut buf).await.e()?; -2359 info!("Accepted 1 stream, received {buf:?}. Closing now."); -2360 // close the connection -2361 conn.close(7u8.into(), b"bye"); -2362 -2363 let res = conn.accept_uni().await; -2364 assert_eq!(res.unwrap_err(), quinn::ConnectionError::LocallyClosed); -2365 -2366 let res = stream.read_to_end(10).await; -2367 assert_eq!( -2368 res.unwrap_err(), -2369 quinn::ReadToEndError::Read(quinn::ReadError::ConnectionLost( -2370 quinn::ConnectionError::LocallyClosed -2371 )) -2372 ); -2373 info!("server test completed"); -2374 Ok::<_, Error>(()) -2375 } -2376 .instrument(info_span!("test-server")), -2377 ) -2378 }; -2379 -2380 let client = tokio::spawn( -2381 async move { -2382 let ep = Endpoint::builder() -2383 .alpns(vec![TEST_ALPN.to_vec()]) -2384 .relay_mode(RelayMode::Custom(relay_map)) -2385 .insecure_skip_relay_cert_verify(true) -2386 .bind() -2387 .await?; -2388 info!("client connecting"); -2389 let node_addr = NodeAddr::new(server_peer_id).with_relay_url(relay_url); -2390 let conn = ep.connect(node_addr, TEST_ALPN).await?; -2391 let mut stream = conn.open_uni().await.e()?; -2392 -2393 // First write is accepted by server. We need this bit of synchronisation -2394 // because if the server closes after simply accepting the connection we can -2395 // not be sure our .open_uni() call would succeed as it may already receive -2396 // the error. -2397 stream.write_all(b"hello").await.e()?; -2398 -2399 info!("waiting for closed"); -2400 // Remote now closes the connection, we should see an error sometime soon. -2401 let err = conn.closed().await; -2402 let expected_err = -2403 quinn::ConnectionError::ApplicationClosed(quinn::ApplicationClose { -2404 error_code: 7u8.into(), -2405 reason: b"bye".to_vec().into(), -2406 }); -2407 assert_eq!(err, expected_err); +2266// TODO: These tests could still be flaky, lets fix that: +2267// https://github.com/n0-computer/iroh/issues/1183 +2268#[cfg(test)] +2269mod tests { +2270 use std::{ +2271 net::SocketAddr, +2272 time::{Duration, Instant}, +2273 }; +2274 +2275 use iroh_base::{NodeAddr, NodeId, SecretKey}; +2276 use iroh_relay::http::Protocol; +2277 use n0_future::{task::AbortOnDropHandle, StreamExt}; +2278 use n0_snafu::{Error, Result, ResultExt}; +2279 use n0_watcher::Watcher; +2280 use quinn::ConnectionError; +2281 use rand::SeedableRng; +2282 use tracing::{error_span, info, info_span, Instrument}; +2283 use tracing_test::traced_test; +2284 +2285 use super::Endpoint; +2286 use crate::{ +2287 endpoint::{ConnectOptions, Connection, ConnectionType, RemoteInfo}, +2288 test_utils::{run_relay_server, run_relay_server_with}, +2289 RelayMode, +2290 }; +2291 +2292 const TEST_ALPN: &[u8] = b"n0/iroh/test"; +2293 +2294 #[tokio::test] +2295 #[traced_test] +2296 async fn test_connect_self() -> Result { +2297 let ep = Endpoint::builder() +2298 .alpns(vec![TEST_ALPN.to_vec()]) +2299 .bind() +2300 .await +2301 .unwrap(); +2302 let my_addr = ep.node_addr().initialized().await.unwrap(); +2303 let res = ep.connect(my_addr.clone(), TEST_ALPN).await; +2304 assert!(res.is_err()); +2305 let err = res.err().unwrap(); +2306 assert!(err.to_string().starts_with("Connecting to ourself")); +2307 +2308 let res = ep.add_node_addr(my_addr); +2309 assert!(res.is_err()); +2310 let err = res.err().unwrap(); +2311 assert!(err.to_string().starts_with("Adding our own address")); +2312 Ok(()) +2313 } +2314 +2315 #[tokio::test] +2316 #[traced_test] +2317 async fn endpoint_connect_close() -> Result { +2318 let (relay_map, relay_url, _guard) = run_relay_server().await?; +2319 let server_secret_key = SecretKey::generate(rand::thread_rng()); +2320 let server_peer_id = server_secret_key.public(); +2321 +2322 let server = { +2323 let relay_map = relay_map.clone(); +2324 tokio::spawn( +2325 async move { +2326 let ep = Endpoint::builder() +2327 .secret_key(server_secret_key) +2328 .alpns(vec![TEST_ALPN.to_vec()]) +2329 .relay_mode(RelayMode::Custom(relay_map)) +2330 .insecure_skip_relay_cert_verify(true) +2331 .bind() +2332 .await?; +2333 info!("accepting connection"); +2334 let incoming = ep.accept().await.e()?; +2335 let conn = incoming.await.e()?; +2336 let mut stream = conn.accept_uni().await.e()?; +2337 let mut buf = [0u8; 5]; +2338 stream.read_exact(&mut buf).await.e()?; +2339 info!("Accepted 1 stream, received {buf:?}. Closing now."); +2340 // close the connection +2341 conn.close(7u8.into(), b"bye"); +2342 +2343 let res = conn.accept_uni().await; +2344 assert_eq!(res.unwrap_err(), quinn::ConnectionError::LocallyClosed); +2345 +2346 let res = stream.read_to_end(10).await; +2347 assert_eq!( +2348 res.unwrap_err(), +2349 quinn::ReadToEndError::Read(quinn::ReadError::ConnectionLost( +2350 quinn::ConnectionError::LocallyClosed +2351 )) +2352 ); +2353 info!("server test completed"); +2354 Ok::<_, Error>(()) +2355 } +2356 .instrument(info_span!("test-server")), +2357 ) +2358 }; +2359 +2360 let client = tokio::spawn( +2361 async move { +2362 let ep = Endpoint::builder() +2363 .alpns(vec![TEST_ALPN.to_vec()]) +2364 .relay_mode(RelayMode::Custom(relay_map)) +2365 .insecure_skip_relay_cert_verify(true) +2366 .bind() +2367 .await?; +2368 info!("client connecting"); +2369 let node_addr = NodeAddr::new(server_peer_id).with_relay_url(relay_url); +2370 let conn = ep.connect(node_addr, TEST_ALPN).await?; +2371 let mut stream = conn.open_uni().await.e()?; +2372 +2373 // First write is accepted by server. We need this bit of synchronisation +2374 // because if the server closes after simply accepting the connection we can +2375 // not be sure our .open_uni() call would succeed as it may already receive +2376 // the error. +2377 stream.write_all(b"hello").await.e()?; +2378 +2379 info!("waiting for closed"); +2380 // Remote now closes the connection, we should see an error sometime soon. +2381 let err = conn.closed().await; +2382 let expected_err = +2383 quinn::ConnectionError::ApplicationClosed(quinn::ApplicationClose { +2384 error_code: 7u8.into(), +2385 reason: b"bye".to_vec().into(), +2386 }); +2387 assert_eq!(err, expected_err); +2388 +2389 info!("opening new - expect it to fail"); +2390 let res = conn.open_uni().await; +2391 assert_eq!(res.unwrap_err(), expected_err); +2392 info!("client test completed"); +2393 Ok::<_, Error>(()) +2394 } +2395 .instrument(info_span!("test-client")), +2396 ); +2397 +2398 let (server, client) = tokio::time::timeout( +2399 Duration::from_secs(30), +2400 n0_future::future::zip(server, client), +2401 ) +2402 .await +2403 .e()?; +2404 server.e()??; +2405 client.e()??; +2406 Ok(()) +2407 } 2408 -2409 info!("opening new - expect it to fail"); -2410 let res = conn.open_uni().await; -2411 assert_eq!(res.unwrap_err(), expected_err); -2412 info!("client test completed"); -2413 Ok::<_, Error>(()) -2414 } -2415 .instrument(info_span!("test-client")), -2416 ); -2417 -2418 let (server, client) = tokio::time::timeout( -2419 Duration::from_secs(30), -2420 n0_future::future::zip(server, client), -2421 ) -2422 .await -2423 .e()?; -2424 server.e()??; -2425 client.e()??; -2426 Ok(()) -2427 } -2428 -2429 /// Test that peers are properly restored -2430 #[tokio::test] -2431 #[traced_test] -2432 async fn restore_peers() -> Result { -2433 let secret_key = SecretKey::generate(rand::thread_rng()); -2434 -2435 /// Create an endpoint for the test. -2436 async fn new_endpoint( -2437 secret_key: SecretKey, -2438 nodes: Option<Vec<NodeAddr>>, -2439 ) -> Result<Endpoint> { -2440 let mut transport_config = quinn::TransportConfig::default(); -2441 transport_config.max_idle_timeout(Some(Duration::from_secs(10).try_into().unwrap())); -2442 -2443 let mut builder = Endpoint::builder() -2444 .secret_key(secret_key.clone()) -2445 .transport_config(transport_config); -2446 if let Some(nodes) = nodes { -2447 builder = builder.known_nodes(nodes); -2448 } -2449 Ok(builder.alpns(vec![TEST_ALPN.to_vec()]).bind().await?) -2450 } -2451 -2452 // create the peer that will be added to the peer map -2453 let peer_id = SecretKey::generate(rand::thread_rng()).public(); -2454 let direct_addr: SocketAddr = -2455 (std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), 8758u16).into(); -2456 let node_addr = NodeAddr::new(peer_id).with_direct_addresses([direct_addr]); -2457 -2458 info!("setting up first endpoint"); -2459 // first time, create a magic endpoint without peers but a peers file and add addressing -2460 // information for a peer -2461 let endpoint = new_endpoint(secret_key.clone(), None).await?; -2462 assert_eq!(endpoint.remote_info_iter().count(), 0); -2463 endpoint.add_node_addr(node_addr.clone())?; -2464 -2465 // Grab the current addrs -2466 let node_addrs: Vec<NodeAddr> = endpoint.remote_info_iter().map(Into::into).collect(); -2467 assert_eq!(node_addrs.len(), 1); -2468 assert_eq!(node_addrs[0], node_addr); -2469 -2470 info!("closing endpoint"); -2471 // close the endpoint and restart it -2472 endpoint.close().await; -2473 -2474 info!("restarting endpoint"); -2475 // now restart it and check the addressing info of the peer -2476 let endpoint = new_endpoint(secret_key, Some(node_addrs)).await?; -2477 let RemoteInfo { mut addrs, .. } = endpoint.remote_info(peer_id).e()?; -2478 let conn_addr = addrs.pop().unwrap().addr; -2479 assert_eq!(conn_addr, direct_addr); -2480 Ok(()) -2481 } -2482 -2483 #[tokio::test] -2484 #[traced_test] -2485 async fn endpoint_relay_connect_loop() -> Result { -2486 let start = Instant::now(); -2487 let n_clients = 5; -2488 let n_chunks_per_client = 2; -2489 let chunk_size = 10; -2490 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42); -2491 let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap(); -2492 let server_secret_key = SecretKey::generate(&mut rng); -2493 let server_node_id = server_secret_key.public(); -2494 -2495 // The server accepts the connections of the clients sequentially. -2496 let server = { -2497 let relay_map = relay_map.clone(); -2498 tokio::spawn( -2499 async move { -2500 let ep = Endpoint::builder() -2501 .insecure_skip_relay_cert_verify(true) -2502 .secret_key(server_secret_key) -2503 .alpns(vec![TEST_ALPN.to_vec()]) -2504 .relay_mode(RelayMode::Custom(relay_map)) -2505 .bind() -2506 .await?; -2507 let eps = ep.bound_sockets(); -2508 info!(me = %ep.node_id().fmt_short(), ipv4=%eps.0, ipv6=?eps.1, "server listening on"); -2509 for i in 0..n_clients { -2510 let round_start = Instant::now(); -2511 info!("[server] round {i}"); -2512 let incoming = ep.accept().await.e()?; -2513 let conn = incoming.await.e()?; -2514 let node_id = conn.remote_node_id()?; -2515 info!(%i, peer = %node_id.fmt_short(), "accepted connection"); -2516 let (mut send, mut recv) = conn.accept_bi().await.e()?; -2517 let mut buf = vec![0u8; chunk_size]; -2518 for _i in 0..n_chunks_per_client { -2519 recv.read_exact(&mut buf).await.e()?; -2520 send.write_all(&buf).await.e()?; -2521 } -2522 send.finish().e()?; -2523 send.stopped().await.e()?; -2524 recv.read_to_end(0).await.e()?; -2525 info!(%i, peer = %node_id.fmt_short(), "finished"); -2526 info!("[server] round {i} done in {:?}", round_start.elapsed()); -2527 } -2528 Ok::<_, Error>(()) -2529 } -2530 .instrument(error_span!("server")), -2531 ) -2532 }; -2533 -2534 for i in 0..n_clients { -2535 let round_start = Instant::now(); -2536 info!("[client] round {}", i); -2537 let relay_map = relay_map.clone(); -2538 let client_secret_key = SecretKey::generate(&mut rng); -2539 let relay_url = relay_url.clone(); -2540 async { -2541 info!("client binding"); -2542 let ep = Endpoint::builder() -2543 .alpns(vec![TEST_ALPN.to_vec()]) -2544 .insecure_skip_relay_cert_verify(true) -2545 .relay_mode(RelayMode::Custom(relay_map)) -2546 .secret_key(client_secret_key) -2547 .bind() -2548 .await?; -2549 let eps = ep.bound_sockets(); -2550 info!(me = %ep.node_id().fmt_short(), ipv4=%eps.0, ipv6=?eps.1, "client bound"); -2551 let node_addr = NodeAddr::new(server_node_id).with_relay_url(relay_url); -2552 info!(to = ?node_addr, "client connecting"); -2553 let conn = ep.connect(node_addr, TEST_ALPN).await.e()?; -2554 info!("client connected"); -2555 let (mut send, mut recv) = conn.open_bi().await.e()?; -2556 -2557 for i in 0..n_chunks_per_client { -2558 let mut buf = vec![i; chunk_size]; -2559 send.write_all(&buf).await.e()?; -2560 recv.read_exact(&mut buf).await.e()?; -2561 assert_eq!(buf, vec![i; chunk_size]); -2562 } -2563 send.finish().e()?; -2564 send.stopped().await.e()?; -2565 recv.read_to_end(0).await.e()?; -2566 info!("client finished"); -2567 ep.close().await; -2568 info!("client closed"); -2569 Ok::<_, Error>(()) -2570 } -2571 .instrument(error_span!("client", %i)) -2572 .await?; -2573 info!("[client] round {i} done in {:?}", round_start.elapsed()); -2574 } -2575 -2576 server.await.e()??; -2577 -2578 // We appear to have seen this being very slow at times. So ensure we fail if this -2579 // test is too slow. We're only making two connections transferring very little -2580 // data, this really shouldn't take long. -2581 if start.elapsed() > Duration::from_secs(15) { -2582 panic!("Test too slow, something went wrong"); -2583 } -2584 -2585 Ok(()) -2586 } +2409 /// Test that peers are properly restored +2410 #[tokio::test] +2411 #[traced_test] +2412 async fn restore_peers() -> Result { +2413 let secret_key = SecretKey::generate(rand::thread_rng()); +2414 +2415 /// Create an endpoint for the test. +2416 async fn new_endpoint( +2417 secret_key: SecretKey, +2418 nodes: Option<Vec<NodeAddr>>, +2419 ) -> Result<Endpoint> { +2420 let mut transport_config = quinn::TransportConfig::default(); +2421 transport_config.max_idle_timeout(Some(Duration::from_secs(10).try_into().unwrap())); +2422 +2423 let mut builder = Endpoint::builder() +2424 .secret_key(secret_key.clone()) +2425 .transport_config(transport_config); +2426 if let Some(nodes) = nodes { +2427 builder = builder.known_nodes(nodes); +2428 } +2429 Ok(builder.alpns(vec![TEST_ALPN.to_vec()]).bind().await?) +2430 } +2431 +2432 // create the peer that will be added to the peer map +2433 let peer_id = SecretKey::generate(rand::thread_rng()).public(); +2434 let direct_addr: SocketAddr = +2435 (std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), 8758u16).into(); +2436 let node_addr = NodeAddr::new(peer_id).with_direct_addresses([direct_addr]); +2437 +2438 info!("setting up first endpoint"); +2439 // first time, create a magic endpoint without peers but a peers file and add addressing +2440 // information for a peer +2441 let endpoint = new_endpoint(secret_key.clone(), None).await?; +2442 assert_eq!(endpoint.remote_info_iter().count(), 0); +2443 endpoint.add_node_addr(node_addr.clone())?; +2444 +2445 // Grab the current addrs +2446 let node_addrs: Vec<NodeAddr> = endpoint.remote_info_iter().map(Into::into).collect(); +2447 assert_eq!(node_addrs.len(), 1); +2448 assert_eq!(node_addrs[0], node_addr); +2449 +2450 info!("closing endpoint"); +2451 // close the endpoint and restart it +2452 endpoint.close().await; +2453 +2454 info!("restarting endpoint"); +2455 // now restart it and check the addressing info of the peer +2456 let endpoint = new_endpoint(secret_key, Some(node_addrs)).await?; +2457 let RemoteInfo { mut addrs, .. } = endpoint.remote_info(peer_id).e()?; +2458 let conn_addr = addrs.pop().unwrap().addr; +2459 assert_eq!(conn_addr, direct_addr); +2460 Ok(()) +2461 } +2462 +2463 #[tokio::test] +2464 #[traced_test] +2465 async fn endpoint_relay_connect_loop() -> Result { +2466 let start = Instant::now(); +2467 let n_clients = 5; +2468 let n_chunks_per_client = 2; +2469 let chunk_size = 10; +2470 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42); +2471 let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap(); +2472 let server_secret_key = SecretKey::generate(&mut rng); +2473 let server_node_id = server_secret_key.public(); +2474 +2475 // The server accepts the connections of the clients sequentially. +2476 let server = { +2477 let relay_map = relay_map.clone(); +2478 tokio::spawn( +2479 async move { +2480 let ep = Endpoint::builder() +2481 .insecure_skip_relay_cert_verify(true) +2482 .secret_key(server_secret_key) +2483 .alpns(vec![TEST_ALPN.to_vec()]) +2484 .relay_mode(RelayMode::Custom(relay_map)) +2485 .bind() +2486 .await?; +2487 let eps = ep.bound_sockets(); +2488 +2489 info!(me = %ep.node_id().fmt_short(), eps = ?eps, "server listening on"); +2490 for i in 0..n_clients { +2491 let round_start = Instant::now(); +2492 info!("[server] round {i}"); +2493 let incoming = ep.accept().await.e()?; +2494 let conn = incoming.await.e()?; +2495 let node_id = conn.remote_node_id()?; +2496 info!(%i, peer = %node_id.fmt_short(), "accepted connection"); +2497 let (mut send, mut recv) = conn.accept_bi().await.e()?; +2498 let mut buf = vec![0u8; chunk_size]; +2499 for _i in 0..n_chunks_per_client { +2500 recv.read_exact(&mut buf).await.e()?; +2501 send.write_all(&buf).await.e()?; +2502 } +2503 send.finish().e()?; +2504 send.stopped().await.e()?; +2505 recv.read_to_end(0).await.e()?; +2506 info!(%i, peer = %node_id.fmt_short(), "finished"); +2507 info!("[server] round {i} done in {:?}", round_start.elapsed()); +2508 } +2509 Ok::<_, Error>(()) +2510 } +2511 .instrument(error_span!("server")), +2512 ) +2513 }; +2514 +2515 for i in 0..n_clients { +2516 let round_start = Instant::now(); +2517 info!("[client] round {}", i); +2518 let relay_map = relay_map.clone(); +2519 let client_secret_key = SecretKey::generate(&mut rng); +2520 let relay_url = relay_url.clone(); +2521 async { +2522 info!("client binding"); +2523 let ep = Endpoint::builder() +2524 .alpns(vec![TEST_ALPN.to_vec()]) +2525 .insecure_skip_relay_cert_verify(true) +2526 .relay_mode(RelayMode::Custom(relay_map)) +2527 .secret_key(client_secret_key) +2528 .bind() +2529 .await?; +2530 let eps = ep.bound_sockets(); +2531 +2532 info!(me = %ep.node_id().fmt_short(), eps=?eps, "client bound"); +2533 let node_addr = NodeAddr::new(server_node_id).with_relay_url(relay_url); +2534 info!(to = ?node_addr, "client connecting"); +2535 let conn = ep.connect(node_addr, TEST_ALPN).await.e()?; +2536 info!("client connected"); +2537 let (mut send, mut recv) = conn.open_bi().await.e()?; +2538 +2539 for i in 0..n_chunks_per_client { +2540 let mut buf = vec![i; chunk_size]; +2541 send.write_all(&buf).await.e()?; +2542 recv.read_exact(&mut buf).await.e()?; +2543 assert_eq!(buf, vec![i; chunk_size]); +2544 } +2545 send.finish().e()?; +2546 send.stopped().await.e()?; +2547 recv.read_to_end(0).await.e()?; +2548 info!("client finished"); +2549 ep.close().await; +2550 info!("client closed"); +2551 Ok::<_, Error>(()) +2552 } +2553 .instrument(error_span!("client", %i)) +2554 .await?; +2555 info!("[client] round {i} done in {:?}", round_start.elapsed()); +2556 } +2557 +2558 server.await.e()??; +2559 +2560 // We appear to have seen this being very slow at times. So ensure we fail if this +2561 // test is too slow. We're only making two connections transferring very little +2562 // data, this really shouldn't take long. +2563 if start.elapsed() > Duration::from_secs(15) { +2564 panic!("Test too slow, something went wrong"); +2565 } +2566 +2567 Ok(()) +2568 } +2569 +2570 #[tokio::test] +2571 #[traced_test] +2572 async fn endpoint_send_relay_websockets() -> Result { +2573 let (relay_map, _relay_url, _guard) = run_relay_server().await?; +2574 let client = Endpoint::builder() +2575 .relay_conn_protocol(Protocol::Websocket) +2576 .insecure_skip_relay_cert_verify(true) +2577 .relay_mode(RelayMode::Custom(relay_map.clone())) +2578 .bind() +2579 .await?; +2580 let server = Endpoint::builder() +2581 .relay_conn_protocol(Protocol::Websocket) +2582 .insecure_skip_relay_cert_verify(true) +2583 .relay_mode(RelayMode::Custom(relay_map)) +2584 .alpns(vec![TEST_ALPN.to_vec()]) +2585 .bind() +2586 .await?; 2587 -2588 #[tokio::test] -2589 #[traced_test] -2590 async fn endpoint_send_relay_websockets() -> Result { -2591 let (relay_map, _relay_url, _guard) = run_relay_server().await?; -2592 let client = Endpoint::builder() -2593 .relay_conn_protocol(Protocol::Websocket) -2594 .insecure_skip_relay_cert_verify(true) -2595 .relay_mode(RelayMode::Custom(relay_map.clone())) -2596 .bind() -2597 .await?; -2598 let server = Endpoint::builder() -2599 .relay_conn_protocol(Protocol::Websocket) -2600 .insecure_skip_relay_cert_verify(true) -2601 .relay_mode(RelayMode::Custom(relay_map)) -2602 .alpns(vec![TEST_ALPN.to_vec()]) -2603 .bind() -2604 .await?; -2605 -2606 let task = tokio::spawn({ -2607 let server = server.clone(); -2608 async move { -2609 let Some(conn) = server.accept().await else { -2610 snafu::whatever!("Expected an incoming connection"); -2611 }; -2612 let conn = conn.await.e()?; -2613 let (mut send, mut recv) = conn.accept_bi().await.e()?; -2614 let data = recv.read_to_end(1000).await.e()?; -2615 send.write_all(&data).await.e()?; -2616 send.finish().e()?; -2617 conn.closed().await; -2618 -2619 Ok::<_, Error>(()) -2620 } -2621 }); +2588 let task = tokio::spawn({ +2589 let server = server.clone(); +2590 async move { +2591 let Some(conn) = server.accept().await else { +2592 snafu::whatever!("Expected an incoming connection"); +2593 }; +2594 let conn = conn.await.e()?; +2595 let (mut send, mut recv) = conn.accept_bi().await.e()?; +2596 let data = recv.read_to_end(1000).await.e()?; +2597 send.write_all(&data).await.e()?; +2598 send.finish().e()?; +2599 conn.closed().await; +2600 +2601 Ok::<_, Error>(()) +2602 } +2603 }); +2604 +2605 let addr = server.node_addr().initialized().await?; +2606 let conn = client.connect(addr, TEST_ALPN).await?; +2607 let (mut send, mut recv) = conn.open_bi().await.e()?; +2608 send.write_all(b"Hello, world!").await.e()?; +2609 send.finish().e()?; +2610 let data = recv.read_to_end(1000).await.e()?; +2611 conn.close(0u32.into(), b"bye!"); +2612 +2613 task.await.e()??; +2614 +2615 client.close().await; +2616 server.close().await; +2617 +2618 assert_eq!(&data, b"Hello, world!"); +2619 +2620 Ok(()) +2621 } 2622 -2623 let addr = server.node_addr().initialized().await?; -2624 let conn = client.connect(addr, TEST_ALPN).await?; -2625 let (mut send, mut recv) = conn.open_bi().await.e()?; -2626 send.write_all(b"Hello, world!").await.e()?; -2627 send.finish().e()?; -2628 let data = recv.read_to_end(1000).await.e()?; -2629 conn.close(0u32.into(), b"bye!"); -2630 -2631 task.await.e()??; -2632 -2633 client.close().await; -2634 server.close().await; -2635 -2636 assert_eq!(&data, b"Hello, world!"); -2637 -2638 Ok(()) -2639 } -2640 -2641 #[tokio::test] -2642 #[traced_test] -2643 async fn endpoint_bidi_send_recv() -> Result { -2644 let ep1 = Endpoint::builder() -2645 .alpns(vec![TEST_ALPN.to_vec()]) -2646 .relay_mode(RelayMode::Disabled); -2647 -2648 let ep1 = ep1.bind().await?; -2649 let ep2 = Endpoint::builder() -2650 .alpns(vec![TEST_ALPN.to_vec()]) -2651 .relay_mode(RelayMode::Disabled); -2652 -2653 let ep2 = ep2.bind().await?; -2654 -2655 let ep1_nodeaddr = ep1.node_addr().initialized().await?; -2656 let ep2_nodeaddr = ep2.node_addr().initialized().await?; -2657 ep1.add_node_addr(ep2_nodeaddr.clone())?; -2658 ep2.add_node_addr(ep1_nodeaddr.clone())?; -2659 let ep1_nodeid = ep1.node_id(); -2660 let ep2_nodeid = ep2.node_id(); -2661 eprintln!("node id 1 {ep1_nodeid}"); -2662 eprintln!("node id 2 {ep2_nodeid}"); -2663 -2664 async fn connect_hello(ep: Endpoint, dst: NodeAddr) -> Result { -2665 let conn = ep.connect(dst, TEST_ALPN).await?; -2666 let (mut send, mut recv) = conn.open_bi().await.e()?; -2667 info!("sending hello"); -2668 send.write_all(b"hello").await.e()?; -2669 send.finish().e()?; -2670 info!("receiving world"); -2671 let m = recv.read_to_end(100).await.e()?; -2672 assert_eq!(m, b"world"); -2673 conn.close(1u8.into(), b"done"); -2674 Ok(()) -2675 } -2676 -2677 async fn accept_world(ep: Endpoint, src: NodeId) -> Result { -2678 let incoming = ep.accept().await.e()?; -2679 let mut iconn = incoming.accept().e()?; -2680 let alpn = iconn.alpn().await?; -2681 let conn = iconn.await.e()?; -2682 let node_id = conn.remote_node_id()?; -2683 assert_eq!(node_id, src); -2684 assert_eq!(alpn, TEST_ALPN); -2685 let (mut send, mut recv) = conn.accept_bi().await.e()?; -2686 info!("receiving hello"); -2687 let m = recv.read_to_end(100).await.e()?; -2688 assert_eq!(m, b"hello"); -2689 info!("sending hello"); -2690 send.write_all(b"world").await.e()?; -2691 send.finish().e()?; -2692 match conn.closed().await { -2693 ConnectionError::ApplicationClosed(closed) => { -2694 assert_eq!(closed.error_code, 1u8.into()); -2695 Ok(()) -2696 } -2697 _ => panic!("wrong close error"), -2698 } -2699 } -2700 -2701 let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_nodeid).instrument(info_span!( -2702 "p1_accept", -2703 ep1 = %ep1.node_id().fmt_short(), -2704 dst = %ep2_nodeid.fmt_short(), -2705 ))); -2706 let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_nodeid).instrument(info_span!( -2707 "p2_accept", -2708 ep2 = %ep2.node_id().fmt_short(), -2709 dst = %ep1_nodeid.fmt_short(), -2710 ))); -2711 let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_nodeaddr).instrument( -2712 info_span!( -2713 "p1_connect", -2714 ep1 = %ep1.node_id().fmt_short(), -2715 dst = %ep2_nodeid.fmt_short(), -2716 ), -2717 )); -2718 let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_nodeaddr).instrument( -2719 info_span!( -2720 "p2_connect", -2721 ep2 = %ep2.node_id().fmt_short(), -2722 dst = %ep1_nodeid.fmt_short(), -2723 ), -2724 )); -2725 -2726 p1_accept.await.e()??; -2727 p2_accept.await.e()??; -2728 p1_connect.await.e()??; -2729 p2_connect.await.e()??; -2730 -2731 Ok(()) -2732 } -2733 -2734 #[tokio::test] -2735 #[traced_test] -2736 async fn endpoint_conn_type_becomes_direct() -> Result { -2737 const TIMEOUT: Duration = std::time::Duration::from_secs(15); -2738 let (relay_map, _relay_url, _relay_guard) = run_relay_server().await?; -2739 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42); -2740 let ep1_secret_key = SecretKey::generate(&mut rng); -2741 let ep2_secret_key = SecretKey::generate(&mut rng); -2742 let ep1 = Endpoint::builder() -2743 .secret_key(ep1_secret_key) -2744 .insecure_skip_relay_cert_verify(true) -2745 .alpns(vec![TEST_ALPN.to_vec()]) -2746 .relay_mode(RelayMode::Custom(relay_map.clone())) -2747 .bind() -2748 .await?; -2749 let ep2 = Endpoint::builder() -2750 .secret_key(ep2_secret_key) -2751 .insecure_skip_relay_cert_verify(true) -2752 .alpns(vec![TEST_ALPN.to_vec()]) -2753 .relay_mode(RelayMode::Custom(relay_map)) -2754 .bind() -2755 .await?; -2756 -2757 async fn wait_for_conn_type_direct(ep: &Endpoint, node_id: NodeId) -> Result { -2758 let mut stream = ep.conn_type(node_id).expect("connection exists").stream(); -2759 let src = ep.node_id().fmt_short(); -2760 let dst = node_id.fmt_short(); -2761 while let Some(conn_type) = stream.next().await { -2762 tracing::info!(me = %src, dst = %dst, conn_type = ?conn_type); -2763 if matches!(conn_type, ConnectionType::Direct(_)) { -2764 return Ok(()); -2765 } -2766 } -2767 snafu::whatever!("conn_type stream ended before `ConnectionType::Direct`"); -2768 } +2623 #[tokio::test] +2624 #[traced_test] +2625 async fn endpoint_bidi_send_recv() -> Result { +2626 let ep1 = Endpoint::builder() +2627 .alpns(vec![TEST_ALPN.to_vec()]) +2628 .relay_mode(RelayMode::Disabled); +2629 +2630 let ep1 = ep1.bind().await?; +2631 let ep2 = Endpoint::builder() +2632 .alpns(vec![TEST_ALPN.to_vec()]) +2633 .relay_mode(RelayMode::Disabled); +2634 +2635 let ep2 = ep2.bind().await?; +2636 +2637 let ep1_nodeaddr = ep1.node_addr().initialized().await?; +2638 let ep2_nodeaddr = ep2.node_addr().initialized().await?; +2639 ep1.add_node_addr(ep2_nodeaddr.clone())?; +2640 ep2.add_node_addr(ep1_nodeaddr.clone())?; +2641 let ep1_nodeid = ep1.node_id(); +2642 let ep2_nodeid = ep2.node_id(); +2643 eprintln!("node id 1 {ep1_nodeid}"); +2644 eprintln!("node id 2 {ep2_nodeid}"); +2645 +2646 async fn connect_hello(ep: Endpoint, dst: NodeAddr) -> Result { +2647 let conn = ep.connect(dst, TEST_ALPN).await?; +2648 let (mut send, mut recv) = conn.open_bi().await.e()?; +2649 info!("sending hello"); +2650 send.write_all(b"hello").await.e()?; +2651 send.finish().e()?; +2652 info!("receiving world"); +2653 let m = recv.read_to_end(100).await.e()?; +2654 assert_eq!(m, b"world"); +2655 conn.close(1u8.into(), b"done"); +2656 Ok(()) +2657 } +2658 +2659 async fn accept_world(ep: Endpoint, src: NodeId) -> Result { +2660 let incoming = ep.accept().await.e()?; +2661 let mut iconn = incoming.accept().e()?; +2662 let alpn = iconn.alpn().await?; +2663 let conn = iconn.await.e()?; +2664 let node_id = conn.remote_node_id()?; +2665 assert_eq!(node_id, src); +2666 assert_eq!(alpn, TEST_ALPN); +2667 let (mut send, mut recv) = conn.accept_bi().await.e()?; +2668 info!("receiving hello"); +2669 let m = recv.read_to_end(100).await.e()?; +2670 assert_eq!(m, b"hello"); +2671 info!("sending hello"); +2672 send.write_all(b"world").await.e()?; +2673 send.finish().e()?; +2674 match conn.closed().await { +2675 ConnectionError::ApplicationClosed(closed) => { +2676 assert_eq!(closed.error_code, 1u8.into()); +2677 Ok(()) +2678 } +2679 _ => panic!("wrong close error"), +2680 } +2681 } +2682 +2683 let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_nodeid).instrument(info_span!( +2684 "p1_accept", +2685 ep1 = %ep1.node_id().fmt_short(), +2686 dst = %ep2_nodeid.fmt_short(), +2687 ))); +2688 let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_nodeid).instrument(info_span!( +2689 "p2_accept", +2690 ep2 = %ep2.node_id().fmt_short(), +2691 dst = %ep1_nodeid.fmt_short(), +2692 ))); +2693 let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_nodeaddr).instrument( +2694 info_span!( +2695 "p1_connect", +2696 ep1 = %ep1.node_id().fmt_short(), +2697 dst = %ep2_nodeid.fmt_short(), +2698 ), +2699 )); +2700 let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_nodeaddr).instrument( +2701 info_span!( +2702 "p2_connect", +2703 ep2 = %ep2.node_id().fmt_short(), +2704 dst = %ep1_nodeid.fmt_short(), +2705 ), +2706 )); +2707 +2708 p1_accept.await.e()??; +2709 p2_accept.await.e()??; +2710 p1_connect.await.e()??; +2711 p2_connect.await.e()??; +2712 +2713 Ok(()) +2714 } +2715 +2716 #[tokio::test] +2717 #[traced_test] +2718 async fn endpoint_conn_type_becomes_direct() -> Result { +2719 const TIMEOUT: Duration = std::time::Duration::from_secs(15); +2720 let (relay_map, _relay_url, _relay_guard) = run_relay_server().await?; +2721 let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42); +2722 let ep1_secret_key = SecretKey::generate(&mut rng); +2723 let ep2_secret_key = SecretKey::generate(&mut rng); +2724 let ep1 = Endpoint::builder() +2725 .secret_key(ep1_secret_key) +2726 .insecure_skip_relay_cert_verify(true) +2727 .alpns(vec![TEST_ALPN.to_vec()]) +2728 .relay_mode(RelayMode::Custom(relay_map.clone())) +2729 .bind() +2730 .await?; +2731 let ep2 = Endpoint::builder() +2732 .secret_key(ep2_secret_key) +2733 .insecure_skip_relay_cert_verify(true) +2734 .alpns(vec![TEST_ALPN.to_vec()]) +2735 .relay_mode(RelayMode::Custom(relay_map)) +2736 .bind() +2737 .await?; +2738 +2739 async fn wait_for_conn_type_direct(ep: &Endpoint, node_id: NodeId) -> Result { +2740 let mut stream = ep.conn_type(node_id).expect("connection exists").stream(); +2741 let src = ep.node_id().fmt_short(); +2742 let dst = node_id.fmt_short(); +2743 while let Some(conn_type) = stream.next().await { +2744 tracing::info!(me = %src, dst = %dst, conn_type = ?conn_type); +2745 if matches!(conn_type, ConnectionType::Direct(_)) { +2746 return Ok(()); +2747 } +2748 } +2749 snafu::whatever!("conn_type stream ended before `ConnectionType::Direct`"); +2750 } +2751 +2752 async fn accept(ep: &Endpoint) -> Result<Connection> { +2753 let incoming = ep.accept().await.expect("ep closed"); +2754 let conn = incoming.await.e()?; +2755 let node_id = conn.remote_node_id()?; +2756 tracing::info!(node_id=%node_id.fmt_short(), "accepted connection"); +2757 Ok(conn) +2758 } +2759 +2760 let ep1_nodeid = ep1.node_id(); +2761 let ep2_nodeid = ep2.node_id(); +2762 +2763 let ep1_nodeaddr = ep1.node_addr().initialized().await?; +2764 tracing::info!( +2765 "node id 1 {ep1_nodeid}, relay URL {:?}", +2766 ep1_nodeaddr.relay_url() +2767 ); +2768 tracing::info!("node id 2 {ep2_nodeid}"); 2769 -2770 async fn accept(ep: &Endpoint) -> Result<Connection> { -2771 let incoming = ep.accept().await.expect("ep closed"); -2772 let conn = incoming.await.e()?; -2773 let node_id = conn.remote_node_id()?; -2774 tracing::info!(node_id=%node_id.fmt_short(), "accepted connection"); -2775 Ok(conn) -2776 } -2777 -2778 let ep1_nodeid = ep1.node_id(); -2779 let ep2_nodeid = ep2.node_id(); -2780 -2781 let ep1_nodeaddr = ep1.node_addr().initialized().await?; -2782 tracing::info!( -2783 "node id 1 {ep1_nodeid}, relay URL {:?}", -2784 ep1_nodeaddr.relay_url() -2785 ); -2786 tracing::info!("node id 2 {ep2_nodeid}"); -2787 -2788 let ep1_side = tokio::time::timeout(TIMEOUT, async move { -2789 let conn = accept(&ep1).await?; -2790 let mut send = conn.open_uni().await.e()?; -2791 wait_for_conn_type_direct(&ep1, ep2_nodeid).await?; -2792 send.write_all(b"Conn is direct").await.e()?; -2793 send.finish().e()?; -2794 conn.closed().await; -2795 Ok::<(), Error>(()) -2796 }); +2770 let ep1_side = tokio::time::timeout(TIMEOUT, async move { +2771 let conn = accept(&ep1).await?; +2772 let mut send = conn.open_uni().await.e()?; +2773 wait_for_conn_type_direct(&ep1, ep2_nodeid).await?; +2774 send.write_all(b"Conn is direct").await.e()?; +2775 send.finish().e()?; +2776 conn.closed().await; +2777 Ok::<(), Error>(()) +2778 }); +2779 +2780 let ep2_side = tokio::time::timeout(TIMEOUT, async move { +2781 let conn = ep2.connect(ep1_nodeaddr, TEST_ALPN).await?; +2782 let mut recv = conn.accept_uni().await.e()?; +2783 wait_for_conn_type_direct(&ep2, ep1_nodeid).await?; +2784 let read = recv.read_to_end(100).await.e()?; +2785 assert_eq!(read, b"Conn is direct".to_vec()); +2786 conn.close(0u32.into(), b"done"); +2787 conn.closed().await; +2788 Ok::<(), Error>(()) +2789 }); +2790 +2791 let res_ep1 = AbortOnDropHandle::new(tokio::spawn(ep1_side)); +2792 let res_ep2 = AbortOnDropHandle::new(tokio::spawn(ep2_side)); +2793 +2794 let (r1, r2) = tokio::try_join!(res_ep1, res_ep2).e()?; +2795 r1.e()??; +2796 r2.e()??; 2797 -2798 let ep2_side = tokio::time::timeout(TIMEOUT, async move { -2799 let conn = ep2.connect(ep1_nodeaddr, TEST_ALPN).await?; -2800 let mut recv = conn.accept_uni().await.e()?; -2801 wait_for_conn_type_direct(&ep2, ep1_nodeid).await?; -2802 let read = recv.read_to_end(100).await.e()?; -2803 assert_eq!(read, b"Conn is direct".to_vec()); -2804 conn.close(0u32.into(), b"done"); -2805 conn.closed().await; -2806 Ok::<(), Error>(()) -2807 }); -2808 -2809 let res_ep1 = AbortOnDropHandle::new(tokio::spawn(ep1_side)); -2810 let res_ep2 = AbortOnDropHandle::new(tokio::spawn(ep2_side)); -2811 -2812 let (r1, r2) = tokio::try_join!(res_ep1, res_ep2).e()?; -2813 r1.e()??; -2814 r2.e()??; -2815 +2798 Ok(()) +2799 } +2800 +2801 #[tokio::test] +2802 #[traced_test] +2803 async fn test_direct_addresses_no_stun_relay() -> Result { +2804 let (relay_map, _, _guard) = run_relay_server_with(None, false).await?; +2805 +2806 let ep = Endpoint::builder() +2807 .alpns(vec![TEST_ALPN.to_vec()]) +2808 .relay_mode(RelayMode::Custom(relay_map)) +2809 .insecure_skip_relay_cert_verify(true) +2810 .bind() +2811 .await?; +2812 +2813 tokio::time::timeout(Duration::from_secs(10), ep.direct_addresses().initialized()) +2814 .await +2815 .e()??; 2816 Ok(()) 2817 } 2818 -2819 #[tokio::test] -2820 #[traced_test] -2821 async fn test_direct_addresses_no_stun_relay() -> Result { -2822 let (relay_map, _, _guard) = run_relay_server_with(None, false).await?; -2823 -2824 let ep = Endpoint::builder() -2825 .alpns(vec![TEST_ALPN.to_vec()]) -2826 .relay_mode(RelayMode::Custom(relay_map)) -2827 .insecure_skip_relay_cert_verify(true) -2828 .bind() -2829 .await?; -2830 -2831 tokio::time::timeout(Duration::from_secs(10), ep.direct_addresses().initialized()) -2832 .await -2833 .e()??; -2834 Ok(()) -2835 } -2836 -2837 async fn spawn_0rtt_server(secret_key: SecretKey, log_span: tracing::Span) -> Result<Endpoint> { -2838 let server = Endpoint::builder() -2839 .secret_key(secret_key) -2840 .alpns(vec![TEST_ALPN.to_vec()]) -2841 .relay_mode(RelayMode::Disabled) -2842 .bind() -2843 .await?; -2844 -2845 // Gets aborted via the endpoint closing causing an `Err` -2846 // a simple echo server -2847 tokio::spawn({ -2848 let server = server.clone(); -2849 async move { -2850 while let Some(incoming) = server.accept().await { -2851 let connecting = incoming.accept().e()?; -2852 let conn = match connecting.into_0rtt() { -2853 Ok((conn, _)) => { -2854 info!("0rtt accepted"); -2855 conn -2856 } -2857 Err(connecting) => { -2858 info!("0rtt denied"); -2859 connecting.await.e()? -2860 } -2861 }; -2862 let (mut send, mut recv) = conn.accept_bi().await.e()?; -2863 let data = recv.read_to_end(10_000_000).await.e()?; -2864 send.write_all(&data).await.e()?; -2865 send.finish().e()?; -2866 -2867 // Stay alive until the other side closes the connection. -2868 conn.closed().await; -2869 } -2870 Ok::<_, Error>(()) -2871 } -2872 .instrument(log_span) -2873 }); -2874 -2875 Ok(server) +2819 async fn spawn_0rtt_server(secret_key: SecretKey, log_span: tracing::Span) -> Result<Endpoint> { +2820 let server = Endpoint::builder() +2821 .secret_key(secret_key) +2822 .alpns(vec![TEST_ALPN.to_vec()]) +2823 .relay_mode(RelayMode::Disabled) +2824 .bind() +2825 .await?; +2826 +2827 // Gets aborted via the endpoint closing causing an `Err` +2828 // a simple echo server +2829 tokio::spawn({ +2830 let server = server.clone(); +2831 async move { +2832 while let Some(incoming) = server.accept().await { +2833 let connecting = incoming.accept().e()?; +2834 let conn = match connecting.into_0rtt() { +2835 Ok((conn, _)) => { +2836 info!("0rtt accepted"); +2837 conn +2838 } +2839 Err(connecting) => { +2840 info!("0rtt denied"); +2841 connecting.await.e()? +2842 } +2843 }; +2844 let (mut send, mut recv) = conn.accept_bi().await.e()?; +2845 let data = recv.read_to_end(10_000_000).await.e()?; +2846 send.write_all(&data).await.e()?; +2847 send.finish().e()?; +2848 +2849 // Stay alive until the other side closes the connection. +2850 conn.closed().await; +2851 } +2852 Ok::<_, Error>(()) +2853 } +2854 .instrument(log_span) +2855 }); +2856 +2857 Ok(server) +2858 } +2859 +2860 async fn connect_client_0rtt_expect_err(client: &Endpoint, server_addr: NodeAddr) -> Result { +2861 let conn = client +2862 .connect_with_opts(server_addr, TEST_ALPN, ConnectOptions::new()) +2863 .await? +2864 .into_0rtt() +2865 .expect_err("expected 0rtt to fail") +2866 .await +2867 .e()?; +2868 +2869 let (mut send, mut recv) = conn.open_bi().await.e()?; +2870 send.write_all(b"hello").await.e()?; +2871 send.finish().e()?; +2872 let received = recv.read_to_end(1_000).await.e()?; +2873 assert_eq!(&received, b"hello"); +2874 conn.close(0u32.into(), b"thx"); +2875 Ok(()) 2876 } 2877 -2878 async fn connect_client_0rtt_expect_err(client: &Endpoint, server_addr: NodeAddr) -> Result { -2879 let conn = client -2880 .connect_with_opts(server_addr, TEST_ALPN, ConnectOptions::new()) -2881 .await? -2882 .into_0rtt() -2883 .expect_err("expected 0rtt to fail") -2884 .await -2885 .e()?; -2886 -2887 let (mut send, mut recv) = conn.open_bi().await.e()?; -2888 send.write_all(b"hello").await.e()?; -2889 send.finish().e()?; -2890 let received = recv.read_to_end(1_000).await.e()?; -2891 assert_eq!(&received, b"hello"); -2892 conn.close(0u32.into(), b"thx"); -2893 Ok(()) -2894 } -2895 -2896 async fn connect_client_0rtt_expect_ok( -2897 client: &Endpoint, -2898 server_addr: NodeAddr, -2899 expect_server_accepts: bool, -2900 ) -> Result { -2901 let (conn, accepted_0rtt) = client -2902 .connect_with_opts(server_addr, TEST_ALPN, ConnectOptions::new()) -2903 .await? -2904 .into_0rtt() -2905 .ok() -2906 .e()?; -2907 -2908 // This is how we send data in 0-RTT: -2909 let (mut send, recv) = conn.open_bi().await.e()?; -2910 send.write_all(b"hello").await.e()?; -2911 send.finish().e()?; -2912 // When this resolves, we've gotten a response from the server about whether the 0-RTT data above was accepted: -2913 let accepted = accepted_0rtt.await; -2914 assert_eq!(accepted, expect_server_accepts); -2915 let mut recv = if accepted { -2916 recv -2917 } else { -2918 // in this case we need to re-send data by re-creating the connection. -2919 let (mut send, recv) = conn.open_bi().await.e()?; -2920 send.write_all(b"hello").await.e()?; -2921 send.finish().e()?; -2922 recv -2923 }; -2924 let received = recv.read_to_end(1_000).await.e()?; -2925 assert_eq!(&received, b"hello"); -2926 conn.close(0u32.into(), b"thx"); -2927 Ok(()) -2928 } +2878 async fn connect_client_0rtt_expect_ok( +2879 client: &Endpoint, +2880 server_addr: NodeAddr, +2881 expect_server_accepts: bool, +2882 ) -> Result { +2883 let (conn, accepted_0rtt) = client +2884 .connect_with_opts(server_addr, TEST_ALPN, ConnectOptions::new()) +2885 .await? +2886 .into_0rtt() +2887 .ok() +2888 .e()?; +2889 +2890 // This is how we send data in 0-RTT: +2891 let (mut send, recv) = conn.open_bi().await.e()?; +2892 send.write_all(b"hello").await.e()?; +2893 send.finish().e()?; +2894 // When this resolves, we've gotten a response from the server about whether the 0-RTT data above was accepted: +2895 let accepted = accepted_0rtt.await; +2896 assert_eq!(accepted, expect_server_accepts); +2897 let mut recv = if accepted { +2898 recv +2899 } else { +2900 // in this case we need to re-send data by re-creating the connection. +2901 let (mut send, recv) = conn.open_bi().await.e()?; +2902 send.write_all(b"hello").await.e()?; +2903 send.finish().e()?; +2904 recv +2905 }; +2906 let received = recv.read_to_end(1_000).await.e()?; +2907 assert_eq!(&received, b"hello"); +2908 conn.close(0u32.into(), b"thx"); +2909 Ok(()) +2910 } +2911 +2912 #[tokio::test] +2913 #[traced_test] +2914 async fn test_0rtt() -> Result { +2915 let client = Endpoint::builder() +2916 .relay_mode(RelayMode::Disabled) +2917 .bind() +2918 .await?; +2919 let server = spawn_0rtt_server( +2920 SecretKey::generate(rand::thread_rng()), +2921 info_span!("server"), +2922 ) +2923 .await?; +2924 +2925 connect_client_0rtt_expect_err(&client, server.node_addr().initialized().await?).await?; +2926 // The second 0rtt attempt should work +2927 connect_client_0rtt_expect_ok(&client, server.node_addr().initialized().await?, true) +2928 .await?; 2929 -2930 #[tokio::test] -2931 #[traced_test] -2932 async fn test_0rtt() -> Result { -2933 let client = Endpoint::builder() -2934 .relay_mode(RelayMode::Disabled) -2935 .bind() -2936 .await?; -2937 let server = spawn_0rtt_server( -2938 SecretKey::generate(rand::thread_rng()), -2939 info_span!("server"), -2940 ) -2941 .await?; -2942 -2943 connect_client_0rtt_expect_err(&client, server.node_addr().initialized().await?).await?; -2944 // The second 0rtt attempt should work -2945 connect_client_0rtt_expect_ok(&client, server.node_addr().initialized().await?, true) -2946 .await?; -2947 -2948 client.close().await; -2949 server.close().await; -2950 -2951 Ok(()) -2952 } +2930 client.close().await; +2931 server.close().await; +2932 +2933 Ok(()) +2934 } +2935 +2936 // We have this test, as this would've failed at some point. +2937 // This effectively tests that we correctly categorize the TLS session tickets we +2938 // receive into the respective "bucket" for the recipient. +2939 #[tokio::test] +2940 #[traced_test] +2941 async fn test_0rtt_non_consecutive() -> Result { +2942 let client = Endpoint::builder() +2943 .relay_mode(RelayMode::Disabled) +2944 .bind() +2945 .await?; +2946 let server = spawn_0rtt_server( +2947 SecretKey::generate(rand::thread_rng()), +2948 info_span!("server"), +2949 ) +2950 .await?; +2951 +2952 connect_client_0rtt_expect_err(&client, server.node_addr().initialized().await?).await?; 2953 -2954 // We have this test, as this would've failed at some point. -2955 // This effectively tests that we correctly categorize the TLS session tickets we -2956 // receive into the respective "bucket" for the recipient. -2957 #[tokio::test] -2958 #[traced_test] -2959 async fn test_0rtt_non_consecutive() -> Result { -2960 let client = Endpoint::builder() -2961 .relay_mode(RelayMode::Disabled) -2962 .bind() -2963 .await?; -2964 let server = spawn_0rtt_server( -2965 SecretKey::generate(rand::thread_rng()), -2966 info_span!("server"), -2967 ) -2968 .await?; +2954 // connecting with another endpoint should not interfere with our +2955 // TLS session ticket cache for the first endpoint: +2956 let another = spawn_0rtt_server( +2957 SecretKey::generate(rand::thread_rng()), +2958 info_span!("another"), +2959 ) +2960 .await?; +2961 connect_client_0rtt_expect_err(&client, another.node_addr().initialized().await?).await?; +2962 another.close().await; +2963 +2964 connect_client_0rtt_expect_ok(&client, server.node_addr().initialized().await?, true) +2965 .await?; +2966 +2967 client.close().await; +2968 server.close().await; 2969 -2970 connect_client_0rtt_expect_err(&client, server.node_addr().initialized().await?).await?; -2971 -2972 // connecting with another endpoint should not interfere with our -2973 // TLS session ticket cache for the first endpoint: -2974 let another = spawn_0rtt_server( -2975 SecretKey::generate(rand::thread_rng()), -2976 info_span!("another"), -2977 ) -2978 .await?; -2979 connect_client_0rtt_expect_err(&client, another.node_addr().initialized().await?).await?; -2980 another.close().await; -2981 -2982 connect_client_0rtt_expect_ok(&client, server.node_addr().initialized().await?, true) -2983 .await?; -2984 -2985 client.close().await; -2986 server.close().await; +2970 Ok(()) +2971 } +2972 +2973 // Test whether 0-RTT is possible after a restart: +2974 #[tokio::test] +2975 #[traced_test] +2976 async fn test_0rtt_after_server_restart() -> Result { +2977 let client = Endpoint::builder() +2978 .relay_mode(RelayMode::Disabled) +2979 .bind() +2980 .await?; +2981 let server_key = SecretKey::generate(rand::thread_rng()); +2982 let server = spawn_0rtt_server(server_key.clone(), info_span!("server-initial")).await?; +2983 +2984 connect_client_0rtt_expect_err(&client, server.node_addr().initialized().await?).await?; +2985 connect_client_0rtt_expect_ok(&client, server.node_addr().initialized().await?, true) +2986 .await?; 2987 -2988 Ok(()) -2989 } -2990 -2991 // Test whether 0-RTT is possible after a restart: -2992 #[tokio::test] -2993 #[traced_test] -2994 async fn test_0rtt_after_server_restart() -> Result { -2995 let client = Endpoint::builder() -2996 .relay_mode(RelayMode::Disabled) -2997 .bind() -2998 .await?; -2999 let server_key = SecretKey::generate(rand::thread_rng()); -3000 let server = spawn_0rtt_server(server_key.clone(), info_span!("server-initial")).await?; -3001 -3002 connect_client_0rtt_expect_err(&client, server.node_addr().initialized().await?).await?; -3003 connect_client_0rtt_expect_ok(&client, server.node_addr().initialized().await?, true) -3004 .await?; -3005 -3006 server.close().await; -3007 -3008 let server = spawn_0rtt_server(server_key, info_span!("server-restart")).await?; -3009 -3010 // we expect the client to *believe* it can 0-RTT connect to the server (hence expect_ok), -3011 // but the server will reject the early data because it discarded necessary state -3012 // to decrypt it when restarting. -3013 connect_client_0rtt_expect_ok(&client, server.node_addr().initialized().await?, false) -3014 .await?; -3015 -3016 client.close().await; -3017 -3018 Ok(()) -3019 } -3020 -3021 #[cfg_attr(target_os = "windows", ignore = "flaky")] -3022 #[tokio::test] -3023 #[traced_test] -3024 async fn graceful_close() -> Result { -3025 let client = Endpoint::builder().bind().await?; -3026 let server = Endpoint::builder() -3027 .alpns(vec![TEST_ALPN.to_vec()]) -3028 .bind() -3029 .await?; -3030 let server_addr = server.node_addr().initialized().await?; -3031 let server_task = tokio::spawn(async move { -3032 let incoming = server.accept().await.e()?; -3033 let conn = incoming.await.e()?; -3034 let (mut send, mut recv) = conn.accept_bi().await.e()?; -3035 let msg = recv.read_to_end(1_000).await.e()?; -3036 send.write_all(&msg).await.e()?; -3037 send.finish().e()?; -3038 let close_reason = conn.closed().await; -3039 Ok::<_, Error>(close_reason) -3040 }); -3041 -3042 let conn = client.connect(server_addr, TEST_ALPN).await?; -3043 let (mut send, mut recv) = conn.open_bi().await.e()?; -3044 send.write_all(b"Hello, world!").await.e()?; -3045 send.finish().e()?; -3046 recv.read_to_end(1_000).await.e()?; -3047 conn.close(42u32.into(), b"thanks, bye!"); -3048 client.close().await; -3049 -3050 let close_err = server_task.await.e()??; -3051 let ConnectionError::ApplicationClosed(app_close) = close_err else { -3052 panic!("Unexpected close reason: {close_err:?}"); -3053 }; -3054 -3055 assert_eq!(app_close.error_code, 42u32.into()); -3056 assert_eq!(app_close.reason.as_ref(), b"thanks, bye!"); -3057 -3058 Ok(()) -3059 } -3060 -3061 #[cfg(feature = "metrics")] -3062 #[tokio::test] -3063 #[traced_test] -3064 async fn metrics_smoke() -> Result { -3065 use iroh_metrics::{MetricsSource, Registry}; -3066 -3067 let secret_key = SecretKey::from_bytes(&[0u8; 32]); -3068 let client = Endpoint::builder() -3069 .secret_key(secret_key) -3070 .relay_mode(RelayMode::Disabled) -3071 .bind() -3072 .await?; -3073 let secret_key = SecretKey::from_bytes(&[1u8; 32]); -3074 let server = Endpoint::builder() -3075 .secret_key(secret_key) -3076 .relay_mode(RelayMode::Disabled) -3077 .alpns(vec![TEST_ALPN.to_vec()]) -3078 .bind() -3079 .await?; -3080 let server_addr = server.node_addr().initialized().await?; -3081 let server_task = tokio::task::spawn(async move { -3082 let conn = server.accept().await.e()?.accept().e()?.await.e()?; -3083 let mut uni = conn.accept_uni().await.e()?; -3084 uni.read_to_end(10).await.e()?; -3085 drop(conn); -3086 Ok::<_, Error>(server) -3087 }); -3088 let conn = client.connect(server_addr, TEST_ALPN).await?; -3089 let mut uni = conn.open_uni().await.e()?; -3090 uni.write_all(b"helloworld").await.e()?; -3091 uni.finish().e()?; -3092 conn.closed().await; -3093 drop(conn); -3094 let server = server_task.await.e()??; -3095 -3096 let m = client.metrics(); -3097 assert_eq!(m.magicsock.num_direct_conns_added.get(), 1); -3098 assert_eq!(m.magicsock.connection_became_direct.get(), 1); -3099 assert_eq!(m.magicsock.connection_handshake_success.get(), 1); -3100 assert_eq!(m.magicsock.nodes_contacted_directly.get(), 1); -3101 assert!(m.magicsock.recv_datagrams.get() > 0); -3102 -3103 let m = server.metrics(); -3104 assert_eq!(m.magicsock.num_direct_conns_added.get(), 1); -3105 assert_eq!(m.magicsock.connection_became_direct.get(), 1); -3106 assert_eq!(m.magicsock.nodes_contacted_directly.get(), 1); -3107 assert_eq!(m.magicsock.connection_handshake_success.get(), 1); -3108 assert!(m.magicsock.recv_datagrams.get() > 0); -3109 -3110 // test openmetrics encoding with labeled subregistries per endpoint -3111 fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) { -3112 let id = endpoint.node_id().fmt_short(); -3113 let sub_registry = registry.sub_registry_with_label("id", id); -3114 sub_registry.register_all(endpoint.metrics()); -3115 } -3116 let mut registry = Registry::default(); -3117 register_endpoint(&mut registry, &client); -3118 register_endpoint(&mut registry, &server); -3119 let s = registry.encode_openmetrics_to_string()?; -3120 assert!(s.contains(r#"magicsock_nodes_contacted_directly_total{id="3b6a27bcce"} 1"#)); -3121 assert!(s.contains(r#"magicsock_nodes_contacted_directly_total{id="8a88e3dd74"} 1"#)); -3122 Ok(()) -3123 } -3124 -3125 /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn` -3126 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN. -3127 async fn alpn_connection_test( -3128 accept_alpns: Vec<Vec<u8>>, -3129 primary_connect_alpn: &[u8], -3130 secondary_connect_alpns: Vec<Vec<u8>>, -3131 ) -> Result<Option<Vec<u8>>> { -3132 let client = Endpoint::builder() -3133 .relay_mode(RelayMode::Disabled) -3134 .bind() -3135 .await?; -3136 let server = Endpoint::builder() -3137 .relay_mode(RelayMode::Disabled) -3138 .alpns(accept_alpns) -3139 .bind() +2988 server.close().await; +2989 +2990 let server = spawn_0rtt_server(server_key, info_span!("server-restart")).await?; +2991 +2992 // we expect the client to *believe* it can 0-RTT connect to the server (hence expect_ok), +2993 // but the server will reject the early data because it discarded necessary state +2994 // to decrypt it when restarting. +2995 connect_client_0rtt_expect_ok(&client, server.node_addr().initialized().await?, false) +2996 .await?; +2997 +2998 client.close().await; +2999 +3000 Ok(()) +3001 } +3002 +3003 #[cfg_attr(target_os = "windows", ignore = "flaky")] +3004 #[tokio::test] +3005 #[traced_test] +3006 async fn graceful_close() -> Result { +3007 let client = Endpoint::builder().bind().await?; +3008 let server = Endpoint::builder() +3009 .alpns(vec![TEST_ALPN.to_vec()]) +3010 .bind() +3011 .await?; +3012 let server_addr = server.node_addr().initialized().await?; +3013 let server_task = tokio::spawn(async move { +3014 let incoming = server.accept().await.e()?; +3015 let conn = incoming.await.e()?; +3016 let (mut send, mut recv) = conn.accept_bi().await.e()?; +3017 let msg = recv.read_to_end(1_000).await.e()?; +3018 send.write_all(&msg).await.e()?; +3019 send.finish().e()?; +3020 let close_reason = conn.closed().await; +3021 Ok::<_, Error>(close_reason) +3022 }); +3023 +3024 let conn = client.connect(server_addr, TEST_ALPN).await?; +3025 let (mut send, mut recv) = conn.open_bi().await.e()?; +3026 send.write_all(b"Hello, world!").await.e()?; +3027 send.finish().e()?; +3028 recv.read_to_end(1_000).await.e()?; +3029 conn.close(42u32.into(), b"thanks, bye!"); +3030 client.close().await; +3031 +3032 let close_err = server_task.await.e()??; +3033 let ConnectionError::ApplicationClosed(app_close) = close_err else { +3034 panic!("Unexpected close reason: {close_err:?}"); +3035 }; +3036 +3037 assert_eq!(app_close.error_code, 42u32.into()); +3038 assert_eq!(app_close.reason.as_ref(), b"thanks, bye!"); +3039 +3040 Ok(()) +3041 } +3042 +3043 #[cfg(feature = "metrics")] +3044 #[tokio::test] +3045 #[traced_test] +3046 async fn metrics_smoke() -> Result { +3047 use iroh_metrics::{MetricsSource, Registry}; +3048 +3049 let secret_key = SecretKey::from_bytes(&[0u8; 32]); +3050 let client = Endpoint::builder() +3051 .secret_key(secret_key) +3052 .relay_mode(RelayMode::Disabled) +3053 .bind() +3054 .await?; +3055 let secret_key = SecretKey::from_bytes(&[1u8; 32]); +3056 let server = Endpoint::builder() +3057 .secret_key(secret_key) +3058 .relay_mode(RelayMode::Disabled) +3059 .alpns(vec![TEST_ALPN.to_vec()]) +3060 .bind() +3061 .await?; +3062 let server_addr = server.node_addr().initialized().await?; +3063 let server_task = tokio::task::spawn(async move { +3064 let conn = server.accept().await.e()?.accept().e()?.await.e()?; +3065 let mut uni = conn.accept_uni().await.e()?; +3066 uni.read_to_end(10).await.e()?; +3067 drop(conn); +3068 Ok::<_, Error>(server) +3069 }); +3070 let conn = client.connect(server_addr, TEST_ALPN).await?; +3071 let mut uni = conn.open_uni().await.e()?; +3072 uni.write_all(b"helloworld").await.e()?; +3073 uni.finish().e()?; +3074 conn.closed().await; +3075 drop(conn); +3076 let server = server_task.await.e()??; +3077 +3078 let m = client.metrics(); +3079 assert_eq!(m.magicsock.num_direct_conns_added.get(), 1); +3080 assert_eq!(m.magicsock.connection_became_direct.get(), 1); +3081 assert_eq!(m.magicsock.connection_handshake_success.get(), 1); +3082 assert_eq!(m.magicsock.nodes_contacted_directly.get(), 1); +3083 assert!(m.magicsock.recv_datagrams.get() > 0); +3084 +3085 let m = server.metrics(); +3086 assert_eq!(m.magicsock.num_direct_conns_added.get(), 1); +3087 assert_eq!(m.magicsock.connection_became_direct.get(), 1); +3088 assert_eq!(m.magicsock.nodes_contacted_directly.get(), 1); +3089 assert_eq!(m.magicsock.connection_handshake_success.get(), 1); +3090 assert!(m.magicsock.recv_datagrams.get() > 0); +3091 +3092 // test openmetrics encoding with labeled subregistries per endpoint +3093 fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) { +3094 let id = endpoint.node_id().fmt_short(); +3095 let sub_registry = registry.sub_registry_with_label("id", id); +3096 sub_registry.register_all(endpoint.metrics()); +3097 } +3098 let mut registry = Registry::default(); +3099 register_endpoint(&mut registry, &client); +3100 register_endpoint(&mut registry, &server); +3101 let s = registry.encode_openmetrics_to_string()?; +3102 assert!(s.contains(r#"magicsock_nodes_contacted_directly_total{id="3b6a27bcce"} 1"#)); +3103 assert!(s.contains(r#"magicsock_nodes_contacted_directly_total{id="8a88e3dd74"} 1"#)); +3104 Ok(()) +3105 } +3106 +3107 /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn` +3108 /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN. +3109 async fn alpn_connection_test( +3110 accept_alpns: Vec<Vec<u8>>, +3111 primary_connect_alpn: &[u8], +3112 secondary_connect_alpns: Vec<Vec<u8>>, +3113 ) -> Result<Option<Vec<u8>>> { +3114 let client = Endpoint::builder() +3115 .relay_mode(RelayMode::Disabled) +3116 .bind() +3117 .await?; +3118 let server = Endpoint::builder() +3119 .relay_mode(RelayMode::Disabled) +3120 .alpns(accept_alpns) +3121 .bind() +3122 .await?; +3123 let server_addr = server.node_addr().initialized().await?; +3124 let server_task = tokio::spawn({ +3125 let server = server.clone(); +3126 async move { +3127 let incoming = server.accept().await.e()?; +3128 let conn = incoming.await.e()?; +3129 conn.close(0u32.into(), b"bye!"); +3130 Ok::<_, n0_snafu::Error>(conn.alpn()) +3131 } +3132 }); +3133 +3134 let conn = client +3135 .connect_with_opts( +3136 server_addr, +3137 primary_connect_alpn, +3138 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns), +3139 ) 3140 .await?; -3141 let server_addr = server.node_addr().initialized().await?; -3142 let server_task = tokio::spawn({ -3143 let server = server.clone(); -3144 async move { -3145 let incoming = server.accept().await.e()?; -3146 let conn = incoming.await.e()?; -3147 conn.close(0u32.into(), b"bye!"); -3148 Ok::<_, n0_snafu::Error>(conn.alpn()) -3149 } -3150 }); -3151 -3152 let conn = client -3153 .connect_with_opts( -3154 server_addr, -3155 primary_connect_alpn, -3156 ConnectOptions::new().with_additional_alpns(secondary_connect_alpns), -3157 ) -3158 .await?; -3159 let conn = conn.await.e()?; -3160 let client_alpn = conn.alpn(); -3161 conn.closed().await; -3162 client.close().await; -3163 server.close().await; -3164 -3165 let server_alpn = server_task.await.e()??; -3166 -3167 assert_eq!(client_alpn, server_alpn); -3168 -3169 Ok(server_alpn) -3170 } +3141 let conn = conn.await.e()?; +3142 let client_alpn = conn.alpn(); +3143 conn.closed().await; +3144 client.close().await; +3145 server.close().await; +3146 +3147 let server_alpn = server_task.await.e()??; +3148 +3149 assert_eq!(client_alpn, server_alpn); +3150 +3151 Ok(server_alpn) +3152 } +3153 +3154 #[tokio::test] +3155 #[traced_test] +3156 async fn connect_multiple_alpn_negotiated() -> Result { +3157 const ALPN_ONE: &[u8] = b"alpn/1"; +3158 const ALPN_TWO: &[u8] = b"alpn/2"; +3159 +3160 assert_eq!( +3161 alpn_connection_test( +3162 // Prefer version 2 over version 1 on the accept side +3163 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], +3164 ALPN_TWO, +3165 vec![ALPN_ONE.to_vec()], +3166 ) +3167 .await?, +3168 Some(ALPN_TWO.to_vec()), +3169 "accept side prefers version 2 over 1" +3170 ); 3171 -3172 #[tokio::test] -3173 #[traced_test] -3174 async fn connect_multiple_alpn_negotiated() -> Result { -3175 const ALPN_ONE: &[u8] = b"alpn/1"; -3176 const ALPN_TWO: &[u8] = b"alpn/2"; -3177 -3178 assert_eq!( -3179 alpn_connection_test( -3180 // Prefer version 2 over version 1 on the accept side -3181 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], -3182 ALPN_TWO, -3183 vec![ALPN_ONE.to_vec()], -3184 ) -3185 .await?, -3186 Some(ALPN_TWO.to_vec()), -3187 "accept side prefers version 2 over 1" -3188 ); -3189 -3190 assert_eq!( -3191 alpn_connection_test( -3192 // Only support the old version -3193 vec![ALPN_ONE.to_vec()], -3194 ALPN_TWO, -3195 vec![ALPN_ONE.to_vec()], -3196 ) -3197 .await?, +3172 assert_eq!( +3173 alpn_connection_test( +3174 // Only support the old version +3175 vec![ALPN_ONE.to_vec()], +3176 ALPN_TWO, +3177 vec![ALPN_ONE.to_vec()], +3178 ) +3179 .await?, +3180 Some(ALPN_ONE.to_vec()), +3181 "accept side only supports the old version" +3182 ); +3183 +3184 assert_eq!( +3185 alpn_connection_test( +3186 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], +3187 ALPN_ONE, +3188 vec![ALPN_TWO.to_vec()], +3189 ) +3190 .await?, +3191 Some(ALPN_TWO.to_vec()), +3192 "connect side ALPN order doesn't matter" +3193 ); +3194 +3195 assert_eq!( +3196 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],) +3197 .await?, 3198 Some(ALPN_ONE.to_vec()), -3199 "accept side only supports the old version" +3199 "connect side only supports the old version" 3200 ); 3201 -3202 assert_eq!( -3203 alpn_connection_test( -3204 vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], -3205 ALPN_ONE, -3206 vec![ALPN_TWO.to_vec()], -3207 ) -3208 .await?, -3209 Some(ALPN_TWO.to_vec()), -3210 "connect side ALPN order doesn't matter" -3211 ); +3202 Ok(()) +3203 } +3204 +3205 #[tokio::test] +3206 #[traced_test] +3207 async fn watch_net_report() -> Result { +3208 let endpoint = Endpoint::builder() +3209 .relay_mode(RelayMode::Staging) +3210 .bind() +3211 .await?; 3212 -3213 assert_eq!( -3214 alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],) -3215 .await?, -3216 Some(ALPN_ONE.to_vec()), -3217 "connect side only supports the old version" -3218 ); -3219 -3220 Ok(()) -3221 } -3222 -3223 #[tokio::test] -3224 #[traced_test] -3225 async fn watch_net_report() -> Result { -3226 let endpoint = Endpoint::builder() -3227 .relay_mode(RelayMode::Staging) -3228 .bind() -3229 .await?; -3230 -3231 // can get a first report -3232 endpoint.net_report().initialized().await?; -3233 -3234 Ok(()) -3235 } -3236} \ No newline at end of file +3213 // can get a first report +3214 endpoint.net_report().initialized().await?; +3215 +3216 Ok(()) +3217 } +3218} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/endpoint/rtt_actor.rs.html b/pr/3327/docs/src/iroh/endpoint/rtt_actor.rs.html index de1bd802f5..fef63a1424 100644 --- a/pr/3327/docs/src/iroh/endpoint/rtt_actor.rs.html +++ b/pr/3327/docs/src/iroh/endpoint/rtt_actor.rs.html @@ -10,7 +10,7 @@ 10use tokio::sync::mpsc; 11use tracing::{debug, info_span, Instrument}; 12 -13use crate::{magicsock::ConnectionType, metrics::MagicsockMetrics, watcher}; +13use crate::{magicsock::ConnectionType, metrics::MagicsockMetrics}; 14 15#[derive(Debug)] 16pub(super) struct RttHandle { @@ -47,7 +47,7 @@ 47 /// The connection. 48 connection: quinn::WeakConnectionHandle, 49 /// Path changes for this connection from the magic socket. -50 conn_type_changes: watcher::Stream<watcher::Direct<ConnectionType>>, +50 conn_type_changes: n0_watcher::Stream<n0_watcher::Direct<ConnectionType>>, 51 /// For reporting-only, the Node ID of this connection. 52 node_id: NodeId, 53 }, @@ -67,7 +67,7 @@ 67 68#[derive(Debug)] 69struct MappedStream { -70 stream: watcher::Stream<watcher::Direct<ConnectionType>>, +70 stream: n0_watcher::Stream<n0_watcher::Direct<ConnectionType>>, 71 node_id: NodeId, 72 /// Reference to the connection. 73 connection: quinn::WeakConnectionHandle, @@ -157,7 +157,7 @@ 157 fn handle_new_connection( 158 &mut self, 159 connection: quinn::WeakConnectionHandle, -160 conn_type_changes: watcher::Stream<watcher::Direct<ConnectionType>>, +160 conn_type_changes: n0_watcher::Stream<n0_watcher::Direct<ConnectionType>>, 161 node_id: NodeId, 162 ) { 163 self.connection_events.push(MappedStream { diff --git a/pr/3327/docs/src/iroh/lib.rs.html b/pr/3327/docs/src/iroh/lib.rs.html index bd033dcab3..da6eaba2d1 100644 --- a/pr/3327/docs/src/iroh/lib.rs.html +++ b/pr/3327/docs/src/iroh/lib.rs.html @@ -195,8 +195,8 @@ 195//! Every [`Endpoint`] can also accept connections: 196//! 197//! ```no_run -198//! use futures_lite::StreamExt; -199//! use iroh::{Endpoint, NodeAddr}; +198//! use iroh::{Endpoint, NodeAddr}; +199//! use n0_future::StreamExt; 200//! use n0_snafu::{Result, ResultExt}; 201//! 202//! async fn accept() -> Result<()> { @@ -269,13 +269,12 @@ 269pub mod metrics; 270pub mod net_report; 271pub mod protocol; -272pub mod watcher; -273 -274pub use endpoint::{Endpoint, RelayMode}; -275pub use iroh_base::{ -276 KeyParsingError, NodeAddr, NodeId, PublicKey, RelayUrl, RelayUrlParseError, SecretKey, -277}; -278pub use iroh_relay::{http::Protocol as RelayProtocol, node_info, RelayMap, RelayNode}; -279 -280#[cfg(any(test, feature = "test-utils"))] -281pub mod test_utils; \ No newline at end of file +272 +273pub use endpoint::{Endpoint, RelayMode}; +274pub use iroh_base::{ +275 KeyParsingError, NodeAddr, NodeId, PublicKey, RelayUrl, RelayUrlParseError, SecretKey, +276}; +277pub use iroh_relay::{http::Protocol as RelayProtocol, node_info, RelayMap, RelayNode}; +278 +279#[cfg(any(test, feature = "test-utils"))] +280pub mod test_utils; \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/magicsock.rs.html b/pr/3327/docs/src/iroh/magicsock.rs.html index 7f7f60358a..e145cb5a8c 100644 --- a/pr/3327/docs/src/iroh/magicsock.rs.html +++ b/pr/3327/docs/src/iroh/magicsock.rs.html @@ -22,4550 +22,3576 @@ 22 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}, 23 pin::Pin, 24 sync::{ -25 atomic::{AtomicBool, AtomicU16, AtomicU64, AtomicUsize, Ordering}, +25 atomic::{AtomicBool, AtomicU64, Ordering}, 26 Arc, RwLock, 27 }, -28 task::{Context, Poll, Waker}, +28 task::{Context, Poll}, 29}; 30 -31use atomic_waker::AtomicWaker; -32use bytes::Bytes; -33use concurrent_queue::ConcurrentQueue; -34use data_encoding::HEXLOWER; -35use iroh_base::{NodeAddr, NodeId, PublicKey, RelayUrl, SecretKey}; -36use iroh_relay::{protos::stun, RelayMap}; -37use n0_future::{ -38 boxed::BoxStream, -39 task::{self, JoinSet}, -40 time::{self, Duration, Instant}, -41 FutureExt, StreamExt, -42}; -43use nested_enum_utils::common_fields; -44use netwatch::{ -45 interfaces, -46 netmon::{self, CallbackToken}, -47}; -48#[cfg(not(wasm_browser))] -49use netwatch::{ip::LocalAddresses, UdpSocket}; -50use quinn::{AsyncUdpSocket, ServerConfig}; -51use rand::{seq::SliceRandom, Rng, SeedableRng}; -52use relay_actor::RelaySendItem; -53use smallvec::{smallvec, SmallVec}; -54use snafu::{IntoError, ResultExt, Snafu}; -55use tokio::sync::{self, mpsc, Mutex}; -56use tokio_util::sync::CancellationToken; -57use tracing::{ -58 debug, error, error_span, event, info, info_span, instrument, trace, trace_span, warn, -59 Instrument, Level, Span, -60}; -61use url::Url; -62 -63#[cfg(not(wasm_browser))] -64use self::udp_conn::UdpConn; -65use self::{ -66 metrics::Metrics as MagicsockMetrics, -67 node_map::{NodeMap, PingAction, PingRole, SendPing}, -68 relay_actor::{RelayActor, RelayActorMessage, RelayRecvDatagram}, -69}; -70#[cfg(not(wasm_browser))] -71use crate::dns::DnsResolver; -72#[cfg(any(test, feature = "test-utils"))] -73use crate::endpoint::PathSelection; -74#[cfg(not(wasm_browser))] -75use crate::net_report::{IpMappedAddr, QuicConfig}; -76use crate::{ -77 defaults::timeouts::NET_REPORT_TIMEOUT, -78 disco::{self, CallMeMaybe, SendAddr}, -79 discovery::{Discovery, DiscoveryItem, DiscoverySubscribers, NodeData, UserData}, -80 key::{public_ed_box, secret_ed_box, DecryptionError, SharedSecret}, -81 metrics::EndpointMetrics, -82 net_report::{self, IpMappedAddresses, Report, ReportError}, -83 watcher::{self, Watchable}, -84}; -85 -86mod metrics; -87mod node_map; -88mod relay_actor; -89#[cfg(not(wasm_browser))] -90mod udp_conn; +31use bytes::Bytes; +32use data_encoding::HEXLOWER; +33use iroh_base::{NodeAddr, NodeId, PublicKey, RelayUrl, SecretKey}; +34use iroh_relay::{protos::stun, RelayMap}; +35use n0_future::{ +36 boxed::BoxStream, +37 task::{self, JoinSet}, +38 time::{self, Duration, Instant}, +39 StreamExt, +40}; +41use n0_watcher::{self, Watchable, Watcher}; +42use nested_enum_utils::common_fields; +43use netwatch::netmon; +44#[cfg(not(wasm_browser))] +45use netwatch::{ip::LocalAddresses, UdpSocket}; +46use quinn::{AsyncUdpSocket, ServerConfig}; +47use rand::{seq::SliceRandom, Rng, SeedableRng}; +48use smallvec::SmallVec; +49use snafu::{IntoError, ResultExt, Snafu}; +50use tokio::sync::{self, mpsc, Mutex}; +51use tracing::{ +52 debug, error, error_span, event, info, info_span, instrument, trace, trace_span, warn, +53 Instrument, Level, Span, +54}; +55use transports::LocalAddrsWatch; +56use url::Url; +57 +58#[cfg(not(wasm_browser))] +59use self::transports::IpTransport; +60use self::{ +61 metrics::Metrics as MagicsockMetrics, +62 node_map::{NodeMap, PingAction, PingRole, SendPing}, +63 transports::{RelayActorConfig, RelayTransport, Transports, UdpSender}, +64}; +65#[cfg(not(wasm_browser))] +66use crate::dns::DnsResolver; +67#[cfg(any(test, feature = "test-utils"))] +68use crate::endpoint::PathSelection; +69#[cfg(not(wasm_browser))] +70use crate::net_report::{IpMappedAddr, QuicConfig}; +71use crate::{ +72 defaults::timeouts::NET_REPORT_TIMEOUT, +73 disco::{self, SendAddr}, +74 discovery::{Discovery, DiscoveryItem, DiscoverySubscribers, NodeData, UserData}, +75 key::{public_ed_box, secret_ed_box, DecryptionError, SharedSecret}, +76 metrics::EndpointMetrics, +77 net_report::{self, IpMappedAddresses, Report, ReportError}, +78}; +79 +80mod metrics; +81mod node_map; +82 +83pub(crate) mod transports; +84 +85pub use node_map::Source; +86 +87pub use self::{ +88 metrics::Metrics, +89 node_map::{ConnectionType, ControlMsg, DirectAddrInfo, RemoteInfo}, +90}; 91 -92pub use node_map::Source; -93 -94pub use self::{ -95 metrics::Metrics, -96 node_map::{ConnectionType, ControlMsg, DirectAddrInfo, RemoteInfo}, -97}; -98 -99/// How long we consider a STUN-derived endpoint valid for. UDP NAT mappings typically -100/// expire at 30 seconds, so this is a few seconds shy of that. -101const ENDPOINTS_FRESH_ENOUGH_DURATION: Duration = Duration::from_secs(27); -102 -103const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5); -104 -105/// Contains options for `MagicSock::listen`. -106#[derive(derive_more::Debug)] -107pub(crate) struct Options { -108 /// The IPv4 address to listen on. -109 /// -110 /// If set to `None` it will choose a random port and listen on `0.0.0.0:0`. -111 pub(crate) addr_v4: Option<SocketAddrV4>, -112 /// The IPv6 address to listen on. -113 /// -114 /// If set to `None` it will choose a random port and listen on `[::]:0`. -115 pub(crate) addr_v6: Option<SocketAddrV6>, -116 -117 /// Secret key for this node. -118 pub(crate) secret_key: SecretKey, -119 -120 /// The [`RelayMap`] to use, leave empty to not use a relay server. -121 pub(crate) relay_map: RelayMap, -122 -123 /// Whether to use websockets or the nonstandard legacy protocol to connect to relays -124 pub(crate) relay_protocol: iroh_relay::http::Protocol, -125 -126 /// An optional [`NodeMap`], to restore information about nodes. -127 pub(crate) node_map: Option<Vec<NodeAddr>>, -128 -129 /// Optional node discovery mechanism. -130 pub(crate) discovery: Option<Box<dyn Discovery>>, -131 -132 /// Optional user-defined discovery data. -133 pub(crate) discovery_user_data: Option<UserData>, +92/// How long we consider a STUN-derived endpoint valid for. UDP NAT mappings typically +93/// expire at 30 seconds, so this is a few seconds shy of that. +94const ENDPOINTS_FRESH_ENOUGH_DURATION: Duration = Duration::from_secs(27); +95 +96const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5); +97 +98/// Contains options for `MagicSock::listen`. +99#[derive(derive_more::Debug)] +100pub(crate) struct Options { +101 /// The IPv4 address to listen on. +102 /// +103 /// If set to `None` it will choose a random port and listen on `0.0.0.0:0`. +104 pub(crate) addr_v4: Option<SocketAddrV4>, +105 /// The IPv6 address to listen on. +106 /// +107 /// If set to `None` it will choose a random port and listen on `[::]:0`. +108 pub(crate) addr_v6: Option<SocketAddrV6>, +109 +110 /// Secret key for this node. +111 pub(crate) secret_key: SecretKey, +112 +113 /// The [`RelayMap`] to use, leave empty to not use a relay server. +114 pub(crate) relay_map: RelayMap, +115 +116 /// Whether to use websockets or the nonstandard legacy protocol to connect to relays +117 pub(crate) relay_protocol: iroh_relay::http::Protocol, +118 +119 /// An optional [`NodeMap`], to restore information about nodes. +120 pub(crate) node_map: Option<Vec<NodeAddr>>, +121 +122 /// Optional node discovery mechanism. +123 pub(crate) discovery: Option<Box<dyn Discovery>>, +124 +125 /// Optional user-defined discovery data. +126 pub(crate) discovery_user_data: Option<UserData>, +127 +128 /// A DNS resolver to use for resolving relay URLs. +129 /// +130 /// You can use [`crate::dns::DnsResolver::new`] for a resolver +131 /// that uses the system's DNS configuration. +132 #[cfg(not(wasm_browser))] +133 pub(crate) dns_resolver: DnsResolver, 134 -135 /// A DNS resolver to use for resolving relay URLs. -136 /// -137 /// You can use [`crate::dns::DnsResolver::new`] for a resolver -138 /// that uses the system's DNS configuration. -139 #[cfg(not(wasm_browser))] -140 pub(crate) dns_resolver: DnsResolver, -141 -142 /// Proxy configuration. -143 pub(crate) proxy_url: Option<Url>, -144 -145 /// ServerConfig for the internal QUIC endpoint -146 pub(crate) server_config: ServerConfig, -147 -148 /// Skip verification of SSL certificates from relay servers -149 /// -150 /// May only be used in tests. -151 #[cfg(any(test, feature = "test-utils"))] -152 pub(crate) insecure_skip_relay_cert_verify: bool, +135 /// Proxy configuration. +136 pub(crate) proxy_url: Option<Url>, +137 +138 /// ServerConfig for the internal QUIC endpoint +139 pub(crate) server_config: ServerConfig, +140 +141 /// Skip verification of SSL certificates from relay servers +142 /// +143 /// May only be used in tests. +144 #[cfg(any(test, feature = "test-utils"))] +145 pub(crate) insecure_skip_relay_cert_verify: bool, +146 +147 /// Configuration for what path selection to use +148 #[cfg(any(test, feature = "test-utils"))] +149 pub(crate) path_selection: PathSelection, +150 +151 pub(crate) metrics: EndpointMetrics, +152} 153 -154 /// Configuration for what path selection to use -155 #[cfg(any(test, feature = "test-utils"))] -156 pub(crate) path_selection: PathSelection, +154/// Contents of a relay message. Use a SmallVec to avoid allocations for the very +155/// common case of a single packet. +156type RelayContents = SmallVec<[Bytes; 1]>; 157 -158 pub(crate) metrics: EndpointMetrics, -159} -160 -161/// Contents of a relay message. Use a SmallVec to avoid allocations for the very -162/// common case of a single packet. -163type RelayContents = SmallVec<[Bytes; 1]>; -164 -165/// Handle for [`MagicSock`]. -166/// -167/// Dereferences to [`MagicSock`], and handles closing. -168#[derive(Clone, Debug, derive_more::Deref)] -169pub(crate) struct Handle { -170 #[deref(forward)] -171 msock: Arc<MagicSock>, -172 // Empty when closed -173 actor_tasks: Arc<Mutex<JoinSet<()>>>, -174 // quinn endpoint -175 endpoint: quinn::Endpoint, -176} -177 -178/// Iroh connectivity layer. -179/// -180/// This is responsible for routing packets to nodes based on node IDs, it will initially -181/// route packets via a relay and transparently try and establish a node-to-node -182/// connection and upgrade to it. It will also keep looking for better connections as the -183/// network details of both nodes change. -184/// -185/// It is usually only necessary to use a single [`MagicSock`] instance in an application, it -186/// means any QUIC endpoints on top will be sharing as much information about nodes as -187/// possible. -188#[derive(derive_more::Debug)] -189pub(crate) struct MagicSock { -190 actor_sender: mpsc::Sender<ActorMessage>, -191 /// String representation of the node_id of this node. -192 me: String, -193 /// Proxy -194 proxy_url: Option<Url>, -195 /// Queue to receive datagrams from relays for [`AsyncUdpSocket::poll_recv`]. -196 /// -197 /// Relay datagrams received by relays are put into this queue and consumed by -198 /// [`AsyncUdpSocket`]. This queue takes care of the wakers needed by -199 /// [`AsyncUdpSocket::poll_recv`]. -200 relay_datagram_recv_queue: Arc<RelayDatagramRecvQueue>, -201 /// Channel on which to send datagrams via a relay server. -202 relay_datagram_send_channel: RelayDatagramSendChannelSender, -203 /// Counter for ordering of [`MagicSock::poll_recv`] polling order. -204 poll_recv_counter: AtomicUsize, -205 -206 /// The DNS resolver to be used in this magicsock. -207 #[cfg(not(wasm_browser))] -208 dns_resolver: DnsResolver, -209 -210 /// Key for this node. -211 secret_key: SecretKey, -212 /// Encryption key for this node. -213 secret_encryption_key: crypto_box::SecretKey, -214 -215 /// Sockets & related state -216 #[cfg(not(wasm_browser))] -217 sockets: SocketState, -218 -219 /// Close is in progress (or done) -220 closing: AtomicBool, -221 /// Close was called. -222 closed: AtomicBool, -223 /// If the last net_report report, reports IPv6 to be available. -224 ipv6_reported: Arc<AtomicBool>, +158/// Handle for [`MagicSock`]. +159/// +160/// Dereferences to [`MagicSock`], and handles closing. +161#[derive(Clone, Debug, derive_more::Deref)] +162pub(crate) struct Handle { +163 #[deref(forward)] +164 msock: Arc<MagicSock>, +165 // Empty when closed +166 actor_tasks: Arc<Mutex<JoinSet<()>>>, +167 // quinn endpoint +168 endpoint: quinn::Endpoint, +169} +170 +171/// Iroh connectivity layer. +172/// +173/// This is responsible for routing packets to nodes based on node IDs, it will initially +174/// route packets via a relay and transparently try and establish a node-to-node +175/// connection and upgrade to it. It will also keep looking for better connections as the +176/// network details of both nodes change. +177/// +178/// It is usually only necessary to use a single [`MagicSock`] instance in an application, it +179/// means any QUIC endpoints on top will be sharing as much information about nodes as +180/// possible. +181#[derive(derive_more::Debug)] +182pub(crate) struct MagicSock { +183 actor_sender: mpsc::Sender<ActorMessage>, +184 /// String representation of the node_id of this node. +185 me: String, +186 +187 /// The DNS resolver to be used in this magicsock. +188 #[cfg(not(wasm_browser))] +189 dns_resolver: DnsResolver, +190 +191 /// Key for this node. +192 secret_key: SecretKey, +193 /// Encryption key for this node. +194 secret_encryption_key: crypto_box::SecretKey, +195 +196 /// Close is in progress (or done) +197 closing: AtomicBool, +198 /// Close was called. +199 closed: AtomicBool, +200 /// If the last net_report report, reports IPv6 to be available. +201 ipv6_reported: Arc<AtomicBool>, +202 +203 /// Zero nodes means relay is disabled. +204 relay_map: RelayMap, +205 /// Tracks the networkmap node entity for each node discovery key. +206 node_map: NodeMap, +207 /// Tracks the mapped IP addresses +208 ip_mapped_addrs: IpMappedAddresses, +209 /// NetReport client +210 net_reporter: net_report::Addr, +211 /// The state for an active DiscoKey. +212 disco_secrets: DiscoSecrets, +213 +214 /// Disco (ping) queue +215 disco_sender: mpsc::Sender<(SendAddr, PublicKey, disco::Message)>, +216 +217 /// Optional discovery service +218 discovery: Option<Box<dyn Discovery>>, +219 +220 /// Optional user-defined discover data. +221 discovery_user_data: RwLock<Option<UserData>>, +222 +223 /// Our discovered direct addresses. +224 direct_addrs: DiscoveredDirectAddrs, 225 -226 /// None (or zero nodes) means relay is disabled. -227 relay_map: RelayMap, -228 /// Nearest relay node ID; 0 means none/unknown. -229 my_relay: Watchable<Option<RelayUrl>>, -230 /// Tracks the networkmap node entity for each node discovery key. -231 node_map: NodeMap, -232 /// Tracks the mapped IP addresses -233 ip_mapped_addrs: IpMappedAddresses, -234 /// NetReport client -235 net_reporter: net_report::Addr, -236 /// The state for an active DiscoKey. -237 disco_secrets: DiscoSecrets, +226 /// Our latest net-report +227 net_report: Watchable<Option<Arc<Report>>>, +228 +229 /// List of CallMeMaybe disco messages that should be sent out after the next endpoint update +230 /// completes +231 pending_call_me_maybes: std::sync::Mutex<HashMap<PublicKey, RelayUrl>>, +232 +233 /// Indicates the direct addr update state. +234 direct_addr_update_state: DirectAddrUpdateState, +235 +236 /// Broadcast channel for listening to discovery updates. +237 discovery_subscribers: DiscoverySubscribers, 238 -239 /// UDP disco (ping) queue -240 udp_disco_sender: mpsc::Sender<(SocketAddr, PublicKey, disco::Message)>, -241 -242 /// Optional discovery service -243 discovery: Option<Box<dyn Discovery>>, -244 -245 /// Optional user-defined discover data. -246 discovery_user_data: RwLock<Option<UserData>>, -247 -248 /// Our discovered direct addresses. -249 direct_addrs: DiscoveredDirectAddrs, -250 -251 /// Our latest net-report -252 net_report: Watchable<Option<Arc<Report>>>, -253 -254 /// List of CallMeMaybe disco messages that should be sent out after the next endpoint update -255 /// completes -256 pending_call_me_maybes: std::sync::Mutex<HashMap<PublicKey, RelayUrl>>, -257 -258 /// Indicates the direct addr update state. -259 direct_addr_update_state: DirectAddrUpdateState, -260 -261 /// Skip verification of SSL certificates from relay servers -262 /// -263 /// May only be used in tests. -264 #[cfg(any(test, feature = "test-utils"))] -265 insecure_skip_relay_cert_verify: bool, -266 -267 /// Broadcast channel for listening to discovery updates. -268 discovery_subscribers: DiscoverySubscribers, +239 pub(crate) metrics: EndpointMetrics, +240 +241 local_addrs_watch: LocalAddrsWatch, +242 #[cfg(not(wasm_browser))] +243 ip_bind_addrs: Vec<SocketAddr>, +244} +245 +246#[allow(missing_docs)] +247#[common_fields({ +248 backtrace: Option<snafu::Backtrace>, +249 #[snafu(implicit)] +250 span_trace: n0_snafu::SpanTrace, +251})] +252#[derive(Debug, Snafu)] +253#[snafu(visibility(pub(crate)))] +254#[non_exhaustive] +255pub enum AddNodeAddrError { +256 #[snafu(display("Empty addressing info"))] +257 Empty {}, +258 #[snafu(display("Empty addressing info, {pruned} direct address have been pruned"))] +259 EmptyPruned { pruned: usize }, +260 #[snafu(display("Adding our own address is not supported"))] +261 OwnAddress {}, +262} +263 +264impl MagicSock { +265 /// Creates a magic [`MagicSock`] listening on [`Options::addr_v4`] and [`Options::addr_v6`]. +266 pub(crate) async fn spawn(opts: Options) -> Result<Handle, CreateHandleError> { +267 Handle::new(opts).await +268 } 269 -270 pub(crate) metrics: EndpointMetrics, -271} -272 -273/// Sockets and related state, grouped together so we can cfg them out for browsers. -274#[cfg(not(wasm_browser))] -275#[derive(Debug)] -276pub(crate) struct SocketState { -277 /// Port configured for the ipv4 socket. Can be 0 -278 port: AtomicU16, -279 /// UDP IPv4 socket -280 v4: UdpConn, -281 /// UDP IPv6 socket -282 v6: Option<UdpConn>, -283 /// Cached version of the Ipv4 and Ipv6 addrs of the current connection. -284 local_addrs: std::sync::RwLock<(SocketAddr, Option<SocketAddr>)>, -285} +270 /// Returns the relay node we are connected to, that has the best latency. +271 /// +272 /// If `None`, then we are not connected to any relay nodes. +273 pub(crate) fn my_relay(&self) -> Option<RelayUrl> { +274 self.local_addr().into_iter().find_map(|a| { +275 if let transports::Addr::Relay(url, _) = a { +276 Some(url) +277 } else { +278 None +279 } +280 }) +281 } +282 +283 fn is_closing(&self) -> bool { +284 self.closing.load(Ordering::Relaxed) +285 } 286 -287#[allow(missing_docs)] -288#[common_fields({ -289 backtrace: Option<snafu::Backtrace>, -290 #[snafu(implicit)] -291 span_trace: n0_snafu::SpanTrace, -292})] -293#[derive(Debug, Snafu)] -294#[snafu(visibility(pub(crate)))] -295#[non_exhaustive] -296pub enum AddNodeAddrError { -297 #[snafu(display("Empty addressing info"))] -298 Empty {}, -299 #[snafu(display("Empty addressing info, {pruned} direct address have been pruned"))] -300 EmptyPruned { pruned: usize }, -301 #[snafu(display("Adding our own address is not supported"))] -302 OwnAddress {}, -303} +287 pub(crate) fn is_closed(&self) -> bool { +288 self.closed.load(Ordering::SeqCst) +289 } +290 +291 fn public_key(&self) -> PublicKey { +292 self.secret_key.public() +293 } +294 +295 /// Get the cached version of addresses. +296 pub(crate) fn local_addr(&self) -> Vec<transports::Addr> { +297 self.local_addrs_watch.get().expect("disconnected") +298 } +299 +300 #[cfg(not(wasm_browser))] +301 fn ip_bind_addrs(&self) -> &[SocketAddr] { +302 &self.ip_bind_addrs +303 } 304 -305impl MagicSock { -306 /// Creates a magic [`MagicSock`] listening on [`Options::addr_v4`] and [`Options::addr_v6`]. -307 pub(crate) async fn spawn(opts: Options) -> Result<Handle, CreateHandleError> { -308 Handle::new(opts).await -309 } +305 fn ip_local_addrs(&self) -> impl Iterator<Item = SocketAddr> { +306 self.local_addr() +307 .into_iter() +308 .filter_map(|addr| addr.into_socket_addr()) +309 } 310 -311 /// Returns the relay node we are connected to, that has the best latency. -312 /// -313 /// If `None`, then we are not connected to any relay nodes. -314 pub(crate) fn my_relay(&self) -> Option<RelayUrl> { -315 self.my_relay.get() +311 /// Returns `true` if we have at least one candidate address where we can send packets to. +312 pub(crate) fn has_send_address(&self, node_key: PublicKey) -> bool { +313 self.remote_info(node_key) +314 .map(|info| info.has_send_address()) +315 .unwrap_or(false) 316 } 317 -318 /// Get the current proxy configuration. -319 pub(crate) fn proxy_url(&self) -> Option<&Url> { -320 self.proxy_url.as_ref() +318 /// Return the [`RemoteInfo`]s of all nodes in the node map. +319 pub(crate) fn list_remote_infos(&self) -> Vec<RemoteInfo> { +320 self.node_map.list_remote_infos(Instant::now()) 321 } 322 -323 /// Sets the relay node with the best latency. -324 /// -325 /// If we are not connected to any relay nodes, set this to `None`. -326 fn set_my_relay(&self, my_relay: Option<RelayUrl>) -> Option<RelayUrl> { -327 self.my_relay.set(my_relay).unwrap_or_else(|e| e) -328 } -329 -330 fn is_closing(&self) -> bool { -331 self.closing.load(Ordering::Relaxed) -332 } -333 -334 pub(crate) fn is_closed(&self) -> bool { -335 self.closed.load(Ordering::SeqCst) -336 } -337 -338 fn public_key(&self) -> PublicKey { -339 self.secret_key.public() -340 } -341 -342 /// Get the cached version of the Ipv4 and Ipv6 addrs of the current connection. -343 #[cfg(not(wasm_browser))] -344 pub(crate) fn local_addr(&self) -> (SocketAddr, Option<SocketAddr>) { -345 *self.sockets.local_addrs.read().expect("not poisoned") -346 } -347 -348 /// Returns `true` if we have at least one candidate address where we can send packets to. -349 pub(crate) fn has_send_address(&self, node_key: PublicKey) -> bool { -350 self.remote_info(node_key) -351 .map(|info| info.has_send_address()) -352 .unwrap_or(false) -353 } -354 -355 /// Return the [`RemoteInfo`]s of all nodes in the node map. -356 pub(crate) fn list_remote_infos(&self) -> Vec<RemoteInfo> { -357 self.node_map.list_remote_infos(Instant::now()) -358 } -359 -360 /// Return the [`RemoteInfo`] for a single node in the node map. -361 pub(crate) fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo> { -362 self.node_map.remote_info(node_id) +323 /// Return the [`RemoteInfo`] for a single node in the node map. +324 pub(crate) fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo> { +325 self.node_map.remote_info(node_id) +326 } +327 +328 /// Returns a [`Watcher`] for this socket's direct addresses. +329 /// +330 /// The [`MagicSock`] continuously monitors the direct addresses, the network addresses +331 /// it might be able to be contacted on, for changes. Whenever changes are detected +332 /// this [`Watcher`] will yield a new list of addresses. +333 /// +334 /// Upon the first creation on the [`MagicSock`] it may not yet have completed a first +335 /// direct addresses discovery, in this case the current item in this [`Watcher`] will be +336 /// [`None`]. Once the first set of direct addresses are discovered the [`Watcher`] will +337 /// store [`Some`] set of addresses. +338 /// +339 /// To get the current direct addresses, use [`Watcher::initialized`]. +340 /// +341 /// [`Watcher`]: n0_watcher::Watcher +342 /// [`Watcher::initialized`]: n0_watcher::Watcher::initialized +343 pub(crate) fn direct_addresses(&self) -> n0_watcher::Direct<Option<BTreeSet<DirectAddr>>> { +344 self.direct_addrs.addrs.watch() +345 } +346 +347 /// Returns a [`Watcher`] for this socket's net-report. +348 /// +349 /// The [`MagicSock`] continuously monitors the network conditions for changes. +350 /// Whenever changes are detected this [`Watcher`] will yield a new report. +351 /// +352 /// Upon the first creation on the [`MagicSock`] it may not yet have completed +353 /// a first net-report. In this case, the current item in this [`Watcher`] will +354 /// be [`None`]. Once the first report has been run, the [`Watcher`] will +355 /// store [`Some`] report. +356 /// +357 /// To get the current `net-report`, use [`Watcher::initialized`]. +358 /// +359 /// [`Watcher`]: n0_watcher::Watcher +360 /// [`Watcher::initialized`]: n0_watcher::Watcher::initialized +361 pub(crate) fn net_report(&self) -> n0_watcher::Direct<Option<Arc<Report>>> { +362 self.net_report.watch() 363 } 364 -365 /// Returns a [`Watcher`] for this socket's direct addresses. +365 /// Watch for changes to the home relay. 366 /// -367 /// The [`MagicSock`] continuously monitors the direct addresses, the network addresses -368 /// it might be able to be contacted on, for changes. Whenever changes are detected -369 /// this [`Watcher`] will yield a new list of addresses. -370 /// -371 /// Upon the first creation on the [`MagicSock`] it may not yet have completed a first -372 /// direct addresses discovery, in this case the current item in this [`Watcher`] will be -373 /// [`None`]. Once the first set of direct addresses are discovered the [`Watcher`] will -374 /// store [`Some`] set of addresses. -375 /// -376 /// To get the current direct addresses, use [`Watcher::initialized`]. -377 /// -378 /// [`Watcher`]: crate::watcher::Watcher -379 /// [`Watcher::initialized`]: crate::watcher::Watcher::initialized -380 pub(crate) fn direct_addresses(&self) -> watcher::Direct<Option<BTreeSet<DirectAddr>>> { -381 self.direct_addrs.addrs.watch() -382 } -383 -384 /// Returns a [`Watcher`] for this socket's net-report. -385 /// -386 /// The [`MagicSock`] continuously monitors the network conditions for changes. -387 /// Whenever changes are detected this [`Watcher`] will yield a new report. -388 /// -389 /// Upon the first creation on the [`MagicSock`] it may not yet have completed -390 /// a first net-report. In this case, the current item in this [`Watcher`] will -391 /// be [`None`]. Once the first report has been run, the [`Watcher`] will -392 /// store [`Some`] report. -393 /// -394 /// To get the current `net-report`, use [`Watcher::initialized`]. -395 /// -396 /// [`Watcher`]: crate::watcher::Watcher -397 /// [`Watcher::initialized`]: crate::watcher::Watcher::initialized -398 pub(crate) fn net_report(&self) -> watcher::Direct<Option<Arc<Report>>> { -399 self.net_report.watch() -400 } -401 -402 /// Watch for changes to the home relay. -403 /// -404 /// Note that this can be used to wait for the initial home relay to be known using -405 /// [`Watcher::initialized`]. -406 /// -407 /// [`Watcher`]: crate::watcher::Watcher -408 /// [`Watcher::initialized`]: crate::watcher::Watcher::initialized -409 pub(crate) fn home_relay(&self) -> watcher::Direct<Option<RelayUrl>> { -410 self.my_relay.watch() -411 } -412 -413 /// Returns a [`watcher::Direct`] that reports the [`ConnectionType`] we have to the -414 /// given `node_id`. -415 /// -416 /// This gets us a copy of the [`watcher::Direct`] for the [`Watchable`] with a [`ConnectionType`] -417 /// that the `NodeMap` stores for each `node_id`'s endpoint. -418 /// -419 /// # Errors -420 /// -421 /// Will return `None` if there is no address information known about the -422 /// given `node_id`. -423 pub(crate) fn conn_type(&self, node_id: NodeId) -> Option<watcher::Direct<ConnectionType>> { -424 self.node_map.conn_type(node_id) -425 } -426 -427 /// Returns the socket address which can be used by the QUIC layer to dial this node. -428 pub(crate) fn get_mapping_addr(&self, node_id: NodeId) -> Option<NodeIdMappedAddr> { -429 self.node_map.get_quic_mapped_addr_for_node_key(node_id) -430 } -431 -432 /// Add addresses for a node to the magic socket's addresbook. -433 #[instrument(skip_all, fields(me = %self.me))] -434 pub fn add_node_addr( -435 &self, -436 mut addr: NodeAddr, -437 source: node_map::Source, -438 ) -> Result<(), AddNodeAddrError> { -439 let mut pruned: usize = 0; -440 for my_addr in self.direct_addrs.sockaddrs() { -441 if addr.direct_addresses.remove(&my_addr) { -442 warn!( node_id=addr.node_id.fmt_short(), %my_addr, %source, "not adding our addr for node"); -443 pruned += 1; -444 } -445 } -446 if !addr.is_empty() { -447 self.node_map -448 .add_node_addr(addr, source, &self.metrics.magicsock); -449 Ok(()) -450 } else if pruned != 0 { -451 Err(EmptyPrunedSnafu { pruned }.build()) -452 } else { -453 Err(EmptySnafu.build()) -454 } -455 } -456 -457 /// Stores a new set of direct addresses. -458 /// -459 /// If the direct addresses have changed from the previous set, they are published to -460 /// discovery. -461 pub(super) fn store_direct_addresses(&self, addrs: BTreeSet<DirectAddr>) { -462 let updated = self.direct_addrs.update(addrs); -463 if updated { -464 self.node_map -465 .on_direct_addr_discovered(self.direct_addrs.sockaddrs()); -466 self.publish_my_addr(); -467 } -468 } -469 -470 /// Get a reference to the DNS resolver used in this [`MagicSock`]. -471 #[cfg(not(wasm_browser))] -472 pub(crate) fn dns_resolver(&self) -> &DnsResolver { -473 &self.dns_resolver +367 /// Note that this can be used to wait for the initial home relay to be known using +368 /// [`Watcher::initialized`]. +369 pub(crate) fn home_relay(&self) -> impl Watcher<Value = Vec<RelayUrl>> { +370 let res = self.local_addrs_watch.clone().map(|addrs| { +371 addrs +372 .into_iter() +373 .filter_map(|addr| { +374 if let transports::Addr::Relay(url, _) = addr { +375 Some(url) +376 } else { +377 None +378 } +379 }) +380 .collect() +381 }); +382 res.expect("disconnected") +383 } +384 +385 /// Returns a [`n0_watcher::Direct`] that reports the [`ConnectionType`] we have to the +386 /// given `node_id`. +387 /// +388 /// This gets us a copy of the [`n0_watcher::Direct`] for the [`Watchable`] with a [`ConnectionType`] +389 /// that the `NodeMap` stores for each `node_id`'s endpoint. +390 /// +391 /// # Errors +392 /// +393 /// Will return `None` if there is no address information known about the +394 /// given `node_id`. +395 pub(crate) fn conn_type(&self, node_id: NodeId) -> Option<n0_watcher::Direct<ConnectionType>> { +396 self.node_map.conn_type(node_id) +397 } +398 +399 /// Returns the socket address which can be used by the QUIC layer to dial this node. +400 pub(crate) fn get_mapping_addr(&self, node_id: NodeId) -> Option<NodeIdMappedAddr> { +401 self.node_map.get_quic_mapped_addr_for_node_key(node_id) +402 } +403 +404 /// Add addresses for a node to the magic socket's addresbook. +405 #[instrument(skip_all, fields(me = %self.me))] +406 pub fn add_node_addr( +407 &self, +408 mut addr: NodeAddr, +409 source: node_map::Source, +410 ) -> Result<(), AddNodeAddrError> { +411 let mut pruned: usize = 0; +412 for my_addr in self.direct_addrs.sockaddrs() { +413 if addr.direct_addresses.remove(&my_addr) { +414 warn!( node_id=addr.node_id.fmt_short(), %my_addr, %source, "not adding our addr for node"); +415 pruned += 1; +416 } +417 } +418 if !addr.is_empty() { +419 self.node_map +420 .add_node_addr(addr, source, &self.metrics.magicsock); +421 Ok(()) +422 } else if pruned != 0 { +423 Err(EmptyPrunedSnafu { pruned }.build()) +424 } else { +425 Err(EmptySnafu.build()) +426 } +427 } +428 +429 /// Stores a new set of direct addresses. +430 /// +431 /// If the direct addresses have changed from the previous set, they are published to +432 /// discovery. +433 pub(super) fn store_direct_addresses(&self, addrs: BTreeSet<DirectAddr>) { +434 let updated = self.direct_addrs.update(addrs); +435 if updated { +436 self.node_map +437 .on_direct_addr_discovered(self.direct_addrs.sockaddrs()); +438 self.publish_my_addr(); +439 } +440 } +441 +442 /// Get a reference to the DNS resolver used in this [`MagicSock`]. +443 #[cfg(not(wasm_browser))] +444 pub(crate) fn dns_resolver(&self) -> &DnsResolver { +445 &self.dns_resolver +446 } +447 +448 /// Reference to optional discovery service +449 pub(crate) fn discovery(&self) -> Option<&dyn Discovery> { +450 self.discovery.as_ref().map(Box::as_ref) +451 } +452 +453 /// Updates the user-defined discovery data for this node. +454 pub(crate) fn set_user_data_for_discovery(&self, user_data: Option<UserData>) { +455 let mut guard = self.discovery_user_data.write().expect("lock poisened"); +456 if *guard != user_data { +457 *guard = user_data; +458 drop(guard); +459 self.publish_my_addr(); +460 } +461 } +462 +463 /// Call to notify the system of potential network changes. +464 pub(crate) async fn network_change(&self) { +465 self.actor_sender +466 .send(ActorMessage::NetworkChange) +467 .await +468 .ok(); +469 } +470 +471 /// Returns a reference to the subscribers channel for discovery events. +472 pub(crate) fn discovery_subscribers(&self) -> &DiscoverySubscribers { +473 &self.discovery_subscribers 474 } 475 -476 /// Reference to optional discovery service -477 pub(crate) fn discovery(&self) -> Option<&dyn Discovery> { -478 self.discovery.as_ref().map(Box::as_ref) -479 } -480 -481 /// Updates the user-defined discovery data for this node. -482 pub(crate) fn set_user_data_for_discovery(&self, user_data: Option<UserData>) { -483 let mut guard = self.discovery_user_data.write().expect("lock poisened"); -484 if *guard != user_data { -485 *guard = user_data; -486 drop(guard); -487 self.publish_my_addr(); -488 } -489 } -490 -491 /// Call to notify the system of potential network changes. -492 pub(crate) async fn network_change(&self) { -493 self.actor_sender -494 .send(ActorMessage::NetworkChange) -495 .await -496 .ok(); -497 } -498 -499 /// Returns a reference to the subscribers channel for discovery events. -500 pub(crate) fn discovery_subscribers(&self) -> &DiscoverySubscribers { -501 &self.discovery_subscribers -502 } -503 -504 #[cfg(test)] -505 async fn force_network_change(&self, is_major: bool) { -506 self.actor_sender -507 .send(ActorMessage::ForceNetworkChange(is_major)) -508 .await -509 .ok(); -510 } -511 -512 #[cfg(not(wasm_browser))] -513 #[cfg_attr(windows, allow(dead_code))] -514 fn normalized_local_addr(&self) -> io::Result<SocketAddr> { -515 let (v4, v6) = self.local_addr(); -516 let addr = if let Some(v6) = v6 { v6 } else { v4 }; -517 Ok(addr) -518 } -519 -520 /// Implementation for AsyncUdpSocket::try_send -521 #[instrument(skip_all)] -522 fn try_send(&self, transmit: &quinn_udp::Transmit) -> io::Result<()> { -523 self.metrics -524 .magicsock -525 .send_data -526 .inc_by(transmit.contents.len() as _); +476 #[cfg(test)] +477 async fn force_network_change(&self, is_major: bool) { +478 self.actor_sender +479 .send(ActorMessage::ForceNetworkChange(is_major)) +480 .await +481 .ok(); +482 } +483 +484 #[cfg_attr(windows, allow(dead_code))] +485 fn normalized_local_addr(&self) -> io::Result<SocketAddr> { +486 let addrs = self.local_addrs_watch.get().expect("disconnected"); +487 +488 let mut ipv4_addr = None; +489 for addr in addrs { +490 let Some(addr) = addr.into_socket_addr() else { +491 continue; +492 }; +493 if addr.is_ipv6() { +494 return Ok(addr); +495 } +496 if addr.is_ipv4() && ipv4_addr.is_none() { +497 ipv4_addr.replace(addr); +498 } +499 } +500 match ipv4_addr { +501 Some(addr) => Ok(addr), +502 None => Err(io::Error::other("no valid socket available")), +503 } +504 } +505 +506 /// Searches the `node_map` to determine the current transports to be used. +507 #[instrument(skip_all)] +508 fn prepare_send( +509 &self, +510 transmit: &quinn_udp::Transmit, +511 ) -> io::Result<SmallVec<[transports::Addr; 3]>> { +512 self.metrics +513 .magicsock +514 .send_data +515 .inc_by(transmit.contents.len() as _); +516 +517 if self.is_closed() { +518 self.metrics +519 .magicsock +520 .send_data_network_down +521 .inc_by(transmit.contents.len() as _); +522 return Err(io::Error::new( +523 io::ErrorKind::NotConnected, +524 "connection closed", +525 )); +526 } 527 -528 if self.is_closed() { -529 self.metrics -530 .magicsock -531 .send_data_network_down -532 .inc_by(transmit.contents.len() as _); -533 return Err(io::Error::new( -534 io::ErrorKind::NotConnected, -535 "connection closed", -536 )); -537 } -538 match MappedAddr::from(transmit.destination) { -539 MappedAddr::None(dest) => { -540 error!(%dest, "Cannot convert to a mapped address, voiding transmit."); -541 // Returning Ok here means we let QUIC timeout. -542 // Returning an error would immediately fail a connection. -543 // The philosophy of quinn-udp is that a UDP connection could -544 // come back at any time or missing should be transient so chooses to let -545 // these kind of errors time out. See test_try_send_no_send_addr to try -546 // this out. -547 Ok(()) -548 } -549 MappedAddr::NodeId(dest) => { -550 trace!( -551 dst = %dest, -552 src = ?transmit.src_ip, -553 len = %transmit.contents.len(), -554 "sending", -555 ); -556 -557 // Get the node's relay address and best direct address, as well -558 // as any pings that need to be sent for hole-punching purposes. -559 let mut transmit = transmit.clone(); -560 match self.node_map.get_send_addrs( -561 dest, -562 self.ipv6_reported.load(Ordering::Relaxed), -563 &self.metrics.magicsock, -564 ) { -565 Some((node_id, udp_addr, relay_url, msgs)) => { -566 let mut pings_sent = false; -567 // If we have pings to send, we *have* to send them out first. -568 if !msgs.is_empty() { -569 if let Err(err) = self.try_send_ping_actions(msgs) { -570 warn!( -571 node = %node_id.fmt_short(), -572 "failed to handle ping actions: {err:#}", -573 ); -574 } -575 pings_sent = true; -576 } -577 -578 let mut udp_sent = false; -579 let mut udp_error: Option<io::Error> = None; -580 let mut relay_sent = false; -581 let mut relay_error = None; -582 -583 // send udp -584 #[cfg(not(wasm_browser))] -585 if let Some(addr) = udp_addr { -586 // rewrite target address -587 transmit.destination = addr; -588 match self.try_send_udp(addr, &transmit) { -589 Ok(()) => { -590 trace!(node = %node_id.fmt_short(), dst = %addr, -591 "sent transmit over UDP"); -592 udp_sent = true; -593 } -594 Err(err) => { -595 // No need to print "WouldBlock" errors to the console -596 if err.kind() != io::ErrorKind::WouldBlock { -597 warn!( -598 node = %node_id.fmt_short(), -599 dst = %addr, -600 "failed to send udp: {err:#}" -601 ); -602 } -603 udp_error = Some(err); -604 } -605 } -606 } -607 -608 // send relay -609 if let Some(ref relay_url) = relay_url { -610 match self.try_send_relay(relay_url, node_id, split_packets(&transmit)) -611 { -612 Ok(()) => { -613 relay_sent = true; -614 } -615 Err(err) => { -616 relay_error = Some(err); -617 } -618 } -619 } -620 -621 #[cfg(not(wasm_browser))] -622 let udp_pending = udp_error -623 .as_ref() -624 .map(|err| err.kind() == io::ErrorKind::WouldBlock) -625 .unwrap_or_default(); -626 #[cfg(wasm_browser)] -627 let udp_pending = false; -628 let relay_pending = relay_error -629 .as_ref() -630 .map(|err| err.kind() == io::ErrorKind::WouldBlock) -631 .unwrap_or_default(); -632 if udp_pending && relay_pending { -633 // Handle backpressure. -634 return Err(io::Error::new(io::ErrorKind::WouldBlock, "pending")); -635 } else { -636 if relay_sent || udp_sent { -637 trace!( -638 node = %node_id.fmt_short(), -639 send_udp = ?udp_addr, -640 send_relay = ?relay_url, -641 "sent transmit", -642 ); -643 } else if !pings_sent { -644 // Returning Ok here means we let QUIC handle a timeout for a lost -645 // packet, same would happen if we returned any errors. The -646 // philosophy of quinn-udp is that a UDP connection could come back -647 // at any time so these errors should be treated as transient and -648 // are just timeouts. Hence we opt for returning Ok. See -649 // test_try_send_no_udp_addr_or_relay_url to explore this further. -650 debug!( -651 node = %node_id.fmt_short(), -652 "no UDP or relay paths available for node, voiding transmit", -653 ); -654 // We log this as debug instead of error, because this is a -655 // situation that comes up under normal operation. If this were an -656 // error log, it would unnecessarily pollute logs. -657 // This situation happens essentially when `pings_sent` is false, -658 // `relay_url` is `None`, so `relay_sent` is false, and the UDP -659 // path is blocking, so `udp_sent` is false and `udp_pending` is -660 // true. -661 // Alternatively returning a WouldBlock error here would -662 // potentially needlessly block sending on the relay path for the -663 // next datagram. -664 } -665 return Ok(()); -666 } -667 } -668 None => { -669 error!(%dest, "no NodeState for mapped address, dropping transmit"); -670 // Returning Ok here means we let QUIC timeout. Returning WouldBlock -671 // triggers a hot loop. Returning an error would immediately fail a -672 // connection. The philosophy of quinn-udp is that a UDP connection could -673 // come back at any time or missing should be transient so chooses to let -674 // these kind of errors time out. See test_try_send_no_send_addr to try -675 // this out. -676 return Ok(()); -677 } -678 } -679 } -680 #[cfg(not(wasm_browser))] -681 MappedAddr::Ip(dest) => { -682 trace!( -683 dst = %dest, -684 src = ?transmit.src_ip, -685 len = %transmit.contents.len(), -686 "sending", -687 ); -688 -689 // Check if this is a known IpMappedAddr, and if so, send over UDP -690 let mut transmit = transmit.clone(); -691 -692 // Get the socket addr -693 match self.ip_mapped_addrs.get_ip_addr(&dest) { -694 Some(addr) => { -695 // rewrite target address -696 transmit.destination = addr; -697 // send udp -698 match self.try_send_udp(addr, &transmit) { -699 Ok(()) => { -700 trace!(dst = %addr, -701 "sent IpMapped transmit over UDP"); -702 } -703 Err(err) => { -704 // No need to print "WouldBlock" errors to the console -705 if err.kind() == io::ErrorKind::WouldBlock { -706 return Err(io::Error::new( -707 io::ErrorKind::WouldBlock, -708 "pending", -709 )); -710 } else { -711 warn!( -712 dst = %addr, -713 "failed to send IpMapped message over udp: {err:#}" -714 ); -715 } -716 } -717 } -718 return Ok(()); -719 } -720 None => { -721 error!(%dest, "unknown mapped address, dropping transmit"); -722 // Returning Ok here means we let QUIC timeout. -723 // Returning an error would immediately fail a connection. -724 // The philosophy of quinn-udp is that a UDP connection could -725 // come back at any time or missing should be transient so chooses to let -726 // these kind of errors time out. See test_try_send_no_send_addr to try -727 // this out. -728 return Ok(()); -729 } -730 } -731 } -732 } -733 } -734 -735 fn try_send_relay( -736 &self, -737 url: &RelayUrl, -738 node: NodeId, -739 contents: RelayContents, -740 ) -> io::Result<()> { -741 trace!( -742 node = %node.fmt_short(), -743 relay_url = %url, -744 count = contents.len(), -745 len = contents.iter().map(|c| c.len()).sum::<usize>(), -746 "send relay", -747 ); -748 let msg = RelaySendItem { -749 remote_node: node, -750 url: url.clone(), -751 datagrams: contents, -752 }; -753 match self.relay_datagram_send_channel.try_send(msg) { -754 Ok(_) => { -755 trace!(node = %node.fmt_short(), relay_url = %url, -756 "send relay: message queued"); -757 Ok(()) +528 let mut active_paths = SmallVec::<[_; 3]>::new(); +529 +530 match MappedAddr::from(transmit.destination) { +531 MappedAddr::None(dest) => { +532 error!(%dest, "Cannot convert to a mapped address."); +533 } +534 MappedAddr::NodeId(dest) => { +535 trace!( +536 dst = %dest, +537 src = ?transmit.src_ip, +538 len = %transmit.contents.len(), +539 "sending", +540 ); +541 +542 // Get the node's relay address and best direct address, as well +543 // as any pings that need to be sent for hole-punching purposes. +544 match self.node_map.get_send_addrs( +545 dest, +546 self.ipv6_reported.load(Ordering::Relaxed), +547 &self.metrics.magicsock, +548 ) { +549 Some((node_id, udp_addr, relay_url, ping_actions)) => { +550 if !ping_actions.is_empty() { +551 self.actor_sender +552 .try_send(ActorMessage::PingActions(ping_actions)) +553 .ok(); +554 } +555 if let Some(addr) = udp_addr { +556 active_paths.push(transports::Addr::from(addr)); +557 } +558 if let Some(url) = relay_url { +559 active_paths.push(transports::Addr::Relay(url, node_id)); +560 } +561 } +562 None => { +563 error!(%dest, "no NodeState for mapped address"); +564 } +565 } +566 } +567 #[cfg(not(wasm_browser))] +568 MappedAddr::Ip(dest) => { +569 trace!( +570 dst = %dest, +571 src = ?transmit.src_ip, +572 len = %transmit.contents.len(), +573 "sending", +574 ); +575 +576 // Check if this is a known IpMappedAddr, and if so, send over UDP +577 // Get the socket addr +578 match self.ip_mapped_addrs.get_ip_addr(&dest) { +579 Some(addr) => { +580 active_paths.push(transports::Addr::from(addr)); +581 } +582 None => { +583 error!(%dest, "unknown mapped address"); +584 } +585 } +586 } +587 } +588 +589 Ok(active_paths) +590 } +591 +592 /// Process datagrams received from UDP sockets. +593 /// +594 /// All the `bufs` and `metas` should have initialized packets in them. +595 /// +596 /// This fixes up the datagrams to use the correct [`NodeIdMappedAddr`] and extracts DISCO +597 /// packets, processing them inside the magic socket. +598 fn process_datagrams( +599 &self, +600 bufs: &mut [io::IoSliceMut<'_>], +601 metas: &mut [quinn_udp::RecvMeta], +602 source_addrs: &[transports::Addr], +603 ) { +604 debug_assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas"); +605 debug_assert_eq!( +606 bufs.len(), +607 source_addrs.len(), +608 "non matching bufs & source_addrs" +609 ); +610 +611 // Adding the IP address we received something on results in Quinn using this +612 // address on the send path to send from. However we let Quinn use a +613 // NodeIdMappedAddress, not a real address. So we used to substitute our bind address +614 // here so that Quinn would send on the right address. But that would sometimes +615 // result in the wrong address family and Windows trips up on that. +616 // +617 // What should be done is that this dst_ip from the RecvMeta is stored in the +618 // NodeState/PathState. Then on the send path it should be retrieved from the +619 // NodeState/PathSate together with the send address and substituted at send time. +620 // This is relevant for IPv6 link-local addresses where the OS otherwise does not +621 // know which interface to send from. +622 #[cfg(not(windows))] +623 let dst_ip = self.normalized_local_addr().ok().map(|addr| addr.ip()); +624 // Reasoning for this here: +625 // https://github.com/n0-computer/iroh/pull/2595#issuecomment-2290947319 +626 #[cfg(windows)] +627 let dst_ip = None; +628 +629 let mut quic_packets_total = 0; +630 +631 for ((quinn_meta, buf), source_addr) in metas +632 .iter_mut() +633 .zip(bufs.iter_mut()) +634 .zip(source_addrs.iter()) +635 { +636 let mut buf_contains_quic_datagrams = false; +637 let mut quic_datagram_count = 0; +638 if quinn_meta.len > quinn_meta.stride { +639 trace!(%quinn_meta.len, %quinn_meta.stride, "GRO datagram received"); +640 self.metrics.magicsock.recv_gro_datagrams.inc(); +641 } +642 +643 // Chunk through the datagrams in this GRO payload to find disco and stun +644 // packets and forward them to the actor +645 for datagram in buf[..quinn_meta.len].chunks_mut(quinn_meta.stride) { +646 if datagram.len() < quinn_meta.stride { +647 trace!( +648 len = %datagram.len(), +649 %quinn_meta.stride, +650 "Last GRO datagram smaller than stride", +651 ); +652 } +653 +654 // Detect DISCO and STUN datagrams and process them. Overwrite the first +655 // byte of those packets with zero to make Quinn ignore the packet. This +656 // relies on quinn::EndpointConfig::grease_quic_bit being set to `false`, +657 // which we do in Endpoint::bind. +658 if source_addr.is_ip() && stun::is(datagram) { +659 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: stun packet"); +660 let packet2 = Bytes::copy_from_slice(datagram); +661 self.net_reporter.receive_stun_packet( +662 packet2, +663 source_addr.clone().into_socket_addr().expect("checked"), +664 ); +665 datagram[0] = 0u8; +666 } else if let Some((sender, sealed_box)) = disco::source_and_box(datagram) { +667 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: disco packet"); +668 self.handle_disco_message(sender, sealed_box, source_addr); +669 datagram[0] = 0u8; +670 } else { +671 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: quic packet"); +672 match source_addr { +673 transports::Addr::Ip(SocketAddr::V4(..)) => { +674 self.metrics +675 .magicsock +676 .recv_data_ipv4 +677 .inc_by(datagram.len() as _); +678 } +679 transports::Addr::Ip(SocketAddr::V6(..)) => { +680 self.metrics +681 .magicsock +682 .recv_data_ipv6 +683 .inc_by(datagram.len() as _); +684 } +685 transports::Addr::Relay(..) => { +686 self.metrics +687 .magicsock +688 .recv_data_relay +689 .inc_by(datagram.len() as _); +690 } +691 } +692 +693 quic_datagram_count += 1; +694 buf_contains_quic_datagrams = true; +695 } +696 } +697 +698 if buf_contains_quic_datagrams { +699 match source_addr { +700 #[cfg(wasm_browser)] +701 transports::Addr::Ip(_addr) => { +702 panic!("cannot use IP based addressing in the browser"); +703 } +704 #[cfg(not(wasm_browser))] +705 transports::Addr::Ip(addr) => { +706 // UDP +707 +708 // Update the NodeMap and remap RecvMeta to the NodeIdMappedAddr. +709 match self.node_map.receive_udp(*addr) { +710 None => { +711 // Check if this address is mapped to an IpMappedAddr +712 if let Some(ip_mapped_addr) = +713 self.ip_mapped_addrs.get_mapped_addr(addr) +714 { +715 trace!( +716 src = %addr, +717 count = %quic_datagram_count, +718 len = quinn_meta.len, +719 "UDP recv QUIC address discovery packets", +720 ); +721 quic_packets_total += quic_datagram_count; +722 quinn_meta.addr = ip_mapped_addr.private_socket_addr(); +723 } else { +724 warn!( +725 src = %addr, +726 count = %quic_datagram_count, +727 len = quinn_meta.len, +728 "UDP recv quic packets: no node state found, skipping", +729 ); +730 // If we have no node state for the from addr, set len to 0 to make +731 // quinn skip the buf completely. +732 quinn_meta.len = 0; +733 } +734 } +735 Some((node_id, quic_mapped_addr)) => { +736 trace!( +737 src = %addr, +738 node = %node_id.fmt_short(), +739 count = %quic_datagram_count, +740 len = quinn_meta.len, +741 "UDP recv quic packets", +742 ); +743 quic_packets_total += quic_datagram_count; +744 quinn_meta.addr = quic_mapped_addr.private_socket_addr(); +745 } +746 } +747 } +748 transports::Addr::Relay(src_url, src_node) => { +749 // Relay +750 let quic_mapped_addr = self.node_map.receive_relay(src_url, *src_node); +751 quinn_meta.addr = quic_mapped_addr.private_socket_addr(); +752 } +753 } +754 } else { +755 // If all datagrams in this buf are DISCO or STUN, set len to zero to make +756 // Quinn skip the buf completely. +757 quinn_meta.len = 0; 758 } -759 Err(mpsc::error::TrySendError::Closed(_)) => { -760 error!(node = %node.fmt_short(), relay_url = %url, -761 "send relay: message dropped, channel to actor is closed"); -762 Err(io::Error::new( -763 io::ErrorKind::ConnectionReset, -764 "channel to actor is closed", -765 )) -766 } -767 Err(mpsc::error::TrySendError::Full(_)) => { -768 warn!(node = %node.fmt_short(), relay_url = %url, -769 "send relay: message dropped, channel to actor is full"); -770 Err(io::Error::new( -771 io::ErrorKind::WouldBlock, -772 "channel to actor is full", -773 )) -774 } -775 } -776 } -777 -778 #[cfg(not(wasm_browser))] -779 fn try_send_udp(&self, addr: SocketAddr, transmit: &quinn_udp::Transmit) -> io::Result<()> { -780 let conn = self.conn_for_addr(addr)?; -781 conn.try_send(transmit)?; -782 let total_bytes: u64 = transmit.contents.len() as u64; -783 if addr.is_ipv6() { -784 self.metrics.magicsock.send_ipv6.inc_by(total_bytes); -785 } else { -786 self.metrics.magicsock.send_ipv4.inc_by(total_bytes); -787 } -788 Ok(()) -789 } -790 -791 #[cfg(not(wasm_browser))] -792 fn conn_for_addr(&self, addr: SocketAddr) -> io::Result<&UdpConn> { -793 let sock = match addr { -794 SocketAddr::V4(_) => &self.sockets.v4, -795 SocketAddr::V6(_) => self -796 .sockets -797 .v6 -798 .as_ref() -799 .ok_or(io::Error::other("no IPv6 connection"))?, -800 }; -801 Ok(sock) -802 } -803 -804 /// NOTE: Receiving on a [`Self::closed`] socket will return [`Poll::Pending`] indefinitely. -805 #[instrument(skip_all)] -806 #[cfg(not(wasm_browser))] -807 fn poll_recv( -808 &self, -809 cx: &mut Context, -810 bufs: &mut [io::IoSliceMut<'_>], -811 metas: &mut [quinn_udp::RecvMeta], -812 ) -> Poll<io::Result<usize>> { -813 debug_assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas"); -814 if self.is_closed() { -815 return Poll::Pending; -816 } -817 -818 // Three macros to help polling: they return if they get a result, execution -819 // continues if they were Pending and we need to poll others (or finally return -820 // Pending). -821 macro_rules! poll_ipv4 { -822 () => { -823 match self.sockets.v4.poll_recv(cx, bufs, metas)? { -824 Poll::Pending | Poll::Ready(0) => {} -825 Poll::Ready(n) => { -826 self.process_udp_datagrams(true, &mut bufs[..n], &mut metas[..n]); -827 return Poll::Ready(Ok(n)); -828 } -829 } -830 }; -831 } -832 macro_rules! poll_ipv6 { -833 () => { -834 if let Some(ref socket) = self.sockets.v6 { -835 match socket.poll_recv(cx, bufs, metas)? { -836 Poll::Pending | Poll::Ready(0) => {} -837 Poll::Ready(n) => { -838 self.process_udp_datagrams(false, &mut bufs[..n], &mut metas[..n]); -839 return Poll::Ready(Ok(n)); -840 } -841 } -842 } -843 }; -844 } -845 macro_rules! poll_relay { -846 () => { -847 match self.poll_recv_relay(cx, bufs, metas) { -848 Poll::Pending => {} -849 Poll::Ready(n) => return Poll::Ready(n), -850 } -851 }; -852 } -853 -854 let counter = self.poll_recv_counter.fetch_add(1, Ordering::Relaxed); -855 match counter % 3 { -856 0 => { -857 // order of polling: UDPv4, UDPv6, relay -858 poll_ipv4!(); -859 poll_ipv6!(); -860 poll_relay!(); -861 Poll::Pending -862 } -863 1 => { -864 // order of polling: UDPv6, relay, UDPv4 -865 poll_ipv6!(); -866 poll_relay!(); -867 poll_ipv4!(); -868 Poll::Pending -869 } -870 _ => { -871 // order of polling: relay, UDPv4, UDPv6 -872 poll_relay!(); -873 poll_ipv4!(); -874 poll_ipv6!(); -875 Poll::Pending +759 // Normalize local_ip +760 quinn_meta.dst_ip = dst_ip; +761 } +762 +763 if quic_packets_total > 0 { +764 self.metrics +765 .magicsock +766 .recv_datagrams +767 .inc_by(quic_packets_total as _); +768 trace!("UDP recv: {} packets", quic_packets_total); +769 } +770 } +771 +772 /// Handles a discovery message. +773 #[instrument("disco_in", skip_all, fields(node = %sender.fmt_short(), ?src))] +774 fn handle_disco_message(&self, sender: PublicKey, sealed_box: &[u8], src: &transports::Addr) { +775 trace!("handle_disco_message start"); +776 if self.is_closed() { +777 return; +778 } +779 +780 if let transports::Addr::Relay(_, node_id) = src { +781 if node_id != &sender { +782 // TODO: return here? +783 warn!("Received relay disco message from connection for {:?}, but with message from {}", node_id.fmt_short(), sender.fmt_short()); +784 } +785 } +786 +787 // We're now reasonably sure we're expecting communication from +788 // this node, do the heavy crypto lifting to see what they want. +789 let dm = match self.disco_secrets.unseal_and_decode( +790 &self.secret_encryption_key, +791 sender, +792 sealed_box.to_vec(), +793 ) { +794 Ok(dm) => dm, +795 Err(DiscoBoxError::Open { source, .. }) => { +796 warn!(?source, "failed to open disco box"); +797 self.metrics.magicsock.recv_disco_bad_key.inc(); +798 return; +799 } +800 Err(DiscoBoxError::Parse { source, .. }) => { +801 // Couldn't parse it, but it was inside a correctly +802 // signed box, so just ignore it, assuming it's from a +803 // newer version of Tailscale that we don't +804 // understand. Not even worth logging about, lest it +805 // be too spammy for old clients. +806 +807 self.metrics.magicsock.recv_disco_bad_parse.inc(); +808 debug!(?source, "failed to parse disco message"); +809 return; +810 } +811 }; +812 +813 if src.is_relay() { +814 self.metrics.magicsock.recv_disco_relay.inc(); +815 } else { +816 self.metrics.magicsock.recv_disco_udp.inc(); +817 } +818 +819 let span = trace_span!("handle_disco", ?dm); +820 let _guard = span.enter(); +821 trace!("receive disco message"); +822 match dm { +823 disco::Message::Ping(ping) => { +824 self.metrics.magicsock.recv_disco_ping.inc(); +825 self.handle_ping(ping, sender, src); +826 } +827 disco::Message::Pong(pong) => { +828 self.metrics.magicsock.recv_disco_pong.inc(); +829 self.node_map.handle_pong(sender, src, pong); +830 } +831 disco::Message::CallMeMaybe(cm) => { +832 self.metrics.magicsock.recv_disco_call_me_maybe.inc(); +833 match src { +834 transports::Addr::Relay(url, _) => { +835 event!( +836 target: "iroh::_events::call-me-maybe::recv", +837 Level::DEBUG, +838 remote_node = sender.fmt_short(), +839 via = ?url, +840 their_addrs = ?cm.my_numbers, +841 ); +842 } +843 _ => { +844 warn!("call-me-maybe packets should only come via relay"); +845 return; +846 } +847 } +848 let ping_actions = +849 self.node_map +850 .handle_call_me_maybe(sender, cm, &self.metrics.magicsock); +851 for action in ping_actions { +852 match action { +853 PingAction::SendCallMeMaybe { .. } => { +854 warn!("Unexpected CallMeMaybe as response of handling a CallMeMaybe"); +855 } +856 PingAction::SendPing(ping) => { +857 self.send_ping_queued(ping); +858 } +859 } +860 } +861 } +862 } +863 trace!("disco message handled"); +864 } +865 +866 /// Handle a ping message. +867 fn handle_ping(&self, dm: disco::Ping, sender: NodeId, src: &transports::Addr) { +868 // Insert the ping into the node map, and return whether a ping with this tx_id was already +869 // received. +870 let addr: SendAddr = src.clone().into(); +871 let handled = self.node_map.handle_ping(sender, addr.clone(), dm.tx_id); +872 match handled.role { +873 PingRole::Duplicate => { +874 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: path already confirmed, skip"); +875 return; 876 } -877 } -878 } -879 -880 /// poll_recv in browsers is "just" polling the relay receive path -881 #[cfg(wasm_browser)] -882 fn poll_recv( -883 &self, -884 cx: &mut Context, -885 bufs: &mut [io::IoSliceMut<'_>], -886 metas: &mut [quinn_udp::RecvMeta], -887 ) -> Poll<io::Result<usize>> { -888 self.poll_recv_relay(cx, bufs, metas) -889 } -890 -891 /// Process datagrams received from UDP sockets. -892 /// -893 /// All the `bufs` and `metas` should have initialized packets in them. -894 /// -895 /// This fixes up the datagrams to use the correct [`NodeIdMappedAddr`] and extracts DISCO -896 /// packets, processing them inside the magic socket. -897 #[cfg(not(wasm_browser))] -898 fn process_udp_datagrams( -899 &self, -900 from_ipv4: bool, -901 bufs: &mut [io::IoSliceMut<'_>], -902 metas: &mut [quinn_udp::RecvMeta], -903 ) { -904 debug_assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas"); -905 -906 // Adding the IP address we received something on results in Quinn using this -907 // address on the send path to send from. However we let Quinn use a -908 // NodeIdMappedAddress, not a real address. So we used to substitute our bind address -909 // here so that Quinn would send on the right address. But that would sometimes -910 // result in the wrong address family and Windows trips up on that. -911 // -912 // What should be done is that this dst_ip from the RecvMeta is stored in the -913 // NodeState/PathState. Then on the send path it should be retrieved from the -914 // NodeState/PathSate together with the send address and substituted at send time. -915 // This is relevant for IPv6 link-local addresses where the OS otherwise does not -916 // know which intervace to send from. -917 #[cfg(not(windows))] -918 let dst_ip = self.normalized_local_addr().ok().map(|addr| addr.ip()); -919 // Reasoning for this here: -920 // https://github.com/n0-computer/iroh/pull/2595#issuecomment-2290947319 -921 #[cfg(windows)] -922 let dst_ip = None; -923 -924 let mut quic_packets_total = 0; -925 -926 for (meta, buf) in metas.iter_mut().zip(bufs.iter_mut()) { -927 let mut buf_contains_quic_datagrams = false; -928 let mut quic_datagram_count = 0; -929 if meta.len > meta.stride { -930 trace!(%meta.len, %meta.stride, "GRO datagram received"); -931 self.metrics.magicsock.recv_gro_datagrams.inc(); -932 } -933 -934 // Chunk through the datagrams in this GRO payload to find disco and stun -935 // packets and forward them to the actor -936 for datagram in buf[..meta.len].chunks_mut(meta.stride) { -937 if datagram.len() < meta.stride { -938 trace!( -939 len = %datagram.len(), -940 %meta.stride, -941 "Last GRO datagram smaller than stride", -942 ); -943 } +877 PingRole::LikelyHeartbeat => {} +878 PingRole::NewPath => { +879 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: new path"); +880 } +881 PingRole::Activate => { +882 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: path active"); +883 } +884 } +885 +886 // Send a pong. +887 debug!(tx = %HEXLOWER.encode(&dm.tx_id), %addr, dstkey = %sender.fmt_short(), +888 "sending pong"); +889 let pong = disco::Message::Pong(disco::Pong { +890 tx_id: dm.tx_id, +891 ping_observed_addr: addr.clone(), +892 }); +893 event!( +894 target: "iroh::_events::pong::sent", +895 Level::DEBUG, +896 remote_node = %sender.fmt_short(), +897 dst = ?addr, +898 txn = ?dm.tx_id, +899 ); +900 +901 if self +902 .disco_sender +903 .try_send((addr.clone(), sender, pong)) +904 .is_err() +905 { +906 warn!(%addr, "failed to queue pong"); +907 } +908 +909 if let Some(ping) = handled.needs_ping_back { +910 debug!( +911 %addr, +912 dstkey = %sender.fmt_short(), +913 "sending direct ping back", +914 ); +915 self.send_ping_queued(ping); +916 } +917 } +918 +919 fn encode_disco_message(&self, dst_key: PublicKey, msg: &disco::Message) -> Bytes { +920 self.disco_secrets.encode_and_seal( +921 &self.secret_encryption_key, +922 self.secret_key.public(), +923 dst_key, +924 msg, +925 ) +926 } +927 +928 fn send_ping_queued(&self, ping: SendPing) { +929 let SendPing { +930 id, +931 dst, +932 dst_node, +933 tx_id, +934 purpose, +935 } = ping; +936 let msg = disco::Message::Ping(disco::Ping { +937 tx_id, +938 node_key: self.public_key(), +939 }); +940 let sent = self +941 .disco_sender +942 .try_send((dst.clone(), dst_node, msg)) +943 .is_ok(); 944 -945 // Detect DISCO and STUN datagrams and process them. Overwrite the first -946 // byte of those packets with zero to make Quinn ignore the packet. This -947 // relies on quinn::EndpointConfig::grease_quic_bit being set to `false`, -948 // which we do in Endpoint::bind. -949 if stun::is(datagram) { -950 trace!(src = %meta.addr, len = %meta.stride, "UDP recv: stun packet"); -951 let packet2 = Bytes::copy_from_slice(datagram); -952 self.net_reporter.receive_stun_packet(packet2, meta.addr); -953 datagram[0] = 0u8; -954 } else if let Some((sender, sealed_box)) = disco::source_and_box(datagram) { -955 trace!(src = %meta.addr, len = %meta.stride, "UDP recv: disco packet"); -956 self.handle_disco_message( -957 sender, -958 sealed_box, -959 DiscoMessageSource::Udp(meta.addr), -960 ); -961 datagram[0] = 0u8; -962 } else { -963 trace!(src = %meta.addr, len = %meta.stride, "UDP recv: quic packet"); -964 if from_ipv4 { -965 self.metrics -966 .magicsock -967 .recv_data_ipv4 -968 .inc_by(datagram.len() as _); -969 } else { -970 self.metrics -971 .magicsock -972 .recv_data_ipv6 -973 .inc_by(datagram.len() as _); -974 } -975 quic_datagram_count += 1; -976 buf_contains_quic_datagrams = true; -977 }; -978 } -979 -980 if buf_contains_quic_datagrams { -981 // Update the NodeMap and remap RecvMeta to the NodeIdMappedAddr. -982 match self.node_map.receive_udp(meta.addr) { -983 None => { -984 // Check if this address is mapped to an IpMappedAddr -985 if let Some(ip_mapped_addr) = -986 self.ip_mapped_addrs.get_mapped_addr(&meta.addr) -987 { -988 trace!( -989 src = ?meta.addr, -990 count = %quic_datagram_count, -991 len = meta.len, -992 "UDP recv QUIC address discovery packets", -993 ); -994 quic_packets_total += quic_datagram_count; -995 meta.addr = ip_mapped_addr.private_socket_addr(); -996 } else { -997 warn!( -998 src = ?meta.addr, -999 count = %quic_datagram_count, -1000 len = meta.len, -1001 "UDP recv quic packets: no node state found, skipping", -1002 ); -1003 // If we have no node state for the from addr, set len to 0 to make -1004 // quinn skip the buf completely. -1005 meta.len = 0; -1006 } -1007 } -1008 Some((node_id, quic_mapped_addr)) => { -1009 trace!( -1010 src = ?meta.addr, -1011 node = %node_id.fmt_short(), -1012 count = %quic_datagram_count, -1013 len = meta.len, -1014 "UDP recv quic packets", -1015 ); -1016 quic_packets_total += quic_datagram_count; -1017 meta.addr = quic_mapped_addr.private_socket_addr(); -1018 } -1019 } -1020 } else { -1021 // If all datagrams in this buf are DISCO or STUN, set len to zero to make -1022 // Quinn skip the buf completely. -1023 meta.len = 0; -1024 } -1025 // Normalize local_ip -1026 meta.dst_ip = dst_ip; -1027 } -1028 -1029 if quic_packets_total > 0 { -1030 self.metrics -1031 .magicsock -1032 .recv_datagrams -1033 .inc_by(quic_packets_total as _); -1034 trace!("UDP recv: {} packets", quic_packets_total); -1035 } -1036 } -1037 -1038 #[instrument(skip_all)] -1039 fn poll_recv_relay( -1040 &self, -1041 cx: &mut Context, -1042 bufs: &mut [io::IoSliceMut<'_>], -1043 metas: &mut [quinn_udp::RecvMeta], -1044 ) -> Poll<io::Result<usize>> { -1045 let mut num_msgs = 0; -1046 'outer: for (buf_out, meta_out) in bufs.iter_mut().zip(metas.iter_mut()) { -1047 if self.is_closed() { -1048 break; -1049 } -1050 -1051 // For each output buffer keep polling the datagrams from the relay until one is -1052 // a QUIC datagram to be placed into the output buffer. Or the channel is empty. -1053 loop { -1054 let recv = match self.relay_datagram_recv_queue.poll_recv(cx) { -1055 Poll::Ready(Ok(recv)) => recv, -1056 Poll::Ready(Err(err)) => { -1057 error!("relay_recv_channel closed: {err:#}"); -1058 return Poll::Ready(Err(io::Error::new( -1059 io::ErrorKind::NotConnected, -1060 "connection closed", -1061 ))); -1062 } -1063 Poll::Pending => { -1064 break 'outer; -1065 } -1066 }; -1067 match self.process_relay_read_result(recv) { -1068 None => { -1069 // Received a DISCO or STUN datagram that was handled internally. -1070 continue; -1071 } -1072 Some((node_id, meta, buf)) => { -1073 self.metrics -1074 .magicsock -1075 .recv_data_relay -1076 .inc_by(buf.len() as _); -1077 trace!( -1078 src = %meta.addr, -1079 node = %node_id.fmt_short(), -1080 count = meta.len / meta.stride, -1081 len = meta.len, -1082 "recv quic packets from relay", -1083 ); -1084 buf_out[..buf.len()].copy_from_slice(&buf); -1085 *meta_out = meta; -1086 num_msgs += 1; -1087 break; -1088 } -1089 } -1090 } -1091 } -1092 -1093 // If we have any msgs to report, they are in the first `num_msgs_total` slots -1094 if num_msgs > 0 { -1095 self.metrics.magicsock.recv_datagrams.inc_by(num_msgs as _); -1096 Poll::Ready(Ok(num_msgs)) -1097 } else { -1098 Poll::Pending -1099 } -1100 } -1101 -1102 /// Process datagrams received from the relay server into incoming Quinn datagrams. -1103 /// -1104 /// This will transform datagrams received from the relay server into Quinn datagrams to -1105 /// receive, adding the [`quinn_udp::RecvMeta`]. -1106 /// -1107 /// If the incoming datagram is a DISCO packet it will be handled internally and `None` -1108 /// is returned. -1109 fn process_relay_read_result( -1110 &self, -1111 dm: RelayRecvDatagram, -1112 ) -> Option<(NodeId, quinn_udp::RecvMeta, Bytes)> { -1113 trace!("process_relay_read {} bytes", dm.buf.len()); -1114 if dm.buf.is_empty() { -1115 warn!("received empty relay packet"); -1116 return None; -1117 } -1118 -1119 if self.handle_relay_disco_message(&dm.buf, &dm.url, dm.src) { -1120 // DISCO messages are handled internally in the MagicSock, do not pass to Quinn. -1121 return None; -1122 } -1123 -1124 let quic_mapped_addr = self.node_map.receive_relay(&dm.url, dm.src); -1125 -1126 // Normalize local_ip -1127 #[cfg(not(any(windows, wasm_browser)))] -1128 let dst_ip = self.normalized_local_addr().ok().map(|addr| addr.ip()); -1129 // Reasoning for this here: -1130 // https://github.com/n0-computer/iroh/pull/2595#issuecomment-2290947319 -1131 #[cfg(any(windows, wasm_browser))] -1132 let dst_ip = None; -1133 -1134 let meta = quinn_udp::RecvMeta { -1135 len: dm.buf.len(), -1136 stride: dm.buf.len(), -1137 addr: quic_mapped_addr.private_socket_addr(), -1138 dst_ip, -1139 ecn: None, -1140 }; -1141 Some((dm.src, meta, dm.buf)) -1142 } -1143 -1144 fn handle_relay_disco_message( -1145 &self, -1146 msg: &[u8], -1147 url: &RelayUrl, -1148 relay_node_src: PublicKey, -1149 ) -> bool { -1150 match disco::source_and_box(msg) { -1151 Some((source, sealed_box)) => { -1152 if relay_node_src != source { -1153 // TODO: return here? -1154 warn!("Received relay disco message from connection for {}, but with message from {}", relay_node_src.fmt_short(), source.fmt_short()); -1155 } -1156 self.handle_disco_message( -1157 source, -1158 sealed_box, -1159 DiscoMessageSource::Relay { -1160 url: url.clone(), -1161 key: relay_node_src, -1162 }, -1163 ); -1164 true -1165 } -1166 None => false, -1167 } -1168 } -1169 -1170 /// Handles a discovery message. -1171 #[instrument("disco_in", skip_all, fields(node = %sender.fmt_short(), %src))] -1172 fn handle_disco_message(&self, sender: PublicKey, sealed_box: &[u8], src: DiscoMessageSource) { -1173 trace!("handle_disco_message start"); -1174 if self.is_closed() { -1175 return; -1176 } -1177 -1178 // We're now reasonably sure we're expecting communication from -1179 // this node, do the heavy crypto lifting to see what they want. -1180 let dm = match self.disco_secrets.unseal_and_decode( -1181 &self.secret_encryption_key, -1182 sender, -1183 sealed_box.to_vec(), -1184 ) { -1185 Ok(dm) => dm, -1186 Err(DiscoBoxError::Open { source, .. }) => { -1187 warn!(?source, "failed to open disco box"); -1188 self.metrics.magicsock.recv_disco_bad_key.inc(); -1189 return; -1190 } -1191 Err(DiscoBoxError::Parse { source, .. }) => { -1192 // Couldn't parse it, but it was inside a correctly -1193 // signed box, so just ignore it, assuming it's from a -1194 // newer version of Tailscale that we don't -1195 // understand. Not even worth logging about, lest it -1196 // be too spammy for old clients. -1197 -1198 self.metrics.magicsock.recv_disco_bad_parse.inc(); -1199 debug!(?source, "failed to parse disco message"); -1200 return; -1201 } -1202 }; -1203 -1204 if src.is_relay() { -1205 self.metrics.magicsock.recv_disco_relay.inc(); -1206 } else { -1207 self.metrics.magicsock.recv_disco_udp.inc(); -1208 } -1209 -1210 let span = trace_span!("handle_disco", ?dm); -1211 let _guard = span.enter(); -1212 trace!("receive disco message"); -1213 match dm { -1214 disco::Message::Ping(ping) => { -1215 self.metrics.magicsock.recv_disco_ping.inc(); -1216 self.handle_ping(ping, sender, src); -1217 } -1218 disco::Message::Pong(pong) => { -1219 self.metrics.magicsock.recv_disco_pong.inc(); -1220 self.node_map.handle_pong(sender, &src, pong); -1221 } -1222 disco::Message::CallMeMaybe(cm) => { -1223 self.metrics.magicsock.recv_disco_call_me_maybe.inc(); -1224 match src { -1225 DiscoMessageSource::Relay { url, .. } => { -1226 event!( -1227 target: "iroh::_events::call-me-maybe::recv", -1228 Level::DEBUG, -1229 remote_node = sender.fmt_short(), -1230 via = ?url, -1231 their_addrs = ?cm.my_numbers, -1232 ); -1233 } -1234 _ => { -1235 warn!("call-me-maybe packets should only come via relay"); -1236 return; -1237 } -1238 } -1239 let ping_actions = -1240 self.node_map -1241 .handle_call_me_maybe(sender, cm, &self.metrics.magicsock); -1242 for action in ping_actions { -1243 match action { -1244 PingAction::SendCallMeMaybe { .. } => { -1245 warn!("Unexpected CallMeMaybe as response of handling a CallMeMaybe"); -1246 } -1247 PingAction::SendPing(ping) => { -1248 self.send_ping_queued(ping); -1249 } -1250 } -1251 } -1252 } -1253 } -1254 trace!("disco message handled"); -1255 } -1256 -1257 /// Handle a ping message. -1258 fn handle_ping(&self, dm: disco::Ping, sender: NodeId, src: DiscoMessageSource) { -1259 // Insert the ping into the node map, and return whether a ping with this tx_id was already -1260 // received. -1261 let addr: SendAddr = src.clone().into(); -1262 let handled = self.node_map.handle_ping(sender, addr.clone(), dm.tx_id); -1263 match handled.role { -1264 PingRole::Duplicate => { -1265 debug!(%src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: path already confirmed, skip"); -1266 return; -1267 } -1268 PingRole::LikelyHeartbeat => {} -1269 PingRole::NewPath => { -1270 debug!(%src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: new path"); -1271 } -1272 PingRole::Activate => { -1273 debug!(%src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: path active"); -1274 } -1275 } -1276 -1277 // Send a pong. -1278 debug!(tx = %HEXLOWER.encode(&dm.tx_id), %addr, dstkey = %sender.fmt_short(), -1279 "sending pong"); -1280 let pong = disco::Message::Pong(disco::Pong { -1281 tx_id: dm.tx_id, -1282 ping_observed_addr: addr.clone(), -1283 }); -1284 event!( -1285 target: "iroh::_events::pong::sent", -1286 Level::DEBUG, -1287 remote_node = %sender.fmt_short(), -1288 dst = ?addr, -1289 txn = ?dm.tx_id, -1290 ); -1291 -1292 if !self.send_disco_message_queued(addr.clone(), sender, pong) { -1293 warn!(%addr, "failed to queue pong"); -1294 } +945 if sent { +946 let msg_sender = self.actor_sender.clone(); +947 trace!(%dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "ping sent (queued)"); +948 self.node_map +949 .notify_ping_sent(id, dst, tx_id, purpose, msg_sender); +950 } else { +951 warn!(dst = ?dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "failed to send ping: queues full"); +952 } +953 } +954 +955 /// Tries to send the ping actions. +956 async fn send_ping_actions(&self, sender: &UdpSender, msgs: Vec<PingAction>) -> io::Result<()> { +957 for msg in msgs { +958 // Abort sending as soon as we know we are shutting down. +959 if self.is_closing() || self.is_closed() { +960 return Ok(()); +961 } +962 match msg { +963 PingAction::SendCallMeMaybe { +964 ref relay_url, +965 dst_node, +966 } => { +967 self.send_or_queue_call_me_maybe(relay_url, dst_node); +968 } +969 PingAction::SendPing(ping) => { +970 self.send_ping(sender, ping).await?; +971 } +972 } +973 } +974 Ok(()) +975 } +976 +977 /// Send a disco message. UDP messages will be polled to send directly on the UDP socket. +978 async fn send_disco_message( +979 &self, +980 sender: &UdpSender, +981 dst: SendAddr, +982 dst_key: PublicKey, +983 msg: disco::Message, +984 ) -> io::Result<()> { +985 let dst = match dst { +986 SendAddr::Udp(addr) => transports::Addr::Ip(addr), +987 SendAddr::Relay(url) => transports::Addr::Relay(url, dst_key), +988 }; +989 +990 trace!(?dst, %msg, "send disco message (UDP)"); +991 if self.is_closed() { +992 return Err(io::Error::new( +993 io::ErrorKind::NotConnected, +994 "connection closed", +995 )); +996 } +997 let pkt = self.encode_disco_message(dst_key, &msg); +998 +999 let transmit = transports::Transmit { +1000 contents: &pkt, +1001 ecn: None, +1002 segment_size: None, +1003 }; +1004 +1005 let dst2 = dst.clone(); +1006 match sender.send(&dst2, None, &transmit).await { +1007 Ok(()) => { +1008 trace!(?dst, %msg, "sent disco message"); +1009 self.metrics.magicsock.sent_disco_udp.inc(); +1010 disco_message_sent(&msg, &self.metrics.magicsock); +1011 Ok(()) +1012 } +1013 Err(err) => { +1014 warn!(?dst, ?msg, ?err, "failed to send disco message"); +1015 Err(err) +1016 } +1017 } +1018 } +1019 +1020 async fn send_ping(&self, sender: &UdpSender, ping: SendPing) -> io::Result<()> { +1021 let SendPing { +1022 id, +1023 dst, +1024 dst_node, +1025 tx_id, +1026 purpose, +1027 } = ping; +1028 let msg = disco::Message::Ping(disco::Ping { +1029 tx_id, +1030 node_key: self.public_key(), +1031 }); +1032 +1033 self.send_disco_message(sender, dst.clone(), dst_node, msg) +1034 .await?; +1035 debug!(%dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "ping sent"); +1036 let msg_sender = self.actor_sender.clone(); +1037 self.node_map +1038 .notify_ping_sent(id, dst.clone(), tx_id, purpose, msg_sender); +1039 Ok(()) +1040 } +1041 +1042 fn send_queued_call_me_maybes(&self) { +1043 let msg = self.direct_addrs.to_call_me_maybe_message(); +1044 let msg = disco::Message::CallMeMaybe(msg); +1045 for (public_key, url) in self +1046 .pending_call_me_maybes +1047 .lock() +1048 .expect("poisoned") +1049 .drain() +1050 { +1051 if self +1052 .disco_sender +1053 .try_send((SendAddr::Relay(url), public_key, msg.clone())) +1054 .is_err() +1055 { +1056 warn!(node = %public_key.fmt_short(), "relay channel full, dropping call-me-maybe"); +1057 } +1058 } +1059 } +1060 +1061 /// Sends the call-me-maybe DISCO message, queuing if addresses are too stale. +1062 /// +1063 /// To send the call-me-maybe message, we need to know our current direct addresses. If +1064 /// this information is too stale, the call-me-maybe is queued while a net_report run is +1065 /// scheduled. Once this run finishes, the call-me-maybe will be sent. +1066 fn send_or_queue_call_me_maybe(&self, url: &RelayUrl, dst_node: NodeId) { +1067 match self.direct_addrs.fresh_enough() { +1068 Ok(()) => { +1069 let msg = self.direct_addrs.to_call_me_maybe_message(); +1070 let msg = disco::Message::CallMeMaybe(msg); +1071 if self +1072 .disco_sender +1073 .try_send((SendAddr::Relay(url.clone()), dst_node, msg.clone())) +1074 .is_err() +1075 { +1076 warn!(dstkey = %dst_node.fmt_short(), relayurl = %url, +1077 "relay channel full, dropping call-me-maybe"); +1078 } else { +1079 debug!(dstkey = %dst_node.fmt_short(), relayurl = %url, "call-me-maybe sent"); +1080 } +1081 } +1082 Err(last_refresh_ago) => { +1083 self.pending_call_me_maybes +1084 .lock() +1085 .expect("poisoned") +1086 .insert(dst_node, url.clone()); +1087 debug!( +1088 ?last_refresh_ago, +1089 "want call-me-maybe but direct addrs stale; queuing after restun", +1090 ); +1091 self.re_stun("refresh-for-peering"); +1092 } +1093 } +1094 } +1095 +1096 /// Triggers an address discovery. The provided why string is for debug logging only. +1097 #[instrument(skip_all)] +1098 fn re_stun(&self, why: &'static str) { +1099 debug!("re_stun: {}", why); +1100 self.metrics.magicsock.re_stun_calls.inc(); +1101 self.direct_addr_update_state.schedule_run(why); +1102 } +1103 +1104 /// Publishes our address to a discovery service, if configured. +1105 /// +1106 /// Called whenever our addresses or home relay node changes. +1107 fn publish_my_addr(&self) { +1108 if let Some(ref discovery) = self.discovery { +1109 let relay_url = self.my_relay(); +1110 let direct_addrs = self.direct_addrs.sockaddrs(); +1111 +1112 let user_data = self +1113 .discovery_user_data +1114 .read() +1115 .expect("lock poisened") +1116 .clone(); +1117 if relay_url.is_none() && direct_addrs.is_empty() && user_data.is_none() { +1118 // do not bother publishing if we don't have any information +1119 return; +1120 } +1121 +1122 let data = NodeData::new(relay_url, direct_addrs).with_user_data(user_data); +1123 discovery.publish(&data); +1124 } +1125 } +1126} +1127 +1128#[derive(Clone, Debug)] +1129enum MappedAddr { +1130 NodeId(NodeIdMappedAddr), +1131 #[cfg(not(wasm_browser))] +1132 Ip(IpMappedAddr), +1133 None(SocketAddr), +1134} +1135 +1136impl From<SocketAddr> for MappedAddr { +1137 fn from(value: SocketAddr) -> Self { +1138 match value.ip() { +1139 IpAddr::V4(_) => MappedAddr::None(value), +1140 IpAddr::V6(addr) => { +1141 if let Ok(node_id_mapped_addr) = NodeIdMappedAddr::try_from(addr) { +1142 return MappedAddr::NodeId(node_id_mapped_addr); +1143 } +1144 #[cfg(not(wasm_browser))] +1145 if let Ok(ip_mapped_addr) = IpMappedAddr::try_from(addr) { +1146 return MappedAddr::Ip(ip_mapped_addr); +1147 } +1148 MappedAddr::None(value) +1149 } +1150 } +1151 } +1152} +1153 +1154/// Manages currently running direct addr discovery, aka net_report runs. +1155/// +1156/// Invariants: +1157/// - only one direct addr update must be running at a time +1158/// - if an update is scheduled while another one is running, remember that +1159/// and start a new one when the current one has finished +1160#[derive(Debug)] +1161struct DirectAddrUpdateState { +1162 /// If running, set to the reason for the currently the update. +1163 running: sync::watch::Sender<Option<&'static str>>, +1164 /// If set, start a new update as soon as the current one is finished. +1165 want_update: std::sync::Mutex<Option<&'static str>>, +1166} +1167 +1168impl DirectAddrUpdateState { +1169 fn new() -> Self { +1170 let (running, _) = sync::watch::channel(None); +1171 DirectAddrUpdateState { +1172 running, +1173 want_update: Default::default(), +1174 } +1175 } +1176 +1177 /// Schedules a new run, either starting it immediately if none is running or +1178 /// scheduling it for later. +1179 fn schedule_run(&self, why: &'static str) { +1180 if self.is_running() { +1181 let _ = self.want_update.lock().expect("poisoned").insert(why); +1182 } else { +1183 self.run(why); +1184 } +1185 } +1186 +1187 /// Returns `true` if an update is currently in progress. +1188 fn is_running(&self) -> bool { +1189 self.running.borrow().is_some() +1190 } +1191 +1192 /// Trigger a new run. +1193 fn run(&self, why: &'static str) { +1194 self.running.send(Some(why)).ok(); +1195 } +1196 +1197 /// Clears the current running state. +1198 fn finish_run(&self) { +1199 self.running.send(None).ok(); +1200 } +1201 +1202 /// Returns the next update, if one is set. +1203 fn next_update(&self) -> Option<&'static str> { +1204 self.want_update.lock().expect("poisoned").take() +1205 } +1206} +1207 +1208#[allow(missing_docs)] +1209#[common_fields({ +1210 backtrace: Option<snafu::Backtrace>, +1211 #[snafu(implicit)] +1212 span_trace: n0_snafu::SpanTrace, +1213})] +1214#[derive(Debug, Snafu)] +1215#[non_exhaustive] +1216pub enum CreateHandleError { +1217 #[snafu(display("Failed to create bind sockets"))] +1218 BindSockets { source: io::Error }, +1219 #[snafu(display("Failed to create internal quinn endpoint"))] +1220 CreateQuinnEndpoint { source: io::Error }, +1221 #[snafu(display("Failed to create socket state"))] +1222 CreateSocketState { source: io::Error }, +1223 #[snafu(display("Failed to create netmon monitor"))] +1224 CreateNetmonMonitor { source: netmon::Error }, +1225 #[snafu(display("Failed to subscribe netmon monitor"))] +1226 SubscribeNetmonMonitor { source: netmon::Error }, +1227} +1228 +1229impl Handle { +1230 /// Creates a magic [`MagicSock`] listening on [`Options::addr_v4`] and [`Options::addr_v6`]. +1231 async fn new(opts: Options) -> Result<Self, CreateHandleError> { +1232 let me = opts.secret_key.public().fmt_short(); +1233 +1234 Self::with_name(me, opts) +1235 .instrument(error_span!("magicsock")) +1236 .await +1237 } +1238 +1239 async fn with_name(me: String, opts: Options) -> Result<Self, CreateHandleError> { +1240 let Options { +1241 addr_v4, +1242 addr_v6, +1243 secret_key, +1244 relay_map, +1245 relay_protocol, +1246 node_map, +1247 discovery, +1248 discovery_user_data, +1249 #[cfg(not(wasm_browser))] +1250 dns_resolver, +1251 proxy_url, +1252 server_config, +1253 #[cfg(any(test, feature = "test-utils"))] +1254 insecure_skip_relay_cert_verify, +1255 #[cfg(any(test, feature = "test-utils"))] +1256 path_selection, +1257 metrics, +1258 } = opts; +1259 +1260 let addr_v4 = addr_v4.unwrap_or_else(|| SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)); +1261 +1262 #[cfg(not(wasm_browser))] +1263 let (ip_transports, port_mapper) = +1264 bind_ip(addr_v4, addr_v6, &metrics).context(BindSocketsSnafu)?; +1265 +1266 #[cfg(not(wasm_browser))] +1267 let v4_socket = ip_transports +1268 .iter() +1269 .find(|t| t.bind_addr().is_ipv4()) +1270 .expect("must bind a ipv4 socket") +1271 .socket(); +1272 #[cfg(not(wasm_browser))] +1273 let v6_socket = ip_transports.iter().find_map(|t| { +1274 if t.bind_addr().is_ipv6() { +1275 Some(t.socket()) +1276 } else { +1277 None +1278 } +1279 }); +1280 +1281 let ip_mapped_addrs = IpMappedAddresses::default(); +1282 +1283 let net_reporter = net_report::Client::new( +1284 #[cfg(not(wasm_browser))] +1285 Some(port_mapper.clone()), +1286 #[cfg(not(wasm_browser))] +1287 dns_resolver.clone(), +1288 #[cfg(not(wasm_browser))] +1289 Some(ip_mapped_addrs.clone()), +1290 metrics.net_report.clone(), +1291 ); +1292 +1293 let (actor_sender, actor_receiver) = mpsc::channel(256); +1294 let (disco_sender, mut disco_receiver) = mpsc::channel(256); 1295 -1296 if let Some(ping) = handled.needs_ping_back { -1297 debug!( -1298 %addr, -1299 dstkey = %sender.fmt_short(), -1300 "sending direct ping back", -1301 ); -1302 self.send_ping_queued(ping); -1303 } -1304 } +1296 // load the node data +1297 let node_map = node_map.unwrap_or_default(); +1298 #[cfg(any(test, feature = "test-utils"))] +1299 let node_map = NodeMap::load_from_vec(node_map, path_selection, &metrics.magicsock); +1300 #[cfg(not(any(test, feature = "test-utils")))] +1301 let node_map = NodeMap::load_from_vec(node_map, &metrics.magicsock); +1302 +1303 let my_relay = Watchable::new(None); +1304 let ipv6_reported = Arc::new(AtomicBool::new(false)); 1305 -1306 fn encode_disco_message(&self, dst_key: PublicKey, msg: &disco::Message) -> Bytes { -1307 self.disco_secrets.encode_and_seal( -1308 &self.secret_encryption_key, -1309 self.secret_key.public(), -1310 dst_key, -1311 msg, -1312 ) -1313 } -1314 -1315 fn send_ping_queued(&self, ping: SendPing) { -1316 let SendPing { -1317 id, -1318 dst, -1319 dst_node, -1320 tx_id, -1321 purpose, -1322 } = ping; -1323 let msg = disco::Message::Ping(disco::Ping { -1324 tx_id, -1325 node_key: self.public_key(), -1326 }); -1327 let sent = match dst { -1328 #[cfg(not(wasm_browser))] -1329 SendAddr::Udp(addr) => self -1330 .udp_disco_sender -1331 .try_send((addr, dst_node, msg)) -1332 .is_ok(), -1333 #[cfg(wasm_browser)] -1334 SendAddr::Udp(_) => { -1335 // Ignoring sending pings over UDP. We don't have a UDP socket. -1336 return; -1337 } -1338 SendAddr::Relay(ref url) => self.send_disco_message_relay(url, dst_node, msg), -1339 }; -1340 if sent { -1341 let msg_sender = self.actor_sender.clone(); -1342 trace!(%dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "ping sent (queued)"); -1343 self.node_map -1344 .notify_ping_sent(id, dst, tx_id, purpose, msg_sender); -1345 } else { -1346 warn!(dst = ?dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "failed to send ping: queues full"); -1347 } -1348 } -1349 -1350 /// Tries to send the ping actions. -1351 /// -1352 /// Note that on failure the (remaining) ping actions are simply dropped. That's bad! -1353 /// The Endpoint will think a full ping was done and not request a new full-ping for a -1354 /// while. We should probably be buffering the pings. -1355 fn try_send_ping_actions(&self, msgs: Vec<PingAction>) -> io::Result<()> { -1356 for msg in msgs { -1357 // Abort sending as soon as we know we are shutting down. -1358 if self.is_closing() || self.is_closed() { -1359 return Ok(()); -1360 } -1361 match msg { -1362 PingAction::SendCallMeMaybe { -1363 ref relay_url, -1364 dst_node, -1365 } => { -1366 self.send_or_queue_call_me_maybe(relay_url, dst_node); -1367 } -1368 PingAction::SendPing(ping) => { -1369 self.try_send_ping(ping)?; -1370 } -1371 } -1372 } -1373 Ok(()) -1374 } -1375 -1376 /// Send a disco message. UDP messages will be queued. -1377 /// -1378 /// If `dst` is [`SendAddr::Relay`], the message will be pushed into the relay client channel. -1379 /// If `dst` is [`SendAddr::Udp`], the message will be pushed into the udp disco send channel. -1380 /// -1381 /// Returns true if the channel had capacity for the message, and false if the message was -1382 /// dropped. -1383 fn send_disco_message_queued( -1384 &self, -1385 dst: SendAddr, -1386 dst_key: PublicKey, -1387 msg: disco::Message, -1388 ) -> bool { -1389 match dst { -1390 SendAddr::Udp(addr) => self.udp_disco_sender.try_send((addr, dst_key, msg)).is_ok(), -1391 SendAddr::Relay(ref url) => self.send_disco_message_relay(url, dst_key, msg), -1392 } -1393 } -1394 -1395 /// Send a disco message. UDP messages will be polled to send directly on the UDP socket. -1396 fn try_send_disco_message( -1397 &self, -1398 dst: SendAddr, -1399 dst_key: PublicKey, -1400 msg: disco::Message, -1401 ) -> io::Result<()> { -1402 match dst { -1403 #[cfg(not(wasm_browser))] -1404 SendAddr::Udp(addr) => { -1405 self.try_send_disco_message_udp(addr, dst_key, &msg)?; -1406 } -1407 #[cfg(wasm_browser)] -1408 SendAddr::Udp(addr) => { -1409 warn!(?addr, "Asked to send on UDP in browser code"); -1410 } -1411 SendAddr::Relay(ref url) => { -1412 if !self.send_disco_message_relay(url, dst_key, msg) { -1413 return Err(io::Error::other("Relay channel full")); -1414 } -1415 } -1416 } -1417 Ok(()) -1418 } -1419 -1420 fn send_disco_message_relay(&self, url: &RelayUrl, dst: NodeId, msg: disco::Message) -> bool { -1421 debug!(node = %dst.fmt_short(), %url, %msg, "send disco message (relay)"); -1422 let pkt = self.encode_disco_message(dst, &msg); -1423 self.metrics.magicsock.send_disco_relay.inc(); -1424 match self.try_send_relay(url, dst, smallvec![pkt]) { -1425 Ok(()) => { -1426 if let disco::Message::CallMeMaybe(CallMeMaybe { ref my_numbers }) = msg { -1427 event!( -1428 target: "iroh::_events::call-me-maybe::sent", -1429 Level::DEBUG, -1430 remote_node = %dst.fmt_short(), -1431 via = ?url, -1432 addrs = ?my_numbers, -1433 ); -1434 } -1435 self.metrics.magicsock.sent_disco_relay.inc(); -1436 disco_message_sent(&msg, &self.metrics.magicsock); -1437 true -1438 } -1439 Err(_) => false, -1440 } -1441 } -1442 -1443 #[cfg(not(wasm_browser))] -1444 async fn send_disco_message_udp( -1445 &self, -1446 dst: SocketAddr, -1447 dst_node: NodeId, -1448 msg: &disco::Message, -1449 ) -> io::Result<()> { -1450 n0_future::future::poll_fn(move |cx| { -1451 loop { -1452 match self.try_send_disco_message_udp(dst, dst_node, msg) { -1453 Ok(()) => return Poll::Ready(Ok(())), -1454 Err(err) if err.kind() == io::ErrorKind::WouldBlock => { -1455 // This is the socket .try_send_disco_message_udp used. -1456 let sock = self.conn_for_addr(dst)?; -1457 match sock.as_socket_ref().poll_writable(cx) { -1458 Poll::Ready(Ok(())) => continue, -1459 Poll::Ready(Err(err)) => return Poll::Ready(Err(err)), -1460 Poll::Pending => return Poll::Pending, -1461 } -1462 } -1463 Err(err) => return Poll::Ready(Err(err)), -1464 } -1465 } -1466 }) -1467 .await -1468 } -1469 -1470 #[cfg(not(wasm_browser))] -1471 fn try_send_disco_message_udp( -1472 &self, -1473 dst: SocketAddr, -1474 dst_node: NodeId, -1475 msg: &disco::Message, -1476 ) -> std::io::Result<()> { -1477 trace!(%dst, %msg, "send disco message (UDP)"); -1478 if self.is_closed() { -1479 return Err(io::Error::new( -1480 io::ErrorKind::NotConnected, -1481 "connection closed", -1482 )); -1483 } -1484 let pkt = self.encode_disco_message(dst_node, msg); -1485 // TODO: These metrics will be wrong with the poll impl -1486 // Also - do we need it? I'd say the `sent_disco_udp` below is enough. -1487 self.metrics.magicsock.send_disco_udp.inc(); -1488 let transmit = quinn_udp::Transmit { -1489 destination: dst, -1490 contents: &pkt, -1491 ecn: None, -1492 segment_size: None, -1493 src_ip: None, // TODO -1494 }; -1495 let sent = self.try_send_udp(dst, &transmit); -1496 match sent { -1497 Ok(()) => { -1498 trace!(%dst, node = %dst_node.fmt_short(), %msg, "sent disco message"); -1499 self.metrics.magicsock.sent_disco_udp.inc(); -1500 disco_message_sent(msg, &self.metrics.magicsock); -1501 Ok(()) -1502 } -1503 Err(err) => { -1504 warn!(%dst, node = %dst_node.fmt_short(), ?msg, ?err, -1505 "failed to send disco message"); -1506 Err(err) -1507 } -1508 } -1509 } -1510 -1511 #[instrument(skip_all)] -1512 async fn handle_ping_actions(&mut self, msgs: Vec<PingAction>) { -1513 // TODO: This used to make sure that all ping actions are sent. Though on the -1514 // poll_send/try_send path we also do fire-and-forget. try_send_ping_actions() -1515 // really should store any unsent pings on the Inner and send them at the next -1516 // possible time. -1517 if let Err(err) = self.try_send_ping_actions(msgs) { -1518 warn!("Not all ping actions were sent: {err:#}"); -1519 } -1520 } -1521 -1522 fn try_send_ping(&self, ping: SendPing) -> io::Result<()> { -1523 let SendPing { -1524 id, -1525 dst, -1526 dst_node, -1527 tx_id, -1528 purpose, -1529 } = ping; -1530 let msg = disco::Message::Ping(disco::Ping { -1531 tx_id, -1532 node_key: self.public_key(), -1533 }); -1534 self.try_send_disco_message(dst.clone(), dst_node, msg)?; -1535 debug!(%dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "ping sent (polled)"); -1536 let msg_sender = self.actor_sender.clone(); -1537 self.node_map -1538 .notify_ping_sent(id, dst.clone(), tx_id, purpose, msg_sender); -1539 Ok(()) -1540 } -1541 -1542 fn send_queued_call_me_maybes(&self) { -1543 let msg = self.direct_addrs.to_call_me_maybe_message(); -1544 let msg = disco::Message::CallMeMaybe(msg); -1545 for (public_key, url) in self -1546 .pending_call_me_maybes -1547 .lock() -1548 .expect("poisoned") -1549 .drain() -1550 { -1551 if !self.send_disco_message_relay(&url, public_key, msg.clone()) { -1552 warn!(node = %public_key.fmt_short(), "relay channel full, dropping call-me-maybe"); -1553 } -1554 } -1555 } -1556 -1557 /// Sends the call-me-maybe DISCO message, queuing if addresses are too stale. -1558 /// -1559 /// To send the call-me-maybe message, we need to know our current direct addresses. If -1560 /// this information is too stale, the call-me-maybe is queued while a net_report run is -1561 /// scheduled. Once this run finishes, the call-me-maybe will be sent. -1562 fn send_or_queue_call_me_maybe(&self, url: &RelayUrl, dst_node: NodeId) { -1563 match self.direct_addrs.fresh_enough() { -1564 Ok(()) => { -1565 let msg = self.direct_addrs.to_call_me_maybe_message(); -1566 let msg = disco::Message::CallMeMaybe(msg); -1567 if !self.send_disco_message_relay(url, dst_node, msg) { -1568 warn!(dstkey = %dst_node.fmt_short(), relayurl = %url, -1569 "relay channel full, dropping call-me-maybe"); -1570 } else { -1571 debug!(dstkey = %dst_node.fmt_short(), relayurl = %url, "call-me-maybe sent"); -1572 } -1573 } -1574 Err(last_refresh_ago) => { -1575 self.pending_call_me_maybes -1576 .lock() -1577 .expect("poisoned") -1578 .insert(dst_node, url.clone()); -1579 debug!( -1580 ?last_refresh_ago, -1581 "want call-me-maybe but direct addrs stale; queuing after restun", -1582 ); -1583 self.re_stun("refresh-for-peering"); -1584 } -1585 } -1586 } -1587 -1588 /// Triggers an address discovery. The provided why string is for debug logging only. -1589 #[instrument(skip_all)] -1590 fn re_stun(&self, why: &'static str) { -1591 debug!("re_stun: {}", why); -1592 self.metrics.magicsock.re_stun_calls.inc(); -1593 self.direct_addr_update_state.schedule_run(why); -1594 } -1595 -1596 /// Publishes our address to a discovery service, if configured. -1597 /// -1598 /// Called whenever our addresses or home relay node changes. -1599 fn publish_my_addr(&self) { -1600 if let Some(ref discovery) = self.discovery { -1601 let relay_url = self.my_relay(); -1602 let direct_addrs = self.direct_addrs.sockaddrs(); -1603 let user_data = self -1604 .discovery_user_data -1605 .read() -1606 .expect("lock poisened") -1607 .clone(); -1608 let data = NodeData::new(relay_url, direct_addrs).with_user_data(user_data); -1609 discovery.publish(&data); -1610 } -1611 } -1612} -1613 -1614#[derive(Clone, Debug)] -1615enum MappedAddr { -1616 NodeId(NodeIdMappedAddr), -1617 #[cfg(not(wasm_browser))] -1618 Ip(IpMappedAddr), -1619 None(SocketAddr), -1620} -1621 -1622impl From<SocketAddr> for MappedAddr { -1623 fn from(value: SocketAddr) -> Self { -1624 match value.ip() { -1625 IpAddr::V4(_) => MappedAddr::None(value), -1626 IpAddr::V6(addr) => { -1627 if let Ok(node_id_mapped_addr) = NodeIdMappedAddr::try_from(addr) { -1628 return MappedAddr::NodeId(node_id_mapped_addr); -1629 } -1630 #[cfg(not(wasm_browser))] -1631 if let Ok(ip_mapped_addr) = IpMappedAddr::try_from(addr) { -1632 return MappedAddr::Ip(ip_mapped_addr); -1633 } -1634 MappedAddr::None(value) -1635 } -1636 } -1637 } -1638} -1639 -1640#[derive(Clone, Debug)] -1641enum DiscoMessageSource { -1642 Udp(SocketAddr), -1643 Relay { url: RelayUrl, key: PublicKey }, -1644} -1645 -1646impl Display for DiscoMessageSource { -1647 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { -1648 match self { -1649 Self::Udp(addr) => write!(f, "Udp({addr})"), -1650 Self::Relay { ref url, key } => write!(f, "Relay({url}, {})", key.fmt_short()), -1651 } -1652 } -1653} -1654 -1655impl From<DiscoMessageSource> for SendAddr { -1656 fn from(value: DiscoMessageSource) -> Self { -1657 match value { -1658 DiscoMessageSource::Udp(addr) => SendAddr::Udp(addr), -1659 DiscoMessageSource::Relay { url, .. } => SendAddr::Relay(url), -1660 } -1661 } -1662} -1663 -1664impl From<&DiscoMessageSource> for SendAddr { -1665 fn from(value: &DiscoMessageSource) -> Self { -1666 match value { -1667 DiscoMessageSource::Udp(addr) => SendAddr::Udp(*addr), -1668 DiscoMessageSource::Relay { url, .. } => SendAddr::Relay(url.clone()), -1669 } -1670 } -1671} -1672 -1673impl DiscoMessageSource { -1674 fn is_relay(&self) -> bool { -1675 matches!(self, DiscoMessageSource::Relay { .. }) -1676 } -1677} -1678 -1679/// Manages currently running direct addr discovery, aka net_report runs. -1680/// -1681/// Invariants: -1682/// - only one direct addr update must be running at a time -1683/// - if an update is scheduled while another one is running, remember that -1684/// and start a new one when the current one has finished -1685#[derive(Debug)] -1686struct DirectAddrUpdateState { -1687 /// If running, set to the reason for the currently the update. -1688 running: sync::watch::Sender<Option<&'static str>>, -1689 /// If set, start a new update as soon as the current one is finished. -1690 want_update: std::sync::Mutex<Option<&'static str>>, -1691} -1692 -1693impl DirectAddrUpdateState { -1694 fn new() -> Self { -1695 let (running, _) = sync::watch::channel(None); -1696 DirectAddrUpdateState { -1697 running, -1698 want_update: Default::default(), -1699 } -1700 } -1701 -1702 /// Schedules a new run, either starting it immediately if none is running or -1703 /// scheduling it for later. -1704 fn schedule_run(&self, why: &'static str) { -1705 if self.is_running() { -1706 let _ = self.want_update.lock().expect("poisoned").insert(why); -1707 } else { -1708 self.run(why); -1709 } -1710 } -1711 -1712 /// Returns `true` if an update is currently in progress. -1713 fn is_running(&self) -> bool { -1714 self.running.borrow().is_some() -1715 } -1716 -1717 /// Trigger a new run. -1718 fn run(&self, why: &'static str) { -1719 self.running.send(Some(why)).ok(); -1720 } -1721 -1722 /// Clears the current running state. -1723 fn finish_run(&self) { -1724 self.running.send(None).ok(); -1725 } -1726 -1727 /// Returns the next update, if one is set. -1728 fn next_update(&self) -> Option<&'static str> { -1729 self.want_update.lock().expect("poisoned").take() -1730 } -1731} +1306 let relay_transport = RelayTransport::new(RelayActorConfig { +1307 my_relay: my_relay.clone(), +1308 secret_key: secret_key.clone(), +1309 #[cfg(not(wasm_browser))] +1310 dns_resolver: dns_resolver.clone(), +1311 proxy_url: proxy_url.clone(), +1312 ipv6_reported: ipv6_reported.clone(), +1313 #[cfg(any(test, feature = "test-utils"))] +1314 insecure_skip_relay_cert_verify, +1315 metrics: metrics.magicsock.clone(), +1316 protocol: relay_protocol, +1317 }); +1318 let relay_transports = vec![relay_transport]; +1319 +1320 let secret_encryption_key = secret_ed_box(secret_key.secret()); +1321 #[cfg(not(wasm_browser))] +1322 let ipv6 = ip_transports.iter().any(|t| t.bind_addr().is_ipv6()); +1323 +1324 #[cfg(not(wasm_browser))] +1325 let transports = Transports::new(ip_transports, relay_transports); +1326 #[cfg(wasm_browser)] +1327 let transports = Transports::new(relay_transports); +1328 +1329 let msock = Arc::new(MagicSock { +1330 me, +1331 secret_key, +1332 secret_encryption_key, +1333 closing: AtomicBool::new(false), +1334 closed: AtomicBool::new(false), +1335 actor_sender: actor_sender.clone(), +1336 ipv6_reported, +1337 relay_map, +1338 net_reporter: net_reporter.addr(), +1339 disco_secrets: DiscoSecrets::default(), +1340 node_map, +1341 ip_mapped_addrs, +1342 disco_sender, +1343 discovery, +1344 discovery_user_data: RwLock::new(discovery_user_data), +1345 direct_addrs: Default::default(), +1346 net_report: Default::default(), +1347 pending_call_me_maybes: Default::default(), +1348 direct_addr_update_state: DirectAddrUpdateState::new(), +1349 #[cfg(not(wasm_browser))] +1350 dns_resolver, +1351 discovery_subscribers: DiscoverySubscribers::new(), +1352 metrics, +1353 local_addrs_watch: transports.local_addrs_watch(), +1354 #[cfg(not(wasm_browser))] +1355 ip_bind_addrs: transports.ip_bind_addrs(), +1356 }); +1357 +1358 let mut endpoint_config = quinn::EndpointConfig::default(); +1359 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit +1360 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet. +1361 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight +1362 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore +1363 // the packet if grease_quic_bit is set to false. +1364 endpoint_config.grease_quic_bit(false); +1365 +1366 let sender1 = transports.create_sender(msock.clone()); +1367 let sender2 = transports.create_sender(msock.clone()); +1368 let local_addrs_watch = transports.local_addrs_watch(); +1369 let network_change_sender = transports.create_network_change_sender(); +1370 +1371 let endpoint = quinn::Endpoint::new_with_abstract_socket( +1372 endpoint_config, +1373 Some(server_config), +1374 Box::new(MagicUdpSocket { +1375 socket: msock.clone(), +1376 transports, +1377 }), +1378 #[cfg(not(wasm_browser))] +1379 Arc::new(quinn::TokioRuntime), +1380 #[cfg(wasm_browser)] +1381 Arc::new(crate::web_runtime::WebRuntime), +1382 ) +1383 .context(CreateQuinnEndpointSnafu)?; +1384 +1385 let mut actor_tasks = JoinSet::default(); +1386 +1387 #[cfg(not(wasm_browser))] +1388 let _ = actor_tasks.spawn({ +1389 let msock = msock.clone(); +1390 async move { +1391 while let Some((dst, dst_key, msg)) = disco_receiver.recv().await { +1392 if let Err(err) = msock.send_disco_message(&sender1, dst.clone(), dst_key, msg).await { +1393 warn!(%dst, node = %dst_key.fmt_short(), ?err, "failed to send disco message (UDP)"); +1394 } +1395 } +1396 } +1397 }); +1398 +1399 let network_monitor = netmon::Monitor::new() +1400 .await +1401 .context(CreateNetmonMonitorSnafu)?; +1402 let qad_endpoint = endpoint.clone(); +1403 +1404 #[cfg(any(test, feature = "test-utils"))] +1405 let client_config = if insecure_skip_relay_cert_verify { +1406 iroh_relay::client::make_dangerous_client_config() +1407 } else { +1408 default_quic_client_config() +1409 }; +1410 #[cfg(not(any(test, feature = "test-utils")))] +1411 let client_config = default_quic_client_config(); +1412 +1413 let net_report_config = net_report::Options::default(); +1414 #[cfg(not(wasm_browser))] +1415 let net_report_config = net_report_config +1416 .stun_v4(Some(v4_socket)) +1417 .stun_v6(v6_socket) +1418 .quic_config(Some(QuicConfig { +1419 ep: qad_endpoint, +1420 client_config, +1421 ipv4: true, +1422 ipv6, +1423 })); +1424 +1425 #[cfg(any(test, feature = "test-utils"))] +1426 let net_report_config = +1427 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify); +1428 +1429 let actor = Actor { +1430 msg_receiver: actor_receiver, +1431 msg_sender: actor_sender, +1432 msock: msock.clone(), +1433 periodic_re_stun_timer: new_re_stun_timer(false), +1434 net_info_last: None, +1435 #[cfg(not(wasm_browser))] +1436 port_mapper, +1437 no_v4_send: false, +1438 net_reporter, +1439 network_monitor, +1440 net_report_config, +1441 network_change_sender, +1442 }; +1443 actor_tasks.spawn( +1444 actor +1445 .run(local_addrs_watch, sender2) +1446 .instrument(info_span!("actor")), +1447 ); +1448 +1449 let actor_tasks = Arc::new(Mutex::new(actor_tasks)); +1450 +1451 Ok(Handle { +1452 msock, +1453 actor_tasks, +1454 endpoint, +1455 }) +1456 } +1457 +1458 /// The underlying [`quinn::Endpoint`] +1459 pub fn endpoint(&self) -> &quinn::Endpoint { +1460 &self.endpoint +1461 } +1462 +1463 /// Closes the connection. +1464 /// +1465 /// Only the first close does anything. Any later closes return nil. +1466 /// Polling the socket ([`AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] +1467 /// indefinitely after this call. +1468 #[instrument(skip_all, fields(me = %self.msock.me))] +1469 pub(crate) async fn close(&self) { +1470 trace!("magicsock closing..."); +1471 // Initiate closing all connections, and refuse future connections. +1472 self.endpoint.close(0u16.into(), b""); +1473 +1474 // In the history of this code, this call had been +1475 // - removed: https://github.com/n0-computer/iroh/pull/1753 +1476 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 +1477 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 +1478 // and finally added back in together with this comment. +1479 // So before removing this call, please consider carefully. +1480 // Among other things, this call tries its best to make sure that any queued close frames +1481 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets +1482 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). +1483 // This allows the other endpoints for these connections to be notified to release +1484 // their resources, or - depending on the protocol - that all data was received. +1485 // With the current quinn API, this is the only way to ensure protocol code can use +1486 // connection close codes, and close the endpoint properly. +1487 // If this call is skipped, then connections that protocols close just shortly before the +1488 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. +1489 self.endpoint.wait_idle().await; +1490 +1491 if self.msock.is_closed() { +1492 return; +1493 } +1494 self.msock.closing.store(true, Ordering::Relaxed); +1495 // If this fails, then there's no receiver listening for shutdown messages, +1496 // so nothing to shut down anyways. +1497 self.msock +1498 .actor_sender +1499 .send(ActorMessage::Shutdown) +1500 .await +1501 .ok(); +1502 self.msock.closed.store(true, Ordering::SeqCst); +1503 +1504 let mut tasks = self.actor_tasks.lock().await; +1505 +1506 // give the tasks a moment to shutdown cleanly +1507 let tasks_ref = &mut tasks; +1508 let shutdown_done = time::timeout(Duration::from_millis(100), async move { +1509 while let Some(task) = tasks_ref.join_next().await { +1510 if let Err(err) = task { +1511 warn!("unexpected error in task shutdown: {:?}", err); +1512 } +1513 } +1514 }) +1515 .await; +1516 match shutdown_done { +1517 Ok(_) => trace!("tasks finished in time, shutdown complete"), +1518 Err(_elapsed) => { +1519 // shutdown all tasks +1520 warn!( +1521 "tasks didn't finish in time, aborting remaining {}/3 tasks", +1522 tasks.len() +1523 ); +1524 tasks.shutdown().await; +1525 } +1526 } +1527 trace!("magicsock closed"); +1528 } +1529} +1530 +1531fn default_quic_client_config() -> rustls::ClientConfig { +1532 // create a client config for the endpoint to use for QUIC address discovery +1533 let root_store = +1534 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); +1535 rustls::client::ClientConfig::builder_with_provider(Arc::new( +1536 rustls::crypto::ring::default_provider(), +1537 )) +1538 .with_safe_default_protocol_versions() +1539 .expect("ring supports these") +1540 .with_root_certificates(root_store) +1541 .with_no_client_auth() +1542} +1543 +1544#[derive(Debug, Default)] +1545struct DiscoSecrets(std::sync::Mutex<HashMap<PublicKey, SharedSecret>>); +1546 +1547impl DiscoSecrets { +1548 fn get<F, T>(&self, secret: &crypto_box::SecretKey, node_id: PublicKey, cb: F) -> T +1549 where +1550 F: FnOnce(&mut SharedSecret) -> T, +1551 { +1552 let mut inner = self.0.lock().expect("poisoned"); +1553 let x = inner.entry(node_id).or_insert_with(|| { +1554 let public_key = public_ed_box(&node_id.public()); +1555 SharedSecret::new(secret, &public_key) +1556 }); +1557 cb(x) +1558 } +1559 +1560 fn encode_and_seal( +1561 &self, +1562 this_secret_key: &crypto_box::SecretKey, +1563 this_node_id: NodeId, +1564 other_node_id: NodeId, +1565 msg: &disco::Message, +1566 ) -> Bytes { +1567 let mut seal = msg.as_bytes(); +1568 self.get(this_secret_key, other_node_id, |secret| { +1569 secret.seal(&mut seal) +1570 }); +1571 disco::encode_message(&this_node_id, seal).into() +1572 } +1573 fn unseal_and_decode( +1574 &self, +1575 secret: &crypto_box::SecretKey, +1576 node_id: PublicKey, +1577 mut sealed_box: Vec<u8>, +1578 ) -> Result<disco::Message, DiscoBoxError> { +1579 self.get(secret, node_id, |secret| secret.open(&mut sealed_box)) +1580 .context(OpenSnafu)?; +1581 disco::Message::from_bytes(&sealed_box).context(ParseSnafu) +1582 } +1583} +1584 +1585#[allow(missing_docs)] +1586#[common_fields({ +1587 backtrace: Option<snafu::Backtrace>, +1588 #[snafu(implicit)] +1589 span_trace: n0_snafu::SpanTrace, +1590})] +1591#[derive(Debug, Snafu)] +1592#[non_exhaustive] +1593enum DiscoBoxError { +1594 #[snafu(display("Failed to open crypto box"))] +1595 Open { +1596 #[snafu(source(from(DecryptionError, Box::new)))] +1597 source: Box<DecryptionError>, +1598 }, +1599 #[snafu(display("Failed to parse disco message"))] +1600 Parse { +1601 #[snafu(source(from(disco::ParseError, Box::new)))] +1602 source: Box<disco::ParseError>, +1603 }, +1604} +1605 +1606#[derive(Debug)] +1607struct MagicUdpSocket { +1608 socket: Arc<MagicSock>, +1609 transports: Transports, +1610} +1611 +1612impl AsyncUdpSocket for MagicUdpSocket { +1613 fn create_sender(&self) -> Pin<Box<dyn quinn::UdpSender>> { +1614 Box::pin(self.transports.create_sender(self.socket.clone())) +1615 } +1616 +1617 /// NOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely. +1618 fn poll_recv( +1619 &mut self, +1620 cx: &mut Context, +1621 bufs: &mut [io::IoSliceMut<'_>], +1622 metas: &mut [quinn_udp::RecvMeta], +1623 ) -> Poll<io::Result<usize>> { +1624 self.transports.poll_recv(cx, bufs, metas, &self.socket) +1625 } +1626 +1627 #[cfg(not(wasm_browser))] +1628 fn local_addr(&self) -> io::Result<SocketAddr> { +1629 let addrs: Vec<_> = self +1630 .transports +1631 .local_addrs() +1632 .into_iter() +1633 .filter_map(|addr| { +1634 let addr: SocketAddr = addr.into_socket_addr()?; +1635 Some(addr) +1636 }) +1637 .collect(); +1638 +1639 if let Some(addr) = addrs.iter().find(|addr| addr.is_ipv6()) { +1640 return Ok(*addr); +1641 } +1642 if let Some(SocketAddr::V4(addr)) = addrs.first() { +1643 // Pretend to be IPv6, because our `MappedAddr`s need to be IPv6. +1644 let ip = addr.ip().to_ipv6_mapped().into(); +1645 return Ok(SocketAddr::new(ip, addr.port())); +1646 } +1647 +1648 Err(io::Error::other("no valid address available")) +1649 } +1650 +1651 #[cfg(wasm_browser)] +1652 fn local_addr(&self) -> io::Result<SocketAddr> { +1653 // Again, we need to pretend we're IPv6, because of our `MappedAddr`s. +1654 Ok(SocketAddr::new(std::net::Ipv6Addr::LOCALHOST.into(), 0)) +1655 } +1656 +1657 fn max_receive_segments(&self) -> usize { +1658 self.transports.max_receive_segments() +1659 } +1660 +1661 fn may_fragment(&self) -> bool { +1662 self.transports.may_fragment() +1663 } +1664} +1665 +1666#[derive(Debug)] +1667enum ActorMessage { +1668 Shutdown, +1669 PingActions(Vec<PingAction>), +1670 EndpointPingExpired(usize, stun_rs::TransactionId), +1671 NetReport( +1672 Result<Option<Arc<net_report::Report>>, NetReportError>, +1673 &'static str, +1674 ), +1675 NetworkChange, +1676 #[cfg(test)] +1677 ForceNetworkChange(bool), +1678} +1679 +1680struct Actor { +1681 msock: Arc<MagicSock>, +1682 msg_receiver: mpsc::Receiver<ActorMessage>, +1683 msg_sender: mpsc::Sender<ActorMessage>, +1684 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun. +1685 periodic_re_stun_timer: time::Interval, +1686 /// The `NetInfo` provided in the last call to `net_info_func`. It's used to deduplicate calls to netInfoFunc. +1687 net_info_last: Option<NetInfo>, +1688 +1689 #[cfg(not(wasm_browser))] +1690 port_mapper: portmapper::Client, +1691 +1692 /// Configuration for net report +1693 net_report_config: net_report::Options, +1694 +1695 /// Whether IPv4 UDP is known to be unable to transmit +1696 /// at all. This could happen if the socket is in an invalid state +1697 /// (as can happen on darwin after a network link status change). +1698 no_v4_send: bool, +1699 +1700 /// The prober that discovers local network conditions, including the closest relay relay and NAT mappings. +1701 net_reporter: net_report::Client, +1702 +1703 network_monitor: netmon::Monitor, +1704 network_change_sender: transports::NetworkChangeSender, +1705} +1706 +1707#[cfg(not(wasm_browser))] +1708fn bind_ip( +1709 addr_v4: SocketAddrV4, +1710 addr_v6: Option<SocketAddrV6>, +1711 metrics: &EndpointMetrics, +1712) -> io::Result<(Vec<IpTransport>, portmapper::Client)> { +1713 let port_mapper = +1714 portmapper::Client::with_metrics(Default::default(), metrics.portmapper.clone()); +1715 +1716 let v4 = Arc::new(bind_with_fallback(SocketAddr::V4(addr_v4))?); +1717 let ip4_port = v4.local_addr()?.port(); +1718 let ip6_port = ip4_port.checked_add(1).unwrap_or(ip4_port - 1); +1719 +1720 let addr_v6 = +1721 addr_v6.unwrap_or_else(|| SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, ip6_port, 0, 0)); +1722 +1723 let v6 = match bind_with_fallback(SocketAddr::V6(addr_v6)) { +1724 Ok(sock) => Some(Arc::new(sock)), +1725 Err(err) => { +1726 info!("bind ignoring IPv6 bind failure: {:?}", err); +1727 None +1728 } +1729 }; +1730 +1731 let port = v4.local_addr().map_or(0, |p| p.port()); 1732 -1733#[allow(missing_docs)] -1734#[common_fields({ -1735 backtrace: Option<snafu::Backtrace>, -1736 #[snafu(implicit)] -1737 span_trace: n0_snafu::SpanTrace, -1738})] -1739#[derive(Debug, Snafu)] -1740#[non_exhaustive] -1741pub enum CreateHandleError { -1742 #[snafu(display("Failed to create bind sockets"))] -1743 BindSockets { source: io::Error }, -1744 #[snafu(display("Failed to create internal quinn endpoint"))] -1745 CreateQuinnEndpoint { source: io::Error }, -1746 #[snafu(display("Failed to create socket state"))] -1747 CreateSocketState { source: io::Error }, -1748 #[snafu(display("Failed to create netmon monitor"))] -1749 CreateNetmonMonitor { source: netmon::Error }, -1750 #[snafu(display("Failed to subscribe netmon monitor"))] -1751 SubscribeNetmonMonitor { source: netmon::Error }, -1752} +1733 let mut ip = vec![IpTransport::new( +1734 addr_v4.into(), +1735 v4, +1736 metrics.magicsock.clone(), +1737 )]; +1738 if let Some(v6) = v6 { +1739 ip.push(IpTransport::new( +1740 addr_v6.into(), +1741 v6, +1742 metrics.magicsock.clone(), +1743 )) +1744 } +1745 +1746 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails +1747 match port.try_into() { +1748 Ok(non_zero_port) => { +1749 port_mapper.update_local_port(non_zero_port); +1750 } +1751 Err(_zero_port) => debug!("Skipping port mapping with zero local port"), +1752 } 1753 -1754impl Handle { -1755 /// Creates a magic [`MagicSock`] listening on [`Options::addr_v4`] and [`Options::addr_v6`]. -1756 async fn new(opts: Options) -> Result<Self, CreateHandleError> { -1757 let me = opts.secret_key.public().fmt_short(); -1758 -1759 Self::with_name(me, opts) -1760 .instrument(error_span!("magicsock")) -1761 .await -1762 } -1763 -1764 async fn with_name(me: String, opts: Options) -> Result<Self, CreateHandleError> { -1765 let Options { -1766 addr_v4, -1767 addr_v6, -1768 secret_key, -1769 relay_map, -1770 relay_protocol, -1771 node_map, -1772 discovery, -1773 discovery_user_data, -1774 #[cfg(not(wasm_browser))] -1775 dns_resolver, -1776 proxy_url, -1777 server_config, -1778 #[cfg(any(test, feature = "test-utils"))] -1779 insecure_skip_relay_cert_verify, -1780 #[cfg(any(test, feature = "test-utils"))] -1781 path_selection, -1782 metrics, -1783 } = opts; +1754 Ok((ip, port_mapper)) +1755} +1756 +1757#[derive(Debug, Snafu)] +1758#[non_exhaustive] +1759enum NetReportError { +1760 #[snafu(display("Net report not received"))] +1761 NotReceived, +1762 #[snafu(display("Net report timed out"))] +1763 Timeout, +1764 #[snafu(display("Net report encountered an error"))] +1765 NetReport { source: ReportError }, +1766} +1767 +1768impl Actor { +1769 async fn run( +1770 mut self, +1771 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, +1772 sender: UdpSender, +1773 ) { +1774 // Setup network monitoring +1775 let mut netmon_watcher = self.network_monitor.interface_state(); +1776 let mut current_netmon_state = netmon_watcher.get().expect("missing network state"); +1777 +1778 #[cfg(not(wasm_browser))] +1779 let mut direct_addr_heartbeat_timer = time::interval(HEARTBEAT_INTERVAL); +1780 let mut direct_addr_update_receiver = +1781 self.msock.direct_addr_update_state.running.subscribe(); +1782 #[cfg(not(wasm_browser))] +1783 let mut portmap_watcher = self.port_mapper.watch_external_address(); 1784 -1785 #[cfg(not(wasm_browser))] -1786 let actor_sockets = ActorSocketState::bind(addr_v4, addr_v6, metrics.portmapper.clone()) -1787 .context(BindSocketsSnafu)?; -1788 -1789 #[cfg(not(wasm_browser))] -1790 let sockets = actor_sockets -1791 .msock_socket_state() -1792 .context(CreateSocketStateSnafu)?; -1793 -1794 let ip_mapped_addrs = IpMappedAddresses::default(); +1785 let mut discovery_events: BoxStream<DiscoveryItem> = Box::pin(n0_future::stream::empty()); +1786 if let Some(d) = self.msock.discovery() { +1787 if let Some(events) = d.subscribe() { +1788 discovery_events = events; +1789 } +1790 } +1791 +1792 let mut receiver_closed = false; +1793 #[cfg_attr(wasm_browser, allow(unused_mut))] +1794 let mut portmap_watcher_closed = false; 1795 -1796 let net_reporter = net_report::Client::new( -1797 #[cfg(not(wasm_browser))] -1798 Some(actor_sockets.port_mapper.clone()), -1799 #[cfg(not(wasm_browser))] -1800 dns_resolver.clone(), -1801 #[cfg(not(wasm_browser))] -1802 Some(ip_mapped_addrs.clone()), -1803 metrics.net_report.clone(), -1804 ); -1805 -1806 let (actor_sender, actor_receiver) = mpsc::channel(256); -1807 let (relay_actor_sender, relay_actor_receiver) = mpsc::channel(256); -1808 let (relay_datagram_send_tx, relay_datagram_send_rx) = relay_datagram_send_channel(); -1809 let relay_datagram_recv_queue = Arc::new(RelayDatagramRecvQueue::new()); -1810 let (udp_disco_sender, mut udp_disco_receiver) = mpsc::channel(256); -1811 -1812 // load the node data -1813 let node_map = node_map.unwrap_or_default(); -1814 #[cfg(any(test, feature = "test-utils"))] -1815 let node_map = NodeMap::load_from_vec(node_map, path_selection, &metrics.magicsock); -1816 #[cfg(not(any(test, feature = "test-utils")))] -1817 let node_map = NodeMap::load_from_vec(node_map, &metrics.magicsock); -1818 -1819 let secret_encryption_key = secret_ed_box(secret_key.secret()); -1820 -1821 let msock = Arc::new(MagicSock { -1822 me, -1823 secret_key, -1824 secret_encryption_key, -1825 proxy_url, -1826 #[cfg(not(wasm_browser))] -1827 sockets, -1828 closing: AtomicBool::new(false), -1829 closed: AtomicBool::new(false), -1830 relay_datagram_recv_queue: relay_datagram_recv_queue.clone(), -1831 relay_datagram_send_channel: relay_datagram_send_tx, -1832 poll_recv_counter: AtomicUsize::new(0), -1833 actor_sender: actor_sender.clone(), -1834 ipv6_reported: Arc::new(AtomicBool::new(false)), -1835 relay_map, -1836 my_relay: Default::default(), -1837 net_reporter: net_reporter.addr(), -1838 disco_secrets: DiscoSecrets::default(), -1839 node_map, -1840 ip_mapped_addrs, -1841 udp_disco_sender, -1842 discovery, -1843 discovery_user_data: RwLock::new(discovery_user_data), -1844 direct_addrs: Default::default(), -1845 net_report: Default::default(), -1846 pending_call_me_maybes: Default::default(), -1847 direct_addr_update_state: DirectAddrUpdateState::new(), -1848 #[cfg(not(wasm_browser))] -1849 dns_resolver, -1850 #[cfg(any(test, feature = "test-utils"))] -1851 insecure_skip_relay_cert_verify, -1852 discovery_subscribers: DiscoverySubscribers::new(), -1853 metrics, -1854 }); -1855 -1856 let mut endpoint_config = quinn::EndpointConfig::default(); -1857 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit -1858 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet. -1859 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight -1860 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore -1861 // the packet if grease_quic_bit is set to false. -1862 endpoint_config.grease_quic_bit(false); -1863 -1864 let endpoint = quinn::Endpoint::new_with_abstract_socket( -1865 endpoint_config, -1866 Some(server_config), -1867 msock.clone(), -1868 #[cfg(not(wasm_browser))] -1869 Arc::new(quinn::TokioRuntime), -1870 #[cfg(wasm_browser)] -1871 Arc::new(crate::web_runtime::WebRuntime), -1872 ) -1873 .context(CreateQuinnEndpointSnafu)?; -1874 -1875 let mut actor_tasks = JoinSet::default(); -1876 -1877 let relay_actor = RelayActor::new(msock.clone(), relay_datagram_recv_queue, relay_protocol); -1878 let relay_actor_cancel_token = relay_actor.cancel_token(); -1879 actor_tasks.spawn( -1880 async move { -1881 relay_actor -1882 .run(relay_actor_receiver, relay_datagram_send_rx) -1883 .await; -1884 } -1885 .instrument(info_span!("relay-actor")), -1886 ); -1887 -1888 #[cfg(not(wasm_browser))] -1889 let _ = actor_tasks.spawn({ -1890 let msock = msock.clone(); -1891 async move { -1892 while let Some((dst, dst_key, msg)) = udp_disco_receiver.recv().await { -1893 if let Err(err) = msock.send_disco_message_udp(dst, dst_key, &msg).await { -1894 warn!(%dst, node = %dst_key.fmt_short(), ?err, "failed to send disco message (UDP)"); -1895 } +1796 loop { +1797 self.msock.metrics.magicsock.actor_tick_main.inc(); +1798 #[cfg(not(wasm_browser))] +1799 let portmap_watcher_changed = portmap_watcher.changed(); +1800 #[cfg(wasm_browser)] +1801 let portmap_watcher_changed = n0_future::future::pending(); +1802 +1803 #[cfg(not(wasm_browser))] +1804 let direct_addr_heartbeat_timer_tick = direct_addr_heartbeat_timer.tick(); +1805 #[cfg(wasm_browser)] +1806 let direct_addr_heartbeat_timer_tick = n0_future::future::pending(); +1807 +1808 tokio::select! { +1809 msg = self.msg_receiver.recv(), if !receiver_closed => { +1810 let Some(msg) = msg else { +1811 trace!("tick: magicsock receiver closed"); +1812 self.msock.metrics.magicsock.actor_tick_other.inc(); +1813 +1814 receiver_closed = true; +1815 continue; +1816 }; +1817 +1818 trace!(?msg, "tick: msg"); +1819 self.msock.metrics.magicsock.actor_tick_msg.inc(); +1820 if self.handle_actor_message(msg, &sender).await { +1821 return; +1822 } +1823 } +1824 tick = self.periodic_re_stun_timer.tick() => { +1825 trace!("tick: re_stun {:?}", tick); +1826 self.msock.metrics.magicsock.actor_tick_re_stun.inc(); +1827 self.msock.re_stun("periodic"); +1828 } +1829 new_addr = watcher.updated() => { +1830 match new_addr { +1831 Ok(addrs) => { +1832 if !addrs.is_empty() { +1833 trace!(?addrs, "local addrs"); +1834 self.msock.publish_my_addr(); +1835 } +1836 } +1837 Err(_) => { +1838 warn!("local addr watcher stopped"); +1839 } +1840 } +1841 } +1842 change = portmap_watcher_changed, if !portmap_watcher_closed => { +1843 #[cfg(not(wasm_browser))] +1844 { +1845 if change.is_err() { +1846 trace!("tick: portmap watcher closed"); +1847 self.msock.metrics.magicsock.actor_tick_other.inc(); +1848 +1849 portmap_watcher_closed = true; +1850 continue; +1851 } +1852 +1853 trace!("tick: portmap changed"); +1854 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc(); +1855 let new_external_address = *portmap_watcher.borrow(); +1856 debug!("external address updated: {new_external_address:?}"); +1857 self.msock.re_stun("portmap_updated"); +1858 } +1859 #[cfg(wasm_browser)] +1860 let _unused_in_browsers = change; +1861 }, +1862 _ = direct_addr_heartbeat_timer_tick => { +1863 #[cfg(not(wasm_browser))] +1864 { +1865 trace!( +1866 "tick: direct addr heartbeat {} direct addrs", +1867 self.msock.node_map.node_count(), +1868 ); +1869 self.msock.metrics.magicsock.actor_tick_direct_addr_heartbeat.inc(); +1870 // TODO: this might trigger too many packets at once, pace this +1871 +1872 self.msock.node_map.prune_inactive(); +1873 let msgs = self.msock.node_map.nodes_stayin_alive(); +1874 self.handle_ping_actions(&sender, msgs).await; +1875 } +1876 } +1877 _ = direct_addr_update_receiver.changed() => { +1878 let reason = *direct_addr_update_receiver.borrow(); +1879 trace!("tick: direct addr update receiver {:?}", reason); +1880 self.msock.metrics.magicsock.actor_tick_direct_addr_update_receiver.inc(); +1881 if let Some(reason) = reason { +1882 self.refresh_direct_addrs(reason).await; +1883 } +1884 } +1885 state = netmon_watcher.updated() => { +1886 let Ok(state) = state else { +1887 trace!("tick: link change receiver closed"); +1888 self.msock.metrics.magicsock.actor_tick_other.inc(); +1889 continue; +1890 }; +1891 let is_major = state.is_major_change(&current_netmon_state); +1892 current_netmon_state = state; +1893 trace!("tick: link change {}", is_major); +1894 self.msock.metrics.magicsock.actor_link_change.inc(); +1895 self.handle_network_change(is_major); 1896 } -1897 } -1898 }); -1899 -1900 let network_monitor = netmon::Monitor::new() -1901 .await -1902 .context(CreateNetmonMonitorSnafu)?; -1903 let qad_endpoint = endpoint.clone(); -1904 -1905 // create a client config for the endpoint to use for QUIC address discovery -1906 let root_store = -1907 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); -1908 let client_config = rustls::client::ClientConfig::builder_with_provider(Arc::new( -1909 rustls::crypto::ring::default_provider(), -1910 )) -1911 .with_safe_default_protocol_versions() -1912 .expect("ring supports these") -1913 .with_root_certificates(root_store) -1914 .with_no_client_auth(); -1915 -1916 #[cfg(not(wasm_browser))] -1917 let quic_config = Some(QuicConfig { -1918 ep: qad_endpoint, -1919 client_config, -1920 ipv4: true, -1921 ipv6: actor_sockets.v6.is_some(), -1922 }); -1923 #[cfg(not(wasm_browser))] -1924 let net_report_config = net_report::Options::default() -1925 .stun_v4(Some(actor_sockets.v4.clone())) -1926 .stun_v6(actor_sockets.v6.clone()) -1927 .quic_config(quic_config); -1928 #[cfg(wasm_browser)] -1929 let net_report_config = net_report::Options::default(); -1930 -1931 // Setup network monitoring -1932 let (link_change_s, link_change_r) = mpsc::channel(8); -1933 let netmon_token = network_monitor -1934 .subscribe(move |is_major| { -1935 let link_change_s = link_change_s.clone(); -1936 async move { -1937 link_change_s.send(is_major).await.ok(); -1938 } -1939 .boxed() -1940 }) -1941 .await -1942 .context(SubscribeNetmonMonitorSnafu)?; -1943 -1944 actor_tasks.spawn({ -1945 let msock = msock.clone(); -1946 async move { -1947 let actor = Actor { -1948 msg_receiver: actor_receiver, -1949 msg_sender: actor_sender, -1950 relay_actor_sender, -1951 relay_actor_cancel_token, -1952 msock, -1953 periodic_re_stun_timer: new_re_stun_timer(false), -1954 net_info_last: None, -1955 #[cfg(not(wasm_browser))] -1956 sockets: actor_sockets, -1957 no_v4_send: false, -1958 net_reporter, -1959 network_monitor, -1960 net_report_config, -1961 }; -1962 -1963 actor.run(link_change_r, netmon_token).await; -1964 } -1965 .instrument(info_span!("actor")) -1966 }); -1967 -1968 let c = Handle { -1969 msock, -1970 actor_tasks: Arc::new(Mutex::new(actor_tasks)), -1971 endpoint, -1972 }; -1973 -1974 Ok(c) -1975 } -1976 -1977 /// The underlying [`quinn::Endpoint`] -1978 pub fn endpoint(&self) -> &quinn::Endpoint { -1979 &self.endpoint -1980 } -1981 -1982 /// Closes the connection. -1983 /// -1984 /// Only the first close does anything. Any later closes return nil. -1985 /// Polling the socket ([`AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] -1986 /// indefinitely after this call. -1987 #[instrument(skip_all, fields(me = %self.msock.me))] -1988 pub(crate) async fn close(&self) { -1989 trace!("magicsock closing..."); -1990 // Initiate closing all connections, and refuse future connections. -1991 self.endpoint.close(0u16.into(), b""); -1992 -1993 // In the history of this code, this call had been -1994 // - removed: https://github.com/n0-computer/iroh/pull/1753 -1995 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 -1996 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 -1997 // and finally added back in together with this comment. -1998 // So before removing this call, please consider carefully. -1999 // Among other things, this call tries its best to make sure that any queued close frames -2000 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets -2001 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). -2002 // This allows the other endpoints for these connections to be notified to release -2003 // their resources, or - depending on the protocol - that all data was received. -2004 // With the current quinn API, this is the only way to ensure protocol code can use -2005 // connection close codes, and close the endpoint properly. -2006 // If this call is skipped, then connections that protocols close just shortly before the -2007 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. -2008 self.endpoint.wait_idle().await; -2009 -2010 if self.msock.is_closed() { -2011 return; -2012 } -2013 self.msock.closing.store(true, Ordering::Relaxed); -2014 // If this fails, then there's no receiver listening for shutdown messages, -2015 // so nothing to shut down anyways. -2016 self.msock -2017 .actor_sender -2018 .send(ActorMessage::Shutdown) -2019 .await -2020 .ok(); -2021 self.msock.closed.store(true, Ordering::SeqCst); -2022 -2023 let mut tasks = self.actor_tasks.lock().await; -2024 -2025 // give the tasks a moment to shutdown cleanly -2026 let tasks_ref = &mut tasks; -2027 let shutdown_done = time::timeout(Duration::from_millis(100), async move { -2028 while let Some(task) = tasks_ref.join_next().await { -2029 if let Err(err) = task { -2030 warn!("unexpected error in task shutdown: {:?}", err); -2031 } -2032 } -2033 }) -2034 .await; -2035 match shutdown_done { -2036 Ok(_) => trace!("tasks finished in time, shutdown complete"), -2037 Err(_elapsed) => { -2038 // shutdown all tasks -2039 warn!( -2040 "tasks didn't finish in time, aborting remaining {}/3 tasks", -2041 tasks.len() -2042 ); -2043 tasks.shutdown().await; -2044 } -2045 } -2046 trace!("magicsock closed"); -2047 } -2048} -2049 -2050#[derive(Debug, Default)] -2051struct DiscoSecrets(std::sync::Mutex<HashMap<PublicKey, SharedSecret>>); -2052 -2053impl DiscoSecrets { -2054 fn get<F, T>(&self, secret: &crypto_box::SecretKey, node_id: PublicKey, cb: F) -> T -2055 where -2056 F: FnOnce(&mut SharedSecret) -> T, -2057 { -2058 let mut inner = self.0.lock().expect("poisoned"); -2059 let x = inner.entry(node_id).or_insert_with(|| { -2060 let public_key = public_ed_box(&node_id.public()); -2061 SharedSecret::new(secret, &public_key) -2062 }); -2063 cb(x) -2064 } -2065 -2066 fn encode_and_seal( -2067 &self, -2068 this_secret_key: &crypto_box::SecretKey, -2069 this_node_id: NodeId, -2070 other_node_id: NodeId, -2071 msg: &disco::Message, -2072 ) -> Bytes { -2073 let mut seal = msg.as_bytes(); -2074 self.get(this_secret_key, other_node_id, |secret| { -2075 secret.seal(&mut seal) -2076 }); -2077 disco::encode_message(&this_node_id, seal).into() -2078 } -2079 fn unseal_and_decode( -2080 &self, -2081 secret: &crypto_box::SecretKey, -2082 node_id: PublicKey, -2083 mut sealed_box: Vec<u8>, -2084 ) -> Result<disco::Message, DiscoBoxError> { -2085 self.get(secret, node_id, |secret| secret.open(&mut sealed_box)) -2086 .context(OpenSnafu)?; -2087 disco::Message::from_bytes(&sealed_box).context(ParseSnafu) -2088 } -2089} -2090 -2091#[allow(missing_docs)] -2092#[common_fields({ -2093 backtrace: Option<snafu::Backtrace>, -2094 #[snafu(implicit)] -2095 span_trace: n0_snafu::SpanTrace, -2096})] -2097#[derive(Debug, Snafu)] -2098#[non_exhaustive] -2099enum DiscoBoxError { -2100 #[snafu(display("Failed to open crypto box"))] -2101 Open { -2102 #[snafu(source(from(DecryptionError, Box::new)))] -2103 source: Box<DecryptionError>, -2104 }, -2105 #[snafu(display("Failed to parse disco message"))] -2106 Parse { -2107 #[snafu(source(from(disco::ParseError, Box::new)))] -2108 source: Box<disco::ParseError>, -2109 }, -2110} -2111 -2112/// Creates a sender and receiver pair for sending datagrams to the [`RelayActor`]. -2113/// -2114/// These includes the waker coordination required to support [`AsyncUdpSocket::try_send`] -2115/// and [`quinn::UdpPoller::poll_writable`]. -2116fn relay_datagram_send_channel() -> ( -2117 RelayDatagramSendChannelSender, -2118 RelayDatagramSendChannelReceiver, -2119) { -2120 let (sender, receiver) = mpsc::channel(256); -2121 let wakers = Arc::new(std::sync::Mutex::new(Vec::new())); -2122 let tx = RelayDatagramSendChannelSender { -2123 sender, -2124 wakers: wakers.clone(), -2125 }; -2126 let rx = RelayDatagramSendChannelReceiver { receiver, wakers }; -2127 (tx, rx) -2128} -2129 -2130/// Sender to send datagrams to the [`RelayActor`]. -2131/// -2132/// This includes the waker coordination required to support [`AsyncUdpSocket::try_send`] -2133/// and [`quinn::UdpPoller::poll_writable`]. -2134#[derive(Debug, Clone)] -2135struct RelayDatagramSendChannelSender { -2136 sender: mpsc::Sender<RelaySendItem>, -2137 wakers: Arc<std::sync::Mutex<Vec<Waker>>>, -2138} +1897 // Even if `discovery_events` yields `None`, it could begin to yield +1898 // `Some` again in the future, so we don't want to disable this branch +1899 // forever like we do with the other branches that yield `Option`s +1900 Some(discovery_item) = discovery_events.next() => { +1901 trace!("tick: discovery event, address discovered: {discovery_item:?}"); +1902 let provenance = discovery_item.provenance(); +1903 let node_addr = discovery_item.to_node_addr(); +1904 if let Err(e) = self.msock.add_node_addr( +1905 node_addr, +1906 Source::Discovery { +1907 name: provenance.to_string() +1908 }) { +1909 let node_addr = discovery_item.to_node_addr(); +1910 warn!(?node_addr, "unable to add discovered node address to the node map: {e:?}"); +1911 } +1912 // Send the discovery item to the subscribers of the discovery broadcast stream. +1913 self.msock.discovery_subscribers.send(discovery_item); +1914 } +1915 } +1916 } +1917 } +1918 +1919 fn handle_network_change(&mut self, is_major: bool) { +1920 debug!("link change detected: major? {}", is_major); +1921 +1922 if is_major { +1923 if let Err(err) = self.network_change_sender.rebind() { +1924 warn!("failed to rebind transports: {:?}", err); +1925 } +1926 +1927 #[cfg(not(wasm_browser))] +1928 self.msock.dns_resolver.clear_cache(); +1929 self.msock.re_stun("link-change-major"); +1930 self.reset_endpoint_states(); +1931 } else { +1932 self.msock.re_stun("link-change-minor"); +1933 } +1934 } +1935 +1936 #[instrument(skip_all)] +1937 async fn handle_ping_actions(&mut self, sender: &UdpSender, msgs: Vec<PingAction>) { +1938 if let Err(err) = self.msock.send_ping_actions(sender, msgs).await { +1939 warn!("Failed to send ping actions: {err:#}"); +1940 } +1941 } +1942 +1943 /// Processes an incoming actor message. +1944 /// +1945 /// Returns `true` if it was a shutdown. +1946 async fn handle_actor_message(&mut self, msg: ActorMessage, sender: &UdpSender) -> bool { +1947 match msg { +1948 ActorMessage::Shutdown => { +1949 debug!("shutting down"); +1950 +1951 self.msock.node_map.notify_shutdown(); +1952 #[cfg(not(wasm_browser))] +1953 self.port_mapper.deactivate(); +1954 +1955 debug!("shutdown complete"); +1956 return true; +1957 } +1958 ActorMessage::EndpointPingExpired(id, txid) => { +1959 self.msock.node_map.notify_ping_timeout(id, txid); +1960 } +1961 ActorMessage::NetReport(report, why) => { +1962 match report { +1963 Ok(report) => { +1964 self.handle_net_report_report(report).await; +1965 } +1966 Err(err) => { +1967 warn!( +1968 "failed to generate net_report report for: {}: {:?}", +1969 why, err +1970 ); +1971 } +1972 } +1973 self.finalize_direct_addrs_update(why); +1974 } +1975 ActorMessage::NetworkChange => { +1976 self.network_monitor.network_change().await.ok(); +1977 } +1978 #[cfg(test)] +1979 ActorMessage::ForceNetworkChange(is_major) => { +1980 self.handle_network_change(is_major); +1981 } +1982 ActorMessage::PingActions(ping_actions) => { +1983 self.handle_ping_actions(sender, ping_actions).await; +1984 } +1985 } +1986 +1987 false +1988 } +1989 +1990 /// Refreshes knowledge about our direct addresses. +1991 /// +1992 /// In other words, this triggers a net_report run. +1993 /// +1994 /// Note that invoking this is managed by the [`DirectAddrUpdateState`] and this should +1995 /// never be invoked directly. Some day this will be refactored to not allow this easy +1996 /// mistake to be made. +1997 #[instrument(level = "debug", skip_all)] +1998 async fn refresh_direct_addrs(&mut self, why: &'static str) { +1999 self.msock.metrics.magicsock.update_direct_addrs.inc(); +2000 +2001 debug!("starting direct addr update ({})", why); +2002 #[cfg(not(wasm_browser))] +2003 self.port_mapper.procure_mapping(); +2004 self.update_net_info(why).await; +2005 } +2006 +2007 /// Updates the direct addresses of this magic socket. +2008 /// +2009 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of +2010 /// direct addresses from: +2011 /// +2012 /// - The portmapper. +2013 /// - A net_report report. +2014 /// - The local interfaces IP addresses. +2015 #[cfg(not(wasm_browser))] +2016 fn update_direct_addresses(&mut self, net_report_report: Option<Arc<net_report::Report>>) { +2017 let portmap_watcher = self.port_mapper.watch_external_address(); +2018 +2019 // We only want to have one DirectAddr for each SocketAddr we have. So we store +2020 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a +2021 // DirectAddr from each entry. +2022 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new(); +2023 +2024 // First add PortMapper provided addresses. +2025 let maybe_port_mapped = *portmap_watcher.borrow(); +2026 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { +2027 addrs +2028 .entry(portmap_ext) +2029 .or_insert(DirectAddrType::Portmapped); +2030 self.set_net_info_have_port_map(); +2031 } +2032 +2033 // Next add STUN addresses from the net_report report. +2034 if let Some(net_report_report) = net_report_report { +2035 if let Some(global_v4) = net_report_report.global_v4 { +2036 addrs +2037 .entry(global_v4.into()) +2038 .or_insert(DirectAddrType::Stun); +2039 +2040 // If they're behind a hard NAT and are using a fixed +2041 // port locally, assume they might've added a static +2042 // port mapping on their router to the same explicit +2043 // port that we are running with. Worst case it's an invalid candidate mapping. +2044 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| { +2045 if addr.port() != 0 { +2046 Some(addr.port()) +2047 } else { +2048 None +2049 } +2050 }); +2051 +2052 if let Some(port) = port { +2053 if net_report_report +2054 .mapping_varies_by_dest_ip +2055 .unwrap_or_default() +2056 { +2057 let mut addr = global_v4; +2058 addr.set_port(port); +2059 addrs +2060 .entry(addr.into()) +2061 .or_insert(DirectAddrType::Stun4LocalPort); +2062 } +2063 } +2064 } +2065 if let Some(global_v6) = net_report_report.global_v6 { +2066 addrs +2067 .entry(global_v6.into()) +2068 .or_insert(DirectAddrType::Stun); +2069 } +2070 } +2071 +2072 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self +2073 .msock +2074 .ip_bind_addrs() +2075 .iter() +2076 .copied() +2077 .zip(self.msock.ip_local_addrs()) +2078 .collect(); +2079 +2080 let msock = self.msock.clone(); +2081 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { +2082 if a.is_ipv4() && a.ip().is_unspecified() { +2083 Some(a.port()) +2084 } else { +2085 None +2086 } +2087 }); +2088 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { +2089 if a.is_ipv6() && a.ip().is_unspecified() { +2090 Some(a.port()) +2091 } else { +2092 None +2093 } +2094 }); +2095 +2096 // The following code can be slow, we do not want to block the caller since it would +2097 // block the actor loop. +2098 task::spawn( +2099 async move { +2100 // If a socket is bound to the unspecified address, create SocketAddrs for +2101 // each local IP address by pairing it with the port the socket is bound on. +2102 if local_addrs +2103 .iter() +2104 .any(|(_, local)| local.ip().is_unspecified()) +2105 { +2106 // Depending on the OS and network interfaces attached and their state +2107 // enumerating the local interfaces can take a long time. Especially +2108 // Windows is very slow. +2109 let LocalAddresses { +2110 regular: mut ips, +2111 loopback, +2112 } = tokio::task::spawn_blocking(LocalAddresses::new) +2113 .await +2114 .expect("spawn panicked"); +2115 if ips.is_empty() && addrs.is_empty() { +2116 // Include loopback addresses only if there are no other interfaces +2117 // or public addresses, this allows testing offline. +2118 ips = loopback; +2119 } +2120 +2121 for ip in ips { +2122 let port_if_unspecified = match ip { +2123 IpAddr::V4(_) => has_ipv4_unspecified, +2124 IpAddr::V6(_) => has_ipv6_unspecified, +2125 }; +2126 if let Some(port) = port_if_unspecified { +2127 let addr = SocketAddr::new(ip, port); +2128 addrs.entry(addr).or_insert(DirectAddrType::Local); +2129 } +2130 } +2131 } +2132 +2133 // If a socket is bound to a specific address, add it. +2134 for (bound, local) in local_addrs { +2135 if !bound.ip().is_unspecified() { +2136 addrs.entry(local).or_insert(DirectAddrType::Local); +2137 } +2138 } 2139 -2140impl RelayDatagramSendChannelSender { -2141 fn try_send( -2142 &self, -2143 item: RelaySendItem, -2144 ) -> Result<(), mpsc::error::TrySendError<RelaySendItem>> { -2145 self.sender.try_send(item) -2146 } -2147 -2148 fn poll_writable(&self, cx: &mut Context) -> Poll<io::Result<()>> { -2149 match self.sender.capacity() { -2150 0 => { -2151 let mut wakers = self.wakers.lock().expect("poisoned"); -2152 if !wakers.iter().any(|waker| waker.will_wake(cx.waker())) { -2153 wakers.push(cx.waker().clone()); -2154 } -2155 drop(wakers); -2156 if self.sender.capacity() != 0 { -2157 // We "risk" a spurious wake-up in this case, but rather that -2158 // than potentially skipping a receive. -2159 Poll::Ready(Ok(())) -2160 } else { -2161 Poll::Pending -2162 } -2163 } -2164 _ => Poll::Ready(Ok(())), -2165 } -2166 } -2167} -2168 -2169/// Receiver to send datagrams to the [`RelayActor`]. -2170/// -2171/// This includes the waker coordination required to support [`AsyncUdpSocket::try_send`] -2172/// and [`quinn::UdpPoller::poll_writable`]. -2173#[derive(Debug)] -2174struct RelayDatagramSendChannelReceiver { -2175 receiver: mpsc::Receiver<RelaySendItem>, -2176 wakers: Arc<std::sync::Mutex<Vec<Waker>>>, -2177} -2178 -2179impl RelayDatagramSendChannelReceiver { -2180 async fn recv(&mut self) -> Option<RelaySendItem> { -2181 let item = self.receiver.recv().await; -2182 let mut wakers = self.wakers.lock().expect("poisoned"); -2183 wakers.drain(..).for_each(Waker::wake); -2184 item -2185 } -2186} +2140 // Finally create and store store all these direct addresses and send any +2141 // queued call-me-maybe messages. +2142 msock.store_direct_addresses( +2143 addrs +2144 .iter() +2145 .map(|(addr, typ)| DirectAddr { +2146 addr: *addr, +2147 typ: *typ, +2148 }) +2149 .collect(), +2150 ); +2151 msock.send_queued_call_me_maybes(); +2152 } +2153 .instrument(Span::current()), +2154 ); +2155 } +2156 +2157 /// Called when a direct addr update is done, no matter if it was successful or not. +2158 fn finalize_direct_addrs_update(&mut self, why: &'static str) { +2159 let new_why = self.msock.direct_addr_update_state.next_update(); +2160 if !self.msock.is_closed() { +2161 if let Some(new_why) = new_why { +2162 self.msock.direct_addr_update_state.run(new_why); +2163 return; +2164 } +2165 #[cfg(not(wasm_browser))] +2166 { +2167 self.periodic_re_stun_timer = new_re_stun_timer(true); +2168 } +2169 } +2170 +2171 self.msock.direct_addr_update_state.finish_run(); +2172 debug!("direct addr update done ({})", why); +2173 } +2174 +2175 /// Updates `NetInfo.HavePortMap` to true. +2176 #[instrument(level = "debug", skip_all)] +2177 fn set_net_info_have_port_map(&mut self) { +2178 if let Some(ref mut net_info_last) = self.net_info_last { +2179 if net_info_last.have_port_map { +2180 // No change. +2181 return; +2182 } +2183 net_info_last.have_port_map = true; +2184 self.net_info_last = Some(net_info_last.clone()); +2185 } +2186 } 2187 -2188/// A queue holding [`RelayRecvDatagram`]s that can be polled in async -2189/// contexts, and wakes up tasks when something adds items using [`try_send`]. -2190/// -2191/// This is used to transfer relay datagrams between the [`RelayActor`] -2192/// and [`MagicSock`]. -2193/// -2194/// [`try_send`]: Self::try_send -2195/// [`RelayActor`]: crate::magicsock::RelayActor -2196/// [`MagicSock`]: crate::magicsock::MagicSock -2197#[derive(Debug)] -2198struct RelayDatagramRecvQueue { -2199 queue: ConcurrentQueue<RelayRecvDatagram>, -2200 waker: AtomicWaker, -2201} -2202 -2203#[derive(Debug, Snafu)] -2204#[non_exhaustive] -2205enum RelayRecvDatagramError { -2206 #[snafu(display("Queue is closed"))] -2207 Closed, -2208} -2209 -2210impl RelayDatagramRecvQueue { -2211 /// Creates a new, empty queue with a fixed size bound of 512 items. -2212 fn new() -> Self { -2213 Self { -2214 queue: ConcurrentQueue::bounded(512), -2215 waker: AtomicWaker::new(), -2216 } -2217 } -2218 -2219 /// Sends an item into this queue and wakes a potential task -2220 /// that's registered its waker with a [`poll_recv`] call. -2221 /// -2222 /// [`poll_recv`]: Self::poll_recv -2223 fn try_send( -2224 &self, -2225 item: RelayRecvDatagram, -2226 ) -> Result<(), concurrent_queue::PushError<RelayRecvDatagram>> { -2227 self.queue.push(item).inspect(|_| { -2228 self.waker.wake(); -2229 }) -2230 } -2231 -2232 /// Polls for new items in the queue. -2233 /// -2234 /// Although this method is available from `&self`, it must not be -2235 /// polled concurrently between tasks. -2236 /// -2237 /// Calling this will replace the current waker used. So if another task -2238 /// waits for this, that task's waker will be replaced and it won't be -2239 /// woken up for new items. -2240 /// -2241 /// The reason this method is made available as `&self` is because -2242 /// the interface for quinn's [`AsyncUdpSocket::poll_recv`] requires us -2243 /// to be able to poll from `&self`. -2244 fn poll_recv( -2245 &self, -2246 cx: &mut Context, -2247 ) -> Poll<Result<RelayRecvDatagram, RelayRecvDatagramError>> { -2248 match self.queue.pop() { -2249 Ok(value) => Poll::Ready(Ok(value)), -2250 Err(concurrent_queue::PopError::Empty) => { -2251 self.waker.register(cx.waker()); -2252 -2253 match self.queue.pop() { -2254 Ok(value) => { -2255 self.waker.take(); -2256 Poll::Ready(Ok(value)) -2257 } -2258 Err(concurrent_queue::PopError::Empty) => Poll::Pending, -2259 Err(concurrent_queue::PopError::Closed) => { -2260 self.waker.take(); -2261 Poll::Ready(Err(ClosedSnafu.build())) -2262 } -2263 } -2264 } -2265 Err(concurrent_queue::PopError::Closed) => Poll::Ready(Err(ClosedSnafu.build())), -2266 } -2267 } -2268} -2269 -2270impl AsyncUdpSocket for MagicSock { -2271 fn create_io_poller(self: Arc<Self>) -> Pin<Box<dyn quinn::UdpPoller>> { -2272 // To do this properly the MagicSock would need a registry of pollers. For each -2273 // node we would look up the poller or create one. Then on each try_send we can -2274 // look up the correct poller and configure it to poll the paths it needs. -2275 // -2276 // Note however that the current quinn impl calls UdpPoller::poll_writable() -2277 // **before** it calls try_send(), as opposed to how it is documented. That is a -2278 // problem as we would not yet know the path that needs to be polled. To avoid such -2279 // ambiguity the API could be changed to a .poll_send(&self, cx: &mut Context, -2280 // io_poller: Pin<&mut dyn UdpPoller>, transmit: &Transmit) -> Poll<io::Result<()>> -2281 // instead of the existing .try_send() because then we would have control over this. -2282 // -2283 // Right now however we have one single poller behaving the same for each -2284 // connection. It checks all paths and returns Poll::Ready as soon as any path is -2285 // ready. -2286 #[cfg(not(wasm_browser))] -2287 let ipv4_poller = self.sockets.v4.create_io_poller(); -2288 #[cfg(not(wasm_browser))] -2289 let ipv6_poller = self.sockets.v6.as_ref().map(|sock| sock.create_io_poller()); -2290 let relay_sender = self.relay_datagram_send_channel.clone(); -2291 Box::pin(IoPoller { -2292 #[cfg(not(wasm_browser))] -2293 ipv4_poller, -2294 #[cfg(not(wasm_browser))] -2295 ipv6_poller, -2296 relay_sender, -2297 }) -2298 } -2299 -2300 fn try_send(&self, transmit: &quinn_udp::Transmit) -> io::Result<()> { -2301 self.try_send(transmit) -2302 } -2303 -2304 /// NOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely. -2305 fn poll_recv( -2306 &self, -2307 cx: &mut Context, -2308 bufs: &mut [io::IoSliceMut<'_>], -2309 metas: &mut [quinn_udp::RecvMeta], -2310 ) -> Poll<io::Result<usize>> { -2311 self.poll_recv(cx, bufs, metas) -2312 } -2313 -2314 fn local_addr(&self) -> io::Result<SocketAddr> { -2315 #[cfg(not(wasm_browser))] -2316 match &*self.sockets.local_addrs.read().expect("not poisoned") { -2317 (ipv4, None) => { -2318 // Pretend to be IPv6, because our `MappedAddr`s -2319 // need to be IPv6. -2320 let ip: IpAddr = match ipv4.ip() { -2321 IpAddr::V4(ip) => ip.to_ipv6_mapped().into(), -2322 IpAddr::V6(ip) => ip.into(), -2323 }; -2324 Ok(SocketAddr::new(ip, ipv4.port())) -2325 } -2326 (_, Some(ipv6)) => Ok(*ipv6), -2327 } -2328 // Again, we need to pretend we're IPv6, because of our `MappedAddr`s. -2329 #[cfg(wasm_browser)] -2330 return Ok(SocketAddr::new(std::net::Ipv6Addr::LOCALHOST.into(), 0)); -2331 } -2332 -2333 #[cfg(not(wasm_browser))] -2334 fn max_transmit_segments(&self) -> usize { -2335 if let Some(socket) = self.sockets.v6.as_ref() { -2336 std::cmp::min( -2337 socket.max_transmit_segments(), -2338 self.sockets.v4.max_transmit_segments(), -2339 ) -2340 } else { -2341 self.sockets.v4.max_transmit_segments() -2342 } -2343 } -2344 -2345 #[cfg(wasm_browser)] -2346 fn max_transmit_segments(&self) -> usize { -2347 1 -2348 } -2349 -2350 #[cfg(not(wasm_browser))] -2351 fn max_receive_segments(&self) -> usize { -2352 if let Some(socket) = self.sockets.v6.as_ref() { -2353 // `max_receive_segments` controls the size of the `RecvMeta` buffer -2354 // that quinn creates. Having buffers slightly bigger than necessary -2355 // isn't terrible, and makes sure a single socket can read the maximum -2356 // amount with a single poll. We considered adding these numbers instead, -2357 // but we never get data from both sockets at the same time in `poll_recv` -2358 // and it's impossible and unnecessary to be refactored that way. -2359 std::cmp::max( -2360 socket.max_receive_segments(), -2361 self.sockets.v4.max_receive_segments(), -2362 ) -2363 } else { -2364 self.sockets.v4.max_receive_segments() -2365 } -2366 } -2367 -2368 #[cfg(wasm_browser)] -2369 fn max_receive_segments(&self) -> usize { -2370 1 -2371 } -2372 -2373 #[cfg(not(wasm_browser))] -2374 fn may_fragment(&self) -> bool { -2375 if let Some(socket) = self.sockets.v6.as_ref() { -2376 socket.may_fragment() || self.sockets.v4.may_fragment() -2377 } else { -2378 self.sockets.v4.may_fragment() -2379 } -2380 } -2381 -2382 #[cfg(wasm_browser)] -2383 fn may_fragment(&self) -> bool { -2384 false -2385 } -2386} -2387 -2388#[derive(Debug)] -2389struct IoPoller { -2390 #[cfg(not(wasm_browser))] -2391 ipv4_poller: Pin<Box<dyn quinn::UdpPoller>>, -2392 #[cfg(not(wasm_browser))] -2393 ipv6_poller: Option<Pin<Box<dyn quinn::UdpPoller>>>, -2394 relay_sender: RelayDatagramSendChannelSender, -2395} -2396 -2397impl quinn::UdpPoller for IoPoller { -2398 fn poll_writable(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> { -2399 // This version returns Ready as soon as any of them are ready. -2400 let this = &mut *self; -2401 #[cfg(not(wasm_browser))] -2402 match this.ipv4_poller.as_mut().poll_writable(cx) { -2403 Poll::Ready(_) => return Poll::Ready(Ok(())), -2404 Poll::Pending => (), -2405 } -2406 #[cfg(not(wasm_browser))] -2407 if let Some(ref mut ipv6_poller) = this.ipv6_poller { -2408 match ipv6_poller.as_mut().poll_writable(cx) { -2409 Poll::Ready(_) => return Poll::Ready(Ok(())), -2410 Poll::Pending => (), -2411 } +2188 #[instrument(level = "debug", skip_all)] +2189 async fn call_net_info_callback(&mut self, ni: NetInfo) { +2190 if let Some(ref net_info_last) = self.net_info_last { +2191 if ni.basically_equal(net_info_last) { +2192 return; +2193 } +2194 } +2195 +2196 self.net_info_last = Some(ni); +2197 } +2198 +2199 /// Calls net_report. +2200 /// +2201 /// Note that invoking this is managed by [`DirectAddrUpdateState`] via +2202 /// [`Actor::refresh_direct_addrs`] and this should never be invoked directly. Some day +2203 /// this will be refactored to not allow this easy mistake to be made. +2204 #[instrument(level = "debug", skip_all)] +2205 async fn update_net_info(&mut self, why: &'static str) { +2206 // Don't start a net report probe if we know +2207 // we are shutting down +2208 if self.msock.is_closing() || self.msock.is_closed() { +2209 debug!("skipping net_report, socket is shutting down"); +2210 return; +2211 } +2212 if self.msock.relay_map.is_empty() { +2213 debug!("skipping net_report, empty RelayMap"); +2214 self.msg_sender +2215 .send(ActorMessage::NetReport(Ok(None), why)) +2216 .await +2217 .ok(); +2218 return; +2219 } +2220 +2221 let relay_map = self.msock.relay_map.clone(); +2222 let opts = self.net_report_config.clone(); +2223 +2224 debug!("requesting net_report report"); +2225 match self.net_reporter.get_report_channel(relay_map, opts).await { +2226 Ok(rx) => { +2227 let msg_sender = self.msg_sender.clone(); +2228 task::spawn(async move { +2229 let report = time::timeout(NET_REPORT_TIMEOUT, rx).await; +2230 let report = match report { +2231 Ok(Ok(Ok(report))) => Ok(Some(report)), +2232 Ok(Ok(Err(err))) => Err(NetReportSnafu.into_error(err)), +2233 Ok(Err(_)) => Err(NotReceivedSnafu.build()), +2234 Err(_) => Err(TimeoutSnafu.build()), +2235 }; +2236 msg_sender +2237 .send(ActorMessage::NetReport(report, why)) +2238 .await +2239 .ok(); +2240 // The receiver of the NetReport message will call +2241 // .finalize_direct_addrs_update(). +2242 }); +2243 } +2244 Err(err) => { +2245 warn!("unable to start net_report generation: {:?}", err); +2246 self.finalize_direct_addrs_update(why); +2247 } +2248 } +2249 } +2250 +2251 async fn handle_net_report_report(&mut self, report: Option<Arc<net_report::Report>>) { +2252 if let Some(ref report) = report { +2253 // only returns Err if the report hasn't changed. +2254 self.msock.net_report.set(Some(report.clone())).ok(); +2255 self.msock +2256 .ipv6_reported +2257 .store(report.ipv6, Ordering::Relaxed); +2258 let r = &report; +2259 trace!( +2260 "setting no_v4_send {} -> {}", +2261 self.no_v4_send, +2262 !r.ipv4_can_send +2263 ); +2264 self.no_v4_send = !r.ipv4_can_send; +2265 +2266 #[cfg(not(wasm_browser))] +2267 let have_port_map = self.port_mapper.watch_external_address().borrow().is_some(); +2268 #[cfg(wasm_browser)] +2269 let have_port_map = false; +2270 +2271 let mut ni = NetInfo { +2272 relay_latency: Default::default(), +2273 mapping_varies_by_dest_ip: r.mapping_varies_by_dest_ip, +2274 hair_pinning: r.hair_pinning, +2275 #[cfg(not(wasm_browser))] +2276 portmap_probe: r.portmap_probe.clone(), +2277 have_port_map, +2278 working_ipv6: Some(r.ipv6), +2279 os_has_ipv6: Some(r.os_has_ipv6), +2280 working_udp: Some(r.udp), +2281 working_icmp_v4: r.icmpv4, +2282 working_icmp_v6: r.icmpv6, +2283 preferred_relay: r.preferred_relay.clone(), +2284 }; +2285 for (rid, d) in r.relay_v4_latency.iter() { +2286 ni.relay_latency +2287 .insert(format!("{rid}-v4"), d.as_secs_f64()); +2288 } +2289 for (rid, d) in r.relay_v6_latency.iter() { +2290 ni.relay_latency +2291 .insert(format!("{rid}-v6"), d.as_secs_f64()); +2292 } +2293 +2294 if ni.preferred_relay.is_none() { +2295 // Perhaps UDP is blocked. Pick a deterministic but arbitrary one. +2296 ni.preferred_relay = self.pick_relay_fallback(); +2297 } +2298 +2299 // Notify all transports +2300 self.network_change_sender.on_network_change(&ni); +2301 +2302 // TODO: set link type +2303 self.call_net_info_callback(ni).await; +2304 } +2305 #[cfg(not(wasm_browser))] +2306 self.update_direct_addresses(report); +2307 } +2308 +2309 /// Returns a deterministic relay node to connect to. This is only used if net_report +2310 /// couldn't find the nearest one, for instance, if UDP is blocked and thus STUN +2311 /// latency checks aren't working. +2312 /// +2313 /// If no the [`RelayMap`] is empty, returns `0`. +2314 fn pick_relay_fallback(&self) -> Option<RelayUrl> { +2315 // TODO: figure out which relay node most of our nodes are using, +2316 // and use that region as our fallback. +2317 // +2318 // If we already had selected something in the past and it has any +2319 // nodes, we want to stay on it. If there are no nodes at all, +2320 // stay on whatever relay we previously picked. If we need to pick +2321 // one and have no node info, pick a node randomly. +2322 // +2323 // We used to do the above for legacy clients, but never updated it for disco. +2324 +2325 let my_relay = self.msock.my_relay(); +2326 if my_relay.is_some() { +2327 return my_relay; +2328 } +2329 +2330 let ids = self.msock.relay_map.urls().collect::<Vec<_>>(); +2331 let mut rng = rand::rngs::StdRng::seed_from_u64(0); +2332 ids.choose(&mut rng).map(|c| (*c).clone()) +2333 } +2334 +2335 /// Resets the preferred address for all nodes. +2336 /// This is called when connectivity changes enough that we no longer trust the old routes. +2337 #[instrument(skip_all, fields(me = %self.msock.me))] +2338 fn reset_endpoint_states(&mut self) { +2339 self.msock.node_map.reset_node_states() +2340 } +2341} +2342 +2343fn new_re_stun_timer(initial_delay: bool) -> time::Interval { +2344 // Pick a random duration between 20 and 26 seconds (just under 30s, +2345 // a common UDP NAT timeout on Linux,etc) +2346 let mut rng = rand::thread_rng(); +2347 let d: Duration = rng.gen_range(Duration::from_secs(20)..=Duration::from_secs(26)); +2348 if initial_delay { +2349 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); +2350 time::interval_at(time::Instant::now() + d, d) +2351 } else { +2352 debug!( +2353 "scheduling periodic_stun to run immediately and in {}s", +2354 d.as_secs() +2355 ); +2356 time::interval(d) +2357 } +2358} +2359 +2360#[cfg(not(wasm_browser))] +2361fn bind_with_fallback(mut addr: SocketAddr) -> io::Result<UdpSocket> { +2362 debug!(%addr, "binding"); +2363 +2364 // First try binding a preferred port, if specified +2365 match UdpSocket::bind_full(addr) { +2366 Ok(socket) => { +2367 let local_addr = socket.local_addr()?; +2368 debug!(%addr, %local_addr, "successfully bound"); +2369 return Ok(socket); +2370 } +2371 Err(err) => { +2372 debug!(%addr, "failed to bind: {err:#}"); +2373 // If that was already the fallback port, then error out +2374 if addr.port() == 0 { +2375 return Err(err); +2376 } +2377 } +2378 } +2379 +2380 // Otherwise, try binding with port 0 +2381 addr.set_port(0); +2382 UdpSocket::bind_full(addr) +2383} +2384 +2385/// The discovered direct addresses of this [`MagicSock`]. +2386/// +2387/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself. +2388/// They include all locally bound ones as well as those discovered by other mechanisms like +2389/// STUN. +2390#[derive(derive_more::Debug, Default, Clone)] +2391struct DiscoveredDirectAddrs { +2392 /// The last set of discovered direct addresses. +2393 addrs: Watchable<Option<BTreeSet<DirectAddr>>>, +2394 +2395 /// The last time the direct addresses were updated, even if there was no change. +2396 /// +2397 /// This is only ever None at startup. +2398 updated_at: Arc<RwLock<Option<Instant>>>, +2399} +2400 +2401impl DiscoveredDirectAddrs { +2402 /// Updates the direct addresses, returns `true` if they changed, `false` if not. +2403 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { +2404 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); +2405 let updated = self.addrs.set(Some(addrs)).is_ok(); +2406 if updated { +2407 event!( +2408 target: "iroh::_events::direct_addrs", +2409 Level::DEBUG, +2410 addrs = ?self.addrs.get(), +2411 ); 2412 } -2413 this.relay_sender.poll_writable(cx) +2413 updated 2414 } -2415} -2416 -2417#[derive(Debug)] -2418enum ActorMessage { -2419 Shutdown, -2420 EndpointPingExpired(usize, stun_rs::TransactionId), -2421 NetReport( -2422 Result<Option<Arc<net_report::Report>>, NetReportError>, -2423 &'static str, -2424 ), -2425 NetworkChange, -2426 #[cfg(test)] -2427 ForceNetworkChange(bool), -2428} -2429 -2430struct Actor { -2431 msock: Arc<MagicSock>, -2432 msg_receiver: mpsc::Receiver<ActorMessage>, -2433 msg_sender: mpsc::Sender<ActorMessage>, -2434 relay_actor_sender: mpsc::Sender<RelayActorMessage>, -2435 relay_actor_cancel_token: CancellationToken, -2436 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun. -2437 periodic_re_stun_timer: time::Interval, -2438 /// The `NetInfo` provided in the last call to `net_info_func`. It's used to deduplicate calls to netInfoFunc. -2439 net_info_last: Option<NetInfo>, -2440 -2441 /// Socket state, grouped so we can cfg it out as one for browsers -2442 #[cfg(not(wasm_browser))] -2443 sockets: ActorSocketState, -2444 -2445 /// Configuration for net report -2446 net_report_config: net_report::Options, -2447 -2448 /// Whether IPv4 UDP is known to be unable to transmit -2449 /// at all. This could happen if the socket is in an invalid state -2450 /// (as can happen on darwin after a network link status change). -2451 no_v4_send: bool, -2452 -2453 /// The prober that discovers local network conditions, including the closest relay relay and NAT mappings. -2454 net_reporter: net_report::Client, -2455 -2456 network_monitor: netmon::Monitor, +2415 +2416 fn sockaddrs(&self) -> BTreeSet<SocketAddr> { +2417 self.addrs +2418 .get() +2419 .unwrap_or_default() +2420 .into_iter() +2421 .map(|da| da.addr) +2422 .collect() +2423 } +2424 +2425 /// Whether the direct addr information is considered "fresh". +2426 /// +2427 /// If not fresh you should probably update the direct addresses before using this info. +2428 /// +2429 /// Returns `Ok(())` if fresh enough and `Err(elapsed)` if not fresh enough. +2430 /// `elapsed` is the time elapsed since the direct addresses were last updated. +2431 /// +2432 /// If there is no direct address information `Err(Duration::ZERO)` is returned. +2433 fn fresh_enough(&self) -> Result<(), Duration> { +2434 match *self.updated_at.read().expect("poisoned") { +2435 None => Err(Duration::ZERO), +2436 Some(time) => { +2437 let elapsed = time.elapsed(); +2438 if elapsed <= ENDPOINTS_FRESH_ENOUGH_DURATION { +2439 Ok(()) +2440 } else { +2441 Err(elapsed) +2442 } +2443 } +2444 } +2445 } +2446 +2447 fn to_call_me_maybe_message(&self) -> disco::CallMeMaybe { +2448 let my_numbers = self +2449 .addrs +2450 .get() +2451 .unwrap_or_default() +2452 .into_iter() +2453 .map(|da| da.addr) +2454 .collect(); +2455 disco::CallMeMaybe { my_numbers } +2456 } 2457} 2458 -2459/// Actor state that relies on sockets being available. +2459/// The fake address used by the QUIC layer to address a node. 2460/// -2461/// We group these together into their own struct to make it easier to cfg out at once. -2462#[cfg(not(wasm_browser))] -2463struct ActorSocketState { -2464 /// The NAT-PMP/PCP/UPnP prober/client, for requesting port mappings from NAT devices. -2465 port_mapper: portmapper::Client, -2466 -2467 // The underlying UDP sockets used to send/rcv packets. -2468 v4: Arc<UdpSocket>, -2469 v6: Option<Arc<UdpSocket>>, -2470} -2471 -2472#[cfg(not(wasm_browser))] -2473impl ActorSocketState { -2474 fn bind( -2475 addr_v4: Option<SocketAddrV4>, -2476 addr_v6: Option<SocketAddrV6>, -2477 metrics: Arc<portmapper::Metrics>, -2478 ) -> io::Result<Self> { -2479 let port_mapper = portmapper::Client::with_metrics(Default::default(), metrics); -2480 let (v4, v6) = Self::bind_sockets(addr_v4, addr_v6)?; -2481 -2482 let this = Self { -2483 port_mapper, -2484 v4, -2485 v6, -2486 }; -2487 -2488 let port = this.port_v4(); -2489 -2490 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails -2491 match port.try_into() { -2492 Ok(non_zero_port) => { -2493 this.port_mapper.update_local_port(non_zero_port); -2494 } -2495 Err(_zero_port) => debug!("Skipping port mapping with zero local port"), -2496 } -2497 -2498 Ok(this) -2499 } -2500 -2501 /// Returns the ipv4 port, or 0 if `netwatch::UdpSocket::socket_addr` failed. -2502 fn port_v4(&self) -> u16 { -2503 self.v4.local_addr().map_or(0, |p| p.port()) -2504 } +2461/// You can consider this as nothing more than a lookup key for a node the [`MagicSock`] knows +2462/// about. +2463/// +2464/// [`MagicSock`] can reach a node by several real socket addresses, or maybe even via the relay +2465/// node. The QUIC layer however needs to address a node by a stable [`SocketAddr`] so +2466/// that normal socket APIs can function. Thus when a new node is introduced to a [`MagicSock`] +2467/// it is given a new fake address. This is the type of that address. +2468/// +2469/// It is but a newtype. And in our QUIC-facing socket APIs like [`AsyncUdpSocket`] it +2470/// comes in as the inner [`Ipv6Addr`], in those interfaces we have to be careful to do +2471/// the conversion to this type. +2472#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +2473pub(crate) struct NodeIdMappedAddr(Ipv6Addr); +2474 +2475/// Can occur when converting a [`SocketAddr`] to an [`NodeIdMappedAddr`] +2476#[derive(Debug, Snafu)] +2477#[snafu(display("Failed to convert"))] +2478pub struct NodeIdMappedAddrError; +2479 +2480/// Counter to always generate unique addresses for [`NodeIdMappedAddr`]. +2481static NODE_ID_ADDR_COUNTER: AtomicU64 = AtomicU64::new(1); +2482 +2483impl NodeIdMappedAddr { +2484 /// The Prefix/L of our Unique Local Addresses. +2485 const ADDR_PREFIXL: u8 = 0xfd; +2486 /// The Global ID used in our Unique Local Addresses. +2487 const ADDR_GLOBAL_ID: [u8; 5] = [21, 7, 10, 81, 11]; +2488 /// The Subnet ID used in our Unique Local Addresses. +2489 const ADDR_SUBNET: [u8; 2] = [0; 2]; +2490 +2491 /// The dummy port used for all [`NodeIdMappedAddr`]s. +2492 const NODE_ID_MAPPED_PORT: u16 = 12345; +2493 +2494 /// Generates a globally unique fake UDP address. +2495 /// +2496 /// This generates and IPv6 Unique Local Address according to RFC 4193. +2497 pub(crate) fn generate() -> Self { +2498 let mut addr = [0u8; 16]; +2499 addr[0] = Self::ADDR_PREFIXL; +2500 addr[1..6].copy_from_slice(&Self::ADDR_GLOBAL_ID); +2501 addr[6..8].copy_from_slice(&Self::ADDR_SUBNET); +2502 +2503 let counter = NODE_ID_ADDR_COUNTER.fetch_add(1, Ordering::Relaxed); +2504 addr[8..16].copy_from_slice(&counter.to_be_bytes()); 2505 -2506 fn bind_sockets( -2507 addr_v4: Option<SocketAddrV4>, -2508 addr_v6: Option<SocketAddrV6>, -2509 ) -> io::Result<(Arc<UdpSocket>, Option<Arc<UdpSocket>>)> { -2510 let addr_v4 = addr_v4.unwrap_or_else(|| SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)); -2511 let v4 = Arc::new(bind_with_fallback(SocketAddr::V4(addr_v4))?); -2512 -2513 let ip4_port = v4.local_addr()?.port(); -2514 let ip6_port = ip4_port.checked_add(1).unwrap_or(ip4_port - 1); -2515 let addr_v6 = -2516 addr_v6.unwrap_or_else(|| SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, ip6_port, 0, 0)); -2517 let v6 = match bind_with_fallback(SocketAddr::V6(addr_v6)) { -2518 Ok(sock) => Some(Arc::new(sock)), -2519 Err(err) => { -2520 info!("bind ignoring IPv6 bind failure: {:?}", err); -2521 None -2522 } -2523 }; -2524 -2525 Ok((v4, v6)) -2526 } -2527 -2528 fn msock_socket_state(&self) -> io::Result<SocketState> { -2529 let ipv4_addr = self.v4.local_addr()?; -2530 let ipv6_addr = self.v6.as_ref().and_then(|c| c.local_addr().ok()); -2531 -2532 let socket_state = SocketState { -2533 port: AtomicU16::new(self.port_v4()), -2534 local_addrs: std::sync::RwLock::new((ipv4_addr, ipv6_addr)), -2535 v4: UdpConn::wrap(self.v4.clone()), -2536 v6: self.v6.clone().map(UdpConn::wrap), -2537 }; -2538 -2539 Ok(socket_state) -2540 } -2541} -2542 -2543#[derive(Debug, Snafu)] -2544#[non_exhaustive] -2545enum NetReportError { -2546 #[snafu(display("Net report not received"))] -2547 NotReceived, -2548 #[snafu(display("Net report timed out"))] -2549 Timeout, -2550 #[snafu(display("Net report encountered an error"))] -2551 NetReport { source: ReportError }, -2552} -2553 -2554impl Actor { -2555 async fn run(mut self, mut link_change_r: mpsc::Receiver<bool>, _token: CallbackToken) { -2556 // Let the the heartbeat only start a couple seconds later -2557 #[cfg(not(wasm_browser))] -2558 let mut direct_addr_heartbeat_timer = time::interval_at( -2559 time::Instant::now() + HEARTBEAT_INTERVAL, -2560 HEARTBEAT_INTERVAL, -2561 ); -2562 let mut direct_addr_update_receiver = -2563 self.msock.direct_addr_update_state.running.subscribe(); -2564 #[cfg(not(wasm_browser))] -2565 let mut portmap_watcher = self.sockets.port_mapper.watch_external_address(); -2566 -2567 let mut discovery_events: BoxStream<DiscoveryItem> = Box::pin(n0_future::stream::empty()); -2568 if let Some(d) = self.msock.discovery() { -2569 if let Some(events) = d.subscribe() { -2570 discovery_events = events; -2571 } -2572 } -2573 -2574 let mut receiver_closed = false; -2575 #[cfg_attr(wasm_browser, allow(unused_mut))] -2576 let mut portmap_watcher_closed = false; -2577 let mut link_change_closed = false; -2578 loop { -2579 self.msock.metrics.magicsock.actor_tick_main.inc(); -2580 #[cfg(not(wasm_browser))] -2581 let portmap_watcher_changed = portmap_watcher.changed(); -2582 #[cfg(wasm_browser)] -2583 let portmap_watcher_changed = n0_future::future::pending(); -2584 -2585 #[cfg(not(wasm_browser))] -2586 let direct_addr_heartbeat_timer_tick = direct_addr_heartbeat_timer.tick(); -2587 #[cfg(wasm_browser)] -2588 let direct_addr_heartbeat_timer_tick = n0_future::future::pending(); -2589 -2590 tokio::select! { -2591 msg = self.msg_receiver.recv(), if !receiver_closed => { -2592 let Some(msg) = msg else { -2593 trace!("tick: magicsock receiver closed"); -2594 self.msock.metrics.magicsock.actor_tick_other.inc(); -2595 -2596 receiver_closed = true; -2597 continue; -2598 }; -2599 -2600 trace!(?msg, "tick: msg"); -2601 self.msock.metrics.magicsock.actor_tick_msg.inc(); -2602 if self.handle_actor_message(msg).await { -2603 return; -2604 } -2605 } -2606 tick = self.periodic_re_stun_timer.tick() => { -2607 trace!("tick: re_stun {:?}", tick); -2608 self.msock.metrics.magicsock.actor_tick_re_stun.inc(); -2609 self.msock.re_stun("periodic"); -2610 } -2611 change = portmap_watcher_changed, if !portmap_watcher_closed => { -2612 #[cfg(not(wasm_browser))] -2613 { -2614 if change.is_err() { -2615 trace!("tick: portmap watcher closed"); -2616 self.msock.metrics.magicsock.actor_tick_other.inc(); -2617 -2618 portmap_watcher_closed = true; -2619 continue; -2620 } +2506 Self(Ipv6Addr::from(addr)) +2507 } +2508 +2509 /// Returns a consistent [`SocketAddr`] for the [`NodeIdMappedAddr`]. +2510 /// +2511 /// This socket address does not have a routable IP address. +2512 /// +2513 /// This uses a made-up port number, since the port does not play a role in looking up +2514 /// the node in the [`NodeMap`]. This socket address is only to be used to pass into +2515 /// Quinn. +2516 pub(crate) fn private_socket_addr(&self) -> SocketAddr { +2517 SocketAddr::new(IpAddr::from(self.0), Self::NODE_ID_MAPPED_PORT) +2518 } +2519} +2520 +2521impl TryFrom<Ipv6Addr> for NodeIdMappedAddr { +2522 type Error = NodeIdMappedAddrError; +2523 +2524 fn try_from(value: Ipv6Addr) -> Result<Self, Self::Error> { +2525 let octets = value.octets(); +2526 if octets[0] == Self::ADDR_PREFIXL +2527 && octets[1..6] == Self::ADDR_GLOBAL_ID +2528 && octets[6..8] == Self::ADDR_SUBNET +2529 { +2530 return Ok(Self(value)); +2531 } +2532 Err(NodeIdMappedAddrError) +2533 } +2534} +2535 +2536impl std::fmt::Display for NodeIdMappedAddr { +2537 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { +2538 write!(f, "NodeIdMappedAddr({})", self.0) +2539 } +2540} +2541 +2542fn disco_message_sent(msg: &disco::Message, metrics: &MagicsockMetrics) { +2543 match msg { +2544 disco::Message::Ping(_) => { +2545 metrics.sent_disco_ping.inc(); +2546 } +2547 disco::Message::Pong(_) => { +2548 metrics.sent_disco_pong.inc(); +2549 } +2550 disco::Message::CallMeMaybe(_) => { +2551 metrics.sent_disco_call_me_maybe.inc(); +2552 } +2553 } +2554} +2555 +2556/// A *direct address* on which an iroh-node might be contactable. +2557/// +2558/// Direct addresses are UDP socket addresses on which an iroh node could potentially be +2559/// contacted. These can come from various sources depending on the network topology of the +2560/// iroh node, see [`DirectAddrType`] for the several kinds of sources. +2561#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +2562pub struct DirectAddr { +2563 /// The address. +2564 pub addr: SocketAddr, +2565 /// The origin of this direct address. +2566 pub typ: DirectAddrType, +2567} +2568 +2569/// The type of direct address. +2570/// +2571/// These are the various sources or origins from which an iroh node might have found a +2572/// possible [`DirectAddr`]. +2573#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +2574pub enum DirectAddrType { +2575 /// Not yet determined.. +2576 Unknown, +2577 /// A locally bound socket address. +2578 Local, +2579 /// Public internet address discovered via STUN. +2580 /// +2581 /// When possible an iroh node will perform STUN to discover which is the address +2582 /// from which it sends data on the public internet. This can be different from locally +2583 /// bound addresses when the node is on a local network which performs NAT or similar. +2584 Stun, +2585 /// An address assigned by the router using port mapping. +2586 /// +2587 /// When possible an iroh node will request a port mapping from the local router to +2588 /// get a publicly routable direct address. +2589 Portmapped, +2590 /// Hard NAT: STUN'ed IPv4 address + local fixed port. +2591 /// +2592 /// It is possible to configure iroh to bound to a specific port and independently +2593 /// configure the router to forward this port to the iroh node. This indicates a +2594 /// situation like this, which still uses STUN to discover the public address. +2595 Stun4LocalPort, +2596} +2597 +2598impl Display for DirectAddrType { +2599 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +2600 match self { +2601 DirectAddrType::Unknown => write!(f, "?"), +2602 DirectAddrType::Local => write!(f, "local"), +2603 DirectAddrType::Stun => write!(f, "stun"), +2604 DirectAddrType::Portmapped => write!(f, "portmap"), +2605 DirectAddrType::Stun4LocalPort => write!(f, "stun4localport"), +2606 } +2607 } +2608} +2609 +2610/// Contains information about the host's network state. +2611#[derive(Debug, Clone, PartialEq)] +2612pub(crate) struct NetInfo { +2613 /// Says whether the host's NAT mappings vary based on the destination IP. +2614 mapping_varies_by_dest_ip: Option<bool>, +2615 +2616 /// If their router does hairpinning. It reports true even if there's no NAT involved. +2617 hair_pinning: Option<bool>, +2618 +2619 /// Whether the host has IPv6 internet connectivity. +2620 working_ipv6: Option<bool>, 2621 -2622 trace!("tick: portmap changed"); -2623 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc(); -2624 let new_external_address = *portmap_watcher.borrow(); -2625 debug!("external address updated: {new_external_address:?}"); -2626 self.msock.re_stun("portmap_updated"); -2627 } -2628 #[cfg(wasm_browser)] -2629 let _unused_in_browsers = change; -2630 }, -2631 _ = direct_addr_heartbeat_timer_tick => { -2632 #[cfg(not(wasm_browser))] -2633 { -2634 trace!( -2635 "tick: direct addr heartbeat {} direct addrs", -2636 self.msock.node_map.node_count(), -2637 ); -2638 self.msock.metrics.magicsock.actor_tick_direct_addr_heartbeat.inc(); -2639 // TODO: this might trigger too many packets at once, pace this +2622 /// Whether the OS supports IPv6 at all, regardless of whether IPv6 internet connectivity is available. +2623 os_has_ipv6: Option<bool>, +2624 +2625 /// Whether the host has UDP internet connectivity. +2626 working_udp: Option<bool>, +2627 +2628 /// Whether ICMPv4 works, `None` means not checked. +2629 working_icmp_v4: Option<bool>, +2630 +2631 /// Whether ICMPv6 works, `None` means not checked. +2632 working_icmp_v6: Option<bool>, +2633 +2634 /// Whether we have an existing portmap open (UPnP, PMP, or PCP). +2635 have_port_map: bool, +2636 +2637 /// Probe indicating the presence of port mapping protocols on the LAN. +2638 #[cfg(not(wasm_browser))] +2639 portmap_probe: Option<portmapper::ProbeOutput>, 2640 -2641 self.msock.node_map.prune_inactive(); -2642 let msgs = self.msock.node_map.nodes_stayin_alive(); -2643 self.handle_ping_actions(msgs).await; -2644 } -2645 } -2646 _ = direct_addr_update_receiver.changed() => { -2647 let reason = *direct_addr_update_receiver.borrow(); -2648 trace!("tick: direct addr update receiver {:?}", reason); -2649 self.msock.metrics.magicsock.actor_tick_direct_addr_update_receiver.inc(); -2650 if let Some(reason) = reason { -2651 self.refresh_direct_addrs(reason).await; -2652 } -2653 } -2654 is_major = link_change_r.recv(), if !link_change_closed => { -2655 let Some(is_major) = is_major else { -2656 trace!("tick: link change receiver closed"); -2657 self.msock.metrics.magicsock.actor_tick_other.inc(); -2658 -2659 link_change_closed = true; -2660 continue; -2661 }; -2662 -2663 trace!("tick: link change {}", is_major); -2664 self.msock.metrics.magicsock.actor_link_change.inc(); -2665 self.handle_network_change(is_major).await; -2666 } -2667 // Even if `discovery_events` yields `None`, it could begin to yield -2668 // `Some` again in the future, so we don't want to disable this branch -2669 // forever like we do with the other branches that yield `Option`s -2670 Some(discovery_item) = discovery_events.next() => { -2671 trace!("tick: discovery event, address discovered: {discovery_item:?}"); -2672 let provenance = discovery_item.provenance(); -2673 let node_addr = discovery_item.to_node_addr(); -2674 if let Err(e) = self.msock.add_node_addr( -2675 node_addr, -2676 Source::Discovery { -2677 name: provenance.to_string() -2678 }) { -2679 let node_addr = discovery_item.to_node_addr(); -2680 warn!(?node_addr, "unable to add discovered node address to the node map: {e:?}"); -2681 } -2682 // Send the discovery item to the subscribers of the discovery broadcast stream. -2683 self.msock.discovery_subscribers.send(discovery_item); -2684 } -2685 } -2686 } -2687 } -2688 -2689 async fn handle_network_change(&mut self, is_major: bool) { -2690 debug!("link change detected: major? {}", is_major); +2641 /// This node's preferred relay server for incoming traffic. +2642 /// +2643 /// The node might be be temporarily connected to multiple relay servers (to send to +2644 /// other nodes) but this is the relay on which you can always contact this node. Also +2645 /// known as home relay. +2646 preferred_relay: Option<RelayUrl>, +2647 +2648 /// The fastest recent time to reach various relay STUN servers, in seconds. +2649 /// +2650 /// This should only be updated rarely, or when there's a +2651 /// material change, as any change here also gets uploaded to the control plane. +2652 relay_latency: BTreeMap<String, f64>, +2653} +2654 +2655impl NetInfo { +2656 /// Checks if this is probably still the same network as *other*. +2657 /// +2658 /// This tries to compare the network situation, without taking into account things +2659 /// expected to change a little like e.g. latency to the relay server. +2660 fn basically_equal(&self, other: &Self) -> bool { +2661 let eq_icmp_v4 = match (self.working_icmp_v4, other.working_icmp_v4) { +2662 (Some(slf), Some(other)) => slf == other, +2663 _ => true, // ignore for comparison if only one report had this info +2664 }; +2665 let eq_icmp_v6 = match (self.working_icmp_v6, other.working_icmp_v6) { +2666 (Some(slf), Some(other)) => slf == other, +2667 _ => true, // ignore for comparison if only one report had this info +2668 }; +2669 +2670 #[cfg(not(wasm_browser))] +2671 let probe_eq = self.portmap_probe == other.portmap_probe; +2672 #[cfg(wasm_browser)] +2673 let probe_eq = true; +2674 +2675 self.mapping_varies_by_dest_ip == other.mapping_varies_by_dest_ip +2676 && self.hair_pinning == other.hair_pinning +2677 && self.working_ipv6 == other.working_ipv6 +2678 && self.os_has_ipv6 == other.os_has_ipv6 +2679 && self.working_udp == other.working_udp +2680 && eq_icmp_v4 +2681 && eq_icmp_v6 +2682 && self.have_port_map == other.have_port_map +2683 && probe_eq +2684 && self.preferred_relay == other.preferred_relay +2685 } +2686} +2687 +2688#[cfg(test)] +2689mod tests { +2690 use std::{collections::BTreeSet, sync::Arc, time::Duration}; 2691 -2692 if is_major { -2693 #[cfg(not(wasm_browser))] -2694 { -2695 if let Err(err) = self.sockets.v4.rebind() { -2696 warn!("failed to rebind Udp IPv4 socket: {:?}", err); -2697 }; -2698 if let Some(ref socket) = self.sockets.v6 { -2699 if let Err(err) = socket.rebind() { -2700 warn!("failed to rebind Udp IPv6 socket: {:?}", err); -2701 }; -2702 } -2703 self.msock.dns_resolver.clear_cache(); -2704 } -2705 self.msock.re_stun("link-change-major"); -2706 self.close_stale_relay_connections().await; -2707 self.reset_endpoint_states(); -2708 } else { -2709 self.msock.re_stun("link-change-minor"); -2710 } -2711 } +2692 use data_encoding::HEXLOWER; +2693 use iroh_base::{NodeAddr, NodeId, PublicKey, SecretKey}; +2694 use iroh_relay::RelayMap; +2695 use n0_future::{time, StreamExt}; +2696 use n0_snafu::{Result, ResultExt}; +2697 use n0_watcher::Watcher; +2698 use quinn::ServerConfig; +2699 use rand::{Rng, RngCore}; +2700 use tokio::task::JoinSet; +2701 use tokio_util::task::AbortOnDropHandle; +2702 use tracing::{error, info, info_span, instrument, Instrument}; +2703 use tracing_test::traced_test; +2704 +2705 use super::{NodeIdMappedAddr, Options}; +2706 use crate::{ +2707 dns::DnsResolver, +2708 endpoint::{DirectAddr, PathSelection, Source}, +2709 magicsock::{node_map, Handle, MagicSock}, +2710 tls, Endpoint, RelayMode, +2711 }; 2712 -2713 #[instrument(skip_all)] -2714 async fn handle_ping_actions(&mut self, msgs: Vec<PingAction>) { -2715 // TODO: This used to make sure that all ping actions are sent. Though on the -2716 // poll_send/try_send path we also do fire-and-forget. try_send_ping_actions() -2717 // really should store any unsent pings on the Inner and send them at the next -2718 // possible time. -2719 if let Err(err) = self.msock.try_send_ping_actions(msgs) { -2720 warn!("Not all ping actions were sent: {err:#}"); -2721 } -2722 } -2723 -2724 /// Processes an incoming actor message. -2725 /// -2726 /// Returns `true` if it was a shutdown. -2727 async fn handle_actor_message(&mut self, msg: ActorMessage) -> bool { -2728 match msg { -2729 ActorMessage::Shutdown => { -2730 debug!("shutting down"); -2731 -2732 self.msock.node_map.notify_shutdown(); -2733 #[cfg(not(wasm_browser))] -2734 self.sockets.port_mapper.deactivate(); -2735 self.relay_actor_cancel_token.cancel(); -2736 -2737 debug!("shutdown complete"); -2738 return true; -2739 } -2740 ActorMessage::EndpointPingExpired(id, txid) => { -2741 self.msock.node_map.notify_ping_timeout(id, txid); -2742 } -2743 ActorMessage::NetReport(report, why) => { -2744 match report { -2745 Ok(report) => { -2746 self.handle_net_report_report(report).await; -2747 } -2748 Err(err) => { -2749 warn!( -2750 "failed to generate net_report report for: {}: {:?}", -2751 why, err -2752 ); -2753 } -2754 } -2755 self.finalize_direct_addrs_update(why); -2756 } -2757 ActorMessage::NetworkChange => { -2758 self.network_monitor.network_change().await.ok(); -2759 } -2760 #[cfg(test)] -2761 ActorMessage::ForceNetworkChange(is_major) => { -2762 self.handle_network_change(is_major).await; -2763 } -2764 } -2765 -2766 false -2767 } +2713 const ALPN: &[u8] = b"n0/test/1"; +2714 +2715 impl Default for Options { +2716 fn default() -> Self { +2717 let secret_key = SecretKey::generate(rand::rngs::OsRng); +2718 let server_config = make_default_server_config(&secret_key); +2719 Options { +2720 addr_v4: None, +2721 addr_v6: None, +2722 secret_key, +2723 relay_map: RelayMap::empty(), +2724 relay_protocol: iroh_relay::http::Protocol::default(), +2725 node_map: None, +2726 discovery: None, +2727 proxy_url: None, +2728 dns_resolver: DnsResolver::new(), +2729 server_config, +2730 #[cfg(any(test, feature = "test-utils"))] +2731 insecure_skip_relay_cert_verify: false, +2732 #[cfg(any(test, feature = "test-utils"))] +2733 path_selection: PathSelection::default(), +2734 discovery_user_data: None, +2735 metrics: Default::default(), +2736 } +2737 } +2738 } +2739 +2740 /// Generate a server config with no ALPNS and a default transport configuration +2741 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig { +2742 let quic_server_config = +2743 crate::tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![], false); +2744 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); +2745 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); +2746 server_config +2747 } +2748 +2749 impl MagicSock { +2750 #[track_caller] +2751 pub fn add_test_addr(&self, node_addr: NodeAddr) { +2752 self.add_node_addr( +2753 node_addr, +2754 Source::NamedApp { +2755 name: "test".into(), +2756 }, +2757 ) +2758 .unwrap() +2759 } +2760 } +2761 +2762 /// Magicsock plus wrappers for sending packets +2763 #[derive(Clone)] +2764 struct MagicStack { +2765 secret_key: SecretKey, +2766 endpoint: Endpoint, +2767 } 2768 -2769 /// Refreshes knowledge about our direct addresses. -2770 /// -2771 /// In other words, this triggers a net_report run. -2772 /// -2773 /// Note that invoking this is managed by the [`DirectAddrUpdateState`] and this should -2774 /// never be invoked directly. Some day this will be refactored to not allow this easy -2775 /// mistake to be made. -2776 #[instrument(level = "debug", skip_all)] -2777 async fn refresh_direct_addrs(&mut self, why: &'static str) { -2778 self.msock.metrics.magicsock.update_direct_addrs.inc(); -2779 -2780 debug!("starting direct addr update ({})", why); -2781 #[cfg(not(wasm_browser))] -2782 self.sockets.port_mapper.procure_mapping(); -2783 self.update_net_info(why).await; -2784 } -2785 -2786 /// Updates the direct addresses of this magic socket. -2787 /// -2788 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of -2789 /// direct addresses from: -2790 /// -2791 /// - The portmapper. -2792 /// - A net_report report. -2793 /// - The local interfaces IP addresses. -2794 #[cfg(not(wasm_browser))] -2795 fn update_direct_addresses(&mut self, net_report_report: Option<Arc<net_report::Report>>) { -2796 let portmap_watcher = self.sockets.port_mapper.watch_external_address(); -2797 -2798 // We only want to have one DirectAddr for each SocketAddr we have. So we store -2799 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a -2800 // DirectAddr from each entry. -2801 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new(); -2802 -2803 // First add PortMapper provided addresses. -2804 let maybe_port_mapped = *portmap_watcher.borrow(); -2805 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { -2806 addrs -2807 .entry(portmap_ext) -2808 .or_insert(DirectAddrType::Portmapped); -2809 self.set_net_info_have_port_map(); -2810 } -2811 -2812 // Next add STUN addresses from the net_report report. -2813 if let Some(net_report_report) = net_report_report { -2814 if let Some(global_v4) = net_report_report.global_v4 { -2815 addrs -2816 .entry(global_v4.into()) -2817 .or_insert(DirectAddrType::Stun); -2818 -2819 // If they're behind a hard NAT and are using a fixed -2820 // port locally, assume they might've added a static -2821 // port mapping on their router to the same explicit -2822 // port that we are running with. Worst case it's an invalid candidate mapping. -2823 let port = self.msock.sockets.port.load(Ordering::Relaxed); -2824 if net_report_report -2825 .mapping_varies_by_dest_ip -2826 .unwrap_or_default() -2827 && port != 0 -2828 { -2829 let mut addr = global_v4; -2830 addr.set_port(port); -2831 addrs -2832 .entry(addr.into()) -2833 .or_insert(DirectAddrType::Stun4LocalPort); -2834 } -2835 } -2836 if let Some(global_v6) = net_report_report.global_v6 { -2837 addrs -2838 .entry(global_v6.into()) -2839 .or_insert(DirectAddrType::Stun); -2840 } -2841 } -2842 -2843 let local_addr_v4 = self.sockets.v4.local_addr().ok(); -2844 let local_addr_v6 = self.sockets.v6.as_ref().and_then(|c| c.local_addr().ok()); -2845 -2846 let is_unspecified_v4 = local_addr_v4 -2847 .map(|a| a.ip().is_unspecified()) -2848 .unwrap_or(false); -2849 let is_unspecified_v6 = local_addr_v6 -2850 .map(|a| a.ip().is_unspecified()) -2851 .unwrap_or(false); -2852 -2853 let msock = self.msock.clone(); -2854 -2855 // The following code can be slow, we do not want to block the caller since it would -2856 // block the actor loop. -2857 task::spawn( -2858 async move { -2859 // If a socket is bound to the unspecified address, create SocketAddrs for -2860 // each local IP address by pairing it with the port the socket is bound on. -2861 if is_unspecified_v4 || is_unspecified_v6 { -2862 // Depending on the OS and network interfaces attached and their state -2863 // enumerating the local interfaces can take a long time. Especially -2864 // Windows is very slow. -2865 let LocalAddresses { -2866 regular: mut ips, -2867 loopback, -2868 } = tokio::task::spawn_blocking(LocalAddresses::new) -2869 .await -2870 .expect("spawn panicked"); -2871 if ips.is_empty() && addrs.is_empty() { -2872 // Include loopback addresses only if there are no other interfaces -2873 // or public addresses, this allows testing offline. -2874 ips = loopback; -2875 } -2876 for ip in ips { -2877 let port_if_unspecified = match ip { -2878 IpAddr::V4(_) if is_unspecified_v4 => { -2879 local_addr_v4.map(|addr| addr.port()) -2880 } -2881 IpAddr::V6(_) if is_unspecified_v6 => { -2882 local_addr_v6.map(|addr| addr.port()) -2883 } -2884 _ => None, -2885 }; -2886 if let Some(port) = port_if_unspecified { -2887 let addr = SocketAddr::new(ip, port); -2888 addrs.entry(addr).or_insert(DirectAddrType::Local); -2889 } -2890 } -2891 } -2892 -2893 // If a socket is bound to a specific address, add it. -2894 if !is_unspecified_v4 { -2895 if let Some(addr) = local_addr_v4 { -2896 addrs.entry(addr).or_insert(DirectAddrType::Local); -2897 } -2898 } -2899 if !is_unspecified_v6 { -2900 if let Some(addr) = local_addr_v6 { -2901 addrs.entry(addr).or_insert(DirectAddrType::Local); -2902 } -2903 } -2904 -2905 // Finally create and store store all these direct addresses and send any -2906 // queued call-me-maybe messages. -2907 msock.store_direct_addresses( -2908 addrs -2909 .iter() -2910 .map(|(addr, typ)| DirectAddr { -2911 addr: *addr, -2912 typ: *typ, -2913 }) -2914 .collect(), -2915 ); -2916 msock.send_queued_call_me_maybes(); -2917 } -2918 .instrument(Span::current()), -2919 ); -2920 } -2921 -2922 /// Called when a direct addr update is done, no matter if it was successful or not. -2923 fn finalize_direct_addrs_update(&mut self, why: &'static str) { -2924 let new_why = self.msock.direct_addr_update_state.next_update(); -2925 if !self.msock.is_closed() { -2926 if let Some(new_why) = new_why { -2927 self.msock.direct_addr_update_state.run(new_why); -2928 return; -2929 } -2930 #[cfg(not(wasm_browser))] -2931 { -2932 self.periodic_re_stun_timer = new_re_stun_timer(true); -2933 } -2934 } -2935 -2936 self.msock.direct_addr_update_state.finish_run(); -2937 debug!("direct addr update done ({})", why); -2938 } -2939 -2940 /// Updates `NetInfo.HavePortMap` to true. -2941 #[instrument(level = "debug", skip_all)] -2942 fn set_net_info_have_port_map(&mut self) { -2943 if let Some(ref mut net_info_last) = self.net_info_last { -2944 if net_info_last.have_port_map { -2945 // No change. -2946 return; -2947 } -2948 net_info_last.have_port_map = true; -2949 self.net_info_last = Some(net_info_last.clone()); -2950 } -2951 } -2952 -2953 #[instrument(level = "debug", skip_all)] -2954 async fn call_net_info_callback(&mut self, ni: NetInfo) { -2955 if let Some(ref net_info_last) = self.net_info_last { -2956 if ni.basically_equal(net_info_last) { -2957 return; -2958 } -2959 } -2960 -2961 self.net_info_last = Some(ni); -2962 } +2769 impl MagicStack { +2770 async fn new(relay_mode: RelayMode) -> Self { +2771 let secret_key = SecretKey::generate(rand::thread_rng()); +2772 +2773 let mut transport_config = quinn::TransportConfig::default(); +2774 transport_config.max_idle_timeout(Some(Duration::from_secs(10).try_into().unwrap())); +2775 +2776 let endpoint = Endpoint::builder() +2777 .secret_key(secret_key.clone()) +2778 .transport_config(transport_config) +2779 .relay_mode(relay_mode) +2780 .alpns(vec![ALPN.to_vec()]) +2781 .bind() +2782 .await +2783 .unwrap(); +2784 +2785 Self { +2786 secret_key, +2787 endpoint, +2788 } +2789 } +2790 +2791 fn tracked_endpoints(&self) -> Vec<PublicKey> { +2792 self.endpoint +2793 .magic_sock() +2794 .list_remote_infos() +2795 .into_iter() +2796 .map(|ep| ep.node_id) +2797 .collect() +2798 } +2799 +2800 fn public(&self) -> PublicKey { +2801 self.secret_key.public() +2802 } +2803 } +2804 +2805 /// Monitors endpoint changes and plumbs things together. +2806 /// +2807 /// This is a way of connecting endpoints without a relay server. Whenever the local +2808 /// endpoints of a magic endpoint change this address is added to the other magic +2809 /// sockets. This function will await until the endpoints are connected the first time +2810 /// before returning. +2811 /// +2812 /// When the returned drop guard is dropped, the tasks doing this updating are stopped. +2813 #[instrument(skip_all)] +2814 async fn mesh_stacks(stacks: Vec<MagicStack>) -> Result<JoinSet<()>> { +2815 /// Registers endpoint addresses of a node to all other nodes. +2816 fn update_direct_addrs( +2817 stacks: &[MagicStack], +2818 my_idx: usize, +2819 new_addrs: BTreeSet<DirectAddr>, +2820 ) { +2821 let me = &stacks[my_idx]; +2822 for (i, m) in stacks.iter().enumerate() { +2823 if i == my_idx { +2824 continue; +2825 } +2826 +2827 let addr = NodeAddr { +2828 node_id: me.public(), +2829 relay_url: None, +2830 direct_addresses: new_addrs.iter().map(|ep| ep.addr).collect(), +2831 }; +2832 m.endpoint.magic_sock().add_test_addr(addr); +2833 } +2834 } +2835 +2836 // For each node, start a task which monitors its local endpoints and registers them +2837 // with the other nodes as local endpoints become known. +2838 let mut tasks = JoinSet::new(); +2839 for (my_idx, m) in stacks.iter().enumerate() { +2840 let m = m.clone(); +2841 let stacks = stacks.clone(); +2842 tasks.spawn(async move { +2843 let me = m.endpoint.node_id().fmt_short(); +2844 let mut stream = m.endpoint.direct_addresses().stream().filter_map(|i| i); +2845 while let Some(new_eps) = stream.next().await { +2846 info!(%me, "conn{} endpoints update: {:?}", my_idx + 1, new_eps); +2847 update_direct_addrs(&stacks, my_idx, new_eps); +2848 } +2849 }); +2850 } +2851 +2852 // Wait for all nodes to be registered with each other. +2853 time::timeout(Duration::from_secs(10), async move { +2854 let all_node_ids: Vec<_> = stacks.iter().map(|ms| ms.endpoint.node_id()).collect(); +2855 loop { +2856 let mut ready = Vec::with_capacity(stacks.len()); +2857 for ms in stacks.iter() { +2858 let endpoints = ms.tracked_endpoints(); +2859 let my_node_id = ms.endpoint.node_id(); +2860 let all_nodes_meshed = all_node_ids +2861 .iter() +2862 .filter(|node_id| **node_id != my_node_id) +2863 .all(|node_id| endpoints.contains(node_id)); +2864 ready.push(all_nodes_meshed); +2865 } +2866 if ready.iter().all(|meshed| *meshed) { +2867 break; +2868 } +2869 time::sleep(Duration::from_millis(200)).await; +2870 } +2871 }) +2872 .await +2873 .context("timeout")?; +2874 info!("all nodes meshed"); +2875 Ok(tasks) +2876 } +2877 +2878 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))] +2879 async fn echo_receiver(ep: MagicStack, loss: ExpectedLoss) -> Result { +2880 info!("accepting conn"); +2881 let conn = ep.endpoint.accept().await.expect("no conn"); +2882 +2883 info!("connecting"); +2884 let conn = conn.await.context("connecting")?; +2885 info!("accepting bi"); +2886 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.context("accept bi")?; +2887 +2888 info!("reading"); +2889 let val = recv_bi +2890 .read_to_end(usize::MAX) +2891 .await +2892 .context("read to end")?; +2893 +2894 info!("replying"); +2895 for chunk in val.chunks(12) { +2896 send_bi.write_all(chunk).await.context("write all")?; +2897 } +2898 +2899 info!("finishing"); +2900 send_bi.finish().context("finish")?; +2901 send_bi.stopped().await.context("stopped")?; +2902 +2903 let stats = conn.stats(); +2904 info!("stats: {:#?}", stats); +2905 // TODO: ensure panics in this function are reported ok +2906 if matches!(loss, ExpectedLoss::AlmostNone) { +2907 assert!( +2908 stats.path.lost_packets < 10, +2909 "[receiver] should not loose many packets", +2910 ); +2911 } +2912 +2913 info!("close"); +2914 conn.close(0u32.into(), b"done"); +2915 info!("wait idle"); +2916 ep.endpoint.endpoint().wait_idle().await; +2917 +2918 Ok(()) +2919 } +2920 +2921 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))] +2922 async fn echo_sender( +2923 ep: MagicStack, +2924 dest_id: PublicKey, +2925 msg: &[u8], +2926 loss: ExpectedLoss, +2927 ) -> Result { +2928 info!("connecting to {}", dest_id.fmt_short()); +2929 let dest = NodeAddr::new(dest_id); +2930 let conn = ep.endpoint.connect(dest, ALPN).await?; +2931 +2932 info!("opening bi"); +2933 let (mut send_bi, mut recv_bi) = conn.open_bi().await.context("open bi")?; +2934 +2935 info!("writing message"); +2936 send_bi.write_all(msg).await.context("write all")?; +2937 +2938 info!("finishing"); +2939 send_bi.finish().context("finish")?; +2940 send_bi.stopped().await.context("stopped")?; +2941 +2942 info!("reading_to_end"); +2943 let val = recv_bi +2944 .read_to_end(usize::MAX) +2945 .await +2946 .context("read to end")?; +2947 assert_eq!( +2948 val, +2949 msg, +2950 "[sender] expected {}, got {}", +2951 HEXLOWER.encode(msg), +2952 HEXLOWER.encode(&val) +2953 ); +2954 +2955 let stats = conn.stats(); +2956 info!("stats: {:#?}", stats); +2957 if matches!(loss, ExpectedLoss::AlmostNone) { +2958 assert!( +2959 stats.path.lost_packets < 10, +2960 "[sender] should not loose many packets", +2961 ); +2962 } 2963 -2964 /// Calls net_report. -2965 /// -2966 /// Note that invoking this is managed by [`DirectAddrUpdateState`] via -2967 /// [`Actor::refresh_direct_addrs`] and this should never be invoked directly. Some day -2968 /// this will be refactored to not allow this easy mistake to be made. -2969 #[instrument(level = "debug", skip_all)] -2970 async fn update_net_info(&mut self, why: &'static str) { -2971 // Don't start a net report probe if we know -2972 // we are shutting down -2973 if self.msock.is_closing() || self.msock.is_closed() { -2974 debug!("skipping net_report, socket is shutting down"); -2975 return; -2976 } -2977 if self.msock.relay_map.is_empty() { -2978 debug!("skipping net_report, empty RelayMap"); -2979 self.msg_sender -2980 .send(ActorMessage::NetReport(Ok(None), why)) -2981 .await -2982 .ok(); -2983 return; -2984 } -2985 -2986 let relay_map = self.msock.relay_map.clone(); -2987 let opts = self.net_report_config.clone(); -2988 -2989 debug!("requesting net_report report"); -2990 match self.net_reporter.get_report_channel(relay_map, opts).await { -2991 Ok(rx) => { -2992 let msg_sender = self.msg_sender.clone(); -2993 task::spawn(async move { -2994 let report = time::timeout(NET_REPORT_TIMEOUT, rx).await; -2995 let report = match report { -2996 Ok(Ok(Ok(report))) => Ok(Some(report)), -2997 Ok(Ok(Err(err))) => Err(NetReportSnafu.into_error(err)), -2998 Ok(Err(_)) => Err(NotReceivedSnafu.build()), -2999 Err(_) => Err(TimeoutSnafu.build()), -3000 }; -3001 msg_sender -3002 .send(ActorMessage::NetReport(report, why)) -3003 .await -3004 .ok(); -3005 // The receiver of the NetReport message will call -3006 // .finalize_direct_addrs_update(). -3007 }); -3008 } -3009 Err(err) => { -3010 warn!("unable to start net_report generation: {:?}", err); -3011 self.finalize_direct_addrs_update(why); -3012 } -3013 } -3014 } -3015 -3016 async fn handle_net_report_report(&mut self, report: Option<Arc<net_report::Report>>) { -3017 if let Some(ref report) = report { -3018 // only returns Err if the report hasn't changed. -3019 self.msock.net_report.set(Some(report.clone())).ok(); -3020 self.msock -3021 .ipv6_reported -3022 .store(report.ipv6, Ordering::Relaxed); -3023 let r = &report; -3024 trace!( -3025 "setting no_v4_send {} -> {}", -3026 self.no_v4_send, -3027 !r.ipv4_can_send -3028 ); -3029 self.no_v4_send = !r.ipv4_can_send; -3030 -3031 #[cfg(not(wasm_browser))] -3032 let have_port_map = self -3033 .sockets -3034 .port_mapper -3035 .watch_external_address() -3036 .borrow() -3037 .is_some(); -3038 #[cfg(wasm_browser)] -3039 let have_port_map = false; -3040 -3041 let mut ni = NetInfo { -3042 relay_latency: Default::default(), -3043 mapping_varies_by_dest_ip: r.mapping_varies_by_dest_ip, -3044 hair_pinning: r.hair_pinning, -3045 #[cfg(not(wasm_browser))] -3046 portmap_probe: r.portmap_probe.clone(), -3047 have_port_map, -3048 working_ipv6: Some(r.ipv6), -3049 os_has_ipv6: Some(r.os_has_ipv6), -3050 working_udp: Some(r.udp), -3051 working_icmp_v4: r.icmpv4, -3052 working_icmp_v6: r.icmpv6, -3053 preferred_relay: r.preferred_relay.clone(), -3054 }; -3055 for (rid, d) in r.relay_v4_latency.iter() { -3056 ni.relay_latency -3057 .insert(format!("{rid}-v4"), d.as_secs_f64()); -3058 } -3059 for (rid, d) in r.relay_v6_latency.iter() { -3060 ni.relay_latency -3061 .insert(format!("{rid}-v6"), d.as_secs_f64()); -3062 } +2964 info!("close"); +2965 conn.close(0u32.into(), b"done"); +2966 info!("wait idle"); +2967 ep.endpoint.endpoint().wait_idle().await; +2968 Ok(()) +2969 } +2970 +2971 #[derive(Debug, Copy, Clone)] +2972 enum ExpectedLoss { +2973 AlmostNone, +2974 YeahSure, +2975 } +2976 +2977 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. +2978 async fn run_roundtrip( +2979 sender: MagicStack, +2980 receiver: MagicStack, +2981 payload: &[u8], +2982 loss: ExpectedLoss, +2983 ) { +2984 let send_node_id = sender.endpoint.node_id(); +2985 let recv_node_id = receiver.endpoint.node_id(); +2986 info!("\nroundtrip: {send_node_id:#} -> {recv_node_id:#}"); +2987 +2988 let receiver_task = tokio::spawn(echo_receiver(receiver, loss)); +2989 let sender_res = echo_sender(sender, recv_node_id, payload, loss).await; +2990 let sender_is_err = match sender_res { +2991 Ok(()) => false, +2992 Err(err) => { +2993 eprintln!("[sender] Error:\n{err:#?}"); +2994 true +2995 } +2996 }; +2997 let receiver_is_err = match receiver_task.await { +2998 Ok(Ok(())) => false, +2999 Ok(Err(err)) => { +3000 eprintln!("[receiver] Error:\n{err:#?}"); +3001 true +3002 } +3003 Err(joinerr) => { +3004 if joinerr.is_panic() { +3005 std::panic::resume_unwind(joinerr.into_panic()); +3006 } else { +3007 eprintln!("[receiver] Error:\n{joinerr:#?}"); +3008 } +3009 true +3010 } +3011 }; +3012 if sender_is_err || receiver_is_err { +3013 panic!("Sender or receiver errored"); +3014 } +3015 } +3016 +3017 #[tokio::test(flavor = "multi_thread")] +3018 #[traced_test] +3019 async fn test_two_devices_roundtrip_quinn_magic() -> Result { +3020 let m1 = MagicStack::new(RelayMode::Disabled).await; +3021 let m2 = MagicStack::new(RelayMode::Disabled).await; +3022 +3023 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; +3024 +3025 for i in 0..5 { +3026 info!("\n-- round {i}"); +3027 run_roundtrip( +3028 m1.clone(), +3029 m2.clone(), +3030 b"hello m1", +3031 ExpectedLoss::AlmostNone, +3032 ) +3033 .await; +3034 run_roundtrip( +3035 m2.clone(), +3036 m1.clone(), +3037 b"hello m2", +3038 ExpectedLoss::AlmostNone, +3039 ) +3040 .await; +3041 +3042 info!("\n-- larger data"); +3043 let mut data = vec![0u8; 10 * 1024]; +3044 rand::thread_rng().fill_bytes(&mut data); +3045 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await; +3046 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await; +3047 } +3048 +3049 Ok(()) +3050 } +3051 +3052 #[tokio::test] +3053 #[traced_test] +3054 async fn test_regression_network_change_rebind_wakes_connection_driver() -> n0_snafu::Result { +3055 let m1 = MagicStack::new(RelayMode::Disabled).await; +3056 let m2 = MagicStack::new(RelayMode::Disabled).await; +3057 +3058 println!("Net change"); +3059 m1.endpoint.magic_sock().force_network_change(true).await; +3060 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding +3061 +3062 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; 3063 -3064 if ni.preferred_relay.is_none() { -3065 // Perhaps UDP is blocked. Pick a deterministic but arbitrary one. -3066 ni.preferred_relay = self.pick_relay_fallback(); -3067 } -3068 -3069 self.set_nearest_relay(ni.preferred_relay.clone()); -3070 -3071 // TODO: set link type -3072 self.call_net_info_callback(ni).await; -3073 } -3074 #[cfg(not(wasm_browser))] -3075 self.update_direct_addresses(report); -3076 } -3077 -3078 fn set_nearest_relay(&mut self, relay_url: Option<RelayUrl>) { -3079 let my_relay = self.msock.my_relay(); -3080 if relay_url == my_relay { -3081 // No change. -3082 return; -3083 } -3084 let old_relay = self.msock.set_my_relay(relay_url.clone()); -3085 -3086 if let Some(ref relay_url) = relay_url { -3087 self.msock.metrics.magicsock.relay_home_change.inc(); -3088 -3089 // On change, notify all currently connected relay servers and -3090 // start connecting to our home relay if we are not already. -3091 info!("home is now relay {}, was {:?}", relay_url, old_relay); -3092 self.msock.publish_my_addr(); -3093 -3094 self.send_relay_actor(RelayActorMessage::SetHome { -3095 url: relay_url.clone(), -3096 }); -3097 } -3098 } -3099 -3100 /// Returns a deterministic relay node to connect to. This is only used if net_report -3101 /// couldn't find the nearest one, for instance, if UDP is blocked and thus STUN -3102 /// latency checks aren't working. -3103 /// -3104 /// If no the [`RelayMap`] is empty, returns `0`. -3105 fn pick_relay_fallback(&self) -> Option<RelayUrl> { -3106 // TODO: figure out which relay node most of our nodes are using, -3107 // and use that region as our fallback. -3108 // -3109 // If we already had selected something in the past and it has any -3110 // nodes, we want to stay on it. If there are no nodes at all, -3111 // stay on whatever relay we previously picked. If we need to pick -3112 // one and have no node info, pick a node randomly. -3113 // -3114 // We used to do the above for legacy clients, but never updated it for disco. -3115 -3116 let my_relay = self.msock.my_relay(); -3117 if my_relay.is_some() { -3118 return my_relay; -3119 } -3120 -3121 let ids = self.msock.relay_map.urls().collect::<Vec<_>>(); -3122 let mut rng = rand::rngs::StdRng::seed_from_u64(0); -3123 ids.choose(&mut rng).map(|c| (*c).clone()) -3124 } -3125 -3126 /// Resets the preferred address for all nodes. -3127 /// This is called when connectivity changes enough that we no longer trust the old routes. -3128 #[instrument(skip_all, fields(me = %self.msock.me))] -3129 fn reset_endpoint_states(&mut self) { -3130 self.msock.node_map.reset_node_states() -3131 } +3064 let _handle = AbortOnDropHandle::new(tokio::spawn({ +3065 let endpoint = m2.endpoint.clone(); +3066 async move { +3067 while let Some(incoming) = endpoint.accept().await { +3068 println!("Incoming first conn!"); +3069 let conn = incoming.await.e()?; +3070 conn.closed().await; +3071 } +3072 +3073 Ok::<_, n0_snafu::Error>(()) +3074 } +3075 })); +3076 +3077 println!("first conn!"); +3078 let conn = m1 +3079 .endpoint +3080 .connect(m2.endpoint.node_addr().initialized().await?, ALPN) +3081 .await?; +3082 println!("Closing first conn"); +3083 conn.close(0u32.into(), b"bye lolz"); +3084 conn.closed().await; +3085 println!("Closed first conn"); +3086 +3087 Ok(()) +3088 } +3089 +3090 #[tokio::test(flavor = "multi_thread")] +3091 #[traced_test] +3092 async fn test_two_devices_roundtrip_network_change() -> Result { +3093 time::timeout( +3094 Duration::from_secs(90), +3095 test_two_devices_roundtrip_network_change_impl(), +3096 ) +3097 .await +3098 .context("timeout")? +3099 } +3100 +3101 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly +3102 /// with (simulated) network changes. +3103 async fn test_two_devices_roundtrip_network_change_impl() -> Result { +3104 let m1 = MagicStack::new(RelayMode::Disabled).await; +3105 let m2 = MagicStack::new(RelayMode::Disabled).await; +3106 +3107 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; +3108 +3109 let offset = || { +3110 let delay = rand::thread_rng().gen_range(10..=500); +3111 Duration::from_millis(delay) +3112 }; +3113 let rounds = 5; +3114 +3115 // Regular network changes to m1 only. +3116 let m1_network_change_guard = { +3117 let m1 = m1.clone(); +3118 let task = tokio::spawn(async move { +3119 loop { +3120 println!("[m1] network change"); +3121 m1.endpoint.magic_sock().force_network_change(true).await; +3122 time::sleep(offset()).await; +3123 } +3124 }); +3125 AbortOnDropHandle::new(task) +3126 }; +3127 +3128 for i in 0..rounds { +3129 println!("-- [m1 changes] round {}", i + 1); +3130 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +3131 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; 3132 -3133 /// Tells the relay actor to close stale relay connections. -3134 /// -3135 /// The relay connections who's local endpoints no longer exist after a network change -3136 /// will error out soon enough. Closing them eagerly speeds this up however and allows -3137 /// re-establishing a relay connection faster. -3138 async fn close_stale_relay_connections(&self) { -3139 let ifs = interfaces::State::new().await; -3140 #[cfg(not(wasm_browser))] -3141 let local_ips = ifs -3142 .interfaces -3143 .values() -3144 .flat_map(|netif| netif.addrs()) -3145 .map(|ipnet| ipnet.addr()) -3146 .collect(); -3147 // In browsers, we don't have this information. This will do the right thing in the ActiveRelayActor, though. -3148 #[cfg(wasm_browser)] -3149 let local_ips = Vec::new(); -3150 self.send_relay_actor(RelayActorMessage::MaybeCloseRelaysOnRebind(local_ips)); -3151 } -3152 -3153 fn send_relay_actor(&self, msg: RelayActorMessage) { -3154 match self.relay_actor_sender.try_send(msg) { -3155 Ok(_) => {} -3156 Err(mpsc::error::TrySendError::Closed(_)) => { -3157 warn!("unable to send to relay actor, already closed"); -3158 } -3159 Err(mpsc::error::TrySendError::Full(_)) => { -3160 warn!("dropping message for relay actor, channel is full"); -3161 } -3162 } -3163 } -3164} -3165 -3166fn new_re_stun_timer(initial_delay: bool) -> time::Interval { -3167 // Pick a random duration between 20 and 26 seconds (just under 30s, -3168 // a common UDP NAT timeout on Linux,etc) -3169 let mut rng = rand::thread_rng(); -3170 let d: Duration = rng.gen_range(Duration::from_secs(20)..=Duration::from_secs(26)); -3171 if initial_delay { -3172 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); -3173 time::interval_at(time::Instant::now() + d, d) -3174 } else { -3175 debug!( -3176 "scheduling periodic_stun to run immediately and in {}s", -3177 d.as_secs() -3178 ); -3179 time::interval(d) -3180 } -3181} +3133 println!("-- [m1 changes] larger data"); +3134 let mut data = vec![0u8; 10 * 1024]; +3135 rand::thread_rng().fill_bytes(&mut data); +3136 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +3137 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +3138 } +3139 +3140 std::mem::drop(m1_network_change_guard); +3141 +3142 // Regular network changes to m2 only. +3143 let m2_network_change_guard = { +3144 let m2 = m2.clone(); +3145 let task = tokio::spawn(async move { +3146 loop { +3147 println!("[m2] network change"); +3148 m2.endpoint.magic_sock().force_network_change(true).await; +3149 time::sleep(offset()).await; +3150 } +3151 }); +3152 AbortOnDropHandle::new(task) +3153 }; +3154 +3155 for i in 0..rounds { +3156 println!("-- [m2 changes] round {}", i + 1); +3157 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +3158 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +3159 +3160 println!("-- [m2 changes] larger data"); +3161 let mut data = vec![0u8; 10 * 1024]; +3162 rand::thread_rng().fill_bytes(&mut data); +3163 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +3164 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +3165 } +3166 +3167 std::mem::drop(m2_network_change_guard); +3168 +3169 // Regular network changes to both m1 and m2 only. +3170 let m1_m2_network_change_guard = { +3171 let m1 = m1.clone(); +3172 let m2 = m2.clone(); +3173 let task = tokio::spawn(async move { +3174 println!("-- [m1] network change"); +3175 m1.endpoint.magic_sock().force_network_change(true).await; +3176 println!("-- [m2] network change"); +3177 m2.endpoint.magic_sock().force_network_change(true).await; +3178 time::sleep(offset()).await; +3179 }); +3180 AbortOnDropHandle::new(task) +3181 }; 3182 -3183#[cfg(not(wasm_browser))] -3184fn bind_with_fallback(mut addr: SocketAddr) -> io::Result<UdpSocket> { -3185 debug!(%addr, "binding"); -3186 -3187 // First try binding a preferred port, if specified -3188 match UdpSocket::bind_full(addr) { -3189 Ok(socket) => { -3190 let local_addr = socket.local_addr()?; -3191 debug!(%addr, %local_addr, "successfully bound"); -3192 return Ok(socket); +3183 for i in 0..rounds { +3184 println!("-- [m1 & m2 changes] round {}", i + 1); +3185 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +3186 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +3187 +3188 println!("-- [m1 & m2 changes] larger data"); +3189 let mut data = vec![0u8; 10 * 1024]; +3190 rand::thread_rng().fill_bytes(&mut data); +3191 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +3192 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; 3193 } -3194 Err(err) => { -3195 debug!(%addr, "failed to bind: {err:#}"); -3196 // If that was already the fallback port, then error out -3197 if addr.port() == 0 { -3198 return Err(err); -3199 } -3200 } -3201 } -3202 -3203 // Otherwise, try binding with port 0 -3204 addr.set_port(0); -3205 UdpSocket::bind_full(addr) -3206} +3194 +3195 std::mem::drop(m1_m2_network_change_guard); +3196 Ok(()) +3197 } +3198 +3199 #[tokio::test(flavor = "multi_thread")] +3200 #[traced_test] +3201 async fn test_two_devices_setup_teardown() -> Result { +3202 for i in 0..10 { +3203 println!("-- round {i}"); +3204 println!("setting up magic stack"); +3205 let m1 = MagicStack::new(RelayMode::Disabled).await; +3206 let m2 = MagicStack::new(RelayMode::Disabled).await; 3207 -3208/// The discovered direct addresses of this [`MagicSock`]. -3209/// -3210/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself. -3211/// They include all locally bound ones as well as those discovered by other mechanisms like -3212/// STUN. -3213#[derive(derive_more::Debug, Default, Clone)] -3214struct DiscoveredDirectAddrs { -3215 /// The last set of discovered direct addresses. -3216 addrs: Watchable<Option<BTreeSet<DirectAddr>>>, -3217 -3218 /// The last time the direct addresses were updated, even if there was no change. -3219 /// -3220 /// This is only ever None at startup. -3221 updated_at: Arc<RwLock<Option<Instant>>>, -3222} -3223 -3224impl DiscoveredDirectAddrs { -3225 /// Updates the direct addresses, returns `true` if they changed, `false` if not. -3226 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { -3227 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); -3228 let updated = self.addrs.set(Some(addrs)).is_ok(); -3229 if updated { -3230 event!( -3231 target: "iroh::_events::direct_addrs", -3232 Level::DEBUG, -3233 addrs = ?self.addrs.get(), -3234 ); -3235 } -3236 updated -3237 } -3238 -3239 fn sockaddrs(&self) -> BTreeSet<SocketAddr> { -3240 self.addrs -3241 .get() -3242 .unwrap_or_default() -3243 .into_iter() -3244 .map(|da| da.addr) -3245 .collect() -3246 } -3247 -3248 /// Whether the direct addr information is considered "fresh". -3249 /// -3250 /// If not fresh you should probably update the direct addresses before using this info. -3251 /// -3252 /// Returns `Ok(())` if fresh enough and `Err(elapsed)` if not fresh enough. -3253 /// `elapsed` is the time elapsed since the direct addresses were last updated. -3254 /// -3255 /// If there is no direct address information `Err(Duration::ZERO)` is returned. -3256 fn fresh_enough(&self) -> Result<(), Duration> { -3257 match *self.updated_at.read().expect("poisoned") { -3258 None => Err(Duration::ZERO), -3259 Some(time) => { -3260 let elapsed = time.elapsed(); -3261 if elapsed <= ENDPOINTS_FRESH_ENOUGH_DURATION { -3262 Ok(()) -3263 } else { -3264 Err(elapsed) -3265 } -3266 } -3267 } -3268 } -3269 -3270 fn to_call_me_maybe_message(&self) -> disco::CallMeMaybe { -3271 let my_numbers = self -3272 .addrs -3273 .get() -3274 .unwrap_or_default() -3275 .into_iter() -3276 .map(|da| da.addr) -3277 .collect(); -3278 disco::CallMeMaybe { my_numbers } -3279 } -3280} -3281 -3282/// Split a transmit containing a GSO payload into individual packets. -3283/// -3284/// This allocates the data. -3285/// -3286/// If the transmit has a segment size it contains multiple GSO packets. It will be split -3287/// into multiple packets according to that segment size. If it does not have a segment -3288/// size, the contents will be sent as a single packet. -3289// TODO: If quinn stayed on bytes this would probably be much cheaper, probably. Need to -3290// figure out where they allocate the Vec. -3291fn split_packets(transmit: &quinn_udp::Transmit) -> RelayContents { -3292 let mut res = SmallVec::with_capacity(1); -3293 let contents = transmit.contents; -3294 if let Some(segment_size) = transmit.segment_size { -3295 for chunk in contents.chunks(segment_size) { -3296 res.push(Bytes::from(chunk.to_vec())); -3297 } -3298 } else { -3299 res.push(Bytes::from(contents.to_vec())); -3300 } -3301 res -3302} -3303 -3304/// The fake address used by the QUIC layer to address a node. -3305/// -3306/// You can consider this as nothing more than a lookup key for a node the [`MagicSock`] knows -3307/// about. -3308/// -3309/// [`MagicSock`] can reach a node by several real socket addresses, or maybe even via the relay -3310/// node. The QUIC layer however needs to address a node by a stable [`SocketAddr`] so -3311/// that normal socket APIs can function. Thus when a new node is introduced to a [`MagicSock`] -3312/// it is given a new fake address. This is the type of that address. -3313/// -3314/// It is but a newtype. And in our QUIC-facing socket APIs like [`AsyncUdpSocket`] it -3315/// comes in as the inner [`Ipv6Addr`], in those interfaces we have to be careful to do -3316/// the conversion to this type. -3317#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -3318pub(crate) struct NodeIdMappedAddr(Ipv6Addr); -3319 -3320/// Can occur when converting a [`SocketAddr`] to an [`NodeIdMappedAddr`] -3321#[derive(Debug, Snafu)] -3322#[snafu(display("Failed to convert"))] -3323pub struct NodeIdMappedAddrError; +3208 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; +3209 +3210 println!("closing endpoints"); +3211 let msock1 = m1.endpoint.magic_sock(); +3212 let msock2 = m2.endpoint.magic_sock(); +3213 m1.endpoint.close().await; +3214 m2.endpoint.close().await; +3215 +3216 assert!(msock1.msock.is_closed()); +3217 assert!(msock2.msock.is_closed()); +3218 } +3219 Ok(()) +3220 } +3221 +3222 #[tokio::test] +3223 #[traced_test] +3224 async fn test_local_endpoints() { +3225 let ms = Handle::new(Default::default()).await.unwrap(); +3226 +3227 // See if we can get endpoints. +3228 let eps0 = ms.direct_addresses().initialized().await.unwrap(); +3229 println!("{eps0:?}"); +3230 assert!(!eps0.is_empty()); +3231 +3232 // Getting the endpoints again immediately should give the same results. +3233 let eps1 = ms.direct_addresses().initialized().await.unwrap(); +3234 println!("{eps1:?}"); +3235 assert_eq!(eps0, eps1); +3236 } +3237 +3238 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`]. +3239 /// +3240 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept +3241 /// connections using [`ALPN`]. +3242 /// +3243 /// Use [`magicsock_connect`] to establish connections. +3244 #[instrument(name = "ep", skip_all, fields(me = secret_key.public().fmt_short()))] +3245 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> { +3246 let quic_server_config = +3247 tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![ALPN.to_vec()], true); +3248 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); +3249 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); +3250 +3251 let dns_resolver = DnsResolver::new(); +3252 let opts = Options { +3253 addr_v4: None, +3254 addr_v6: None, +3255 secret_key: secret_key.clone(), +3256 relay_map: RelayMap::empty(), +3257 relay_protocol: iroh_relay::http::Protocol::default(), +3258 node_map: None, +3259 discovery: None, +3260 discovery_user_data: None, +3261 dns_resolver, +3262 proxy_url: None, +3263 server_config, +3264 insecure_skip_relay_cert_verify: false, +3265 path_selection: PathSelection::default(), +3266 metrics: Default::default(), +3267 }; +3268 let msock = MagicSock::spawn(opts).await?; +3269 Ok(msock) +3270 } +3271 +3272 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`. +3273 /// +3274 /// Uses [`ALPN`], `node_id`, must match `addr`. +3275 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))] +3276 async fn magicsock_connect( +3277 ep: &quinn::Endpoint, +3278 ep_secret_key: SecretKey, +3279 addr: NodeIdMappedAddr, +3280 node_id: NodeId, +3281 ) -> Result<quinn::Connection> { +3282 // Endpoint::connect sets this, do the same to have similar behaviour. +3283 let mut transport_config = quinn::TransportConfig::default(); +3284 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); +3285 +3286 magicsock_connect_with_transport_config( +3287 ep, +3288 ep_secret_key, +3289 addr, +3290 node_id, +3291 Arc::new(transport_config), +3292 ) +3293 .await +3294 } +3295 +3296 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`. +3297 /// +3298 /// This version allows customising the transport config. +3299 /// +3300 /// Uses [`ALPN`], `node_id`, must match `addr`. +3301 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))] +3302 async fn magicsock_connect_with_transport_config( +3303 ep: &quinn::Endpoint, +3304 ep_secret_key: SecretKey, +3305 mapped_addr: NodeIdMappedAddr, +3306 node_id: NodeId, +3307 transport_config: Arc<quinn::TransportConfig>, +3308 ) -> Result<quinn::Connection> { +3309 let alpns = vec![ALPN.to_vec()]; +3310 let quic_client_config = +3311 tls::TlsConfig::new(ep_secret_key.clone()).make_client_config(alpns, true); +3312 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); +3313 client_config.transport_config(transport_config); +3314 let connect = ep +3315 .connect_with( +3316 client_config, +3317 mapped_addr.private_socket_addr(), +3318 &tls::name::encode(node_id), +3319 ) +3320 .context("connect")?; +3321 let connection = connect.await.e()?; +3322 Ok(connection) +3323 } 3324 -3325/// Counter to always generate unique addresses for [`NodeIdMappedAddr`]. -3326static NODE_ID_ADDR_COUNTER: AtomicU64 = AtomicU64::new(1); -3327 -3328impl NodeIdMappedAddr { -3329 /// The Prefix/L of our Unique Local Addresses. -3330 const ADDR_PREFIXL: u8 = 0xfd; -3331 /// The Global ID used in our Unique Local Addresses. -3332 const ADDR_GLOBAL_ID: [u8; 5] = [21, 7, 10, 81, 11]; -3333 /// The Subnet ID used in our Unique Local Addresses. -3334 const ADDR_SUBNET: [u8; 2] = [0; 2]; -3335 -3336 /// The dummy port used for all [`NodeIdMappedAddr`]s. -3337 const NODE_ID_MAPPED_PORT: u16 = 12345; +3325 #[tokio::test] +3326 #[traced_test] +3327 async fn test_try_send_no_send_addr() { +3328 // Regression test: if there is no send_addr we should keep being able to use the +3329 // Endpoint. +3330 +3331 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +3332 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +3333 let node_id_2 = secret_key_2.public(); +3334 let secret_key_missing_node = SecretKey::from_bytes(&[255u8; 32]); +3335 let node_id_missing_node = secret_key_missing_node.public(); +3336 +3337 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); 3338 -3339 /// Generates a globally unique fake UDP address. -3340 /// -3341 /// This generates and IPv6 Unique Local Address according to RFC 4193. -3342 pub(crate) fn generate() -> Self { -3343 let mut addr = [0u8; 16]; -3344 addr[0] = Self::ADDR_PREFIXL; -3345 addr[1..6].copy_from_slice(&Self::ADDR_GLOBAL_ID); -3346 addr[6..8].copy_from_slice(&Self::ADDR_SUBNET); -3347 -3348 let counter = NODE_ID_ADDR_COUNTER.fetch_add(1, Ordering::Relaxed); -3349 addr[8..16].copy_from_slice(&counter.to_be_bytes()); -3350 -3351 Self(Ipv6Addr::from(addr)) -3352 } -3353 -3354 /// Returns a consistent [`SocketAddr`] for the [`NodeIdMappedAddr`]. -3355 /// -3356 /// This socket address does not have a routable IP address. -3357 /// -3358 /// This uses a made-up port number, since the port does not play a role in looking up -3359 /// the node in the [`NodeMap`]. This socket address is only to be used to pass into -3360 /// Quinn. -3361 pub(crate) fn private_socket_addr(&self) -> SocketAddr { -3362 SocketAddr::new(IpAddr::from(self.0), Self::NODE_ID_MAPPED_PORT) -3363 } -3364} -3365 -3366impl TryFrom<Ipv6Addr> for NodeIdMappedAddr { -3367 type Error = NodeIdMappedAddrError; -3368 -3369 fn try_from(value: Ipv6Addr) -> Result<Self, Self::Error> { -3370 let octets = value.octets(); -3371 if octets[0] == Self::ADDR_PREFIXL -3372 && octets[1..6] == Self::ADDR_GLOBAL_ID -3373 && octets[6..8] == Self::ADDR_SUBNET -3374 { -3375 return Ok(Self(value)); -3376 } -3377 Err(NodeIdMappedAddrError) -3378 } -3379} -3380 -3381impl std::fmt::Display for NodeIdMappedAddr { -3382 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { -3383 write!(f, "NodeIdMappedAddr({})", self.0) -3384 } -3385} -3386 -3387fn disco_message_sent(msg: &disco::Message, metrics: &MagicsockMetrics) { -3388 match msg { -3389 disco::Message::Ping(_) => { -3390 metrics.sent_disco_ping.inc(); -3391 } -3392 disco::Message::Pong(_) => { -3393 metrics.sent_disco_pong.inc(); -3394 } -3395 disco::Message::CallMeMaybe(_) => { -3396 metrics.sent_disco_call_me_maybe.inc(); -3397 } -3398 } -3399} -3400 -3401/// A *direct address* on which an iroh-node might be contactable. -3402/// -3403/// Direct addresses are UDP socket addresses on which an iroh node could potentially be -3404/// contacted. These can come from various sources depending on the network topology of the -3405/// iroh node, see [`DirectAddrType`] for the several kinds of sources. -3406#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -3407pub struct DirectAddr { -3408 /// The address. -3409 pub addr: SocketAddr, -3410 /// The origin of this direct address. -3411 pub typ: DirectAddrType, -3412} +3339 // Generate an address not present in the NodeMap. +3340 let bad_addr = NodeIdMappedAddr::generate(); +3341 +3342 // 500ms is rather fast here. Running this locally it should always be the correct +3343 // timeout. If this is too slow however the test will not become flaky as we are +3344 // expecting the timeout, we might just get the timeout for the wrong reason. But +3345 // this speeds up the test. +3346 let res = tokio::time::timeout( +3347 Duration::from_millis(500), +3348 magicsock_connect( +3349 msock_1.endpoint(), +3350 secret_key_1.clone(), +3351 bad_addr, +3352 node_id_missing_node, +3353 ), +3354 ) +3355 .await; +3356 assert!(res.is_err(), "expecting timeout"); +3357 +3358 // Now check we can still create another connection with this endpoint. +3359 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); +3360 +3361 // This needs an accept task +3362 let accept_task = tokio::spawn({ +3363 async fn accept(ep: quinn::Endpoint) -> Result<()> { +3364 let incoming = ep.accept().await.context("no incoming")?; +3365 let _conn = incoming +3366 .accept() +3367 .context("accept")? +3368 .await +3369 .context("connecting")?; +3370 +3371 // Keep this connection alive for a while +3372 tokio::time::sleep(Duration::from_secs(10)).await; +3373 info!("accept finished"); +3374 Ok(()) +3375 } +3376 let ep = msock_2.endpoint().clone(); +3377 async move { +3378 if let Err(err) = accept(ep).await { +3379 error!("{err:#}"); +3380 } +3381 } +3382 .instrument(info_span!("ep2.accept, me = node_id_2.fmt_short()")) +3383 }); +3384 let _accept_task = AbortOnDropHandle::new(accept_task); +3385 +3386 let node_addr_2 = NodeAddr { +3387 node_id: node_id_2, +3388 relay_url: None, +3389 direct_addresses: msock_2 +3390 .direct_addresses() +3391 .initialized() +3392 .await +3393 .expect("no direct addrs") +3394 .into_iter() +3395 .map(|x| x.addr) +3396 .collect(), +3397 }; +3398 msock_1 +3399 .add_node_addr( +3400 node_addr_2, +3401 Source::NamedApp { +3402 name: "test".into(), +3403 }, +3404 ) +3405 .unwrap(); +3406 let addr = msock_1.get_mapping_addr(node_id_2).unwrap(); +3407 let res = tokio::time::timeout( +3408 Duration::from_secs(10), +3409 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr, node_id_2), +3410 ) +3411 .await +3412 .expect("timeout while connecting"); 3413 -3414/// The type of direct address. -3415/// -3416/// These are the various sources or origins from which an iroh node might have found a -3417/// possible [`DirectAddr`]. -3418#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] -3419pub enum DirectAddrType { -3420 /// Not yet determined.. -3421 Unknown, -3422 /// A locally bound socket address. -3423 Local, -3424 /// Public internet address discovered via STUN. -3425 /// -3426 /// When possible an iroh node will perform STUN to discover which is the address -3427 /// from which it sends data on the public internet. This can be different from locally -3428 /// bound addresses when the node is on a local network which performs NAT or similar. -3429 Stun, -3430 /// An address assigned by the router using port mapping. -3431 /// -3432 /// When possible an iroh node will request a port mapping from the local router to -3433 /// get a publicly routable direct address. -3434 Portmapped, -3435 /// Hard NAT: STUN'ed IPv4 address + local fixed port. -3436 /// -3437 /// It is possible to configure iroh to bound to a specific port and independently -3438 /// configure the router to forward this port to the iroh node. This indicates a -3439 /// situation like this, which still uses STUN to discover the public address. -3440 Stun4LocalPort, -3441} -3442 -3443impl Display for DirectAddrType { -3444 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { -3445 match self { -3446 DirectAddrType::Unknown => write!(f, "?"), -3447 DirectAddrType::Local => write!(f, "local"), -3448 DirectAddrType::Stun => write!(f, "stun"), -3449 DirectAddrType::Portmapped => write!(f, "portmap"), -3450 DirectAddrType::Stun4LocalPort => write!(f, "stun4localport"), -3451 } -3452 } -3453} -3454 -3455/// Contains information about the host's network state. -3456#[derive(Debug, Clone, PartialEq)] -3457struct NetInfo { -3458 /// Says whether the host's NAT mappings vary based on the destination IP. -3459 mapping_varies_by_dest_ip: Option<bool>, -3460 -3461 /// If their router does hairpinning. It reports true even if there's no NAT involved. -3462 hair_pinning: Option<bool>, -3463 -3464 /// Whether the host has IPv6 internet connectivity. -3465 working_ipv6: Option<bool>, -3466 -3467 /// Whether the OS supports IPv6 at all, regardless of whether IPv6 internet connectivity is available. -3468 os_has_ipv6: Option<bool>, -3469 -3470 /// Whether the host has UDP internet connectivity. -3471 working_udp: Option<bool>, -3472 -3473 /// Whether ICMPv4 works, `None` means not checked. -3474 working_icmp_v4: Option<bool>, -3475 -3476 /// Whether ICMPv6 works, `None` means not checked. -3477 working_icmp_v6: Option<bool>, -3478 -3479 /// Whether we have an existing portmap open (UPnP, PMP, or PCP). -3480 have_port_map: bool, -3481 -3482 /// Probe indicating the presence of port mapping protocols on the LAN. -3483 #[cfg(not(wasm_browser))] -3484 portmap_probe: Option<portmapper::ProbeOutput>, -3485 -3486 /// This node's preferred relay server for incoming traffic. -3487 /// -3488 /// The node might be be temporarily connected to multiple relay servers (to send to -3489 /// other nodes) but this is the relay on which you can always contact this node. Also -3490 /// known as home relay. -3491 preferred_relay: Option<RelayUrl>, -3492 -3493 /// The fastest recent time to reach various relay STUN servers, in seconds. -3494 /// -3495 /// This should only be updated rarely, or when there's a -3496 /// material change, as any change here also gets uploaded to the control plane. -3497 relay_latency: BTreeMap<String, f64>, -3498} -3499 -3500impl NetInfo { -3501 /// Checks if this is probably still the same network as *other*. -3502 /// -3503 /// This tries to compare the network situation, without taking into account things -3504 /// expected to change a little like e.g. latency to the relay server. -3505 fn basically_equal(&self, other: &Self) -> bool { -3506 let eq_icmp_v4 = match (self.working_icmp_v4, other.working_icmp_v4) { -3507 (Some(slf), Some(other)) => slf == other, -3508 _ => true, // ignore for comparison if only one report had this info -3509 }; -3510 let eq_icmp_v6 = match (self.working_icmp_v6, other.working_icmp_v6) { -3511 (Some(slf), Some(other)) => slf == other, -3512 _ => true, // ignore for comparison if only one report had this info -3513 }; +3414 // aka assert!(res.is_ok()) but with nicer error reporting. +3415 res.unwrap(); +3416 +3417 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that +3418 // much internal state for now. +3419 } +3420 +3421 #[tokio::test] +3422 #[traced_test] +3423 async fn test_try_send_no_udp_addr_or_relay_url() { +3424 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` +3425 // behaviour of MagicSock::try_send. +3426 +3427 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +3428 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +3429 let node_id_2 = secret_key_2.public(); +3430 +3431 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); +3432 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); +3433 let ep_2 = msock_2.endpoint().clone(); +3434 +3435 // We need a task to accept the connection. +3436 let accept_task = tokio::spawn({ +3437 async fn accept(ep: quinn::Endpoint) -> Result<()> { +3438 let incoming = ep.accept().await.context("no incoming")?; +3439 let conn = incoming +3440 .accept() +3441 .context("accept")? +3442 .await +3443 .context("connecting")?; +3444 let mut stream = conn.accept_uni().await.context("accept uni")?; +3445 stream.read_to_end(1 << 16).await.context("read to end")?; +3446 info!("accept finished"); +3447 Ok(()) +3448 } +3449 async move { +3450 if let Err(err) = accept(ep_2).await { +3451 error!("{err:#}"); +3452 } +3453 } +3454 .instrument(info_span!("ep2.accept", me = node_id_2.fmt_short())) +3455 }); +3456 let _accept_task = AbortOnDropHandle::new(accept_task); +3457 +3458 // Add an empty entry in the NodeMap of ep_1 +3459 msock_1.node_map.add_node_addr( +3460 NodeAddr { +3461 node_id: node_id_2, +3462 relay_url: None, +3463 direct_addresses: Default::default(), +3464 }, +3465 Source::NamedApp { +3466 name: "test".into(), +3467 }, +3468 &msock_1.metrics.magicsock, +3469 ); +3470 let addr_2 = msock_1.get_mapping_addr(node_id_2).unwrap(); +3471 +3472 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does +3473 // not take forever. You need to check the log output to verify this is really +3474 // triggering the correct error. +3475 // In test_try_send_no_send_addr() above you may have noticed we used +3476 // tokio::time::timeout() on the connection attempt instead. Here however we want +3477 // Quinn itself to have fully given up on the connection attempt because we will +3478 // later connect to **the same** node. If Quinn did not give up on the connection +3479 // we'd close it on drop, and the retransmits of the close packets would interfere +3480 // with the next handshake, closing it during the handshake. This makes the test a +3481 // little slower though. +3482 let mut transport_config = quinn::TransportConfig::default(); +3483 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); +3484 let res = magicsock_connect_with_transport_config( +3485 msock_1.endpoint(), +3486 secret_key_1.clone(), +3487 addr_2, +3488 node_id_2, +3489 Arc::new(transport_config), +3490 ) +3491 .await; +3492 assert!(res.is_err(), "expected timeout"); +3493 info!("first connect timed out as expected"); +3494 +3495 // Provide correct addressing information +3496 msock_1.node_map.add_node_addr( +3497 NodeAddr { +3498 node_id: node_id_2, +3499 relay_url: None, +3500 direct_addresses: msock_2 +3501 .direct_addresses() +3502 .initialized() +3503 .await +3504 .expect("no direct addrs") +3505 .into_iter() +3506 .map(|x| x.addr) +3507 .collect(), +3508 }, +3509 Source::NamedApp { +3510 name: "test".into(), +3511 }, +3512 &msock_1.metrics.magicsock, +3513 ); 3514 -3515 #[cfg(not(wasm_browser))] -3516 let probe_eq = self.portmap_probe == other.portmap_probe; -3517 #[cfg(wasm_browser)] -3518 let probe_eq = true; -3519 -3520 self.mapping_varies_by_dest_ip == other.mapping_varies_by_dest_ip -3521 && self.hair_pinning == other.hair_pinning -3522 && self.working_ipv6 == other.working_ipv6 -3523 && self.os_has_ipv6 == other.os_has_ipv6 -3524 && self.working_udp == other.working_udp -3525 && eq_icmp_v4 -3526 && eq_icmp_v6 -3527 && self.have_port_map == other.have_port_map -3528 && probe_eq -3529 && self.preferred_relay == other.preferred_relay -3530 } -3531} -3532 -3533#[cfg(test)] -3534mod tests { -3535 use std::{collections::BTreeSet, sync::Arc, time::Duration}; -3536 -3537 use bytes::Bytes; -3538 use data_encoding::HEXLOWER; -3539 use iroh_base::{NodeAddr, NodeId, PublicKey, RelayUrl, SecretKey}; -3540 use iroh_relay::RelayMap; -3541 use n0_future::{time, StreamExt}; -3542 use n0_snafu::{Result, ResultExt}; -3543 use quinn::ServerConfig; -3544 use rand::{Rng, RngCore}; -3545 use tokio::task::JoinSet; -3546 use tokio_util::task::AbortOnDropHandle; -3547 use tracing::{debug, error, info, info_span, instrument, Instrument}; -3548 use tracing_test::traced_test; -3549 -3550 use super::{split_packets, NodeIdMappedAddr, Options}; -3551 use crate::{ -3552 defaults::staging::{self, EU_RELAY_HOSTNAME}, -3553 dns::DnsResolver, -3554 endpoint::{DirectAddr, PathSelection, Source}, -3555 magicsock::{ -3556 node_map, Handle, MagicSock, RelayContents, RelayDatagramRecvQueue, RelayRecvDatagram, -3557 }, -3558 tls, -3559 watcher::Watcher as _, -3560 Endpoint, RelayMode, -3561 }; -3562 -3563 const ALPN: &[u8] = b"n0/test/1"; -3564 -3565 impl Default for Options { -3566 fn default() -> Self { -3567 let secret_key = SecretKey::generate(rand::rngs::OsRng); -3568 let server_config = make_default_server_config(&secret_key); -3569 Options { -3570 addr_v4: None, -3571 addr_v6: None, -3572 secret_key, -3573 relay_map: RelayMap::empty(), -3574 relay_protocol: iroh_relay::http::Protocol::default(), -3575 node_map: None, -3576 discovery: None, -3577 proxy_url: None, -3578 dns_resolver: DnsResolver::new(), -3579 server_config, -3580 #[cfg(any(test, feature = "test-utils"))] -3581 insecure_skip_relay_cert_verify: false, -3582 #[cfg(any(test, feature = "test-utils"))] -3583 path_selection: PathSelection::default(), -3584 discovery_user_data: None, -3585 metrics: Default::default(), -3586 } -3587 } -3588 } -3589 -3590 /// Generate a server config with no ALPNS and a default transport configuration -3591 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig { -3592 let quic_server_config = -3593 crate::tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![], false); -3594 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); -3595 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); -3596 server_config -3597 } -3598 -3599 impl MagicSock { -3600 #[track_caller] -3601 pub fn add_test_addr(&self, node_addr: NodeAddr) { -3602 self.add_node_addr( -3603 node_addr, -3604 Source::NamedApp { -3605 name: "test".into(), -3606 }, -3607 ) -3608 .unwrap() -3609 } -3610 } -3611 -3612 /// Magicsock plus wrappers for sending packets -3613 #[derive(Clone)] -3614 struct MagicStack { -3615 secret_key: SecretKey, -3616 endpoint: Endpoint, -3617 } -3618 -3619 impl MagicStack { -3620 async fn new(relay_mode: RelayMode) -> Self { -3621 let secret_key = SecretKey::generate(rand::thread_rng()); -3622 -3623 let mut transport_config = quinn::TransportConfig::default(); -3624 transport_config.max_idle_timeout(Some(Duration::from_secs(10).try_into().unwrap())); -3625 -3626 let endpoint = Endpoint::builder() -3627 .secret_key(secret_key.clone()) -3628 .transport_config(transport_config) -3629 .relay_mode(relay_mode) -3630 .alpns(vec![ALPN.to_vec()]) -3631 .bind() -3632 .await -3633 .unwrap(); -3634 -3635 Self { -3636 secret_key, -3637 endpoint, -3638 } -3639 } -3640 -3641 fn tracked_endpoints(&self) -> Vec<PublicKey> { -3642 self.endpoint -3643 .magic_sock() -3644 .list_remote_infos() -3645 .into_iter() -3646 .map(|ep| ep.node_id) -3647 .collect() -3648 } -3649 -3650 fn public(&self) -> PublicKey { -3651 self.secret_key.public() -3652 } -3653 } -3654 -3655 /// Monitors endpoint changes and plumbs things together. -3656 /// -3657 /// This is a way of connecting endpoints without a relay server. Whenever the local -3658 /// endpoints of a magic endpoint change this address is added to the other magic -3659 /// sockets. This function will await until the endpoints are connected the first time -3660 /// before returning. -3661 /// -3662 /// When the returned drop guard is dropped, the tasks doing this updating are stopped. -3663 #[instrument(skip_all)] -3664 async fn mesh_stacks(stacks: Vec<MagicStack>) -> Result<JoinSet<()>> { -3665 /// Registers endpoint addresses of a node to all other nodes. -3666 fn update_direct_addrs( -3667 stacks: &[MagicStack], -3668 my_idx: usize, -3669 new_addrs: BTreeSet<DirectAddr>, -3670 ) { -3671 let me = &stacks[my_idx]; -3672 for (i, m) in stacks.iter().enumerate() { -3673 if i == my_idx { -3674 continue; -3675 } -3676 -3677 let addr = NodeAddr { -3678 node_id: me.public(), -3679 relay_url: None, -3680 direct_addresses: new_addrs.iter().map(|ep| ep.addr).collect(), -3681 }; -3682 m.endpoint.magic_sock().add_test_addr(addr); -3683 } -3684 } -3685 -3686 // For each node, start a task which monitors its local endpoints and registers them -3687 // with the other nodes as local endpoints become known. -3688 let mut tasks = JoinSet::new(); -3689 for (my_idx, m) in stacks.iter().enumerate() { -3690 let m = m.clone(); -3691 let stacks = stacks.clone(); -3692 tasks.spawn(async move { -3693 let me = m.endpoint.node_id().fmt_short(); -3694 let mut stream = m.endpoint.direct_addresses().stream().filter_map(|i| i); -3695 while let Some(new_eps) = stream.next().await { -3696 info!(%me, "conn{} endpoints update: {:?}", my_idx + 1, new_eps); -3697 update_direct_addrs(&stacks, my_idx, new_eps); -3698 } -3699 }); -3700 } -3701 -3702 // Wait for all nodes to be registered with each other. -3703 time::timeout(Duration::from_secs(10), async move { -3704 let all_node_ids: Vec<_> = stacks.iter().map(|ms| ms.endpoint.node_id()).collect(); -3705 loop { -3706 let mut ready = Vec::with_capacity(stacks.len()); -3707 for ms in stacks.iter() { -3708 let endpoints = ms.tracked_endpoints(); -3709 let my_node_id = ms.endpoint.node_id(); -3710 let all_nodes_meshed = all_node_ids -3711 .iter() -3712 .filter(|node_id| **node_id != my_node_id) -3713 .all(|node_id| endpoints.contains(node_id)); -3714 ready.push(all_nodes_meshed); -3715 } -3716 if ready.iter().all(|meshed| *meshed) { -3717 break; -3718 } -3719 time::sleep(Duration::from_millis(200)).await; -3720 } -3721 }) -3722 .await -3723 .context("timeout")?; -3724 info!("all nodes meshed"); -3725 Ok(tasks) -3726 } -3727 -3728 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))] -3729 async fn echo_receiver(ep: MagicStack, loss: ExpectedLoss) -> Result { -3730 info!("accepting conn"); -3731 let conn = ep.endpoint.accept().await.expect("no conn"); -3732 -3733 info!("connecting"); -3734 let conn = conn.await.context("connecting")?; -3735 info!("accepting bi"); -3736 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.context("accept bi")?; -3737 -3738 info!("reading"); -3739 let val = recv_bi -3740 .read_to_end(usize::MAX) -3741 .await -3742 .context("read to end")?; -3743 -3744 info!("replying"); -3745 for chunk in val.chunks(12) { -3746 send_bi.write_all(chunk).await.context("write all")?; -3747 } -3748 -3749 info!("finishing"); -3750 send_bi.finish().context("finish")?; -3751 send_bi.stopped().await.context("stopped")?; -3752 -3753 let stats = conn.stats(); -3754 info!("stats: {:#?}", stats); -3755 // TODO: ensure panics in this function are reported ok -3756 if matches!(loss, ExpectedLoss::AlmostNone) { -3757 assert!( -3758 stats.path.lost_packets < 10, -3759 "[receiver] should not loose many packets", -3760 ); -3761 } -3762 -3763 info!("close"); -3764 conn.close(0u32.into(), b"done"); -3765 info!("wait idle"); -3766 ep.endpoint.endpoint().wait_idle().await; -3767 -3768 Ok(()) -3769 } -3770 -3771 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))] -3772 async fn echo_sender( -3773 ep: MagicStack, -3774 dest_id: PublicKey, -3775 msg: &[u8], -3776 loss: ExpectedLoss, -3777 ) -> Result { -3778 info!("connecting to {}", dest_id.fmt_short()); -3779 let dest = NodeAddr::new(dest_id); -3780 let conn = ep.endpoint.connect(dest, ALPN).await?; -3781 -3782 info!("opening bi"); -3783 let (mut send_bi, mut recv_bi) = conn.open_bi().await.context("open bi")?; -3784 -3785 info!("writing message"); -3786 send_bi.write_all(msg).await.context("write all")?; -3787 -3788 info!("finishing"); -3789 send_bi.finish().context("finish")?; -3790 send_bi.stopped().await.context("stopped")?; -3791 -3792 info!("reading_to_end"); -3793 let val = recv_bi -3794 .read_to_end(usize::MAX) -3795 .await -3796 .context("read to end")?; -3797 assert_eq!( -3798 val, -3799 msg, -3800 "[sender] expected {}, got {}", -3801 HEXLOWER.encode(msg), -3802 HEXLOWER.encode(&val) -3803 ); -3804 -3805 let stats = conn.stats(); -3806 info!("stats: {:#?}", stats); -3807 if matches!(loss, ExpectedLoss::AlmostNone) { -3808 assert!( -3809 stats.path.lost_packets < 10, -3810 "[sender] should not loose many packets", -3811 ); -3812 } -3813 -3814 info!("close"); -3815 conn.close(0u32.into(), b"done"); -3816 info!("wait idle"); -3817 ep.endpoint.endpoint().wait_idle().await; -3818 Ok(()) -3819 } -3820 -3821 #[derive(Debug, Copy, Clone)] -3822 enum ExpectedLoss { -3823 AlmostNone, -3824 YeahSure, -3825 } -3826 -3827 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. -3828 async fn run_roundtrip( -3829 sender: MagicStack, -3830 receiver: MagicStack, -3831 payload: &[u8], -3832 loss: ExpectedLoss, -3833 ) { -3834 let send_node_id = sender.endpoint.node_id(); -3835 let recv_node_id = receiver.endpoint.node_id(); -3836 info!("\nroundtrip: {send_node_id:#} -> {recv_node_id:#}"); -3837 -3838 let receiver_task = tokio::spawn(echo_receiver(receiver, loss)); -3839 let sender_res = echo_sender(sender, recv_node_id, payload, loss).await; -3840 let sender_is_err = match sender_res { -3841 Ok(()) => false, -3842 Err(err) => { -3843 eprintln!("[sender] Error:\n{err:#?}"); -3844 true -3845 } -3846 }; -3847 let receiver_is_err = match receiver_task.await { -3848 Ok(Ok(())) => false, -3849 Ok(Err(err)) => { -3850 eprintln!("[receiver] Error:\n{err:#?}"); -3851 true -3852 } -3853 Err(joinerr) => { -3854 if joinerr.is_panic() { -3855 std::panic::resume_unwind(joinerr.into_panic()); -3856 } else { -3857 eprintln!("[receiver] Error:\n{joinerr:#?}"); -3858 } -3859 true -3860 } -3861 }; -3862 if sender_is_err || receiver_is_err { -3863 panic!("Sender or receiver errored"); -3864 } -3865 } -3866 -3867 #[tokio::test(flavor = "multi_thread")] -3868 #[traced_test] -3869 async fn test_two_devices_roundtrip_quinn_magic() -> Result { -3870 let m1 = MagicStack::new(RelayMode::Disabled).await; -3871 let m2 = MagicStack::new(RelayMode::Disabled).await; -3872 -3873 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; -3874 -3875 for i in 0..5 { -3876 info!("\n-- round {i}"); -3877 run_roundtrip( -3878 m1.clone(), -3879 m2.clone(), -3880 b"hello m1", -3881 ExpectedLoss::AlmostNone, -3882 ) -3883 .await; -3884 run_roundtrip( -3885 m2.clone(), -3886 m1.clone(), -3887 b"hello m2", -3888 ExpectedLoss::AlmostNone, -3889 ) -3890 .await; -3891 -3892 info!("\n-- larger data"); -3893 let mut data = vec![0u8; 10 * 1024]; -3894 rand::thread_rng().fill_bytes(&mut data); -3895 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await; -3896 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await; -3897 } -3898 -3899 Ok(()) -3900 } -3901 -3902 #[tokio::test] -3903 #[traced_test] -3904 async fn test_regression_network_change_rebind_wakes_connection_driver() -> n0_snafu::Result { -3905 let m1 = MagicStack::new(RelayMode::Disabled).await; -3906 let m2 = MagicStack::new(RelayMode::Disabled).await; -3907 -3908 println!("Net change"); -3909 m1.endpoint.magic_sock().force_network_change(true).await; -3910 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding -3911 -3912 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; -3913 -3914 let _handle = AbortOnDropHandle::new(tokio::spawn({ -3915 let endpoint = m2.endpoint.clone(); -3916 async move { -3917 while let Some(incoming) = endpoint.accept().await { -3918 println!("Incoming first conn!"); -3919 let conn = incoming.await.e()?; -3920 conn.closed().await; -3921 } -3922 -3923 Ok::<_, n0_snafu::Error>(()) -3924 } -3925 })); -3926 -3927 println!("first conn!"); -3928 let conn = m1 -3929 .endpoint -3930 .connect(m2.endpoint.node_addr().initialized().await?, ALPN) -3931 .await?; -3932 println!("Closing first conn"); -3933 conn.close(0u32.into(), b"bye lolz"); -3934 conn.closed().await; -3935 println!("Closed first conn"); -3936 -3937 Ok(()) -3938 } -3939 -3940 #[tokio::test(flavor = "multi_thread")] -3941 #[traced_test] -3942 async fn test_two_devices_roundtrip_network_change() -> Result { -3943 time::timeout( -3944 Duration::from_secs(90), -3945 test_two_devices_roundtrip_network_change_impl(), -3946 ) -3947 .await -3948 .context("timeout")? -3949 } -3950 -3951 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly -3952 /// with (simulated) network changes. -3953 async fn test_two_devices_roundtrip_network_change_impl() -> Result { -3954 let m1 = MagicStack::new(RelayMode::Disabled).await; -3955 let m2 = MagicStack::new(RelayMode::Disabled).await; -3956 -3957 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; -3958 -3959 let offset = || { -3960 let delay = rand::thread_rng().gen_range(10..=500); -3961 Duration::from_millis(delay) -3962 }; -3963 let rounds = 5; -3964 -3965 // Regular network changes to m1 only. -3966 let m1_network_change_guard = { -3967 let m1 = m1.clone(); -3968 let task = tokio::spawn(async move { -3969 loop { -3970 println!("[m1] network change"); -3971 m1.endpoint.magic_sock().force_network_change(true).await; -3972 time::sleep(offset()).await; -3973 } -3974 }); -3975 AbortOnDropHandle::new(task) -3976 }; -3977 -3978 for i in 0..rounds { -3979 println!("-- [m1 changes] round {}", i + 1); -3980 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -3981 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -3982 -3983 println!("-- [m1 changes] larger data"); -3984 let mut data = vec![0u8; 10 * 1024]; -3985 rand::thread_rng().fill_bytes(&mut data); -3986 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -3987 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -3988 } -3989 -3990 std::mem::drop(m1_network_change_guard); -3991 -3992 // Regular network changes to m2 only. -3993 let m2_network_change_guard = { -3994 let m2 = m2.clone(); -3995 let task = tokio::spawn(async move { -3996 loop { -3997 println!("[m2] network change"); -3998 m2.endpoint.magic_sock().force_network_change(true).await; -3999 time::sleep(offset()).await; -4000 } -4001 }); -4002 AbortOnDropHandle::new(task) -4003 }; -4004 -4005 for i in 0..rounds { -4006 println!("-- [m2 changes] round {}", i + 1); -4007 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -4008 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -4009 -4010 println!("-- [m2 changes] larger data"); -4011 let mut data = vec![0u8; 10 * 1024]; -4012 rand::thread_rng().fill_bytes(&mut data); -4013 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -4014 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -4015 } -4016 -4017 std::mem::drop(m2_network_change_guard); -4018 -4019 // Regular network changes to both m1 and m2 only. -4020 let m1_m2_network_change_guard = { -4021 let m1 = m1.clone(); -4022 let m2 = m2.clone(); -4023 let task = tokio::spawn(async move { -4024 println!("-- [m1] network change"); -4025 m1.endpoint.magic_sock().force_network_change(true).await; -4026 println!("-- [m2] network change"); -4027 m2.endpoint.magic_sock().force_network_change(true).await; -4028 time::sleep(offset()).await; -4029 }); -4030 AbortOnDropHandle::new(task) -4031 }; -4032 -4033 for i in 0..rounds { -4034 println!("-- [m1 & m2 changes] round {}", i + 1); -4035 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -4036 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -4037 -4038 println!("-- [m1 & m2 changes] larger data"); -4039 let mut data = vec![0u8; 10 * 1024]; -4040 rand::thread_rng().fill_bytes(&mut data); -4041 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -4042 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -4043 } -4044 -4045 std::mem::drop(m1_m2_network_change_guard); -4046 Ok(()) -4047 } -4048 -4049 #[tokio::test(flavor = "multi_thread")] -4050 #[traced_test] -4051 async fn test_two_devices_setup_teardown() -> Result { -4052 for i in 0..10 { -4053 println!("-- round {i}"); -4054 println!("setting up magic stack"); -4055 let m1 = MagicStack::new(RelayMode::Disabled).await; -4056 let m2 = MagicStack::new(RelayMode::Disabled).await; -4057 -4058 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; -4059 -4060 println!("closing endpoints"); -4061 let msock1 = m1.endpoint.magic_sock(); -4062 let msock2 = m2.endpoint.magic_sock(); -4063 m1.endpoint.close().await; -4064 m2.endpoint.close().await; -4065 -4066 assert!(msock1.msock.is_closed()); -4067 assert!(msock2.msock.is_closed()); -4068 } -4069 Ok(()) -4070 } -4071 -4072 #[test] -4073 fn test_split_packets() { -4074 fn mk_transmit(contents: &[u8], segment_size: Option<usize>) -> quinn_udp::Transmit<'_> { -4075 let destination = "127.0.0.1:0".parse().unwrap(); -4076 quinn_udp::Transmit { -4077 destination, -4078 ecn: None, -4079 contents, -4080 segment_size, -4081 src_ip: None, -4082 } -4083 } -4084 fn mk_expected(parts: impl IntoIterator<Item = &'static str>) -> RelayContents { -4085 parts -4086 .into_iter() -4087 .map(|p| p.as_bytes().to_vec().into()) -4088 .collect() -4089 } -4090 // no split -4091 assert_eq!( -4092 split_packets(&mk_transmit(b"hello", None)), -4093 mk_expected(["hello"]) -4094 ); -4095 // split without rest -4096 assert_eq!( -4097 split_packets(&mk_transmit(b"helloworld", Some(5))), -4098 mk_expected(["hello", "world"]) -4099 ); -4100 // split with rest and second transmit -4101 assert_eq!( -4102 split_packets(&mk_transmit(b"hello world", Some(5))), -4103 mk_expected(["hello", " worl", "d"]) // spellchecker:disable-line -4104 ); -4105 // split that results in 1 packet -4106 assert_eq!( -4107 split_packets(&mk_transmit(b"hello world", Some(1000))), -4108 mk_expected(["hello world"]) -4109 ); -4110 } -4111 -4112 #[tokio::test] -4113 #[traced_test] -4114 async fn test_local_endpoints() { -4115 let ms = Handle::new(Default::default()).await.unwrap(); -4116 -4117 // See if we can get endpoints. -4118 let eps0 = ms.direct_addresses().initialized().await.unwrap(); -4119 println!("{eps0:?}"); -4120 assert!(!eps0.is_empty()); -4121 -4122 // Getting the endpoints again immediately should give the same results. -4123 let eps1 = ms.direct_addresses().initialized().await.unwrap(); -4124 println!("{eps1:?}"); -4125 assert_eq!(eps0, eps1); -4126 } -4127 -4128 #[tokio::test] -4129 async fn test_watch_home_relay() { -4130 // use an empty relay map to get full control of the changes during the test -4131 let ops = Options { -4132 relay_map: RelayMap::empty(), -4133 ..Default::default() -4134 }; -4135 let msock = MagicSock::spawn(ops).await.unwrap(); -4136 let mut relay_stream = msock.home_relay().stream().filter_map(|r| r); -4137 -4138 // no relay, nothing to report -4139 assert_eq!( -4140 n0_future::future::poll_once(relay_stream.next()).await, -4141 None -4142 ); -4143 -4144 let url: RelayUrl = format!("https://{}", EU_RELAY_HOSTNAME).parse().unwrap(); -4145 msock.set_my_relay(Some(url.clone())); -4146 -4147 assert_eq!(relay_stream.next().await, Some(url.clone())); -4148 -4149 // drop the stream and query it again, the result should be immediately available -4150 -4151 let mut relay_stream = msock.home_relay().stream().filter_map(|r| r); -4152 assert_eq!( -4153 n0_future::future::poll_once(relay_stream.next()).await, -4154 Some(Some(url)) -4155 ); -4156 } -4157 -4158 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`]. -4159 /// -4160 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept -4161 /// connections using [`ALPN`]. -4162 /// -4163 /// Use [`magicsock_connect`] to establish connections. -4164 #[instrument(name = "ep", skip_all, fields(me = secret_key.public().fmt_short()))] -4165 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> { -4166 let quic_server_config = -4167 tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![ALPN.to_vec()], true); -4168 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); -4169 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); -4170 -4171 let dns_resolver = DnsResolver::new(); -4172 let opts = Options { -4173 addr_v4: None, -4174 addr_v6: None, -4175 secret_key: secret_key.clone(), -4176 relay_map: RelayMap::empty(), -4177 relay_protocol: iroh_relay::http::Protocol::default(), -4178 node_map: None, -4179 discovery: None, -4180 discovery_user_data: None, -4181 dns_resolver, -4182 proxy_url: None, -4183 server_config, -4184 insecure_skip_relay_cert_verify: true, -4185 path_selection: PathSelection::default(), -4186 metrics: Default::default(), -4187 }; -4188 let msock = MagicSock::spawn(opts).await?; -4189 Ok(msock) -4190 } -4191 -4192 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`. -4193 /// -4194 /// Uses [`ALPN`], `node_id`, must match `addr`. -4195 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))] -4196 async fn magicsock_connect( -4197 ep: &quinn::Endpoint, -4198 ep_secret_key: SecretKey, -4199 addr: NodeIdMappedAddr, -4200 node_id: NodeId, -4201 ) -> Result<quinn::Connection> { -4202 // Endpoint::connect sets this, do the same to have similar behaviour. -4203 let mut transport_config = quinn::TransportConfig::default(); -4204 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); -4205 -4206 magicsock_connect_with_transport_config( -4207 ep, -4208 ep_secret_key, -4209 addr, -4210 node_id, -4211 Arc::new(transport_config), -4212 ) -4213 .await -4214 } -4215 -4216 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`. -4217 /// -4218 /// This version allows customising the transport config. -4219 /// -4220 /// Uses [`ALPN`], `node_id`, must match `addr`. -4221 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))] -4222 async fn magicsock_connect_with_transport_config( -4223 ep: &quinn::Endpoint, -4224 ep_secret_key: SecretKey, -4225 mapped_addr: NodeIdMappedAddr, -4226 node_id: NodeId, -4227 transport_config: Arc<quinn::TransportConfig>, -4228 ) -> Result<quinn::Connection> { -4229 let alpns = vec![ALPN.to_vec()]; -4230 let quic_client_config = -4231 tls::TlsConfig::new(ep_secret_key.clone()).make_client_config(alpns, true); -4232 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); -4233 client_config.transport_config(transport_config); -4234 let connect = ep -4235 .connect_with( -4236 client_config, -4237 mapped_addr.private_socket_addr(), -4238 &tls::name::encode(node_id), -4239 ) -4240 .context("connect")?; -4241 let connection = connect.await.e()?; -4242 Ok(connection) -4243 } -4244 -4245 #[tokio::test] -4246 #[traced_test] -4247 async fn test_try_send_no_send_addr() { -4248 // Regression test: if there is no send_addr we should keep being able to use the -4249 // Endpoint. -4250 -4251 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -4252 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -4253 let node_id_2 = secret_key_2.public(); -4254 let secret_key_missing_node = SecretKey::from_bytes(&[255u8; 32]); -4255 let node_id_missing_node = secret_key_missing_node.public(); -4256 -4257 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); -4258 -4259 // Generate an address not present in the NodeMap. -4260 let bad_addr = NodeIdMappedAddr::generate(); -4261 -4262 // 500ms is rather fast here. Running this locally it should always be the correct -4263 // timeout. If this is too slow however the test will not become flaky as we are -4264 // expecting the timeout, we might just get the timeout for the wrong reason. But -4265 // this speeds up the test. -4266 let res = tokio::time::timeout( -4267 Duration::from_millis(500), -4268 magicsock_connect( -4269 msock_1.endpoint(), -4270 secret_key_1.clone(), -4271 bad_addr, -4272 node_id_missing_node, -4273 ), -4274 ) -4275 .await; -4276 assert!(res.is_err(), "expecting timeout"); -4277 -4278 // Now check we can still create another connection with this endpoint. -4279 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); -4280 -4281 // This needs an accept task -4282 let accept_task = tokio::spawn({ -4283 async fn accept(ep: quinn::Endpoint) -> Result<()> { -4284 let incoming = ep.accept().await.context("no incoming")?; -4285 let _conn = incoming -4286 .accept() -4287 .context("accept")? -4288 .await -4289 .context("connecting")?; -4290 -4291 // Keep this connection alive for a while -4292 tokio::time::sleep(Duration::from_secs(10)).await; -4293 info!("accept finished"); -4294 Ok(()) -4295 } -4296 let ep = msock_2.endpoint().clone(); -4297 async move { -4298 if let Err(err) = accept(ep).await { -4299 error!("{err:#}"); -4300 } -4301 } -4302 .instrument(info_span!("ep2.accept, me = node_id_2.fmt_short()")) -4303 }); -4304 let _accept_task = AbortOnDropHandle::new(accept_task); -4305 -4306 let node_addr_2 = NodeAddr { -4307 node_id: node_id_2, -4308 relay_url: None, -4309 direct_addresses: msock_2 -4310 .direct_addresses() -4311 .initialized() -4312 .await -4313 .expect("no direct addrs") -4314 .into_iter() -4315 .map(|x| x.addr) -4316 .collect(), -4317 }; -4318 msock_1 -4319 .add_node_addr( -4320 node_addr_2, -4321 Source::NamedApp { -4322 name: "test".into(), -4323 }, -4324 ) -4325 .unwrap(); -4326 let addr = msock_1.get_mapping_addr(node_id_2).unwrap(); -4327 let res = tokio::time::timeout( -4328 Duration::from_secs(10), -4329 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr, node_id_2), -4330 ) -4331 .await -4332 .expect("timeout while connecting"); -4333 -4334 // aka assert!(res.is_ok()) but with nicer error reporting. -4335 res.unwrap(); -4336 -4337 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that -4338 // much internal state for now. -4339 } -4340 -4341 #[tokio::test] -4342 #[traced_test] -4343 async fn test_try_send_no_udp_addr_or_relay_url() { -4344 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` -4345 // behaviour of MagicSock::try_send. -4346 -4347 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -4348 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -4349 let node_id_2 = secret_key_2.public(); -4350 -4351 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); -4352 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); -4353 let ep_2 = msock_2.endpoint().clone(); -4354 -4355 // We need a task to accept the connection. -4356 let accept_task = tokio::spawn({ -4357 async fn accept(ep: quinn::Endpoint) -> Result<()> { -4358 let incoming = ep.accept().await.context("no incoming")?; -4359 let conn = incoming -4360 .accept() -4361 .context("accept")? -4362 .await -4363 .context("connecting")?; -4364 let mut stream = conn.accept_uni().await.context("accept uni")?; -4365 stream.read_to_end(1 << 16).await.context("read to end")?; -4366 info!("accept finished"); -4367 Ok(()) -4368 } -4369 async move { -4370 if let Err(err) = accept(ep_2).await { -4371 error!("{err:#}"); -4372 } -4373 } -4374 .instrument(info_span!("ep2.accept", me = node_id_2.fmt_short())) -4375 }); -4376 let _accept_task = AbortOnDropHandle::new(accept_task); -4377 -4378 // Add an empty entry in the NodeMap of ep_1 -4379 msock_1.node_map.add_node_addr( -4380 NodeAddr { -4381 node_id: node_id_2, -4382 relay_url: None, -4383 direct_addresses: Default::default(), -4384 }, -4385 Source::NamedApp { -4386 name: "test".into(), -4387 }, -4388 &msock_1.metrics.magicsock, -4389 ); -4390 let addr_2 = msock_1.get_mapping_addr(node_id_2).unwrap(); -4391 -4392 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does -4393 // not take forever. You need to check the log output to verify this is really -4394 // triggering the correct error. -4395 // In test_try_send_no_send_addr() above you may have noticed we used -4396 // tokio::time::timeout() on the connection attempt instead. Here however we want -4397 // Quinn itself to have fully given up on the connection attempt because we will -4398 // later connect to **the same** node. If Quinn did not give up on the connection -4399 // we'd close it on drop, and the retransmits of the close packets would interfere -4400 // with the next handshake, closing it during the handshake. This makes the test a -4401 // little slower though. -4402 let mut transport_config = quinn::TransportConfig::default(); -4403 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); -4404 let res = magicsock_connect_with_transport_config( -4405 msock_1.endpoint(), -4406 secret_key_1.clone(), -4407 addr_2, -4408 node_id_2, -4409 Arc::new(transport_config), -4410 ) -4411 .await; -4412 assert!(res.is_err(), "expected timeout"); -4413 info!("first connect timed out as expected"); -4414 -4415 // Provide correct addressing information -4416 msock_1.node_map.add_node_addr( -4417 NodeAddr { -4418 node_id: node_id_2, -4419 relay_url: None, -4420 direct_addresses: msock_2 -4421 .direct_addresses() -4422 .initialized() -4423 .await -4424 .expect("no direct addrs") -4425 .into_iter() -4426 .map(|x| x.addr) -4427 .collect(), -4428 }, -4429 Source::NamedApp { -4430 name: "test".into(), -4431 }, -4432 &msock_1.metrics.magicsock, -4433 ); -4434 -4435 // We can now connect -4436 tokio::time::timeout(Duration::from_secs(10), async move { -4437 info!("establishing new connection"); -4438 let conn = -4439 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr_2, node_id_2) -4440 .await -4441 .unwrap(); -4442 info!("have connection"); -4443 let mut stream = conn.open_uni().await.unwrap(); -4444 stream.write_all(b"hello").await.unwrap(); -4445 stream.finish().unwrap(); -4446 stream.stopped().await.unwrap(); -4447 info!("finished stream"); -4448 }) -4449 .await -4450 .expect("connection timed out"); -4451 -4452 // TODO: could remove the addresses again, send, add it back and see it recover. -4453 // But we don't have that much private access to the NodeMap. This will do for now. -4454 } -4455 -4456 #[tokio::test(flavor = "multi_thread")] -4457 async fn test_relay_datagram_queue() { -4458 let queue = Arc::new(RelayDatagramRecvQueue::new()); -4459 let url = staging::default_na_relay_node().url; -4460 let capacity = queue.queue.capacity().unwrap(); -4461 -4462 let mut tasks = JoinSet::new(); -4463 -4464 tasks.spawn({ -4465 let queue = queue.clone(); -4466 async move { -4467 let mut expected_msgs: BTreeSet<usize> = (0..capacity).collect(); -4468 while !expected_msgs.is_empty() { -4469 let datagram = n0_future::future::poll_fn(|cx| { -4470 queue.poll_recv(cx).map(|result| result.unwrap()) -4471 }) -4472 .await; -4473 -4474 let msg_num = usize::from_le_bytes(datagram.buf.as_ref().try_into().unwrap()); -4475 debug!("Received {msg_num}"); -4476 -4477 if !expected_msgs.remove(&msg_num) { -4478 panic!("Received message number {msg_num} twice or more, but expected it only exactly once."); -4479 } -4480 } -4481 } -4482 }); -4483 -4484 for i in 0..capacity { -4485 tasks.spawn({ -4486 let queue = queue.clone(); -4487 let url = url.clone(); -4488 async move { -4489 debug!("Sending {i}"); -4490 queue -4491 .try_send(RelayRecvDatagram { -4492 url, -4493 src: PublicKey::from_bytes(&[0u8; 32]).unwrap(), -4494 buf: Bytes::copy_from_slice(&i.to_le_bytes()), -4495 }) -4496 .unwrap(); -4497 } -4498 }); -4499 } -4500 -4501 // We expect all of this work to be done in 10 seconds max. -4502 if tokio::time::timeout(Duration::from_secs(10), tasks.join_all()) -4503 .await -4504 .is_err() -4505 { -4506 panic!("Timeout - not all messages between 0 and {capacity} received."); -4507 } -4508 } -4509 -4510 #[tokio::test] -4511 async fn test_add_node_addr() -> Result { -4512 let stack = MagicStack::new(RelayMode::Default).await; -4513 let mut rng = rand::thread_rng(); -4514 -4515 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 0); -4516 -4517 // Empty -4518 let empty_addr = NodeAddr { -4519 node_id: SecretKey::generate(&mut rng).public(), -4520 relay_url: None, -4521 direct_addresses: Default::default(), -4522 }; -4523 let err = stack -4524 .endpoint -4525 .magic_sock() -4526 .add_node_addr(empty_addr, node_map::Source::App) -4527 .unwrap_err(); -4528 assert!(err -4529 .to_string() -4530 .to_lowercase() -4531 .contains("empty addressing info")); -4532 -4533 // relay url only -4534 let addr = NodeAddr { -4535 node_id: SecretKey::generate(&mut rng).public(), -4536 relay_url: Some("http://my-relay.com".parse().unwrap()), -4537 direct_addresses: Default::default(), -4538 }; -4539 stack -4540 .endpoint -4541 .magic_sock() -4542 .add_node_addr(addr, node_map::Source::App)?; -4543 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 1); -4544 -4545 // addrs only -4546 let addr = NodeAddr { -4547 node_id: SecretKey::generate(&mut rng).public(), -4548 relay_url: None, -4549 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(), -4550 }; -4551 stack -4552 .endpoint -4553 .magic_sock() -4554 .add_node_addr(addr, node_map::Source::App)?; -4555 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 2); -4556 -4557 // both -4558 let addr = NodeAddr { -4559 node_id: SecretKey::generate(&mut rng).public(), -4560 relay_url: Some("http://my-relay.com".parse().unwrap()), -4561 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(), -4562 }; -4563 stack -4564 .endpoint -4565 .magic_sock() -4566 .add_node_addr(addr, node_map::Source::App)?; -4567 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 3); -4568 -4569 Ok(()) -4570 } -4571} \ No newline at end of file +3515 // We can now connect +3516 tokio::time::timeout(Duration::from_secs(10), async move { +3517 info!("establishing new connection"); +3518 let conn = +3519 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr_2, node_id_2) +3520 .await +3521 .unwrap(); +3522 info!("have connection"); +3523 let mut stream = conn.open_uni().await.unwrap(); +3524 stream.write_all(b"hello").await.unwrap(); +3525 stream.finish().unwrap(); +3526 stream.stopped().await.unwrap(); +3527 info!("finished stream"); +3528 }) +3529 .await +3530 .expect("connection timed out"); +3531 +3532 // TODO: could remove the addresses again, send, add it back and see it recover. +3533 // But we don't have that much private access to the NodeMap. This will do for now. +3534 } +3535 +3536 #[tokio::test] +3537 async fn test_add_node_addr() -> Result { +3538 let stack = MagicStack::new(RelayMode::Default).await; +3539 let mut rng = rand::thread_rng(); +3540 +3541 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 0); +3542 +3543 // Empty +3544 let empty_addr = NodeAddr { +3545 node_id: SecretKey::generate(&mut rng).public(), +3546 relay_url: None, +3547 direct_addresses: Default::default(), +3548 }; +3549 let err = stack +3550 .endpoint +3551 .magic_sock() +3552 .add_node_addr(empty_addr, node_map::Source::App) +3553 .unwrap_err(); +3554 assert!(err +3555 .to_string() +3556 .to_lowercase() +3557 .contains("empty addressing info")); +3558 +3559 // relay url only +3560 let addr = NodeAddr { +3561 node_id: SecretKey::generate(&mut rng).public(), +3562 relay_url: Some("http://my-relay.com".parse().unwrap()), +3563 direct_addresses: Default::default(), +3564 }; +3565 stack +3566 .endpoint +3567 .magic_sock() +3568 .add_node_addr(addr, node_map::Source::App)?; +3569 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 1); +3570 +3571 // addrs only +3572 let addr = NodeAddr { +3573 node_id: SecretKey::generate(&mut rng).public(), +3574 relay_url: None, +3575 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(), +3576 }; +3577 stack +3578 .endpoint +3579 .magic_sock() +3580 .add_node_addr(addr, node_map::Source::App)?; +3581 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 2); +3582 +3583 // both +3584 let addr = NodeAddr { +3585 node_id: SecretKey::generate(&mut rng).public(), +3586 relay_url: Some("http://my-relay.com".parse().unwrap()), +3587 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(), +3588 }; +3589 stack +3590 .endpoint +3591 .magic_sock() +3592 .add_node_addr(addr, node_map::Source::App)?; +3593 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 3); +3594 +3595 Ok(()) +3596 } +3597} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/magicsock/node_map.rs.html b/pr/3327/docs/src/iroh/magicsock/node_map.rs.html index fe12509f96..d20992afbf 100644 --- a/pr/3327/docs/src/iroh/magicsock/node_map.rs.html +++ b/pr/3327/docs/src/iroh/magicsock/node_map.rs.html @@ -15,887 +15,884 @@ 15 best_addr::ClearReason, 16 node_state::{NodeState, Options, PingHandled}, 17}; -18use super::{metrics::Metrics, ActorMessage, DiscoMessageSource, NodeIdMappedAddr}; -19#[cfg(any(test, feature = "test-utils"))] -20use crate::endpoint::PathSelection; -21use crate::{ -22 disco::{CallMeMaybe, Pong, SendAddr}, -23 watcher, -24}; -25 -26mod best_addr; -27mod node_state; -28mod path_state; -29mod udp_paths; +18use super::{metrics::Metrics, transports, ActorMessage, NodeIdMappedAddr}; +19use crate::disco::{CallMeMaybe, Pong, SendAddr}; +20#[cfg(any(test, feature = "test-utils"))] +21use crate::endpoint::PathSelection; +22 +23mod best_addr; +24mod node_state; +25mod path_state; +26mod udp_paths; +27 +28pub use node_state::{ConnectionType, ControlMsg, DirectAddrInfo, RemoteInfo}; +29pub(super) use node_state::{DiscoPingPurpose, PingAction, PingRole, SendPing}; 30 -31pub use node_state::{ConnectionType, ControlMsg, DirectAddrInfo, RemoteInfo}; -32pub(super) use node_state::{DiscoPingPurpose, PingAction, PingRole, SendPing}; -33 -34/// Number of nodes that are inactive for which we keep info about. This limit is enforced -35/// periodically via [`NodeMap::prune_inactive`]. -36const MAX_INACTIVE_NODES: usize = 30; -37 -38/// Map of the [`NodeState`] information for all the known nodes. -39/// -40/// The nodes can be looked up by: +31/// Number of nodes that are inactive for which we keep info about. This limit is enforced +32/// periodically via [`NodeMap::prune_inactive`]. +33const MAX_INACTIVE_NODES: usize = 30; +34 +35/// Map of the [`NodeState`] information for all the known nodes. +36/// +37/// The nodes can be looked up by: +38/// +39/// - The node's ID in this map, only useful if you know the ID from an insert or lookup. +40/// This is static and never changes. 41/// -42/// - The node's ID in this map, only useful if you know the ID from an insert or lookup. -43/// This is static and never changes. +42/// - The [`NodeIdMappedAddr`] which internally identifies the node to the QUIC stack. This +43/// is static and never changes. 44/// -45/// - The [`NodeIdMappedAddr`] which internally identifies the node to the QUIC stack. This -46/// is static and never changes. +45/// - The nodes's public key, aka `PublicKey` or "node_key". This is static and never changes, +46/// however a node could be added when this is not yet known. 47/// -48/// - The nodes's public key, aka `PublicKey` or "node_key". This is static and never changes, -49/// however a node could be added when this is not yet known. +48/// - A public socket address on which they are reachable on the internet, known as ip-port. +49/// These come and go as the node moves around on the internet 50/// -51/// - A public socket address on which they are reachable on the internet, known as ip-port. -52/// These come and go as the node moves around on the internet -53/// -54/// An index of nodeInfos by node key, NodeIdMappedAddr, and discovered ip:port endpoints. -55#[derive(Debug, Default)] -56pub(super) struct NodeMap { -57 inner: Mutex<NodeMapInner>, -58} -59 -60#[derive(Default, Debug)] -61pub(super) struct NodeMapInner { -62 by_node_key: HashMap<NodeId, usize>, -63 by_ip_port: HashMap<IpPort, usize>, -64 by_quic_mapped_addr: HashMap<NodeIdMappedAddr, usize>, -65 by_id: HashMap<usize, NodeState>, -66 next_id: usize, -67 #[cfg(any(test, feature = "test-utils"))] -68 path_selection: PathSelection, -69} -70 -71/// Identifier to look up a [`NodeState`] in the [`NodeMap`]. -72/// -73/// You can look up entries in [`NodeMap`] with various keys, depending on the context you -74/// have for the node. These are all the keys the [`NodeMap`] can use. -75#[derive(Debug, Clone)] -76enum NodeStateKey { -77 Idx(usize), -78 NodeId(NodeId), -79 NodeIdMappedAddr(NodeIdMappedAddr), -80 IpPort(IpPort), -81} -82 -83/// The origin or *source* through which an address associated with a remote node -84/// was discovered. +51/// An index of nodeInfos by node key, NodeIdMappedAddr, and discovered ip:port endpoints. +52#[derive(Debug, Default)] +53pub(super) struct NodeMap { +54 inner: Mutex<NodeMapInner>, +55} +56 +57#[derive(Default, Debug)] +58pub(super) struct NodeMapInner { +59 by_node_key: HashMap<NodeId, usize>, +60 by_ip_port: HashMap<IpPort, usize>, +61 by_quic_mapped_addr: HashMap<NodeIdMappedAddr, usize>, +62 by_id: HashMap<usize, NodeState>, +63 next_id: usize, +64 #[cfg(any(test, feature = "test-utils"))] +65 path_selection: PathSelection, +66} +67 +68/// Identifier to look up a [`NodeState`] in the [`NodeMap`]. +69/// +70/// You can look up entries in [`NodeMap`] with various keys, depending on the context you +71/// have for the node. These are all the keys the [`NodeMap`] can use. +72#[derive(Debug, Clone)] +73enum NodeStateKey { +74 Idx(usize), +75 NodeId(NodeId), +76 NodeIdMappedAddr(NodeIdMappedAddr), +77 IpPort(IpPort), +78} +79 +80/// The origin or *source* through which an address associated with a remote node +81/// was discovered. +82/// +83/// An aggregate of the [`Source`]s of all the addresses of a node describe the +84/// [`Source`]s of the node itself. 85/// -86/// An aggregate of the [`Source`]s of all the addresses of a node describe the -87/// [`Source`]s of the node itself. -88/// -89/// A [`Source`] helps track how and where an address was learned. Multiple -90/// sources can be associated with a single address, if we have discovered this -91/// address through multiple means. -92/// -93/// Each time a [`NodeAddr`] is added to the node map, usually through -94/// [`crate::endpoint::Endpoint::add_node_addr_with_source`], a [`Source`] must be supplied to indicate -95/// how the address was obtained. -96/// -97/// A [`Source`] can describe a variety of places that an address or node was -98/// discovered, such as a configured discovery service, the network itself -99/// (if another node has reached out to us), or as a user supplied [`NodeAddr`]. -100 -101#[derive(Serialize, Deserialize, strum::Display, Debug, Clone, Eq, PartialEq, Hash)] -102#[strum(serialize_all = "kebab-case")] -103pub enum Source { -104 /// Address was loaded from the fs. -105 Saved, -106 /// A node communicated with us first via UDP. -107 Udp, -108 /// A node communicated with us first via relay. -109 Relay, -110 /// Application layer added the address directly. -111 App, -112 /// The address was discovered by a discovery service. -113 #[strum(serialize = "{name}")] -114 Discovery { -115 /// The name of the discovery service that discovered the address. -116 name: String, -117 }, -118 /// Application layer with a specific name added the node directly. -119 #[strum(serialize = "{name}")] -120 NamedApp { -121 /// The name of the application that added the node -122 name: String, -123 }, -124} -125 -126impl NodeMap { -127 #[cfg(not(any(test, feature = "test-utils")))] -128 /// Create a new [`NodeMap`] from a list of [`NodeAddr`]s. -129 pub(super) fn load_from_vec(nodes: Vec<NodeAddr>, metrics: &Metrics) -> Self { -130 Self::from_inner(NodeMapInner::load_from_vec(nodes, metrics)) -131 } -132 -133 #[cfg(any(test, feature = "test-utils"))] -134 /// Create a new [`NodeMap`] from a list of [`NodeAddr`]s. -135 pub(super) fn load_from_vec( -136 nodes: Vec<NodeAddr>, -137 path_selection: PathSelection, -138 metrics: &Metrics, -139 ) -> Self { -140 Self::from_inner(NodeMapInner::load_from_vec(nodes, path_selection, metrics)) -141 } -142 -143 fn from_inner(inner: NodeMapInner) -> Self { -144 Self { -145 inner: Mutex::new(inner), -146 } -147 } -148 -149 /// Add the contact information for a node. -150 pub(super) fn add_node_addr(&self, node_addr: NodeAddr, source: Source, metrics: &Metrics) { -151 self.inner -152 .lock() -153 .expect("poisoned") -154 .add_node_addr(node_addr, source, metrics) -155 } -156 -157 /// Number of nodes currently listed. -158 pub(super) fn node_count(&self) -> usize { -159 self.inner.lock().expect("poisoned").node_count() -160 } -161 -162 #[cfg(not(wasm_browser))] -163 pub(super) fn receive_udp( -164 &self, -165 udp_addr: SocketAddr, -166 ) -> Option<(PublicKey, NodeIdMappedAddr)> { -167 self.inner.lock().expect("poisoned").receive_udp(udp_addr) -168 } -169 -170 pub(super) fn receive_relay(&self, relay_url: &RelayUrl, src: NodeId) -> NodeIdMappedAddr { -171 self.inner -172 .lock() -173 .expect("poisoned") -174 .receive_relay(relay_url, src) -175 } -176 -177 pub(super) fn notify_ping_sent( -178 &self, -179 id: usize, -180 dst: SendAddr, -181 tx_id: stun_rs::TransactionId, -182 purpose: DiscoPingPurpose, -183 msg_sender: tokio::sync::mpsc::Sender<ActorMessage>, -184 ) { -185 if let Some(ep) = self -186 .inner -187 .lock() -188 .expect("poisoned") -189 .get_mut(NodeStateKey::Idx(id)) -190 { -191 ep.ping_sent(dst, tx_id, purpose, msg_sender); -192 } -193 } -194 -195 pub(super) fn notify_ping_timeout(&self, id: usize, tx_id: stun_rs::TransactionId) { -196 if let Some(ep) = self -197 .inner -198 .lock() -199 .expect("poisoned") -200 .get_mut(NodeStateKey::Idx(id)) -201 { -202 ep.ping_timeout(tx_id); -203 } -204 } -205 -206 pub(super) fn get_quic_mapped_addr_for_node_key( -207 &self, -208 node_key: NodeId, -209 ) -> Option<NodeIdMappedAddr> { -210 self.inner -211 .lock() -212 .expect("poisoned") -213 .get(NodeStateKey::NodeId(node_key)) -214 .map(|ep| *ep.quic_mapped_addr()) -215 } -216 -217 /// Insert a received ping into the node map, and return whether a ping with this tx_id was already -218 /// received. -219 pub(super) fn handle_ping( -220 &self, -221 sender: PublicKey, -222 src: SendAddr, -223 tx_id: TransactionId, -224 ) -> PingHandled { -225 self.inner -226 .lock() -227 .expect("poisoned") -228 .handle_ping(sender, src, tx_id) -229 } -230 -231 pub(super) fn handle_pong(&self, sender: PublicKey, src: &DiscoMessageSource, pong: Pong) { -232 self.inner -233 .lock() -234 .expect("poisoned") -235 .handle_pong(sender, src, pong) -236 } -237 -238 #[must_use = "actions must be handled"] -239 pub(super) fn handle_call_me_maybe( -240 &self, -241 sender: PublicKey, -242 cm: CallMeMaybe, -243 metrics: &Metrics, -244 ) -> Vec<PingAction> { -245 self.inner -246 .lock() -247 .expect("poisoned") -248 .handle_call_me_maybe(sender, cm, metrics) -249 } -250 -251 #[allow(clippy::type_complexity)] -252 pub(super) fn get_send_addrs( -253 &self, -254 addr: NodeIdMappedAddr, -255 have_ipv6: bool, -256 metrics: &Metrics, -257 ) -> Option<( -258 PublicKey, -259 Option<SocketAddr>, -260 Option<RelayUrl>, -261 Vec<PingAction>, -262 )> { -263 let mut inner = self.inner.lock().expect("poisoned"); -264 let ep = inner.get_mut(NodeStateKey::NodeIdMappedAddr(addr))?; -265 let public_key = *ep.public_key(); -266 trace!(dest = %addr, node_id = %public_key.fmt_short(), "dst mapped to NodeId"); -267 let (udp_addr, relay_url, msgs) = ep.get_send_addrs(have_ipv6, metrics); -268 Some((public_key, udp_addr, relay_url, msgs)) -269 } -270 -271 pub(super) fn notify_shutdown(&self) { -272 let mut inner = self.inner.lock().expect("poisoned"); -273 for (_, ep) in inner.node_states_mut() { -274 ep.reset(); -275 } -276 } -277 -278 pub(super) fn reset_node_states(&self) { -279 let mut inner = self.inner.lock().expect("poisoned"); -280 for (_, ep) in inner.node_states_mut() { -281 ep.note_connectivity_change(); -282 } -283 } -284 -285 pub(super) fn nodes_stayin_alive(&self) -> Vec<PingAction> { -286 let mut inner = self.inner.lock().expect("poisoned"); -287 inner -288 .node_states_mut() -289 .flat_map(|(_idx, node_state)| node_state.stayin_alive()) -290 .collect() -291 } -292 -293 /// Returns the [`RemoteInfo`]s for each node in the node map. -294 pub(super) fn list_remote_infos(&self, now: Instant) -> Vec<RemoteInfo> { -295 // NOTE: calls to this method will often call `into_iter` (or similar methods). Note that -296 // we can't avoid `collect` here since it would hold a lock for an indefinite time. Even if -297 // we were to find this acceptable, dealing with the lifetimes of the mutex's guard and the -298 // internal iterator will be a hassle, if possible at all. -299 self.inner -300 .lock() -301 .expect("poisoned") -302 .remote_infos_iter(now) -303 .collect() -304 } -305 -306 /// Returns a [`watcher::Direct`] for given node's [`ConnectionType`]. -307 /// -308 /// # Errors -309 /// -310 /// Will return `None` if there is not an entry in the [`NodeMap`] for -311 /// the `node_id` -312 pub(super) fn conn_type(&self, node_id: NodeId) -> Option<watcher::Direct<ConnectionType>> { -313 self.inner.lock().expect("poisoned").conn_type(node_id) -314 } -315 -316 /// Get the [`RemoteInfo`]s for the node identified by [`NodeId`]. -317 pub(super) fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo> { -318 self.inner.lock().expect("poisoned").remote_info(node_id) -319 } -320 -321 /// Prunes nodes without recent activity so that at most [`MAX_INACTIVE_NODES`] are kept. -322 pub(super) fn prune_inactive(&self) { -323 self.inner.lock().expect("poisoned").prune_inactive(); -324 } -325 -326 pub(crate) fn on_direct_addr_discovered(&self, discovered: BTreeSet<SocketAddr>) { -327 self.inner -328 .lock() -329 .expect("poisoned") -330 .on_direct_addr_discovered(discovered); -331 } -332} -333 -334impl NodeMapInner { -335 #[cfg(not(any(test, feature = "test-utils")))] -336 /// Create a new [`NodeMap`] from a list of [`NodeAddr`]s. -337 fn load_from_vec(nodes: Vec<NodeAddr>, metrics: &Metrics) -> Self { -338 let mut me = Self::default(); -339 for node_addr in nodes { -340 me.add_node_addr(node_addr, Source::Saved, metrics); -341 } -342 me -343 } -344 -345 #[cfg(any(test, feature = "test-utils"))] -346 /// Create a new [`NodeMap`] from a list of [`NodeAddr`]s. -347 fn load_from_vec( -348 nodes: Vec<NodeAddr>, -349 path_selection: PathSelection, -350 metrics: &Metrics, -351 ) -> Self { -352 let mut me = Self { -353 path_selection, -354 ..Default::default() -355 }; -356 for node_addr in nodes { -357 me.add_node_addr(node_addr, Source::Saved, metrics); -358 } -359 me -360 } -361 -362 /// Add the contact information for a node. -363 #[instrument(skip_all, fields(node = %node_addr.node_id.fmt_short()))] -364 fn add_node_addr(&mut self, node_addr: NodeAddr, source: Source, metrics: &Metrics) { -365 let source0 = source.clone(); -366 let node_id = node_addr.node_id; -367 let relay_url = node_addr.relay_url.clone(); -368 #[cfg(any(test, feature = "test-utils"))] -369 let path_selection = self.path_selection; -370 let node_state = self.get_or_insert_with(NodeStateKey::NodeId(node_id), || Options { -371 node_id, -372 relay_url, -373 active: false, -374 source, -375 #[cfg(any(test, feature = "test-utils"))] -376 path_selection, -377 }); -378 node_state.update_from_node_addr( -379 node_addr.relay_url.as_ref(), -380 &node_addr.direct_addresses, -381 source0, -382 metrics, -383 ); -384 let id = node_state.id(); -385 for addr in node_addr.direct_addresses() { -386 self.set_node_state_for_ip_port(*addr, id); -387 } -388 } -389 -390 /// Prunes direct addresses from nodes that claim to share an address we know points to us. -391 pub(super) fn on_direct_addr_discovered(&mut self, discovered: BTreeSet<SocketAddr>) { -392 for addr in discovered { -393 self.remove_by_ipp(addr.into(), ClearReason::MatchesOurLocalAddr) -394 } -395 } -396 -397 /// Removes a direct address from a node. -398 fn remove_by_ipp(&mut self, ipp: IpPort, reason: ClearReason) { -399 if let Some(id) = self.by_ip_port.remove(&ipp) { -400 if let Entry::Occupied(mut entry) = self.by_id.entry(id) { -401 let node = entry.get_mut(); -402 node.remove_direct_addr(&ipp, reason); -403 if node.direct_addresses().count() == 0 { -404 let node_id = node.public_key(); -405 let mapped_addr = node.quic_mapped_addr(); -406 self.by_node_key.remove(node_id); -407 self.by_quic_mapped_addr.remove(mapped_addr); -408 debug!(node_id=%node_id.fmt_short(), ?reason, "removing node"); -409 entry.remove(); -410 } -411 } -412 } -413 } -414 -415 fn get_id(&self, id: NodeStateKey) -> Option<usize> { -416 match id { -417 NodeStateKey::Idx(id) => Some(id), -418 NodeStateKey::NodeId(node_key) => self.by_node_key.get(&node_key).copied(), -419 NodeStateKey::NodeIdMappedAddr(addr) => self.by_quic_mapped_addr.get(&addr).copied(), -420 NodeStateKey::IpPort(ipp) => self.by_ip_port.get(&ipp).copied(), -421 } -422 } -423 -424 fn get_mut(&mut self, id: NodeStateKey) -> Option<&mut NodeState> { -425 self.get_id(id).and_then(|id| self.by_id.get_mut(&id)) -426 } -427 -428 fn get(&self, id: NodeStateKey) -> Option<&NodeState> { -429 self.get_id(id).and_then(|id| self.by_id.get(&id)) -430 } -431 -432 fn get_or_insert_with( -433 &mut self, -434 id: NodeStateKey, -435 f: impl FnOnce() -> Options, -436 ) -> &mut NodeState { -437 let id = self.get_id(id); -438 match id { -439 None => self.insert_node(f()), -440 Some(id) => self.by_id.get_mut(&id).expect("is not empty"), -441 } -442 } -443 -444 /// Number of nodes currently listed. -445 fn node_count(&self) -> usize { -446 self.by_id.len() -447 } -448 -449 /// Marks the node we believe to be at `ipp` as recently used. -450 #[cfg(not(wasm_browser))] -451 fn receive_udp(&mut self, udp_addr: SocketAddr) -> Option<(NodeId, NodeIdMappedAddr)> { -452 let ip_port: IpPort = udp_addr.into(); -453 let Some(node_state) = self.get_mut(NodeStateKey::IpPort(ip_port)) else { -454 trace!(src=%udp_addr, "receive_udp: no node_state found for addr, ignore"); -455 return None; -456 }; -457 node_state.receive_udp(ip_port, Instant::now()); -458 Some((*node_state.public_key(), *node_state.quic_mapped_addr())) -459 } -460 -461 #[instrument(skip_all, fields(src = %src.fmt_short()))] -462 fn receive_relay(&mut self, relay_url: &RelayUrl, src: NodeId) -> NodeIdMappedAddr { -463 #[cfg(any(test, feature = "test-utils"))] -464 let path_selection = self.path_selection; -465 let node_state = self.get_or_insert_with(NodeStateKey::NodeId(src), || { -466 trace!("packets from unknown node, insert into node map"); -467 Options { -468 node_id: src, -469 relay_url: Some(relay_url.clone()), -470 active: true, -471 source: Source::Relay, -472 #[cfg(any(test, feature = "test-utils"))] -473 path_selection, -474 } -475 }); -476 node_state.receive_relay(relay_url, src, Instant::now()); -477 *node_state.quic_mapped_addr() -478 } -479 -480 fn node_states(&self) -> impl Iterator<Item = (&usize, &NodeState)> { -481 self.by_id.iter() -482 } -483 -484 fn node_states_mut(&mut self) -> impl Iterator<Item = (&usize, &mut NodeState)> { -485 self.by_id.iter_mut() -486 } -487 -488 /// Get the [`RemoteInfo`]s for all nodes. -489 fn remote_infos_iter(&self, now: Instant) -> impl Iterator<Item = RemoteInfo> + '_ { -490 self.node_states().map(move |(_, ep)| ep.info(now)) -491 } -492 -493 /// Get the [`RemoteInfo`]s for each node. -494 fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo> { -495 self.get(NodeStateKey::NodeId(node_id)) -496 .map(|ep| ep.info(Instant::now())) -497 } -498 -499 /// Returns a stream of [`ConnectionType`]. +86/// A [`Source`] helps track how and where an address was learned. Multiple +87/// sources can be associated with a single address, if we have discovered this +88/// address through multiple means. +89/// +90/// Each time a [`NodeAddr`] is added to the node map, usually through +91/// [`crate::endpoint::Endpoint::add_node_addr_with_source`], a [`Source`] must be supplied to indicate +92/// how the address was obtained. +93/// +94/// A [`Source`] can describe a variety of places that an address or node was +95/// discovered, such as a configured discovery service, the network itself +96/// (if another node has reached out to us), or as a user supplied [`NodeAddr`]. +97 +98#[derive(Serialize, Deserialize, strum::Display, Debug, Clone, Eq, PartialEq, Hash)] +99#[strum(serialize_all = "kebab-case")] +100pub enum Source { +101 /// Address was loaded from the fs. +102 Saved, +103 /// A node communicated with us first via UDP. +104 Udp, +105 /// A node communicated with us first via relay. +106 Relay, +107 /// Application layer added the address directly. +108 App, +109 /// The address was discovered by a discovery service. +110 #[strum(serialize = "{name}")] +111 Discovery { +112 /// The name of the discovery service that discovered the address. +113 name: String, +114 }, +115 /// Application layer with a specific name added the node directly. +116 #[strum(serialize = "{name}")] +117 NamedApp { +118 /// The name of the application that added the node +119 name: String, +120 }, +121} +122 +123impl NodeMap { +124 #[cfg(not(any(test, feature = "test-utils")))] +125 /// Create a new [`NodeMap`] from a list of [`NodeAddr`]s. +126 pub(super) fn load_from_vec(nodes: Vec<NodeAddr>, metrics: &Metrics) -> Self { +127 Self::from_inner(NodeMapInner::load_from_vec(nodes, metrics)) +128 } +129 +130 #[cfg(any(test, feature = "test-utils"))] +131 /// Create a new [`NodeMap`] from a list of [`NodeAddr`]s. +132 pub(super) fn load_from_vec( +133 nodes: Vec<NodeAddr>, +134 path_selection: PathSelection, +135 metrics: &Metrics, +136 ) -> Self { +137 Self::from_inner(NodeMapInner::load_from_vec(nodes, path_selection, metrics)) +138 } +139 +140 fn from_inner(inner: NodeMapInner) -> Self { +141 Self { +142 inner: Mutex::new(inner), +143 } +144 } +145 +146 /// Add the contact information for a node. +147 pub(super) fn add_node_addr(&self, node_addr: NodeAddr, source: Source, metrics: &Metrics) { +148 self.inner +149 .lock() +150 .expect("poisoned") +151 .add_node_addr(node_addr, source, metrics) +152 } +153 +154 /// Number of nodes currently listed. +155 pub(super) fn node_count(&self) -> usize { +156 self.inner.lock().expect("poisoned").node_count() +157 } +158 +159 #[cfg(not(wasm_browser))] +160 pub(super) fn receive_udp( +161 &self, +162 udp_addr: SocketAddr, +163 ) -> Option<(PublicKey, NodeIdMappedAddr)> { +164 self.inner.lock().expect("poisoned").receive_udp(udp_addr) +165 } +166 +167 pub(super) fn receive_relay(&self, relay_url: &RelayUrl, src: NodeId) -> NodeIdMappedAddr { +168 self.inner +169 .lock() +170 .expect("poisoned") +171 .receive_relay(relay_url, src) +172 } +173 +174 pub(super) fn notify_ping_sent( +175 &self, +176 id: usize, +177 dst: SendAddr, +178 tx_id: stun_rs::TransactionId, +179 purpose: DiscoPingPurpose, +180 msg_sender: tokio::sync::mpsc::Sender<ActorMessage>, +181 ) { +182 if let Some(ep) = self +183 .inner +184 .lock() +185 .expect("poisoned") +186 .get_mut(NodeStateKey::Idx(id)) +187 { +188 ep.ping_sent(dst, tx_id, purpose, msg_sender); +189 } +190 } +191 +192 pub(super) fn notify_ping_timeout(&self, id: usize, tx_id: stun_rs::TransactionId) { +193 if let Some(ep) = self +194 .inner +195 .lock() +196 .expect("poisoned") +197 .get_mut(NodeStateKey::Idx(id)) +198 { +199 ep.ping_timeout(tx_id); +200 } +201 } +202 +203 pub(super) fn get_quic_mapped_addr_for_node_key( +204 &self, +205 node_key: NodeId, +206 ) -> Option<NodeIdMappedAddr> { +207 self.inner +208 .lock() +209 .expect("poisoned") +210 .get(NodeStateKey::NodeId(node_key)) +211 .map(|ep| *ep.quic_mapped_addr()) +212 } +213 +214 /// Insert a received ping into the node map, and return whether a ping with this tx_id was already +215 /// received. +216 pub(super) fn handle_ping( +217 &self, +218 sender: PublicKey, +219 src: SendAddr, +220 tx_id: TransactionId, +221 ) -> PingHandled { +222 self.inner +223 .lock() +224 .expect("poisoned") +225 .handle_ping(sender, src, tx_id) +226 } +227 +228 pub(super) fn handle_pong(&self, sender: PublicKey, src: &transports::Addr, pong: Pong) { +229 self.inner +230 .lock() +231 .expect("poisoned") +232 .handle_pong(sender, src, pong) +233 } +234 +235 #[must_use = "actions must be handled"] +236 pub(super) fn handle_call_me_maybe( +237 &self, +238 sender: PublicKey, +239 cm: CallMeMaybe, +240 metrics: &Metrics, +241 ) -> Vec<PingAction> { +242 self.inner +243 .lock() +244 .expect("poisoned") +245 .handle_call_me_maybe(sender, cm, metrics) +246 } +247 +248 #[allow(clippy::type_complexity)] +249 pub(super) fn get_send_addrs( +250 &self, +251 addr: NodeIdMappedAddr, +252 have_ipv6: bool, +253 metrics: &Metrics, +254 ) -> Option<( +255 PublicKey, +256 Option<SocketAddr>, +257 Option<RelayUrl>, +258 Vec<PingAction>, +259 )> { +260 let mut inner = self.inner.lock().expect("poisoned"); +261 let ep = inner.get_mut(NodeStateKey::NodeIdMappedAddr(addr))?; +262 let public_key = *ep.public_key(); +263 trace!(dest = %addr, node_id = %public_key.fmt_short(), "dst mapped to NodeId"); +264 let (udp_addr, relay_url, ping_actions) = ep.get_send_addrs(have_ipv6, metrics); +265 Some((public_key, udp_addr, relay_url, ping_actions)) +266 } +267 +268 pub(super) fn notify_shutdown(&self) { +269 let mut inner = self.inner.lock().expect("poisoned"); +270 for (_, ep) in inner.node_states_mut() { +271 ep.reset(); +272 } +273 } +274 +275 pub(super) fn reset_node_states(&self) { +276 let mut inner = self.inner.lock().expect("poisoned"); +277 for (_, ep) in inner.node_states_mut() { +278 ep.note_connectivity_change(); +279 } +280 } +281 +282 pub(super) fn nodes_stayin_alive(&self) -> Vec<PingAction> { +283 let mut inner = self.inner.lock().expect("poisoned"); +284 inner +285 .node_states_mut() +286 .flat_map(|(_idx, node_state)| node_state.stayin_alive()) +287 .collect() +288 } +289 +290 /// Returns the [`RemoteInfo`]s for each node in the node map. +291 pub(super) fn list_remote_infos(&self, now: Instant) -> Vec<RemoteInfo> { +292 // NOTE: calls to this method will often call `into_iter` (or similar methods). Note that +293 // we can't avoid `collect` here since it would hold a lock for an indefinite time. Even if +294 // we were to find this acceptable, dealing with the lifetimes of the mutex's guard and the +295 // internal iterator will be a hassle, if possible at all. +296 self.inner +297 .lock() +298 .expect("poisoned") +299 .remote_infos_iter(now) +300 .collect() +301 } +302 +303 /// Returns a [`n0_watcher::Direct`] for given node's [`ConnectionType`]. +304 /// +305 /// # Errors +306 /// +307 /// Will return `None` if there is not an entry in the [`NodeMap`] for +308 /// the `node_id` +309 pub(super) fn conn_type(&self, node_id: NodeId) -> Option<n0_watcher::Direct<ConnectionType>> { +310 self.inner.lock().expect("poisoned").conn_type(node_id) +311 } +312 +313 /// Get the [`RemoteInfo`]s for the node identified by [`NodeId`]. +314 pub(super) fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo> { +315 self.inner.lock().expect("poisoned").remote_info(node_id) +316 } +317 +318 /// Prunes nodes without recent activity so that at most [`MAX_INACTIVE_NODES`] are kept. +319 pub(super) fn prune_inactive(&self) { +320 self.inner.lock().expect("poisoned").prune_inactive(); +321 } +322 +323 pub(crate) fn on_direct_addr_discovered(&self, discovered: BTreeSet<SocketAddr>) { +324 self.inner +325 .lock() +326 .expect("poisoned") +327 .on_direct_addr_discovered(discovered); +328 } +329} +330 +331impl NodeMapInner { +332 #[cfg(not(any(test, feature = "test-utils")))] +333 /// Create a new [`NodeMap`] from a list of [`NodeAddr`]s. +334 fn load_from_vec(nodes: Vec<NodeAddr>, metrics: &Metrics) -> Self { +335 let mut me = Self::default(); +336 for node_addr in nodes { +337 me.add_node_addr(node_addr, Source::Saved, metrics); +338 } +339 me +340 } +341 +342 #[cfg(any(test, feature = "test-utils"))] +343 /// Create a new [`NodeMap`] from a list of [`NodeAddr`]s. +344 fn load_from_vec( +345 nodes: Vec<NodeAddr>, +346 path_selection: PathSelection, +347 metrics: &Metrics, +348 ) -> Self { +349 let mut me = Self { +350 path_selection, +351 ..Default::default() +352 }; +353 for node_addr in nodes { +354 me.add_node_addr(node_addr, Source::Saved, metrics); +355 } +356 me +357 } +358 +359 /// Add the contact information for a node. +360 #[instrument(skip_all, fields(node = %node_addr.node_id.fmt_short()))] +361 fn add_node_addr(&mut self, node_addr: NodeAddr, source: Source, metrics: &Metrics) { +362 let source0 = source.clone(); +363 let node_id = node_addr.node_id; +364 let relay_url = node_addr.relay_url.clone(); +365 #[cfg(any(test, feature = "test-utils"))] +366 let path_selection = self.path_selection; +367 let node_state = self.get_or_insert_with(NodeStateKey::NodeId(node_id), || Options { +368 node_id, +369 relay_url, +370 active: false, +371 source, +372 #[cfg(any(test, feature = "test-utils"))] +373 path_selection, +374 }); +375 node_state.update_from_node_addr( +376 node_addr.relay_url.as_ref(), +377 &node_addr.direct_addresses, +378 source0, +379 metrics, +380 ); +381 let id = node_state.id(); +382 for addr in node_addr.direct_addresses() { +383 self.set_node_state_for_ip_port(*addr, id); +384 } +385 } +386 +387 /// Prunes direct addresses from nodes that claim to share an address we know points to us. +388 pub(super) fn on_direct_addr_discovered(&mut self, discovered: BTreeSet<SocketAddr>) { +389 for addr in discovered { +390 self.remove_by_ipp(addr.into(), ClearReason::MatchesOurLocalAddr) +391 } +392 } +393 +394 /// Removes a direct address from a node. +395 fn remove_by_ipp(&mut self, ipp: IpPort, reason: ClearReason) { +396 if let Some(id) = self.by_ip_port.remove(&ipp) { +397 if let Entry::Occupied(mut entry) = self.by_id.entry(id) { +398 let node = entry.get_mut(); +399 node.remove_direct_addr(&ipp, reason); +400 if node.direct_addresses().count() == 0 { +401 let node_id = node.public_key(); +402 let mapped_addr = node.quic_mapped_addr(); +403 self.by_node_key.remove(node_id); +404 self.by_quic_mapped_addr.remove(mapped_addr); +405 debug!(node_id=%node_id.fmt_short(), ?reason, "removing node"); +406 entry.remove(); +407 } +408 } +409 } +410 } +411 +412 fn get_id(&self, id: NodeStateKey) -> Option<usize> { +413 match id { +414 NodeStateKey::Idx(id) => Some(id), +415 NodeStateKey::NodeId(node_key) => self.by_node_key.get(&node_key).copied(), +416 NodeStateKey::NodeIdMappedAddr(addr) => self.by_quic_mapped_addr.get(&addr).copied(), +417 NodeStateKey::IpPort(ipp) => self.by_ip_port.get(&ipp).copied(), +418 } +419 } +420 +421 fn get_mut(&mut self, id: NodeStateKey) -> Option<&mut NodeState> { +422 self.get_id(id).and_then(|id| self.by_id.get_mut(&id)) +423 } +424 +425 fn get(&self, id: NodeStateKey) -> Option<&NodeState> { +426 self.get_id(id).and_then(|id| self.by_id.get(&id)) +427 } +428 +429 fn get_or_insert_with( +430 &mut self, +431 id: NodeStateKey, +432 f: impl FnOnce() -> Options, +433 ) -> &mut NodeState { +434 let id = self.get_id(id); +435 match id { +436 None => self.insert_node(f()), +437 Some(id) => self.by_id.get_mut(&id).expect("is not empty"), +438 } +439 } +440 +441 /// Number of nodes currently listed. +442 fn node_count(&self) -> usize { +443 self.by_id.len() +444 } +445 +446 /// Marks the node we believe to be at `ipp` as recently used. +447 #[cfg(not(wasm_browser))] +448 fn receive_udp(&mut self, udp_addr: SocketAddr) -> Option<(NodeId, NodeIdMappedAddr)> { +449 let ip_port: IpPort = udp_addr.into(); +450 let Some(node_state) = self.get_mut(NodeStateKey::IpPort(ip_port)) else { +451 trace!(src=%udp_addr, "receive_udp: no node_state found for addr, ignore"); +452 return None; +453 }; +454 node_state.receive_udp(ip_port, Instant::now()); +455 Some((*node_state.public_key(), *node_state.quic_mapped_addr())) +456 } +457 +458 #[instrument(skip_all, fields(src = %src.fmt_short()))] +459 fn receive_relay(&mut self, relay_url: &RelayUrl, src: NodeId) -> NodeIdMappedAddr { +460 #[cfg(any(test, feature = "test-utils"))] +461 let path_selection = self.path_selection; +462 let node_state = self.get_or_insert_with(NodeStateKey::NodeId(src), || { +463 trace!("packets from unknown node, insert into node map"); +464 Options { +465 node_id: src, +466 relay_url: Some(relay_url.clone()), +467 active: true, +468 source: Source::Relay, +469 #[cfg(any(test, feature = "test-utils"))] +470 path_selection, +471 } +472 }); +473 node_state.receive_relay(relay_url, src, Instant::now()); +474 *node_state.quic_mapped_addr() +475 } +476 +477 fn node_states(&self) -> impl Iterator<Item = (&usize, &NodeState)> { +478 self.by_id.iter() +479 } +480 +481 fn node_states_mut(&mut self) -> impl Iterator<Item = (&usize, &mut NodeState)> { +482 self.by_id.iter_mut() +483 } +484 +485 /// Get the [`RemoteInfo`]s for all nodes. +486 fn remote_infos_iter(&self, now: Instant) -> impl Iterator<Item = RemoteInfo> + '_ { +487 self.node_states().map(move |(_, ep)| ep.info(now)) +488 } +489 +490 /// Get the [`RemoteInfo`]s for each node. +491 fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo> { +492 self.get(NodeStateKey::NodeId(node_id)) +493 .map(|ep| ep.info(Instant::now())) +494 } +495 +496 /// Returns a stream of [`ConnectionType`]. +497 /// +498 /// Sends the current [`ConnectionType`] whenever any changes to the +499 /// connection type for `public_key` has occurred. 500 /// -501 /// Sends the current [`ConnectionType`] whenever any changes to the -502 /// connection type for `public_key` has occurred. -503 /// -504 /// # Errors -505 /// -506 /// Will return `None` if there is not an entry in the [`NodeMap`] for -507 /// the `public_key` -508 fn conn_type(&self, node_id: NodeId) -> Option<watcher::Direct<ConnectionType>> { -509 self.get(NodeStateKey::NodeId(node_id)) -510 .map(|ep| ep.conn_type()) -511 } -512 -513 fn handle_pong(&mut self, sender: NodeId, src: &DiscoMessageSource, pong: Pong) { -514 if let Some(ns) = self.get_mut(NodeStateKey::NodeId(sender)).as_mut() { -515 let insert = ns.handle_pong(&pong, src.into()); -516 if let Some((src, key)) = insert { -517 self.set_node_key_for_ip_port(src, &key); -518 } -519 trace!(?insert, "received pong") -520 } else { -521 warn!("received pong: node unknown, ignore") -522 } -523 } -524 -525 #[must_use = "actions must be handled"] -526 fn handle_call_me_maybe( -527 &mut self, -528 sender: NodeId, -529 cm: CallMeMaybe, -530 metrics: &Metrics, -531 ) -> Vec<PingAction> { -532 let ns_id = NodeStateKey::NodeId(sender); -533 if let Some(id) = self.get_id(ns_id.clone()) { -534 for number in &cm.my_numbers { -535 // ensure the new addrs are known -536 self.set_node_state_for_ip_port(*number, id); -537 } -538 } -539 match self.get_mut(ns_id) { -540 None => { -541 debug!("received call-me-maybe: ignore, node is unknown"); -542 metrics.recv_disco_call_me_maybe_bad_disco.inc(); -543 vec![] -544 } -545 Some(ns) => { -546 debug!(endpoints = ?cm.my_numbers, "received call-me-maybe"); -547 -548 ns.handle_call_me_maybe(cm) -549 } -550 } -551 } -552 -553 fn handle_ping(&mut self, sender: NodeId, src: SendAddr, tx_id: TransactionId) -> PingHandled { -554 #[cfg(any(test, feature = "test-utils"))] -555 let path_selection = self.path_selection; -556 let node_state = self.get_or_insert_with(NodeStateKey::NodeId(sender), || { -557 debug!("received ping: node unknown, add to node map"); -558 let source = if src.is_relay() { -559 Source::Relay -560 } else { -561 Source::Udp -562 }; -563 Options { -564 node_id: sender, -565 relay_url: src.relay_url(), -566 active: true, -567 source, -568 #[cfg(any(test, feature = "test-utils"))] -569 path_selection, -570 } -571 }); -572 -573 let handled = node_state.handle_ping(src.clone(), tx_id); -574 if let SendAddr::Udp(ref addr) = src { -575 if matches!(handled.role, PingRole::NewPath) { -576 self.set_node_key_for_ip_port(*addr, &sender); -577 } -578 } -579 handled -580 } -581 -582 /// Inserts a new node into the [`NodeMap`]. -583 fn insert_node(&mut self, options: Options) -> &mut NodeState { -584 info!( -585 node = %options.node_id.fmt_short(), -586 relay_url = ?options.relay_url, -587 source = %options.source, -588 "inserting new node in NodeMap", -589 ); -590 let id = self.next_id; -591 self.next_id = self.next_id.wrapping_add(1); -592 let node_state = NodeState::new(id, options); -593 -594 // update indices -595 self.by_quic_mapped_addr -596 .insert(*node_state.quic_mapped_addr(), id); -597 self.by_node_key.insert(*node_state.public_key(), id); -598 -599 self.by_id.insert(id, node_state); -600 self.by_id.get_mut(&id).expect("just inserted") -601 } -602 -603 /// Makes future node lookups by ipp return the same endpoint as a lookup by nk. -604 /// -605 /// This should only be called with a fully verified mapping of ipp to -606 /// nk, because calling this function defines the endpoint we hand to -607 /// WireGuard for packets received from ipp. -608 fn set_node_key_for_ip_port(&mut self, ipp: impl Into<IpPort>, nk: &PublicKey) { -609 let ipp = ipp.into(); -610 if let Some(id) = self.by_ip_port.get(&ipp) { -611 if !self.by_node_key.contains_key(nk) { -612 self.by_node_key.insert(*nk, *id); -613 } -614 self.by_ip_port.remove(&ipp); -615 } -616 if let Some(id) = self.by_node_key.get(nk) { -617 trace!("insert ip -> id: {:?} -> {}", ipp, id); -618 self.by_ip_port.insert(ipp, *id); -619 } -620 } -621 -622 fn set_node_state_for_ip_port(&mut self, ipp: impl Into<IpPort>, id: usize) { -623 let ipp = ipp.into(); -624 trace!(?ipp, ?id, "set endpoint for ip:port"); -625 self.by_ip_port.insert(ipp, id); -626 } -627 -628 /// Prunes nodes without recent activity so that at most [`MAX_INACTIVE_NODES`] are kept. -629 fn prune_inactive(&mut self) { -630 let now = Instant::now(); -631 let mut prune_candidates: Vec<_> = self -632 .by_id -633 .values() -634 .filter(|node| !node.is_active(&now)) -635 .map(|node| (*node.public_key(), node.last_used())) -636 .collect(); -637 -638 let prune_count = prune_candidates.len().saturating_sub(MAX_INACTIVE_NODES); -639 if prune_count == 0 { -640 // within limits -641 return; -642 } -643 -644 prune_candidates.sort_unstable_by_key(|(_pk, last_used)| *last_used); -645 prune_candidates.truncate(prune_count); -646 for (public_key, last_used) in prune_candidates.into_iter() { -647 let node = public_key.fmt_short(); -648 match last_used.map(|instant| instant.elapsed()) { -649 Some(last_used) => trace!(%node, ?last_used, "pruning inactive"), -650 None => trace!(%node, last_used=%"never", "pruning inactive"), -651 } -652 -653 let Some(id) = self.by_node_key.remove(&public_key) else { -654 debug_assert!(false, "missing by_node_key entry for pk in by_id"); -655 continue; -656 }; -657 -658 let Some(ep) = self.by_id.remove(&id) else { -659 debug_assert!(false, "missing by_id entry for id in by_node_key"); -660 continue; -661 }; -662 -663 for ip_port in ep.direct_addresses() { -664 self.by_ip_port.remove(&ip_port); -665 } -666 -667 self.by_quic_mapped_addr.remove(ep.quic_mapped_addr()); -668 } -669 } -670} -671 -672/// An (Ip, Port) pair. -673/// -674/// NOTE: storing an [`IpPort`] is safer than storing a [`SocketAddr`] because for IPv6 socket -675/// addresses include fields that can't be assumed consistent even within a single connection. -676#[derive(Debug, derive_more::Display, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] -677#[display("{}", SocketAddr::from(*self))] -678pub struct IpPort { -679 ip: IpAddr, -680 port: u16, -681} -682 -683impl From<SocketAddr> for IpPort { -684 fn from(socket_addr: SocketAddr) -> Self { -685 Self { -686 ip: socket_addr.ip(), -687 port: socket_addr.port(), -688 } -689 } -690} -691 -692impl From<IpPort> for SocketAddr { -693 fn from(ip_port: IpPort) -> Self { -694 let IpPort { ip, port } = ip_port; -695 (ip, port).into() -696 } -697} -698 -699impl IpPort { -700 pub fn ip(&self) -> &IpAddr { -701 &self.ip -702 } -703 -704 pub fn port(&self) -> u16 { -705 self.port -706 } -707} -708 -709#[cfg(test)] -710mod tests { -711 use std::net::Ipv4Addr; +501 /// # Errors +502 /// +503 /// Will return `None` if there is not an entry in the [`NodeMap`] for +504 /// the `public_key` +505 fn conn_type(&self, node_id: NodeId) -> Option<n0_watcher::Direct<ConnectionType>> { +506 self.get(NodeStateKey::NodeId(node_id)) +507 .map(|ep| ep.conn_type()) +508 } +509 +510 fn handle_pong(&mut self, sender: NodeId, src: &transports::Addr, pong: Pong) { +511 if let Some(ns) = self.get_mut(NodeStateKey::NodeId(sender)).as_mut() { +512 let insert = ns.handle_pong(&pong, src.clone().into()); +513 if let Some((src, key)) = insert { +514 self.set_node_key_for_ip_port(src, &key); +515 } +516 trace!(?insert, "received pong") +517 } else { +518 warn!("received pong: node unknown, ignore") +519 } +520 } +521 +522 #[must_use = "actions must be handled"] +523 fn handle_call_me_maybe( +524 &mut self, +525 sender: NodeId, +526 cm: CallMeMaybe, +527 metrics: &Metrics, +528 ) -> Vec<PingAction> { +529 let ns_id = NodeStateKey::NodeId(sender); +530 if let Some(id) = self.get_id(ns_id.clone()) { +531 for number in &cm.my_numbers { +532 // ensure the new addrs are known +533 self.set_node_state_for_ip_port(*number, id); +534 } +535 } +536 match self.get_mut(ns_id) { +537 None => { +538 debug!("received call-me-maybe: ignore, node is unknown"); +539 metrics.recv_disco_call_me_maybe_bad_disco.inc(); +540 vec![] +541 } +542 Some(ns) => { +543 debug!(endpoints = ?cm.my_numbers, "received call-me-maybe"); +544 +545 ns.handle_call_me_maybe(cm) +546 } +547 } +548 } +549 +550 fn handle_ping(&mut self, sender: NodeId, src: SendAddr, tx_id: TransactionId) -> PingHandled { +551 #[cfg(any(test, feature = "test-utils"))] +552 let path_selection = self.path_selection; +553 let node_state = self.get_or_insert_with(NodeStateKey::NodeId(sender), || { +554 debug!("received ping: node unknown, add to node map"); +555 let source = if src.is_relay() { +556 Source::Relay +557 } else { +558 Source::Udp +559 }; +560 Options { +561 node_id: sender, +562 relay_url: src.relay_url(), +563 active: true, +564 source, +565 #[cfg(any(test, feature = "test-utils"))] +566 path_selection, +567 } +568 }); +569 +570 let handled = node_state.handle_ping(src.clone(), tx_id); +571 if let SendAddr::Udp(ref addr) = src { +572 if matches!(handled.role, PingRole::NewPath) { +573 self.set_node_key_for_ip_port(*addr, &sender); +574 } +575 } +576 handled +577 } +578 +579 /// Inserts a new node into the [`NodeMap`]. +580 fn insert_node(&mut self, options: Options) -> &mut NodeState { +581 info!( +582 node = %options.node_id.fmt_short(), +583 relay_url = ?options.relay_url, +584 source = %options.source, +585 "inserting new node in NodeMap", +586 ); +587 let id = self.next_id; +588 self.next_id = self.next_id.wrapping_add(1); +589 let node_state = NodeState::new(id, options); +590 +591 // update indices +592 self.by_quic_mapped_addr +593 .insert(*node_state.quic_mapped_addr(), id); +594 self.by_node_key.insert(*node_state.public_key(), id); +595 +596 self.by_id.insert(id, node_state); +597 self.by_id.get_mut(&id).expect("just inserted") +598 } +599 +600 /// Makes future node lookups by ipp return the same endpoint as a lookup by nk. +601 /// +602 /// This should only be called with a fully verified mapping of ipp to +603 /// nk, because calling this function defines the endpoint we hand to +604 /// WireGuard for packets received from ipp. +605 fn set_node_key_for_ip_port(&mut self, ipp: impl Into<IpPort>, nk: &PublicKey) { +606 let ipp = ipp.into(); +607 if let Some(id) = self.by_ip_port.get(&ipp) { +608 if !self.by_node_key.contains_key(nk) { +609 self.by_node_key.insert(*nk, *id); +610 } +611 self.by_ip_port.remove(&ipp); +612 } +613 if let Some(id) = self.by_node_key.get(nk) { +614 trace!("insert ip -> id: {:?} -> {}", ipp, id); +615 self.by_ip_port.insert(ipp, *id); +616 } +617 } +618 +619 fn set_node_state_for_ip_port(&mut self, ipp: impl Into<IpPort>, id: usize) { +620 let ipp = ipp.into(); +621 trace!(?ipp, ?id, "set endpoint for ip:port"); +622 self.by_ip_port.insert(ipp, id); +623 } +624 +625 /// Prunes nodes without recent activity so that at most [`MAX_INACTIVE_NODES`] are kept. +626 fn prune_inactive(&mut self) { +627 let now = Instant::now(); +628 let mut prune_candidates: Vec<_> = self +629 .by_id +630 .values() +631 .filter(|node| !node.is_active(&now)) +632 .map(|node| (*node.public_key(), node.last_used())) +633 .collect(); +634 +635 let prune_count = prune_candidates.len().saturating_sub(MAX_INACTIVE_NODES); +636 if prune_count == 0 { +637 // within limits +638 return; +639 } +640 +641 prune_candidates.sort_unstable_by_key(|(_pk, last_used)| *last_used); +642 prune_candidates.truncate(prune_count); +643 for (public_key, last_used) in prune_candidates.into_iter() { +644 let node = public_key.fmt_short(); +645 match last_used.map(|instant| instant.elapsed()) { +646 Some(last_used) => trace!(%node, ?last_used, "pruning inactive"), +647 None => trace!(%node, last_used=%"never", "pruning inactive"), +648 } +649 +650 let Some(id) = self.by_node_key.remove(&public_key) else { +651 debug_assert!(false, "missing by_node_key entry for pk in by_id"); +652 continue; +653 }; +654 +655 let Some(ep) = self.by_id.remove(&id) else { +656 debug_assert!(false, "missing by_id entry for id in by_node_key"); +657 continue; +658 }; +659 +660 for ip_port in ep.direct_addresses() { +661 self.by_ip_port.remove(&ip_port); +662 } +663 +664 self.by_quic_mapped_addr.remove(ep.quic_mapped_addr()); +665 } +666 } +667} +668 +669/// An (Ip, Port) pair. +670/// +671/// NOTE: storing an [`IpPort`] is safer than storing a [`SocketAddr`] because for IPv6 socket +672/// addresses include fields that can't be assumed consistent even within a single connection. +673#[derive(Debug, derive_more::Display, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)] +674#[display("{}", SocketAddr::from(*self))] +675pub struct IpPort { +676 ip: IpAddr, +677 port: u16, +678} +679 +680impl From<SocketAddr> for IpPort { +681 fn from(socket_addr: SocketAddr) -> Self { +682 Self { +683 ip: socket_addr.ip(), +684 port: socket_addr.port(), +685 } +686 } +687} +688 +689impl From<IpPort> for SocketAddr { +690 fn from(ip_port: IpPort) -> Self { +691 let IpPort { ip, port } = ip_port; +692 (ip, port).into() +693 } +694} +695 +696impl IpPort { +697 pub fn ip(&self) -> &IpAddr { +698 &self.ip +699 } +700 +701 pub fn port(&self) -> u16 { +702 self.port +703 } +704} +705 +706#[cfg(test)] +707mod tests { +708 use std::net::Ipv4Addr; +709 +710 use iroh_base::SecretKey; +711 use tracing_test::traced_test; 712 -713 use iroh_base::SecretKey; -714 use tracing_test::traced_test; -715 -716 use super::{node_state::MAX_INACTIVE_DIRECT_ADDRESSES, *}; -717 -718 impl NodeMap { -719 #[track_caller] -720 fn add_test_addr(&self, node_addr: NodeAddr) { -721 self.add_node_addr( -722 node_addr, -723 Source::NamedApp { -724 name: "test".into(), -725 }, -726 &Default::default(), -727 ) -728 } -729 } -730 -731 /// Test persisting and loading of known nodes. -732 #[tokio::test] -733 #[traced_test] -734 async fn restore_from_vec() { -735 let node_map = NodeMap::default(); -736 -737 let mut rng = rand::thread_rng(); -738 let node_a = SecretKey::generate(&mut rng).public(); -739 let node_b = SecretKey::generate(&mut rng).public(); -740 let node_c = SecretKey::generate(&mut rng).public(); -741 let node_d = SecretKey::generate(&mut rng).public(); +713 use super::{node_state::MAX_INACTIVE_DIRECT_ADDRESSES, *}; +714 +715 impl NodeMap { +716 #[track_caller] +717 fn add_test_addr(&self, node_addr: NodeAddr) { +718 self.add_node_addr( +719 node_addr, +720 Source::NamedApp { +721 name: "test".into(), +722 }, +723 &Default::default(), +724 ) +725 } +726 } +727 +728 /// Test persisting and loading of known nodes. +729 #[tokio::test] +730 #[traced_test] +731 async fn restore_from_vec() { +732 let node_map = NodeMap::default(); +733 +734 let mut rng = rand::thread_rng(); +735 let node_a = SecretKey::generate(&mut rng).public(); +736 let node_b = SecretKey::generate(&mut rng).public(); +737 let node_c = SecretKey::generate(&mut rng).public(); +738 let node_d = SecretKey::generate(&mut rng).public(); +739 +740 let relay_x: RelayUrl = "https://my-relay-1.com".parse().unwrap(); +741 let relay_y: RelayUrl = "https://my-relay-2.com".parse().unwrap(); 742 -743 let relay_x: RelayUrl = "https://my-relay-1.com".parse().unwrap(); -744 let relay_y: RelayUrl = "https://my-relay-2.com".parse().unwrap(); +743 let direct_addresses_a = [addr(4000), addr(4001)]; +744 let direct_addresses_c = [addr(5000)]; 745 -746 let direct_addresses_a = [addr(4000), addr(4001)]; -747 let direct_addresses_c = [addr(5000)]; -748 -749 let node_addr_a = NodeAddr::new(node_a) -750 .with_relay_url(relay_x) -751 .with_direct_addresses(direct_addresses_a); -752 let node_addr_b = NodeAddr::new(node_b).with_relay_url(relay_y); -753 let node_addr_c = NodeAddr::new(node_c).with_direct_addresses(direct_addresses_c); -754 let node_addr_d = NodeAddr::new(node_d); -755 -756 node_map.add_test_addr(node_addr_a); -757 node_map.add_test_addr(node_addr_b); -758 node_map.add_test_addr(node_addr_c); -759 node_map.add_test_addr(node_addr_d); -760 -761 let mut addrs: Vec<NodeAddr> = node_map -762 .list_remote_infos(Instant::now()) -763 .into_iter() -764 .filter_map(|info| { -765 let addr: NodeAddr = info.into(); -766 if addr.is_empty() { -767 return None; -768 } -769 Some(addr) -770 }) -771 .collect(); -772 let loaded_node_map = -773 NodeMap::load_from_vec(addrs.clone(), PathSelection::default(), &Default::default()); -774 -775 let mut loaded: Vec<NodeAddr> = loaded_node_map -776 .list_remote_infos(Instant::now()) -777 .into_iter() -778 .filter_map(|info| { -779 let addr: NodeAddr = info.into(); -780 if addr.is_empty() { -781 return None; -782 } -783 Some(addr) -784 }) -785 .collect(); +746 let node_addr_a = NodeAddr::new(node_a) +747 .with_relay_url(relay_x) +748 .with_direct_addresses(direct_addresses_a); +749 let node_addr_b = NodeAddr::new(node_b).with_relay_url(relay_y); +750 let node_addr_c = NodeAddr::new(node_c).with_direct_addresses(direct_addresses_c); +751 let node_addr_d = NodeAddr::new(node_d); +752 +753 node_map.add_test_addr(node_addr_a); +754 node_map.add_test_addr(node_addr_b); +755 node_map.add_test_addr(node_addr_c); +756 node_map.add_test_addr(node_addr_d); +757 +758 let mut addrs: Vec<NodeAddr> = node_map +759 .list_remote_infos(Instant::now()) +760 .into_iter() +761 .filter_map(|info| { +762 let addr: NodeAddr = info.into(); +763 if addr.is_empty() { +764 return None; +765 } +766 Some(addr) +767 }) +768 .collect(); +769 let loaded_node_map = +770 NodeMap::load_from_vec(addrs.clone(), PathSelection::default(), &Default::default()); +771 +772 let mut loaded: Vec<NodeAddr> = loaded_node_map +773 .list_remote_infos(Instant::now()) +774 .into_iter() +775 .filter_map(|info| { +776 let addr: NodeAddr = info.into(); +777 if addr.is_empty() { +778 return None; +779 } +780 Some(addr) +781 }) +782 .collect(); +783 +784 loaded.sort_unstable(); +785 addrs.sort_unstable(); 786 -787 loaded.sort_unstable(); -788 addrs.sort_unstable(); -789 -790 // compare the node maps via their known nodes -791 assert_eq!(addrs, loaded); -792 } -793 -794 fn addr(port: u16) -> SocketAddr { -795 (std::net::IpAddr::V4(Ipv4Addr::LOCALHOST), port).into() -796 } -797 -798 #[test] -799 #[traced_test] -800 fn test_prune_direct_addresses() { -801 let node_map = NodeMap::default(); -802 let public_key = SecretKey::generate(rand::thread_rng()).public(); -803 let id = node_map -804 .inner -805 .lock() -806 .unwrap() -807 .insert_node(Options { -808 node_id: public_key, -809 relay_url: None, -810 active: false, -811 source: Source::NamedApp { -812 name: "test".into(), -813 }, -814 path_selection: PathSelection::default(), -815 }) -816 .id(); -817 -818 const LOCALHOST: IpAddr = IpAddr::V4(std::net::Ipv4Addr::LOCALHOST); +787 // compare the node maps via their known nodes +788 assert_eq!(addrs, loaded); +789 } +790 +791 fn addr(port: u16) -> SocketAddr { +792 (std::net::IpAddr::V4(Ipv4Addr::LOCALHOST), port).into() +793 } +794 +795 #[test] +796 #[traced_test] +797 fn test_prune_direct_addresses() { +798 let node_map = NodeMap::default(); +799 let public_key = SecretKey::generate(rand::thread_rng()).public(); +800 let id = node_map +801 .inner +802 .lock() +803 .unwrap() +804 .insert_node(Options { +805 node_id: public_key, +806 relay_url: None, +807 active: false, +808 source: Source::NamedApp { +809 name: "test".into(), +810 }, +811 path_selection: PathSelection::default(), +812 }) +813 .id(); +814 +815 const LOCALHOST: IpAddr = IpAddr::V4(std::net::Ipv4Addr::LOCALHOST); +816 +817 // add [`MAX_INACTIVE_DIRECT_ADDRESSES`] active direct addresses and double +818 // [`MAX_INACTIVE_DIRECT_ADDRESSES`] that are inactive 819 -820 // add [`MAX_INACTIVE_DIRECT_ADDRESSES`] active direct addresses and double -821 // [`MAX_INACTIVE_DIRECT_ADDRESSES`] that are inactive -822 -823 info!("Adding active addresses"); -824 for i in 0..MAX_INACTIVE_DIRECT_ADDRESSES { -825 let addr = SocketAddr::new(LOCALHOST, 5000 + i as u16); -826 let node_addr = NodeAddr::new(public_key).with_direct_addresses([addr]); -827 // add address -828 node_map.add_test_addr(node_addr); -829 // make it active -830 node_map.inner.lock().unwrap().receive_udp(addr); -831 } -832 -833 info!("Adding offline/inactive addresses"); -834 for i in 0..MAX_INACTIVE_DIRECT_ADDRESSES * 2 { -835 let addr = SocketAddr::new(LOCALHOST, 6000 + i as u16); -836 let node_addr = NodeAddr::new(public_key).with_direct_addresses([addr]); -837 node_map.add_test_addr(node_addr); -838 } +820 info!("Adding active addresses"); +821 for i in 0..MAX_INACTIVE_DIRECT_ADDRESSES { +822 let addr = SocketAddr::new(LOCALHOST, 5000 + i as u16); +823 let node_addr = NodeAddr::new(public_key).with_direct_addresses([addr]); +824 // add address +825 node_map.add_test_addr(node_addr); +826 // make it active +827 node_map.inner.lock().unwrap().receive_udp(addr); +828 } +829 +830 info!("Adding offline/inactive addresses"); +831 for i in 0..MAX_INACTIVE_DIRECT_ADDRESSES * 2 { +832 let addr = SocketAddr::new(LOCALHOST, 6000 + i as u16); +833 let node_addr = NodeAddr::new(public_key).with_direct_addresses([addr]); +834 node_map.add_test_addr(node_addr); +835 } +836 +837 let mut node_map_inner = node_map.inner.lock().unwrap(); +838 let endpoint = node_map_inner.by_id.get_mut(&id).unwrap(); 839 -840 let mut node_map_inner = node_map.inner.lock().unwrap(); -841 let endpoint = node_map_inner.by_id.get_mut(&id).unwrap(); -842 -843 info!("Adding alive addresses"); -844 for i in 0..MAX_INACTIVE_DIRECT_ADDRESSES { -845 let addr = SendAddr::Udp(SocketAddr::new(LOCALHOST, 7000 + i as u16)); -846 let txid = stun_rs::TransactionId::from([i as u8; 12]); -847 // Note that this already invokes .prune_direct_addresses() because these are -848 // new UDP paths. -849 endpoint.handle_ping(addr, txid); -850 } +840 info!("Adding alive addresses"); +841 for i in 0..MAX_INACTIVE_DIRECT_ADDRESSES { +842 let addr = SendAddr::Udp(SocketAddr::new(LOCALHOST, 7000 + i as u16)); +843 let txid = stun_rs::TransactionId::from([i as u8; 12]); +844 // Note that this already invokes .prune_direct_addresses() because these are +845 // new UDP paths. +846 endpoint.handle_ping(addr, txid); +847 } +848 +849 info!("Pruning addresses"); +850 endpoint.prune_direct_addresses(); 851 -852 info!("Pruning addresses"); -853 endpoint.prune_direct_addresses(); -854 -855 // Half the offline addresses should have been pruned. All the active and alive -856 // addresses should have been kept. -857 assert_eq!( -858 endpoint.direct_addresses().count(), -859 MAX_INACTIVE_DIRECT_ADDRESSES * 3 -860 ); -861 -862 // We should have both offline and alive addresses which are not active. -863 assert_eq!( -864 endpoint -865 .direct_address_states() -866 .filter(|(_addr, state)| !state.is_active()) -867 .count(), -868 MAX_INACTIVE_DIRECT_ADDRESSES * 2 -869 ) -870 } -871 -872 #[test] -873 fn test_prune_inactive() { -874 let node_map = NodeMap::default(); -875 // add one active node and more than MAX_INACTIVE_NODES inactive nodes -876 let active_node = SecretKey::generate(rand::thread_rng()).public(); -877 let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 167); -878 node_map.add_test_addr(NodeAddr::new(active_node).with_direct_addresses([addr])); -879 node_map -880 .inner -881 .lock() -882 .unwrap() -883 .receive_udp(addr) -884 .expect("registered"); -885 -886 for _ in 0..MAX_INACTIVE_NODES + 1 { -887 let node = SecretKey::generate(rand::thread_rng()).public(); -888 node_map.add_test_addr(NodeAddr::new(node)); -889 } -890 -891 assert_eq!(node_map.node_count(), MAX_INACTIVE_NODES + 2); -892 node_map.prune_inactive(); -893 assert_eq!(node_map.node_count(), MAX_INACTIVE_NODES + 1); -894 node_map -895 .inner -896 .lock() -897 .unwrap() -898 .get(NodeStateKey::NodeId(active_node)) -899 .expect("should not be pruned"); -900 } -901} \ No newline at end of file +852 // Half the offline addresses should have been pruned. All the active and alive +853 // addresses should have been kept. +854 assert_eq!( +855 endpoint.direct_addresses().count(), +856 MAX_INACTIVE_DIRECT_ADDRESSES * 3 +857 ); +858 +859 // We should have both offline and alive addresses which are not active. +860 assert_eq!( +861 endpoint +862 .direct_address_states() +863 .filter(|(_addr, state)| !state.is_active()) +864 .count(), +865 MAX_INACTIVE_DIRECT_ADDRESSES * 2 +866 ) +867 } +868 +869 #[test] +870 fn test_prune_inactive() { +871 let node_map = NodeMap::default(); +872 // add one active node and more than MAX_INACTIVE_NODES inactive nodes +873 let active_node = SecretKey::generate(rand::thread_rng()).public(); +874 let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 167); +875 node_map.add_test_addr(NodeAddr::new(active_node).with_direct_addresses([addr])); +876 node_map +877 .inner +878 .lock() +879 .unwrap() +880 .receive_udp(addr) +881 .expect("registered"); +882 +883 for _ in 0..MAX_INACTIVE_NODES + 1 { +884 let node = SecretKey::generate(rand::thread_rng()).public(); +885 node_map.add_test_addr(NodeAddr::new(node)); +886 } +887 +888 assert_eq!(node_map.node_count(), MAX_INACTIVE_NODES + 2); +889 node_map.prune_inactive(); +890 assert_eq!(node_map.node_count(), MAX_INACTIVE_NODES + 1); +891 node_map +892 .inner +893 .lock() +894 .unwrap() +895 .get(NodeStateKey::NodeId(active_node)) +896 .expect("should not be pruned"); +897 } +898} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/magicsock/node_map/best_addr.rs.html b/pr/3327/docs/src/iroh/magicsock/node_map/best_addr.rs.html index 84afc2c216..d3f7847934 100644 --- a/pr/3327/docs/src/iroh/magicsock/node_map/best_addr.rs.html +++ b/pr/3327/docs/src/iroh/magicsock/node_map/best_addr.rs.html @@ -180,7 +180,7 @@ 180 self.0 = Some(inner); 181 } 182 -183 pub fn state(&self, now: Instant) -> State { +183 pub fn state(&self, now: Instant) -> State<'_> { 184 match &self.0 { 185 None => State::Empty, 186 Some(state) => match state.trust_until { diff --git a/pr/3327/docs/src/iroh/magicsock/node_map/node_state.rs.html b/pr/3327/docs/src/iroh/magicsock/node_map/node_state.rs.html index 60d3b6ca2e..abd2a3382c 100644 --- a/pr/3327/docs/src/iroh/magicsock/node_map/node_state.rs.html +++ b/pr/3327/docs/src/iroh/magicsock/node_map/node_state.rs.html @@ -11,22 +11,22 @@ 11 task::{self, AbortOnDropHandle}, 12 time::{self, Duration, Instant}, 13}; -14use serde::{Deserialize, Serialize}; -15use tokio::sync::mpsc; -16use tracing::{debug, event, info, instrument, trace, warn, Level}; -17 -18use super::{ -19 best_addr::{self, ClearReason, Source as BestAddrSource}, -20 path_state::{summarize_node_paths, PathState}, -21 udp_paths::{NodeUdpPaths, UdpSendAddr}, -22 IpPort, Source, -23}; -24#[cfg(any(test, feature = "test-utils"))] -25use crate::endpoint::PathSelection; -26use crate::{ -27 disco::{self, SendAddr}, -28 magicsock::{ActorMessage, MagicsockMetrics, NodeIdMappedAddr, HEARTBEAT_INTERVAL}, -29 watcher::{self, Watchable}, +14use n0_watcher::Watchable; +15use serde::{Deserialize, Serialize}; +16use tokio::sync::mpsc; +17use tracing::{debug, event, info, instrument, trace, warn, Level}; +18 +19use super::{ +20 best_addr::{self, ClearReason, Source as BestAddrSource}, +21 path_state::{summarize_node_paths, PathState}, +22 udp_paths::{NodeUdpPaths, UdpSendAddr}, +23 IpPort, Source, +24}; +25#[cfg(any(test, feature = "test-utils"))] +26use crate::endpoint::PathSelection; +27use crate::{ +28 disco::{self, SendAddr}, +29 magicsock::{ActorMessage, MagicsockMetrics, NodeIdMappedAddr, HEARTBEAT_INTERVAL}, 30}; 31 32/// Number of addresses that are not active that we keep around per node. @@ -202,7 +202,7 @@ 202 self.id 203 } 204 -205 pub(super) fn conn_type(&self) -> watcher::Direct<ConnectionType> { +205 pub(super) fn conn_type(&self) -> n0_watcher::Direct<ConnectionType> { 206 self.conn_type.watch() 207 } 208 @@ -586,1175 +586,1173 @@ 586 } 587 } 588 } -589 -590 // We send pings regardless of whether we have a RelayUrl. If we were given any -591 // direct address paths to contact but no RelayUrl, we still need to send a DISCO -592 // ping to the direct address paths so that the other node will learn about us and -593 // accepts the connection. -594 let mut msgs = self.send_pings(now); -595 -596 if let Some(url) = self.relay_url() { -597 debug!(%url, "queue call-me-maybe"); -598 msgs.push(PingAction::SendCallMeMaybe { -599 relay_url: url, -600 dst_node: self.node_id, -601 }); -602 self.last_call_me_maybe = Some(now); -603 } else { -604 debug!("can not send call-me-maybe, no relay URL"); -605 } -606 -607 msgs -608 } -609 -610 /// Send DISCO Pings to all the paths of this node. -611 /// -612 /// Any paths to the node which have not been recently pinged will be sent a disco -613 /// ping. -614 /// -615 /// The caller is responsible for sending the messages. -616 #[must_use = "actions must be handled"] -617 fn send_pings(&mut self, now: Instant) -> Vec<PingAction> { -618 // We allocate +1 in case the caller wants to add a call-me-maybe message. -619 let mut ping_msgs = Vec::with_capacity(self.udp_paths.paths.len() + 1); -620 -621 if let Some((url, state)) = self.relay_url.as_ref() { -622 if state.needs_ping(&now) { -623 debug!(%url, "relay path needs ping"); -624 if let Some(msg) = -625 self.start_ping(SendAddr::Relay(url.clone()), DiscoPingPurpose::Discovery) -626 { -627 ping_msgs.push(PingAction::SendPing(msg)) -628 } -629 } -630 } -631 -632 #[cfg(any(test, feature = "test-utils"))] -633 if self.path_selection == PathSelection::RelayOnly { -634 warn!("in `RelayOnly` mode, ignoring request to respond to a hole punching attempt."); -635 return ping_msgs; -636 } -637 -638 self.prune_direct_addresses(); -639 let mut ping_dsts = String::from("["); -640 self.udp_paths -641 .paths -642 .iter() -643 .filter_map(|(ipp, state)| state.needs_ping(&now).then_some(*ipp)) -644 .filter_map(|ipp| { -645 self.start_ping(SendAddr::Udp(ipp.into()), DiscoPingPurpose::Discovery) -646 }) -647 .for_each(|msg| { -648 use std::fmt::Write; -649 write!(&mut ping_dsts, " {} ", msg.dst).ok(); -650 ping_msgs.push(PingAction::SendPing(msg)); -651 }); -652 ping_dsts.push(']'); -653 debug!( -654 %ping_dsts, -655 dst = %self.node_id.fmt_short(), -656 paths = %summarize_node_paths(&self.udp_paths.paths), -657 "sending pings to node", -658 ); -659 self.last_full_ping.replace(now); -660 ping_msgs -661 } -662 -663 pub(super) fn update_from_node_addr( -664 &mut self, -665 new_relay_url: Option<&RelayUrl>, -666 new_addrs: &BTreeSet<SocketAddr>, -667 source: super::Source, -668 metrics: &MagicsockMetrics, -669 ) { -670 if self.udp_paths.best_addr.is_empty() { -671 // we do not have a direct connection, so changing the relay information may -672 // have an effect on our connection status -673 if self.relay_url.is_none() && new_relay_url.is_some() { -674 // we did not have a relay connection before, but now we do -675 metrics.num_relay_conns_added.inc(); -676 } else if self.relay_url.is_some() && new_relay_url.is_none() { -677 // we had a relay connection before but do not have one now -678 metrics.num_relay_conns_removed.inc(); -679 } -680 } -681 -682 let now = Instant::now(); -683 -684 if new_relay_url.is_some() && new_relay_url != self.relay_url().as_ref() { -685 debug!( -686 "Changing relay node from {:?} to {:?}", -687 self.relay_url, new_relay_url -688 ); -689 self.relay_url = new_relay_url.map(|url| { -690 ( -691 url.clone(), -692 PathState::new(self.node_id, url.clone().into(), source.clone(), now), -693 ) -694 }); -695 } -696 -697 for &addr in new_addrs.iter() { -698 self.udp_paths -699 .paths -700 .entry(addr.into()) -701 .and_modify(|path_state| { -702 path_state.add_source(source.clone(), now); -703 }) -704 .or_insert_with(|| { -705 PathState::new(self.node_id, SendAddr::from(addr), source.clone(), now) -706 }); -707 } -708 let paths = summarize_node_paths(&self.udp_paths.paths); -709 debug!(new = ?new_addrs , %paths, "added new direct paths for endpoint"); -710 } -711 -712 /// Clears all the endpoint's p2p state, reverting it to a relay-only endpoint. -713 #[instrument(skip_all, fields(node = %self.node_id.fmt_short()))] -714 pub(super) fn reset(&mut self) { -715 self.last_full_ping = None; -716 self.udp_paths -717 .best_addr -718 .clear(ClearReason::Reset, self.relay_url.is_some()); -719 -720 for es in self.udp_paths.paths.values_mut() { -721 es.last_ping = None; -722 } -723 } -724 -725 /// Handle a received Disco Ping. -726 /// -727 /// - Ensures the paths the ping was received on is a known path for this endpoint. -728 /// -729 /// - If there is no best_addr for this endpoint yet, sends a ping itself to try and -730 /// establish one. -731 /// -732 /// This is called once we've already verified that we got a valid discovery message -733 /// from `self` via ep. -734 pub(super) fn handle_ping( -735 &mut self, -736 path: SendAddr, -737 tx_id: stun::TransactionId, -738 ) -> PingHandled { -739 let now = Instant::now(); -740 -741 let role = match path { -742 SendAddr::Udp(addr) => match self.udp_paths.paths.entry(addr.into()) { -743 Entry::Occupied(mut occupied) => occupied.get_mut().handle_ping(tx_id, now), -744 Entry::Vacant(vacant) => { -745 info!(%addr, "new direct addr for node"); -746 vacant.insert(PathState::with_ping( -747 self.node_id, -748 path.clone(), -749 tx_id, -750 Source::Udp, -751 now, -752 )); -753 PingRole::NewPath -754 } -755 }, -756 SendAddr::Relay(ref url) => { -757 match self.relay_url.as_mut() { -758 Some((home_url, _state)) if home_url != url => { -759 // either the node changed relays or we didn't have a relay address for the -760 // node. In both cases, trust the new confirmed url -761 info!(%url, "new relay addr for node"); -762 self.relay_url = Some(( -763 url.clone(), -764 PathState::with_ping( -765 self.node_id, -766 path.clone(), -767 tx_id, -768 Source::Relay, -769 now, -770 ), -771 )); -772 PingRole::NewPath -773 } -774 Some((_home_url, state)) => state.handle_ping(tx_id, now), -775 None => { -776 info!(%url, "new relay addr for node"); -777 self.relay_url = Some(( -778 url.clone(), -779 PathState::with_ping( -780 self.node_id, -781 path.clone(), -782 tx_id, -783 Source::Relay, -784 now, -785 ), -786 )); -787 PingRole::NewPath -788 } -789 } -790 } -791 }; -792 event!( -793 target: "iroh::_events::ping::recv", -794 Level::DEBUG, -795 remote_node = %self.node_id.fmt_short(), -796 src = ?path, -797 txn = ?tx_id, -798 ?role, -799 ); -800 -801 if matches!(path, SendAddr::Udp(_)) && matches!(role, PingRole::NewPath) { -802 self.prune_direct_addresses(); -803 } -804 -805 // if the endpoint does not yet have a best_addrr -806 let needs_ping_back = if matches!(path, SendAddr::Udp(_)) -807 && matches!( -808 self.udp_paths.best_addr.state(now), -809 best_addr::State::Empty | best_addr::State::Outdated(_) -810 ) { -811 // We also need to send a ping to make this path available to us as well. This -812 // is always sent together with a pong. So in the worst case the pong gets lost -813 // and this ping does not. In that case we ping-pong until both sides have -814 // received at least one pong. Once both sides have received one pong they both -815 // have a best_addr and this ping will stop being sent. -816 self.start_ping(path, DiscoPingPurpose::PingBack) -817 } else { -818 None -819 }; -820 -821 debug!( -822 ?role, -823 needs_ping_back = ?needs_ping_back.is_some(), -824 paths = %summarize_node_paths(&self.udp_paths.paths), -825 "endpoint handled ping", -826 ); -827 PingHandled { -828 role, -829 needs_ping_back, -830 } -831 } -832 -833 /// Prune inactive paths. -834 /// -835 /// This trims the list of inactive paths for an endpoint. At most -836 /// [`MAX_INACTIVE_DIRECT_ADDRESSES`] are kept. -837 pub(super) fn prune_direct_addresses(&mut self) { -838 // prune candidates are addresses that are not active -839 let mut prune_candidates: Vec<_> = self -840 .udp_paths -841 .paths -842 .iter() -843 .filter(|(_ip_port, state)| !state.is_active()) -844 .map(|(ip_port, state)| (*ip_port, state.last_alive())) -845 .filter(|(_ipp, last_alive)| match last_alive { -846 Some(last_seen) => last_seen.elapsed() > LAST_ALIVE_PRUNE_DURATION, -847 None => true, -848 }) -849 .collect(); -850 let prune_count = prune_candidates -851 .len() -852 .saturating_sub(MAX_INACTIVE_DIRECT_ADDRESSES); -853 if prune_count == 0 { -854 // nothing to do, within limits -855 debug!( -856 paths = %summarize_node_paths(&self.udp_paths.paths), -857 "prune addresses: {prune_count} pruned", -858 ); -859 return; -860 } -861 -862 // sort leaving the worst addresses first (never contacted) and better ones (most recently -863 // used ones) last -864 prune_candidates.sort_unstable_by_key(|(_ip_port, last_alive)| *last_alive); -865 prune_candidates.truncate(prune_count); -866 for (ip_port, _last_alive) in prune_candidates.into_iter() { -867 self.remove_direct_addr(&ip_port, ClearReason::Inactive) -868 } -869 debug!( -870 paths = %summarize_node_paths(&self.udp_paths.paths), -871 "prune addresses: {prune_count} pruned", -872 ); -873 } -874 -875 /// Called when connectivity changes enough that we should question our earlier -876 /// assumptions about which paths work. -877 #[instrument("disco", skip_all, fields(node = %self.node_id.fmt_short()))] -878 pub(super) fn note_connectivity_change(&mut self) { -879 self.udp_paths.best_addr.clear_trust("connectivity changed"); -880 for es in self.udp_paths.paths.values_mut() { -881 es.clear(); -882 } -883 } -884 -885 /// Handles a Pong message (a reply to an earlier ping). -886 /// -887 /// It reports the address and key that should be inserted for the endpoint if any. -888 #[instrument(skip(self))] -889 pub(super) fn handle_pong( -890 &mut self, -891 m: &disco::Pong, -892 src: SendAddr, -893 ) -> Option<(SocketAddr, PublicKey)> { -894 event!( -895 target: "iroh::_events::pong::recv", -896 Level::DEBUG, -897 remote_node = self.node_id.fmt_short(), -898 ?src, -899 txn = ?m.tx_id, -900 ); -901 let is_relay = src.is_relay(); -902 match self.sent_pings.remove(&m.tx_id) { -903 None => { -904 // This is not a pong for a ping we sent. In reality however we probably -905 // did send this ping but it has timed-out by the time we receive this pong -906 // so we removed the state already. -907 debug!(tx = %HEXLOWER.encode(&m.tx_id), "received unknown pong (did it timeout?)"); -908 None -909 } -910 Some(sp) => { -911 let mut node_map_insert = None; -912 -913 let now = Instant::now(); -914 let latency = now - sp.at; -915 -916 debug!( -917 tx = %HEXLOWER.encode(&m.tx_id), -918 src = %src, -919 reported_ping_src = %m.ping_observed_addr, -920 ping_dst = %sp.to, -921 is_relay = %src.is_relay(), -922 latency = %latency.as_millis(), -923 "received pong", -924 ); -925 -926 match src { -927 SendAddr::Udp(addr) => { -928 match self.udp_paths.paths.get_mut(&addr.into()) { -929 None => { -930 warn!("ignoring pong: no state for src addr"); -931 // This is no longer an endpoint we care about. -932 return node_map_insert; -933 } -934 Some(st) => { -935 node_map_insert = Some((addr, self.node_id)); -936 st.add_pong_reply(PongReply { -937 latency, -938 pong_at: now, -939 from: src, -940 pong_src: m.ping_observed_addr.clone(), -941 }); -942 } -943 } -944 debug!( -945 paths = %summarize_node_paths(&self.udp_paths.paths), -946 "handled pong", -947 ); -948 } -949 SendAddr::Relay(ref url) => match self.relay_url.as_mut() { -950 Some((home_url, state)) if home_url == url => { -951 state.add_pong_reply(PongReply { -952 latency, -953 pong_at: now, -954 from: src, -955 pong_src: m.ping_observed_addr.clone(), -956 }); -957 } -958 other => { -959 // if we are here then we sent this ping, but the url changed -960 // waiting for the response. It was either set to None or changed to -961 // another relay. This should either never happen or be extremely -962 // unlikely. Log and ignore for now -963 warn!( -964 stored=?other, -965 received=?url, -966 "ignoring pong via relay for different relay from last one", -967 ); -968 } -969 }, -970 } -971 -972 // Promote this pong response to our current best address if it's lower latency. -973 // TODO(bradfitz): decide how latency vs. preference order affects decision -974 if let SendAddr::Udp(to) = sp.to { -975 debug_assert!(!is_relay, "mismatching relay & udp"); -976 self.udp_paths.best_addr.insert_if_better_or_reconfirm( -977 to, -978 latency, -979 best_addr::Source::ReceivedPong, -980 now, -981 ); -982 } -983 -984 node_map_insert -985 } -986 } -987 } -988 -989 /// Handles a DISCO CallMeMaybe discovery message. -990 /// -991 /// The contract for use of this message is that the node has already pinged to us via -992 /// UDP, so their stateful firewall should be open. Now we can Ping back and make it -993 /// through. -994 /// -995 /// However if the remote side has no direct path information to us, they would not have -996 /// had any [`IpPort`]s to send pings to and our pings might end up blocked. But at -997 /// least open the firewalls on our side, giving the other side another change of making -998 /// it through when it pings in response. -999 pub(super) fn handle_call_me_maybe(&mut self, m: disco::CallMeMaybe) -> Vec<PingAction> { -1000 let now = Instant::now(); -1001 let mut call_me_maybe_ipps = BTreeSet::new(); -1002 -1003 for peer_sockaddr in &m.my_numbers { -1004 if let IpAddr::V6(ip) = peer_sockaddr.ip() { -1005 if netwatch::ip::is_unicast_link_local(ip) { -1006 // We send these out, but ignore them for now. -1007 // TODO: teach the ping code to ping on all interfaces for these. -1008 continue; -1009 } -1010 } -1011 let ipp = IpPort::from(*peer_sockaddr); -1012 call_me_maybe_ipps.insert(ipp); -1013 self.udp_paths -1014 .paths -1015 .entry(ipp) -1016 .or_insert_with(|| { -1017 PathState::new( -1018 self.node_id, -1019 SendAddr::from(*peer_sockaddr), -1020 Source::Relay, -1021 now, -1022 ) -1023 }) -1024 .call_me_maybe_time -1025 .replace(now); -1026 } -1027 -1028 // Zero out all the last_ping times to force send_pings to send new ones, even if -1029 // it's been less than 5 seconds ago. Also clear pongs for direct addresses not -1030 // included in the updated set. -1031 for (ipp, st) in self.udp_paths.paths.iter_mut() { -1032 st.last_ping = None; -1033 if !call_me_maybe_ipps.contains(ipp) { -1034 // TODO: This seems like a weird way to signal that the endpoint no longer -1035 // thinks it has this IpPort as an available path. -1036 if st.recent_pong.is_some() { -1037 debug!(path=?ipp ,"clearing recent pong"); -1038 st.recent_pong = None; -1039 } -1040 } -1041 } -1042 // Clear trust on our best_addr if it is not included in the updated set. Also -1043 // clear the last call-me-maybe send time so we will send one again. -1044 if let Some(addr) = self.udp_paths.best_addr.addr() { -1045 let ipp: IpPort = addr.into(); -1046 if !call_me_maybe_ipps.contains(&ipp) { -1047 self.udp_paths -1048 .best_addr -1049 .clear_trust("best_addr not in new call-me-maybe"); -1050 self.last_call_me_maybe = None; -1051 } -1052 } -1053 debug!( -1054 paths = %summarize_node_paths(&self.udp_paths.paths), -1055 "updated endpoint paths from call-me-maybe", -1056 ); -1057 self.send_pings(now) -1058 } -1059 -1060 /// Marks this node as having received a UDP payload message. -1061 #[cfg(not(wasm_browser))] -1062 pub(super) fn receive_udp(&mut self, addr: IpPort, now: Instant) { -1063 let Some(state) = self.udp_paths.paths.get_mut(&addr) else { -1064 debug_assert!(false, "node map inconsistency by_ip_port <-> direct addr"); -1065 return; -1066 }; -1067 state.last_payload_msg = Some(now); -1068 self.last_used = Some(now); -1069 self.udp_paths -1070 .best_addr -1071 .reconfirm_if_used(addr.into(), BestAddrSource::Udp, now); -1072 } -1073 -1074 pub(super) fn receive_relay(&mut self, url: &RelayUrl, src: NodeId, now: Instant) { -1075 match self.relay_url.as_mut() { -1076 Some((current_home, state)) if current_home == url => { -1077 // We received on the expected url. update state. -1078 state.last_payload_msg = Some(now); -1079 } -1080 Some((_current_home, _state)) => { -1081 // we have a different url. we only update on ping, not on receive_relay. -1082 } -1083 None => { -1084 self.relay_url = Some(( -1085 url.clone(), -1086 PathState::with_last_payload( -1087 src, -1088 SendAddr::from(url.clone()), -1089 Source::Relay, -1090 now, -1091 ), -1092 )); -1093 } -1094 } -1095 self.last_used = Some(now); -1096 } -1097 -1098 pub(super) fn last_ping(&self, addr: &SendAddr) -> Option<Instant> { -1099 match addr { -1100 SendAddr::Udp(addr) => self -1101 .udp_paths -1102 .paths -1103 .get(&(*addr).into()) -1104 .and_then(|ep| ep.last_ping), -1105 SendAddr::Relay(url) => self -1106 .relay_url -1107 .as_ref() -1108 .filter(|(home_url, _state)| home_url == url) -1109 .and_then(|(_home_url, state)| state.last_ping), -1110 } -1111 } -1112 -1113 /// Checks if this `Endpoint` is currently actively being used. -1114 pub(super) fn is_active(&self, now: &Instant) -> bool { -1115 match self.last_used { -1116 Some(last_active) => now.duration_since(last_active) <= SESSION_ACTIVE_TIMEOUT, -1117 None => false, -1118 } -1119 } -1120 -1121 /// Send a heartbeat to the node to keep the connection alive, or trigger a full ping -1122 /// if necessary. -1123 #[instrument("stayin_alive", skip_all, fields(node = %self.node_id.fmt_short()))] -1124 pub(super) fn stayin_alive(&mut self) -> Vec<PingAction> { -1125 trace!("stayin_alive"); -1126 let now = Instant::now(); -1127 if !self.is_active(&now) { -1128 trace!("skipping stayin alive: session is inactive"); -1129 return Vec::new(); -1130 } -1131 -1132 // If we do not have an optimal addr, send pings to all known places. -1133 if self.want_call_me_maybe(&now) { -1134 debug!("sending a call-me-maybe"); -1135 return self.send_call_me_maybe(now, SendCallMeMaybe::Always); -1136 } -1137 -1138 // Send heartbeat ping to keep the current addr going as long as we need it. -1139 if let Some(udp_addr) = self.udp_paths.best_addr.addr() { -1140 let elapsed = self.last_ping(&SendAddr::Udp(udp_addr)).map(|l| now - l); -1141 // Send a ping if the last ping is older than 2 seconds. -1142 let needs_ping = match elapsed { -1143 Some(e) => e >= STAYIN_ALIVE_MIN_ELAPSED, -1144 None => false, -1145 }; -1146 -1147 if needs_ping { -1148 debug!( -1149 dst = %udp_addr, -1150 since_last_ping=?elapsed, -1151 "send stayin alive ping", -1152 ); -1153 if let Some(msg) = -1154 self.start_ping(SendAddr::Udp(udp_addr), DiscoPingPurpose::StayinAlive) -1155 { -1156 return vec![PingAction::SendPing(msg)]; -1157 } -1158 } -1159 } -1160 -1161 Vec::new() -1162 } -1163 -1164 /// Returns the addresses on which a payload should be sent right now. -1165 /// -1166 /// This is in the hot path of `.poll_send()`. -1167 #[instrument("get_send_addrs", skip_all, fields(node = %self.node_id.fmt_short()))] -1168 pub(crate) fn get_send_addrs( -1169 &mut self, -1170 have_ipv6: bool, -1171 metrics: &MagicsockMetrics, -1172 ) -> (Option<SocketAddr>, Option<RelayUrl>, Vec<PingAction>) { -1173 let now = Instant::now(); -1174 let prev = self.last_used.replace(now); -1175 if prev.is_none() { -1176 // this is the first time we are trying to connect to this node -1177 metrics.nodes_contacted.inc(); -1178 } -1179 let (udp_addr, relay_url) = self.addr_for_send(&now, have_ipv6, metrics); -1180 let mut ping_msgs = Vec::new(); -1181 -1182 if self.want_call_me_maybe(&now) { -1183 ping_msgs = self.send_call_me_maybe(now, SendCallMeMaybe::IfNoRecent); -1184 } -1185 -1186 trace!( -1187 ?udp_addr, -1188 ?relay_url, -1189 pings = %ping_msgs.len(), -1190 "found send address", -1191 ); -1192 -1193 (udp_addr, relay_url, ping_msgs) -1194 } -1195 -1196 /// Get the direct addresses for this endpoint. -1197 pub(super) fn direct_addresses(&self) -> impl Iterator<Item = IpPort> + '_ { -1198 self.udp_paths.paths.keys().copied() -1199 } -1200 -1201 #[cfg(test)] -1202 pub(super) fn direct_address_states(&self) -> impl Iterator<Item = (&IpPort, &PathState)> + '_ { -1203 self.udp_paths.paths.iter() -1204 } -1205 -1206 pub(super) fn last_used(&self) -> Option<Instant> { -1207 self.last_used -1208 } -1209} -1210 -1211impl From<RemoteInfo> for NodeAddr { -1212 fn from(info: RemoteInfo) -> Self { -1213 let direct_addresses = info -1214 .addrs -1215 .into_iter() -1216 .map(|info| info.addr) -1217 .collect::<BTreeSet<_>>(); -1218 -1219 NodeAddr { -1220 node_id: info.node_id, -1221 relay_url: info.relay_url.map(Into::into), -1222 direct_addresses, -1223 } -1224 } -1225} -1226 -1227/// Whether to send a call-me-maybe message after sending pings to all known paths. -1228/// -1229/// `IfNoRecent` will only send a call-me-maybe if no previous one was sent in the last -1230/// [`HEARTBEAT_INTERVAL`]. -1231#[derive(Debug)] -1232enum SendCallMeMaybe { -1233 Always, -1234 IfNoRecent, -1235} -1236 -1237#[derive(Debug, Clone, PartialEq, Eq, Hash)] -1238pub(super) struct PongReply { -1239 pub(super) latency: Duration, -1240 /// When we received the pong. -1241 pub(super) pong_at: Instant, -1242 /// The pong's src (usually same as endpoint map key). -1243 pub(super) from: SendAddr, -1244 /// What they reported they heard. -1245 pub(super) pong_src: SendAddr, -1246} -1247 -1248#[derive(Debug)] -1249pub(super) struct SentPing { -1250 pub(super) to: SendAddr, -1251 pub(super) at: Instant, -1252 #[allow(dead_code)] -1253 pub(super) purpose: DiscoPingPurpose, -1254 pub(super) _expiry_task: AbortOnDropHandle<()>, -1255} -1256 -1257/// The reason why a discovery ping message was sent. -1258#[derive(Debug, Clone, Copy, PartialEq, Eq)] -1259pub enum DiscoPingPurpose { -1260 /// The purpose of a ping was to see if a path was valid. -1261 Discovery, -1262 /// Ping to ensure the current route is still valid. -1263 StayinAlive, -1264 /// When a ping was received and no direct connection exists yet. -1265 /// -1266 /// When a ping was received we suspect a direct connection is possible. If we do not -1267 /// yet have one that triggers a ping, indicated with this reason. -1268 PingBack, -1269} -1270 -1271/// The type of control message we have received. -1272#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize, derive_more::Display)] -1273pub enum ControlMsg { -1274 /// We received a Ping from the node. -1275 #[display("ping←")] -1276 Ping, -1277 /// We received a Pong from the node. -1278 #[display("pong←")] -1279 Pong, -1280 /// We received a CallMeMaybe. -1281 #[display("call me")] -1282 CallMeMaybe, -1283} -1284 -1285/// Information about a *direct address*. -1286/// -1287/// The *direct addresses* of an iroh node are those that could be used by other nodes to -1288/// establish direct connectivity, depending on the network situation. Due to NAT configurations, -1289/// for example, not all direct addresses of a node are usable by all peers. -1290#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] -1291pub struct DirectAddrInfo { -1292 /// The UDP address reported by the remote node. -1293 pub addr: SocketAddr, -1294 /// The latency to the remote node over this network path. -1295 /// -1296 /// If there has never been any connectivity via this address no latency will be known. -1297 pub latency: Option<Duration>, -1298 /// Last control message received by this node about this address. -1299 /// -1300 /// This contains the elapsed duration since the control message was received and the -1301 /// kind of control message received at that time. Only the most recent control message -1302 /// is returned. -1303 /// -1304 /// Note that [`ControlMsg::CallMeMaybe`] is received via a relay path, while -1305 /// [`ControlMsg::Ping`] and [`ControlMsg::Pong`] are received on the path to -1306 /// [`DirectAddrInfo::addr`] itself and thus convey very different information. -1307 pub last_control: Option<(Duration, ControlMsg)>, -1308 /// Elapsed time since the last payload message was received on this network path. -1309 /// -1310 /// This indicates how long ago a QUIC datagram was received from the remote node sent -1311 /// from this [`DirectAddrInfo::addr`]. It indicates the network path was in use to -1312 /// transport payload data. -1313 pub last_payload: Option<Duration>, -1314 /// Elapsed time since this network path was known to exist. -1315 /// -1316 /// A network path is considered to exist only because the remote node advertised it. -1317 /// It may not mean the path is usable. However, if there was any communication with -1318 /// the remote node over this network path it also means the path exists. -1319 /// -1320 /// The elapsed time since *any* confirmation of the path's existence was received is -1321 /// returned. If the remote node moved networks and no longer has this path, this could -1322 /// be a long duration. If the path was added via [`Endpoint::add_node_addr`] or some -1323 /// node discovery the path may never have been known to exist. -1324 /// -1325 /// [`Endpoint::add_node_addr`]: crate::endpoint::Endpoint::add_node_addr -1326 pub last_alive: Option<Duration>, -1327 /// A [`HashMap`] of [`Source`]s to [`Duration`]s. -1328 /// -1329 /// The [`Duration`] indicates the elapsed time since this source last -1330 /// recorded this address. -1331 /// -1332 /// The [`Duration`] will always indicate the most recent time the source -1333 /// recorded this address. -1334 pub sources: HashMap<Source, Duration>, -1335} -1336 -1337/// Information about the network path to a remote node via a relay server. -1338#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] -1339pub struct RelayUrlInfo { -1340 /// The relay URL. -1341 pub relay_url: RelayUrl, -1342 /// Elapsed time since this relay path last received payload or control data. -1343 pub last_alive: Option<Duration>, -1344 /// Latency to the remote node over this relayed network path. -1345 pub latency: Option<Duration>, -1346} -1347 -1348impl From<(RelayUrl, PathState)> for RelayUrlInfo { -1349 fn from(value: (RelayUrl, PathState)) -> Self { -1350 RelayUrlInfo { -1351 relay_url: value.0, -1352 last_alive: value.1.last_alive().map(|i| i.elapsed()), -1353 latency: value.1.latency(), -1354 } -1355 } -1356} -1357 -1358impl From<RelayUrlInfo> for RelayUrl { -1359 fn from(value: RelayUrlInfo) -> Self { -1360 value.relay_url -1361 } -1362} -1363 -1364/// Details about a remote iroh node which is known to this node. -1365/// -1366/// Having details of a node does not mean it can be connected to, nor that it has ever been -1367/// connected to in the past. There are various reasons a node might be known: it could have -1368/// been manually added via [`Endpoint::add_node_addr`], it could have been added by some -1369/// discovery mechanism, the node could have contacted this node, etc. -1370/// -1371/// [`Endpoint::add_node_addr`]: crate::endpoint::Endpoint::add_node_addr -1372#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] -1373pub struct RemoteInfo { -1374 /// The globally unique identifier for this node. -1375 pub node_id: NodeId, -1376 /// Relay server information, if available. -1377 pub relay_url: Option<RelayUrlInfo>, -1378 /// The addresses at which this node might be reachable. -1379 /// -1380 /// Some of these addresses might only be valid for networks we are not part of, but the remote -1381 /// node might be a part of. -1382 pub addrs: Vec<DirectAddrInfo>, -1383 /// The type of connection we have to the node, either direct or over relay. -1384 pub conn_type: ConnectionType, -1385 /// The latency of the current network path to the remote node. -1386 pub latency: Option<Duration>, -1387 /// Time elapsed time since last we have sent to or received from the node. -1388 /// -1389 /// This is the duration since *any* data (payload or control messages) was sent or receive -1390 /// from the remote node. Note that sending to the remote node does not imply -1391 /// the remote node received anything. -1392 pub last_used: Option<Duration>, -1393} -1394 -1395impl RemoteInfo { -1396 /// Get the duration since the last activity we received from this endpoint -1397 /// on any of its direct addresses. -1398 pub fn last_received(&self) -> Option<Duration> { -1399 self.addrs -1400 .iter() -1401 .filter_map(|addr| addr.last_control.map(|x| x.0).min(addr.last_payload)) -1402 .min() -1403 } -1404 -1405 /// Whether there is a possible known network path to the remote node. -1406 /// -1407 /// Note that this does not provide any guarantees of whether any network path is -1408 /// usable. -1409 pub fn has_send_address(&self) -> bool { -1410 self.relay_url.is_some() || !self.addrs.is_empty() -1411 } -1412 -1413 /// Returns a deduplicated list of [`Source`]s merged from all address in the [`RemoteInfo`]. -1414 /// -1415 /// Deduplication is on the (`Source`, `Duration`) tuple, so you will get multiple [`Source`]s -1416 /// for each `Source` variant, if different addresses were discovered from the same [`Source`] -1417 /// at different times. -1418 /// -1419 /// The list is sorted from least to most recent [`Source`]. -1420 pub fn sources(&self) -> Vec<(Source, Duration)> { -1421 let mut sources = vec![]; -1422 for addr in &self.addrs { -1423 for source in &addr.sources { -1424 let source = (source.0.clone(), *source.1); -1425 if !sources.contains(&source) { -1426 sources.push(source) -1427 } -1428 } -1429 } -1430 sources.sort_by(|a, b| b.1.cmp(&a.1)); -1431 sources -1432 } -1433} -1434 -1435/// The type of connection we have to the endpoint. -1436#[derive(derive_more::Display, Default, Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] -1437pub enum ConnectionType { -1438 /// Direct UDP connection -1439 #[display("direct({_0})")] -1440 Direct(SocketAddr), -1441 /// Relay connection over relay -1442 #[display("relay({_0})")] -1443 Relay(RelayUrl), -1444 /// Both a UDP and a relay connection are used. -1445 /// -1446 /// This is the case if we do have a UDP address, but are missing a recent confirmation that -1447 /// the address works. -1448 #[display("mixed(udp: {_0}, relay: {_1})")] -1449 Mixed(SocketAddr, RelayUrl), -1450 /// We have no verified connection to this PublicKey -1451 #[default] -1452 #[display("none")] -1453 None, -1454} -1455 -1456#[cfg(test)] -1457mod tests { -1458 use std::{collections::BTreeMap, net::Ipv4Addr}; -1459 -1460 use best_addr::BestAddr; -1461 use iroh_base::SecretKey; -1462 -1463 use super::*; -1464 use crate::magicsock::node_map::{NodeMap, NodeMapInner}; -1465 -1466 #[test] -1467 fn test_remote_infos() { -1468 let now = Instant::now(); -1469 let elapsed = Duration::from_secs(3); -1470 let later = now + elapsed; -1471 let send_addr: RelayUrl = "https://my-relay.com".parse().unwrap(); -1472 let pong_src = SendAddr::Udp("0.0.0.0:1".parse().unwrap()); -1473 let latency = Duration::from_millis(50); -1474 -1475 let relay_and_state = |node_id: NodeId, url: RelayUrl| { -1476 let relay_state = PathState::with_pong_reply( -1477 node_id, -1478 PongReply { -1479 latency, -1480 pong_at: now, -1481 from: SendAddr::Relay(send_addr.clone()), -1482 pong_src: pong_src.clone(), -1483 }, -1484 ); -1485 Some((url, relay_state)) -1486 }; -1487 -1488 // endpoint with a `best_addr` that has a latency but no relay -1489 let (a_endpoint, a_socket_addr) = { -1490 let key = SecretKey::generate(rand::thread_rng()); -1491 let node_id = key.public(); -1492 let ip_port = IpPort { -1493 ip: Ipv4Addr::UNSPECIFIED.into(), -1494 port: 10, -1495 }; -1496 let endpoint_state = BTreeMap::from([( -1497 ip_port, -1498 PathState::with_pong_reply( -1499 node_id, -1500 PongReply { -1501 latency, -1502 pong_at: now, -1503 from: SendAddr::Udp(ip_port.into()), -1504 pong_src: pong_src.clone(), -1505 }, -1506 ), -1507 )]); -1508 ( -1509 NodeState { -1510 id: 0, -1511 quic_mapped_addr: NodeIdMappedAddr::generate(), -1512 node_id: key.public(), -1513 last_full_ping: None, -1514 relay_url: None, -1515 udp_paths: NodeUdpPaths::from_parts( -1516 endpoint_state, -1517 BestAddr::from_parts( -1518 ip_port.into(), -1519 latency, -1520 now, -1521 now + Duration::from_secs(100), -1522 ), -1523 ), -1524 sent_pings: HashMap::new(), -1525 last_used: Some(now), -1526 last_call_me_maybe: None, -1527 conn_type: Watchable::new(ConnectionType::Direct(ip_port.into())), -1528 has_been_direct: true, -1529 #[cfg(any(test, feature = "test-utils"))] -1530 path_selection: PathSelection::default(), -1531 }, -1532 ip_port.into(), -1533 ) -1534 }; -1535 // endpoint w/ no best addr but a relay w/ latency -1536 let b_endpoint = { -1537 // let socket_addr = "0.0.0.0:9".parse().unwrap(); -1538 let key = SecretKey::generate(rand::thread_rng()); -1539 NodeState { -1540 id: 1, -1541 quic_mapped_addr: NodeIdMappedAddr::generate(), -1542 node_id: key.public(), -1543 last_full_ping: None, -1544 relay_url: relay_and_state(key.public(), send_addr.clone()), -1545 udp_paths: NodeUdpPaths::new(), -1546 sent_pings: HashMap::new(), -1547 last_used: Some(now), -1548 last_call_me_maybe: None, -1549 conn_type: Watchable::new(ConnectionType::Relay(send_addr.clone())), -1550 has_been_direct: false, -1551 #[cfg(any(test, feature = "test-utils"))] -1552 path_selection: PathSelection::default(), -1553 } -1554 }; -1555 -1556 // endpoint w/ no best addr but a relay w/ no latency -1557 let c_endpoint = { -1558 // let socket_addr = "0.0.0.0:8".parse().unwrap(); -1559 let key = SecretKey::generate(rand::thread_rng()); -1560 NodeState { -1561 id: 2, -1562 quic_mapped_addr: NodeIdMappedAddr::generate(), -1563 node_id: key.public(), -1564 last_full_ping: None, -1565 relay_url: Some(( -1566 send_addr.clone(), -1567 PathState::new( -1568 key.public(), -1569 SendAddr::from(send_addr.clone()), -1570 Source::App, -1571 now, -1572 ), -1573 )), -1574 udp_paths: NodeUdpPaths::new(), -1575 sent_pings: HashMap::new(), -1576 last_used: Some(now), -1577 last_call_me_maybe: None, -1578 conn_type: Watchable::new(ConnectionType::Relay(send_addr.clone())), -1579 has_been_direct: false, -1580 #[cfg(any(test, feature = "test-utils"))] -1581 path_selection: PathSelection::default(), -1582 } -1583 }; -1584 -1585 // endpoint w/ expired best addr and relay w/ latency -1586 let (d_endpoint, d_socket_addr) = { -1587 let socket_addr: SocketAddr = "0.0.0.0:7".parse().unwrap(); -1588 let expired = now.checked_sub(Duration::from_secs(100)).unwrap(); -1589 let key = SecretKey::generate(rand::thread_rng()); -1590 let node_id = key.public(); -1591 let endpoint_state = BTreeMap::from([( -1592 IpPort::from(socket_addr), -1593 PathState::with_pong_reply( -1594 node_id, -1595 PongReply { -1596 latency, -1597 pong_at: now, -1598 from: SendAddr::Udp(socket_addr), -1599 pong_src: pong_src.clone(), -1600 }, -1601 ), -1602 )]); -1603 ( -1604 NodeState { -1605 id: 3, -1606 quic_mapped_addr: NodeIdMappedAddr::generate(), -1607 node_id: key.public(), -1608 last_full_ping: None, -1609 relay_url: relay_and_state(key.public(), send_addr.clone()), -1610 udp_paths: NodeUdpPaths::from_parts( -1611 endpoint_state, -1612 BestAddr::from_parts(socket_addr, Duration::from_millis(80), now, expired), -1613 ), -1614 sent_pings: HashMap::new(), -1615 last_used: Some(now), -1616 last_call_me_maybe: None, -1617 conn_type: Watchable::new(ConnectionType::Mixed( -1618 socket_addr, -1619 send_addr.clone(), -1620 )), -1621 has_been_direct: false, -1622 #[cfg(any(test, feature = "test-utils"))] -1623 path_selection: PathSelection::default(), -1624 }, -1625 socket_addr, -1626 ) -1627 }; -1628 -1629 let mut expect = Vec::from([ -1630 RemoteInfo { -1631 node_id: a_endpoint.node_id, -1632 relay_url: None, -1633 addrs: Vec::from([DirectAddrInfo { -1634 addr: a_socket_addr, -1635 latency: Some(latency), -1636 last_control: Some((elapsed, ControlMsg::Pong)), -1637 last_payload: None, -1638 last_alive: Some(elapsed), -1639 sources: HashMap::new(), -1640 }]), -1641 conn_type: ConnectionType::Direct(a_socket_addr), -1642 latency: Some(latency), -1643 last_used: Some(elapsed), -1644 }, -1645 RemoteInfo { -1646 node_id: b_endpoint.node_id, -1647 relay_url: Some(RelayUrlInfo { -1648 relay_url: b_endpoint.relay_url.as_ref().unwrap().0.clone(), -1649 last_alive: None, -1650 latency: Some(latency), -1651 }), -1652 addrs: Vec::new(), -1653 conn_type: ConnectionType::Relay(send_addr.clone()), -1654 latency: Some(latency), -1655 last_used: Some(elapsed), -1656 }, -1657 RemoteInfo { -1658 node_id: c_endpoint.node_id, -1659 relay_url: Some(RelayUrlInfo { -1660 relay_url: c_endpoint.relay_url.as_ref().unwrap().0.clone(), -1661 last_alive: None, -1662 latency: None, -1663 }), -1664 addrs: Vec::new(), -1665 conn_type: ConnectionType::Relay(send_addr.clone()), -1666 latency: None, -1667 last_used: Some(elapsed), -1668 }, -1669 RemoteInfo { -1670 node_id: d_endpoint.node_id, -1671 relay_url: Some(RelayUrlInfo { -1672 relay_url: d_endpoint.relay_url.as_ref().unwrap().0.clone(), -1673 last_alive: None, -1674 latency: Some(latency), -1675 }), -1676 addrs: Vec::from([DirectAddrInfo { -1677 addr: d_socket_addr, -1678 latency: Some(latency), -1679 last_control: Some((elapsed, ControlMsg::Pong)), -1680 last_payload: None, -1681 last_alive: Some(elapsed), -1682 sources: HashMap::new(), -1683 }]), -1684 conn_type: ConnectionType::Mixed(d_socket_addr, send_addr.clone()), -1685 latency: Some(Duration::from_millis(50)), -1686 last_used: Some(elapsed), -1687 }, -1688 ]); -1689 -1690 let node_map = NodeMap::from_inner(NodeMapInner { -1691 by_node_key: HashMap::from([ -1692 (a_endpoint.node_id, a_endpoint.id), -1693 (b_endpoint.node_id, b_endpoint.id), -1694 (c_endpoint.node_id, c_endpoint.id), -1695 (d_endpoint.node_id, d_endpoint.id), -1696 ]), -1697 by_ip_port: HashMap::from([ -1698 (a_socket_addr.into(), a_endpoint.id), -1699 (d_socket_addr.into(), d_endpoint.id), -1700 ]), -1701 by_quic_mapped_addr: HashMap::from([ -1702 (a_endpoint.quic_mapped_addr, a_endpoint.id), -1703 (b_endpoint.quic_mapped_addr, b_endpoint.id), -1704 (c_endpoint.quic_mapped_addr, c_endpoint.id), -1705 (d_endpoint.quic_mapped_addr, d_endpoint.id), -1706 ]), -1707 by_id: HashMap::from([ -1708 (a_endpoint.id, a_endpoint), -1709 (b_endpoint.id, b_endpoint), -1710 (c_endpoint.id, c_endpoint), -1711 (d_endpoint.id, d_endpoint), -1712 ]), -1713 next_id: 5, -1714 path_selection: PathSelection::default(), -1715 }); -1716 let mut got = node_map.list_remote_infos(later); -1717 got.sort_by_key(|p| p.node_id); -1718 expect.sort_by_key(|p| p.node_id); -1719 remove_non_deterministic_fields(&mut got); -1720 assert_eq!(expect, got); -1721 } -1722 -1723 fn remove_non_deterministic_fields(infos: &mut [RemoteInfo]) { -1724 for info in infos.iter_mut() { -1725 if info.relay_url.is_some() { -1726 info.relay_url.as_mut().unwrap().last_alive = None; -1727 } -1728 } -1729 } -1730 -1731 #[test] -1732 fn test_prune_direct_addresses() { -1733 // When we handle a call-me-maybe with more than MAX_INACTIVE_DIRECT_ADDRESSES we do -1734 // not want to prune them right away but send pings to all of them. -1735 -1736 let key = SecretKey::generate(rand::thread_rng()); -1737 let opts = Options { -1738 node_id: key.public(), -1739 relay_url: None, -1740 active: true, -1741 source: crate::magicsock::Source::NamedApp { -1742 name: "test".into(), -1743 }, -1744 path_selection: PathSelection::default(), -1745 }; -1746 let mut ep = NodeState::new(0, opts); -1747 -1748 let my_numbers_count: u16 = (MAX_INACTIVE_DIRECT_ADDRESSES + 5).try_into().unwrap(); -1749 let my_numbers = (0u16..my_numbers_count) -1750 .map(|i| SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 1000 + i)) -1751 .collect(); -1752 let call_me_maybe = disco::CallMeMaybe { my_numbers }; +589 // We send pings regardless of whether we have a RelayUrl. If we were given any +590 // direct address paths to contact but no RelayUrl, we still need to send a DISCO +591 // ping to the direct address paths so that the other node will learn about us and +592 // accepts the connection. +593 let mut msgs = self.send_pings(now); +594 +595 if let Some(url) = self.relay_url() { +596 debug!(%url, "queue call-me-maybe"); +597 msgs.push(PingAction::SendCallMeMaybe { +598 relay_url: url, +599 dst_node: self.node_id, +600 }); +601 self.last_call_me_maybe = Some(now); +602 } else { +603 debug!("can not send call-me-maybe, no relay URL"); +604 } +605 +606 msgs +607 } +608 +609 /// Send DISCO Pings to all the paths of this node. +610 /// +611 /// Any paths to the node which have not been recently pinged will be sent a disco +612 /// ping. +613 /// +614 /// The caller is responsible for sending the messages. +615 #[must_use = "actions must be handled"] +616 fn send_pings(&mut self, now: Instant) -> Vec<PingAction> { +617 // We allocate +1 in case the caller wants to add a call-me-maybe message. +618 let mut ping_msgs = Vec::with_capacity(self.udp_paths.paths.len() + 1); +619 +620 if let Some((url, state)) = self.relay_url.as_ref() { +621 if state.needs_ping(&now) { +622 debug!(%url, "relay path needs ping"); +623 if let Some(msg) = +624 self.start_ping(SendAddr::Relay(url.clone()), DiscoPingPurpose::Discovery) +625 { +626 ping_msgs.push(PingAction::SendPing(msg)) +627 } +628 } +629 } +630 +631 #[cfg(any(test, feature = "test-utils"))] +632 if self.path_selection == PathSelection::RelayOnly { +633 warn!("in `RelayOnly` mode, ignoring request to respond to a hole punching attempt."); +634 return ping_msgs; +635 } +636 +637 self.prune_direct_addresses(); +638 let mut ping_dsts = String::from("["); +639 self.udp_paths +640 .paths +641 .iter() +642 .filter_map(|(ipp, state)| state.needs_ping(&now).then_some(*ipp)) +643 .filter_map(|ipp| { +644 self.start_ping(SendAddr::Udp(ipp.into()), DiscoPingPurpose::Discovery) +645 }) +646 .for_each(|msg| { +647 use std::fmt::Write; +648 write!(&mut ping_dsts, " {} ", msg.dst).ok(); +649 ping_msgs.push(PingAction::SendPing(msg)); +650 }); +651 ping_dsts.push(']'); +652 debug!( +653 %ping_dsts, +654 dst = %self.node_id.fmt_short(), +655 paths = %summarize_node_paths(&self.udp_paths.paths), +656 "sending pings to node", +657 ); +658 self.last_full_ping.replace(now); +659 ping_msgs +660 } +661 +662 pub(super) fn update_from_node_addr( +663 &mut self, +664 new_relay_url: Option<&RelayUrl>, +665 new_addrs: &BTreeSet<SocketAddr>, +666 source: super::Source, +667 metrics: &MagicsockMetrics, +668 ) { +669 if self.udp_paths.best_addr.is_empty() { +670 // we do not have a direct connection, so changing the relay information may +671 // have an effect on our connection status +672 if self.relay_url.is_none() && new_relay_url.is_some() { +673 // we did not have a relay connection before, but now we do +674 metrics.num_relay_conns_added.inc(); +675 } else if self.relay_url.is_some() && new_relay_url.is_none() { +676 // we had a relay connection before but do not have one now +677 metrics.num_relay_conns_removed.inc(); +678 } +679 } +680 +681 let now = Instant::now(); +682 +683 if new_relay_url.is_some() && new_relay_url != self.relay_url().as_ref() { +684 debug!( +685 "Changing relay node from {:?} to {:?}", +686 self.relay_url, new_relay_url +687 ); +688 self.relay_url = new_relay_url.map(|url| { +689 ( +690 url.clone(), +691 PathState::new(self.node_id, url.clone().into(), source.clone(), now), +692 ) +693 }); +694 } +695 +696 for &addr in new_addrs.iter() { +697 self.udp_paths +698 .paths +699 .entry(addr.into()) +700 .and_modify(|path_state| { +701 path_state.add_source(source.clone(), now); +702 }) +703 .or_insert_with(|| { +704 PathState::new(self.node_id, SendAddr::from(addr), source.clone(), now) +705 }); +706 } +707 let paths = summarize_node_paths(&self.udp_paths.paths); +708 debug!(new = ?new_addrs , %paths, "added new direct paths for endpoint"); +709 } +710 +711 /// Clears all the endpoint's p2p state, reverting it to a relay-only endpoint. +712 #[instrument(skip_all, fields(node = %self.node_id.fmt_short()))] +713 pub(super) fn reset(&mut self) { +714 self.last_full_ping = None; +715 self.udp_paths +716 .best_addr +717 .clear(ClearReason::Reset, self.relay_url.is_some()); +718 +719 for es in self.udp_paths.paths.values_mut() { +720 es.last_ping = None; +721 } +722 } +723 +724 /// Handle a received Disco Ping. +725 /// +726 /// - Ensures the paths the ping was received on is a known path for this endpoint. +727 /// +728 /// - If there is no best_addr for this endpoint yet, sends a ping itself to try and +729 /// establish one. +730 /// +731 /// This is called once we've already verified that we got a valid discovery message +732 /// from `self` via ep. +733 pub(super) fn handle_ping( +734 &mut self, +735 path: SendAddr, +736 tx_id: stun::TransactionId, +737 ) -> PingHandled { +738 let now = Instant::now(); +739 +740 let role = match path { +741 SendAddr::Udp(addr) => match self.udp_paths.paths.entry(addr.into()) { +742 Entry::Occupied(mut occupied) => occupied.get_mut().handle_ping(tx_id, now), +743 Entry::Vacant(vacant) => { +744 info!(%addr, "new direct addr for node"); +745 vacant.insert(PathState::with_ping( +746 self.node_id, +747 path.clone(), +748 tx_id, +749 Source::Udp, +750 now, +751 )); +752 PingRole::NewPath +753 } +754 }, +755 SendAddr::Relay(ref url) => { +756 match self.relay_url.as_mut() { +757 Some((home_url, _state)) if home_url != url => { +758 // either the node changed relays or we didn't have a relay address for the +759 // node. In both cases, trust the new confirmed url +760 info!(%url, "new relay addr for node"); +761 self.relay_url = Some(( +762 url.clone(), +763 PathState::with_ping( +764 self.node_id, +765 path.clone(), +766 tx_id, +767 Source::Relay, +768 now, +769 ), +770 )); +771 PingRole::NewPath +772 } +773 Some((_home_url, state)) => state.handle_ping(tx_id, now), +774 None => { +775 info!(%url, "new relay addr for node"); +776 self.relay_url = Some(( +777 url.clone(), +778 PathState::with_ping( +779 self.node_id, +780 path.clone(), +781 tx_id, +782 Source::Relay, +783 now, +784 ), +785 )); +786 PingRole::NewPath +787 } +788 } +789 } +790 }; +791 event!( +792 target: "iroh::_events::ping::recv", +793 Level::DEBUG, +794 remote_node = %self.node_id.fmt_short(), +795 src = ?path, +796 txn = ?tx_id, +797 ?role, +798 ); +799 +800 if matches!(path, SendAddr::Udp(_)) && matches!(role, PingRole::NewPath) { +801 self.prune_direct_addresses(); +802 } +803 +804 // if the endpoint does not yet have a best_addrr +805 let needs_ping_back = if matches!(path, SendAddr::Udp(_)) +806 && matches!( +807 self.udp_paths.best_addr.state(now), +808 best_addr::State::Empty | best_addr::State::Outdated(_) +809 ) { +810 // We also need to send a ping to make this path available to us as well. This +811 // is always sent together with a pong. So in the worst case the pong gets lost +812 // and this ping does not. In that case we ping-pong until both sides have +813 // received at least one pong. Once both sides have received one pong they both +814 // have a best_addr and this ping will stop being sent. +815 self.start_ping(path, DiscoPingPurpose::PingBack) +816 } else { +817 None +818 }; +819 +820 debug!( +821 ?role, +822 needs_ping_back = ?needs_ping_back.is_some(), +823 paths = %summarize_node_paths(&self.udp_paths.paths), +824 "endpoint handled ping", +825 ); +826 PingHandled { +827 role, +828 needs_ping_back, +829 } +830 } +831 +832 /// Prune inactive paths. +833 /// +834 /// This trims the list of inactive paths for an endpoint. At most +835 /// [`MAX_INACTIVE_DIRECT_ADDRESSES`] are kept. +836 pub(super) fn prune_direct_addresses(&mut self) { +837 // prune candidates are addresses that are not active +838 let mut prune_candidates: Vec<_> = self +839 .udp_paths +840 .paths +841 .iter() +842 .filter(|(_ip_port, state)| !state.is_active()) +843 .map(|(ip_port, state)| (*ip_port, state.last_alive())) +844 .filter(|(_ipp, last_alive)| match last_alive { +845 Some(last_seen) => last_seen.elapsed() > LAST_ALIVE_PRUNE_DURATION, +846 None => true, +847 }) +848 .collect(); +849 let prune_count = prune_candidates +850 .len() +851 .saturating_sub(MAX_INACTIVE_DIRECT_ADDRESSES); +852 if prune_count == 0 { +853 // nothing to do, within limits +854 debug!( +855 paths = %summarize_node_paths(&self.udp_paths.paths), +856 "prune addresses: {prune_count} pruned", +857 ); +858 return; +859 } +860 +861 // sort leaving the worst addresses first (never contacted) and better ones (most recently +862 // used ones) last +863 prune_candidates.sort_unstable_by_key(|(_ip_port, last_alive)| *last_alive); +864 prune_candidates.truncate(prune_count); +865 for (ip_port, _last_alive) in prune_candidates.into_iter() { +866 self.remove_direct_addr(&ip_port, ClearReason::Inactive) +867 } +868 debug!( +869 paths = %summarize_node_paths(&self.udp_paths.paths), +870 "prune addresses: {prune_count} pruned", +871 ); +872 } +873 +874 /// Called when connectivity changes enough that we should question our earlier +875 /// assumptions about which paths work. +876 #[instrument("disco", skip_all, fields(node = %self.node_id.fmt_short()))] +877 pub(super) fn note_connectivity_change(&mut self) { +878 self.udp_paths.best_addr.clear_trust("connectivity changed"); +879 for es in self.udp_paths.paths.values_mut() { +880 es.clear(); +881 } +882 } +883 +884 /// Handles a Pong message (a reply to an earlier ping). +885 /// +886 /// It reports the address and key that should be inserted for the endpoint if any. +887 #[instrument(skip(self))] +888 pub(super) fn handle_pong( +889 &mut self, +890 m: &disco::Pong, +891 src: SendAddr, +892 ) -> Option<(SocketAddr, PublicKey)> { +893 event!( +894 target: "iroh::_events::pong::recv", +895 Level::DEBUG, +896 remote_node = self.node_id.fmt_short(), +897 ?src, +898 txn = ?m.tx_id, +899 ); +900 let is_relay = src.is_relay(); +901 match self.sent_pings.remove(&m.tx_id) { +902 None => { +903 // This is not a pong for a ping we sent. In reality however we probably +904 // did send this ping but it has timed-out by the time we receive this pong +905 // so we removed the state already. +906 debug!(tx = %HEXLOWER.encode(&m.tx_id), "received unknown pong (did it timeout?)"); +907 None +908 } +909 Some(sp) => { +910 let mut node_map_insert = None; +911 +912 let now = Instant::now(); +913 let latency = now - sp.at; +914 +915 debug!( +916 tx = %HEXLOWER.encode(&m.tx_id), +917 src = %src, +918 reported_ping_src = %m.ping_observed_addr, +919 ping_dst = %sp.to, +920 is_relay = %src.is_relay(), +921 latency = %latency.as_millis(), +922 "received pong", +923 ); +924 +925 match src { +926 SendAddr::Udp(addr) => { +927 match self.udp_paths.paths.get_mut(&addr.into()) { +928 None => { +929 warn!("ignoring pong: no state for src addr"); +930 // This is no longer an endpoint we care about. +931 return node_map_insert; +932 } +933 Some(st) => { +934 node_map_insert = Some((addr, self.node_id)); +935 st.add_pong_reply(PongReply { +936 latency, +937 pong_at: now, +938 from: src, +939 pong_src: m.ping_observed_addr.clone(), +940 }); +941 } +942 } +943 debug!( +944 paths = %summarize_node_paths(&self.udp_paths.paths), +945 "handled pong", +946 ); +947 } +948 SendAddr::Relay(ref url) => match self.relay_url.as_mut() { +949 Some((home_url, state)) if home_url == url => { +950 state.add_pong_reply(PongReply { +951 latency, +952 pong_at: now, +953 from: src, +954 pong_src: m.ping_observed_addr.clone(), +955 }); +956 } +957 other => { +958 // if we are here then we sent this ping, but the url changed +959 // waiting for the response. It was either set to None or changed to +960 // another relay. This should either never happen or be extremely +961 // unlikely. Log and ignore for now +962 warn!( +963 stored=?other, +964 received=?url, +965 "ignoring pong via relay for different relay from last one", +966 ); +967 } +968 }, +969 } +970 +971 // Promote this pong response to our current best address if it's lower latency. +972 // TODO(bradfitz): decide how latency vs. preference order affects decision +973 if let SendAddr::Udp(to) = sp.to { +974 debug_assert!(!is_relay, "mismatching relay & udp"); +975 self.udp_paths.best_addr.insert_if_better_or_reconfirm( +976 to, +977 latency, +978 best_addr::Source::ReceivedPong, +979 now, +980 ); +981 } +982 +983 node_map_insert +984 } +985 } +986 } +987 +988 /// Handles a DISCO CallMeMaybe discovery message. +989 /// +990 /// The contract for use of this message is that the node has already pinged to us via +991 /// UDP, so their stateful firewall should be open. Now we can Ping back and make it +992 /// through. +993 /// +994 /// However if the remote side has no direct path information to us, they would not have +995 /// had any [`IpPort`]s to send pings to and our pings might end up blocked. But at +996 /// least open the firewalls on our side, giving the other side another change of making +997 /// it through when it pings in response. +998 pub(super) fn handle_call_me_maybe(&mut self, m: disco::CallMeMaybe) -> Vec<PingAction> { +999 let now = Instant::now(); +1000 let mut call_me_maybe_ipps = BTreeSet::new(); +1001 +1002 for peer_sockaddr in &m.my_numbers { +1003 if let IpAddr::V6(ip) = peer_sockaddr.ip() { +1004 if netwatch::ip::is_unicast_link_local(ip) { +1005 // We send these out, but ignore them for now. +1006 // TODO: teach the ping code to ping on all interfaces for these. +1007 continue; +1008 } +1009 } +1010 let ipp = IpPort::from(*peer_sockaddr); +1011 call_me_maybe_ipps.insert(ipp); +1012 self.udp_paths +1013 .paths +1014 .entry(ipp) +1015 .or_insert_with(|| { +1016 PathState::new( +1017 self.node_id, +1018 SendAddr::from(*peer_sockaddr), +1019 Source::Relay, +1020 now, +1021 ) +1022 }) +1023 .call_me_maybe_time +1024 .replace(now); +1025 } +1026 +1027 // Zero out all the last_ping times to force send_pings to send new ones, even if +1028 // it's been less than 5 seconds ago. Also clear pongs for direct addresses not +1029 // included in the updated set. +1030 for (ipp, st) in self.udp_paths.paths.iter_mut() { +1031 st.last_ping = None; +1032 if !call_me_maybe_ipps.contains(ipp) { +1033 // TODO: This seems like a weird way to signal that the endpoint no longer +1034 // thinks it has this IpPort as an available path. +1035 if st.recent_pong.is_some() { +1036 debug!(path=?ipp ,"clearing recent pong"); +1037 st.recent_pong = None; +1038 } +1039 } +1040 } +1041 // Clear trust on our best_addr if it is not included in the updated set. Also +1042 // clear the last call-me-maybe send time so we will send one again. +1043 if let Some(addr) = self.udp_paths.best_addr.addr() { +1044 let ipp: IpPort = addr.into(); +1045 if !call_me_maybe_ipps.contains(&ipp) { +1046 self.udp_paths +1047 .best_addr +1048 .clear_trust("best_addr not in new call-me-maybe"); +1049 self.last_call_me_maybe = None; +1050 } +1051 } +1052 debug!( +1053 paths = %summarize_node_paths(&self.udp_paths.paths), +1054 "updated endpoint paths from call-me-maybe", +1055 ); +1056 self.send_pings(now) +1057 } +1058 +1059 /// Marks this node as having received a UDP payload message. +1060 #[cfg(not(wasm_browser))] +1061 pub(super) fn receive_udp(&mut self, addr: IpPort, now: Instant) { +1062 let Some(state) = self.udp_paths.paths.get_mut(&addr) else { +1063 debug_assert!(false, "node map inconsistency by_ip_port <-> direct addr"); +1064 return; +1065 }; +1066 state.last_payload_msg = Some(now); +1067 self.last_used = Some(now); +1068 self.udp_paths +1069 .best_addr +1070 .reconfirm_if_used(addr.into(), BestAddrSource::Udp, now); +1071 } +1072 +1073 pub(super) fn receive_relay(&mut self, url: &RelayUrl, src: NodeId, now: Instant) { +1074 match self.relay_url.as_mut() { +1075 Some((current_home, state)) if current_home == url => { +1076 // We received on the expected url. update state. +1077 state.last_payload_msg = Some(now); +1078 } +1079 Some((_current_home, _state)) => { +1080 // we have a different url. we only update on ping, not on receive_relay. +1081 } +1082 None => { +1083 self.relay_url = Some(( +1084 url.clone(), +1085 PathState::with_last_payload( +1086 src, +1087 SendAddr::from(url.clone()), +1088 Source::Relay, +1089 now, +1090 ), +1091 )); +1092 } +1093 } +1094 self.last_used = Some(now); +1095 } +1096 +1097 pub(super) fn last_ping(&self, addr: &SendAddr) -> Option<Instant> { +1098 match addr { +1099 SendAddr::Udp(addr) => self +1100 .udp_paths +1101 .paths +1102 .get(&(*addr).into()) +1103 .and_then(|ep| ep.last_ping), +1104 SendAddr::Relay(url) => self +1105 .relay_url +1106 .as_ref() +1107 .filter(|(home_url, _state)| home_url == url) +1108 .and_then(|(_home_url, state)| state.last_ping), +1109 } +1110 } +1111 +1112 /// Checks if this `Endpoint` is currently actively being used. +1113 pub(super) fn is_active(&self, now: &Instant) -> bool { +1114 match self.last_used { +1115 Some(last_active) => now.duration_since(last_active) <= SESSION_ACTIVE_TIMEOUT, +1116 None => false, +1117 } +1118 } +1119 +1120 /// Send a heartbeat to the node to keep the connection alive, or trigger a full ping +1121 /// if necessary. +1122 #[instrument("stayin_alive", skip_all, fields(node = %self.node_id.fmt_short()))] +1123 pub(super) fn stayin_alive(&mut self) -> Vec<PingAction> { +1124 trace!("stayin_alive"); +1125 let now = Instant::now(); +1126 if !self.is_active(&now) { +1127 trace!("skipping stayin alive: session is inactive"); +1128 return Vec::new(); +1129 } +1130 +1131 // If we do not have an optimal addr, send pings to all known places. +1132 if self.want_call_me_maybe(&now) { +1133 debug!("sending a call-me-maybe"); +1134 return self.send_call_me_maybe(now, SendCallMeMaybe::Always); +1135 } +1136 +1137 // Send heartbeat ping to keep the current addr going as long as we need it. +1138 if let Some(udp_addr) = self.udp_paths.best_addr.addr() { +1139 let elapsed = self.last_ping(&SendAddr::Udp(udp_addr)).map(|l| now - l); +1140 // Send a ping if the last ping is older than 2 seconds. +1141 let needs_ping = match elapsed { +1142 Some(e) => e >= STAYIN_ALIVE_MIN_ELAPSED, +1143 None => false, +1144 }; +1145 +1146 if needs_ping { +1147 debug!( +1148 dst = %udp_addr, +1149 since_last_ping=?elapsed, +1150 "send stayin alive ping", +1151 ); +1152 if let Some(msg) = +1153 self.start_ping(SendAddr::Udp(udp_addr), DiscoPingPurpose::StayinAlive) +1154 { +1155 return vec![PingAction::SendPing(msg)]; +1156 } +1157 } +1158 } +1159 +1160 Vec::new() +1161 } +1162 +1163 /// Returns the addresses on which a payload should be sent right now. +1164 /// +1165 /// This is in the hot path of `.poll_send()`. +1166 #[instrument("get_send_addrs", skip_all, fields(node = %self.node_id.fmt_short()))] +1167 pub(crate) fn get_send_addrs( +1168 &mut self, +1169 have_ipv6: bool, +1170 metrics: &MagicsockMetrics, +1171 ) -> (Option<SocketAddr>, Option<RelayUrl>, Vec<PingAction>) { +1172 let now = Instant::now(); +1173 let prev = self.last_used.replace(now); +1174 if prev.is_none() { +1175 // this is the first time we are trying to connect to this node +1176 metrics.nodes_contacted.inc(); +1177 } +1178 let (udp_addr, relay_url) = self.addr_for_send(&now, have_ipv6, metrics); +1179 +1180 let ping_msgs = if self.want_call_me_maybe(&now) { +1181 self.send_call_me_maybe(now, SendCallMeMaybe::IfNoRecent) +1182 } else { +1183 Vec::new() +1184 }; +1185 trace!( +1186 ?udp_addr, +1187 ?relay_url, +1188 pings = %ping_msgs.len(), +1189 "found send address", +1190 ); +1191 (udp_addr, relay_url, ping_msgs) +1192 } +1193 +1194 /// Get the direct addresses for this endpoint. +1195 pub(super) fn direct_addresses(&self) -> impl Iterator<Item = IpPort> + '_ { +1196 self.udp_paths.paths.keys().copied() +1197 } +1198 +1199 #[cfg(test)] +1200 pub(super) fn direct_address_states(&self) -> impl Iterator<Item = (&IpPort, &PathState)> + '_ { +1201 self.udp_paths.paths.iter() +1202 } +1203 +1204 pub(super) fn last_used(&self) -> Option<Instant> { +1205 self.last_used +1206 } +1207} +1208 +1209impl From<RemoteInfo> for NodeAddr { +1210 fn from(info: RemoteInfo) -> Self { +1211 let direct_addresses = info +1212 .addrs +1213 .into_iter() +1214 .map(|info| info.addr) +1215 .collect::<BTreeSet<_>>(); +1216 +1217 NodeAddr { +1218 node_id: info.node_id, +1219 relay_url: info.relay_url.map(Into::into), +1220 direct_addresses, +1221 } +1222 } +1223} +1224 +1225/// Whether to send a call-me-maybe message after sending pings to all known paths. +1226/// +1227/// `IfNoRecent` will only send a call-me-maybe if no previous one was sent in the last +1228/// [`HEARTBEAT_INTERVAL`]. +1229#[derive(Debug)] +1230enum SendCallMeMaybe { +1231 Always, +1232 IfNoRecent, +1233} +1234 +1235#[derive(Debug, Clone, PartialEq, Eq, Hash)] +1236pub(super) struct PongReply { +1237 pub(super) latency: Duration, +1238 /// When we received the pong. +1239 pub(super) pong_at: Instant, +1240 /// The pong's src (usually same as endpoint map key). +1241 pub(super) from: SendAddr, +1242 /// What they reported they heard. +1243 pub(super) pong_src: SendAddr, +1244} +1245 +1246#[derive(Debug)] +1247pub(super) struct SentPing { +1248 pub(super) to: SendAddr, +1249 pub(super) at: Instant, +1250 #[allow(dead_code)] +1251 pub(super) purpose: DiscoPingPurpose, +1252 pub(super) _expiry_task: AbortOnDropHandle<()>, +1253} +1254 +1255/// The reason why a discovery ping message was sent. +1256#[derive(Debug, Clone, Copy, PartialEq, Eq)] +1257pub enum DiscoPingPurpose { +1258 /// The purpose of a ping was to see if a path was valid. +1259 Discovery, +1260 /// Ping to ensure the current route is still valid. +1261 StayinAlive, +1262 /// When a ping was received and no direct connection exists yet. +1263 /// +1264 /// When a ping was received we suspect a direct connection is possible. If we do not +1265 /// yet have one that triggers a ping, indicated with this reason. +1266 PingBack, +1267} +1268 +1269/// The type of control message we have received. +1270#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize, derive_more::Display)] +1271pub enum ControlMsg { +1272 /// We received a Ping from the node. +1273 #[display("ping←")] +1274 Ping, +1275 /// We received a Pong from the node. +1276 #[display("pong←")] +1277 Pong, +1278 /// We received a CallMeMaybe. +1279 #[display("call me")] +1280 CallMeMaybe, +1281} +1282 +1283/// Information about a *direct address*. +1284/// +1285/// The *direct addresses* of an iroh node are those that could be used by other nodes to +1286/// establish direct connectivity, depending on the network situation. Due to NAT configurations, +1287/// for example, not all direct addresses of a node are usable by all peers. +1288#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +1289pub struct DirectAddrInfo { +1290 /// The UDP address reported by the remote node. +1291 pub addr: SocketAddr, +1292 /// The latency to the remote node over this network path. +1293 /// +1294 /// If there has never been any connectivity via this address no latency will be known. +1295 pub latency: Option<Duration>, +1296 /// Last control message received by this node about this address. +1297 /// +1298 /// This contains the elapsed duration since the control message was received and the +1299 /// kind of control message received at that time. Only the most recent control message +1300 /// is returned. +1301 /// +1302 /// Note that [`ControlMsg::CallMeMaybe`] is received via a relay path, while +1303 /// [`ControlMsg::Ping`] and [`ControlMsg::Pong`] are received on the path to +1304 /// [`DirectAddrInfo::addr`] itself and thus convey very different information. +1305 pub last_control: Option<(Duration, ControlMsg)>, +1306 /// Elapsed time since the last payload message was received on this network path. +1307 /// +1308 /// This indicates how long ago a QUIC datagram was received from the remote node sent +1309 /// from this [`DirectAddrInfo::addr`]. It indicates the network path was in use to +1310 /// transport payload data. +1311 pub last_payload: Option<Duration>, +1312 /// Elapsed time since this network path was known to exist. +1313 /// +1314 /// A network path is considered to exist only because the remote node advertised it. +1315 /// It may not mean the path is usable. However, if there was any communication with +1316 /// the remote node over this network path it also means the path exists. +1317 /// +1318 /// The elapsed time since *any* confirmation of the path's existence was received is +1319 /// returned. If the remote node moved networks and no longer has this path, this could +1320 /// be a long duration. If the path was added via [`Endpoint::add_node_addr`] or some +1321 /// node discovery the path may never have been known to exist. +1322 /// +1323 /// [`Endpoint::add_node_addr`]: crate::endpoint::Endpoint::add_node_addr +1324 pub last_alive: Option<Duration>, +1325 /// A [`HashMap`] of [`Source`]s to [`Duration`]s. +1326 /// +1327 /// The [`Duration`] indicates the elapsed time since this source last +1328 /// recorded this address. +1329 /// +1330 /// The [`Duration`] will always indicate the most recent time the source +1331 /// recorded this address. +1332 pub sources: HashMap<Source, Duration>, +1333} +1334 +1335/// Information about the network path to a remote node via a relay server. +1336#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +1337pub struct RelayUrlInfo { +1338 /// The relay URL. +1339 pub relay_url: RelayUrl, +1340 /// Elapsed time since this relay path last received payload or control data. +1341 pub last_alive: Option<Duration>, +1342 /// Latency to the remote node over this relayed network path. +1343 pub latency: Option<Duration>, +1344} +1345 +1346impl From<(RelayUrl, PathState)> for RelayUrlInfo { +1347 fn from(value: (RelayUrl, PathState)) -> Self { +1348 RelayUrlInfo { +1349 relay_url: value.0, +1350 last_alive: value.1.last_alive().map(|i| i.elapsed()), +1351 latency: value.1.latency(), +1352 } +1353 } +1354} +1355 +1356impl From<RelayUrlInfo> for RelayUrl { +1357 fn from(value: RelayUrlInfo) -> Self { +1358 value.relay_url +1359 } +1360} +1361 +1362/// Details about a remote iroh node which is known to this node. +1363/// +1364/// Having details of a node does not mean it can be connected to, nor that it has ever been +1365/// connected to in the past. There are various reasons a node might be known: it could have +1366/// been manually added via [`Endpoint::add_node_addr`], it could have been added by some +1367/// discovery mechanism, the node could have contacted this node, etc. +1368/// +1369/// [`Endpoint::add_node_addr`]: crate::endpoint::Endpoint::add_node_addr +1370#[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +1371pub struct RemoteInfo { +1372 /// The globally unique identifier for this node. +1373 pub node_id: NodeId, +1374 /// Relay server information, if available. +1375 pub relay_url: Option<RelayUrlInfo>, +1376 /// The addresses at which this node might be reachable. +1377 /// +1378 /// Some of these addresses might only be valid for networks we are not part of, but the remote +1379 /// node might be a part of. +1380 pub addrs: Vec<DirectAddrInfo>, +1381 /// The type of connection we have to the node, either direct or over relay. +1382 pub conn_type: ConnectionType, +1383 /// The latency of the current network path to the remote node. +1384 pub latency: Option<Duration>, +1385 /// Time elapsed time since last we have sent to or received from the node. +1386 /// +1387 /// This is the duration since *any* data (payload or control messages) was sent or receive +1388 /// from the remote node. Note that sending to the remote node does not imply +1389 /// the remote node received anything. +1390 pub last_used: Option<Duration>, +1391} +1392 +1393impl RemoteInfo { +1394 /// Get the duration since the last activity we received from this endpoint +1395 /// on any of its direct addresses. +1396 pub fn last_received(&self) -> Option<Duration> { +1397 self.addrs +1398 .iter() +1399 .filter_map(|addr| addr.last_control.map(|x| x.0).min(addr.last_payload)) +1400 .min() +1401 } +1402 +1403 /// Whether there is a possible known network path to the remote node. +1404 /// +1405 /// Note that this does not provide any guarantees of whether any network path is +1406 /// usable. +1407 pub fn has_send_address(&self) -> bool { +1408 self.relay_url.is_some() || !self.addrs.is_empty() +1409 } +1410 +1411 /// Returns a deduplicated list of [`Source`]s merged from all address in the [`RemoteInfo`]. +1412 /// +1413 /// Deduplication is on the (`Source`, `Duration`) tuple, so you will get multiple [`Source`]s +1414 /// for each `Source` variant, if different addresses were discovered from the same [`Source`] +1415 /// at different times. +1416 /// +1417 /// The list is sorted from least to most recent [`Source`]. +1418 pub fn sources(&self) -> Vec<(Source, Duration)> { +1419 let mut sources = vec![]; +1420 for addr in &self.addrs { +1421 for source in &addr.sources { +1422 let source = (source.0.clone(), *source.1); +1423 if !sources.contains(&source) { +1424 sources.push(source) +1425 } +1426 } +1427 } +1428 sources.sort_by(|a, b| b.1.cmp(&a.1)); +1429 sources +1430 } +1431} +1432 +1433/// The type of connection we have to the endpoint. +1434#[derive(derive_more::Display, Default, Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] +1435pub enum ConnectionType { +1436 /// Direct UDP connection +1437 #[display("direct({_0})")] +1438 Direct(SocketAddr), +1439 /// Relay connection over relay +1440 #[display("relay({_0})")] +1441 Relay(RelayUrl), +1442 /// Both a UDP and a relay connection are used. +1443 /// +1444 /// This is the case if we do have a UDP address, but are missing a recent confirmation that +1445 /// the address works. +1446 #[display("mixed(udp: {_0}, relay: {_1})")] +1447 Mixed(SocketAddr, RelayUrl), +1448 /// We have no verified connection to this PublicKey +1449 #[default] +1450 #[display("none")] +1451 None, +1452} +1453 +1454#[cfg(test)] +1455mod tests { +1456 use std::{collections::BTreeMap, net::Ipv4Addr}; +1457 +1458 use best_addr::BestAddr; +1459 use iroh_base::SecretKey; +1460 +1461 use super::*; +1462 use crate::magicsock::node_map::{NodeMap, NodeMapInner}; +1463 +1464 #[test] +1465 fn test_remote_infos() { +1466 let now = Instant::now(); +1467 let elapsed = Duration::from_secs(3); +1468 let later = now + elapsed; +1469 let send_addr: RelayUrl = "https://my-relay.com".parse().unwrap(); +1470 let pong_src = SendAddr::Udp("0.0.0.0:1".parse().unwrap()); +1471 let latency = Duration::from_millis(50); +1472 +1473 let relay_and_state = |node_id: NodeId, url: RelayUrl| { +1474 let relay_state = PathState::with_pong_reply( +1475 node_id, +1476 PongReply { +1477 latency, +1478 pong_at: now, +1479 from: SendAddr::Relay(send_addr.clone()), +1480 pong_src: pong_src.clone(), +1481 }, +1482 ); +1483 Some((url, relay_state)) +1484 }; +1485 +1486 // endpoint with a `best_addr` that has a latency but no relay +1487 let (a_endpoint, a_socket_addr) = { +1488 let key = SecretKey::generate(rand::thread_rng()); +1489 let node_id = key.public(); +1490 let ip_port = IpPort { +1491 ip: Ipv4Addr::UNSPECIFIED.into(), +1492 port: 10, +1493 }; +1494 let endpoint_state = BTreeMap::from([( +1495 ip_port, +1496 PathState::with_pong_reply( +1497 node_id, +1498 PongReply { +1499 latency, +1500 pong_at: now, +1501 from: SendAddr::Udp(ip_port.into()), +1502 pong_src: pong_src.clone(), +1503 }, +1504 ), +1505 )]); +1506 ( +1507 NodeState { +1508 id: 0, +1509 quic_mapped_addr: NodeIdMappedAddr::generate(), +1510 node_id: key.public(), +1511 last_full_ping: None, +1512 relay_url: None, +1513 udp_paths: NodeUdpPaths::from_parts( +1514 endpoint_state, +1515 BestAddr::from_parts( +1516 ip_port.into(), +1517 latency, +1518 now, +1519 now + Duration::from_secs(100), +1520 ), +1521 ), +1522 sent_pings: HashMap::new(), +1523 last_used: Some(now), +1524 last_call_me_maybe: None, +1525 conn_type: Watchable::new(ConnectionType::Direct(ip_port.into())), +1526 has_been_direct: true, +1527 #[cfg(any(test, feature = "test-utils"))] +1528 path_selection: PathSelection::default(), +1529 }, +1530 ip_port.into(), +1531 ) +1532 }; +1533 // endpoint w/ no best addr but a relay w/ latency +1534 let b_endpoint = { +1535 // let socket_addr = "0.0.0.0:9".parse().unwrap(); +1536 let key = SecretKey::generate(rand::thread_rng()); +1537 NodeState { +1538 id: 1, +1539 quic_mapped_addr: NodeIdMappedAddr::generate(), +1540 node_id: key.public(), +1541 last_full_ping: None, +1542 relay_url: relay_and_state(key.public(), send_addr.clone()), +1543 udp_paths: NodeUdpPaths::new(), +1544 sent_pings: HashMap::new(), +1545 last_used: Some(now), +1546 last_call_me_maybe: None, +1547 conn_type: Watchable::new(ConnectionType::Relay(send_addr.clone())), +1548 has_been_direct: false, +1549 #[cfg(any(test, feature = "test-utils"))] +1550 path_selection: PathSelection::default(), +1551 } +1552 }; +1553 +1554 // endpoint w/ no best addr but a relay w/ no latency +1555 let c_endpoint = { +1556 // let socket_addr = "0.0.0.0:8".parse().unwrap(); +1557 let key = SecretKey::generate(rand::thread_rng()); +1558 NodeState { +1559 id: 2, +1560 quic_mapped_addr: NodeIdMappedAddr::generate(), +1561 node_id: key.public(), +1562 last_full_ping: None, +1563 relay_url: Some(( +1564 send_addr.clone(), +1565 PathState::new( +1566 key.public(), +1567 SendAddr::from(send_addr.clone()), +1568 Source::App, +1569 now, +1570 ), +1571 )), +1572 udp_paths: NodeUdpPaths::new(), +1573 sent_pings: HashMap::new(), +1574 last_used: Some(now), +1575 last_call_me_maybe: None, +1576 conn_type: Watchable::new(ConnectionType::Relay(send_addr.clone())), +1577 has_been_direct: false, +1578 #[cfg(any(test, feature = "test-utils"))] +1579 path_selection: PathSelection::default(), +1580 } +1581 }; +1582 +1583 // endpoint w/ expired best addr and relay w/ latency +1584 let (d_endpoint, d_socket_addr) = { +1585 let socket_addr: SocketAddr = "0.0.0.0:7".parse().unwrap(); +1586 let expired = now.checked_sub(Duration::from_secs(100)).unwrap(); +1587 let key = SecretKey::generate(rand::thread_rng()); +1588 let node_id = key.public(); +1589 let endpoint_state = BTreeMap::from([( +1590 IpPort::from(socket_addr), +1591 PathState::with_pong_reply( +1592 node_id, +1593 PongReply { +1594 latency, +1595 pong_at: now, +1596 from: SendAddr::Udp(socket_addr), +1597 pong_src: pong_src.clone(), +1598 }, +1599 ), +1600 )]); +1601 ( +1602 NodeState { +1603 id: 3, +1604 quic_mapped_addr: NodeIdMappedAddr::generate(), +1605 node_id: key.public(), +1606 last_full_ping: None, +1607 relay_url: relay_and_state(key.public(), send_addr.clone()), +1608 udp_paths: NodeUdpPaths::from_parts( +1609 endpoint_state, +1610 BestAddr::from_parts(socket_addr, Duration::from_millis(80), now, expired), +1611 ), +1612 sent_pings: HashMap::new(), +1613 last_used: Some(now), +1614 last_call_me_maybe: None, +1615 conn_type: Watchable::new(ConnectionType::Mixed( +1616 socket_addr, +1617 send_addr.clone(), +1618 )), +1619 has_been_direct: false, +1620 #[cfg(any(test, feature = "test-utils"))] +1621 path_selection: PathSelection::default(), +1622 }, +1623 socket_addr, +1624 ) +1625 }; +1626 +1627 let mut expect = Vec::from([ +1628 RemoteInfo { +1629 node_id: a_endpoint.node_id, +1630 relay_url: None, +1631 addrs: Vec::from([DirectAddrInfo { +1632 addr: a_socket_addr, +1633 latency: Some(latency), +1634 last_control: Some((elapsed, ControlMsg::Pong)), +1635 last_payload: None, +1636 last_alive: Some(elapsed), +1637 sources: HashMap::new(), +1638 }]), +1639 conn_type: ConnectionType::Direct(a_socket_addr), +1640 latency: Some(latency), +1641 last_used: Some(elapsed), +1642 }, +1643 RemoteInfo { +1644 node_id: b_endpoint.node_id, +1645 relay_url: Some(RelayUrlInfo { +1646 relay_url: b_endpoint.relay_url.as_ref().unwrap().0.clone(), +1647 last_alive: None, +1648 latency: Some(latency), +1649 }), +1650 addrs: Vec::new(), +1651 conn_type: ConnectionType::Relay(send_addr.clone()), +1652 latency: Some(latency), +1653 last_used: Some(elapsed), +1654 }, +1655 RemoteInfo { +1656 node_id: c_endpoint.node_id, +1657 relay_url: Some(RelayUrlInfo { +1658 relay_url: c_endpoint.relay_url.as_ref().unwrap().0.clone(), +1659 last_alive: None, +1660 latency: None, +1661 }), +1662 addrs: Vec::new(), +1663 conn_type: ConnectionType::Relay(send_addr.clone()), +1664 latency: None, +1665 last_used: Some(elapsed), +1666 }, +1667 RemoteInfo { +1668 node_id: d_endpoint.node_id, +1669 relay_url: Some(RelayUrlInfo { +1670 relay_url: d_endpoint.relay_url.as_ref().unwrap().0.clone(), +1671 last_alive: None, +1672 latency: Some(latency), +1673 }), +1674 addrs: Vec::from([DirectAddrInfo { +1675 addr: d_socket_addr, +1676 latency: Some(latency), +1677 last_control: Some((elapsed, ControlMsg::Pong)), +1678 last_payload: None, +1679 last_alive: Some(elapsed), +1680 sources: HashMap::new(), +1681 }]), +1682 conn_type: ConnectionType::Mixed(d_socket_addr, send_addr.clone()), +1683 latency: Some(Duration::from_millis(50)), +1684 last_used: Some(elapsed), +1685 }, +1686 ]); +1687 +1688 let node_map = NodeMap::from_inner(NodeMapInner { +1689 by_node_key: HashMap::from([ +1690 (a_endpoint.node_id, a_endpoint.id), +1691 (b_endpoint.node_id, b_endpoint.id), +1692 (c_endpoint.node_id, c_endpoint.id), +1693 (d_endpoint.node_id, d_endpoint.id), +1694 ]), +1695 by_ip_port: HashMap::from([ +1696 (a_socket_addr.into(), a_endpoint.id), +1697 (d_socket_addr.into(), d_endpoint.id), +1698 ]), +1699 by_quic_mapped_addr: HashMap::from([ +1700 (a_endpoint.quic_mapped_addr, a_endpoint.id), +1701 (b_endpoint.quic_mapped_addr, b_endpoint.id), +1702 (c_endpoint.quic_mapped_addr, c_endpoint.id), +1703 (d_endpoint.quic_mapped_addr, d_endpoint.id), +1704 ]), +1705 by_id: HashMap::from([ +1706 (a_endpoint.id, a_endpoint), +1707 (b_endpoint.id, b_endpoint), +1708 (c_endpoint.id, c_endpoint), +1709 (d_endpoint.id, d_endpoint), +1710 ]), +1711 next_id: 5, +1712 path_selection: PathSelection::default(), +1713 }); +1714 let mut got = node_map.list_remote_infos(later); +1715 got.sort_by_key(|p| p.node_id); +1716 expect.sort_by_key(|p| p.node_id); +1717 remove_non_deterministic_fields(&mut got); +1718 assert_eq!(expect, got); +1719 } +1720 +1721 fn remove_non_deterministic_fields(infos: &mut [RemoteInfo]) { +1722 for info in infos.iter_mut() { +1723 if info.relay_url.is_some() { +1724 info.relay_url.as_mut().unwrap().last_alive = None; +1725 } +1726 } +1727 } +1728 +1729 #[test] +1730 fn test_prune_direct_addresses() { +1731 // When we handle a call-me-maybe with more than MAX_INACTIVE_DIRECT_ADDRESSES we do +1732 // not want to prune them right away but send pings to all of them. +1733 +1734 let key = SecretKey::generate(rand::thread_rng()); +1735 let opts = Options { +1736 node_id: key.public(), +1737 relay_url: None, +1738 active: true, +1739 source: crate::magicsock::Source::NamedApp { +1740 name: "test".into(), +1741 }, +1742 path_selection: PathSelection::default(), +1743 }; +1744 let mut ep = NodeState::new(0, opts); +1745 +1746 let my_numbers_count: u16 = (MAX_INACTIVE_DIRECT_ADDRESSES + 5).try_into().unwrap(); +1747 let my_numbers = (0u16..my_numbers_count) +1748 .map(|i| SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 1000 + i)) +1749 .collect(); +1750 let call_me_maybe = disco::CallMeMaybe { my_numbers }; +1751 +1752 let ping_messages = ep.handle_call_me_maybe(call_me_maybe); 1753 -1754 let ping_messages = ep.handle_call_me_maybe(call_me_maybe); -1755 -1756 // We have no relay server and no previous direct addresses, so we should get the same -1757 // number of pings as direct addresses in the call-me-maybe. -1758 assert_eq!(ping_messages.len(), my_numbers_count as usize); -1759 } -1760} \ No newline at end of file +1754 // We have no relay server and no previous direct addresses, so we should get the same +1755 // number of pings as direct addresses in the call-me-maybe. +1756 assert_eq!(ping_messages.len(), my_numbers_count as usize); +1757 } +1758} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/magicsock/relay_actor.rs.html b/pr/3327/docs/src/iroh/magicsock/relay_actor.rs.html deleted file mode 100644 index 7d2196f35f..0000000000 --- a/pr/3327/docs/src/iroh/magicsock/relay_actor.rs.html +++ /dev/null @@ -1,1713 +0,0 @@ -relay_actor.rs - source

    iroh/magicsock/
    relay_actor.rs

    1//! The relay actor.
    -2//!
    -3//! The [`RelayActor`] handles all the relay connections.  It is helped by the
    -4//! [`ActiveRelayActor`] which handles a single relay connection.
    -5//!
    -6//! - The [`RelayActor`] manages all connections to relay servers.
    -7//!   - It starts a new [`ActiveRelayActor`] for each relay server needed.
    -8//!   - The [`ActiveRelayActor`] will exit when unused.
    -9//!     - Unless it is for the home relay, this one never exits.
    -10//!   - Each [`ActiveRelayActor`] uses a relay [`Client`].
    -11//!     - The relay [`Client`] is a `Stream` and `Sink` directly connected to the
    -12//!       `TcpStream` connected to the relay server.
    -13//!   - Each [`ActiveRelayActor`] will try and maintain a connection with the relay server.
    -14//!     - If connections fail, exponential backoff is used for reconnections.
    -15//! - When `AsyncUdpSocket` needs to send datagrams:
    -16//!   - It puts them on a queue to the [`RelayActor`].
    -17//!   - The [`RelayActor`] ensures the correct [`ActiveRelayActor`] is running and
    -18//!     forwards datagrams to it.
    -19//!   - The ActiveRelayActor sends datagrams directly to the relay server.
    -20//! - The relay receive path is:
    -21//!   - Whenever [`ActiveRelayActor`] is connected it reads from the underlying `TcpStream`.
    -22//!   - Received datagrams are placed on an mpsc channel that now bypasses the
    -23//!     [`RelayActor`] and goes straight to the `AsyncUpdSocket` interface.
    -24//!
    -25//! [`Client`]: iroh_relay::client::Client
    -26
    -27#[cfg(test)]
    -28use std::net::SocketAddr;
    -29use std::{
    -30    collections::{BTreeMap, BTreeSet},
    -31    future::Future,
    -32    net::IpAddr,
    -33    pin::{pin, Pin},
    -34    sync::{
    -35        atomic::{AtomicBool, Ordering},
    -36        Arc,
    -37    },
    -38};
    -39
    -40use backon::{Backoff, BackoffBuilder, ExponentialBuilder};
    -41use bytes::{Bytes, BytesMut};
    -42use iroh_base::{NodeId, PublicKey, RelayUrl, SecretKey};
    -43use iroh_relay::{
    -44    self as relay,
    -45    client::{Client, ConnectError, ReceivedMessage, RecvError, SendError, SendMessage},
    -46    PingTracker, MAX_PACKET_SIZE,
    -47};
    -48use n0_future::{
    -49    task::JoinSet,
    -50    time::{self, Duration, Instant, MissedTickBehavior},
    -51    FuturesUnorderedBounded, SinkExt, StreamExt,
    -52};
    -53use nested_enum_utils::common_fields;
    -54use snafu::{IntoError, ResultExt, Snafu};
    -55use tokio::sync::{mpsc, oneshot};
    -56use tokio_util::sync::CancellationToken;
    -57use tracing::{debug, error, event, info_span, instrument, trace, warn, Instrument, Level};
    -58use url::Url;
    -59
    -60use super::RelayDatagramSendChannelReceiver;
    -61#[cfg(not(wasm_browser))]
    -62use crate::dns::DnsResolver;
    -63use crate::{
    -64    magicsock::{MagicSock, Metrics as MagicsockMetrics, RelayContents, RelayDatagramRecvQueue},
    -65    util::MaybeFuture,
    -66};
    -67
    -68/// How long a non-home relay connection needs to be idle (last written to) before we close it.
    -69const RELAY_INACTIVE_CLEANUP_TIME: Duration = Duration::from_secs(60);
    -70
    -71/// Maximum size a datagram payload is allowed to be.
    -72const MAX_PAYLOAD_SIZE: usize = MAX_PACKET_SIZE - PublicKey::LENGTH;
    -73
    -74/// Interval in which we ping the relay server to ensure the connection is alive.
    -75///
    -76/// The default QUIC max_idle_timeout is 30s, so setting that to half this time gives some
    -77/// chance of recovering.
    -78const PING_INTERVAL: Duration = Duration::from_secs(15);
    -79
    -80/// Number of datagrams which can be sent to the relay server in one batch.
    -81///
    -82/// This means while this batch is sending to the server no other relay protocol frames can
    -83/// be sent to the server, e.g. no Ping frames or so.  While the maximum packet size is
    -84/// rather large, each item can typically be expected to up to 1500 or the max GSO size.
    -85const SEND_DATAGRAM_BATCH_SIZE: usize = 20;
    -86
    -87/// Timeout for establishing the relay connection.
    -88///
    -89/// This includes DNS, dialing the server, upgrading the connection, and completing the
    -90/// handshake.
    -91const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
    -92
    -93/// Time after which the [`ActiveRelayActor`] will drop undeliverable datagrams.
    -94///
    -95/// When the [`ActiveRelayActor`] is not connected it can not deliver datagrams.  However it
    -96/// will still receive datagrams to send from the [`RelayActor`].  If connecting takes
    -97/// longer than this timeout datagrams will be dropped.
    -98///
    -99/// This value is set to 3 times the QUIC initial Probe Timeout (PTO).
    -100const UNDELIVERABLE_DATAGRAM_TIMEOUT: Duration = Duration::from_secs(3);
    -101
    -102/// An actor which handles the connection to a single relay server.
    -103///
    -104/// It is responsible for maintaining the connection to the relay server and handling all
    -105/// communication with it.
    -106///
    -107/// The actor shuts down itself on inactivity: inactivity is determined when no more
    -108/// datagrams are being queued to send.
    -109///
    -110/// This actor has 3 main states it can be in, each has it's dedicated run loop:
    -111///
    -112/// - Dialing the relay server.
    -113///
    -114///   This will continuously dial the server until connected, using exponential backoff if
    -115///   it can not connect.  See [`ActiveRelayActor::run_dialing`].
    -116///
    -117/// - Connected to the relay server.
    -118///
    -119///   This state allows receiving from the relay server, though sending is idle in this
    -120///   state.  See [`ActiveRelayActor::run_connected`].
    -121///
    -122/// - Sending to the relay server.
    -123///
    -124///   This is a sub-state of `connected` so the actor can still be receiving from the relay
    -125///   server at this time.  However it is actively sending data to the server so can not
    -126///   consume any further items from inboxes which will result in sending more data to the
    -127///   server until the actor goes back to the `connected` state.
    -128///
    -129/// All these are driven from the top-level [`ActiveRelayActor::run`] loop.
    -130#[derive(Debug)]
    -131struct ActiveRelayActor {
    -132    // The inboxes and channels this actor communicates over.
    -133    /// Inbox for messages which should be handled without any blocking.
    -134    prio_inbox: mpsc::Receiver<ActiveRelayPrioMessage>,
    -135    /// Inbox for messages which involve sending to the relay server.
    -136    inbox: mpsc::Receiver<ActiveRelayMessage>,
    -137    /// Queue for received relay datagrams.
    -138    relay_datagrams_recv: Arc<RelayDatagramRecvQueue>,
    -139    /// Channel on which we queue packets to send to the relay.
    -140    relay_datagrams_send: mpsc::Receiver<RelaySendItem>,
    -141
    -142    // Other actor state.
    -143    /// The relay server for this actor.
    -144    url: RelayUrl,
    -145    /// Builder which can repeatedly build a relay client.
    -146    relay_client_builder: relay::client::ClientBuilder,
    -147    /// Whether or not this is the home relay server.
    -148    ///
    -149    /// The home relay server needs to maintain it's connection to the relay server, even if
    -150    /// the relay actor is otherwise idle.
    -151    is_home_relay: bool,
    -152    /// When this expires the actor has been idle and should shut down.
    -153    ///
    -154    /// Unless it is managing the home relay connection.  Inactivity is only tracked on the
    -155    /// last datagram sent to the relay, received datagrams will trigger QUIC ACKs which is
    -156    /// sufficient to keep active connections open.
    -157    inactive_timeout: Pin<Box<time::Sleep>>,
    -158    /// Token indicating the [`ActiveRelayActor`] should stop.
    -159    stop_token: CancellationToken,
    -160    metrics: Arc<MagicsockMetrics>,
    -161}
    -162
    -163#[derive(Debug)]
    -164enum ActiveRelayMessage {
    -165    /// Triggers a connection check to the relay server.
    -166    ///
    -167    /// Sometimes it is known the local network interfaces have changed in which case it
    -168    /// might be prudent to check if the relay connection is still working.  `Vec<IpAddr>`
    -169    /// should contain the current local IP addresses.  If the connection uses a local
    -170    /// socket with an IP address in this list the relay server will be pinged.  If the
    -171    /// connection uses a local socket with an IP address not in this list the server will
    -172    /// always re-connect.
    -173    CheckConnection(Vec<IpAddr>),
    -174    /// Sets this relay as the home relay, or not.
    -175    SetHomeRelay(bool),
    -176    #[cfg(test)]
    -177    GetLocalAddr(oneshot::Sender<Option<SocketAddr>>),
    -178    #[cfg(test)]
    -179    PingServer(oneshot::Sender<()>),
    -180}
    -181
    -182/// Messages for the [`ActiveRelayActor`] which should never block.
    -183///
    -184/// Most messages in the [`ActiveRelayMessage`] enum trigger sending to the relay server,
    -185/// which can be blocking.  So the actor may not always be processing that inbox.  Messages
    -186/// here are processed immediately.
    -187#[derive(Debug)]
    -188enum ActiveRelayPrioMessage {
    -189    /// Returns whether or not this relay can reach the NodeId.
    -190    HasNodeRoute(NodeId, oneshot::Sender<bool>),
    -191}
    -192
    -193/// Configuration needed to start an [`ActiveRelayActor`].
    -194#[derive(Debug)]
    -195struct ActiveRelayActorOptions {
    -196    url: RelayUrl,
    -197    prio_inbox_: mpsc::Receiver<ActiveRelayPrioMessage>,
    -198    inbox: mpsc::Receiver<ActiveRelayMessage>,
    -199    relay_datagrams_send: mpsc::Receiver<RelaySendItem>,
    -200    relay_datagrams_recv: Arc<RelayDatagramRecvQueue>,
    -201    connection_opts: RelayConnectionOptions,
    -202    stop_token: CancellationToken,
    -203    metrics: Arc<MagicsockMetrics>,
    -204}
    -205
    -206/// Configuration needed to create a connection to a relay server.
    -207#[derive(Debug, Clone)]
    -208struct RelayConnectionOptions {
    -209    secret_key: SecretKey,
    -210    #[cfg(not(wasm_browser))]
    -211    dns_resolver: DnsResolver,
    -212    proxy_url: Option<Url>,
    -213    prefer_ipv6: Arc<AtomicBool>,
    -214    #[cfg(any(test, feature = "test-utils"))]
    -215    insecure_skip_cert_verify: bool,
    -216    protocol: iroh_relay::http::Protocol,
    -217}
    -218
    -219/// Possible reasons for a failed relay connection.
    -220#[allow(missing_docs)]
    -221#[common_fields({
    -222    backtrace: Option<snafu::Backtrace>,
    -223    #[snafu(implicit)]
    -224    span_trace: n0_snafu::SpanTrace,
    -225})]
    -226#[derive(Debug, Snafu)]
    -227enum RelayConnectionError {
    -228    #[snafu(display("Failed to connect to relay server"))]
    -229    Dial { source: DialError },
    -230    #[snafu(display("Failed to handshake with relay server"))]
    -231    Handshake { source: RunError },
    -232    #[snafu(display("Lost connection to relay server"))]
    -233    Established { source: RunError },
    -234}
    -235
    -236#[allow(missing_docs)]
    -237#[common_fields({
    -238    backtrace: Option<snafu::Backtrace>,
    -239    #[snafu(implicit)]
    -240    span_trace: n0_snafu::SpanTrace,
    -241})]
    -242#[derive(Debug, Snafu)]
    -243enum RunError {
    -244    #[snafu(display("Send timeout"))]
    -245    SendTimeout {},
    -246    #[snafu(display("Ping timeout"))]
    -247    PingTimeout {},
    -248    #[snafu(display("Local IP no longer valid"))]
    -249    LocalIpInvalid {},
    -250    #[snafu(display("No local address"))]
    -251    LocalAddrMissing {},
    -252    #[snafu(display("Stream closed by server."))]
    -253    StreamClosedServer {},
    -254    #[snafu(display("Client stream read failed"))]
    -255    ClientStreamRead { source: RecvError },
    -256    #[snafu(display("Client stream write failed"))]
    -257    ClientStreamWrite { source: SendError },
    -258}
    -259
    -260#[allow(missing_docs)]
    -261#[common_fields({
    -262    backtrace: Option<snafu::Backtrace>,
    -263    #[snafu(implicit)]
    -264    span_trace: n0_snafu::SpanTrace,
    -265})]
    -266#[derive(Debug, Snafu)]
    -267enum DialError {
    -268    #[snafu(display("timeout trying to establish a connection"))]
    -269    Timeout {},
    -270    #[snafu(display("unable to connect"))]
    -271    Connect {
    -272        #[snafu(source(from(ConnectError, Box::new)))]
    -273        source: Box<ConnectError>,
    -274    },
    -275}
    -276
    -277impl ActiveRelayActor {
    -278    fn new(opts: ActiveRelayActorOptions) -> Self {
    -279        let ActiveRelayActorOptions {
    -280            url,
    -281            prio_inbox_: prio_inbox,
    -282            inbox,
    -283            relay_datagrams_send,
    -284            relay_datagrams_recv,
    -285            connection_opts,
    -286            stop_token,
    -287            metrics,
    -288        } = opts;
    -289        let relay_client_builder = Self::create_relay_builder(url.clone(), connection_opts);
    -290        ActiveRelayActor {
    -291            prio_inbox,
    -292            inbox,
    -293            relay_datagrams_recv,
    -294            relay_datagrams_send,
    -295            url,
    -296            relay_client_builder,
    -297            is_home_relay: false,
    -298            inactive_timeout: Box::pin(time::sleep(RELAY_INACTIVE_CLEANUP_TIME)),
    -299            stop_token,
    -300            metrics,
    -301        }
    -302    }
    -303
    -304    fn create_relay_builder(
    -305        url: RelayUrl,
    -306        opts: RelayConnectionOptions,
    -307    ) -> relay::client::ClientBuilder {
    -308        let RelayConnectionOptions {
    -309            secret_key,
    -310            #[cfg(not(wasm_browser))]
    -311            dns_resolver,
    -312            proxy_url,
    -313            prefer_ipv6,
    -314            #[cfg(any(test, feature = "test-utils"))]
    -315            insecure_skip_cert_verify,
    -316            protocol,
    -317        } = opts;
    -318
    -319        let mut builder = relay::client::ClientBuilder::new(
    -320            url,
    -321            secret_key,
    -322            #[cfg(not(wasm_browser))]
    -323            dns_resolver,
    -324        )
    -325        .protocol(protocol)
    -326        .address_family_selector(move || prefer_ipv6.load(Ordering::Relaxed));
    -327        if let Some(proxy_url) = proxy_url {
    -328            builder = builder.proxy_url(proxy_url);
    -329        }
    -330        #[cfg(any(test, feature = "test-utils"))]
    -331        let builder = builder.insecure_skip_cert_verify(insecure_skip_cert_verify);
    -332        builder
    -333    }
    -334
    -335    /// The main actor run loop.
    -336    ///
    -337    /// Primarily switches between the dialing and connected states.
    -338    async fn run(mut self) {
    -339        // TODO(frando): decide what this metric means, it's either wrong here or in node_state.rs.
    -340        // From the existing description, it is wrong here.
    -341        // self.metrics.num_relay_conns_added.inc();
    -342
    -343        let mut backoff = Self::build_backoff();
    -344
    -345        while let Err(err) = self.run_once().await {
    -346            warn!("{err}");
    -347            match err {
    -348                RelayConnectionError::Dial { .. } | RelayConnectionError::Handshake { .. } => {
    -349                    // If dialing failed, or if the relay connection failed before we received a pong,
    -350                    // we wait an exponentially increasing time until we attempt to reconnect again.
    -351                    let Some(delay) = backoff.next() else {
    -352                        warn!("retries exceeded");
    -353                        break;
    -354                    };
    -355                    debug!("retry in {delay:?}");
    -356                    time::sleep(delay).await;
    -357                }
    -358                RelayConnectionError::Established { .. } => {
    -359                    // If the relay connection remained established long enough so that we received a pong
    -360                    // from the relay server, we reset the backoff and attempt to reconnect immediately.
    -361                    backoff = Self::build_backoff();
    -362                }
    -363            }
    -364        }
    -365        debug!("exiting");
    -366        // TODO(frando): decide what this metric means, it's either wrong here or in node_state.rs.
    -367        // From the existing description, it is wrong here.
    -368        // self.metrics.num_relay_conns_removed.inc();
    -369    }
    -370
    -371    fn build_backoff() -> impl Backoff {
    -372        ExponentialBuilder::new()
    -373            .with_min_delay(Duration::from_millis(10))
    -374            .with_max_delay(Duration::from_secs(16))
    -375            .with_jitter()
    -376            .without_max_times()
    -377            .build()
    -378    }
    -379
    -380    /// Attempt to connect to the relay, and run the connected actor loop.
    -381    ///
    -382    /// Returns `Ok(())` if the actor loop should shut down. Returns an error if dialing failed,
    -383    /// or if the relay connection failed while connected. In both cases, the connection should
    -384    /// be retried with a backoff.
    -385    async fn run_once(&mut self) -> Result<(), RelayConnectionError> {
    -386        let client = match self.run_dialing().instrument(info_span!("dialing")).await {
    -387            Some(client_res) => client_res.context(DialSnafu)?,
    -388            None => return Ok(()),
    -389        };
    -390        self.run_connected(client)
    -391            .instrument(info_span!("connected"))
    -392            .await
    -393    }
    -394
    -395    fn reset_inactive_timeout(&mut self) {
    -396        self.inactive_timeout
    -397            .as_mut()
    -398            .reset(Instant::now() + RELAY_INACTIVE_CLEANUP_TIME);
    -399    }
    -400
    -401    fn set_home_relay(&mut self, is_home: bool) {
    -402        let prev = std::mem::replace(&mut self.is_home_relay, is_home);
    -403        if self.is_home_relay != prev {
    -404            event!(
    -405                target: "iroh::_events::relay::home_changed",
    -406                Level::DEBUG,
    -407                url = %self.url,
    -408                home_relay = self.is_home_relay,
    -409            );
    -410        }
    -411    }
    -412
    -413    /// Actor loop when connecting to the relay server.
    -414    ///
    -415    /// Returns `None` if the actor needs to shut down.  Returns `Some(Ok(client))` when the
    -416    /// connection is established, and `Some(Err(err))` if dialing the relay failed.
    -417    async fn run_dialing(&mut self) -> Option<Result<iroh_relay::client::Client, DialError>> {
    -418        debug!("Actor loop: connecting to relay.");
    -419
    -420        // We regularly flush the relay_datagrams_send queue so it is not full of stale
    -421        // packets while reconnecting.  Those datagrams are dropped and the QUIC congestion
    -422        // controller will have to handle this (DISCO packets do not yet have retry).  This
    -423        // is not an ideal mechanism, an alternative approach would be to use
    -424        // e.g. ConcurrentQueue with force_push, though now you might still send very stale
    -425        // packets when eventually connected.  So perhaps this is a reasonable compromise.
    -426        let mut send_datagram_flush = time::interval(UNDELIVERABLE_DATAGRAM_TIMEOUT);
    -427        send_datagram_flush.set_missed_tick_behavior(MissedTickBehavior::Delay);
    -428        send_datagram_flush.reset(); // Skip the immediate interval
    -429
    -430        let dialing_fut = self.dial_relay();
    -431        tokio::pin!(dialing_fut);
    -432        loop {
    -433            tokio::select! {
    -434                biased;
    -435                _ = self.stop_token.cancelled() => {
    -436                    debug!("Shutdown.");
    -437                    break None;
    -438                }
    -439                msg = self.prio_inbox.recv() => {
    -440                    let Some(msg) = msg else {
    -441                        warn!("Priority inbox closed, shutdown.");
    -442                        break None;
    -443                    };
    -444                    match msg {
    -445                        ActiveRelayPrioMessage::HasNodeRoute(_peer, sender) => {
    -446                            sender.send(false).ok();
    -447                        }
    -448                    }
    -449                }
    -450                res = &mut dialing_fut => {
    -451                    match res {
    -452                        Ok(client) => {
    -453                            break Some(Ok(client));
    -454                        }
    -455                        Err(err) => {
    -456                            break Some(Err(err));
    -457                        }
    -458                    }
    -459                }
    -460                msg = self.inbox.recv() => {
    -461                    let Some(msg) = msg else {
    -462                        debug!("Inbox closed, shutdown.");
    -463                        break None;
    -464                    };
    -465                    match msg {
    -466                        ActiveRelayMessage::SetHomeRelay(is_home) => {
    -467                            self.set_home_relay(is_home);
    -468                        }
    -469                        ActiveRelayMessage::CheckConnection(_local_ips) => {}
    -470                        #[cfg(test)]
    -471                        ActiveRelayMessage::GetLocalAddr(sender) => {
    -472                            sender.send(None).ok();
    -473                        }
    -474                        #[cfg(test)]
    -475                        ActiveRelayMessage::PingServer(sender) => {
    -476                            drop(sender);
    -477                        }
    -478                    }
    -479                }
    -480                _ = send_datagram_flush.tick() => {
    -481                    self.reset_inactive_timeout();
    -482                    let mut logged = false;
    -483                    while self.relay_datagrams_send.try_recv().is_ok() {
    -484                        if !logged {
    -485                            debug!(?UNDELIVERABLE_DATAGRAM_TIMEOUT, "Dropping datagrams to send.");
    -486                            logged = true;
    -487                        }
    -488                    }
    -489                }
    -490                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
    -491                    debug!(?RELAY_INACTIVE_CLEANUP_TIME, "Inactive, exiting.");
    -492                    break None;
    -493                }
    -494            }
    -495        }
    -496    }
    -497
    -498    /// Returns a future which will complete once connected to the relay server.
    -499    ///
    -500    /// The future only completes once the connection is established and retries
    -501    /// connections.  It currently does not ever return `Err` as the retries continue
    -502    /// forever.
    -503    // This is using `impl Future` to return a future without a reference to self.
    -504    fn dial_relay(&self) -> impl Future<Output = Result<Client, DialError>> {
    -505        let client_builder = self.relay_client_builder.clone();
    -506        async move {
    -507            match time::timeout(CONNECT_TIMEOUT, client_builder.connect()).await {
    -508                Ok(Ok(client)) => Ok(client),
    -509                Ok(Err(err)) => Err(ConnectSnafu.into_error(err)),
    -510                Err(_) => Err(TimeoutSnafu.build()),
    -511            }
    -512        }
    -513    }
    -514
    -515    /// Runs the actor loop when connected to a relay server.
    -516    ///
    -517    /// Returns `Ok` if the actor needs to shut down.  `Err` is returned if the connection
    -518    /// to the relay server is lost.
    -519    async fn run_connected(
    -520        &mut self,
    -521        client: iroh_relay::client::Client,
    -522    ) -> Result<(), RelayConnectionError> {
    -523        debug!("Actor loop: connected to relay");
    -524        event!(
    -525            target: "iroh::_events::relay::connected",
    -526            Level::DEBUG,
    -527            url = %self.url,
    -528            home_relay = self.is_home_relay,
    -529        );
    -530
    -531        let (mut client_stream, client_sink) = client.split();
    -532        let mut client_sink = client_sink.sink_map_err(|e| ClientStreamWriteSnafu.into_error(e));
    -533
    -534        let mut state = ConnectedRelayState {
    -535            ping_tracker: PingTracker::default(),
    -536            nodes_present: BTreeSet::new(),
    -537            last_packet_src: None,
    -538            pong_pending: None,
    -539            established: false,
    -540            #[cfg(test)]
    -541            test_pong: None,
    -542        };
    -543
    -544        // A buffer to pass through multiple datagrams at once as an optimisation.
    -545        let mut send_datagrams_buf = Vec::with_capacity(SEND_DATAGRAM_BATCH_SIZE);
    -546
    -547        // Regularly send pings so we know the connection is healthy.
    -548        // The first ping will be sent immediately.
    -549        let mut ping_interval = time::interval(PING_INTERVAL);
    -550        ping_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
    -551
    -552        let res = loop {
    -553            if let Some(data) = state.pong_pending.take() {
    -554                let fut = client_sink.send(SendMessage::Pong(data));
    -555                self.run_sending(fut, &mut state, &mut client_stream)
    -556                    .await?;
    -557            }
    -558            tokio::select! {
    -559                biased;
    -560                _ = self.stop_token.cancelled() => {
    -561                    debug!("Shutdown.");
    -562                    break Ok(());
    -563                }
    -564                msg = self.prio_inbox.recv() => {
    -565                    let Some(msg) = msg else {
    -566                        warn!("Priority inbox closed, shutdown.");
    -567                        break Ok(());
    -568                    };
    -569                    match msg {
    -570                        ActiveRelayPrioMessage::HasNodeRoute(peer, sender) => {
    -571                            let has_peer = state.nodes_present.contains(&peer);
    -572                            sender.send(has_peer).ok();
    -573                        }
    -574                    }
    -575                }
    -576                _ = state.ping_tracker.timeout() => {
    -577                    break Err(PingTimeoutSnafu.build());
    -578                }
    -579                _ = ping_interval.tick() => {
    -580                    let data = state.ping_tracker.new_ping();
    -581                    let fut = client_sink.send(SendMessage::Ping(data));
    -582                    self.run_sending(fut, &mut state, &mut client_stream).await?;
    -583                }
    -584                msg = self.inbox.recv() => {
    -585                    let Some(msg) = msg else {
    -586                        warn!("Inbox closed, shutdown.");
    -587                        break Ok(());
    -588                    };
    -589                    match msg {
    -590                        ActiveRelayMessage::SetHomeRelay(is_home) => {
    -591                            self.set_home_relay(is_home);
    -592                        }
    -593                        ActiveRelayMessage::CheckConnection(local_ips) => {
    -594                            match client_stream.local_addr() {
    -595                                Some(addr) if local_ips.contains(&addr.ip()) => {
    -596                                    let data = state.ping_tracker.new_ping();
    -597                                    let fut = client_sink.send(SendMessage::Ping(data));
    -598                                    self.run_sending(fut, &mut state, &mut client_stream).await?;
    -599                                }
    -600                                Some(_) => break Err(LocalIpInvalidSnafu.build()),
    -601                                None => break Err(LocalAddrMissingSnafu.build()),
    -602                            }
    -603                        }
    -604                        #[cfg(test)]
    -605                        ActiveRelayMessage::GetLocalAddr(sender) => {
    -606                            let addr = client_stream.local_addr();
    -607                            sender.send(addr).ok();
    -608                        }
    -609                        #[cfg(test)]
    -610                        ActiveRelayMessage::PingServer(sender) => {
    -611                            let data = rand::random();
    -612                            state.test_pong = Some((data, sender));
    -613                            let fut = client_sink.send(SendMessage::Ping(data));
    -614                            self.run_sending(fut, &mut state, &mut client_stream).await?;
    -615                        }
    -616                    }
    -617                }
    -618                count = self.relay_datagrams_send.recv_many(
    -619                    &mut send_datagrams_buf,
    -620                    SEND_DATAGRAM_BATCH_SIZE,
    -621                ) => {
    -622                    if count == 0 {
    -623                        warn!("Datagram inbox closed, shutdown");
    -624                        break Ok(());
    -625                    };
    -626                    self.reset_inactive_timeout();
    -627                    // TODO: This allocation is *very* unfortunate.  But so is the
    -628                    // allocation *inside* of PacketizeIter...
    -629                    let dgrams = std::mem::replace(
    -630                        &mut send_datagrams_buf,
    -631                        Vec::with_capacity(SEND_DATAGRAM_BATCH_SIZE),
    -632                    );
    -633                    // TODO(frando): can we avoid the clone here?
    -634                    let metrics = self.metrics.clone();
    -635                    let packet_iter = dgrams.into_iter().flat_map(|datagrams| {
    -636                        PacketizeIter::<_, MAX_PAYLOAD_SIZE>::new(
    -637                            datagrams.remote_node,
    -638                            datagrams.datagrams.clone(),
    -639                        )
    -640                        .map(|p| {
    -641                            Ok(SendMessage::SendPacket(p.node_id, p.payload))
    -642                        })
    -643                    });
    -644                    let mut packet_stream = n0_future::stream::iter(packet_iter).inspect(|m| {
    -645                        if let Ok(SendMessage::SendPacket(_node_id, payload)) = m {
    -646                            metrics.send_relay.inc_by(payload.len() as _);
    -647                        }
    -648                    });
    -649                    let fut = client_sink.send_all(&mut packet_stream);
    -650                    self.run_sending(fut, &mut state, &mut client_stream).await?;
    -651                }
    -652                msg = client_stream.next() => {
    -653                    let Some(msg) = msg else {
    -654                        break Err(StreamClosedServerSnafu.build());
    -655                    };
    -656                    match msg {
    -657                        Ok(msg) => {
    -658                            self.handle_relay_msg(msg, &mut state);
    -659                            // reset the ping timer, we have just received a message
    -660                            ping_interval.reset();
    -661                        },
    -662                        Err(err) => break Err(ClientStreamReadSnafu.into_error(err)),
    -663                    }
    -664                }
    -665                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
    -666                    debug!("Inactive for {RELAY_INACTIVE_CLEANUP_TIME:?}, exiting.");
    -667                    break Ok(());
    -668                }
    -669            }
    -670        };
    -671
    -672        if res.is_ok() {
    -673            if let Err(err) = client_sink.close().await {
    -674                debug!("Failed to close client sink gracefully: {err:#}");
    -675            }
    -676        }
    -677
    -678        res.map_err(|err| state.map_err(err))
    -679    }
    -680
    -681    fn handle_relay_msg(&mut self, msg: ReceivedMessage, state: &mut ConnectedRelayState) {
    -682        match msg {
    -683            ReceivedMessage::ReceivedPacket {
    -684                remote_node_id,
    -685                data,
    -686            } => {
    -687                trace!(len = %data.len(), "received msg");
    -688                // If this is a new sender, register a route for this peer.
    -689                if state
    -690                    .last_packet_src
    -691                    .as_ref()
    -692                    .map(|p| *p != remote_node_id)
    -693                    .unwrap_or(true)
    -694                {
    -695                    // Avoid map lookup with high throughput single peer.
    -696                    state.last_packet_src = Some(remote_node_id);
    -697                    state.nodes_present.insert(remote_node_id);
    -698                }
    -699                for datagram in PacketSplitIter::new(self.url.clone(), remote_node_id, data) {
    -700                    let Ok(datagram) = datagram else {
    -701                        warn!("Invalid packet split");
    -702                        break;
    -703                    };
    -704                    if let Err(err) = self.relay_datagrams_recv.try_send(datagram) {
    -705                        warn!("Dropping received relay packet: {err:#}");
    -706                    }
    -707                }
    -708            }
    -709            ReceivedMessage::NodeGone(node_id) => {
    -710                state.nodes_present.remove(&node_id);
    -711            }
    -712            ReceivedMessage::Ping(data) => state.pong_pending = Some(data),
    -713            ReceivedMessage::Pong(data) => {
    -714                #[cfg(test)]
    -715                {
    -716                    if let Some((expected_data, sender)) = state.test_pong.take() {
    -717                        if data == expected_data {
    -718                            sender.send(()).ok();
    -719                        } else {
    -720                            state.test_pong = Some((expected_data, sender));
    -721                        }
    -722                    }
    -723                }
    -724                state.ping_tracker.pong_received(data);
    -725                state.established = true;
    -726            }
    -727            ReceivedMessage::Health { problem } => {
    -728                let problem = problem.as_deref().unwrap_or("unknown");
    -729                warn!("Relay server reports problem: {problem}");
    -730            }
    -731            ReceivedMessage::KeepAlive | ReceivedMessage::ServerRestarting { .. } => {
    -732                trace!("Ignoring {msg:?}")
    -733            }
    -734        }
    -735    }
    -736
    -737    /// Run the actor main loop while sending to the relay server.
    -738    ///
    -739    /// While sending the actor should not read any inboxes which will give it more things
    -740    /// to send to the relay server.
    -741    ///
    -742    /// # Returns
    -743    ///
    -744    /// On `Err` the relay connection should be disconnected.  An `Ok` return means either
    -745    /// the actor should shut down, consult the [`ActiveRelayActor::stop_token`] and
    -746    /// [`ActiveRelayActor::inactive_timeout`] for this, or the send was successful.
    -747    #[instrument(name = "tx", skip_all)]
    -748    async fn run_sending<T>(
    -749        &mut self,
    -750        sending_fut: impl Future<Output = Result<T, RunError>>,
    -751        state: &mut ConnectedRelayState,
    -752        client_stream: &mut iroh_relay::client::ClientStream,
    -753    ) -> Result<(), RelayConnectionError> {
    -754        // we use the same time as for our ping interval
    -755        let send_timeout = PING_INTERVAL;
    -756
    -757        let mut timeout = pin!(time::sleep(send_timeout));
    -758        let mut sending_fut = pin!(sending_fut);
    -759        let res = loop {
    -760            tokio::select! {
    -761                biased;
    -762                _ = self.stop_token.cancelled() => {
    -763                    break Ok(());
    -764                }
    -765                _ = &mut timeout => {
    -766                    break Err(SendTimeoutSnafu.build());
    -767                }
    -768                msg = self.prio_inbox.recv() => {
    -769                    let Some(msg) = msg else {
    -770                        warn!("Priority inbox closed, shutdown.");
    -771                        break Ok(());
    -772                    };
    -773                    match msg {
    -774                        ActiveRelayPrioMessage::HasNodeRoute(peer, sender) => {
    -775                            let has_peer = state.nodes_present.contains(&peer);
    -776                            sender.send(has_peer).ok();
    -777                        }
    -778                    }
    -779                }
    -780                res = &mut sending_fut => {
    -781                    match res {
    -782                        Ok(_) => break Ok(()),
    -783                        Err(err) => break Err(err),
    -784                    }
    -785                }
    -786                _ = state.ping_tracker.timeout() => {
    -787                    break Err(PingTimeoutSnafu.build());
    -788                }
    -789                // No need to read the inbox or datagrams to send.
    -790                msg = client_stream.next() => {
    -791                    let Some(msg) = msg else {
    -792                        break Err(StreamClosedServerSnafu.build());
    -793                    };
    -794                    match msg {
    -795                        Ok(msg) => self.handle_relay_msg(msg, state),
    -796                        Err(err) => break Err(ClientStreamReadSnafu.into_error(err)),
    -797                    }
    -798                }
    -799                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
    -800                    debug!("Inactive for {RELAY_INACTIVE_CLEANUP_TIME:?}, exiting.");
    -801                    break Ok(());
    -802                }
    -803            }
    -804        };
    -805        res.map_err(|err| state.map_err(err))
    -806    }
    -807}
    -808
    -809/// Shared state when the [`ActiveRelayActor`] is connected to a relay server.
    -810///
    -811/// Common state between [`ActiveRelayActor::run_connected`] and
    -812/// [`ActiveRelayActor::run_sending`].
    -813#[derive(Debug)]
    -814struct ConnectedRelayState {
    -815    /// Tracks pings we have sent, awaits pong replies.
    -816    ping_tracker: PingTracker,
    -817    /// Nodes which are reachable via this relay server.
    -818    nodes_present: BTreeSet<NodeId>,
    -819    /// The [`NodeId`] from whom we received the last packet.
    -820    ///
    -821    /// This is to avoid a slower lookup in the [`ConnectedRelayState::nodes_present`] map
    -822    /// when we are only communicating to a single remote node.
    -823    last_packet_src: Option<NodeId>,
    -824    /// A pong we need to send ASAP.
    -825    pong_pending: Option<[u8; 8]>,
    -826    /// Whether the connection is to be considered established.
    -827    ///
    -828    /// This is set to `true` once a pong was received from the server.
    -829    established: bool,
    -830    #[cfg(test)]
    -831    test_pong: Option<([u8; 8], oneshot::Sender<()>)>,
    -832}
    -833
    -834impl ConnectedRelayState {
    -835    fn map_err(&self, error: RunError) -> RelayConnectionError {
    -836        if self.established {
    -837            EstablishedSnafu.into_error(error)
    -838        } else {
    -839            HandshakeSnafu.into_error(error)
    -840        }
    -841    }
    -842}
    -843
    -844pub(super) enum RelayActorMessage {
    -845    MaybeCloseRelaysOnRebind(Vec<IpAddr>),
    -846    SetHome { url: RelayUrl },
    -847}
    -848
    -849#[derive(Debug, Clone)]
    -850pub(super) struct RelaySendItem {
    -851    /// The destination for the datagrams.
    -852    pub(super) remote_node: NodeId,
    -853    /// The home relay of the remote node.
    -854    pub(super) url: RelayUrl,
    -855    /// One or more datagrams to send.
    -856    pub(super) datagrams: RelayContents,
    -857}
    -858
    -859pub(super) struct RelayActor {
    -860    msock: Arc<MagicSock>,
    -861    /// Queue on which to put received datagrams.
    -862    ///
    -863    /// [`AsyncUdpSocket::poll_recv`] will read from this queue.
    -864    ///
    -865    /// [`AsyncUdpSocket::poll_recv`]: quinn::AsyncUdpSocket::poll_recv
    -866    relay_datagram_recv_queue: Arc<RelayDatagramRecvQueue>,
    -867    /// The actors managing each currently used relay server.
    -868    ///
    -869    /// These actors will exit when they have any inactivity.  Otherwise they will keep
    -870    /// trying to maintain a connection to the relay server as needed.
    -871    active_relays: BTreeMap<RelayUrl, ActiveRelayHandle>,
    -872    /// The tasks for the [`ActiveRelayActor`]s in `active_relays` above.
    -873    active_relay_tasks: JoinSet<()>,
    -874    cancel_token: CancellationToken,
    -875    protocol: iroh_relay::http::Protocol,
    -876}
    -877
    -878impl RelayActor {
    -879    pub(super) fn new(
    -880        msock: Arc<MagicSock>,
    -881        relay_datagram_recv_queue: Arc<RelayDatagramRecvQueue>,
    -882        protocol: iroh_relay::http::Protocol,
    -883    ) -> Self {
    -884        let cancel_token = CancellationToken::new();
    -885        Self {
    -886            msock,
    -887            relay_datagram_recv_queue,
    -888            active_relays: Default::default(),
    -889            active_relay_tasks: JoinSet::new(),
    -890            cancel_token,
    -891            protocol,
    -892        }
    -893    }
    -894
    -895    pub(super) fn cancel_token(&self) -> CancellationToken {
    -896        self.cancel_token.clone()
    -897    }
    -898
    -899    pub(super) async fn run(
    -900        mut self,
    -901        mut receiver: mpsc::Receiver<RelayActorMessage>,
    -902        mut datagram_send_channel: RelayDatagramSendChannelReceiver,
    -903    ) {
    -904        // When this future is present, it is sending pending datagrams to an
    -905        // ActiveRelayActor.  We can not process further datagrams during this time.
    -906        let mut datagram_send_fut = std::pin::pin!(MaybeFuture::none());
    -907
    -908        loop {
    -909            tokio::select! {
    -910                biased;
    -911                _ = self.cancel_token.cancelled() => {
    -912                    debug!("shutting down");
    -913                    break;
    -914                }
    -915                Some(res) = self.active_relay_tasks.join_next() => {
    -916                    match res {
    -917                        Ok(()) => (),
    -918                        Err(err) if err.is_panic() => {
    -919                            error!("ActiveRelayActor task panicked: {err:#?}");
    -920                        }
    -921                        Err(err) if err.is_cancelled() => {
    -922                            error!("ActiveRelayActor cancelled: {err:#?}");
    -923                        }
    -924                        Err(err) => error!("ActiveRelayActor failed: {err:#?}"),
    -925                    }
    -926                    self.reap_active_relays();
    -927                }
    -928                msg = receiver.recv() => {
    -929                    let Some(msg) = msg else {
    -930                        debug!("Inbox dropped, shutting down.");
    -931                        break;
    -932                    };
    -933                    let cancel_token = self.cancel_token.child_token();
    -934                    cancel_token.run_until_cancelled(self.handle_msg(msg)).await;
    -935                }
    -936                // Only poll for new datagrams if we are not blocked on sending them.
    -937                item = datagram_send_channel.recv(), if datagram_send_fut.is_none() => {
    -938                    let Some(item) = item else {
    -939                        debug!("Datagram send channel dropped, shutting down.");
    -940                        break;
    -941                    };
    -942                    let token = self.cancel_token.child_token();
    -943                    if let Some(Some(fut)) = token.run_until_cancelled(
    -944                        self.try_send_datagram(item)
    -945                    ).await {
    -946                        datagram_send_fut.as_mut().set_future(fut);
    -947                    }
    -948                }
    -949                // Only poll this future if it is in use.
    -950                _ = &mut datagram_send_fut, if datagram_send_fut.is_some() => {
    -951                    datagram_send_fut.as_mut().set_none();
    -952                }
    -953            }
    -954        }
    -955
    -956        // try shutdown
    -957        if time::timeout(Duration::from_secs(3), self.close_all_active_relays())
    -958            .await
    -959            .is_err()
    -960        {
    -961            warn!("Failed to shut down all ActiveRelayActors");
    -962        }
    -963    }
    -964
    -965    async fn handle_msg(&mut self, msg: RelayActorMessage) {
    -966        match msg {
    -967            RelayActorMessage::SetHome { url } => {
    -968                self.set_home_relay(url).await;
    -969            }
    -970            RelayActorMessage::MaybeCloseRelaysOnRebind(ifs) => {
    -971                self.maybe_close_relays_on_rebind(&ifs).await;
    -972            }
    -973        }
    -974    }
    -975
    -976    /// Sends datagrams to the correct [`ActiveRelayActor`], or returns a future.
    -977    ///
    -978    /// If the datagram can not be sent immediately, because the destination channel is
    -979    /// full, a future is returned that will complete once the datagrams have been sent to
    -980    /// the [`ActiveRelayActor`].
    -981    async fn try_send_datagram(&mut self, item: RelaySendItem) -> Option<impl Future<Output = ()>> {
    -982        let url = item.url.clone();
    -983        let handle = self
    -984            .active_relay_handle_for_node(&item.url, &item.remote_node)
    -985            .await;
    -986        match handle.datagrams_send_queue.try_send(item) {
    -987            Ok(()) => None,
    -988            Err(mpsc::error::TrySendError::Closed(_)) => {
    -989                warn!(?url, "Dropped datagram(s): ActiveRelayActor closed.");
    -990                None
    -991            }
    -992            Err(mpsc::error::TrySendError::Full(item)) => {
    -993                let sender = handle.datagrams_send_queue.clone();
    -994                let fut = async move {
    -995                    if sender.send(item).await.is_err() {
    -996                        warn!(?url, "Dropped datagram(s): ActiveRelayActor closed.");
    -997                    }
    -998                };
    -999                Some(fut)
    -1000            }
    -1001        }
    -1002    }
    -1003
    -1004    async fn set_home_relay(&mut self, home_url: RelayUrl) {
    -1005        let home_url_ref = &home_url;
    -1006        n0_future::join_all(self.active_relays.iter().map(|(url, handle)| async move {
    -1007            let is_preferred = url == home_url_ref;
    -1008            handle
    -1009                .inbox_addr
    -1010                .send(ActiveRelayMessage::SetHomeRelay(is_preferred))
    -1011                .await
    -1012                .ok()
    -1013        }))
    -1014        .await;
    -1015        // Ensure we have an ActiveRelayActor for the current home relay.
    -1016        self.active_relay_handle(home_url);
    -1017    }
    -1018
    -1019    /// Returns the handle for the [`ActiveRelayActor`] to reach `remote_node`.
    -1020    ///
    -1021    /// The node is expected to be reachable on `url`, but if no [`ActiveRelayActor`] for
    -1022    /// `url` exists but another existing [`ActiveRelayActor`] already knows about the node,
    -1023    /// that other node is used.
    -1024    async fn active_relay_handle_for_node(
    -1025        &mut self,
    -1026        url: &RelayUrl,
    -1027        remote_node: &NodeId,
    -1028    ) -> ActiveRelayHandle {
    -1029        if let Some(handle) = self.active_relays.get(url) {
    -1030            return handle.clone();
    -1031        }
    -1032
    -1033        let mut found_relay: Option<RelayUrl> = None;
    -1034        // If we don't have an open connection to the remote node's home relay, see if
    -1035        // we have an open connection to a relay node where we'd heard from that peer
    -1036        // already.  E.g. maybe they dialed our home relay recently.
    -1037        {
    -1038            // Futures which return Some(RelayUrl) if the relay knows about the remote node.
    -1039            let check_futs = self.active_relays.iter().map(|(url, handle)| async move {
    -1040                let (tx, rx) = oneshot::channel();
    -1041                handle
    -1042                    .prio_inbox_addr
    -1043                    .send(ActiveRelayPrioMessage::HasNodeRoute(*remote_node, tx))
    -1044                    .await
    -1045                    .ok();
    -1046                match rx.await {
    -1047                    Ok(true) => Some(url.clone()),
    -1048                    _ => None,
    -1049                }
    -1050            });
    -1051            let mut futures = FuturesUnorderedBounded::from_iter(check_futs);
    -1052            while let Some(maybe_url) = futures.next().await {
    -1053                if maybe_url.is_some() {
    -1054                    found_relay = maybe_url;
    -1055                    break;
    -1056                }
    -1057            }
    -1058        }
    -1059        let url = found_relay.unwrap_or(url.clone());
    -1060        self.active_relay_handle(url)
    -1061    }
    -1062
    -1063    /// Returns the handle of the [`ActiveRelayActor`].
    -1064    fn active_relay_handle(&mut self, url: RelayUrl) -> ActiveRelayHandle {
    -1065        match self.active_relays.get(&url) {
    -1066            Some(e) => e.clone(),
    -1067            None => {
    -1068                let handle = self.start_active_relay(url.clone());
    -1069                if Some(&url) == self.msock.my_relay().as_ref() {
    -1070                    if let Err(err) = handle
    -1071                        .inbox_addr
    -1072                        .try_send(ActiveRelayMessage::SetHomeRelay(true))
    -1073                    {
    -1074                        error!("Home relay not set, send to new actor failed: {err:#}.");
    -1075                    }
    -1076                }
    -1077                self.active_relays.insert(url, handle.clone());
    -1078                self.log_active_relay();
    -1079                handle
    -1080            }
    -1081        }
    -1082    }
    -1083
    -1084    fn start_active_relay(&mut self, url: RelayUrl) -> ActiveRelayHandle {
    -1085        debug!(?url, "Adding relay connection");
    -1086
    -1087        let connection_opts = RelayConnectionOptions {
    -1088            secret_key: self.msock.secret_key.clone(),
    -1089            #[cfg(not(wasm_browser))]
    -1090            dns_resolver: self.msock.dns_resolver.clone(),
    -1091            proxy_url: self.msock.proxy_url().cloned(),
    -1092            prefer_ipv6: self.msock.ipv6_reported.clone(),
    -1093            #[cfg(any(test, feature = "test-utils"))]
    -1094            insecure_skip_cert_verify: self.msock.insecure_skip_relay_cert_verify,
    -1095            protocol: self.protocol,
    -1096        };
    -1097
    -1098        // TODO: Replace 64 with PER_CLIENT_SEND_QUEUE_DEPTH once that's unused
    -1099        let (send_datagram_tx, send_datagram_rx) = mpsc::channel(64);
    -1100        let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(32);
    -1101        let (inbox_tx, inbox_rx) = mpsc::channel(64);
    -1102        let span = info_span!("active-relay", %url);
    -1103        let opts = ActiveRelayActorOptions {
    -1104            url,
    -1105            prio_inbox_: prio_inbox_rx,
    -1106            inbox: inbox_rx,
    -1107            relay_datagrams_send: send_datagram_rx,
    -1108            relay_datagrams_recv: self.relay_datagram_recv_queue.clone(),
    -1109            connection_opts,
    -1110            stop_token: self.cancel_token.child_token(),
    -1111            metrics: self.msock.metrics.magicsock.clone(),
    -1112        };
    -1113        let actor = ActiveRelayActor::new(opts);
    -1114        self.active_relay_tasks.spawn(
    -1115            async move {
    -1116                actor.run().await;
    -1117            }
    -1118            .instrument(span),
    -1119        );
    -1120        let handle = ActiveRelayHandle {
    -1121            prio_inbox_addr: prio_inbox_tx,
    -1122            inbox_addr: inbox_tx,
    -1123            datagrams_send_queue: send_datagram_tx,
    -1124        };
    -1125        self.log_active_relay();
    -1126        handle
    -1127    }
    -1128
    -1129    /// Closes the relay connections not originating from a local IP address.
    -1130    ///
    -1131    /// Called in response to a rebind, any relay connection originating from an address
    -1132    /// that's not known to be currently a local IP address should be closed.  All the other
    -1133    /// relay connections are pinged.
    -1134    async fn maybe_close_relays_on_rebind(&mut self, okay_local_ips: &[IpAddr]) {
    -1135        let send_futs = self.active_relays.values().map(|handle| async move {
    -1136            handle
    -1137                .inbox_addr
    -1138                .send(ActiveRelayMessage::CheckConnection(okay_local_ips.to_vec()))
    -1139                .await
    -1140                .ok();
    -1141        });
    -1142        n0_future::join_all(send_futs).await;
    -1143        self.log_active_relay();
    -1144    }
    -1145
    -1146    /// Cleans up [`ActiveRelayActor`]s which have stopped running.
    -1147    fn reap_active_relays(&mut self) {
    -1148        self.active_relays
    -1149            .retain(|_url, handle| !handle.inbox_addr.is_closed());
    -1150
    -1151        // Make sure home relay exists
    -1152        if let Some(ref url) = self.msock.my_relay() {
    -1153            self.active_relay_handle(url.clone());
    -1154        }
    -1155        self.log_active_relay();
    -1156    }
    -1157
    -1158    /// Stops all [`ActiveRelayActor`]s and awaits for them to finish.
    -1159    async fn close_all_active_relays(&mut self) {
    -1160        self.cancel_token.cancel();
    -1161        let tasks = std::mem::take(&mut self.active_relay_tasks);
    -1162        tasks.join_all().await;
    -1163
    -1164        self.log_active_relay();
    -1165    }
    -1166
    -1167    fn log_active_relay(&self) {
    -1168        debug!("{} active relay conns{}", self.active_relays.len(), {
    -1169            let mut s = String::new();
    -1170            if !self.active_relays.is_empty() {
    -1171                s += ":";
    -1172                for node in self.active_relay_sorted() {
    -1173                    s += &format!(" relay-{}", node,);
    -1174                }
    -1175            }
    -1176            s
    -1177        });
    -1178    }
    -1179
    -1180    fn active_relay_sorted(&self) -> impl Iterator<Item = RelayUrl> {
    -1181        let mut ids: Vec<_> = self.active_relays.keys().cloned().collect();
    -1182        ids.sort();
    -1183
    -1184        ids.into_iter()
    -1185    }
    -1186}
    -1187
    -1188/// Handle to one [`ActiveRelayActor`].
    -1189#[derive(Debug, Clone)]
    -1190struct ActiveRelayHandle {
    -1191    prio_inbox_addr: mpsc::Sender<ActiveRelayPrioMessage>,
    -1192    inbox_addr: mpsc::Sender<ActiveRelayMessage>,
    -1193    datagrams_send_queue: mpsc::Sender<RelaySendItem>,
    -1194}
    -1195
    -1196/// A packet to send over the relay.
    -1197///
    -1198/// This is nothing but a newtype, it should be constructed using [`PacketizeIter`].  This
    -1199/// is a packet of one or more datagrams, each prefixed with a u16-be length.  This is what
    -1200/// the `Frame::SendPacket` of the `DerpCodec` transports and is produced by
    -1201/// [`PacketizeIter`] and transformed back into datagrams using [`PacketSplitIter`].
    -1202#[derive(Debug, PartialEq, Eq)]
    -1203struct RelaySendPacket {
    -1204    node_id: NodeId,
    -1205    payload: Bytes,
    -1206}
    -1207
    -1208/// A single datagram received from a relay server.
    -1209///
    -1210/// This could be either a QUIC or DISCO packet.
    -1211#[derive(Debug)]
    -1212pub(super) struct RelayRecvDatagram {
    -1213    pub(super) url: RelayUrl,
    -1214    pub(super) src: NodeId,
    -1215    pub(super) buf: Bytes,
    -1216}
    -1217
    -1218/// Combines datagrams into a single DISCO frame of at most MAX_PACKET_SIZE.
    -1219///
    -1220/// The disco `iroh_relay::protos::Frame::SendPacket` frame can contain more then a single
    -1221/// datagram.  Each datagram in this frame is prefixed with a little-endian 2-byte length
    -1222/// prefix.  This occurs when Quinn sends a GSO transmit containing more than one datagram,
    -1223/// which are split using [`crate::magicsock::split_packets`].
    -1224///
    -1225/// The [`PacketSplitIter`] does the inverse and splits such packets back into individual
    -1226/// datagrams.
    -1227struct PacketizeIter<I: Iterator, const N: usize> {
    -1228    node_id: NodeId,
    -1229    iter: std::iter::Peekable<I>,
    -1230    buffer: BytesMut,
    -1231}
    -1232
    -1233impl<I: Iterator, const N: usize> PacketizeIter<I, N> {
    -1234    /// Create a new new PacketizeIter from something that can be turned into an
    -1235    /// iterator of slices, like a `Vec<Bytes>`.
    -1236    fn new(node_id: NodeId, iter: impl IntoIterator<IntoIter = I>) -> Self {
    -1237        Self {
    -1238            node_id,
    -1239            iter: iter.into_iter().peekable(),
    -1240            buffer: BytesMut::with_capacity(N),
    -1241        }
    -1242    }
    -1243}
    -1244
    -1245impl<I: Iterator, const N: usize> Iterator for PacketizeIter<I, N>
    -1246where
    -1247    I::Item: AsRef<[u8]>,
    -1248{
    -1249    type Item = RelaySendPacket;
    -1250
    -1251    fn next(&mut self) -> Option<Self::Item> {
    -1252        use bytes::BufMut;
    -1253        while let Some(next_bytes) = self.iter.peek() {
    -1254            let next_bytes = next_bytes.as_ref();
    -1255            assert!(next_bytes.len() + 2 <= N);
    -1256            let next_length: u16 = next_bytes.len().try_into().expect("items < 64k size");
    -1257            if self.buffer.len() + next_bytes.len() + 2 > N {
    -1258                break;
    -1259            }
    -1260            self.buffer.put_u16_le(next_length);
    -1261            self.buffer.put_slice(next_bytes);
    -1262            self.iter.next();
    -1263        }
    -1264        if !self.buffer.is_empty() {
    -1265            Some(RelaySendPacket {
    -1266                node_id: self.node_id,
    -1267                payload: self.buffer.split().freeze(),
    -1268            })
    -1269        } else {
    -1270            None
    -1271        }
    -1272    }
    -1273}
    -1274
    -1275/// Splits a single [`ReceivedMessage::ReceivedPacket`] frame into datagrams.
    -1276///
    -1277/// This splits packets joined by [`PacketizeIter`] back into individual datagrams.  See
    -1278/// that struct for more details.
    -1279#[derive(Debug)]
    -1280struct PacketSplitIter {
    -1281    url: RelayUrl,
    -1282    src: NodeId,
    -1283    bytes: Bytes,
    -1284}
    -1285
    -1286impl PacketSplitIter {
    -1287    /// Create a new PacketSplitIter from a packet.
    -1288    fn new(url: RelayUrl, src: NodeId, bytes: Bytes) -> Self {
    -1289        Self { url, src, bytes }
    -1290    }
    -1291
    -1292    fn fail(&mut self) -> Option<std::io::Result<RelayRecvDatagram>> {
    -1293        self.bytes.clear();
    -1294        Some(Err(std::io::Error::new(
    -1295            std::io::ErrorKind::UnexpectedEof,
    -1296            "",
    -1297        )))
    -1298    }
    -1299}
    -1300
    -1301impl Iterator for PacketSplitIter {
    -1302    type Item = std::io::Result<RelayRecvDatagram>;
    -1303
    -1304    fn next(&mut self) -> Option<Self::Item> {
    -1305        use bytes::Buf;
    -1306        if self.bytes.has_remaining() {
    -1307            if self.bytes.remaining() < 2 {
    -1308                return self.fail();
    -1309            }
    -1310            let len = self.bytes.get_u16_le() as usize;
    -1311            if self.bytes.remaining() < len {
    -1312                return self.fail();
    -1313            }
    -1314            let buf = self.bytes.split_to(len);
    -1315            Some(Ok(RelayRecvDatagram {
    -1316                url: self.url.clone(),
    -1317                src: self.src,
    -1318                buf,
    -1319            }))
    -1320        } else {
    -1321            None
    -1322        }
    -1323    }
    -1324}
    -1325
    -1326#[cfg(test)]
    -1327mod tests {
    -1328    use std::{
    -1329        sync::{atomic::AtomicBool, Arc},
    -1330        time::Duration,
    -1331    };
    -1332
    -1333    use bytes::Bytes;
    -1334    use iroh_base::{NodeId, RelayUrl, SecretKey};
    -1335    use iroh_relay::PingTracker;
    -1336    use n0_future::future;
    -1337    use n0_snafu::{Error, Result, ResultExt};
    -1338    use smallvec::smallvec;
    -1339    use tokio::sync::{mpsc, oneshot};
    -1340    use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle};
    -1341    use tracing::{info, info_span, Instrument};
    -1342    use tracing_test::traced_test;
    -1343
    -1344    use super::{
    -1345        ActiveRelayActor, ActiveRelayActorOptions, ActiveRelayMessage, ActiveRelayPrioMessage,
    -1346        RelayConnectionOptions, RelaySendItem, MAX_PACKET_SIZE,
    -1347    };
    -1348    use crate::{
    -1349        dns::DnsResolver,
    -1350        magicsock::{
    -1351            relay_actor::{
    -1352                PacketizeIter, RELAY_INACTIVE_CLEANUP_TIME, UNDELIVERABLE_DATAGRAM_TIMEOUT,
    -1353            },
    -1354            RelayDatagramRecvQueue, RelayRecvDatagram,
    -1355        },
    -1356        test_utils,
    -1357    };
    -1358
    -1359    #[test]
    -1360    fn test_packetize_iter() {
    -1361        let node_id = SecretKey::generate(rand::thread_rng()).public();
    -1362        let empty_vec: Vec<Bytes> = Vec::new();
    -1363        let mut iter = PacketizeIter::<_, MAX_PACKET_SIZE>::new(node_id, empty_vec);
    -1364        assert_eq!(None, iter.next());
    -1365
    -1366        let single_vec = vec!["Hello"];
    -1367        let iter = PacketizeIter::<_, MAX_PACKET_SIZE>::new(node_id, single_vec);
    -1368        let result = iter.collect::<Vec<_>>();
    -1369        assert_eq!(1, result.len());
    -1370        assert_eq!(
    -1371            &[5, 0, b'H', b'e', b'l', b'l', b'o'],
    -1372            &result[0].payload[..]
    -1373        );
    -1374
    -1375        let spacer = vec![0u8; MAX_PACKET_SIZE - 10];
    -1376        let multiple_vec = vec![&b"Hello"[..], &spacer, &b"World"[..]];
    -1377        let iter = PacketizeIter::<_, MAX_PACKET_SIZE>::new(node_id, multiple_vec);
    -1378        let result = iter.collect::<Vec<_>>();
    -1379        assert_eq!(2, result.len());
    -1380        assert_eq!(
    -1381            &[5, 0, b'H', b'e', b'l', b'l', b'o'],
    -1382            &result[0].payload[..7]
    -1383        );
    -1384        assert_eq!(
    -1385            &[5, 0, b'W', b'o', b'r', b'l', b'd'],
    -1386            &result[1].payload[..]
    -1387        );
    -1388    }
    -1389
    -1390    /// Starts a new [`ActiveRelayActor`].
    -1391    #[allow(clippy::too_many_arguments)]
    -1392    fn start_active_relay_actor(
    -1393        secret_key: SecretKey,
    -1394        stop_token: CancellationToken,
    -1395        url: RelayUrl,
    -1396        prio_inbox_rx: mpsc::Receiver<ActiveRelayPrioMessage>,
    -1397        inbox_rx: mpsc::Receiver<ActiveRelayMessage>,
    -1398        relay_datagrams_send: mpsc::Receiver<RelaySendItem>,
    -1399        relay_datagrams_recv: Arc<RelayDatagramRecvQueue>,
    -1400        span: tracing::Span,
    -1401    ) -> AbortOnDropHandle<()> {
    -1402        let opts = ActiveRelayActorOptions {
    -1403            url,
    -1404            prio_inbox_: prio_inbox_rx,
    -1405            inbox: inbox_rx,
    -1406            relay_datagrams_send,
    -1407            relay_datagrams_recv,
    -1408            connection_opts: RelayConnectionOptions {
    -1409                secret_key,
    -1410                dns_resolver: DnsResolver::new(),
    -1411                proxy_url: None,
    -1412                prefer_ipv6: Arc::new(AtomicBool::new(true)),
    -1413                insecure_skip_cert_verify: true,
    -1414                protocol: iroh_relay::http::Protocol::default(),
    -1415            },
    -1416            stop_token,
    -1417            metrics: Default::default(),
    -1418        };
    -1419        let task = tokio::spawn(ActiveRelayActor::new(opts).run().instrument(span));
    -1420        AbortOnDropHandle::new(task)
    -1421    }
    -1422
    -1423    /// Starts an [`ActiveRelayActor`] as an "iroh echo node".
    -1424    ///
    -1425    /// This actor will connect to the relay server, pretending to be an iroh node, and echo
    -1426    /// back any datagram it receives from the relay.  This is used by the
    -1427    /// [`ActiveRelayNode`] under test to check connectivity works.
    -1428    fn start_echo_node(relay_url: RelayUrl) -> (NodeId, AbortOnDropHandle<()>) {
    -1429        let secret_key = SecretKey::from_bytes(&[8u8; 32]);
    -1430        let recv_datagram_queue = Arc::new(RelayDatagramRecvQueue::new());
    -1431        let (send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
    -1432        let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
    -1433        let (inbox_tx, inbox_rx) = mpsc::channel(16);
    -1434        let cancel_token = CancellationToken::new();
    -1435        let actor_task = start_active_relay_actor(
    -1436            secret_key.clone(),
    -1437            cancel_token.clone(),
    -1438            relay_url.clone(),
    -1439            prio_inbox_rx,
    -1440            inbox_rx,
    -1441            send_datagram_rx,
    -1442            recv_datagram_queue.clone(),
    -1443            info_span!("echo-node"),
    -1444        );
    -1445        let echo_task = tokio::spawn({
    -1446            let relay_url = relay_url.clone();
    -1447            async move {
    -1448                loop {
    -1449                    let datagram = future::poll_fn(|cx| recv_datagram_queue.poll_recv(cx)).await;
    -1450                    if let Ok(recv) = datagram {
    -1451                        let RelayRecvDatagram { url: _, src, buf } = recv;
    -1452                        info!(from = src.fmt_short(), "Received datagram");
    -1453                        let send = RelaySendItem {
    -1454                            remote_node: src,
    -1455                            url: relay_url.clone(),
    -1456                            datagrams: smallvec![buf],
    -1457                        };
    -1458                        send_datagram_tx.send(send).await.ok();
    -1459                    }
    -1460                }
    -1461            }
    -1462            .instrument(info_span!("echo-task"))
    -1463        });
    -1464        let echo_task = AbortOnDropHandle::new(echo_task);
    -1465        let supervisor_task = tokio::spawn(async move {
    -1466            let _guard = cancel_token.drop_guard();
    -1467            // move the inboxes here so it is not dropped, as this stops the actor.
    -1468            let _prio_inbox_tx = prio_inbox_tx;
    -1469            let _inbox_tx = inbox_tx;
    -1470            tokio::select! {
    -1471                biased;
    -1472                _ = actor_task => (),
    -1473                _ = echo_task => (),
    -1474            };
    -1475        });
    -1476        let supervisor_task = AbortOnDropHandle::new(supervisor_task);
    -1477        (secret_key.public(), supervisor_task)
    -1478    }
    -1479
    -1480    /// Sends a message to the echo node, receives the response.
    -1481    ///
    -1482    /// This takes care of retry and timeout.  Because we don't know when both the
    -1483    /// node-under-test and the echo node will be ready and datagrams aren't queued to send
    -1484    /// forever, we have to retry a few times.
    -1485    async fn send_recv_echo(
    -1486        item: RelaySendItem,
    -1487        tx: &mpsc::Sender<RelaySendItem>,
    -1488        rx: &Arc<RelayDatagramRecvQueue>,
    -1489    ) -> Result<()> {
    -1490        assert!(item.datagrams.len() == 1);
    -1491        tokio::time::timeout(Duration::from_secs(10), async move {
    -1492            loop {
    -1493                let res = tokio::time::timeout(UNDELIVERABLE_DATAGRAM_TIMEOUT, async {
    -1494                    tx.send(item.clone()).await.context("send item")?;
    -1495                    let RelayRecvDatagram {
    -1496                        url: _,
    -1497                        src: _,
    -1498                        buf,
    -1499                    } = future::poll_fn(|cx| rx.poll_recv(cx)).await?;
    -1500
    -1501                    assert_eq!(buf.as_ref(), item.datagrams[0]);
    -1502
    -1503                    Ok::<_, Error>(())
    -1504                })
    -1505                .await;
    -1506                if res.is_ok() {
    -1507                    break;
    -1508                }
    -1509            }
    -1510        })
    -1511        .await
    -1512        .expect("overall timeout exceeded");
    -1513        Ok(())
    -1514    }
    -1515
    -1516    #[tokio::test]
    -1517    #[traced_test]
    -1518    async fn test_active_relay_reconnect() -> Result {
    -1519        let (_relay_map, relay_url, _server) = test_utils::run_relay_server().await?;
    -1520        let (peer_node, _echo_node_task) = start_echo_node(relay_url.clone());
    -1521
    -1522        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
    -1523        let datagram_recv_queue = Arc::new(RelayDatagramRecvQueue::new());
    -1524        let (send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
    -1525        let (_prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
    -1526        let (inbox_tx, inbox_rx) = mpsc::channel(16);
    -1527        let cancel_token = CancellationToken::new();
    -1528        let task = start_active_relay_actor(
    -1529            secret_key,
    -1530            cancel_token.clone(),
    -1531            relay_url.clone(),
    -1532            prio_inbox_rx,
    -1533            inbox_rx,
    -1534            send_datagram_rx,
    -1535            datagram_recv_queue.clone(),
    -1536            info_span!("actor-under-test"),
    -1537        );
    -1538
    -1539        // Send a datagram to our echo node.
    -1540        info!("first echo");
    -1541        let hello_send_item = RelaySendItem {
    -1542            remote_node: peer_node,
    -1543            url: relay_url.clone(),
    -1544            datagrams: smallvec![Bytes::from_static(b"hello")],
    -1545        };
    -1546        send_recv_echo(
    -1547            hello_send_item.clone(),
    -1548            &send_datagram_tx,
    -1549            &datagram_recv_queue,
    -1550        )
    -1551        .await?;
    -1552
    -1553        // Now ask to check the connection, triggering a ping but no reconnect.
    -1554        let (tx, rx) = oneshot::channel();
    -1555        inbox_tx
    -1556            .send(ActiveRelayMessage::GetLocalAddr(tx))
    -1557            .await
    -1558            .context("send get local addr msg")?;
    -1559
    -1560        let local_addr = rx
    -1561            .await
    -1562            .context("wait for local addr msg")?
    -1563            .context("no local addr")?;
    -1564        info!(?local_addr, "check connection with addr");
    -1565        inbox_tx
    -1566            .send(ActiveRelayMessage::CheckConnection(vec![local_addr.ip()]))
    -1567            .await
    -1568            .context("send check connection message")?;
    -1569
    -1570        // Sync the ActiveRelayActor. Ping blocks it and we want to be sure it has handled
    -1571        // another inbox message before continuing.
    -1572        let (tx, rx) = oneshot::channel();
    -1573        inbox_tx
    -1574            .send(ActiveRelayMessage::GetLocalAddr(tx))
    -1575            .await
    -1576            .context("send get local addr msg")?;
    -1577        rx.await.context("recv send local addr msg")?;
    -1578
    -1579        // Echo should still work.
    -1580        info!("second echo");
    -1581        send_recv_echo(
    -1582            hello_send_item.clone(),
    -1583            &send_datagram_tx,
    -1584            &datagram_recv_queue,
    -1585        )
    -1586        .await?;
    -1587
    -1588        // Now ask to check the connection, this will reconnect without pinging because we
    -1589        // do not supply any "valid" local IP addresses.
    -1590        info!("check connection");
    -1591        inbox_tx
    -1592            .send(ActiveRelayMessage::CheckConnection(Vec::new()))
    -1593            .await
    -1594            .context("send check connection msg")?;
    -1595
    -1596        // Give some time to reconnect, mostly to sort logs rather than functional.
    -1597        tokio::time::sleep(Duration::from_millis(10)).await;
    -1598
    -1599        // Echo should still work.
    -1600        info!("third echo");
    -1601        send_recv_echo(
    -1602            hello_send_item.clone(),
    -1603            &send_datagram_tx,
    -1604            &datagram_recv_queue,
    -1605        )
    -1606        .await?;
    -1607
    -1608        // Shut down the actor.
    -1609        cancel_token.cancel();
    -1610        task.await.context("wait for task to finish")?;
    -1611
    -1612        Ok(())
    -1613    }
    -1614
    -1615    #[tokio::test]
    -1616    #[traced_test]
    -1617    async fn test_active_relay_inactive() -> Result {
    -1618        let (_relay_map, relay_url, _server) = test_utils::run_relay_server().await?;
    -1619
    -1620        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
    -1621        let datagram_recv_queue = Arc::new(RelayDatagramRecvQueue::new());
    -1622        let (_send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
    -1623        let (_prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
    -1624        let (inbox_tx, inbox_rx) = mpsc::channel(16);
    -1625        let cancel_token = CancellationToken::new();
    -1626        let mut task = start_active_relay_actor(
    -1627            secret_key,
    -1628            cancel_token.clone(),
    -1629            relay_url,
    -1630            prio_inbox_rx,
    -1631            inbox_rx,
    -1632            send_datagram_rx,
    -1633            datagram_recv_queue.clone(),
    -1634            info_span!("actor-under-test"),
    -1635        );
    -1636
    -1637        // Wait until the actor is connected to the relay server.
    -1638        tokio::time::timeout(Duration::from_secs(5), async {
    -1639            loop {
    -1640                let (tx, rx) = oneshot::channel();
    -1641                inbox_tx.send(ActiveRelayMessage::PingServer(tx)).await.ok();
    -1642                if tokio::time::timeout(Duration::from_millis(200), rx)
    -1643                    .await
    -1644                    .map(|resp| resp.is_ok())
    -1645                    .unwrap_or_default()
    -1646                {
    -1647                    break;
    -1648                }
    -1649            }
    -1650        })
    -1651        .await
    -1652        .context("timeout")?;
    -1653
    -1654        // We now have an idling ActiveRelayActor.  If we advance time just a little it
    -1655        // should stay alive.
    -1656        info!("Stepping time forwards by RELAY_INACTIVE_CLEANUP_TIME / 2");
    -1657        tokio::time::pause();
    -1658        tokio::time::advance(RELAY_INACTIVE_CLEANUP_TIME / 2).await;
    -1659        tokio::time::resume();
    -1660
    -1661        assert!(
    -1662            tokio::time::timeout(Duration::from_millis(100), &mut task)
    -1663                .await
    -1664                .is_err(),
    -1665            "actor task terminated"
    -1666        );
    -1667
    -1668        // If we advance time a lot it should finish.
    -1669        info!("Stepping time forwards by RELAY_INACTIVE_CLEANUP_TIME");
    -1670        tokio::time::pause();
    -1671        tokio::time::advance(RELAY_INACTIVE_CLEANUP_TIME).await;
    -1672        tokio::time::resume();
    -1673        assert!(
    -1674            tokio::time::timeout(Duration::from_secs(1), task)
    -1675                .await
    -1676                .is_ok(),
    -1677            "actor task still running"
    -1678        );
    -1679
    -1680        cancel_token.cancel();
    -1681
    -1682        Ok(())
    -1683    }
    -1684
    -1685    #[tokio::test]
    -1686    async fn test_ping_tracker() {
    -1687        tokio::time::pause();
    -1688        let mut tracker = PingTracker::default();
    -1689
    -1690        let ping0 = tracker.new_ping();
    -1691
    -1692        let res = tokio::time::timeout(Duration::from_secs(1), tracker.timeout()).await;
    -1693        assert!(res.is_err(), "no ping timeout has elapsed yet");
    -1694
    -1695        tracker.pong_received(ping0);
    -1696        let res = tokio::time::timeout(Duration::from_secs(10), tracker.timeout()).await;
    -1697        assert!(res.is_err(), "ping completed before timeout");
    -1698
    -1699        let _ping1 = tracker.new_ping();
    -1700
    -1701        let res = tokio::time::timeout(Duration::from_secs(10), tracker.timeout()).await;
    -1702        assert!(res.is_ok(), "ping timeout should have happened");
    -1703
    -1704        let _ping2 = tracker.new_ping();
    -1705
    -1706        tokio::time::sleep(Duration::from_secs(10)).await;
    -1707        let res = tokio::time::timeout(Duration::from_millis(1), tracker.timeout()).await;
    -1708        assert!(res.is_ok(), "ping timeout happened in the past");
    -1709
    -1710        let res = tokio::time::timeout(Duration::from_secs(10), tracker.timeout()).await;
    -1711        assert!(res.is_err(), "ping timeout should only happen once");
    -1712    }
    -1713}
    \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/magicsock/transports.rs.html b/pr/3327/docs/src/iroh/magicsock/transports.rs.html new file mode 100644 index 0000000000..c0181faf77 --- /dev/null +++ b/pr/3327/docs/src/iroh/magicsock/transports.rs.html @@ -0,0 +1,597 @@ +transports.rs - source

    iroh/magicsock/
    transports.rs

    1use std::{
    +2    io::{self, IoSliceMut},
    +3    net::{IpAddr, Ipv6Addr, SocketAddr, SocketAddrV6},
    +4    pin::Pin,
    +5    sync::{atomic::AtomicUsize, Arc},
    +6    task::{Context, Poll},
    +7};
    +8
    +9use iroh_base::{NodeId, RelayUrl};
    +10use n0_watcher::Watcher;
    +11use relay::{RelayNetworkChangeSender, RelaySender};
    +12use smallvec::SmallVec;
    +13use tracing::{error, trace, warn};
    +14
    +15#[cfg(not(wasm_browser))]
    +16mod ip;
    +17mod relay;
    +18
    +19#[cfg(not(wasm_browser))]
    +20pub(crate) use self::ip::IpTransport;
    +21#[cfg(not(wasm_browser))]
    +22use self::ip::{IpNetworkChangeSender, IpSender};
    +23pub(crate) use self::relay::{RelayActorConfig, RelayTransport};
    +24use super::{MagicSock, NetInfo};
    +25
    +26/// Manages the different underlying data transports that the magicsock
    +27/// can support.
    +28#[derive(Debug)]
    +29pub(crate) struct Transports {
    +30    #[cfg(not(wasm_browser))]
    +31    ip: Vec<IpTransport>,
    +32    relay: Vec<RelayTransport>,
    +33
    +34    poll_recv_counter: AtomicUsize,
    +35}
    +36
    +37#[cfg(not(wasm_browser))]
    +38pub(crate) type LocalAddrsWatch = n0_watcher::Map<
    +39    (
    +40        n0_watcher::Join<SocketAddr, n0_watcher::Direct<SocketAddr>>,
    +41        n0_watcher::Join<
    +42            Option<(RelayUrl, NodeId)>,
    +43            n0_watcher::Map<n0_watcher::Direct<Option<RelayUrl>>, Option<(RelayUrl, NodeId)>>,
    +44        >,
    +45    ),
    +46    Vec<Addr>,
    +47>;
    +48
    +49#[cfg(wasm_browser)]
    +50pub(crate) type LocalAddrsWatch = n0_watcher::Map<
    +51    n0_watcher::Join<
    +52        Option<(RelayUrl, NodeId)>,
    +53        n0_watcher::Map<n0_watcher::Direct<Option<RelayUrl>>, Option<(RelayUrl, NodeId)>>,
    +54    >,
    +55    Vec<Addr>,
    +56>;
    +57
    +58impl Transports {
    +59    /// Creates a new transports structure.
    +60    pub(crate) fn new(
    +61        #[cfg(not(wasm_browser))] ip: Vec<IpTransport>,
    +62        relay: Vec<RelayTransport>,
    +63    ) -> Self {
    +64        Self {
    +65            #[cfg(not(wasm_browser))]
    +66            ip,
    +67            relay,
    +68            poll_recv_counter: Default::default(),
    +69        }
    +70    }
    +71
    +72    pub(crate) fn poll_recv(
    +73        &mut self,
    +74        cx: &mut Context,
    +75        bufs: &mut [io::IoSliceMut<'_>],
    +76        metas: &mut [quinn_udp::RecvMeta],
    +77        msock: &MagicSock,
    +78    ) -> Poll<io::Result<usize>> {
    +79        debug_assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
    +80        if msock.is_closed() {
    +81            return Poll::Pending;
    +82        }
    +83
    +84        let mut source_addrs = vec![Addr::default(); metas.len()];
    +85        match self.inner_poll_recv(cx, bufs, metas, &mut source_addrs)? {
    +86            Poll::Pending | Poll::Ready(0) => Poll::Pending,
    +87            Poll::Ready(n) => {
    +88                msock.process_datagrams(&mut bufs[..n], &mut metas[..n], &source_addrs[..n]);
    +89                Poll::Ready(Ok(n))
    +90            }
    +91        }
    +92    }
    +93
    +94    /// Tries to recv data, on all available transports.
    +95    fn inner_poll_recv(
    +96        &mut self,
    +97        cx: &mut Context,
    +98        bufs: &mut [IoSliceMut<'_>],
    +99        metas: &mut [quinn_udp::RecvMeta],
    +100        source_addrs: &mut [Addr],
    +101    ) -> Poll<io::Result<usize>> {
    +102        debug_assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
    +103
    +104        macro_rules! poll_transport {
    +105            ($socket:expr) => {
    +106                match $socket.poll_recv(cx, bufs, metas, source_addrs)? {
    +107                    Poll::Pending | Poll::Ready(0) => {}
    +108                    Poll::Ready(n) => {
    +109                        return Poll::Ready(Ok(n));
    +110                    }
    +111                }
    +112            };
    +113        }
    +114
    +115        // To improve fairness, every other call reverses the ordering of polling.
    +116
    +117        let counter = self
    +118            .poll_recv_counter
    +119            .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    +120
    +121        if counter % 2 == 0 {
    +122            #[cfg(not(wasm_browser))]
    +123            for transport in &mut self.ip {
    +124                poll_transport!(transport);
    +125            }
    +126            for transport in &mut self.relay {
    +127                poll_transport!(transport);
    +128            }
    +129        } else {
    +130            for transport in self.relay.iter_mut().rev() {
    +131                poll_transport!(transport);
    +132            }
    +133            #[cfg(not(wasm_browser))]
    +134            for transport in self.ip.iter_mut().rev() {
    +135                poll_transport!(transport);
    +136            }
    +137        }
    +138
    +139        Poll::Pending
    +140    }
    +141
    +142    /// Returns a list of all currently known local addresses.
    +143    ///
    +144    /// For IP based transports this is the [`SocketAddr`] of the socket,
    +145    /// for relay transports, this is the home relay.
    +146    pub(crate) fn local_addrs(&self) -> Vec<Addr> {
    +147        self.local_addrs_watch().get().expect("not disconnected")
    +148    }
    +149
    +150    /// Watch for all currently known local addresses.
    +151    #[cfg(not(wasm_browser))]
    +152    pub(crate) fn local_addrs_watch(&self) -> LocalAddrsWatch {
    +153        let ips = n0_watcher::Join::new(self.ip.iter().map(|t| t.local_addr_watch()));
    +154        let relays = n0_watcher::Join::new(self.relay.iter().map(|t| t.local_addr_watch()));
    +155
    +156        (ips, relays)
    +157            .map(|(ips, relays)| {
    +158                ips.into_iter()
    +159                    .map(Addr::from)
    +160                    .chain(
    +161                        relays
    +162                            .into_iter()
    +163                            .flatten()
    +164                            .map(|(relay_url, node_id)| Addr::Relay(relay_url, node_id)),
    +165                    )
    +166                    .collect()
    +167            })
    +168            .expect("disconnected")
    +169    }
    +170
    +171    #[cfg(wasm_browser)]
    +172    pub(crate) fn local_addrs_watch(&self) -> LocalAddrsWatch {
    +173        let relays = self.relay.iter().map(|t| t.local_addr_watch());
    +174        n0_watcher::Join::new(relays)
    +175            .map(|relays| relays.into_iter().flatten().map(Addr::from).collect())
    +176            .expect("disconnected")
    +177    }
    +178
    +179    /// Returns the bound addresses for IP based transports
    +180    #[cfg(not(wasm_browser))]
    +181    pub(crate) fn ip_bind_addrs(&self) -> Vec<SocketAddr> {
    +182        self.ip.iter().map(|t| t.bind_addr()).collect()
    +183    }
    +184
    +185    #[cfg(not(wasm_browser))]
    +186    pub(crate) fn max_transmit_segments(&self) -> usize {
    +187        let res = self.ip.iter().map(|t| t.max_transmit_segments()).min();
    +188        res.unwrap_or(1)
    +189    }
    +190
    +191    #[cfg(wasm_browser)]
    +192    pub(crate) fn max_transmit_segments(&self) -> usize {
    +193        1
    +194    }
    +195
    +196    #[cfg(not(wasm_browser))]
    +197    pub(crate) fn max_receive_segments(&self) -> usize {
    +198        // `max_receive_segments` controls the size of the `RecvMeta` buffer
    +199        // that quinn creates. Having buffers slightly bigger than necessary
    +200        // isn't terrible, and makes sure a single socket can read the maximum
    +201        // amount with a single poll. We considered adding these numbers instead,
    +202        // but we never get data from both sockets at the same time in `poll_recv`
    +203        // and it's impossible and unnecessary to be refactored that way.
    +204
    +205        let res = self.ip.iter().map(|t| t.max_receive_segments()).max();
    +206        res.unwrap_or(1)
    +207    }
    +208
    +209    #[cfg(wasm_browser)]
    +210    pub(crate) fn max_receive_segments(&self) -> usize {
    +211        1
    +212    }
    +213
    +214    #[cfg(not(wasm_browser))]
    +215    pub(crate) fn may_fragment(&self) -> bool {
    +216        self.ip.iter().any(|t| t.may_fragment())
    +217    }
    +218
    +219    #[cfg(wasm_browser)]
    +220    pub(crate) fn may_fragment(&self) -> bool {
    +221        false
    +222    }
    +223
    +224    pub(crate) fn create_sender(&self, msock: Arc<MagicSock>) -> UdpSender {
    +225        #[cfg(not(wasm_browser))]
    +226        let ip = self.ip.iter().map(|t| t.create_sender()).collect();
    +227        let relay = self.relay.iter().map(|t| t.create_sender()).collect();
    +228        let max_transmit_segments = self.max_transmit_segments();
    +229
    +230        UdpSender {
    +231            #[cfg(not(wasm_browser))]
    +232            ip,
    +233            msock,
    +234            relay,
    +235            max_transmit_segments,
    +236        }
    +237    }
    +238
    +239    /// Handles potential changes to the underlying network conditions.
    +240    pub(crate) fn create_network_change_sender(&self) -> NetworkChangeSender {
    +241        NetworkChangeSender {
    +242            #[cfg(not(wasm_browser))]
    +243            ip: self
    +244                .ip
    +245                .iter()
    +246                .map(|t| t.create_network_change_sender())
    +247                .collect(),
    +248            relay: self
    +249                .relay
    +250                .iter()
    +251                .map(|t| t.create_network_change_sender())
    +252                .collect(),
    +253        }
    +254    }
    +255}
    +256
    +257#[derive(Debug)]
    +258pub(crate) struct NetworkChangeSender {
    +259    #[cfg(not(wasm_browser))]
    +260    ip: Vec<IpNetworkChangeSender>,
    +261    relay: Vec<RelayNetworkChangeSender>,
    +262}
    +263
    +264impl NetworkChangeSender {
    +265    pub(crate) fn on_network_change(&self, info: &NetInfo) {
    +266        #[cfg(not(wasm_browser))]
    +267        for ip in &self.ip {
    +268            ip.on_network_change(info);
    +269        }
    +270
    +271        for relay in &self.relay {
    +272            relay.on_network_change(info);
    +273        }
    +274    }
    +275
    +276    /// Rebinds underlying connections, if necessary.
    +277    pub(crate) fn rebind(&self) -> std::io::Result<()> {
    +278        let mut res = Ok(());
    +279
    +280        #[cfg(not(wasm_browser))]
    +281        for transport in &self.ip {
    +282            if let Err(err) = transport.rebind() {
    +283                warn!("failed to rebind {:?}", err);
    +284                res = Err(err);
    +285            }
    +286        }
    +287
    +288        for transport in &self.relay {
    +289            if let Err(err) = transport.rebind() {
    +290                warn!("failed to rebind {:?}", err);
    +291                res = Err(err);
    +292            }
    +293        }
    +294        res
    +295    }
    +296}
    +297
    +298/// An outgoing packet
    +299#[derive(Debug, Clone)]
    +300pub(crate) struct Transmit<'a> {
    +301    pub(crate) ecn: Option<quinn_udp::EcnCodepoint>,
    +302    pub(crate) contents: &'a [u8],
    +303    pub(crate) segment_size: Option<usize>,
    +304}
    +305
    +306#[derive(Debug, Clone, PartialEq, Eq)]
    +307pub(crate) enum Addr {
    +308    Ip(SocketAddr),
    +309    Relay(RelayUrl, NodeId),
    +310}
    +311
    +312impl Default for Addr {
    +313    fn default() -> Self {
    +314        Self::Ip(SocketAddr::V6(SocketAddrV6::new(
    +315            Ipv6Addr::UNSPECIFIED,
    +316            0,
    +317            0,
    +318            0,
    +319        )))
    +320    }
    +321}
    +322
    +323impl From<SocketAddr> for Addr {
    +324    fn from(value: SocketAddr) -> Self {
    +325        Self::Ip(value)
    +326    }
    +327}
    +328
    +329impl From<(RelayUrl, NodeId)> for Addr {
    +330    fn from(value: (RelayUrl, NodeId)) -> Self {
    +331        Self::Relay(value.0, value.1)
    +332    }
    +333}
    +334
    +335impl Addr {
    +336    pub(crate) fn is_relay(&self) -> bool {
    +337        matches!(self, Self::Relay(..))
    +338    }
    +339
    +340    pub(crate) fn is_ip(&self) -> bool {
    +341        matches!(self, Self::Ip(..))
    +342    }
    +343
    +344    /// Returns `None` if not an `Ip`.
    +345    pub(crate) fn into_socket_addr(self) -> Option<SocketAddr> {
    +346        match self {
    +347            Self::Ip(ip) => Some(ip),
    +348            Self::Relay(..) => None,
    +349        }
    +350    }
    +351}
    +352
    +353#[derive(Debug)]
    +354pub(crate) struct UdpSender {
    +355    msock: Arc<MagicSock>, // :(
    +356    #[cfg(not(wasm_browser))]
    +357    ip: Vec<IpSender>,
    +358    relay: Vec<RelaySender>,
    +359    max_transmit_segments: usize,
    +360}
    +361
    +362impl UdpSender {
    +363    pub(crate) async fn send(
    +364        &self,
    +365        destination: &Addr,
    +366        src: Option<IpAddr>,
    +367        transmit: &Transmit<'_>,
    +368    ) -> io::Result<()> {
    +369        trace!(?destination, "sending");
    +370
    +371        let mut any_match = false;
    +372        match destination {
    +373            #[cfg(wasm_browser)]
    +374            Addr::Ip(..) => return Err(io::Error::other("IP is unsupported in browser")),
    +375            #[cfg(not(wasm_browser))]
    +376            Addr::Ip(addr) => {
    +377                for sender in &self.ip {
    +378                    if sender.is_valid_send_addr(addr) {
    +379                        any_match = true;
    +380                        match sender.send(*addr, src, transmit).await {
    +381                            Ok(()) => {
    +382                                return Ok(());
    +383                            }
    +384                            Err(err) => {
    +385                                warn!("ip failed to send: {:?}", err);
    +386                            }
    +387                        }
    +388                    }
    +389                }
    +390            }
    +391            Addr::Relay(url, node_id) => {
    +392                for sender in &self.relay {
    +393                    if sender.is_valid_send_addr(url, node_id) {
    +394                        any_match = true;
    +395                        match sender.send(url.clone(), *node_id, transmit).await {
    +396                            Ok(()) => {
    +397                                return Ok(());
    +398                            }
    +399                            Err(err) => {
    +400                                warn!("relay failed to send: {:?}", err);
    +401                            }
    +402                        }
    +403                    }
    +404                }
    +405            }
    +406        }
    +407        if any_match {
    +408            Err(io::Error::other("all available transports failed"))
    +409        } else {
    +410            Err(io::Error::other("no transport available"))
    +411        }
    +412    }
    +413
    +414    pub(crate) fn inner_poll_send(
    +415        mut self: Pin<&mut Self>,
    +416        cx: &mut std::task::Context,
    +417        destination: &Addr,
    +418        src: Option<IpAddr>,
    +419        transmit: &Transmit<'_>,
    +420    ) -> Poll<io::Result<()>> {
    +421        trace!(?destination, "sending");
    +422
    +423        match destination {
    +424            #[cfg(wasm_browser)]
    +425            Addr::Ip(..) => {
    +426                return Poll::Ready(Err(io::Error::other("IP is unsupported in browser")))
    +427            }
    +428            #[cfg(not(wasm_browser))]
    +429            Addr::Ip(addr) => {
    +430                for sender in &mut self.ip {
    +431                    if sender.is_valid_send_addr(addr) {
    +432                        match Pin::new(sender).poll_send(cx, *addr, src, transmit) {
    +433                            Poll::Pending => {}
    +434                            Poll::Ready(res) => return Poll::Ready(res),
    +435                        }
    +436                    }
    +437                }
    +438            }
    +439            Addr::Relay(url, node_id) => {
    +440                for sender in &mut self.relay {
    +441                    if sender.is_valid_send_addr(url, node_id) {
    +442                        match sender.poll_send(cx, url.clone(), *node_id, transmit) {
    +443                            Poll::Pending => {}
    +444                            Poll::Ready(res) => return Poll::Ready(res),
    +445                        }
    +446                    }
    +447                }
    +448            }
    +449        }
    +450        Poll::Pending
    +451    }
    +452
    +453    /// Best effort sending
    +454    fn inner_try_send(
    +455        &self,
    +456        destination: &Addr,
    +457        src: Option<IpAddr>,
    +458        transmit: &Transmit<'_>,
    +459    ) -> io::Result<()> {
    +460        trace!(?destination, "sending, best effort");
    +461
    +462        match destination {
    +463            #[cfg(wasm_browser)]
    +464            Addr::Ip(..) => return Err(io::Error::other("IP is unsupported in browser")),
    +465            #[cfg(not(wasm_browser))]
    +466            Addr::Ip(addr) => {
    +467                for transport in &self.ip {
    +468                    if transport.is_valid_send_addr(addr) {
    +469                        match transport.try_send(*addr, src, transmit) {
    +470                            Ok(()) => return Ok(()),
    +471                            Err(_err) => {
    +472                                continue;
    +473                            }
    +474                        }
    +475                    }
    +476                }
    +477            }
    +478            Addr::Relay(url, node_id) => {
    +479                for transport in &self.relay {
    +480                    if transport.is_valid_send_addr(url, node_id) {
    +481                        match transport.try_send(url.clone(), *node_id, transmit) {
    +482                            Ok(()) => return Ok(()),
    +483                            Err(_err) => {
    +484                                continue;
    +485                            }
    +486                        }
    +487                    }
    +488                }
    +489            }
    +490        }
    +491        Err(io::Error::new(
    +492            io::ErrorKind::WouldBlock,
    +493            "no transport ready",
    +494        ))
    +495    }
    +496}
    +497
    +498impl quinn::UdpSender for UdpSender {
    +499    fn poll_send(
    +500        mut self: Pin<&mut Self>,
    +501        transmit: &quinn_udp::Transmit,
    +502        cx: &mut Context,
    +503    ) -> Poll<io::Result<()>> {
    +504        let active_paths = self.msock.prepare_send(transmit)?;
    +505
    +506        if active_paths.is_empty() {
    +507            // Returning Ok here means we let QUIC timeout.
    +508            // Returning an error would immediately fail a connection.
    +509            // The philosophy of quinn-udp is that a UDP connection could
    +510            // come back at any time or missing should be transient so chooses to let
    +511            // these kind of errors time out.  See test_try_send_no_send_addr to try
    +512            // this out.
    +513            error!("no paths available for node, voiding transmit");
    +514            return Poll::Ready(Ok(()));
    +515        }
    +516
    +517        let mut results = SmallVec::<[_; 3]>::new();
    +518
    +519        trace!(?active_paths, "attempting to send");
    +520
    +521        for destination in active_paths {
    +522            let src = transmit.src_ip;
    +523            let transmit = Transmit {
    +524                ecn: transmit.ecn,
    +525                contents: transmit.contents,
    +526                segment_size: transmit.segment_size,
    +527            };
    +528
    +529            let res = self
    +530                .as_mut()
    +531                .inner_poll_send(cx, &destination, src, &transmit);
    +532            match res {
    +533                Poll::Ready(Ok(())) => {
    +534                    trace!(dst = ?destination, "sent transmit");
    +535                }
    +536                Poll::Ready(Err(ref err)) => {
    +537                    warn!(dst = ?destination, "failed to send: {err:#}");
    +538                }
    +539                Poll::Pending => {}
    +540            }
    +541            results.push(res);
    +542        }
    +543
    +544        if results.iter().all(|p| matches!(p, Poll::Pending)) {
    +545            // Handle backpressure.
    +546            return Poll::Pending;
    +547        }
    +548        Poll::Ready(Ok(()))
    +549    }
    +550
    +551    fn max_transmit_segments(&self) -> usize {
    +552        self.max_transmit_segments
    +553    }
    +554
    +555    fn try_send(self: Pin<&mut Self>, transmit: &quinn_udp::Transmit) -> io::Result<()> {
    +556        let active_paths = self.msock.prepare_send(transmit)?;
    +557        if active_paths.is_empty() {
    +558            // Returning Ok here means we let QUIC timeout.
    +559            // Returning an error would immediately fail a connection.
    +560            // The philosophy of quinn-udp is that a UDP connection could
    +561            // come back at any time or missing should be transient so chooses to let
    +562            // these kind of errors time out.  See test_try_send_no_send_addr to try
    +563            // this out.
    +564            error!("no paths available for node, voiding transmit");
    +565            return Ok(());
    +566        }
    +567
    +568        let mut results = SmallVec::<[_; 3]>::new();
    +569
    +570        trace!(?active_paths, "attempting to send");
    +571
    +572        for destination in active_paths {
    +573            let src = transmit.src_ip;
    +574            let transmit = Transmit {
    +575                ecn: transmit.ecn,
    +576                contents: transmit.contents,
    +577                segment_size: transmit.segment_size,
    +578            };
    +579
    +580            let res = self.inner_try_send(&destination, src, &transmit);
    +581            match res {
    +582                Ok(()) => {
    +583                    trace!(dst = ?destination, "sent transmit");
    +584                }
    +585                Err(ref err) => {
    +586                    warn!(dst = ?destination, "failed to send: {err:#}");
    +587                }
    +588            }
    +589            results.push(res);
    +590        }
    +591
    +592        if results.iter().all(|p| p.is_err()) {
    +593            return Err(io::Error::other("all failed"));
    +594        }
    +595        Ok(())
    +596    }
    +597}
    \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/magicsock/transports/ip.rs.html b/pr/3327/docs/src/iroh/magicsock/transports/ip.rs.html new file mode 100644 index 0000000000..f27d893f2a --- /dev/null +++ b/pr/3327/docs/src/iroh/magicsock/transports/ip.rs.html @@ -0,0 +1,249 @@ +ip.rs - source

    iroh/magicsock/transports/
    ip.rs

    1use std::{
    +2    io,
    +3    net::{IpAddr, SocketAddr},
    +4    pin::Pin,
    +5    sync::Arc,
    +6    task::{Context, Poll},
    +7};
    +8
    +9use n0_watcher::Watchable;
    +10use netwatch::{UdpSender, UdpSocket};
    +11use pin_project::pin_project;
    +12use tracing::trace;
    +13
    +14use super::{Addr, Transmit};
    +15use crate::metrics::MagicsockMetrics;
    +16
    +17#[derive(Debug)]
    +18pub(crate) struct IpTransport {
    +19    bind_addr: SocketAddr,
    +20    socket: Arc<UdpSocket>,
    +21    local_addr: Watchable<SocketAddr>,
    +22    metrics: Arc<MagicsockMetrics>,
    +23}
    +24
    +25impl IpTransport {
    +26    pub(crate) fn new(
    +27        bind_addr: SocketAddr,
    +28        socket: Arc<UdpSocket>,
    +29        metrics: Arc<MagicsockMetrics>,
    +30    ) -> Self {
    +31        // Currently gets updated on manual rebind
    +32        // TODO: update when UdpSocket under the hood rebinds automatically
    +33        let local_addr = Watchable::new(socket.local_addr().expect("invalid socket"));
    +34
    +35        Self {
    +36            bind_addr,
    +37            socket,
    +38            local_addr,
    +39            metrics,
    +40        }
    +41    }
    +42
    +43    /// NOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely.
    +44    pub(super) fn poll_recv(
    +45        &mut self,
    +46        cx: &mut Context,
    +47        bufs: &mut [io::IoSliceMut<'_>],
    +48        metas: &mut [quinn_udp::RecvMeta],
    +49        source_addrs: &mut [Addr],
    +50    ) -> Poll<io::Result<usize>> {
    +51        match self.socket.poll_recv_quinn(cx, bufs, metas) {
    +52            Poll::Pending => Poll::Pending,
    +53            Poll::Ready(Ok(n)) => {
    +54                for (addr, el) in source_addrs.iter_mut().zip(metas.iter()).take(n) {
    +55                    *addr = el.addr.into();
    +56                }
    +57                Poll::Ready(Ok(n))
    +58            }
    +59            Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
    +60        }
    +61    }
    +62
    +63    pub(super) fn local_addr_watch(&self) -> n0_watcher::Direct<SocketAddr> {
    +64        self.local_addr.watch()
    +65    }
    +66
    +67    pub(super) fn max_transmit_segments(&self) -> usize {
    +68        self.socket.max_gso_segments()
    +69    }
    +70
    +71    pub(super) fn max_receive_segments(&self) -> usize {
    +72        self.socket.gro_segments()
    +73    }
    +74
    +75    pub(super) fn may_fragment(&self) -> bool {
    +76        self.socket.may_fragment()
    +77    }
    +78
    +79    pub(crate) fn bind_addr(&self) -> SocketAddr {
    +80        self.bind_addr
    +81    }
    +82
    +83    pub(super) fn create_network_change_sender(&self) -> IpNetworkChangeSender {
    +84        IpNetworkChangeSender {
    +85            socket: self.socket.clone(),
    +86            local_addr: self.local_addr.clone(),
    +87        }
    +88    }
    +89
    +90    pub(crate) fn socket(&self) -> Arc<UdpSocket> {
    +91        self.socket.clone()
    +92    }
    +93
    +94    pub(super) fn create_sender(&self) -> IpSender {
    +95        let sender = self.socket.clone().create_sender();
    +96        IpSender {
    +97            bind_addr: self.bind_addr,
    +98            sender,
    +99            metrics: self.metrics.clone(),
    +100        }
    +101    }
    +102}
    +103
    +104#[derive(Debug)]
    +105pub(super) struct IpNetworkChangeSender {
    +106    socket: Arc<UdpSocket>,
    +107    local_addr: Watchable<SocketAddr>,
    +108}
    +109
    +110impl IpNetworkChangeSender {
    +111    pub(super) fn rebind(&self) -> io::Result<()> {
    +112        self.socket.rebind()?;
    +113        let addr = self.socket.local_addr()?;
    +114        self.local_addr.set(addr).ok();
    +115
    +116        Ok(())
    +117    }
    +118
    +119    pub(super) fn on_network_change(&self, _info: &crate::magicsock::NetInfo) {
    +120        // Nothing to do for now
    +121    }
    +122}
    +123
    +124#[derive(Debug)]
    +125#[pin_project]
    +126pub(super) struct IpSender {
    +127    bind_addr: SocketAddr,
    +128    #[pin]
    +129    sender: UdpSender,
    +130    metrics: Arc<MagicsockMetrics>,
    +131}
    +132
    +133impl IpSender {
    +134    pub(super) fn is_valid_send_addr(&self, addr: &SocketAddr) -> bool {
    +135        #[allow(clippy::match_like_matches_macro)]
    +136        match (self.bind_addr, addr) {
    +137            (SocketAddr::V4(_), SocketAddr::V4(..)) => true,
    +138            (SocketAddr::V6(_), SocketAddr::V6(..)) => true,
    +139            _ => false,
    +140        }
    +141    }
    +142
    +143    pub(super) async fn send(
    +144        &self,
    +145        destination: SocketAddr,
    +146        src: Option<IpAddr>,
    +147        transmit: &Transmit<'_>,
    +148    ) -> io::Result<()> {
    +149        trace!("sending to {}", destination);
    +150        let total_bytes = transmit.contents.len() as u64;
    +151        let res = self
    +152            .sender
    +153            .send(&quinn_udp::Transmit {
    +154                destination,
    +155                ecn: transmit.ecn,
    +156                contents: transmit.contents,
    +157                segment_size: transmit.segment_size,
    +158                src_ip: src,
    +159            })
    +160            .await;
    +161        trace!("send res: {:?}", res);
    +162
    +163        match res {
    +164            Ok(res) => {
    +165                match destination {
    +166                    SocketAddr::V4(_) => {
    +167                        self.metrics.send_ipv4.inc_by(total_bytes);
    +168                    }
    +169                    SocketAddr::V6(_) => {
    +170                        self.metrics.send_ipv6.inc_by(total_bytes);
    +171                    }
    +172                }
    +173                Ok(res)
    +174            }
    +175            Err(err) => Err(err),
    +176        }
    +177    }
    +178
    +179    pub(super) fn poll_send(
    +180        mut self: Pin<&mut Self>,
    +181        cx: &mut std::task::Context,
    +182        destination: SocketAddr,
    +183        src: Option<IpAddr>,
    +184        transmit: &Transmit<'_>,
    +185    ) -> Poll<io::Result<()>> {
    +186        trace!("sending to {}", destination);
    +187        let total_bytes = transmit.contents.len() as u64;
    +188        let res = Pin::new(&mut self.sender).poll_send(
    +189            &quinn_udp::Transmit {
    +190                destination,
    +191                ecn: transmit.ecn,
    +192                contents: transmit.contents,
    +193                segment_size: transmit.segment_size,
    +194                src_ip: src,
    +195            },
    +196            cx,
    +197        );
    +198        trace!("send res: {:?}", res);
    +199
    +200        match res {
    +201            Poll::Ready(Ok(res)) => {
    +202                match destination {
    +203                    SocketAddr::V4(_) => {
    +204                        self.metrics.send_ipv4.inc_by(total_bytes);
    +205                    }
    +206                    SocketAddr::V6(_) => {
    +207                        self.metrics.send_ipv6.inc_by(total_bytes);
    +208                    }
    +209                }
    +210                Poll::Ready(Ok(res))
    +211            }
    +212            Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
    +213            Poll::Pending => Poll::Pending,
    +214        }
    +215    }
    +216
    +217    pub(super) fn try_send(
    +218        &self,
    +219        destination: SocketAddr,
    +220        src: Option<IpAddr>,
    +221        transmit: &Transmit<'_>,
    +222    ) -> io::Result<()> {
    +223        trace!("sending to {}", destination);
    +224        let total_bytes = transmit.contents.len() as u64;
    +225        let res = self.sender.try_send(&quinn_udp::Transmit {
    +226            destination,
    +227            ecn: transmit.ecn,
    +228            contents: transmit.contents,
    +229            segment_size: transmit.segment_size,
    +230            src_ip: src,
    +231        });
    +232        trace!("send res: {:?}", res);
    +233
    +234        match res {
    +235            Ok(res) => {
    +236                match destination {
    +237                    SocketAddr::V4(_) => {
    +238                        self.metrics.send_ipv4.inc_by(total_bytes);
    +239                    }
    +240                    SocketAddr::V6(_) => {
    +241                        self.metrics.send_ipv6.inc_by(total_bytes);
    +242                    }
    +243                }
    +244                Ok(res)
    +245            }
    +246            Err(err) => Err(err),
    +247        }
    +248    }
    +249}
    \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/magicsock/transports/relay.rs.html b/pr/3327/docs/src/iroh/magicsock/transports/relay.rs.html new file mode 100644 index 0000000000..ee69168547 --- /dev/null +++ b/pr/3327/docs/src/iroh/magicsock/transports/relay.rs.html @@ -0,0 +1,423 @@ +relay.rs - source

    iroh/magicsock/transports/
    relay.rs

    1use std::{
    +2    io,
    +3    task::{Context, Poll},
    +4};
    +5
    +6use bytes::Bytes;
    +7use iroh_base::{NodeId, RelayUrl};
    +8use n0_future::{
    +9    ready,
    +10    task::{self, AbortOnDropHandle},
    +11};
    +12use n0_watcher::{Watchable, Watcher as _};
    +13use smallvec::SmallVec;
    +14use tokio::sync::mpsc;
    +15use tokio_util::sync::PollSender;
    +16use tracing::{error, info_span, trace, warn, Instrument};
    +17
    +18use super::{Addr, Transmit};
    +19use crate::magicsock::RelayContents;
    +20
    +21mod actor;
    +22
    +23pub(crate) use self::actor::Config as RelayActorConfig;
    +24use self::actor::{RelayActor, RelayActorMessage, RelayRecvDatagram, RelaySendItem};
    +25
    +26#[derive(Debug)]
    +27pub(crate) struct RelayTransport {
    +28    /// Queue to receive datagrams from relays for [`quinn::AsyncUdpSocket::poll_recv`].
    +29    relay_datagram_recv_queue: mpsc::Receiver<RelayRecvDatagram>,
    +30    /// Channel on which to send datagrams via a relay server.
    +31    relay_datagram_send_channel: mpsc::Sender<RelaySendItem>,
    +32    actor_sender: mpsc::Sender<RelayActorMessage>,
    +33    _actor_handle: AbortOnDropHandle<()>,
    +34    my_relay: Watchable<Option<RelayUrl>>,
    +35    my_node_id: NodeId,
    +36}
    +37
    +38impl RelayTransport {
    +39    pub(crate) fn new(config: RelayActorConfig) -> Self {
    +40        let (relay_datagram_send_tx, relay_datagram_send_rx) = mpsc::channel(256);
    +41
    +42        let (relay_datagram_recv_tx, relay_datagram_recv_rx) = mpsc::channel(512);
    +43
    +44        let (actor_sender, actor_receiver) = mpsc::channel(256);
    +45
    +46        let my_node_id = config.secret_key.public();
    +47        let my_relay = config.my_relay.clone();
    +48
    +49        let relay_actor = RelayActor::new(config, relay_datagram_recv_tx);
    +50
    +51        let actor_handle = AbortOnDropHandle::new(task::spawn(
    +52            async move {
    +53                relay_actor
    +54                    .run(actor_receiver, relay_datagram_send_rx)
    +55                    .await;
    +56            }
    +57            .instrument(info_span!("relay-actor")),
    +58        ));
    +59
    +60        Self {
    +61            relay_datagram_recv_queue: relay_datagram_recv_rx,
    +62            relay_datagram_send_channel: relay_datagram_send_tx,
    +63            actor_sender,
    +64            _actor_handle: actor_handle,
    +65            my_relay,
    +66            my_node_id,
    +67        }
    +68    }
    +69
    +70    pub(crate) fn create_sender(&self) -> RelaySender {
    +71        RelaySender {
    +72            sender: PollSender::new(self.relay_datagram_send_channel.clone()),
    +73        }
    +74    }
    +75
    +76    pub(super) fn poll_recv(
    +77        &mut self,
    +78        cx: &mut Context,
    +79        bufs: &mut [io::IoSliceMut<'_>],
    +80        metas: &mut [quinn_udp::RecvMeta],
    +81        source_addrs: &mut [Addr],
    +82    ) -> Poll<io::Result<usize>> {
    +83        let mut num_msgs = 0;
    +84        for ((buf_out, meta_out), addr) in bufs
    +85            .iter_mut()
    +86            .zip(metas.iter_mut())
    +87            .zip(source_addrs.iter_mut())
    +88        {
    +89            let dm = match self.relay_datagram_recv_queue.poll_recv(cx) {
    +90                Poll::Ready(Some(recv)) => recv,
    +91                Poll::Ready(None) => {
    +92                    error!("relay_recv_channel closed");
    +93                    return Poll::Ready(Err(io::Error::new(
    +94                        io::ErrorKind::NotConnected,
    +95                        "connection closed",
    +96                    )));
    +97                }
    +98                Poll::Pending => {
    +99                    break;
    +100                }
    +101            };
    +102
    +103            buf_out[..dm.buf.len()].copy_from_slice(&dm.buf);
    +104            meta_out.len = dm.buf.len();
    +105            meta_out.stride = dm.buf.len();
    +106            meta_out.ecn = None;
    +107            meta_out.dst_ip = None; // TODO: insert the relay url for this relay
    +108
    +109            *addr = (dm.url, dm.src).into();
    +110            num_msgs += 1;
    +111        }
    +112
    +113        // If we have any msgs to report, they are in the first `num_msgs_total` slots
    +114        if num_msgs > 0 {
    +115            debug_assert!(num_msgs <= metas.len());
    +116            Poll::Ready(Ok(num_msgs))
    +117        } else {
    +118            Poll::Pending
    +119        }
    +120    }
    +121
    +122    pub(super) fn local_addr_watch(
    +123        &self,
    +124    ) -> n0_watcher::Map<n0_watcher::Direct<Option<RelayUrl>>, Option<(RelayUrl, NodeId)>> {
    +125        let my_node_id = self.my_node_id;
    +126        self.my_relay
    +127            .watch()
    +128            .map(move |url| url.map(|url| (url, my_node_id)))
    +129            .expect("disconnected")
    +130    }
    +131
    +132    pub(super) fn create_network_change_sender(&self) -> RelayNetworkChangeSender {
    +133        RelayNetworkChangeSender {
    +134            sender: self.actor_sender.clone(),
    +135        }
    +136    }
    +137}
    +138
    +139#[derive(Debug)]
    +140pub(super) struct RelayNetworkChangeSender {
    +141    sender: mpsc::Sender<RelayActorMessage>,
    +142}
    +143
    +144impl RelayNetworkChangeSender {
    +145    pub(super) fn on_network_change(&self, info: &crate::magicsock::NetInfo) {
    +146        self.send_relay_actor(RelayActorMessage::NetworkChange { info: info.clone() });
    +147    }
    +148
    +149    pub(super) fn rebind(&self) -> io::Result<()> {
    +150        self.send_relay_actor(RelayActorMessage::MaybeCloseRelaysOnRebind);
    +151
    +152        Ok(())
    +153    }
    +154
    +155    fn send_relay_actor(&self, msg: RelayActorMessage) {
    +156        match self.sender.try_send(msg) {
    +157            Ok(_) => {}
    +158            Err(mpsc::error::TrySendError::Closed(_)) => {
    +159                warn!("unable to send to relay actor, already closed");
    +160            }
    +161            Err(mpsc::error::TrySendError::Full(_)) => {
    +162                warn!("dropping message for relay actor, channel is full");
    +163            }
    +164        }
    +165    }
    +166}
    +167
    +168/// Sender to send datagrams to the [`RelayActor`].
    +169///
    +170/// This includes the waker coordination required to support [`quinn::UdpSender::poll_send`].
    +171#[derive(Debug, Clone)]
    +172pub(crate) struct RelaySender {
    +173    sender: PollSender<RelaySendItem>,
    +174}
    +175
    +176impl RelaySender {
    +177    pub(super) fn is_valid_send_addr(&self, _url: &RelayUrl, _node_id: &NodeId) -> bool {
    +178        true
    +179    }
    +180
    +181    pub(super) async fn send(
    +182        &self,
    +183        dest_url: RelayUrl,
    +184        dest_node: NodeId,
    +185        transmit: &Transmit<'_>,
    +186    ) -> io::Result<()> {
    +187        let contents = split_packets(transmit);
    +188
    +189        let item = RelaySendItem {
    +190            remote_node: dest_node,
    +191            url: dest_url.clone(),
    +192            datagrams: contents,
    +193        };
    +194
    +195        let dest_node = item.remote_node;
    +196        let dest_url = item.url.clone();
    +197        let Some(sender) = self.sender.get_ref() else {
    +198            return Err(io::Error::other("channel closed"));
    +199        };
    +200        match sender.send(item).await {
    +201            Ok(_) => {
    +202                trace!(node = %dest_node.fmt_short(), relay_url = %dest_url,
    +203                        "send relay: message queued");
    +204                Ok(())
    +205            }
    +206            Err(mpsc::error::SendError(_)) => {
    +207                error!(node = %dest_node.fmt_short(), relay_url = %dest_url,
    +208                        "send relay: message dropped, channel to actor is closed");
    +209                Err(io::Error::new(
    +210                    io::ErrorKind::ConnectionReset,
    +211                    "channel to actor is closed",
    +212                ))
    +213            }
    +214        }
    +215    }
    +216
    +217    pub(super) fn poll_send(
    +218        &mut self,
    +219        cx: &mut Context,
    +220        dest_url: RelayUrl,
    +221        dest_node: NodeId,
    +222        transmit: &Transmit<'_>,
    +223    ) -> Poll<io::Result<()>> {
    +224        match ready!(self.sender.poll_reserve(cx)) {
    +225            Ok(()) => {
    +226                trace!(node = %dest_node.fmt_short(), relay_url = %dest_url,
    +227                    "send relay: message queued");
    +228
    +229                let contents = split_packets(transmit);
    +230                let item = RelaySendItem {
    +231                    remote_node: dest_node,
    +232                    url: dest_url.clone(),
    +233                    datagrams: contents,
    +234                };
    +235                let dest_node = item.remote_node;
    +236                let dest_url = item.url.clone();
    +237
    +238                match self.sender.send_item(item) {
    +239                    Ok(()) => Poll::Ready(Ok(())),
    +240                    Err(_err) => {
    +241                        error!(node = %dest_node.fmt_short(), relay_url = %dest_url,
    +242                      "send relay: message dropped, channel to actor is closed");
    +243                        Poll::Ready(Err(io::Error::new(
    +244                            io::ErrorKind::ConnectionReset,
    +245                            "channel to actor is closed",
    +246                        )))
    +247                    }
    +248                }
    +249            }
    +250            Err(_err) => {
    +251                error!(node = %dest_node.fmt_short(), relay_url = %dest_url,
    +252                      "send relay: message dropped, channel to actor is closed");
    +253                Poll::Ready(Err(io::Error::new(
    +254                    io::ErrorKind::ConnectionReset,
    +255                    "channel to actor is closed",
    +256                )))
    +257            }
    +258        }
    +259    }
    +260
    +261    pub(super) fn try_send(
    +262        &self,
    +263        dest_url: RelayUrl,
    +264        dest_node: NodeId,
    +265        transmit: &Transmit<'_>,
    +266    ) -> io::Result<()> {
    +267        let contents = split_packets(transmit);
    +268
    +269        let item = RelaySendItem {
    +270            remote_node: dest_node,
    +271            url: dest_url.clone(),
    +272            datagrams: contents,
    +273        };
    +274
    +275        let dest_node = item.remote_node;
    +276        let dest_url = item.url.clone();
    +277
    +278        let Some(sender) = self.sender.get_ref() else {
    +279            return Err(io::Error::other("channel closed"));
    +280        };
    +281
    +282        match sender.try_send(item) {
    +283            Ok(_) => {
    +284                trace!(node = %dest_node.fmt_short(), relay_url = %dest_url,
    +285                       "send relay: message queued");
    +286                Ok(())
    +287            }
    +288            Err(mpsc::error::TrySendError::Closed(_)) => {
    +289                error!(node = %dest_node.fmt_short(), relay_url = %dest_url,
    +290                    "send relay: message dropped, channel to actor is closed");
    +291                Err(io::Error::new(
    +292                    io::ErrorKind::ConnectionReset,
    +293                    "channel to actor is closed",
    +294                ))
    +295            }
    +296            Err(mpsc::error::TrySendError::Full(_)) => {
    +297                warn!(node = %dest_node.fmt_short(), relay_url = %dest_url,
    +298                      "send relay: message dropped, channel to actor is full");
    +299                Err(io::Error::new(io::ErrorKind::WouldBlock, "channel full"))
    +300            }
    +301        }
    +302    }
    +303}
    +304
    +305/// Split a transmit containing a GSO payload into individual packets.
    +306///
    +307/// This allocates the data.
    +308///
    +309/// If the transmit has a segment size it contains multiple GSO packets.  It will be split
    +310/// into multiple packets according to that segment size.  If it does not have a segment
    +311/// size, the contents will be sent as a single packet.
    +312// TODO: If quinn stayed on bytes this would probably be much cheaper, probably.  Need to
    +313// figure out where they allocate the Vec.
    +314fn split_packets(transmit: &Transmit<'_>) -> RelayContents {
    +315    let mut res = SmallVec::with_capacity(1);
    +316    let contents = transmit.contents;
    +317    if let Some(segment_size) = transmit.segment_size {
    +318        for chunk in contents.chunks(segment_size) {
    +319            res.push(Bytes::from(chunk.to_vec()));
    +320        }
    +321    } else {
    +322        res.push(Bytes::from(contents.to_vec()));
    +323    }
    +324    res
    +325}
    +326
    +327#[cfg(test)]
    +328mod tests {
    +329    use std::{collections::BTreeSet, time::Duration};
    +330
    +331    use iroh_base::NodeId;
    +332    use tokio::task::JoinSet;
    +333    use tracing::debug;
    +334
    +335    use super::*;
    +336    use crate::defaults::staging;
    +337
    +338    #[test]
    +339    fn test_split_packets() {
    +340        fn mk_transmit(contents: &[u8], segment_size: Option<usize>) -> Transmit<'_> {
    +341            Transmit {
    +342                ecn: None,
    +343                contents,
    +344                segment_size,
    +345            }
    +346        }
    +347        fn mk_expected(parts: impl IntoIterator<Item = &'static str>) -> RelayContents {
    +348            parts
    +349                .into_iter()
    +350                .map(|p| p.as_bytes().to_vec().into())
    +351                .collect()
    +352        }
    +353        // no split
    +354        assert_eq!(
    +355            split_packets(&mk_transmit(b"hello", None)),
    +356            mk_expected(["hello"])
    +357        );
    +358        // split without rest
    +359        assert_eq!(
    +360            split_packets(&mk_transmit(b"helloworld", Some(5))),
    +361            mk_expected(["hello", "world"])
    +362        );
    +363        // split with rest and second transmit
    +364        assert_eq!(
    +365            split_packets(&mk_transmit(b"hello world", Some(5))),
    +366            mk_expected(["hello", " worl", "d"]) // spellchecker:disable-line
    +367        );
    +368        // split that results in 1 packet
    +369        assert_eq!(
    +370            split_packets(&mk_transmit(b"hello world", Some(1000))),
    +371            mk_expected(["hello world"])
    +372        );
    +373    }
    +374
    +375    #[tokio::test(flavor = "multi_thread")]
    +376    async fn test_relay_datagram_queue() {
    +377        let capacity = 16;
    +378        let (sender, mut receiver) = mpsc::channel(capacity);
    +379        let url = staging::default_na_relay_node().url;
    +380
    +381        let mut tasks = JoinSet::new();
    +382
    +383        tasks.spawn({
    +384            async move {
    +385                let mut expected_msgs: BTreeSet<usize> = (0..capacity).collect();
    +386                while !expected_msgs.is_empty() {
    +387                    let datagram: RelayRecvDatagram = receiver.recv().await.unwrap();
    +388                    let msg_num = usize::from_le_bytes(datagram.buf.as_ref().try_into().unwrap());
    +389                    debug!("Received {msg_num}");
    +390
    +391                    if !expected_msgs.remove(&msg_num) {
    +392                        panic!("Received message number {msg_num} twice or more, but expected it only exactly once.");
    +393                    }
    +394                }
    +395            }
    +396        });
    +397
    +398        for i in 0..capacity {
    +399            tasks.spawn({
    +400                let sender = sender.clone();
    +401                let url = url.clone();
    +402                async move {
    +403                    debug!("Sending {i}");
    +404                    sender
    +405                        .try_send(RelayRecvDatagram {
    +406                            url,
    +407                            src: NodeId::from_bytes(&[0u8; 32]).unwrap(),
    +408                            buf: Bytes::copy_from_slice(&i.to_le_bytes()),
    +409                        })
    +410                        .unwrap();
    +411                }
    +412            });
    +413        }
    +414
    +415        // We expect all of this work to be done in 10 seconds max.
    +416        if tokio::time::timeout(Duration::from_secs(10), tasks.join_all())
    +417            .await
    +418            .is_err()
    +419        {
    +420            panic!("Timeout - not all messages between 0 and {capacity} received.");
    +421        }
    +422    }
    +423}
    \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/magicsock/transports/relay/actor.rs.html b/pr/3327/docs/src/iroh/magicsock/transports/relay/actor.rs.html new file mode 100644 index 0000000000..97c0b5d16d --- /dev/null +++ b/pr/3327/docs/src/iroh/magicsock/transports/relay/actor.rs.html @@ -0,0 +1,1747 @@ +actor.rs - source

    iroh/magicsock/transports/relay/
    actor.rs

    1//! The relay actor.
    +2//!
    +3//! The [`RelayActor`] handles all the relay connections.  It is helped by the
    +4//! [`ActiveRelayActor`] which handles a single relay connection.
    +5//!
    +6//! - The [`RelayActor`] manages all connections to relay servers.
    +7//!   - It starts a new [`ActiveRelayActor`] for each relay server needed.
    +8//!   - The [`ActiveRelayActor`] will exit when unused.
    +9//!     - Unless it is for the home relay, this one never exits.
    +10//!   - Each [`ActiveRelayActor`] uses a relay [`Client`].
    +11//!     - The relay [`Client`] is a `Stream` and `Sink` directly connected to the
    +12//!       `TcpStream` connected to the relay server.
    +13//!   - Each [`ActiveRelayActor`] will try and maintain a connection with the relay server.
    +14//!     - If connections fail, exponential backoff is used for reconnections.
    +15//! - When `AsyncUdpSocket` needs to send datagrams:
    +16//!   - It puts them on a queue to the [`RelayActor`].
    +17//!   - The [`RelayActor`] ensures the correct [`ActiveRelayActor`] is running and
    +18//!     forwards datagrams to it.
    +19//!   - The ActiveRelayActor sends datagrams directly to the relay server.
    +20//! - The relay receive path is:
    +21//!   - Whenever [`ActiveRelayActor`] is connected it reads from the underlying `TcpStream`.
    +22//!   - Received datagrams are placed on an mpsc channel that now bypasses the
    +23//!     [`RelayActor`] and goes straight to the `AsyncUpdSocket` interface.
    +24//!
    +25//! [`Client`]: iroh_relay::client::Client
    +26
    +27#[cfg(test)]
    +28use std::net::SocketAddr;
    +29use std::{
    +30    collections::{BTreeMap, BTreeSet},
    +31    future::Future,
    +32    net::IpAddr,
    +33    pin::{pin, Pin},
    +34    sync::{
    +35        atomic::{AtomicBool, Ordering},
    +36        Arc,
    +37    },
    +38};
    +39
    +40use backon::{Backoff, BackoffBuilder, ExponentialBuilder};
    +41use bytes::{Bytes, BytesMut};
    +42use iroh_base::{NodeId, PublicKey, RelayUrl, SecretKey};
    +43use iroh_relay::{
    +44    self as relay,
    +45    client::{Client, ConnectError, ReceivedMessage, RecvError, SendError, SendMessage},
    +46    PingTracker, MAX_PACKET_SIZE,
    +47};
    +48use n0_future::{
    +49    task::JoinSet,
    +50    time::{self, Duration, Instant, MissedTickBehavior},
    +51    FuturesUnorderedBounded, SinkExt, StreamExt,
    +52};
    +53use n0_watcher::Watchable;
    +54use nested_enum_utils::common_fields;
    +55use netwatch::interfaces;
    +56use snafu::{IntoError, ResultExt, Snafu};
    +57use tokio::sync::{mpsc, oneshot};
    +58use tokio_util::sync::CancellationToken;
    +59use tracing::{debug, error, event, info, info_span, instrument, trace, warn, Instrument, Level};
    +60use url::Url;
    +61
    +62#[cfg(not(wasm_browser))]
    +63use crate::dns::DnsResolver;
    +64use crate::{
    +65    magicsock::{Metrics as MagicsockMetrics, NetInfo, RelayContents},
    +66    util::MaybeFuture,
    +67};
    +68
    +69/// How long a non-home relay connection needs to be idle (last written to) before we close it.
    +70const RELAY_INACTIVE_CLEANUP_TIME: Duration = Duration::from_secs(60);
    +71
    +72/// Maximum size a datagram payload is allowed to be.
    +73const MAX_PAYLOAD_SIZE: usize = MAX_PACKET_SIZE - PublicKey::LENGTH;
    +74
    +75/// Interval in which we ping the relay server to ensure the connection is alive.
    +76///
    +77/// The default QUIC max_idle_timeout is 30s, so setting that to half this time gives some
    +78/// chance of recovering.
    +79const PING_INTERVAL: Duration = Duration::from_secs(15);
    +80
    +81/// Number of datagrams which can be sent to the relay server in one batch.
    +82///
    +83/// This means while this batch is sending to the server no other relay protocol frames can
    +84/// be sent to the server, e.g. no Ping frames or so.  While the maximum packet size is
    +85/// rather large, each item can typically be expected to up to 1500 or the max GSO size.
    +86const SEND_DATAGRAM_BATCH_SIZE: usize = 20;
    +87
    +88/// Timeout for establishing the relay connection.
    +89///
    +90/// This includes DNS, dialing the server, upgrading the connection, and completing the
    +91/// handshake.
    +92const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
    +93
    +94/// Time after which the [`ActiveRelayActor`] will drop undeliverable datagrams.
    +95///
    +96/// When the [`ActiveRelayActor`] is not connected it can not deliver datagrams.  However it
    +97/// will still receive datagrams to send from the [`RelayActor`].  If connecting takes
    +98/// longer than this timeout datagrams will be dropped.
    +99///
    +100/// This value is set to 3 times the QUIC initial Probe Timeout (PTO).
    +101const UNDELIVERABLE_DATAGRAM_TIMEOUT: Duration = Duration::from_secs(3);
    +102
    +103/// An actor which handles the connection to a single relay server.
    +104///
    +105/// It is responsible for maintaining the connection to the relay server and handling all
    +106/// communication with it.
    +107///
    +108/// The actor shuts down itself on inactivity: inactivity is determined when no more
    +109/// datagrams are being queued to send.
    +110///
    +111/// This actor has 3 main states it can be in, each has it's dedicated run loop:
    +112///
    +113/// - Dialing the relay server.
    +114///
    +115///   This will continuously dial the server until connected, using exponential backoff if
    +116///   it can not connect.  See [`ActiveRelayActor::run_dialing`].
    +117///
    +118/// - Connected to the relay server.
    +119///
    +120///   This state allows receiving from the relay server, though sending is idle in this
    +121///   state.  See [`ActiveRelayActor::run_connected`].
    +122///
    +123/// - Sending to the relay server.
    +124///
    +125///   This is a sub-state of `connected` so the actor can still be receiving from the relay
    +126///   server at this time.  However it is actively sending data to the server so can not
    +127///   consume any further items from inboxes which will result in sending more data to the
    +128///   server until the actor goes back to the `connected` state.
    +129///
    +130/// All these are driven from the top-level [`ActiveRelayActor::run`] loop.
    +131#[derive(Debug)]
    +132struct ActiveRelayActor {
    +133    // The inboxes and channels this actor communicates over.
    +134    /// Inbox for messages which should be handled without any blocking.
    +135    prio_inbox: mpsc::Receiver<ActiveRelayPrioMessage>,
    +136    /// Inbox for messages which involve sending to the relay server.
    +137    inbox: mpsc::Receiver<ActiveRelayMessage>,
    +138    /// Queue for received relay datagrams.
    +139    relay_datagrams_recv: mpsc::Sender<RelayRecvDatagram>,
    +140    /// Channel on which we queue packets to send to the relay.
    +141    relay_datagrams_send: mpsc::Receiver<RelaySendItem>,
    +142
    +143    // Other actor state.
    +144    /// The relay server for this actor.
    +145    url: RelayUrl,
    +146    /// Builder which can repeatedly build a relay client.
    +147    relay_client_builder: relay::client::ClientBuilder,
    +148    /// Whether or not this is the home relay server.
    +149    ///
    +150    /// The home relay server needs to maintain it's connection to the relay server, even if
    +151    /// the relay actor is otherwise idle.
    +152    is_home_relay: bool,
    +153    /// When this expires the actor has been idle and should shut down.
    +154    ///
    +155    /// Unless it is managing the home relay connection.  Inactivity is only tracked on the
    +156    /// last datagram sent to the relay, received datagrams will trigger QUIC ACKs which is
    +157    /// sufficient to keep active connections open.
    +158    inactive_timeout: Pin<Box<time::Sleep>>,
    +159    /// Token indicating the [`ActiveRelayActor`] should stop.
    +160    stop_token: CancellationToken,
    +161    metrics: Arc<MagicsockMetrics>,
    +162}
    +163
    +164#[derive(Debug)]
    +165enum ActiveRelayMessage {
    +166    /// Triggers a connection check to the relay server.
    +167    ///
    +168    /// Sometimes it is known the local network interfaces have changed in which case it
    +169    /// might be prudent to check if the relay connection is still working.  `Vec<IpAddr>`
    +170    /// should contain the current local IP addresses.  If the connection uses a local
    +171    /// socket with an IP address in this list the relay server will be pinged.  If the
    +172    /// connection uses a local socket with an IP address not in this list the server will
    +173    /// always re-connect.
    +174    CheckConnection(Vec<IpAddr>),
    +175    /// Sets this relay as the home relay, or not.
    +176    SetHomeRelay(bool),
    +177    #[cfg(test)]
    +178    GetLocalAddr(oneshot::Sender<Option<SocketAddr>>),
    +179    #[cfg(test)]
    +180    PingServer(oneshot::Sender<()>),
    +181}
    +182
    +183/// Messages for the [`ActiveRelayActor`] which should never block.
    +184///
    +185/// Most messages in the [`ActiveRelayMessage`] enum trigger sending to the relay server,
    +186/// which can be blocking.  So the actor may not always be processing that inbox.  Messages
    +187/// here are processed immediately.
    +188#[derive(Debug)]
    +189enum ActiveRelayPrioMessage {
    +190    /// Returns whether or not this relay can reach the NodeId.
    +191    HasNodeRoute(NodeId, oneshot::Sender<bool>),
    +192}
    +193
    +194/// Configuration needed to start an [`ActiveRelayActor`].
    +195#[derive(Debug)]
    +196struct ActiveRelayActorOptions {
    +197    url: RelayUrl,
    +198    prio_inbox_: mpsc::Receiver<ActiveRelayPrioMessage>,
    +199    inbox: mpsc::Receiver<ActiveRelayMessage>,
    +200    relay_datagrams_send: mpsc::Receiver<RelaySendItem>,
    +201    relay_datagrams_recv: mpsc::Sender<RelayRecvDatagram>,
    +202    connection_opts: RelayConnectionOptions,
    +203    stop_token: CancellationToken,
    +204    metrics: Arc<MagicsockMetrics>,
    +205}
    +206
    +207/// Configuration needed to create a connection to a relay server.
    +208#[derive(Debug, Clone)]
    +209struct RelayConnectionOptions {
    +210    secret_key: SecretKey,
    +211    #[cfg(not(wasm_browser))]
    +212    dns_resolver: DnsResolver,
    +213    proxy_url: Option<Url>,
    +214    prefer_ipv6: Arc<AtomicBool>,
    +215    #[cfg(any(test, feature = "test-utils"))]
    +216    insecure_skip_cert_verify: bool,
    +217    protocol: iroh_relay::http::Protocol,
    +218}
    +219
    +220/// Possible reasons for a failed relay connection.
    +221#[allow(missing_docs)]
    +222#[common_fields({
    +223    backtrace: Option<snafu::Backtrace>,
    +224    #[snafu(implicit)]
    +225    span_trace: n0_snafu::SpanTrace,
    +226})]
    +227#[derive(Debug, Snafu)]
    +228enum RelayConnectionError {
    +229    #[snafu(display("Failed to connect to relay server"))]
    +230    Dial { source: DialError },
    +231    #[snafu(display("Failed to handshake with relay server"))]
    +232    Handshake { source: RunError },
    +233    #[snafu(display("Lost connection to relay server"))]
    +234    Established { source: RunError },
    +235}
    +236
    +237#[allow(missing_docs)]
    +238#[common_fields({
    +239    backtrace: Option<snafu::Backtrace>,
    +240    #[snafu(implicit)]
    +241    span_trace: n0_snafu::SpanTrace,
    +242})]
    +243#[derive(Debug, Snafu)]
    +244enum RunError {
    +245    #[snafu(display("Send timeout"))]
    +246    SendTimeout {},
    +247    #[snafu(display("Ping timeout"))]
    +248    PingTimeout {},
    +249    #[snafu(display("Local IP no longer valid"))]
    +250    LocalIpInvalid {},
    +251    #[snafu(display("No local address"))]
    +252    LocalAddrMissing {},
    +253    #[snafu(display("Stream closed by server."))]
    +254    StreamClosedServer {},
    +255    #[snafu(display("Client stream read failed"))]
    +256    ClientStreamRead { source: RecvError },
    +257    #[snafu(display("Client stream write failed"))]
    +258    ClientStreamWrite { source: SendError },
    +259}
    +260
    +261#[allow(missing_docs)]
    +262#[common_fields({
    +263    backtrace: Option<snafu::Backtrace>,
    +264    #[snafu(implicit)]
    +265    span_trace: n0_snafu::SpanTrace,
    +266})]
    +267#[derive(Debug, Snafu)]
    +268enum DialError {
    +269    #[snafu(display("timeout trying to establish a connection"))]
    +270    Timeout {},
    +271    #[snafu(display("unable to connect"))]
    +272    Connect {
    +273        #[snafu(source(from(ConnectError, Box::new)))]
    +274        source: Box<ConnectError>,
    +275    },
    +276}
    +277
    +278impl ActiveRelayActor {
    +279    fn new(opts: ActiveRelayActorOptions) -> Self {
    +280        let ActiveRelayActorOptions {
    +281            url,
    +282            prio_inbox_: prio_inbox,
    +283            inbox,
    +284            relay_datagrams_send,
    +285            relay_datagrams_recv,
    +286            connection_opts,
    +287            stop_token,
    +288            metrics,
    +289        } = opts;
    +290        let relay_client_builder = Self::create_relay_builder(url.clone(), connection_opts);
    +291        ActiveRelayActor {
    +292            prio_inbox,
    +293            inbox,
    +294            relay_datagrams_recv,
    +295            relay_datagrams_send,
    +296            url,
    +297            relay_client_builder,
    +298            is_home_relay: false,
    +299            inactive_timeout: Box::pin(time::sleep(RELAY_INACTIVE_CLEANUP_TIME)),
    +300            stop_token,
    +301            metrics,
    +302        }
    +303    }
    +304
    +305    fn create_relay_builder(
    +306        url: RelayUrl,
    +307        opts: RelayConnectionOptions,
    +308    ) -> relay::client::ClientBuilder {
    +309        let RelayConnectionOptions {
    +310            secret_key,
    +311            #[cfg(not(wasm_browser))]
    +312            dns_resolver,
    +313            proxy_url,
    +314            prefer_ipv6,
    +315            #[cfg(any(test, feature = "test-utils"))]
    +316            insecure_skip_cert_verify,
    +317            protocol,
    +318        } = opts;
    +319
    +320        let mut builder = relay::client::ClientBuilder::new(
    +321            url,
    +322            secret_key,
    +323            #[cfg(not(wasm_browser))]
    +324            dns_resolver,
    +325        )
    +326        .protocol(protocol)
    +327        .address_family_selector(move || prefer_ipv6.load(Ordering::Relaxed));
    +328        if let Some(proxy_url) = proxy_url {
    +329            builder = builder.proxy_url(proxy_url);
    +330        }
    +331        #[cfg(any(test, feature = "test-utils"))]
    +332        let builder = builder.insecure_skip_cert_verify(insecure_skip_cert_verify);
    +333        builder
    +334    }
    +335
    +336    /// The main actor run loop.
    +337    ///
    +338    /// Primarily switches between the dialing and connected states.
    +339    async fn run(mut self) {
    +340        // TODO(frando): decide what this metric means, it's either wrong here or in node_state.rs.
    +341        // From the existing description, it is wrong here.
    +342        // self.metrics.num_relay_conns_added.inc();
    +343
    +344        let mut backoff = Self::build_backoff();
    +345
    +346        while let Err(err) = self.run_once().await {
    +347            warn!("{err}");
    +348            match err {
    +349                RelayConnectionError::Dial { .. } | RelayConnectionError::Handshake { .. } => {
    +350                    // If dialing failed, or if the relay connection failed before we received a pong,
    +351                    // we wait an exponentially increasing time until we attempt to reconnect again.
    +352                    let Some(delay) = backoff.next() else {
    +353                        warn!("retries exceeded");
    +354                        break;
    +355                    };
    +356                    debug!("retry in {delay:?}");
    +357                    time::sleep(delay).await;
    +358                }
    +359                RelayConnectionError::Established { .. } => {
    +360                    // If the relay connection remained established long enough so that we received a pong
    +361                    // from the relay server, we reset the backoff and attempt to reconnect immediately.
    +362                    backoff = Self::build_backoff();
    +363                }
    +364            }
    +365        }
    +366        debug!("exiting");
    +367        // TODO(frando): decide what this metric means, it's either wrong here or in node_state.rs.
    +368        // From the existing description, it is wrong here.
    +369        // self.metrics.num_relay_conns_removed.inc();
    +370    }
    +371
    +372    fn build_backoff() -> impl Backoff {
    +373        ExponentialBuilder::new()
    +374            .with_min_delay(Duration::from_millis(10))
    +375            .with_max_delay(Duration::from_secs(16))
    +376            .with_jitter()
    +377            .without_max_times()
    +378            .build()
    +379    }
    +380
    +381    /// Attempt to connect to the relay, and run the connected actor loop.
    +382    ///
    +383    /// Returns `Ok(())` if the actor loop should shut down. Returns an error if dialing failed,
    +384    /// or if the relay connection failed while connected. In both cases, the connection should
    +385    /// be retried with a backoff.
    +386    async fn run_once(&mut self) -> Result<(), RelayConnectionError> {
    +387        let client = match self.run_dialing().instrument(info_span!("dialing")).await {
    +388            Some(client_res) => client_res.context(DialSnafu)?,
    +389            None => return Ok(()),
    +390        };
    +391        self.run_connected(client)
    +392            .instrument(info_span!("connected"))
    +393            .await
    +394    }
    +395
    +396    fn reset_inactive_timeout(&mut self) {
    +397        self.inactive_timeout
    +398            .as_mut()
    +399            .reset(Instant::now() + RELAY_INACTIVE_CLEANUP_TIME);
    +400    }
    +401
    +402    fn set_home_relay(&mut self, is_home: bool) {
    +403        let prev = std::mem::replace(&mut self.is_home_relay, is_home);
    +404        if self.is_home_relay != prev {
    +405            event!(
    +406                target: "iroh::_events::relay::home_changed",
    +407                Level::DEBUG,
    +408                url = %self.url,
    +409                home_relay = self.is_home_relay,
    +410            );
    +411        }
    +412    }
    +413
    +414    /// Actor loop when connecting to the relay server.
    +415    ///
    +416    /// Returns `None` if the actor needs to shut down.  Returns `Some(Ok(client))` when the
    +417    /// connection is established, and `Some(Err(err))` if dialing the relay failed.
    +418    async fn run_dialing(&mut self) -> Option<Result<iroh_relay::client::Client, DialError>> {
    +419        debug!("Actor loop: connecting to relay.");
    +420
    +421        // We regularly flush the relay_datagrams_send queue so it is not full of stale
    +422        // packets while reconnecting.  Those datagrams are dropped and the QUIC congestion
    +423        // controller will have to handle this (DISCO packets do not yet have retry).  This
    +424        // is not an ideal mechanism, an alternative approach would be to use
    +425        // e.g. ConcurrentQueue with force_push, though now you might still send very stale
    +426        // packets when eventually connected.  So perhaps this is a reasonable compromise.
    +427        let mut send_datagram_flush = time::interval(UNDELIVERABLE_DATAGRAM_TIMEOUT);
    +428        send_datagram_flush.set_missed_tick_behavior(MissedTickBehavior::Delay);
    +429        send_datagram_flush.reset(); // Skip the immediate interval
    +430
    +431        let dialing_fut = self.dial_relay();
    +432        tokio::pin!(dialing_fut);
    +433        loop {
    +434            tokio::select! {
    +435                biased;
    +436                _ = self.stop_token.cancelled() => {
    +437                    debug!("Shutdown.");
    +438                    break None;
    +439                }
    +440                msg = self.prio_inbox.recv() => {
    +441                    let Some(msg) = msg else {
    +442                        warn!("Priority inbox closed, shutdown.");
    +443                        break None;
    +444                    };
    +445                    match msg {
    +446                        ActiveRelayPrioMessage::HasNodeRoute(_peer, sender) => {
    +447                            sender.send(false).ok();
    +448                        }
    +449                    }
    +450                }
    +451                res = &mut dialing_fut => {
    +452                    match res {
    +453                        Ok(client) => {
    +454                            break Some(Ok(client));
    +455                        }
    +456                        Err(err) => {
    +457                            break Some(Err(err));
    +458                        }
    +459                    }
    +460                }
    +461                msg = self.inbox.recv() => {
    +462                    let Some(msg) = msg else {
    +463                        debug!("Inbox closed, shutdown.");
    +464                        break None;
    +465                    };
    +466                    match msg {
    +467                        ActiveRelayMessage::SetHomeRelay(is_home) => {
    +468                            self.set_home_relay(is_home);
    +469                        }
    +470                        ActiveRelayMessage::CheckConnection(_local_ips) => {}
    +471                        #[cfg(test)]
    +472                        ActiveRelayMessage::GetLocalAddr(sender) => {
    +473                            sender.send(None).ok();
    +474                        }
    +475                        #[cfg(test)]
    +476                        ActiveRelayMessage::PingServer(sender) => {
    +477                            drop(sender);
    +478                        }
    +479                    }
    +480                }
    +481                _ = send_datagram_flush.tick() => {
    +482                    self.reset_inactive_timeout();
    +483                    let mut logged = false;
    +484                    while self.relay_datagrams_send.try_recv().is_ok() {
    +485                        if !logged {
    +486                            debug!(?UNDELIVERABLE_DATAGRAM_TIMEOUT, "Dropping datagrams to send.");
    +487                            logged = true;
    +488                        }
    +489                    }
    +490                }
    +491                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
    +492                    debug!(?RELAY_INACTIVE_CLEANUP_TIME, "Inactive, exiting.");
    +493                    break None;
    +494                }
    +495            }
    +496        }
    +497    }
    +498
    +499    /// Returns a future which will complete once connected to the relay server.
    +500    ///
    +501    /// The future only completes once the connection is established and retries
    +502    /// connections.  It currently does not ever return `Err` as the retries continue
    +503    /// forever.
    +504    // This is using `impl Future` to return a future without a reference to self.
    +505    fn dial_relay(&self) -> impl Future<Output = Result<Client, DialError>> {
    +506        let client_builder = self.relay_client_builder.clone();
    +507        async move {
    +508            match time::timeout(CONNECT_TIMEOUT, client_builder.connect()).await {
    +509                Ok(Ok(client)) => Ok(client),
    +510                Ok(Err(err)) => Err(ConnectSnafu.into_error(err)),
    +511                Err(_) => Err(TimeoutSnafu.build()),
    +512            }
    +513        }
    +514    }
    +515
    +516    /// Runs the actor loop when connected to a relay server.
    +517    ///
    +518    /// Returns `Ok` if the actor needs to shut down.  `Err` is returned if the connection
    +519    /// to the relay server is lost.
    +520    async fn run_connected(
    +521        &mut self,
    +522        client: iroh_relay::client::Client,
    +523    ) -> Result<(), RelayConnectionError> {
    +524        debug!("Actor loop: connected to relay");
    +525        event!(
    +526            target: "iroh::_events::relay::connected",
    +527            Level::DEBUG,
    +528            url = %self.url,
    +529            home_relay = self.is_home_relay,
    +530        );
    +531
    +532        let (mut client_stream, client_sink) = client.split();
    +533        let mut client_sink = client_sink.sink_map_err(|e| ClientStreamWriteSnafu.into_error(e));
    +534
    +535        let mut state = ConnectedRelayState {
    +536            ping_tracker: PingTracker::default(),
    +537            nodes_present: BTreeSet::new(),
    +538            last_packet_src: None,
    +539            pong_pending: None,
    +540            established: false,
    +541            #[cfg(test)]
    +542            test_pong: None,
    +543        };
    +544
    +545        // A buffer to pass through multiple datagrams at once as an optimisation.
    +546        let mut send_datagrams_buf = Vec::with_capacity(SEND_DATAGRAM_BATCH_SIZE);
    +547
    +548        // Regularly send pings so we know the connection is healthy.
    +549        // The first ping will be sent immediately.
    +550        let mut ping_interval = time::interval(PING_INTERVAL);
    +551        ping_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
    +552
    +553        let res = loop {
    +554            if let Some(data) = state.pong_pending.take() {
    +555                let fut = client_sink.send(SendMessage::Pong(data));
    +556                self.run_sending(fut, &mut state, &mut client_stream)
    +557                    .await?;
    +558            }
    +559            tokio::select! {
    +560                biased;
    +561                _ = self.stop_token.cancelled() => {
    +562                    debug!("Shutdown.");
    +563                    break Ok(());
    +564                }
    +565                msg = self.prio_inbox.recv() => {
    +566                    let Some(msg) = msg else {
    +567                        warn!("Priority inbox closed, shutdown.");
    +568                        break Ok(());
    +569                    };
    +570                    match msg {
    +571                        ActiveRelayPrioMessage::HasNodeRoute(peer, sender) => {
    +572                            let has_peer = state.nodes_present.contains(&peer);
    +573                            sender.send(has_peer).ok();
    +574                        }
    +575                    }
    +576                }
    +577                _ = state.ping_tracker.timeout() => {
    +578                    break Err(PingTimeoutSnafu.build());
    +579                }
    +580                _ = ping_interval.tick() => {
    +581                    let data = state.ping_tracker.new_ping();
    +582                    let fut = client_sink.send(SendMessage::Ping(data));
    +583                    self.run_sending(fut, &mut state, &mut client_stream).await?;
    +584                }
    +585                msg = self.inbox.recv() => {
    +586                    let Some(msg) = msg else {
    +587                        warn!("Inbox closed, shutdown.");
    +588                        break Ok(());
    +589                    };
    +590                    match msg {
    +591                        ActiveRelayMessage::SetHomeRelay(is_home) => {
    +592                            self.set_home_relay(is_home);
    +593                        }
    +594                        ActiveRelayMessage::CheckConnection(local_ips) => {
    +595                            match client_stream.local_addr() {
    +596                                Some(addr) if local_ips.contains(&addr.ip()) => {
    +597                                    let data = state.ping_tracker.new_ping();
    +598                                    let fut = client_sink.send(SendMessage::Ping(data));
    +599                                    self.run_sending(fut, &mut state, &mut client_stream).await?;
    +600                                }
    +601                                Some(_) => break Err(LocalIpInvalidSnafu.build()),
    +602                                None => break Err(LocalAddrMissingSnafu.build()),
    +603                            }
    +604                        }
    +605                        #[cfg(test)]
    +606                        ActiveRelayMessage::GetLocalAddr(sender) => {
    +607                            let addr = client_stream.local_addr();
    +608                            sender.send(addr).ok();
    +609                        }
    +610                        #[cfg(test)]
    +611                        ActiveRelayMessage::PingServer(sender) => {
    +612                            let data = rand::random();
    +613                            state.test_pong = Some((data, sender));
    +614                            let fut = client_sink.send(SendMessage::Ping(data));
    +615                            self.run_sending(fut, &mut state, &mut client_stream).await?;
    +616                        }
    +617                    }
    +618                }
    +619                count = self.relay_datagrams_send.recv_many(
    +620                    &mut send_datagrams_buf,
    +621                    SEND_DATAGRAM_BATCH_SIZE,
    +622                ) => {
    +623                    if count == 0 {
    +624                        warn!("Datagram inbox closed, shutdown");
    +625                        break Ok(());
    +626                    };
    +627                    self.reset_inactive_timeout();
    +628                    // TODO: This allocation is *very* unfortunate.  But so is the
    +629                    // allocation *inside* of PacketizeIter...
    +630                    let dgrams = std::mem::replace(
    +631                        &mut send_datagrams_buf,
    +632                        Vec::with_capacity(SEND_DATAGRAM_BATCH_SIZE),
    +633                    );
    +634                    // TODO(frando): can we avoid the clone here?
    +635                    let metrics = self.metrics.clone();
    +636                    let packet_iter = dgrams.into_iter().flat_map(|datagrams| {
    +637                        PacketizeIter::<_, MAX_PAYLOAD_SIZE>::new(
    +638                            datagrams.remote_node,
    +639                            datagrams.datagrams.clone(),
    +640                        )
    +641                        .map(|p| {
    +642                            Ok(SendMessage::SendPacket(p.node_id, p.payload))
    +643                        })
    +644                    });
    +645                    let mut packet_stream = n0_future::stream::iter(packet_iter).inspect(|m| {
    +646                        if let Ok(SendMessage::SendPacket(_node_id, payload)) = m {
    +647                            metrics.send_relay.inc_by(payload.len() as _);
    +648                        }
    +649                    });
    +650                    let fut = client_sink.send_all(&mut packet_stream);
    +651                    self.run_sending(fut, &mut state, &mut client_stream).await?;
    +652                }
    +653                msg = client_stream.next() => {
    +654                    let Some(msg) = msg else {
    +655                        break Err(StreamClosedServerSnafu.build());
    +656                    };
    +657                    match msg {
    +658                        Ok(msg) => {
    +659                            self.handle_relay_msg(msg, &mut state);
    +660                            // reset the ping timer, we have just received a message
    +661                            ping_interval.reset();
    +662                        },
    +663                        Err(err) => break Err(ClientStreamReadSnafu.into_error(err)),
    +664                    }
    +665                }
    +666                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
    +667                    debug!("Inactive for {RELAY_INACTIVE_CLEANUP_TIME:?}, exiting.");
    +668                    break Ok(());
    +669                }
    +670            }
    +671        };
    +672
    +673        if res.is_ok() {
    +674            if let Err(err) = client_sink.close().await {
    +675                debug!("Failed to close client sink gracefully: {err:#}");
    +676            }
    +677        }
    +678
    +679        res.map_err(|err| state.map_err(err))
    +680    }
    +681
    +682    fn handle_relay_msg(&mut self, msg: ReceivedMessage, state: &mut ConnectedRelayState) {
    +683        match msg {
    +684            ReceivedMessage::ReceivedPacket {
    +685                remote_node_id,
    +686                data,
    +687            } => {
    +688                trace!(len = %data.len(), "received msg");
    +689                // If this is a new sender, register a route for this peer.
    +690                if state
    +691                    .last_packet_src
    +692                    .as_ref()
    +693                    .map(|p| *p != remote_node_id)
    +694                    .unwrap_or(true)
    +695                {
    +696                    // Avoid map lookup with high throughput single peer.
    +697                    state.last_packet_src = Some(remote_node_id);
    +698                    state.nodes_present.insert(remote_node_id);
    +699                }
    +700                for datagram in PacketSplitIter::new(self.url.clone(), remote_node_id, data) {
    +701                    let Ok(datagram) = datagram else {
    +702                        warn!("Invalid packet split");
    +703                        break;
    +704                    };
    +705                    if let Err(err) = self.relay_datagrams_recv.try_send(datagram) {
    +706                        warn!("Dropping received relay packet: {err:#}");
    +707                    }
    +708                }
    +709            }
    +710            ReceivedMessage::NodeGone(node_id) => {
    +711                state.nodes_present.remove(&node_id);
    +712            }
    +713            ReceivedMessage::Ping(data) => state.pong_pending = Some(data),
    +714            ReceivedMessage::Pong(data) => {
    +715                #[cfg(test)]
    +716                {
    +717                    if let Some((expected_data, sender)) = state.test_pong.take() {
    +718                        if data == expected_data {
    +719                            sender.send(()).ok();
    +720                        } else {
    +721                            state.test_pong = Some((expected_data, sender));
    +722                        }
    +723                    }
    +724                }
    +725                state.ping_tracker.pong_received(data);
    +726                state.established = true;
    +727            }
    +728            ReceivedMessage::Health { problem } => {
    +729                let problem = problem.as_deref().unwrap_or("unknown");
    +730                warn!("Relay server reports problem: {problem}");
    +731            }
    +732            ReceivedMessage::KeepAlive | ReceivedMessage::ServerRestarting { .. } => {
    +733                trace!("Ignoring {msg:?}")
    +734            }
    +735        }
    +736    }
    +737
    +738    /// Run the actor main loop while sending to the relay server.
    +739    ///
    +740    /// While sending the actor should not read any inboxes which will give it more things
    +741    /// to send to the relay server.
    +742    ///
    +743    /// # Returns
    +744    ///
    +745    /// On `Err` the relay connection should be disconnected.  An `Ok` return means either
    +746    /// the actor should shut down, consult the [`ActiveRelayActor::stop_token`] and
    +747    /// [`ActiveRelayActor::inactive_timeout`] for this, or the send was successful.
    +748    #[instrument(name = "tx", skip_all)]
    +749    async fn run_sending<T>(
    +750        &mut self,
    +751        sending_fut: impl Future<Output = Result<T, RunError>>,
    +752        state: &mut ConnectedRelayState,
    +753        client_stream: &mut iroh_relay::client::ClientStream,
    +754    ) -> Result<(), RelayConnectionError> {
    +755        // we use the same time as for our ping interval
    +756        let send_timeout = PING_INTERVAL;
    +757
    +758        let mut timeout = pin!(time::sleep(send_timeout));
    +759        let mut sending_fut = pin!(sending_fut);
    +760        let res = loop {
    +761            tokio::select! {
    +762                biased;
    +763                _ = self.stop_token.cancelled() => {
    +764                    break Ok(());
    +765                }
    +766                _ = &mut timeout => {
    +767                    break Err(SendTimeoutSnafu.build());
    +768                }
    +769                msg = self.prio_inbox.recv() => {
    +770                    let Some(msg) = msg else {
    +771                        warn!("Priority inbox closed, shutdown.");
    +772                        break Ok(());
    +773                    };
    +774                    match msg {
    +775                        ActiveRelayPrioMessage::HasNodeRoute(peer, sender) => {
    +776                            let has_peer = state.nodes_present.contains(&peer);
    +777                            sender.send(has_peer).ok();
    +778                        }
    +779                    }
    +780                }
    +781                res = &mut sending_fut => {
    +782                    match res {
    +783                        Ok(_) => break Ok(()),
    +784                        Err(err) => break Err(err),
    +785                    }
    +786                }
    +787                _ = state.ping_tracker.timeout() => {
    +788                    break Err(PingTimeoutSnafu.build());
    +789                }
    +790                // No need to read the inbox or datagrams to send.
    +791                msg = client_stream.next() => {
    +792                    let Some(msg) = msg else {
    +793                        break Err(StreamClosedServerSnafu.build());
    +794                    };
    +795                    match msg {
    +796                        Ok(msg) => self.handle_relay_msg(msg, state),
    +797                        Err(err) => break Err(ClientStreamReadSnafu.into_error(err)),
    +798                    }
    +799                }
    +800                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
    +801                    debug!("Inactive for {RELAY_INACTIVE_CLEANUP_TIME:?}, exiting.");
    +802                    break Ok(());
    +803                }
    +804            }
    +805        };
    +806        res.map_err(|err| state.map_err(err))
    +807    }
    +808}
    +809
    +810/// Shared state when the [`ActiveRelayActor`] is connected to a relay server.
    +811///
    +812/// Common state between [`ActiveRelayActor::run_connected`] and
    +813/// [`ActiveRelayActor::run_sending`].
    +814#[derive(Debug)]
    +815struct ConnectedRelayState {
    +816    /// Tracks pings we have sent, awaits pong replies.
    +817    ping_tracker: PingTracker,
    +818    /// Nodes which are reachable via this relay server.
    +819    nodes_present: BTreeSet<NodeId>,
    +820    /// The [`NodeId`] from whom we received the last packet.
    +821    ///
    +822    /// This is to avoid a slower lookup in the [`ConnectedRelayState::nodes_present`] map
    +823    /// when we are only communicating to a single remote node.
    +824    last_packet_src: Option<NodeId>,
    +825    /// A pong we need to send ASAP.
    +826    pong_pending: Option<[u8; 8]>,
    +827    /// Whether the connection is to be considered established.
    +828    ///
    +829    /// This is set to `true` once a pong was received from the server.
    +830    established: bool,
    +831    #[cfg(test)]
    +832    test_pong: Option<([u8; 8], oneshot::Sender<()>)>,
    +833}
    +834
    +835impl ConnectedRelayState {
    +836    fn map_err(&self, error: RunError) -> RelayConnectionError {
    +837        if self.established {
    +838            EstablishedSnafu.into_error(error)
    +839        } else {
    +840            HandshakeSnafu.into_error(error)
    +841        }
    +842    }
    +843}
    +844
    +845pub(super) enum RelayActorMessage {
    +846    MaybeCloseRelaysOnRebind,
    +847    NetworkChange { info: NetInfo },
    +848}
    +849
    +850#[derive(Debug, Clone)]
    +851pub(crate) struct RelaySendItem {
    +852    /// The destination for the datagrams.
    +853    pub(crate) remote_node: NodeId,
    +854    /// The home relay of the remote node.
    +855    pub(crate) url: RelayUrl,
    +856    /// One or more datagrams to send.
    +857    pub(crate) datagrams: RelayContents,
    +858}
    +859
    +860pub(super) struct RelayActor {
    +861    config: Config,
    +862    /// Queue on which to put received datagrams.
    +863    relay_datagram_recv_queue: mpsc::Sender<RelayRecvDatagram>,
    +864    /// The actors managing each currently used relay server.
    +865    ///
    +866    /// These actors will exit when they have any inactivity.  Otherwise they will keep
    +867    /// trying to maintain a connection to the relay server as needed.
    +868    active_relays: BTreeMap<RelayUrl, ActiveRelayHandle>,
    +869    /// The tasks for the [`ActiveRelayActor`]s in `active_relays` above.
    +870    active_relay_tasks: JoinSet<()>,
    +871    cancel_token: CancellationToken,
    +872}
    +873
    +874#[derive(Debug)]
    +875pub struct Config {
    +876    pub my_relay: Watchable<Option<RelayUrl>>,
    +877    pub secret_key: SecretKey,
    +878    #[cfg(not(wasm_browser))]
    +879    pub dns_resolver: DnsResolver,
    +880    /// Proxy
    +881    pub proxy_url: Option<Url>,
    +882    /// If the last net_report report, reports IPv6 to be available.
    +883    pub ipv6_reported: Arc<AtomicBool>,
    +884    #[cfg(any(test, feature = "test-utils"))]
    +885    pub insecure_skip_relay_cert_verify: bool,
    +886    pub metrics: Arc<MagicsockMetrics>,
    +887    pub protocol: iroh_relay::http::Protocol,
    +888}
    +889
    +890impl RelayActor {
    +891    pub(super) fn new(
    +892        config: Config,
    +893        relay_datagram_recv_queue: mpsc::Sender<RelayRecvDatagram>,
    +894    ) -> Self {
    +895        let cancel_token = CancellationToken::new();
    +896        Self {
    +897            config,
    +898            relay_datagram_recv_queue,
    +899            active_relays: Default::default(),
    +900            active_relay_tasks: JoinSet::new(),
    +901            cancel_token,
    +902        }
    +903    }
    +904
    +905    pub(super) async fn run(
    +906        mut self,
    +907        mut receiver: mpsc::Receiver<RelayActorMessage>,
    +908        mut datagram_send_channel: mpsc::Receiver<RelaySendItem>,
    +909    ) {
    +910        // When this future is present, it is sending pending datagrams to an
    +911        // ActiveRelayActor.  We can not process further datagrams during this time.
    +912        let mut datagram_send_fut = std::pin::pin!(MaybeFuture::none());
    +913
    +914        loop {
    +915            tokio::select! {
    +916                biased;
    +917                _ = self.cancel_token.cancelled() => {
    +918                    debug!("shutting down");
    +919                    break;
    +920                }
    +921                Some(res) = self.active_relay_tasks.join_next() => {
    +922                    match res {
    +923                        Ok(()) => (),
    +924                        Err(err) if err.is_panic() => {
    +925                            error!("ActiveRelayActor task panicked: {err:#?}");
    +926                        }
    +927                        Err(err) if err.is_cancelled() => {
    +928                            error!("ActiveRelayActor cancelled: {err:#?}");
    +929                        }
    +930                        Err(err) => error!("ActiveRelayActor failed: {err:#?}"),
    +931                    }
    +932                    self.reap_active_relays();
    +933                }
    +934                msg = receiver.recv() => {
    +935                    let Some(msg) = msg else {
    +936                        debug!("Inbox dropped, shutting down.");
    +937                        break;
    +938                    };
    +939                    let cancel_token = self.cancel_token.child_token();
    +940                    cancel_token.run_until_cancelled(self.handle_msg(msg)).await;
    +941                }
    +942                // Only poll for new datagrams if we are not blocked on sending them.
    +943                item = datagram_send_channel.recv(), if datagram_send_fut.is_none() => {
    +944                    let Some(item) = item else {
    +945                        debug!("Datagram send channel dropped, shutting down.");
    +946                        break;
    +947                    };
    +948                    let token = self.cancel_token.child_token();
    +949                    if let Some(Some(fut)) = token.run_until_cancelled(
    +950                        self.try_send_datagram(item)
    +951                    ).await {
    +952                        datagram_send_fut.as_mut().set_future(fut);
    +953                    }
    +954                }
    +955                // Only poll this future if it is in use.
    +956                _ = &mut datagram_send_fut, if datagram_send_fut.is_some() => {
    +957                    datagram_send_fut.as_mut().set_none();
    +958                }
    +959            }
    +960        }
    +961
    +962        // try shutdown
    +963        if time::timeout(Duration::from_secs(3), self.close_all_active_relays())
    +964            .await
    +965            .is_err()
    +966        {
    +967            warn!("Failed to shut down all ActiveRelayActors");
    +968        }
    +969    }
    +970
    +971    async fn handle_msg(&mut self, msg: RelayActorMessage) {
    +972        match msg {
    +973            RelayActorMessage::NetworkChange { info } => {
    +974                self.on_network_change(info).await;
    +975            }
    +976            RelayActorMessage::MaybeCloseRelaysOnRebind => {
    +977                self.maybe_close_relays_on_rebind().await;
    +978            }
    +979        }
    +980    }
    +981
    +982    /// Sends datagrams to the correct [`ActiveRelayActor`], or returns a future.
    +983    ///
    +984    /// If the datagram can not be sent immediately, because the destination channel is
    +985    /// full, a future is returned that will complete once the datagrams have been sent to
    +986    /// the [`ActiveRelayActor`].
    +987    async fn try_send_datagram(&mut self, item: RelaySendItem) -> Option<impl Future<Output = ()>> {
    +988        let url = item.url.clone();
    +989        let handle = self
    +990            .active_relay_handle_for_node(&item.url, &item.remote_node)
    +991            .await;
    +992        match handle.datagrams_send_queue.try_send(item) {
    +993            Ok(()) => None,
    +994            Err(mpsc::error::TrySendError::Closed(_)) => {
    +995                warn!(?url, "Dropped datagram(s): ActiveRelayActor closed.");
    +996                None
    +997            }
    +998            Err(mpsc::error::TrySendError::Full(item)) => {
    +999                let sender = handle.datagrams_send_queue.clone();
    +1000                let fut = async move {
    +1001                    if sender.send(item).await.is_err() {
    +1002                        warn!(?url, "Dropped datagram(s): ActiveRelayActor closed.");
    +1003                    }
    +1004                };
    +1005                Some(fut)
    +1006            }
    +1007        }
    +1008    }
    +1009
    +1010    async fn on_network_change(&mut self, info: NetInfo) {
    +1011        let my_relay = self.config.my_relay.get();
    +1012        if info.preferred_relay == my_relay {
    +1013            // No change.
    +1014            return;
    +1015        }
    +1016        let old_relay = self
    +1017            .config
    +1018            .my_relay
    +1019            .set(info.preferred_relay.clone())
    +1020            .unwrap_or_else(|e| e);
    +1021
    +1022        if let Some(relay_url) = info.preferred_relay {
    +1023            self.config.metrics.relay_home_change.inc();
    +1024
    +1025            // On change, notify all currently connected relay servers and
    +1026            // start connecting to our home relay if we are not already.
    +1027            info!("home is now relay {}, was {:?}", relay_url, old_relay);
    +1028            self.set_home_relay(relay_url).await;
    +1029        }
    +1030    }
    +1031
    +1032    async fn set_home_relay(&mut self, home_url: RelayUrl) {
    +1033        let home_url_ref = &home_url;
    +1034        n0_future::join_all(self.active_relays.iter().map(|(url, handle)| async move {
    +1035            let is_preferred = url == home_url_ref;
    +1036            handle
    +1037                .inbox_addr
    +1038                .send(ActiveRelayMessage::SetHomeRelay(is_preferred))
    +1039                .await
    +1040                .ok()
    +1041        }))
    +1042        .await;
    +1043        // Ensure we have an ActiveRelayActor for the current home relay.
    +1044        self.active_relay_handle(home_url);
    +1045    }
    +1046
    +1047    /// Returns the handle for the [`ActiveRelayActor`] to reach `remote_node`.
    +1048    ///
    +1049    /// The node is expected to be reachable on `url`, but if no [`ActiveRelayActor`] for
    +1050    /// `url` exists but another existing [`ActiveRelayActor`] already knows about the node,
    +1051    /// that other node is used.
    +1052    async fn active_relay_handle_for_node(
    +1053        &mut self,
    +1054        url: &RelayUrl,
    +1055        remote_node: &NodeId,
    +1056    ) -> ActiveRelayHandle {
    +1057        if let Some(handle) = self.active_relays.get(url) {
    +1058            return handle.clone();
    +1059        }
    +1060
    +1061        let mut found_relay: Option<RelayUrl> = None;
    +1062        // If we don't have an open connection to the remote node's home relay, see if
    +1063        // we have an open connection to a relay node where we'd heard from that peer
    +1064        // already.  E.g. maybe they dialed our home relay recently.
    +1065        {
    +1066            // Futures which return Some(RelayUrl) if the relay knows about the remote node.
    +1067            let check_futs = self.active_relays.iter().map(|(url, handle)| async move {
    +1068                let (tx, rx) = oneshot::channel();
    +1069                handle
    +1070                    .prio_inbox_addr
    +1071                    .send(ActiveRelayPrioMessage::HasNodeRoute(*remote_node, tx))
    +1072                    .await
    +1073                    .ok();
    +1074                match rx.await {
    +1075                    Ok(true) => Some(url.clone()),
    +1076                    _ => None,
    +1077                }
    +1078            });
    +1079            let mut futures = FuturesUnorderedBounded::from_iter(check_futs);
    +1080            while let Some(maybe_url) = futures.next().await {
    +1081                if maybe_url.is_some() {
    +1082                    found_relay = maybe_url;
    +1083                    break;
    +1084                }
    +1085            }
    +1086        }
    +1087        let url = found_relay.unwrap_or(url.clone());
    +1088        self.active_relay_handle(url)
    +1089    }
    +1090
    +1091    /// Returns the handle of the [`ActiveRelayActor`].
    +1092    fn active_relay_handle(&mut self, url: RelayUrl) -> ActiveRelayHandle {
    +1093        match self.active_relays.get(&url) {
    +1094            Some(e) => e.clone(),
    +1095            None => {
    +1096                let handle = self.start_active_relay(url.clone());
    +1097                if Some(&url) == self.config.my_relay.get().as_ref() {
    +1098                    if let Err(err) = handle
    +1099                        .inbox_addr
    +1100                        .try_send(ActiveRelayMessage::SetHomeRelay(true))
    +1101                    {
    +1102                        error!("Home relay not set, send to new actor failed: {err:#}.");
    +1103                    }
    +1104                }
    +1105                self.active_relays.insert(url, handle.clone());
    +1106                self.log_active_relay();
    +1107                handle
    +1108            }
    +1109        }
    +1110    }
    +1111
    +1112    fn start_active_relay(&mut self, url: RelayUrl) -> ActiveRelayHandle {
    +1113        debug!(?url, "Adding relay connection");
    +1114
    +1115        let connection_opts = RelayConnectionOptions {
    +1116            secret_key: self.config.secret_key.clone(),
    +1117            #[cfg(not(wasm_browser))]
    +1118            dns_resolver: self.config.dns_resolver.clone(),
    +1119            proxy_url: self.config.proxy_url.clone(),
    +1120            prefer_ipv6: self.config.ipv6_reported.clone(),
    +1121            #[cfg(any(test, feature = "test-utils"))]
    +1122            insecure_skip_cert_verify: self.config.insecure_skip_relay_cert_verify,
    +1123            protocol: self.config.protocol,
    +1124        };
    +1125
    +1126        // TODO: Replace 64 with PER_CLIENT_SEND_QUEUE_DEPTH once that's unused
    +1127        let (send_datagram_tx, send_datagram_rx) = mpsc::channel(64);
    +1128        let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(32);
    +1129        let (inbox_tx, inbox_rx) = mpsc::channel(64);
    +1130        let span = info_span!("active-relay", %url);
    +1131        let opts = ActiveRelayActorOptions {
    +1132            url,
    +1133            prio_inbox_: prio_inbox_rx,
    +1134            inbox: inbox_rx,
    +1135            relay_datagrams_send: send_datagram_rx,
    +1136            relay_datagrams_recv: self.relay_datagram_recv_queue.clone(),
    +1137            connection_opts,
    +1138            stop_token: self.cancel_token.child_token(),
    +1139            metrics: self.config.metrics.clone(),
    +1140        };
    +1141        let actor = ActiveRelayActor::new(opts);
    +1142        self.active_relay_tasks.spawn(
    +1143            async move {
    +1144                actor.run().await;
    +1145            }
    +1146            .instrument(span),
    +1147        );
    +1148        let handle = ActiveRelayHandle {
    +1149            prio_inbox_addr: prio_inbox_tx,
    +1150            inbox_addr: inbox_tx,
    +1151            datagrams_send_queue: send_datagram_tx,
    +1152        };
    +1153        self.log_active_relay();
    +1154        handle
    +1155    }
    +1156
    +1157    /// Closes the relay connections not originating from a local IP address.
    +1158    ///
    +1159    /// Called in response to a rebind, any relay connection originating from an address
    +1160    /// that's not known to be currently a local IP address should be closed.  All the other
    +1161    /// relay connections are pinged.
    +1162    async fn maybe_close_relays_on_rebind(&mut self) {
    +1163        #[cfg(not(wasm_browser))]
    +1164        let ifs = interfaces::State::new().await;
    +1165        #[cfg(not(wasm_browser))]
    +1166        let local_ips: Vec<_> = ifs
    +1167            .interfaces
    +1168            .values()
    +1169            .flat_map(|netif| netif.addrs())
    +1170            .map(|ipnet| ipnet.addr())
    +1171            .collect();
    +1172        // In browsers, we don't have this information. This will do the right thing in the ActiveRelayActor, though.
    +1173        #[cfg(wasm_browser)]
    +1174        let local_ips = Vec::new();
    +1175        let send_futs = self.active_relays.values().map(|handle| {
    +1176            let local_ips = local_ips.clone();
    +1177            async move {
    +1178                handle
    +1179                    .inbox_addr
    +1180                    .send(ActiveRelayMessage::CheckConnection(local_ips))
    +1181                    .await
    +1182                    .ok();
    +1183            }
    +1184        });
    +1185        n0_future::join_all(send_futs).await;
    +1186        self.log_active_relay();
    +1187    }
    +1188
    +1189    /// Cleans up [`ActiveRelayActor`]s which have stopped running.
    +1190    fn reap_active_relays(&mut self) {
    +1191        self.active_relays
    +1192            .retain(|_url, handle| !handle.inbox_addr.is_closed());
    +1193
    +1194        // Make sure home relay exists
    +1195        if let Some(url) = self.config.my_relay.get() {
    +1196            self.active_relay_handle(url);
    +1197        }
    +1198        self.log_active_relay();
    +1199    }
    +1200
    +1201    /// Stops all [`ActiveRelayActor`]s and awaits for them to finish.
    +1202    async fn close_all_active_relays(&mut self) {
    +1203        self.cancel_token.cancel();
    +1204        let tasks = std::mem::take(&mut self.active_relay_tasks);
    +1205        tasks.join_all().await;
    +1206
    +1207        self.log_active_relay();
    +1208    }
    +1209
    +1210    fn log_active_relay(&self) {
    +1211        debug!("{} active relay conns{}", self.active_relays.len(), {
    +1212            let mut s = String::new();
    +1213            if !self.active_relays.is_empty() {
    +1214                s += ":";
    +1215                for node in self.active_relay_sorted() {
    +1216                    s += &format!(" relay-{}", node,);
    +1217                }
    +1218            }
    +1219            s
    +1220        });
    +1221    }
    +1222
    +1223    fn active_relay_sorted(&self) -> impl Iterator<Item = RelayUrl> {
    +1224        let mut ids: Vec<_> = self.active_relays.keys().cloned().collect();
    +1225        ids.sort();
    +1226
    +1227        ids.into_iter()
    +1228    }
    +1229}
    +1230
    +1231/// Handle to one [`ActiveRelayActor`].
    +1232#[derive(Debug, Clone)]
    +1233struct ActiveRelayHandle {
    +1234    prio_inbox_addr: mpsc::Sender<ActiveRelayPrioMessage>,
    +1235    inbox_addr: mpsc::Sender<ActiveRelayMessage>,
    +1236    datagrams_send_queue: mpsc::Sender<RelaySendItem>,
    +1237}
    +1238
    +1239/// A packet to send over the relay.
    +1240///
    +1241/// This is nothing but a newtype, it should be constructed using [`PacketizeIter`].  This
    +1242/// is a packet of one or more datagrams, each prefixed with a u16-be length.  This is what
    +1243/// the `Frame::SendPacket` of the `DerpCodec` transports and is produced by
    +1244/// [`PacketizeIter`] and transformed back into datagrams using [`PacketSplitIter`].
    +1245#[derive(Debug, PartialEq, Eq)]
    +1246struct RelaySendPacket {
    +1247    node_id: NodeId,
    +1248    payload: Bytes,
    +1249}
    +1250
    +1251/// A single datagram received from a relay server.
    +1252///
    +1253/// This could be either a QUIC or DISCO packet.
    +1254#[derive(Debug)]
    +1255pub(crate) struct RelayRecvDatagram {
    +1256    pub(crate) url: RelayUrl,
    +1257    pub(crate) src: NodeId,
    +1258    pub(crate) buf: Bytes,
    +1259}
    +1260
    +1261/// Combines datagrams into a single DISCO frame of at most MAX_PACKET_SIZE.
    +1262///
    +1263/// The disco `iroh_relay::protos::Frame::SendPacket` frame can contain more then a single
    +1264/// datagram.  Each datagram in this frame is prefixed with a little-endian 2-byte length
    +1265/// prefix.  This occurs when Quinn sends a GSO transmit containing more than one datagram,
    +1266/// which are split using `split_packets`.
    +1267///
    +1268/// The [`PacketSplitIter`] does the inverse and splits such packets back into individual
    +1269/// datagrams.
    +1270struct PacketizeIter<I: Iterator, const N: usize> {
    +1271    node_id: NodeId,
    +1272    iter: std::iter::Peekable<I>,
    +1273    buffer: BytesMut,
    +1274}
    +1275
    +1276impl<I: Iterator, const N: usize> PacketizeIter<I, N> {
    +1277    /// Create a new new PacketizeIter from something that can be turned into an
    +1278    /// iterator of slices, like a `Vec<Bytes>`.
    +1279    fn new(node_id: NodeId, iter: impl IntoIterator<IntoIter = I>) -> Self {
    +1280        Self {
    +1281            node_id,
    +1282            iter: iter.into_iter().peekable(),
    +1283            buffer: BytesMut::with_capacity(N),
    +1284        }
    +1285    }
    +1286}
    +1287
    +1288impl<I: Iterator, const N: usize> Iterator for PacketizeIter<I, N>
    +1289where
    +1290    I::Item: AsRef<[u8]>,
    +1291{
    +1292    type Item = RelaySendPacket;
    +1293
    +1294    fn next(&mut self) -> Option<Self::Item> {
    +1295        use bytes::BufMut;
    +1296        while let Some(next_bytes) = self.iter.peek() {
    +1297            let next_bytes = next_bytes.as_ref();
    +1298            assert!(next_bytes.len() + 2 <= N);
    +1299            let next_length: u16 = next_bytes.len().try_into().expect("items < 64k size");
    +1300            if self.buffer.len() + next_bytes.len() + 2 > N {
    +1301                break;
    +1302            }
    +1303            self.buffer.put_u16_le(next_length);
    +1304            self.buffer.put_slice(next_bytes);
    +1305            self.iter.next();
    +1306        }
    +1307        if !self.buffer.is_empty() {
    +1308            Some(RelaySendPacket {
    +1309                node_id: self.node_id,
    +1310                payload: self.buffer.split().freeze(),
    +1311            })
    +1312        } else {
    +1313            None
    +1314        }
    +1315    }
    +1316}
    +1317
    +1318/// Splits a single [`ReceivedMessage::ReceivedPacket`] frame into datagrams.
    +1319///
    +1320/// This splits packets joined by [`PacketizeIter`] back into individual datagrams.  See
    +1321/// that struct for more details.
    +1322#[derive(Debug)]
    +1323struct PacketSplitIter {
    +1324    url: RelayUrl,
    +1325    src: NodeId,
    +1326    bytes: Bytes,
    +1327}
    +1328
    +1329impl PacketSplitIter {
    +1330    /// Create a new PacketSplitIter from a packet.
    +1331    fn new(url: RelayUrl, src: NodeId, bytes: Bytes) -> Self {
    +1332        Self { url, src, bytes }
    +1333    }
    +1334
    +1335    fn fail(&mut self) -> Option<std::io::Result<RelayRecvDatagram>> {
    +1336        self.bytes.clear();
    +1337        Some(Err(std::io::Error::new(
    +1338            std::io::ErrorKind::UnexpectedEof,
    +1339            "",
    +1340        )))
    +1341    }
    +1342}
    +1343
    +1344impl Iterator for PacketSplitIter {
    +1345    type Item = std::io::Result<RelayRecvDatagram>;
    +1346
    +1347    fn next(&mut self) -> Option<Self::Item> {
    +1348        use bytes::Buf;
    +1349        if self.bytes.has_remaining() {
    +1350            if self.bytes.remaining() < 2 {
    +1351                return self.fail();
    +1352            }
    +1353            let len = self.bytes.get_u16_le() as usize;
    +1354            if self.bytes.remaining() < len {
    +1355                return self.fail();
    +1356            }
    +1357            let buf = self.bytes.split_to(len);
    +1358            Some(Ok(RelayRecvDatagram {
    +1359                url: self.url.clone(),
    +1360                src: self.src,
    +1361                buf,
    +1362            }))
    +1363        } else {
    +1364            None
    +1365        }
    +1366    }
    +1367}
    +1368
    +1369#[cfg(test)]
    +1370mod tests {
    +1371    use std::{
    +1372        sync::{atomic::AtomicBool, Arc},
    +1373        time::Duration,
    +1374    };
    +1375
    +1376    use bytes::Bytes;
    +1377    use iroh_base::{NodeId, RelayUrl, SecretKey};
    +1378    use iroh_relay::PingTracker;
    +1379    use n0_snafu::{Error, Result, ResultExt};
    +1380    use smallvec::smallvec;
    +1381    use tokio::sync::{mpsc, oneshot};
    +1382    use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle};
    +1383    use tracing::{info, info_span, Instrument};
    +1384    use tracing_test::traced_test;
    +1385
    +1386    use super::{
    +1387        ActiveRelayActor, ActiveRelayActorOptions, ActiveRelayMessage, ActiveRelayPrioMessage,
    +1388        PacketizeIter, RelayConnectionOptions, RelayRecvDatagram, RelaySendItem, MAX_PACKET_SIZE,
    +1389        RELAY_INACTIVE_CLEANUP_TIME, UNDELIVERABLE_DATAGRAM_TIMEOUT,
    +1390    };
    +1391    use crate::{dns::DnsResolver, test_utils};
    +1392
    +1393    #[test]
    +1394    fn test_packetize_iter() {
    +1395        let node_id = SecretKey::generate(rand::thread_rng()).public();
    +1396        let empty_vec: Vec<Bytes> = Vec::new();
    +1397        let mut iter = PacketizeIter::<_, MAX_PACKET_SIZE>::new(node_id, empty_vec);
    +1398        assert_eq!(None, iter.next());
    +1399
    +1400        let single_vec = vec!["Hello"];
    +1401        let iter = PacketizeIter::<_, MAX_PACKET_SIZE>::new(node_id, single_vec);
    +1402        let result = iter.collect::<Vec<_>>();
    +1403        assert_eq!(1, result.len());
    +1404        assert_eq!(
    +1405            &[5, 0, b'H', b'e', b'l', b'l', b'o'],
    +1406            &result[0].payload[..]
    +1407        );
    +1408
    +1409        let spacer = vec![0u8; MAX_PACKET_SIZE - 10];
    +1410        let multiple_vec = vec![&b"Hello"[..], &spacer, &b"World"[..]];
    +1411        let iter = PacketizeIter::<_, MAX_PACKET_SIZE>::new(node_id, multiple_vec);
    +1412        let result = iter.collect::<Vec<_>>();
    +1413        assert_eq!(2, result.len());
    +1414        assert_eq!(
    +1415            &[5, 0, b'H', b'e', b'l', b'l', b'o'],
    +1416            &result[0].payload[..7]
    +1417        );
    +1418        assert_eq!(
    +1419            &[5, 0, b'W', b'o', b'r', b'l', b'd'],
    +1420            &result[1].payload[..]
    +1421        );
    +1422    }
    +1423
    +1424    /// Starts a new [`ActiveRelayActor`].
    +1425    #[allow(clippy::too_many_arguments)]
    +1426    fn start_active_relay_actor(
    +1427        secret_key: SecretKey,
    +1428        stop_token: CancellationToken,
    +1429        url: RelayUrl,
    +1430        prio_inbox_rx: mpsc::Receiver<ActiveRelayPrioMessage>,
    +1431        inbox_rx: mpsc::Receiver<ActiveRelayMessage>,
    +1432        relay_datagrams_send: mpsc::Receiver<RelaySendItem>,
    +1433        relay_datagrams_recv: mpsc::Sender<RelayRecvDatagram>,
    +1434        span: tracing::Span,
    +1435    ) -> AbortOnDropHandle<()> {
    +1436        let opts = ActiveRelayActorOptions {
    +1437            url,
    +1438            prio_inbox_: prio_inbox_rx,
    +1439            inbox: inbox_rx,
    +1440            relay_datagrams_send,
    +1441            relay_datagrams_recv,
    +1442            connection_opts: RelayConnectionOptions {
    +1443                secret_key,
    +1444                dns_resolver: DnsResolver::new(),
    +1445                proxy_url: None,
    +1446                prefer_ipv6: Arc::new(AtomicBool::new(true)),
    +1447                insecure_skip_cert_verify: true,
    +1448                protocol: iroh_relay::http::Protocol::default(),
    +1449            },
    +1450            stop_token,
    +1451            metrics: Default::default(),
    +1452        };
    +1453        let task = tokio::spawn(ActiveRelayActor::new(opts).run().instrument(span));
    +1454        AbortOnDropHandle::new(task)
    +1455    }
    +1456
    +1457    /// Starts an [`ActiveRelayActor`] as an "iroh echo node".
    +1458    ///
    +1459    /// This actor will connect to the relay server, pretending to be an iroh node, and echo
    +1460    /// back any datagram it receives from the relay.  This is used by the
    +1461    /// [`ActiveRelayNode`] under test to check connectivity works.
    +1462    fn start_echo_node(relay_url: RelayUrl) -> (NodeId, AbortOnDropHandle<()>) {
    +1463        let secret_key = SecretKey::from_bytes(&[8u8; 32]);
    +1464        let (recv_datagram_tx, mut recv_datagram_rx) = mpsc::channel(16);
    +1465        let (send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
    +1466        let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
    +1467        let (inbox_tx, inbox_rx) = mpsc::channel(16);
    +1468        let cancel_token = CancellationToken::new();
    +1469        let actor_task = start_active_relay_actor(
    +1470            secret_key.clone(),
    +1471            cancel_token.clone(),
    +1472            relay_url.clone(),
    +1473            prio_inbox_rx,
    +1474            inbox_rx,
    +1475            send_datagram_rx,
    +1476            recv_datagram_tx,
    +1477            info_span!("echo-node"),
    +1478        );
    +1479        let echo_task = tokio::spawn({
    +1480            let relay_url = relay_url.clone();
    +1481            async move {
    +1482                loop {
    +1483                    let datagram = recv_datagram_rx.recv().await;
    +1484                    if let Some(recv) = datagram {
    +1485                        let RelayRecvDatagram { url: _, src, buf } = recv;
    +1486                        info!(from = src.fmt_short(), "Received datagram");
    +1487                        let send = RelaySendItem {
    +1488                            remote_node: src,
    +1489                            url: relay_url.clone(),
    +1490                            datagrams: smallvec![buf],
    +1491                        };
    +1492                        send_datagram_tx.send(send).await.ok();
    +1493                    }
    +1494                }
    +1495            }
    +1496            .instrument(info_span!("echo-task"))
    +1497        });
    +1498        let echo_task = AbortOnDropHandle::new(echo_task);
    +1499        let supervisor_task = tokio::spawn(async move {
    +1500            let _guard = cancel_token.drop_guard();
    +1501            // move the inboxes here so it is not dropped, as this stops the actor.
    +1502            let _prio_inbox_tx = prio_inbox_tx;
    +1503            let _inbox_tx = inbox_tx;
    +1504            tokio::select! {
    +1505                biased;
    +1506                _ = actor_task => (),
    +1507                _ = echo_task => (),
    +1508            };
    +1509        });
    +1510        let supervisor_task = AbortOnDropHandle::new(supervisor_task);
    +1511        (secret_key.public(), supervisor_task)
    +1512    }
    +1513
    +1514    /// Sends a message to the echo node, receives the response.
    +1515    ///
    +1516    /// This takes care of retry and timeout.  Because we don't know when both the
    +1517    /// node-under-test and the echo node will be ready and datagrams aren't queued to send
    +1518    /// forever, we have to retry a few times.
    +1519    async fn send_recv_echo(
    +1520        item: RelaySendItem,
    +1521        tx: &mpsc::Sender<RelaySendItem>,
    +1522        rx: &mut mpsc::Receiver<RelayRecvDatagram>,
    +1523    ) -> Result<()> {
    +1524        assert!(item.datagrams.len() == 1);
    +1525        tokio::time::timeout(Duration::from_secs(10), async move {
    +1526            loop {
    +1527                let res = tokio::time::timeout(UNDELIVERABLE_DATAGRAM_TIMEOUT, async {
    +1528                    tx.send(item.clone()).await.context("send item")?;
    +1529                    let RelayRecvDatagram {
    +1530                        url: _,
    +1531                        src: _,
    +1532                        buf,
    +1533                    } = rx.recv().await.unwrap();
    +1534
    +1535                    assert_eq!(buf.as_ref(), item.datagrams[0]);
    +1536
    +1537                    Ok::<_, Error>(())
    +1538                })
    +1539                .await;
    +1540                if res.is_ok() {
    +1541                    break;
    +1542                }
    +1543            }
    +1544        })
    +1545        .await
    +1546        .expect("overall timeout exceeded");
    +1547        Ok(())
    +1548    }
    +1549
    +1550    #[tokio::test]
    +1551    #[traced_test]
    +1552    async fn test_active_relay_reconnect() -> Result {
    +1553        let (_relay_map, relay_url, _server) = test_utils::run_relay_server().await?;
    +1554        let (peer_node, _echo_node_task) = start_echo_node(relay_url.clone());
    +1555
    +1556        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
    +1557        let (datagram_recv_tx, mut datagram_recv_rx) = mpsc::channel(16);
    +1558        let (send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
    +1559        let (_prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
    +1560        let (inbox_tx, inbox_rx) = mpsc::channel(16);
    +1561        let cancel_token = CancellationToken::new();
    +1562        let task = start_active_relay_actor(
    +1563            secret_key,
    +1564            cancel_token.clone(),
    +1565            relay_url.clone(),
    +1566            prio_inbox_rx,
    +1567            inbox_rx,
    +1568            send_datagram_rx,
    +1569            datagram_recv_tx.clone(),
    +1570            info_span!("actor-under-test"),
    +1571        );
    +1572
    +1573        // Send a datagram to our echo node.
    +1574        info!("first echo");
    +1575        let hello_send_item = RelaySendItem {
    +1576            remote_node: peer_node,
    +1577            url: relay_url.clone(),
    +1578            datagrams: smallvec![Bytes::from_static(b"hello")],
    +1579        };
    +1580        send_recv_echo(
    +1581            hello_send_item.clone(),
    +1582            &send_datagram_tx,
    +1583            &mut datagram_recv_rx,
    +1584        )
    +1585        .await?;
    +1586
    +1587        // Now ask to check the connection, triggering a ping but no reconnect.
    +1588        let (tx, rx) = oneshot::channel();
    +1589        inbox_tx
    +1590            .send(ActiveRelayMessage::GetLocalAddr(tx))
    +1591            .await
    +1592            .context("send get local addr msg")?;
    +1593
    +1594        let local_addr = rx
    +1595            .await
    +1596            .context("wait for local addr msg")?
    +1597            .context("no local addr")?;
    +1598        info!(?local_addr, "check connection with addr");
    +1599        inbox_tx
    +1600            .send(ActiveRelayMessage::CheckConnection(vec![local_addr.ip()]))
    +1601            .await
    +1602            .context("send check connection message")?;
    +1603
    +1604        // Sync the ActiveRelayActor. Ping blocks it and we want to be sure it has handled
    +1605        // another inbox message before continuing.
    +1606        let (tx, rx) = oneshot::channel();
    +1607        inbox_tx
    +1608            .send(ActiveRelayMessage::GetLocalAddr(tx))
    +1609            .await
    +1610            .context("send get local addr msg")?;
    +1611        rx.await.context("recv send local addr msg")?;
    +1612
    +1613        // Echo should still work.
    +1614        info!("second echo");
    +1615        send_recv_echo(
    +1616            hello_send_item.clone(),
    +1617            &send_datagram_tx,
    +1618            &mut datagram_recv_rx,
    +1619        )
    +1620        .await?;
    +1621
    +1622        // Now ask to check the connection, this will reconnect without pinging because we
    +1623        // do not supply any "valid" local IP addresses.
    +1624        info!("check connection");
    +1625        inbox_tx
    +1626            .send(ActiveRelayMessage::CheckConnection(Vec::new()))
    +1627            .await
    +1628            .context("send check connection msg")?;
    +1629
    +1630        // Give some time to reconnect, mostly to sort logs rather than functional.
    +1631        tokio::time::sleep(Duration::from_millis(10)).await;
    +1632
    +1633        // Echo should still work.
    +1634        info!("third echo");
    +1635        send_recv_echo(
    +1636            hello_send_item.clone(),
    +1637            &send_datagram_tx,
    +1638            &mut datagram_recv_rx,
    +1639        )
    +1640        .await?;
    +1641
    +1642        // Shut down the actor.
    +1643        cancel_token.cancel();
    +1644        task.await.context("wait for task to finish")?;
    +1645
    +1646        Ok(())
    +1647    }
    +1648
    +1649    #[tokio::test]
    +1650    #[traced_test]
    +1651    async fn test_active_relay_inactive() -> Result {
    +1652        let (_relay_map, relay_url, _server) = test_utils::run_relay_server().await?;
    +1653
    +1654        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
    +1655        let (datagram_recv_tx, _datagram_recv_rx) = mpsc::channel(16);
    +1656        let (_send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
    +1657        let (_prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
    +1658        let (inbox_tx, inbox_rx) = mpsc::channel(16);
    +1659        let cancel_token = CancellationToken::new();
    +1660        let mut task = start_active_relay_actor(
    +1661            secret_key,
    +1662            cancel_token.clone(),
    +1663            relay_url,
    +1664            prio_inbox_rx,
    +1665            inbox_rx,
    +1666            send_datagram_rx,
    +1667            datagram_recv_tx,
    +1668            info_span!("actor-under-test"),
    +1669        );
    +1670
    +1671        // Wait until the actor is connected to the relay server.
    +1672        tokio::time::timeout(Duration::from_secs(5), async {
    +1673            loop {
    +1674                let (tx, rx) = oneshot::channel();
    +1675                inbox_tx.send(ActiveRelayMessage::PingServer(tx)).await.ok();
    +1676                if tokio::time::timeout(Duration::from_millis(200), rx)
    +1677                    .await
    +1678                    .map(|resp| resp.is_ok())
    +1679                    .unwrap_or_default()
    +1680                {
    +1681                    break;
    +1682                }
    +1683            }
    +1684        })
    +1685        .await
    +1686        .context("timeout")?;
    +1687
    +1688        // We now have an idling ActiveRelayActor.  If we advance time just a little it
    +1689        // should stay alive.
    +1690        info!("Stepping time forwards by RELAY_INACTIVE_CLEANUP_TIME / 2");
    +1691        tokio::time::pause();
    +1692        tokio::time::advance(RELAY_INACTIVE_CLEANUP_TIME / 2).await;
    +1693        tokio::time::resume();
    +1694
    +1695        assert!(
    +1696            tokio::time::timeout(Duration::from_millis(100), &mut task)
    +1697                .await
    +1698                .is_err(),
    +1699            "actor task terminated"
    +1700        );
    +1701
    +1702        // If we advance time a lot it should finish.
    +1703        info!("Stepping time forwards by RELAY_INACTIVE_CLEANUP_TIME");
    +1704        tokio::time::pause();
    +1705        tokio::time::advance(RELAY_INACTIVE_CLEANUP_TIME).await;
    +1706        tokio::time::resume();
    +1707        assert!(
    +1708            tokio::time::timeout(Duration::from_secs(1), task)
    +1709                .await
    +1710                .is_ok(),
    +1711            "actor task still running"
    +1712        );
    +1713
    +1714        cancel_token.cancel();
    +1715
    +1716        Ok(())
    +1717    }
    +1718
    +1719    #[tokio::test]
    +1720    async fn test_ping_tracker() {
    +1721        tokio::time::pause();
    +1722        let mut tracker = PingTracker::default();
    +1723
    +1724        let ping0 = tracker.new_ping();
    +1725
    +1726        let res = tokio::time::timeout(Duration::from_secs(1), tracker.timeout()).await;
    +1727        assert!(res.is_err(), "no ping timeout has elapsed yet");
    +1728
    +1729        tracker.pong_received(ping0);
    +1730        let res = tokio::time::timeout(Duration::from_secs(10), tracker.timeout()).await;
    +1731        assert!(res.is_err(), "ping completed before timeout");
    +1732
    +1733        let _ping1 = tracker.new_ping();
    +1734
    +1735        let res = tokio::time::timeout(Duration::from_secs(10), tracker.timeout()).await;
    +1736        assert!(res.is_ok(), "ping timeout should have happened");
    +1737
    +1738        let _ping2 = tracker.new_ping();
    +1739
    +1740        tokio::time::sleep(Duration::from_secs(10)).await;
    +1741        let res = tokio::time::timeout(Duration::from_millis(1), tracker.timeout()).await;
    +1742        assert!(res.is_ok(), "ping timeout happened in the past");
    +1743
    +1744        let res = tokio::time::timeout(Duration::from_secs(10), tracker.timeout()).await;
    +1745        assert!(res.is_err(), "ping timeout should only happen once");
    +1746    }
    +1747}
    \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/magicsock/udp_conn.rs.html b/pr/3327/docs/src/iroh/magicsock/udp_conn.rs.html deleted file mode 100644 index 63c56fd792..0000000000 --- a/pr/3327/docs/src/iroh/magicsock/udp_conn.rs.html +++ /dev/null @@ -1,81 +0,0 @@ -udp_conn.rs - source

    iroh/magicsock/
    udp_conn.rs

    1use std::{
    -2    fmt::Debug,
    -3    io,
    -4    net::SocketAddr,
    -5    pin::Pin,
    -6    sync::Arc,
    -7    task::{Context, Poll},
    -8};
    -9
    -10use netwatch::UdpSocket;
    -11use quinn::AsyncUdpSocket;
    -12use quinn_udp::Transmit;
    -13
    -14/// Wrapper struct to implement Quinn's [`AsyncUdpSocket`] for [`UdpSocket`].
    -15#[derive(Debug, Clone)]
    -16pub(super) struct UdpConn {
    -17    inner: Arc<UdpSocket>,
    -18}
    -19
    -20impl UdpConn {
    -21    pub(super) fn wrap(inner: Arc<UdpSocket>) -> Self {
    -22        Self { inner }
    -23    }
    -24
    -25    pub(super) fn as_socket_ref(&self) -> &UdpSocket {
    -26        &self.inner
    -27    }
    -28
    -29    pub(super) fn create_io_poller(&self) -> Pin<Box<dyn quinn::UdpPoller>> {
    -30        Box::pin(IoPoller {
    -31            io: self.inner.clone(),
    -32        })
    -33    }
    -34}
    -35
    -36impl AsyncUdpSocket for UdpConn {
    -37    fn create_io_poller(self: Arc<Self>) -> Pin<Box<dyn quinn::UdpPoller>> {
    -38        (*self).create_io_poller()
    -39    }
    -40
    -41    fn try_send(&self, transmit: &Transmit<'_>) -> io::Result<()> {
    -42        self.inner.try_send_quinn(transmit)
    -43    }
    -44
    -45    fn poll_recv(
    -46        &self,
    -47        cx: &mut Context,
    -48        bufs: &mut [io::IoSliceMut<'_>],
    -49        meta: &mut [quinn_udp::RecvMeta],
    -50    ) -> Poll<io::Result<usize>> {
    -51        self.inner.poll_recv_quinn(cx, bufs, meta)
    -52    }
    -53
    -54    fn local_addr(&self) -> io::Result<SocketAddr> {
    -55        self.inner.local_addr()
    -56    }
    -57
    -58    fn may_fragment(&self) -> bool {
    -59        self.inner.may_fragment()
    -60    }
    -61
    -62    fn max_transmit_segments(&self) -> usize {
    -63        self.inner.max_gso_segments()
    -64    }
    -65
    -66    fn max_receive_segments(&self) -> usize {
    -67        self.inner.gro_segments()
    -68    }
    -69}
    -70
    -71/// Poller for when the socket is writable.
    -72#[derive(Debug)]
    -73struct IoPoller {
    -74    io: Arc<UdpSocket>,
    -75}
    -76
    -77impl quinn::UdpPoller for IoPoller {
    -78    fn poll_writable(self: Pin<&mut Self>, cx: &mut Context) -> Poll<io::Result<()>> {
    -79        self.io.poll_writable(cx)
    -80    }
    -81}
    \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/net_report.rs.html b/pr/3327/docs/src/iroh/net_report.rs.html index 16df7c8354..3deda46857 100644 --- a/pr/3327/docs/src/iroh/net_report.rs.html +++ b/pr/3327/docs/src/iroh/net_report.rs.html @@ -617,759 +617,761 @@ 617 self.metrics.clone(), 618 #[cfg(not(wasm_browser))] 619 socket_state, -620 ); -621 -622 self.current_report_run = Some(ReportRun { -623 _reportgen: actor, -624 report_tx: response_tx, -625 }); -626 } -627 -628 fn handle_report_ready(&mut self, report: Report) { -629 let report = self.finish_and_store_report(report); -630 self.in_flight_stun_requests.clear(); -631 if let Some(ReportRun { report_tx, .. }) = self.current_report_run.take() { -632 report_tx.send(Ok(report)).ok(); -633 } -634 } -635 -636 fn handle_report_aborted(&mut self, reason: ActorRunError) { -637 self.in_flight_stun_requests.clear(); -638 if let Some(ReportRun { report_tx, .. }) = self.current_report_run.take() { -639 report_tx.send(Err(AbortSnafu { reason }.build())).ok(); -640 } -641 } -642 -643 /// Handles [`Message::StunPacket`]. -644 /// -645 /// If there are currently no in-flight stun requests registered this is dropped, -646 /// otherwise forwarded to the probe. -647 fn handle_stun_packet(&mut self, pkt: &[u8], src: SocketAddr) { -648 trace!(%src, "received STUN packet"); -649 if self.in_flight_stun_requests.is_empty() { -650 return; -651 } -652 -653 #[cfg(feature = "metrics")] -654 match &src { -655 SocketAddr::V4(_) => { -656 self.metrics.stun_packets_recv_ipv4.inc(); -657 } -658 SocketAddr::V6(_) => { -659 self.metrics.stun_packets_recv_ipv6.inc(); -660 } -661 } -662 -663 match stun::parse_response(pkt) { -664 Ok((txn, addr_port)) => match self.in_flight_stun_requests.remove(&txn) { -665 Some(inf) => { -666 debug!(%src, %txn, "received known STUN packet"); -667 let elapsed = inf.start.elapsed(); -668 inf.s.send((elapsed, addr_port)).ok(); -669 } -670 None => { -671 debug!(%src, %txn, "received unexpected STUN message response"); -672 } -673 }, -674 Err(err) => { -675 match stun::parse_binding_request(pkt) { -676 Ok(txn) => { -677 // Is this our hairpin request? -678 match self.in_flight_stun_requests.remove(&txn) { -679 Some(inf) => { -680 debug!(%src, %txn, "received our hairpin STUN request"); -681 let elapsed = inf.start.elapsed(); -682 inf.s.send((elapsed, src)).ok(); -683 } -684 None => { -685 debug!(%src, %txn, "unknown STUN request"); -686 } -687 } -688 } -689 Err(_) => { -690 debug!(%src, "received invalid STUN response: {err:#}"); -691 } -692 } -693 } -694 } -695 } -696 -697 /// Handles [`Message::InFlightStun`]. -698 /// -699 /// The in-flight request is added to [`Actor::in_flight_stun_requests`] so that -700 /// [`Actor::handle_stun_packet`] can forward packets correctly. -701 /// -702 /// *response_tx* is to signal the actor message has been handled. -703 fn handle_in_flight_stun(&mut self, inflight: Inflight, response_tx: oneshot::Sender<()>) { -704 self.in_flight_stun_requests.insert(inflight.txn, inflight); -705 response_tx.send(()).ok(); -706 } -707 -708 fn finish_and_store_report(&mut self, report: Report) -> Arc<Report> { -709 let report = self.add_report_history_and_set_preferred_relay(report); -710 debug!("{report:?}"); -711 report -712 } -713 -714 /// Adds `r` to the set of recent Reports and mutates `r.preferred_relay` to contain the best recent one. -715 /// `r` is stored ref counted and a reference is returned. -716 fn add_report_history_and_set_preferred_relay(&mut self, mut r: Report) -> Arc<Report> { -717 let mut prev_relay = None; -718 if let Some(ref last) = self.reports.last { -719 prev_relay.clone_from(&last.preferred_relay); -720 } -721 let now = Instant::now(); -722 const MAX_AGE: Duration = Duration::from_secs(5 * 60); -723 -724 // relay ID => its best recent latency in last MAX_AGE -725 let mut best_recent = RelayLatencies::new(); -726 -727 // chain the current report as we are still mutating it -728 let prevs_iter = self -729 .reports -730 .prev -731 .iter() -732 .map(|(a, b)| -> (&Instant, &Report) { (a, b) }) -733 .chain(std::iter::once((&now, &r))); -734 -735 let mut to_remove = Vec::new(); -736 for (t, pr) in prevs_iter { -737 if now.duration_since(*t) > MAX_AGE { -738 to_remove.push(*t); -739 continue; -740 } -741 best_recent.merge(&pr.relay_latency); -742 } -743 -744 for t in to_remove { -745 self.reports.prev.remove(&t); -746 } -747 -748 // Then, pick which currently-alive relay server from the -749 // current report has the best latency over the past MAX_AGE. -750 let mut best_any = Duration::default(); -751 let mut old_relay_cur_latency = Duration::default(); -752 { -753 for (url, duration) in r.relay_latency.iter() { -754 if Some(url) == prev_relay.as_ref() { -755 old_relay_cur_latency = duration; -756 } -757 if let Some(best) = best_recent.get(url) { -758 if r.preferred_relay.is_none() || best < best_any { -759 best_any = best; -760 r.preferred_relay.replace(url.clone()); -761 } -762 } -763 } -764 -765 // If we're changing our preferred relay but the old one's still -766 // accessible and the new one's not much better, just stick with -767 // where we are. -768 if prev_relay.is_some() -769 && r.preferred_relay != prev_relay -770 && !old_relay_cur_latency.is_zero() -771 && best_any > old_relay_cur_latency / 3 * 2 -772 { -773 r.preferred_relay = prev_relay; -774 } -775 } -776 -777 let r = Arc::new(r); -778 self.reports.prev.insert(now, r.clone()); -779 self.reports.last = Some(r.clone()); -780 -781 r -782 } -783} -784 -785/// State the net_report actor needs for an in-progress report generation. -786#[derive(Debug)] -787struct ReportRun { -788 /// The handle of the [`reportgen`] actor, cancels the actor on drop. -789 _reportgen: reportgen::Client, -790 /// Where to send the completed report. -791 report_tx: oneshot::Sender<Result<Arc<Report>, ReportError>>, -792} -793 -794#[allow(missing_docs)] -795#[common_fields({ -796 backtrace: Option<snafu::Backtrace>, -797 #[snafu(implicit)] -798 span_trace: n0_snafu::SpanTrace, -799})] -800#[derive(Debug, Snafu)] -801#[non_exhaustive] -802pub enum ReportError { -803 #[snafu(display("Report aborted early"))] -804 Abort { reason: ActorRunError }, -805 #[snafu(display("Report generation is already running"))] -806 AlreadyRunning {}, -807 #[snafu(display("Internal actor is gone"))] -808 ActorGone {}, -809} -810 -811/// Test if IPv6 works at all, or if it's been hard disabled at the OS level. -812#[cfg(not(wasm_browser))] -813fn os_has_ipv6() -> bool { -814 UdpSocket::bind_local_v6(0).is_ok() -815} -816 -817/// Always returns false in browsers -818#[cfg(wasm_browser)] -819fn os_has_ipv6() -> bool { -820 false -821} -822 -823#[cfg(not(wasm_browser))] -824pub(crate) mod stun_utils { -825 use netwatch::IpFamily; -826 use tokio_util::sync::CancellationToken; -827 -828 use super::*; +620 #[cfg(any(test, feature = "test-utils"))] +621 opts.insecure_skip_relay_cert_verify, +622 ); +623 +624 self.current_report_run = Some(ReportRun { +625 _reportgen: actor, +626 report_tx: response_tx, +627 }); +628 } +629 +630 fn handle_report_ready(&mut self, report: Report) { +631 let report = self.finish_and_store_report(report); +632 self.in_flight_stun_requests.clear(); +633 if let Some(ReportRun { report_tx, .. }) = self.current_report_run.take() { +634 report_tx.send(Ok(report)).ok(); +635 } +636 } +637 +638 fn handle_report_aborted(&mut self, reason: ActorRunError) { +639 self.in_flight_stun_requests.clear(); +640 if let Some(ReportRun { report_tx, .. }) = self.current_report_run.take() { +641 report_tx.send(Err(AbortSnafu { reason }.build())).ok(); +642 } +643 } +644 +645 /// Handles [`Message::StunPacket`]. +646 /// +647 /// If there are currently no in-flight stun requests registered this is dropped, +648 /// otherwise forwarded to the probe. +649 fn handle_stun_packet(&mut self, pkt: &[u8], src: SocketAddr) { +650 trace!(%src, "received STUN packet"); +651 if self.in_flight_stun_requests.is_empty() { +652 return; +653 } +654 +655 #[cfg(feature = "metrics")] +656 match &src { +657 SocketAddr::V4(_) => { +658 self.metrics.stun_packets_recv_ipv4.inc(); +659 } +660 SocketAddr::V6(_) => { +661 self.metrics.stun_packets_recv_ipv6.inc(); +662 } +663 } +664 +665 match stun::parse_response(pkt) { +666 Ok((txn, addr_port)) => match self.in_flight_stun_requests.remove(&txn) { +667 Some(inf) => { +668 debug!(%src, %txn, "received known STUN packet"); +669 let elapsed = inf.start.elapsed(); +670 inf.s.send((elapsed, addr_port)).ok(); +671 } +672 None => { +673 debug!(%src, %txn, "received unexpected STUN message response"); +674 } +675 }, +676 Err(err) => { +677 match stun::parse_binding_request(pkt) { +678 Ok(txn) => { +679 // Is this our hairpin request? +680 match self.in_flight_stun_requests.remove(&txn) { +681 Some(inf) => { +682 debug!(%src, %txn, "received our hairpin STUN request"); +683 let elapsed = inf.start.elapsed(); +684 inf.s.send((elapsed, src)).ok(); +685 } +686 None => { +687 debug!(%src, %txn, "unknown STUN request"); +688 } +689 } +690 } +691 Err(_) => { +692 debug!(%src, "received invalid STUN response: {err:#}"); +693 } +694 } +695 } +696 } +697 } +698 +699 /// Handles [`Message::InFlightStun`]. +700 /// +701 /// The in-flight request is added to [`Actor::in_flight_stun_requests`] so that +702 /// [`Actor::handle_stun_packet`] can forward packets correctly. +703 /// +704 /// *response_tx* is to signal the actor message has been handled. +705 fn handle_in_flight_stun(&mut self, inflight: Inflight, response_tx: oneshot::Sender<()>) { +706 self.in_flight_stun_requests.insert(inflight.txn, inflight); +707 response_tx.send(()).ok(); +708 } +709 +710 fn finish_and_store_report(&mut self, report: Report) -> Arc<Report> { +711 let report = self.add_report_history_and_set_preferred_relay(report); +712 debug!("{report:?}"); +713 report +714 } +715 +716 /// Adds `r` to the set of recent Reports and mutates `r.preferred_relay` to contain the best recent one. +717 /// `r` is stored ref counted and a reference is returned. +718 fn add_report_history_and_set_preferred_relay(&mut self, mut r: Report) -> Arc<Report> { +719 let mut prev_relay = None; +720 if let Some(ref last) = self.reports.last { +721 prev_relay.clone_from(&last.preferred_relay); +722 } +723 let now = Instant::now(); +724 const MAX_AGE: Duration = Duration::from_secs(5 * 60); +725 +726 // relay ID => its best recent latency in last MAX_AGE +727 let mut best_recent = RelayLatencies::new(); +728 +729 // chain the current report as we are still mutating it +730 let prevs_iter = self +731 .reports +732 .prev +733 .iter() +734 .map(|(a, b)| -> (&Instant, &Report) { (a, b) }) +735 .chain(std::iter::once((&now, &r))); +736 +737 let mut to_remove = Vec::new(); +738 for (t, pr) in prevs_iter { +739 if now.duration_since(*t) > MAX_AGE { +740 to_remove.push(*t); +741 continue; +742 } +743 best_recent.merge(&pr.relay_latency); +744 } +745 +746 for t in to_remove { +747 self.reports.prev.remove(&t); +748 } +749 +750 // Then, pick which currently-alive relay server from the +751 // current report has the best latency over the past MAX_AGE. +752 let mut best_any = Duration::default(); +753 let mut old_relay_cur_latency = Duration::default(); +754 { +755 for (url, duration) in r.relay_latency.iter() { +756 if Some(url) == prev_relay.as_ref() { +757 old_relay_cur_latency = duration; +758 } +759 if let Some(best) = best_recent.get(url) { +760 if r.preferred_relay.is_none() || best < best_any { +761 best_any = best; +762 r.preferred_relay.replace(url.clone()); +763 } +764 } +765 } +766 +767 // If we're changing our preferred relay but the old one's still +768 // accessible and the new one's not much better, just stick with +769 // where we are. +770 if prev_relay.is_some() +771 && r.preferred_relay != prev_relay +772 && !old_relay_cur_latency.is_zero() +773 && best_any > old_relay_cur_latency / 3 * 2 +774 { +775 r.preferred_relay = prev_relay; +776 } +777 } +778 +779 let r = Arc::new(r); +780 self.reports.prev.insert(now, r.clone()); +781 self.reports.last = Some(r.clone()); +782 +783 r +784 } +785} +786 +787/// State the net_report actor needs for an in-progress report generation. +788#[derive(Debug)] +789struct ReportRun { +790 /// The handle of the [`reportgen`] actor, cancels the actor on drop. +791 _reportgen: reportgen::Client, +792 /// Where to send the completed report. +793 report_tx: oneshot::Sender<Result<Arc<Report>, ReportError>>, +794} +795 +796#[allow(missing_docs)] +797#[common_fields({ +798 backtrace: Option<snafu::Backtrace>, +799 #[snafu(implicit)] +800 span_trace: n0_snafu::SpanTrace, +801})] +802#[derive(Debug, Snafu)] +803#[non_exhaustive] +804pub enum ReportError { +805 #[snafu(display("Report aborted early"))] +806 Abort { reason: ActorRunError }, +807 #[snafu(display("Report generation is already running"))] +808 AlreadyRunning {}, +809 #[snafu(display("Internal actor is gone"))] +810 ActorGone {}, +811} +812 +813/// Test if IPv6 works at all, or if it's been hard disabled at the OS level. +814#[cfg(not(wasm_browser))] +815fn os_has_ipv6() -> bool { +816 UdpSocket::bind_local_v6(0).is_ok() +817} +818 +819/// Always returns false in browsers +820#[cfg(wasm_browser)] +821fn os_has_ipv6() -> bool { +822 false +823} +824 +825#[cfg(not(wasm_browser))] +826pub(crate) mod stun_utils { +827 use netwatch::IpFamily; +828 use tokio_util::sync::CancellationToken; 829 -830 /// Attempts to bind a local socket to send STUN packets from. -831 /// -832 /// If successful this returns the bound socket and will forward STUN responses to the -833 /// provided *actor_addr*. The *cancel_token* serves to stop the packet forwarding when the -834 /// socket is no longer needed. -835 pub fn bind_local_stun_socket( -836 network: IpFamily, -837 actor_addr: Addr, -838 cancel_token: CancellationToken, -839 ) -> Option<Arc<UdpSocket>> { -840 let sock = match UdpSocket::bind(network, 0) { -841 Ok(sock) => Arc::new(sock), -842 Err(err) => { -843 debug!("failed to bind STUN socket: {}", err); -844 return None; -845 } -846 }; -847 let span = info_span!( -848 "stun_udp_listener", -849 local_addr = sock -850 .local_addr() -851 .map(|a| a.to_string()) -852 .unwrap_or(String::from("-")), -853 ); -854 { -855 let sock = sock.clone(); -856 task::spawn( -857 async move { -858 debug!("udp stun socket listener started"); -859 // TODO: Can we do better for buffers here? Probably doesn't matter much. -860 let mut buf = vec![0u8; 64 << 10]; -861 loop { -862 tokio::select! { -863 biased; -864 _ = cancel_token.cancelled() => break, -865 res = recv_stun_once(&sock, &mut buf, &actor_addr) => { -866 if let Err(err) = res { -867 warn!(%err, "stun recv failed"); -868 break; -869 } -870 } -871 } -872 } -873 debug!("udp stun socket listener stopped"); -874 } -875 .instrument(span), -876 ); -877 } -878 Some(sock) -879 } -880 -881 #[derive(Debug, Snafu)] -882 enum RecvStunError { -883 #[snafu(transparent)] -884 Recv { source: std::io::Error }, -885 #[snafu(display("Internal actor is gone"))] -886 ActorGone, -887 } -888 -889 /// Receive STUN response from a UDP socket, pass it to the actor. -890 async fn recv_stun_once( -891 sock: &UdpSocket, -892 buf: &mut [u8], -893 actor_addr: &Addr, -894 ) -> Result<(), RecvStunError> { -895 let (count, mut from_addr) = sock.recv_from(buf).await?; -896 -897 let payload = &buf[..count]; -898 from_addr.set_ip(from_addr.ip().to_canonical()); -899 let msg = Message::StunPacket { -900 payload: Bytes::from(payload.to_vec()), -901 from_addr, -902 }; -903 actor_addr -904 .send(msg) -905 .await -906 .map_err(|_| ActorGoneSnafu.build()) -907 } -908} -909 -910#[cfg(test)] -911mod test_utils { -912 //! Creates a relay server against which to perform tests -913 -914 use iroh_relay::{server, RelayNode, RelayQuicConfig}; +830 use super::*; +831 +832 /// Attempts to bind a local socket to send STUN packets from. +833 /// +834 /// If successful this returns the bound socket and will forward STUN responses to the +835 /// provided *actor_addr*. The *cancel_token* serves to stop the packet forwarding when the +836 /// socket is no longer needed. +837 pub fn bind_local_stun_socket( +838 network: IpFamily, +839 actor_addr: Addr, +840 cancel_token: CancellationToken, +841 ) -> Option<Arc<UdpSocket>> { +842 let sock = match UdpSocket::bind(network, 0) { +843 Ok(sock) => Arc::new(sock), +844 Err(err) => { +845 debug!("failed to bind STUN socket: {}", err); +846 return None; +847 } +848 }; +849 let span = info_span!( +850 "stun_udp_listener", +851 local_addr = sock +852 .local_addr() +853 .map(|a| a.to_string()) +854 .unwrap_or(String::from("-")), +855 ); +856 { +857 let sock = sock.clone(); +858 task::spawn( +859 async move { +860 debug!("udp stun socket listener started"); +861 // TODO: Can we do better for buffers here? Probably doesn't matter much. +862 let mut buf = vec![0u8; 64 << 10]; +863 loop { +864 tokio::select! { +865 biased; +866 _ = cancel_token.cancelled() => break, +867 res = recv_stun_once(&sock, &mut buf, &actor_addr) => { +868 if let Err(err) = res { +869 warn!(%err, "stun recv failed"); +870 break; +871 } +872 } +873 } +874 } +875 debug!("udp stun socket listener stopped"); +876 } +877 .instrument(span), +878 ); +879 } +880 Some(sock) +881 } +882 +883 #[derive(Debug, Snafu)] +884 enum RecvStunError { +885 #[snafu(transparent)] +886 Recv { source: std::io::Error }, +887 #[snafu(display("Internal actor is gone"))] +888 ActorGone, +889 } +890 +891 /// Receive STUN response from a UDP socket, pass it to the actor. +892 async fn recv_stun_once( +893 sock: &UdpSocket, +894 buf: &mut [u8], +895 actor_addr: &Addr, +896 ) -> Result<(), RecvStunError> { +897 let (count, mut from_addr) = sock.recv_from(buf).await?; +898 +899 let payload = &buf[..count]; +900 from_addr.set_ip(from_addr.ip().to_canonical()); +901 let msg = Message::StunPacket { +902 payload: Bytes::from(payload.to_vec()), +903 from_addr, +904 }; +905 actor_addr +906 .send(msg) +907 .await +908 .map_err(|_| ActorGoneSnafu.build()) +909 } +910} +911 +912#[cfg(test)] +913mod test_utils { +914 //! Creates a relay server against which to perform tests 915 -916 pub(crate) async fn relay() -> (server::Server, RelayNode) { -917 let server = server::Server::spawn(server::testing::server_config()) -918 .await -919 .expect("should serve relay"); -920 let quic = Some(RelayQuicConfig { -921 port: server.quic_addr().expect("server should run quic").port(), -922 }); -923 let node_desc = RelayNode { -924 url: server.https_url().expect("should work as relay"), -925 stun_only: false, // the checks above and below guarantee both stun and relay -926 stun_port: server.stun_addr().expect("server should serve stun").port(), -927 quic, -928 }; -929 -930 (server, node_desc) -931 } -932 -933 /// Create a [`crate::RelayMap`] of the given size. -934 /// -935 /// This function uses [`relay`]. Note that the returned map uses internal order that will -936 /// often _not_ match the order of the servers. -937 pub(crate) async fn relay_map(relays: usize) -> (Vec<server::Server>, crate::RelayMap) { -938 let mut servers = Vec::with_capacity(relays); -939 let mut nodes = Vec::with_capacity(relays); -940 for _ in 0..relays { -941 let (relay_server, node) = relay().await; -942 servers.push(relay_server); -943 nodes.push(node); -944 } -945 (servers, crate::RelayMap::from_iter(nodes)) -946 } -947} -948 -949#[cfg(test)] -950mod tests { -951 use bytes::BytesMut; -952 use n0_snafu::{Result, ResultExt}; -953 use netwatch::IpFamily; -954 use tokio_util::sync::CancellationToken; -955 use tracing::info; -956 use tracing_test::traced_test; -957 -958 use super::*; -959 use crate::net_report::{dns, stun_utils::bind_local_stun_socket}; -960 -961 mod stun_utils { -962 //! Utils for testing that expose a simple stun server. -963 -964 use std::{net::IpAddr, sync::Arc}; +916 use iroh_relay::{server, RelayNode, RelayQuicConfig}; +917 +918 pub(crate) async fn relay() -> (server::Server, RelayNode) { +919 let server = server::Server::spawn(server::testing::server_config()) +920 .await +921 .expect("should serve relay"); +922 let quic = Some(RelayQuicConfig { +923 port: server.quic_addr().expect("server should run quic").port(), +924 }); +925 let node_desc = RelayNode { +926 url: server.https_url().expect("should work as relay"), +927 stun_only: false, // the checks above and below guarantee both stun and relay +928 stun_port: server.stun_addr().expect("server should serve stun").port(), +929 quic, +930 }; +931 +932 (server, node_desc) +933 } +934 +935 /// Create a [`crate::RelayMap`] of the given size. +936 /// +937 /// This function uses [`relay`]. Note that the returned map uses internal order that will +938 /// often _not_ match the order of the servers. +939 pub(crate) async fn relay_map(relays: usize) -> (Vec<server::Server>, crate::RelayMap) { +940 let mut servers = Vec::with_capacity(relays); +941 let mut nodes = Vec::with_capacity(relays); +942 for _ in 0..relays { +943 let (relay_server, node) = relay().await; +944 servers.push(relay_server); +945 nodes.push(node); +946 } +947 (servers, crate::RelayMap::from_iter(nodes)) +948 } +949} +950 +951#[cfg(test)] +952mod tests { +953 use bytes::BytesMut; +954 use n0_snafu::{Result, ResultExt}; +955 use netwatch::IpFamily; +956 use tokio_util::sync::CancellationToken; +957 use tracing::info; +958 use tracing_test::traced_test; +959 +960 use super::*; +961 use crate::net_report::{dns, stun_utils::bind_local_stun_socket}; +962 +963 mod stun_utils { +964 //! Utils for testing that expose a simple stun server. 965 -966 use iroh_base::RelayUrl; -967 use iroh_relay::RelayNode; -968 use tokio::{ -969 net, -970 sync::{oneshot, Mutex}, -971 }; -972 use tracing::{debug, trace}; -973 -974 use super::*; +966 use std::{net::IpAddr, sync::Arc}; +967 +968 use iroh_base::RelayUrl; +969 use iroh_relay::RelayNode; +970 use tokio::{ +971 net, +972 sync::{oneshot, Mutex}, +973 }; +974 use tracing::{debug, trace}; 975 -976 /// A drop guard to clean up test infrastructure. -977 /// -978 /// After dropping the test infrastructure will asynchronously shutdown and release its -979 /// resources. -980 // Nightly sees the sender as dead code currently, but we only rely on Drop of the -981 // sender. -982 #[derive(Debug)] -983 pub struct CleanupDropGuard { -984 _guard: oneshot::Sender<()>, -985 } -986 -987 // (read_ipv4, read_ipv6) -988 #[derive(Debug, Default, Clone)] -989 pub struct StunStats(Arc<Mutex<(usize, usize)>>); -990 -991 impl StunStats { -992 pub async fn total(&self) -> usize { -993 let s = self.0.lock().await; -994 s.0 + s.1 -995 } -996 } -997 -998 pub fn relay_map_of(stun: impl Iterator<Item = SocketAddr>) -> RelayMap { -999 relay_map_of_opts(stun.map(|addr| (addr, true))) -1000 } -1001 -1002 pub fn relay_map_of_opts(stun: impl Iterator<Item = (SocketAddr, bool)>) -> RelayMap { -1003 let nodes = stun.map(|(addr, stun_only)| { -1004 let host = addr.ip(); -1005 let port = addr.port(); -1006 -1007 let url: RelayUrl = format!("http://{host}:{port}").parse().unwrap(); -1008 RelayNode { -1009 url, -1010 stun_port: port, -1011 stun_only, -1012 quic: None, -1013 } -1014 }); -1015 RelayMap::from_iter(nodes) -1016 } -1017 -1018 /// Sets up a simple STUN server binding to `0.0.0.0:0`. -1019 /// -1020 /// See [`serve`] for more details. -1021 pub(crate) async fn serve_v4() -> std::io::Result<(SocketAddr, StunStats, CleanupDropGuard)> -1022 { -1023 serve(std::net::Ipv4Addr::UNSPECIFIED.into()).await -1024 } -1025 -1026 /// Sets up a simple STUN server. -1027 pub(crate) async fn serve( -1028 ip: IpAddr, -1029 ) -> std::io::Result<(SocketAddr, StunStats, CleanupDropGuard)> { -1030 let stats = StunStats::default(); -1031 -1032 let pc = net::UdpSocket::bind((ip, 0)).await?; -1033 let mut addr = pc.local_addr()?; -1034 match addr.ip() { -1035 IpAddr::V4(ip) => { -1036 if ip.octets() == [0, 0, 0, 0] { -1037 addr.set_ip("127.0.0.1".parse().unwrap()); -1038 } -1039 } -1040 _ => unreachable!("using ipv4"), -1041 } -1042 -1043 println!("STUN listening on {}", addr); -1044 let (_guard, r) = oneshot::channel(); -1045 let stats_c = stats.clone(); -1046 tokio::task::spawn(async move { -1047 run_stun(pc, stats_c, r).await; -1048 }); -1049 -1050 Ok((addr, stats, CleanupDropGuard { _guard })) -1051 } -1052 -1053 async fn run_stun(pc: net::UdpSocket, stats: StunStats, mut done: oneshot::Receiver<()>) { -1054 let mut buf = vec![0u8; 64 << 10]; -1055 loop { -1056 trace!("read loop"); -1057 tokio::select! { -1058 _ = &mut done => { -1059 debug!("shutting down"); -1060 break; -1061 } -1062 res = pc.recv_from(&mut buf) => match res { -1063 Ok((n, addr)) => { -1064 trace!("read packet {}bytes from {}", n, addr); -1065 let pkt = &buf[..n]; -1066 if !stun::is(pkt) { -1067 debug!("received non STUN pkt"); -1068 continue; -1069 } -1070 if let Ok(txid) = stun::parse_binding_request(pkt) { -1071 debug!("received binding request"); -1072 let mut s = stats.0.lock().await; -1073 if addr.is_ipv4() { -1074 s.0 += 1; -1075 } else { -1076 s.1 += 1; -1077 } -1078 drop(s); -1079 -1080 let res = stun::response(txid, addr); -1081 if let Err(err) = pc.send_to(&res, addr).await { -1082 eprintln!("STUN server write failed: {:?}", err); -1083 } -1084 } -1085 } -1086 Err(err) => { -1087 eprintln!("failed to read: {:?}", err); -1088 } -1089 } -1090 } -1091 } -1092 } -1093 } -1094 -1095 #[tokio::test] -1096 #[traced_test] -1097 async fn test_basic() -> Result { -1098 let (stun_addr, stun_stats, _cleanup_guard) = -1099 stun_utils::serve("127.0.0.1".parse().unwrap()).await.e()?; -1100 -1101 let resolver = dns::tests::resolver(); -1102 let mut client = Client::new(None, resolver.clone(), None, Default::default()); -1103 let dm = stun_utils::relay_map_of([stun_addr].into_iter()); -1104 -1105 // Note that the ProbePlan will change with each iteration. -1106 for i in 0..5 { -1107 let cancel = CancellationToken::new(); -1108 let sock = bind_local_stun_socket(IpFamily::V4, client.addr(), cancel.clone()); -1109 println!("--round {}", i); -1110 let r = client.get_report_all(dm.clone(), sock, None, None).await?; -1111 -1112 assert!(r.udp, "want UDP"); -1113 assert_eq!( -1114 r.relay_latency.len(), -1115 1, -1116 "expected 1 key in RelayLatency; got {}", -1117 r.relay_latency.len() -1118 ); -1119 assert!( -1120 r.relay_latency.iter().next().is_some(), -1121 "expected key 1 in RelayLatency; got {:?}", -1122 r.relay_latency -1123 ); -1124 assert!(r.global_v4.is_some(), "expected globalV4 set"); -1125 assert!(r.preferred_relay.is_some(),); -1126 cancel.cancel(); -1127 } -1128 -1129 assert!( -1130 stun_stats.total().await >= 5, -1131 "expected at least 5 stun, got {}", -1132 stun_stats.total().await, -1133 ); -1134 -1135 Ok(()) -1136 } -1137 -1138 #[tokio::test(flavor = "current_thread", start_paused = true)] -1139 async fn test_add_report_history_set_preferred_relay() -> Result { -1140 fn relay_url(i: u16) -> RelayUrl { -1141 format!("http://{i}.com").parse().unwrap() -1142 } -1143 -1144 // report returns a *Report from (relay host, Duration)+ pairs. -1145 fn report(a: impl IntoIterator<Item = (&'static str, u64)>) -> Option<Arc<Report>> { -1146 let mut report = Report::default(); -1147 for (s, d) in a { -1148 assert!(s.starts_with('d'), "invalid relay server key"); -1149 let id: u16 = s[1..].parse().unwrap(); -1150 report -1151 .relay_latency -1152 .0 -1153 .insert(relay_url(id), Duration::from_secs(d)); -1154 } -1155 -1156 Some(Arc::new(report)) -1157 } -1158 struct Step { -1159 /// Delay in seconds -1160 after: u64, -1161 r: Option<Arc<Report>>, -1162 } -1163 struct Test { -1164 name: &'static str, -1165 steps: Vec<Step>, -1166 /// want PreferredRelay on final step -1167 want_relay: Option<RelayUrl>, -1168 // wanted len(c.prev) -1169 want_prev_len: usize, -1170 } -1171 -1172 let tests = [ -1173 Test { -1174 name: "first_reading", -1175 steps: vec![Step { -1176 after: 0, -1177 r: report([("d1", 2), ("d2", 3)]), -1178 }], -1179 want_prev_len: 1, -1180 want_relay: Some(relay_url(1)), -1181 }, -1182 Test { -1183 name: "with_two", -1184 steps: vec![ -1185 Step { -1186 after: 0, -1187 r: report([("d1", 2), ("d2", 3)]), -1188 }, -1189 Step { -1190 after: 1, -1191 r: report([("d1", 4), ("d2", 3)]), -1192 }, -1193 ], -1194 want_prev_len: 2, -1195 want_relay: Some(relay_url(1)), // t0's d1 of 2 is still best -1196 }, -1197 Test { -1198 name: "but_now_d1_gone", -1199 steps: vec![ -1200 Step { -1201 after: 0, -1202 r: report([("d1", 2), ("d2", 3)]), -1203 }, -1204 Step { -1205 after: 1, -1206 r: report([("d1", 4), ("d2", 3)]), -1207 }, -1208 Step { -1209 after: 2, -1210 r: report([("d2", 3)]), -1211 }, -1212 ], -1213 want_prev_len: 3, -1214 want_relay: Some(relay_url(2)), // only option -1215 }, -1216 Test { -1217 name: "d1_is_back", -1218 steps: vec![ -1219 Step { -1220 after: 0, -1221 r: report([("d1", 2), ("d2", 3)]), -1222 }, -1223 Step { -1224 after: 1, -1225 r: report([("d1", 4), ("d2", 3)]), -1226 }, -1227 Step { -1228 after: 2, -1229 r: report([("d2", 3)]), -1230 }, -1231 Step { -1232 after: 3, -1233 r: report([("d1", 4), ("d2", 3)]), -1234 }, // same as 2 seconds ago -1235 ], -1236 want_prev_len: 4, -1237 want_relay: Some(relay_url(1)), // t0's d1 of 2 is still best -1238 }, -1239 Test { -1240 name: "things_clean_up", -1241 steps: vec![ -1242 Step { -1243 after: 0, -1244 r: report([("d1", 1), ("d2", 2)]), -1245 }, -1246 Step { -1247 after: 1, -1248 r: report([("d1", 1), ("d2", 2)]), -1249 }, -1250 Step { -1251 after: 2, -1252 r: report([("d1", 1), ("d2", 2)]), -1253 }, -1254 Step { -1255 after: 3, -1256 r: report([("d1", 1), ("d2", 2)]), -1257 }, -1258 Step { -1259 after: 10 * 60, -1260 r: report([("d3", 3)]), -1261 }, -1262 ], -1263 want_prev_len: 1, // t=[0123]s all gone. (too old, older than 10 min) -1264 want_relay: Some(relay_url(3)), // only option -1265 }, -1266 Test { -1267 name: "preferred_relay_hysteresis_no_switch", -1268 steps: vec![ -1269 Step { -1270 after: 0, -1271 r: report([("d1", 4), ("d2", 5)]), -1272 }, -1273 Step { -1274 after: 1, -1275 r: report([("d1", 4), ("d2", 3)]), -1276 }, -1277 ], -1278 want_prev_len: 2, -1279 want_relay: Some(relay_url(1)), // 2 didn't get fast enough -1280 }, -1281 Test { -1282 name: "preferred_relay_hysteresis_do_switch", -1283 steps: vec![ -1284 Step { -1285 after: 0, -1286 r: report([("d1", 4), ("d2", 5)]), -1287 }, -1288 Step { -1289 after: 1, -1290 r: report([("d1", 4), ("d2", 1)]), -1291 }, -1292 ], -1293 want_prev_len: 2, -1294 want_relay: Some(relay_url(2)), // 2 got fast enough -1295 }, -1296 ]; -1297 let resolver = dns::tests::resolver(); -1298 for mut tt in tests { -1299 println!("test: {}", tt.name); -1300 let mut actor = Actor::new(None, resolver.clone(), None, Default::default()); -1301 for s in &mut tt.steps { -1302 // trigger the timer -1303 tokio::time::advance(Duration::from_secs(s.after)).await; -1304 let r = Arc::try_unwrap(s.r.take().unwrap()).unwrap(); -1305 s.r = Some(actor.add_report_history_and_set_preferred_relay(r)); -1306 } -1307 let last_report = tt.steps.last().unwrap().r.clone().unwrap(); -1308 let got = actor.reports.prev.len(); -1309 let want = tt.want_prev_len; -1310 assert_eq!(got, want, "prev length"); -1311 let got = &last_report.preferred_relay; -1312 let want = &tt.want_relay; -1313 assert_eq!(got, want, "preferred_relay"); -1314 } -1315 -1316 Ok(()) -1317 } -1318 -1319 #[tokio::test] -1320 async fn test_hairpin() -> Result { -1321 // Hairpinning is initiated after we discover our own IPv4 socket address (IP + -1322 // port) via STUN, so the test needs to have a STUN server and perform STUN over -1323 // IPv4 first. Hairpinning detection works by sending a STUN *request* to **our own -1324 // public socket address** (IP + port). If the router supports hairpinning the STUN -1325 // request is returned back to us and received on our public address. This doesn't -1326 // need to be a STUN request, but STUN already has a unique transaction ID which we -1327 // can easily use to identify the packet. -1328 -1329 // Setup STUN server and create relay_map. -1330 let (stun_addr, _stun_stats, _done) = stun_utils::serve_v4().await.e()?; -1331 let dm = stun_utils::relay_map_of([stun_addr].into_iter()); -1332 dbg!(&dm); -1333 -1334 let resolver = dns::tests::resolver().clone(); -1335 let mut client = Client::new(None, resolver, None, Default::default()); -1336 -1337 // Set up an external socket to send STUN requests from, this will be discovered as -1338 // our public socket address by STUN. We send back any packets received on this -1339 // socket to the net_report client using Client::receive_stun_packet. Once we sent -1340 // the hairpin STUN request (from a different randomly bound socket) we are sending -1341 // it to this socket, which is forwarnding it back to our net_report client, because -1342 // this dumb implementation just forwards anything even if it would be garbage. -1343 // Thus hairpinning detection will declare hairpinning to work. -1344 let sock = UdpSocket::bind_local(netwatch::IpFamily::V4, 0).e()?; -1345 let sock = Arc::new(sock); -1346 info!(addr=?sock.local_addr().unwrap(), "Using local addr"); -1347 let task = { -1348 let sock = sock.clone(); -1349 let addr = client.addr.clone(); -1350 tokio::spawn( -1351 async move { -1352 let mut buf = BytesMut::zeroed(64 << 10); -1353 loop { -1354 let (count, src) = sock.recv_from(&mut buf).await.unwrap(); -1355 info!( -1356 addr=?sock.local_addr().unwrap(), -1357 %count, -1358 "Forwarding payload to net_report client", -1359 ); -1360 let payload = buf.split_to(count).freeze(); -1361 addr.receive_stun_packet(payload, src); -1362 } -1363 } -1364 .instrument(info_span!("pkt-fwd")), -1365 ) -1366 }; -1367 -1368 let r = client.get_report_all(dm, Some(sock), None, None).await?; -1369 dbg!(&r); -1370 assert_eq!(r.hair_pinning, Some(true)); -1371 -1372 task.abort(); -1373 Ok(()) -1374 } -1375} \ No newline at end of file +976 use super::*; +977 +978 /// A drop guard to clean up test infrastructure. +979 /// +980 /// After dropping the test infrastructure will asynchronously shutdown and release its +981 /// resources. +982 // Nightly sees the sender as dead code currently, but we only rely on Drop of the +983 // sender. +984 #[derive(Debug)] +985 pub struct CleanupDropGuard { +986 _guard: oneshot::Sender<()>, +987 } +988 +989 // (read_ipv4, read_ipv6) +990 #[derive(Debug, Default, Clone)] +991 pub struct StunStats(Arc<Mutex<(usize, usize)>>); +992 +993 impl StunStats { +994 pub async fn total(&self) -> usize { +995 let s = self.0.lock().await; +996 s.0 + s.1 +997 } +998 } +999 +1000 pub fn relay_map_of(stun: impl Iterator<Item = SocketAddr>) -> RelayMap { +1001 relay_map_of_opts(stun.map(|addr| (addr, true))) +1002 } +1003 +1004 pub fn relay_map_of_opts(stun: impl Iterator<Item = (SocketAddr, bool)>) -> RelayMap { +1005 let nodes = stun.map(|(addr, stun_only)| { +1006 let host = addr.ip(); +1007 let port = addr.port(); +1008 +1009 let url: RelayUrl = format!("http://{host}:{port}").parse().unwrap(); +1010 RelayNode { +1011 url, +1012 stun_port: port, +1013 stun_only, +1014 quic: None, +1015 } +1016 }); +1017 RelayMap::from_iter(nodes) +1018 } +1019 +1020 /// Sets up a simple STUN server binding to `0.0.0.0:0`. +1021 /// +1022 /// See [`serve`] for more details. +1023 pub(crate) async fn serve_v4() -> std::io::Result<(SocketAddr, StunStats, CleanupDropGuard)> +1024 { +1025 serve(std::net::Ipv4Addr::UNSPECIFIED.into()).await +1026 } +1027 +1028 /// Sets up a simple STUN server. +1029 pub(crate) async fn serve( +1030 ip: IpAddr, +1031 ) -> std::io::Result<(SocketAddr, StunStats, CleanupDropGuard)> { +1032 let stats = StunStats::default(); +1033 +1034 let pc = net::UdpSocket::bind((ip, 0)).await?; +1035 let mut addr = pc.local_addr()?; +1036 match addr.ip() { +1037 IpAddr::V4(ip) => { +1038 if ip.octets() == [0, 0, 0, 0] { +1039 addr.set_ip("127.0.0.1".parse().unwrap()); +1040 } +1041 } +1042 _ => unreachable!("using ipv4"), +1043 } +1044 +1045 println!("STUN listening on {}", addr); +1046 let (_guard, r) = oneshot::channel(); +1047 let stats_c = stats.clone(); +1048 tokio::task::spawn(async move { +1049 run_stun(pc, stats_c, r).await; +1050 }); +1051 +1052 Ok((addr, stats, CleanupDropGuard { _guard })) +1053 } +1054 +1055 async fn run_stun(pc: net::UdpSocket, stats: StunStats, mut done: oneshot::Receiver<()>) { +1056 let mut buf = vec![0u8; 64 << 10]; +1057 loop { +1058 trace!("read loop"); +1059 tokio::select! { +1060 _ = &mut done => { +1061 debug!("shutting down"); +1062 break; +1063 } +1064 res = pc.recv_from(&mut buf) => match res { +1065 Ok((n, addr)) => { +1066 trace!("read packet {}bytes from {}", n, addr); +1067 let pkt = &buf[..n]; +1068 if !stun::is(pkt) { +1069 debug!("received non STUN pkt"); +1070 continue; +1071 } +1072 if let Ok(txid) = stun::parse_binding_request(pkt) { +1073 debug!("received binding request"); +1074 let mut s = stats.0.lock().await; +1075 if addr.is_ipv4() { +1076 s.0 += 1; +1077 } else { +1078 s.1 += 1; +1079 } +1080 drop(s); +1081 +1082 let res = stun::response(txid, addr); +1083 if let Err(err) = pc.send_to(&res, addr).await { +1084 eprintln!("STUN server write failed: {:?}", err); +1085 } +1086 } +1087 } +1088 Err(err) => { +1089 eprintln!("failed to read: {:?}", err); +1090 } +1091 } +1092 } +1093 } +1094 } +1095 } +1096 +1097 #[tokio::test] +1098 #[traced_test] +1099 async fn test_basic() -> Result { +1100 let (stun_addr, stun_stats, _cleanup_guard) = +1101 stun_utils::serve("127.0.0.1".parse().unwrap()).await.e()?; +1102 +1103 let resolver = dns::tests::resolver(); +1104 let mut client = Client::new(None, resolver.clone(), None, Default::default()); +1105 let dm = stun_utils::relay_map_of([stun_addr].into_iter()); +1106 +1107 // Note that the ProbePlan will change with each iteration. +1108 for i in 0..5 { +1109 let cancel = CancellationToken::new(); +1110 let sock = bind_local_stun_socket(IpFamily::V4, client.addr(), cancel.clone()); +1111 println!("--round {}", i); +1112 let r = client.get_report_all(dm.clone(), sock, None, None).await?; +1113 +1114 assert!(r.udp, "want UDP"); +1115 assert_eq!( +1116 r.relay_latency.len(), +1117 1, +1118 "expected 1 key in RelayLatency; got {}", +1119 r.relay_latency.len() +1120 ); +1121 assert!( +1122 r.relay_latency.iter().next().is_some(), +1123 "expected key 1 in RelayLatency; got {:?}", +1124 r.relay_latency +1125 ); +1126 assert!(r.global_v4.is_some(), "expected globalV4 set"); +1127 assert!(r.preferred_relay.is_some(),); +1128 cancel.cancel(); +1129 } +1130 +1131 assert!( +1132 stun_stats.total().await >= 5, +1133 "expected at least 5 stun, got {}", +1134 stun_stats.total().await, +1135 ); +1136 +1137 Ok(()) +1138 } +1139 +1140 #[tokio::test(flavor = "current_thread", start_paused = true)] +1141 async fn test_add_report_history_set_preferred_relay() -> Result { +1142 fn relay_url(i: u16) -> RelayUrl { +1143 format!("http://{i}.com").parse().unwrap() +1144 } +1145 +1146 // report returns a *Report from (relay host, Duration)+ pairs. +1147 fn report(a: impl IntoIterator<Item = (&'static str, u64)>) -> Option<Arc<Report>> { +1148 let mut report = Report::default(); +1149 for (s, d) in a { +1150 assert!(s.starts_with('d'), "invalid relay server key"); +1151 let id: u16 = s[1..].parse().unwrap(); +1152 report +1153 .relay_latency +1154 .0 +1155 .insert(relay_url(id), Duration::from_secs(d)); +1156 } +1157 +1158 Some(Arc::new(report)) +1159 } +1160 struct Step { +1161 /// Delay in seconds +1162 after: u64, +1163 r: Option<Arc<Report>>, +1164 } +1165 struct Test { +1166 name: &'static str, +1167 steps: Vec<Step>, +1168 /// want PreferredRelay on final step +1169 want_relay: Option<RelayUrl>, +1170 // wanted len(c.prev) +1171 want_prev_len: usize, +1172 } +1173 +1174 let tests = [ +1175 Test { +1176 name: "first_reading", +1177 steps: vec![Step { +1178 after: 0, +1179 r: report([("d1", 2), ("d2", 3)]), +1180 }], +1181 want_prev_len: 1, +1182 want_relay: Some(relay_url(1)), +1183 }, +1184 Test { +1185 name: "with_two", +1186 steps: vec![ +1187 Step { +1188 after: 0, +1189 r: report([("d1", 2), ("d2", 3)]), +1190 }, +1191 Step { +1192 after: 1, +1193 r: report([("d1", 4), ("d2", 3)]), +1194 }, +1195 ], +1196 want_prev_len: 2, +1197 want_relay: Some(relay_url(1)), // t0's d1 of 2 is still best +1198 }, +1199 Test { +1200 name: "but_now_d1_gone", +1201 steps: vec![ +1202 Step { +1203 after: 0, +1204 r: report([("d1", 2), ("d2", 3)]), +1205 }, +1206 Step { +1207 after: 1, +1208 r: report([("d1", 4), ("d2", 3)]), +1209 }, +1210 Step { +1211 after: 2, +1212 r: report([("d2", 3)]), +1213 }, +1214 ], +1215 want_prev_len: 3, +1216 want_relay: Some(relay_url(2)), // only option +1217 }, +1218 Test { +1219 name: "d1_is_back", +1220 steps: vec![ +1221 Step { +1222 after: 0, +1223 r: report([("d1", 2), ("d2", 3)]), +1224 }, +1225 Step { +1226 after: 1, +1227 r: report([("d1", 4), ("d2", 3)]), +1228 }, +1229 Step { +1230 after: 2, +1231 r: report([("d2", 3)]), +1232 }, +1233 Step { +1234 after: 3, +1235 r: report([("d1", 4), ("d2", 3)]), +1236 }, // same as 2 seconds ago +1237 ], +1238 want_prev_len: 4, +1239 want_relay: Some(relay_url(1)), // t0's d1 of 2 is still best +1240 }, +1241 Test { +1242 name: "things_clean_up", +1243 steps: vec![ +1244 Step { +1245 after: 0, +1246 r: report([("d1", 1), ("d2", 2)]), +1247 }, +1248 Step { +1249 after: 1, +1250 r: report([("d1", 1), ("d2", 2)]), +1251 }, +1252 Step { +1253 after: 2, +1254 r: report([("d1", 1), ("d2", 2)]), +1255 }, +1256 Step { +1257 after: 3, +1258 r: report([("d1", 1), ("d2", 2)]), +1259 }, +1260 Step { +1261 after: 10 * 60, +1262 r: report([("d3", 3)]), +1263 }, +1264 ], +1265 want_prev_len: 1, // t=[0123]s all gone. (too old, older than 10 min) +1266 want_relay: Some(relay_url(3)), // only option +1267 }, +1268 Test { +1269 name: "preferred_relay_hysteresis_no_switch", +1270 steps: vec![ +1271 Step { +1272 after: 0, +1273 r: report([("d1", 4), ("d2", 5)]), +1274 }, +1275 Step { +1276 after: 1, +1277 r: report([("d1", 4), ("d2", 3)]), +1278 }, +1279 ], +1280 want_prev_len: 2, +1281 want_relay: Some(relay_url(1)), // 2 didn't get fast enough +1282 }, +1283 Test { +1284 name: "preferred_relay_hysteresis_do_switch", +1285 steps: vec![ +1286 Step { +1287 after: 0, +1288 r: report([("d1", 4), ("d2", 5)]), +1289 }, +1290 Step { +1291 after: 1, +1292 r: report([("d1", 4), ("d2", 1)]), +1293 }, +1294 ], +1295 want_prev_len: 2, +1296 want_relay: Some(relay_url(2)), // 2 got fast enough +1297 }, +1298 ]; +1299 let resolver = dns::tests::resolver(); +1300 for mut tt in tests { +1301 println!("test: {}", tt.name); +1302 let mut actor = Actor::new(None, resolver.clone(), None, Default::default()); +1303 for s in &mut tt.steps { +1304 // trigger the timer +1305 tokio::time::advance(Duration::from_secs(s.after)).await; +1306 let r = Arc::try_unwrap(s.r.take().unwrap()).unwrap(); +1307 s.r = Some(actor.add_report_history_and_set_preferred_relay(r)); +1308 } +1309 let last_report = tt.steps.last().unwrap().r.clone().unwrap(); +1310 let got = actor.reports.prev.len(); +1311 let want = tt.want_prev_len; +1312 assert_eq!(got, want, "prev length"); +1313 let got = &last_report.preferred_relay; +1314 let want = &tt.want_relay; +1315 assert_eq!(got, want, "preferred_relay"); +1316 } +1317 +1318 Ok(()) +1319 } +1320 +1321 #[tokio::test] +1322 async fn test_hairpin() -> Result { +1323 // Hairpinning is initiated after we discover our own IPv4 socket address (IP + +1324 // port) via STUN, so the test needs to have a STUN server and perform STUN over +1325 // IPv4 first. Hairpinning detection works by sending a STUN *request* to **our own +1326 // public socket address** (IP + port). If the router supports hairpinning the STUN +1327 // request is returned back to us and received on our public address. This doesn't +1328 // need to be a STUN request, but STUN already has a unique transaction ID which we +1329 // can easily use to identify the packet. +1330 +1331 // Setup STUN server and create relay_map. +1332 let (stun_addr, _stun_stats, _done) = stun_utils::serve_v4().await.e()?; +1333 let dm = stun_utils::relay_map_of([stun_addr].into_iter()); +1334 dbg!(&dm); +1335 +1336 let resolver = dns::tests::resolver().clone(); +1337 let mut client = Client::new(None, resolver, None, Default::default()); +1338 +1339 // Set up an external socket to send STUN requests from, this will be discovered as +1340 // our public socket address by STUN. We send back any packets received on this +1341 // socket to the net_report client using Client::receive_stun_packet. Once we sent +1342 // the hairpin STUN request (from a different randomly bound socket) we are sending +1343 // it to this socket, which is forwarnding it back to our net_report client, because +1344 // this dumb implementation just forwards anything even if it would be garbage. +1345 // Thus hairpinning detection will declare hairpinning to work. +1346 let sock = UdpSocket::bind_local(netwatch::IpFamily::V4, 0).e()?; +1347 let sock = Arc::new(sock); +1348 info!(addr=?sock.local_addr().unwrap(), "Using local addr"); +1349 let task = { +1350 let sock = sock.clone(); +1351 let addr = client.addr.clone(); +1352 tokio::spawn( +1353 async move { +1354 let mut buf = BytesMut::zeroed(64 << 10); +1355 loop { +1356 let (count, src) = sock.recv_from(&mut buf).await.unwrap(); +1357 info!( +1358 addr=?sock.local_addr().unwrap(), +1359 %count, +1360 "Forwarding payload to net_report client", +1361 ); +1362 let payload = buf.split_to(count).freeze(); +1363 addr.receive_stun_packet(payload, src); +1364 } +1365 } +1366 .instrument(info_span!("pkt-fwd")), +1367 ) +1368 }; +1369 +1370 let r = client.get_report_all(dm, Some(sock), None, None).await?; +1371 dbg!(&r); +1372 assert_eq!(r.hair_pinning, Some(true)); +1373 +1374 task.abort(); +1375 Ok(()) +1376 } +1377} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/net_report/options.rs.html b/pr/3327/docs/src/iroh/net_report/options.rs.html index 1272d96702..5d7e5cba04 100644 --- a/pr/3327/docs/src/iroh/net_report/options.rs.html +++ b/pr/3327/docs/src/iroh/net_report/options.rs.html @@ -50,144 +50,158 @@ 50 /// 51 /// On by default 52 pub(crate) https: bool, -53 } -54 -55 impl Default for Options { -56 fn default() -> Self { -57 Self { -58 stun_sock_v4: None, -59 stun_sock_v6: None, -60 quic_config: None, -61 icmp_v4: true, -62 icmp_v6: true, -63 https: true, -64 } -65 } -66 } -67 -68 impl Options { -69 /// Create an [`Options`] that disables all probes -70 pub fn disabled() -> Self { -71 Self { -72 stun_sock_v4: None, -73 stun_sock_v6: None, -74 quic_config: None, -75 icmp_v4: false, -76 icmp_v6: false, -77 https: false, -78 } -79 } -80 -81 /// Set the ipv4 stun socket and enable ipv4 stun probes -82 pub fn stun_v4(mut self, sock: Option<Arc<UdpSocket>>) -> Self { -83 self.stun_sock_v4 = sock; -84 self -85 } -86 -87 /// Set the ipv6 stun socket and enable ipv6 stun probes -88 pub fn stun_v6(mut self, sock: Option<Arc<UdpSocket>>) -> Self { -89 self.stun_sock_v6 = sock; -90 self -91 } -92 -93 /// Enable quic probes -94 pub fn quic_config(mut self, quic_config: Option<QuicConfig>) -> Self { -95 self.quic_config = quic_config; -96 self -97 } -98 -99 /// Enable or disable icmp_v4 probe -100 pub fn icmp_v4(mut self, enable: bool) -> Self { -101 self.icmp_v4 = enable; -102 self -103 } -104 -105 /// Enable or disable icmp_v6 probe -106 pub fn icmp_v6(mut self, enable: bool) -> Self { -107 self.icmp_v6 = enable; -108 self -109 } -110 -111 /// Enable or disable https probe -112 pub fn https(mut self, enable: bool) -> Self { -113 self.https = enable; -114 self -115 } -116 -117 /// Turn the options into set of valid protocols -118 pub(crate) fn to_protocols(&self) -> BTreeSet<ProbeProto> { -119 let mut protocols = BTreeSet::new(); -120 if self.stun_sock_v4.is_some() { -121 protocols.insert(ProbeProto::StunIpv4); -122 } -123 if self.stun_sock_v6.is_some() { -124 protocols.insert(ProbeProto::StunIpv6); -125 } -126 if let Some(ref quic) = self.quic_config { -127 if quic.ipv4 { -128 protocols.insert(ProbeProto::QuicIpv4); -129 } -130 if quic.ipv6 { -131 protocols.insert(ProbeProto::QuicIpv6); -132 } -133 } -134 if self.icmp_v4 { -135 protocols.insert(ProbeProto::IcmpV4); +53 +54 #[cfg(any(test, feature = "test-utils"))] +55 pub(crate) insecure_skip_relay_cert_verify: bool, +56 } +57 +58 impl Default for Options { +59 fn default() -> Self { +60 Self { +61 stun_sock_v4: None, +62 stun_sock_v6: None, +63 quic_config: None, +64 icmp_v4: true, +65 icmp_v6: true, +66 https: true, +67 #[cfg(any(test, feature = "test-utils"))] +68 insecure_skip_relay_cert_verify: false, +69 } +70 } +71 } +72 +73 impl Options { +74 /// Create an [`Options`] that disables all probes +75 pub fn disabled() -> Self { +76 Self { +77 stun_sock_v4: None, +78 stun_sock_v6: None, +79 quic_config: None, +80 icmp_v4: false, +81 icmp_v6: false, +82 https: false, +83 #[cfg(any(test, feature = "test-utils"))] +84 insecure_skip_relay_cert_verify: false, +85 } +86 } +87 +88 /// Set the ipv4 stun socket and enable ipv4 stun probes +89 pub fn stun_v4(mut self, sock: Option<Arc<UdpSocket>>) -> Self { +90 self.stun_sock_v4 = sock; +91 self +92 } +93 +94 /// Set the ipv6 stun socket and enable ipv6 stun probes +95 pub fn stun_v6(mut self, sock: Option<Arc<UdpSocket>>) -> Self { +96 self.stun_sock_v6 = sock; +97 self +98 } +99 +100 /// Enable quic probes +101 pub fn quic_config(mut self, quic_config: Option<QuicConfig>) -> Self { +102 self.quic_config = quic_config; +103 self +104 } +105 +106 /// Enable or disable icmp_v4 probe +107 pub fn icmp_v4(mut self, enable: bool) -> Self { +108 self.icmp_v4 = enable; +109 self +110 } +111 +112 /// Enable or disable icmp_v6 probe +113 pub fn icmp_v6(mut self, enable: bool) -> Self { +114 self.icmp_v6 = enable; +115 self +116 } +117 +118 /// Enable or disable https probe +119 pub fn https(mut self, enable: bool) -> Self { +120 self.https = enable; +121 self +122 } +123 +124 /// Skip cert verification +125 #[cfg(any(test, feature = "test-utils"))] +126 pub fn insecure_skip_relay_cert_verify(mut self, skip: bool) -> Self { +127 self.insecure_skip_relay_cert_verify = skip; +128 self +129 } +130 +131 /// Turn the options into set of valid protocols +132 pub(crate) fn to_protocols(&self) -> BTreeSet<ProbeProto> { +133 let mut protocols = BTreeSet::new(); +134 if self.stun_sock_v4.is_some() { +135 protocols.insert(ProbeProto::StunIpv4); 136 } -137 if self.icmp_v6 { -138 protocols.insert(ProbeProto::IcmpV6); +137 if self.stun_sock_v6.is_some() { +138 protocols.insert(ProbeProto::StunIpv6); 139 } -140 if self.https { -141 protocols.insert(ProbeProto::Https); -142 } -143 protocols -144 } -145 } -146} -147 -148#[cfg(wasm_browser)] -149mod imp { -150 use std::collections::BTreeSet; -151 -152 use crate::net_report::reportgen::ProbeProto; -153 -154 /// Options for running probes (in browsers). -155 /// -156 /// Only HTTPS probes are supported in browsers. -157 /// These are run by default. -158 #[derive(Debug, Clone)] -159 pub struct Options { -160 /// Enable https probes -161 /// -162 /// On by default -163 pub(crate) https: bool, -164 } +140 if let Some(ref quic) = self.quic_config { +141 if quic.ipv4 { +142 protocols.insert(ProbeProto::QuicIpv4); +143 } +144 if quic.ipv6 { +145 protocols.insert(ProbeProto::QuicIpv6); +146 } +147 } +148 if self.icmp_v4 { +149 protocols.insert(ProbeProto::IcmpV4); +150 } +151 if self.icmp_v6 { +152 protocols.insert(ProbeProto::IcmpV6); +153 } +154 if self.https { +155 protocols.insert(ProbeProto::Https); +156 } +157 protocols +158 } +159 } +160} +161 +162#[cfg(wasm_browser)] +163mod imp { +164 use std::collections::BTreeSet; 165 -166 impl Default for Options { -167 fn default() -> Self { -168 Self { https: true } -169 } -170 } -171 -172 impl Options { -173 /// Create an [`Options`] that disables all probes -174 pub fn disabled() -> Self { -175 Self { https: false } -176 } -177 -178 /// Enable or disable https probe -179 pub fn https(mut self, enable: bool) -> Self { -180 self.https = enable; -181 self -182 } -183 -184 /// Turn the options into set of valid protocols -185 pub(crate) fn to_protocols(&self) -> BTreeSet<ProbeProto> { -186 let mut protocols = BTreeSet::new(); -187 if self.https { -188 protocols.insert(ProbeProto::Https); -189 } -190 protocols -191 } -192 } -193} \ No newline at end of file +166 use crate::net_report::reportgen::ProbeProto; +167 +168 /// Options for running probes (in browsers). +169 /// +170 /// Only HTTPS probes are supported in browsers. +171 /// These are run by default. +172 #[derive(Debug, Clone)] +173 pub struct Options { +174 /// Enable https probes +175 /// +176 /// On by default +177 pub(crate) https: bool, +178 } +179 +180 impl Default for Options { +181 fn default() -> Self { +182 Self { https: true } +183 } +184 } +185 +186 impl Options { +187 /// Create an [`Options`] that disables all probes +188 pub fn disabled() -> Self { +189 Self { https: false } +190 } +191 +192 /// Enable or disable https probe +193 pub fn https(mut self, enable: bool) -> Self { +194 self.https = enable; +195 self +196 } +197 +198 /// Turn the options into set of valid protocols +199 pub(crate) fn to_protocols(&self) -> BTreeSet<ProbeProto> { +200 let mut protocols = BTreeSet::new(); +201 if self.https { +202 protocols.insert(ProbeProto::Https); +203 } +204 protocols +205 } +206 } +207} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/net_report/reportgen.rs.html b/pr/3327/docs/src/iroh/net_report/reportgen.rs.html index a993d29046..b21f1a4ca6 100644 --- a/pr/3327/docs/src/iroh/net_report/reportgen.rs.html +++ b/pr/3327/docs/src/iroh/net_report/reportgen.rs.html @@ -28,7 +28,7 @@ 28use http::StatusCode; 29use iroh_base::RelayUrl; 30#[cfg(not(wasm_browser))] -31use iroh_relay::dns::{DnsError, DnsResolver}; +31use iroh_relay::dns::{DnsError, DnsResolver, StaggeredError}; 32use iroh_relay::{ 33 defaults::{DEFAULT_RELAY_QUIC_PORT, DEFAULT_STUN_PORT}, 34 http::RELAY_PROBE_PATH, @@ -115,1821 +115,1828 @@ 115 protocols: BTreeSet<ProbeProto>, 116 metrics: Arc<Metrics>, 117 #[cfg(not(wasm_browser))] socket_state: SocketState, -118 ) -> Self { -119 let (msg_tx, msg_rx) = mpsc::channel(32); -120 let addr = Addr { -121 sender: msg_tx.clone(), -122 }; -123 let mut actor = Actor { -124 msg_tx, -125 msg_rx, -126 net_report: net_report.clone(), -127 last_report, -128 relay_map, -129 report: Report::default(), -130 outstanding_tasks: OutstandingTasks::default(), -131 protocols, -132 #[cfg(not(wasm_browser))] -133 socket_state, -134 #[cfg(not(wasm_browser))] -135 hairpin_actor: hairpin::Client::new(net_report, addr), -136 metrics, -137 }; -138 let task = -139 task::spawn(async move { actor.run().await }.instrument(info_span!("reportgen.actor"))); -140 Self { -141 _drop_guard: AbortOnDropHandle::new(task), -142 } -143 } -144} -145 -146/// The address of the reportstate [`Actor`]. -147/// -148/// Unlike the [`Client`] struct itself this is the raw channel to send message over. -149/// Keeping this alive will not keep the actor alive, which makes this handy to pass to -150/// internal tasks. -151#[derive(Debug, Clone)] -152pub(super) struct Addr { -153 sender: mpsc::Sender<Message>, -154} -155 -156impl Addr { -157 /// Blocking send to the actor, to be used from a non-actor future. -158 async fn send(&self, msg: Message) -> Result<(), mpsc::error::SendError<Message>> { -159 trace!( -160 "sending {:?} to channel with cap {}", -161 msg, -162 self.sender.capacity() -163 ); -164 self.sender.send(msg).await -165 } -166} -167 -168/// Messages to send to the reportstate [`Actor`]. -169#[derive(Debug)] -170enum Message { -171 /// Set the hairpinning availability in the report. -172 HairpinResult(bool), -173 /// Check whether executing a probe would still help. -174 // TODO: Ideally we remove the need for this message and the logic is inverted: once we -175 // get a probe result we cancel all probes that are no longer needed. But for now it's -176 // this way around to ease conversion. -177 ProbeWouldHelp(Probe, Arc<RelayNode>, oneshot::Sender<bool>), -178 /// Abort all remaining probes. -179 AbortProbes, -180} -181 -182/// The reportstate actor. -183/// -184/// This actor starts, generates a single report and exits. -185#[derive(Debug)] -186struct Actor { -187 /// The sender of the message channel, so we can give out [`Addr`]. -188 msg_tx: mpsc::Sender<Message>, -189 /// The receiver of the message channel. -190 msg_rx: mpsc::Receiver<Message>, -191 /// The address of the net_report actor. -192 net_report: super::Addr, -193 -194 // Provided state -195 /// The previous report, if it exists. -196 last_report: Option<Arc<Report>>, -197 /// The relay configuration. -198 relay_map: RelayMap, -199 -200 // Internal state. -201 /// The report being built. -202 report: Report, -203 /// Which tasks the [`Actor`] is still waiting on. -204 /// -205 /// This is essentially the summary of all the work the [`Actor`] is doing. -206 outstanding_tasks: OutstandingTasks, -207 /// Protocols we should attempt to create probes for, if we have the correct -208 /// configuration for that protocol. -209 protocols: BTreeSet<ProbeProto>, -210 -211 /// Any socket-related state that doesn't exist/work in browsers -212 #[cfg(not(wasm_browser))] -213 socket_state: SocketState, -214 /// The hairpin actor. +118 #[cfg(any(test, feature = "test-utils"))] insecure_skip_relay_cert_verify: bool, +119 ) -> Self { +120 let (msg_tx, msg_rx) = mpsc::channel(32); +121 let addr = Addr { +122 sender: msg_tx.clone(), +123 }; +124 let mut actor = Actor { +125 msg_tx, +126 msg_rx, +127 net_report: net_report.clone(), +128 last_report, +129 relay_map, +130 report: Report::default(), +131 outstanding_tasks: OutstandingTasks::default(), +132 protocols, +133 #[cfg(not(wasm_browser))] +134 socket_state, +135 #[cfg(not(wasm_browser))] +136 hairpin_actor: hairpin::Client::new(net_report, addr), +137 metrics, +138 #[cfg(any(test, feature = "test-utils"))] +139 insecure_skip_relay_cert_verify, +140 }; +141 let task = +142 task::spawn(async move { actor.run().await }.instrument(info_span!("reportgen.actor"))); +143 Self { +144 _drop_guard: AbortOnDropHandle::new(task), +145 } +146 } +147} +148 +149/// The address of the reportstate [`Actor`]. +150/// +151/// Unlike the [`Client`] struct itself this is the raw channel to send message over. +152/// Keeping this alive will not keep the actor alive, which makes this handy to pass to +153/// internal tasks. +154#[derive(Debug, Clone)] +155pub(super) struct Addr { +156 sender: mpsc::Sender<Message>, +157} +158 +159impl Addr { +160 /// Blocking send to the actor, to be used from a non-actor future. +161 async fn send(&self, msg: Message) -> Result<(), mpsc::error::SendError<Message>> { +162 trace!( +163 "sending {:?} to channel with cap {}", +164 msg, +165 self.sender.capacity() +166 ); +167 self.sender.send(msg).await +168 } +169} +170 +171/// Messages to send to the reportstate [`Actor`]. +172#[derive(Debug)] +173enum Message { +174 /// Set the hairpinning availability in the report. +175 HairpinResult(bool), +176 /// Check whether executing a probe would still help. +177 // TODO: Ideally we remove the need for this message and the logic is inverted: once we +178 // get a probe result we cancel all probes that are no longer needed. But for now it's +179 // this way around to ease conversion. +180 ProbeWouldHelp(Probe, Arc<RelayNode>, oneshot::Sender<bool>), +181 /// Abort all remaining probes. +182 AbortProbes, +183} +184 +185/// The reportstate actor. +186/// +187/// This actor starts, generates a single report and exits. +188#[derive(Debug)] +189struct Actor { +190 /// The sender of the message channel, so we can give out [`Addr`]. +191 msg_tx: mpsc::Sender<Message>, +192 /// The receiver of the message channel. +193 msg_rx: mpsc::Receiver<Message>, +194 /// The address of the net_report actor. +195 net_report: super::Addr, +196 +197 // Provided state +198 /// The previous report, if it exists. +199 last_report: Option<Arc<Report>>, +200 /// The relay configuration. +201 relay_map: RelayMap, +202 +203 // Internal state. +204 /// The report being built. +205 report: Report, +206 /// Which tasks the [`Actor`] is still waiting on. +207 /// +208 /// This is essentially the summary of all the work the [`Actor`] is doing. +209 outstanding_tasks: OutstandingTasks, +210 /// Protocols we should attempt to create probes for, if we have the correct +211 /// configuration for that protocol. +212 protocols: BTreeSet<ProbeProto>, +213 +214 /// Any socket-related state that doesn't exist/work in browsers 215 #[cfg(not(wasm_browser))] -216 hairpin_actor: hairpin::Client, -217 metrics: Arc<Metrics>, -218} -219 -220#[allow(missing_docs)] -221#[derive(Debug, Snafu)] -222#[non_exhaustive] -223pub enum ActorRunError { -224 #[snafu(display("Report generation timed out"))] -225 Timeout, -226 #[snafu(display("Client that requested the report is gone"))] -227 ClientGone, -228 #[snafu(display("Internal NetReport actor is gone"))] -229 ActorGone, -230 #[snafu(transparent)] -231 Probes { source: ProbesError }, -232} -233 -234#[allow(missing_docs)] -235#[derive(Debug, Snafu)] -236#[non_exhaustive] -237pub enum ProbesError { -238 #[snafu(display("Probe failed"))] -239 ProbeFailure { source: ProbeError }, -240 #[snafu(display("All probes failed"))] -241 AllProbesFailed, -242} -243 -244impl Actor { -245 fn addr(&self) -> Addr { -246 Addr { -247 sender: self.msg_tx.clone(), -248 } -249 } -250 -251 async fn run(&mut self) { -252 match self.run_inner().await { -253 Ok(_) => debug!("reportgen actor finished"), -254 Err(err) => { -255 self.net_report -256 .send(net_report::Message::ReportAborted { reason: err }) -257 .await -258 .ok(); -259 } -260 } -261 } -262 -263 /// Runs the main reportgen actor logic. -264 /// -265 /// This actor runs by: -266 /// -267 /// - Creates a hairpin actor. -268 /// - Creates a captive portal future. -269 /// - Creates ProbeSet futures in a group of futures. -270 /// - Runs a main loop: -271 /// - Drives all the above futures. -272 /// - Receives actor messages (sent by those futures). -273 /// - Updates the report, cancels unneeded futures. -274 /// - Sends the report to the net_report actor. -275 async fn run_inner(&mut self) -> Result<(), ActorRunError> { -276 #[cfg(not(wasm_browser))] -277 let port_mapper = self.socket_state.port_mapper.is_some(); -278 #[cfg(wasm_browser)] -279 let port_mapper = false; -280 debug!(%port_mapper, "reportstate actor starting"); -281 -282 self.report.os_has_ipv6 = super::os_has_ipv6(); -283 -284 let mut port_mapping = self.prepare_portmapper_task(); -285 let mut captive_task = self.prepare_captive_portal_task(); -286 let mut probes = self.spawn_probes_task().await; -287 -288 let total_timer = time::sleep(OVERALL_REPORT_TIMEOUT); -289 tokio::pin!(total_timer); -290 let probe_timer = time::sleep(PROBES_TIMEOUT); -291 tokio::pin!(probe_timer); +216 socket_state: SocketState, +217 /// The hairpin actor. +218 #[cfg(not(wasm_browser))] +219 hairpin_actor: hairpin::Client, +220 metrics: Arc<Metrics>, +221 #[cfg(any(test, feature = "test-utils"))] +222 insecure_skip_relay_cert_verify: bool, +223} +224 +225#[allow(missing_docs)] +226#[derive(Debug, Snafu)] +227#[non_exhaustive] +228pub enum ActorRunError { +229 #[snafu(display("Report generation timed out"))] +230 Timeout, +231 #[snafu(display("Client that requested the report is gone"))] +232 ClientGone, +233 #[snafu(display("Internal NetReport actor is gone"))] +234 ActorGone, +235 #[snafu(transparent)] +236 Probes { source: ProbesError }, +237} +238 +239#[allow(missing_docs)] +240#[derive(Debug, Snafu)] +241#[non_exhaustive] +242pub enum ProbesError { +243 #[snafu(display("Probe failed"))] +244 ProbeFailure { source: ProbeError }, +245 #[snafu(display("All probes failed"))] +246 AllProbesFailed, +247} +248 +249impl Actor { +250 fn addr(&self) -> Addr { +251 Addr { +252 sender: self.msg_tx.clone(), +253 } +254 } +255 +256 async fn run(&mut self) { +257 match self.run_inner().await { +258 Ok(_) => debug!("reportgen actor finished"), +259 Err(err) => { +260 self.net_report +261 .send(net_report::Message::ReportAborted { reason: err }) +262 .await +263 .ok(); +264 } +265 } +266 } +267 +268 /// Runs the main reportgen actor logic. +269 /// +270 /// This actor runs by: +271 /// +272 /// - Creates a hairpin actor. +273 /// - Creates a captive portal future. +274 /// - Creates ProbeSet futures in a group of futures. +275 /// - Runs a main loop: +276 /// - Drives all the above futures. +277 /// - Receives actor messages (sent by those futures). +278 /// - Updates the report, cancels unneeded futures. +279 /// - Sends the report to the net_report actor. +280 async fn run_inner(&mut self) -> Result<(), ActorRunError> { +281 #[cfg(not(wasm_browser))] +282 let port_mapper = self.socket_state.port_mapper.is_some(); +283 #[cfg(wasm_browser)] +284 let port_mapper = false; +285 debug!(%port_mapper, "reportstate actor starting"); +286 +287 self.report.os_has_ipv6 = super::os_has_ipv6(); +288 +289 let mut port_mapping = self.prepare_portmapper_task(); +290 let mut captive_task = self.prepare_captive_portal_task(); +291 let mut probes = self.spawn_probes_task().await; 292 -293 loop { -294 trace!(awaiting = ?self.outstanding_tasks, "tick; awaiting tasks"); -295 if self.outstanding_tasks.all_done() { -296 debug!("all tasks done"); -297 break; -298 } -299 tokio::select! { -300 biased; -301 _ = &mut total_timer => { -302 trace!("tick: total_timer expired"); -303 return Err(TimeoutSnafu.build()); -304 } -305 -306 _ = &mut probe_timer => { -307 warn!("tick: probes timed out"); -308 // Set new timeout to not go into this branch multiple times. We need -309 // the abort to finish all probes normally. PROBES_TIMEOUT is -310 // sufficiently far in the future. -311 probe_timer.as_mut().reset(Instant::now() + PROBES_TIMEOUT); -312 probes.abort_all(); -313 self.handle_abort_probes(); -314 } -315 -316 // Drive the portmapper. -317 pm = &mut port_mapping, if self.outstanding_tasks.port_mapper => { -318 debug!(report=?pm, "tick: portmapper probe report"); -319 self.report.portmap_probe = pm; -320 port_mapping.inner = None; -321 self.outstanding_tasks.port_mapper = false; -322 } -323 -324 // Check for probes finishing. -325 set_result = probes.join_next(), if self.outstanding_tasks.probes => { -326 trace!("tick: probes done: {:?}", set_result); -327 match set_result { -328 Some(Ok(Ok(report))) => self.handle_probe_report(report), -329 Some(Ok(Err(_))) => (), -330 Some(Err(e)) => { -331 warn!("probes task error: {:?}", e); -332 } -333 None => { -334 self.handle_abort_probes(); -335 } -336 } -337 trace!("tick: probes handled"); -338 } -339 -340 // Drive the captive task. -341 found = &mut captive_task, if self.outstanding_tasks.captive_task => { -342 trace!("tick: captive portal task done"); -343 self.report.captive_portal = found; -344 captive_task.inner = None; -345 self.outstanding_tasks.captive_task = false; -346 } -347 -348 // Handle actor messages. -349 msg = self.msg_rx.recv() => { -350 trace!("tick: msg recv: {:?}", msg); -351 match msg { -352 Some(msg) => self.handle_message(msg), -353 None => { -354 return Err(ClientGoneSnafu.build()); -355 } -356 } -357 } -358 } -359 } -360 -361 if !probes.is_empty() { -362 debug!( -363 "aborting {} probe sets, already have enough reports", -364 probes.len() -365 ); -366 drop(probes); -367 } -368 -369 debug!("Sending report to net_report actor"); -370 self.net_report -371 .send(net_report::Message::ReportReady { -372 report: Box::new(self.report.clone()), -373 }) -374 .await -375 .map_err(|_| ActorGoneSnafu.build())?; -376 -377 Ok(()) -378 } -379 -380 /// Handles an actor message. -381 /// -382 /// Returns `true` if all the probes need to be aborted. -383 fn handle_message(&mut self, msg: Message) { -384 trace!(?msg, "handling message"); -385 match msg { -386 Message::HairpinResult(works) => { -387 self.report.hair_pinning = Some(works); -388 self.outstanding_tasks.hairpin = false; -389 } -390 Message::ProbeWouldHelp(probe, relay_node, response_tx) => { -391 let res = self.probe_would_help(probe, relay_node); -392 if response_tx.send(res).is_err() { -393 debug!("probe dropped before ProbeWouldHelp response sent"); -394 } -395 } -396 Message::AbortProbes => { -397 self.handle_abort_probes(); -398 } -399 } -400 } -401 -402 fn handle_probe_report(&mut self, probe_report: ProbeReport) { -403 debug!(?probe_report, "finished probe"); -404 update_report(&mut self.report, probe_report); -405 -406 // When we discover the first IPv4 address we want to start the hairpin actor. -407 #[cfg(not(wasm_browser))] -408 if let Some(ref addr) = self.report.global_v4 { -409 if !self.hairpin_actor.has_started() { -410 self.hairpin_actor.start_check(*addr); -411 self.outstanding_tasks.hairpin = true; -412 } -413 } -414 -415 // Once we've heard from enough relay servers (3), start a timer to give up on the other -416 // probes. The timer's duration is a function of whether this is our initial full -417 // probe or an incremental one. For incremental ones, wait for the duration of the -418 // slowest relay. For initial ones, double that. -419 let enough_relays = std::cmp::min(self.relay_map.len(), ENOUGH_NODES); -420 if self.report.relay_latency.len() == enough_relays { -421 let timeout = self.report.relay_latency.max_latency(); -422 let timeout = match self.last_report.is_some() { -423 true => timeout, -424 false => timeout * 2, -425 }; -426 let reportcheck = self.addr(); -427 debug!( -428 reports=self.report.relay_latency.len(), -429 delay=?timeout, -430 "Have enough probe reports, aborting further probes soon", -431 ); -432 task::spawn( -433 async move { -434 time::sleep(timeout).await; -435 // Because we do this after a timeout it is entirely normal that the -436 // actor is no longer there by the time we send this message. -437 reportcheck -438 .send(Message::AbortProbes) -439 .await -440 .map_err(|err| trace!("Failed to abort all probes: {err:#}")) -441 .ok(); -442 } -443 .instrument(Span::current()), -444 ); -445 } -446 } -447 -448 /// Whether running this probe would still improve our report. -449 fn probe_would_help(&mut self, probe: Probe, relay_node: Arc<RelayNode>) -> bool { -450 // If the probe is for a relay we don't yet know about, that would help. -451 if self.report.relay_latency.get(&relay_node.url).is_none() { -452 return true; -453 } -454 -455 // If the probe is for IPv6 and we don't yet have an IPv6 report, that would help. -456 #[cfg(not(wasm_browser))] -457 if probe.proto() == ProbeProto::StunIpv6 && self.report.relay_v6_latency.is_empty() { -458 return true; -459 } -460 -461 // For IPv4, we need at least two IPv4 results overall to -462 // determine whether we're behind a NAT that shows us as -463 // different source IPs and/or ports depending on who we're -464 // talking to. If we don't yet have two results yet -465 // (`mapping_varies_by_dest_ip` is blank), then another IPv4 probe -466 // would be good. -467 #[cfg(not(wasm_browser))] -468 if probe.proto() == ProbeProto::StunIpv4 && self.report.mapping_varies_by_dest_ip.is_none() -469 { -470 return true; -471 } -472 -473 // Otherwise not interesting. -474 false -475 } -476 -477 /// Stops further probes. -478 /// -479 /// This makes sure that no further probes are run and also cancels the captive portal -480 /// and portmapper tasks if there were successful probes. Be sure to only handle this -481 /// after all the required [`ProbeReport`]s have been processed. -482 fn handle_abort_probes(&mut self) { -483 trace!("handle abort probes"); -484 self.outstanding_tasks.probes = false; -485 if self.report.udp { -486 self.outstanding_tasks.port_mapper = false; -487 self.outstanding_tasks.captive_task = false; -488 } -489 } -490 -491 /// Creates the future which will perform the portmapper task. -492 /// -493 /// The returned future will run the portmapper, if enabled, resolving to it's result. -494 fn prepare_portmapper_task( -495 &mut self, -496 ) -> MaybeFuture<Pin<Box<impl Future<Output = Option<portmapper::ProbeOutput>>>>> { -497 // In the browser, the compiler struggles to infer the type of future inside, because it's never set. -498 #[cfg(wasm_browser)] -499 let port_mapping: MaybeFuture<Pin<Box<Pending<Option<portmapper::ProbeOutput>>>>> = -500 MaybeFuture::default(); -501 -502 #[cfg(not(wasm_browser))] -503 let mut port_mapping = MaybeFuture::default(); -504 -505 #[cfg(not(wasm_browser))] -506 if let Some(port_mapper) = self.socket_state.port_mapper.clone() { -507 port_mapping.inner = Some(Box::pin(async move { -508 match port_mapper.probe().await { -509 Ok(Ok(res)) => Some(res), -510 Ok(Err(err)) => { -511 debug!("skipping port mapping: {err:?}"); -512 None -513 } -514 Err(recv_err) => { -515 warn!("skipping port mapping: {recv_err:?}"); -516 None -517 } -518 } -519 })); -520 self.outstanding_tasks.port_mapper = true; -521 } -522 port_mapping -523 } -524 -525 /// Creates the future which will perform the captive portal check. -526 fn prepare_captive_portal_task( -527 &mut self, -528 ) -> MaybeFuture<Pin<Box<impl Future<Output = Option<bool>>>>> { -529 // In the browser case the compiler cannot infer the type of the future, because it's never set: -530 #[cfg(wasm_browser)] -531 let captive_task: MaybeFuture<Pin<Box<Pending<Option<bool>>>>> = MaybeFuture::default(); -532 -533 #[cfg(not(wasm_browser))] -534 let mut captive_task = MaybeFuture::default(); -535 -536 // If we're doing a full probe, also check for a captive portal. We -537 // delay by a bit to wait for UDP STUN to finish, to avoid the probe if -538 // it's unnecessary. -539 #[cfg(not(wasm_browser))] -540 if self.last_report.is_none() { -541 // Even if we're doing a non-incremental update, we may want to try our -542 // preferred relay for captive portal detection. -543 let preferred_relay = self -544 .last_report -545 .as_ref() -546 .and_then(|l| l.preferred_relay.clone()); -547 -548 let dns_resolver = self.socket_state.dns_resolver.clone(); -549 let dm = self.relay_map.clone(); -550 self.outstanding_tasks.captive_task = true; -551 captive_task.inner = Some(Box::pin(async move { -552 time::sleep(CAPTIVE_PORTAL_DELAY).await; -553 debug!("Captive portal check started after {CAPTIVE_PORTAL_DELAY:?}"); -554 let captive_portal_check = time::timeout( -555 CAPTIVE_PORTAL_TIMEOUT, -556 check_captive_portal(&dns_resolver, &dm, preferred_relay) -557 .instrument(debug_span!("captive-portal")), -558 ); -559 match captive_portal_check.await { -560 Ok(Ok(found)) => Some(found), -561 Ok(Err(err)) => { -562 match err { -563 CaptivePortalError::CreateReqwestClient { ref source } -564 | CaptivePortalError::HttpRequest { ref source } => { -565 if source.is_connect() { -566 debug!("check_captive_portal failed: {err:#}"); -567 } -568 } -569 _ => warn!("check_captive_portal error: {err:#}"), -570 } -571 None -572 } -573 Err(_) => { -574 warn!("check_captive_portal timed out"); -575 None -576 } -577 } -578 })); -579 } -580 -581 self.outstanding_tasks.captive_task = false; -582 captive_task -583 } -584 -585 /// Prepares the future which will run all the probes as per generated ProbePlan. -586 /// -587 /// Probes operate like the following: -588 /// -589 /// - A future is created for each probe in all probe sets. -590 /// - All probes in a set are grouped in [`JoinSet`]. -591 /// - All those probe sets are grouped in one overall [`JoinSet`]. -592 /// - This future is polled by the main actor loop to make progress. -593 /// - Once a probe future is polled: -594 /// - Many probes start with a delay, they sleep during this time. -595 /// - When a probe starts it first asks the reportgen [`Actor`] if it is still useful -596 /// to run. If not it aborts the entire probe set. -597 /// - When a probe finishes, its [`ProbeReport`] is yielded to the reportgen actor. -598 /// - Probes get aborted in several ways: -599 /// - A running it can fail and abort the entire probe set if it deems the -600 /// failure permanent. Probes in a probe set are essentially retries. -601 /// - Once there are [`ProbeReport`]s from enough nodes, all remaining probes are -602 /// aborted. That is, the main actor loop stops polling them. -603 async fn spawn_probes_task(&mut self) -> JoinSet<Result<ProbeReport, ProbesError>> { -604 #[cfg(not(wasm_browser))] -605 let if_state = interfaces::State::new().await; -606 #[cfg(not(wasm_browser))] -607 debug!(%if_state, "Local interfaces"); -608 let plan = match self.last_report { -609 Some(ref report) => ProbePlan::with_last_report( -610 &self.relay_map, -611 report, -612 &self.protocols, -613 #[cfg(not(wasm_browser))] -614 &if_state, -615 ), -616 None => ProbePlan::initial( -617 &self.relay_map, -618 &self.protocols, -619 #[cfg(not(wasm_browser))] -620 &if_state, -621 ), -622 }; -623 trace!(%plan, "probe plan"); -624 -625 // The pinger is created here so that any sockets that might be bound for it are -626 // shared between the probes that use it. It binds sockets lazily, so we can always -627 // create it. -628 #[cfg(not(wasm_browser))] -629 let pinger = Pinger::new(); -630 -631 // A collection of futures running probe sets. -632 let mut probes = JoinSet::default(); -633 for probe_set in plan.iter() { -634 let mut set = JoinSet::default(); -635 for probe in probe_set { -636 let reportstate = self.addr(); -637 let relay_node = probe.node().clone(); -638 let probe = probe.clone(); -639 let net_report = self.net_report.clone(); -640 -641 #[cfg(not(wasm_browser))] -642 let pinger = pinger.clone(); -643 #[cfg(not(wasm_browser))] -644 let socket_state = self.socket_state.clone(); +293 let total_timer = time::sleep(OVERALL_REPORT_TIMEOUT); +294 tokio::pin!(total_timer); +295 let probe_timer = time::sleep(PROBES_TIMEOUT); +296 tokio::pin!(probe_timer); +297 +298 loop { +299 trace!(awaiting = ?self.outstanding_tasks, "tick; awaiting tasks"); +300 if self.outstanding_tasks.all_done() { +301 debug!("all tasks done"); +302 break; +303 } +304 tokio::select! { +305 biased; +306 _ = &mut total_timer => { +307 trace!("tick: total_timer expired"); +308 return Err(TimeoutSnafu.build()); +309 } +310 +311 _ = &mut probe_timer => { +312 warn!("tick: probes timed out"); +313 // Set new timeout to not go into this branch multiple times. We need +314 // the abort to finish all probes normally. PROBES_TIMEOUT is +315 // sufficiently far in the future. +316 probe_timer.as_mut().reset(Instant::now() + PROBES_TIMEOUT); +317 probes.abort_all(); +318 self.handle_abort_probes(); +319 } +320 +321 // Drive the portmapper. +322 pm = &mut port_mapping, if self.outstanding_tasks.port_mapper => { +323 debug!(report=?pm, "tick: portmapper probe report"); +324 self.report.portmap_probe = pm; +325 port_mapping.inner = None; +326 self.outstanding_tasks.port_mapper = false; +327 } +328 +329 // Check for probes finishing. +330 set_result = probes.join_next(), if self.outstanding_tasks.probes => { +331 trace!("tick: probes done: {:?}", set_result); +332 match set_result { +333 Some(Ok(Ok(report))) => self.handle_probe_report(report), +334 Some(Ok(Err(_))) => (), +335 Some(Err(e)) => { +336 warn!("probes task error: {:?}", e); +337 } +338 None => { +339 self.handle_abort_probes(); +340 } +341 } +342 trace!("tick: probes handled"); +343 } +344 +345 // Drive the captive task. +346 found = &mut captive_task, if self.outstanding_tasks.captive_task => { +347 trace!("tick: captive portal task done"); +348 self.report.captive_portal = found; +349 captive_task.inner = None; +350 self.outstanding_tasks.captive_task = false; +351 } +352 +353 // Handle actor messages. +354 msg = self.msg_rx.recv() => { +355 trace!("tick: msg recv: {:?}", msg); +356 match msg { +357 Some(msg) => self.handle_message(msg), +358 None => { +359 return Err(ClientGoneSnafu.build()); +360 } +361 } +362 } +363 } +364 } +365 +366 if !probes.is_empty() { +367 debug!( +368 "aborting {} probe sets, already have enough reports", +369 probes.len() +370 ); +371 drop(probes); +372 } +373 +374 debug!("Sending report to net_report actor"); +375 self.net_report +376 .send(net_report::Message::ReportReady { +377 report: Box::new(self.report.clone()), +378 }) +379 .await +380 .map_err(|_| ActorGoneSnafu.build())?; +381 +382 Ok(()) +383 } +384 +385 /// Handles an actor message. +386 /// +387 /// Returns `true` if all the probes need to be aborted. +388 fn handle_message(&mut self, msg: Message) { +389 trace!(?msg, "handling message"); +390 match msg { +391 Message::HairpinResult(works) => { +392 self.report.hair_pinning = Some(works); +393 self.outstanding_tasks.hairpin = false; +394 } +395 Message::ProbeWouldHelp(probe, relay_node, response_tx) => { +396 let res = self.probe_would_help(probe, relay_node); +397 if response_tx.send(res).is_err() { +398 debug!("probe dropped before ProbeWouldHelp response sent"); +399 } +400 } +401 Message::AbortProbes => { +402 self.handle_abort_probes(); +403 } +404 } +405 } +406 +407 fn handle_probe_report(&mut self, probe_report: ProbeReport) { +408 debug!(?probe_report, "finished probe"); +409 update_report(&mut self.report, probe_report); +410 +411 // When we discover the first IPv4 address we want to start the hairpin actor. +412 #[cfg(not(wasm_browser))] +413 if let Some(ref addr) = self.report.global_v4 { +414 if !self.hairpin_actor.has_started() { +415 self.hairpin_actor.start_check(*addr); +416 self.outstanding_tasks.hairpin = true; +417 } +418 } +419 +420 // Once we've heard from enough relay servers (3), start a timer to give up on the other +421 // probes. The timer's duration is a function of whether this is our initial full +422 // probe or an incremental one. For incremental ones, wait for the duration of the +423 // slowest relay. For initial ones, double that. +424 let enough_relays = std::cmp::min(self.relay_map.len(), ENOUGH_NODES); +425 if self.report.relay_latency.len() == enough_relays { +426 let timeout = self.report.relay_latency.max_latency(); +427 let timeout = match self.last_report.is_some() { +428 true => timeout, +429 false => timeout * 2, +430 }; +431 let reportcheck = self.addr(); +432 debug!( +433 reports=self.report.relay_latency.len(), +434 delay=?timeout, +435 "Have enough probe reports, aborting further probes soon", +436 ); +437 task::spawn( +438 async move { +439 time::sleep(timeout).await; +440 // Because we do this after a timeout it is entirely normal that the +441 // actor is no longer there by the time we send this message. +442 reportcheck +443 .send(Message::AbortProbes) +444 .await +445 .map_err(|err| trace!("Failed to abort all probes: {err:#}")) +446 .ok(); +447 } +448 .instrument(Span::current()), +449 ); +450 } +451 } +452 +453 /// Whether running this probe would still improve our report. +454 fn probe_would_help(&mut self, probe: Probe, relay_node: Arc<RelayNode>) -> bool { +455 // If the probe is for a relay we don't yet know about, that would help. +456 if self.report.relay_latency.get(&relay_node.url).is_none() { +457 return true; +458 } +459 +460 // If the probe is for IPv6 and we don't yet have an IPv6 report, that would help. +461 #[cfg(not(wasm_browser))] +462 if probe.proto() == ProbeProto::StunIpv6 && self.report.relay_v6_latency.is_empty() { +463 return true; +464 } +465 +466 // For IPv4, we need at least two IPv4 results overall to +467 // determine whether we're behind a NAT that shows us as +468 // different source IPs and/or ports depending on who we're +469 // talking to. If we don't yet have two results yet +470 // (`mapping_varies_by_dest_ip` is blank), then another IPv4 probe +471 // would be good. +472 #[cfg(not(wasm_browser))] +473 if probe.proto() == ProbeProto::StunIpv4 && self.report.mapping_varies_by_dest_ip.is_none() +474 { +475 return true; +476 } +477 +478 // Otherwise not interesting. +479 false +480 } +481 +482 /// Stops further probes. +483 /// +484 /// This makes sure that no further probes are run and also cancels the captive portal +485 /// and portmapper tasks if there were successful probes. Be sure to only handle this +486 /// after all the required [`ProbeReport`]s have been processed. +487 fn handle_abort_probes(&mut self) { +488 trace!("handle abort probes"); +489 self.outstanding_tasks.probes = false; +490 if self.report.udp { +491 self.outstanding_tasks.port_mapper = false; +492 self.outstanding_tasks.captive_task = false; +493 } +494 } +495 +496 /// Creates the future which will perform the portmapper task. +497 /// +498 /// The returned future will run the portmapper, if enabled, resolving to it's result. +499 fn prepare_portmapper_task( +500 &mut self, +501 ) -> MaybeFuture<Pin<Box<impl Future<Output = Option<portmapper::ProbeOutput>>>>> { +502 // In the browser, the compiler struggles to infer the type of future inside, because it's never set. +503 #[cfg(wasm_browser)] +504 let port_mapping: MaybeFuture<Pin<Box<Pending<Option<portmapper::ProbeOutput>>>>> = +505 MaybeFuture::default(); +506 +507 #[cfg(not(wasm_browser))] +508 let mut port_mapping = MaybeFuture::default(); +509 +510 #[cfg(not(wasm_browser))] +511 if let Some(port_mapper) = self.socket_state.port_mapper.clone() { +512 port_mapping.inner = Some(Box::pin(async move { +513 match port_mapper.probe().await { +514 Ok(Ok(res)) => Some(res), +515 Ok(Err(err)) => { +516 debug!("skipping port mapping: {err:?}"); +517 None +518 } +519 Err(recv_err) => { +520 warn!("skipping port mapping: {recv_err:?}"); +521 None +522 } +523 } +524 })); +525 self.outstanding_tasks.port_mapper = true; +526 } +527 port_mapping +528 } +529 +530 /// Creates the future which will perform the captive portal check. +531 fn prepare_captive_portal_task( +532 &mut self, +533 ) -> MaybeFuture<Pin<Box<impl Future<Output = Option<bool>>>>> { +534 // In the browser case the compiler cannot infer the type of the future, because it's never set: +535 #[cfg(wasm_browser)] +536 let captive_task: MaybeFuture<Pin<Box<Pending<Option<bool>>>>> = MaybeFuture::default(); +537 +538 #[cfg(not(wasm_browser))] +539 let mut captive_task = MaybeFuture::default(); +540 +541 // If we're doing a full probe, also check for a captive portal. We +542 // delay by a bit to wait for UDP STUN to finish, to avoid the probe if +543 // it's unnecessary. +544 #[cfg(not(wasm_browser))] +545 if self.last_report.is_none() { +546 // Even if we're doing a non-incremental update, we may want to try our +547 // preferred relay for captive portal detection. +548 let preferred_relay = self +549 .last_report +550 .as_ref() +551 .and_then(|l| l.preferred_relay.clone()); +552 +553 let dns_resolver = self.socket_state.dns_resolver.clone(); +554 let dm = self.relay_map.clone(); +555 self.outstanding_tasks.captive_task = true; +556 captive_task.inner = Some(Box::pin(async move { +557 time::sleep(CAPTIVE_PORTAL_DELAY).await; +558 debug!("Captive portal check started after {CAPTIVE_PORTAL_DELAY:?}"); +559 let captive_portal_check = time::timeout( +560 CAPTIVE_PORTAL_TIMEOUT, +561 check_captive_portal(&dns_resolver, &dm, preferred_relay) +562 .instrument(debug_span!("captive-portal")), +563 ); +564 match captive_portal_check.await { +565 Ok(Ok(found)) => Some(found), +566 Ok(Err(err)) => { +567 match err { +568 CaptivePortalError::CreateReqwestClient { ref source } +569 | CaptivePortalError::HttpRequest { ref source } => { +570 if source.is_connect() { +571 debug!("check_captive_portal failed: {err:#}"); +572 } +573 } +574 _ => warn!("check_captive_portal error: {err:#}"), +575 } +576 None +577 } +578 Err(_) => { +579 warn!("check_captive_portal timed out"); +580 None +581 } +582 } +583 })); +584 } +585 +586 self.outstanding_tasks.captive_task = false; +587 captive_task +588 } +589 +590 /// Prepares the future which will run all the probes as per generated ProbePlan. +591 /// +592 /// Probes operate like the following: +593 /// +594 /// - A future is created for each probe in all probe sets. +595 /// - All probes in a set are grouped in [`JoinSet`]. +596 /// - All those probe sets are grouped in one overall [`JoinSet`]. +597 /// - This future is polled by the main actor loop to make progress. +598 /// - Once a probe future is polled: +599 /// - Many probes start with a delay, they sleep during this time. +600 /// - When a probe starts it first asks the reportgen [`Actor`] if it is still useful +601 /// to run. If not it aborts the entire probe set. +602 /// - When a probe finishes, its [`ProbeReport`] is yielded to the reportgen actor. +603 /// - Probes get aborted in several ways: +604 /// - A running it can fail and abort the entire probe set if it deems the +605 /// failure permanent. Probes in a probe set are essentially retries. +606 /// - Once there are [`ProbeReport`]s from enough nodes, all remaining probes are +607 /// aborted. That is, the main actor loop stops polling them. +608 async fn spawn_probes_task(&mut self) -> JoinSet<Result<ProbeReport, ProbesError>> { +609 #[cfg(not(wasm_browser))] +610 let if_state = interfaces::State::new().await; +611 #[cfg(not(wasm_browser))] +612 debug!(%if_state, "Local interfaces"); +613 let plan = match self.last_report { +614 Some(ref report) => ProbePlan::with_last_report( +615 &self.relay_map, +616 report, +617 &self.protocols, +618 #[cfg(not(wasm_browser))] +619 &if_state, +620 ), +621 None => ProbePlan::initial( +622 &self.relay_map, +623 &self.protocols, +624 #[cfg(not(wasm_browser))] +625 &if_state, +626 ), +627 }; +628 trace!(%plan, "probe plan"); +629 +630 // The pinger is created here so that any sockets that might be bound for it are +631 // shared between the probes that use it. It binds sockets lazily, so we can always +632 // create it. +633 #[cfg(not(wasm_browser))] +634 let pinger = Pinger::new(); +635 +636 // A collection of futures running probe sets. +637 let mut probes = JoinSet::default(); +638 for probe_set in plan.iter() { +639 let mut set = JoinSet::default(); +640 for probe in probe_set { +641 let reportstate = self.addr(); +642 let relay_node = probe.node().clone(); +643 let probe = probe.clone(); +644 let net_report = self.net_report.clone(); 645 -646 let metrics = self.metrics.clone(); -647 set.spawn( -648 run_probe( -649 reportstate, -650 relay_node, -651 probe.clone(), -652 net_report, -653 metrics, -654 #[cfg(not(wasm_browser))] -655 pinger, -656 #[cfg(not(wasm_browser))] -657 socket_state, -658 ) -659 .instrument(debug_span!("run_probe", %probe)), -660 ); -661 } -662 -663 // Add the probe set to all futures of probe sets. Handle aborting a probe set -664 // if needed, only normal errors means the set continues. -665 probes.spawn( -666 async move { -667 // Hack because ProbeSet is not it's own type yet. -668 let mut probe_proto = None; -669 while let Some(res) = set.join_next().await { -670 match res { -671 Ok(Ok(report)) => return Ok(report), -672 Ok(Err(ProbeErrorWithProbe::Error(err, probe))) => { -673 probe_proto = Some(probe.proto()); -674 warn!(?probe, "probe failed: {:#}", err); -675 continue; -676 } -677 Ok(Err(ProbeErrorWithProbe::AbortSet(err, probe))) => { -678 debug!(?probe, "probe set aborted: {:#}", err); -679 set.abort_all(); -680 return Err(ProbeFailureSnafu.into_error(err)); -681 } -682 Err(err) => { -683 warn!("fatal probe set error, aborting: {:#}", err); -684 continue; -685 } -686 } -687 } -688 warn!(?probe_proto, "no successful probes in ProbeSet"); -689 Err(AllProbesFailedSnafu.build()) -690 } -691 .instrument(info_span!("probe")), -692 ); -693 } -694 self.outstanding_tasks.probes = true; -695 -696 probes -697 } -698} -699 -700/// Tasks on which the reportgen [`Actor`] is still waiting. -701/// -702/// There is no particular progression, e.g. hairpin starts `false`, moves to `true` when a -703/// check is started and then becomes `false` again once it is finished. -704#[derive(Debug, Default)] -705struct OutstandingTasks { -706 probes: bool, -707 port_mapper: bool, -708 captive_task: bool, -709 hairpin: bool, -710} -711 -712impl OutstandingTasks { -713 fn all_done(&self) -> bool { -714 !(self.probes || self.port_mapper || self.captive_task || self.hairpin) -715 } -716} -717 -718/// The success result of [`run_probe`]. -719#[derive(Debug, Clone)] -720struct ProbeReport { -721 /// Whether we can send IPv4 UDP packets. -722 ipv4_can_send: bool, -723 /// Whether we can send IPv6 UDP packets. -724 ipv6_can_send: bool, -725 /// Whether we can send ICMPv4 packets, `None` if not checked. -726 icmpv4: Option<bool>, -727 /// Whether we can send ICMPv6 packets, `None` if not checked. -728 icmpv6: Option<bool>, -729 /// The latency to the relay node. -730 latency: Option<Duration>, -731 /// The probe that generated this report. -732 probe: Probe, -733 /// The discovered public address. -734 addr: Option<SocketAddr>, -735} -736 -737impl ProbeReport { -738 fn new(probe: Probe) -> Self { -739 ProbeReport { -740 probe, -741 ipv4_can_send: false, -742 ipv6_can_send: false, -743 icmpv4: None, -744 icmpv6: None, -745 latency: None, -746 addr: None, -747 } -748 } -749} -750 -751/// Errors for [`run_probe`]. -752/// -753/// The main purpose is to signal whether other probes in this probe set should still be -754/// run. Recall that a probe set is normally a set of identical probes with delays, -755/// effectively creating retries, and the first successful probe of a probe set will cancel -756/// the others in the set. So this allows an unsuccessful probe to cancel the remainder of -757/// the set or not. -758#[derive(Debug)] -759enum ProbeErrorWithProbe { -760 /// Abort the current set. -761 AbortSet(ProbeError, Probe), -762 /// Continue the other probes in the set. -763 Error(ProbeError, Probe), -764} -765 -766#[allow(missing_docs)] -767#[derive(Debug, Snafu)] -768#[snafu(module)] -769#[non_exhaustive] -770pub enum ProbeError { -771 #[snafu(display("Client is gone"))] -772 ClientGone, -773 #[snafu(display("Probe is no longer useful"))] -774 NotUseful, -775 #[cfg(not(wasm_browser))] -776 #[snafu(display("Failed to retrieve the relay address"))] -777 GetRelayAddr { source: GetRelayAddrError }, -778 #[snafu(display("Failed to run stun probe"))] -779 Stun { source: StunError }, -780 #[snafu(display("Failed to run QUIC probe"))] -781 Quic { source: QuicError }, +646 #[cfg(not(wasm_browser))] +647 let pinger = pinger.clone(); +648 #[cfg(not(wasm_browser))] +649 let socket_state = self.socket_state.clone(); +650 +651 let metrics = self.metrics.clone(); +652 set.spawn( +653 run_probe( +654 reportstate, +655 relay_node, +656 probe.clone(), +657 net_report, +658 metrics, +659 #[cfg(not(wasm_browser))] +660 pinger, +661 #[cfg(not(wasm_browser))] +662 socket_state, +663 #[cfg(any(test, feature = "test-utils"))] +664 self.insecure_skip_relay_cert_verify, +665 ) +666 .instrument(debug_span!("run_probe", %probe)), +667 ); +668 } +669 +670 // Add the probe set to all futures of probe sets. Handle aborting a probe set +671 // if needed, only normal errors means the set continues. +672 probes.spawn( +673 async move { +674 // Hack because ProbeSet is not it's own type yet. +675 let mut probe_proto = None; +676 while let Some(res) = set.join_next().await { +677 match res { +678 Ok(Ok(report)) => return Ok(report), +679 Ok(Err(ProbeErrorWithProbe::Error(err, probe))) => { +680 probe_proto = Some(probe.proto()); +681 warn!(?probe, "probe failed: {:#}", err); +682 continue; +683 } +684 Ok(Err(ProbeErrorWithProbe::AbortSet(err, probe))) => { +685 debug!(?probe, "probe set aborted: {:#}", err); +686 set.abort_all(); +687 return Err(ProbeFailureSnafu.into_error(err)); +688 } +689 Err(err) => { +690 warn!("fatal probe set error, aborting: {:#}", err); +691 continue; +692 } +693 } +694 } +695 warn!(?probe_proto, "no successful probes in ProbeSet"); +696 Err(AllProbesFailedSnafu.build()) +697 } +698 .instrument(info_span!("probe")), +699 ); +700 } +701 self.outstanding_tasks.probes = true; +702 +703 probes +704 } +705} +706 +707/// Tasks on which the reportgen [`Actor`] is still waiting. +708/// +709/// There is no particular progression, e.g. hairpin starts `false`, moves to `true` when a +710/// check is started and then becomes `false` again once it is finished. +711#[derive(Debug, Default)] +712struct OutstandingTasks { +713 probes: bool, +714 port_mapper: bool, +715 captive_task: bool, +716 hairpin: bool, +717} +718 +719impl OutstandingTasks { +720 fn all_done(&self) -> bool { +721 !(self.probes || self.port_mapper || self.captive_task || self.hairpin) +722 } +723} +724 +725/// The success result of [`run_probe`]. +726#[derive(Debug, Clone)] +727struct ProbeReport { +728 /// Whether we can send IPv4 UDP packets. +729 ipv4_can_send: bool, +730 /// Whether we can send IPv6 UDP packets. +731 ipv6_can_send: bool, +732 /// Whether we can send ICMPv4 packets, `None` if not checked. +733 icmpv4: Option<bool>, +734 /// Whether we can send ICMPv6 packets, `None` if not checked. +735 icmpv6: Option<bool>, +736 /// The latency to the relay node. +737 latency: Option<Duration>, +738 /// The probe that generated this report. +739 probe: Probe, +740 /// The discovered public address. +741 addr: Option<SocketAddr>, +742} +743 +744impl ProbeReport { +745 fn new(probe: Probe) -> Self { +746 ProbeReport { +747 probe, +748 ipv4_can_send: false, +749 ipv6_can_send: false, +750 icmpv4: None, +751 icmpv6: None, +752 latency: None, +753 addr: None, +754 } +755 } +756} +757 +758/// Errors for [`run_probe`]. +759/// +760/// The main purpose is to signal whether other probes in this probe set should still be +761/// run. Recall that a probe set is normally a set of identical probes with delays, +762/// effectively creating retries, and the first successful probe of a probe set will cancel +763/// the others in the set. So this allows an unsuccessful probe to cancel the remainder of +764/// the set or not. +765#[derive(Debug)] +766enum ProbeErrorWithProbe { +767 /// Abort the current set. +768 AbortSet(ProbeError, Probe), +769 /// Continue the other probes in the set. +770 Error(ProbeError, Probe), +771} +772 +773#[allow(missing_docs)] +774#[derive(Debug, Snafu)] +775#[snafu(module)] +776#[non_exhaustive] +777pub enum ProbeError { +778 #[snafu(display("Client is gone"))] +779 ClientGone, +780 #[snafu(display("Probe is no longer useful"))] +781 NotUseful, 782 #[cfg(not(wasm_browser))] -783 #[snafu(display("Failed to run ICMP probe"))] -784 Icmp { source: PingError }, -785} -786 -787#[allow(missing_docs)] -788#[derive(Debug, Snafu)] -789#[snafu(module)] -790#[non_exhaustive] -791pub enum StunError { -792 #[snafu(display("No UDP socket available"))] -793 NoSocket, -794 #[snafu(display("Stun channel is gone"))] -795 StunChannelGone, -796 #[snafu(display("Failed to send full STUN request"))] -797 SendFull, -798 #[snafu(display("Failed to send STUN request"))] -799 Send { source: std::io::Error }, -800} -801 -802#[allow(missing_docs)] -803#[derive(Debug, Snafu)] -804#[snafu(module)] -805#[non_exhaustive] -806pub enum QuicError { -807 #[snafu(display("No QUIC endpoint available"))] -808 NoEndpoint, -809 #[snafu(display("URL must have 'host' to use QUIC address discovery probes"))] -810 InvalidUrl, -811 #[snafu(display("Failed to create QUIC endpoint"))] -812 CreateClient { source: iroh_relay::quic::Error }, -813 #[snafu(display("Failed to get address and latency"))] -814 GetAddr { source: iroh_relay::quic::Error }, -815} -816 -817/// Pieces needed to do QUIC address discovery. -818#[derive(Debug, Clone)] -819pub struct QuicConfig { -820 /// A QUIC Endpoint -821 pub ep: quinn::Endpoint, -822 /// A client config. -823 pub client_config: rustls::ClientConfig, -824 /// Enable ipv4 QUIC address discovery probes -825 pub ipv4: bool, -826 /// Enable ipv6 QUIC address discovery probes -827 pub ipv6: bool, -828} -829 -830/// Executes a particular [`Probe`], including using a delayed start if needed. -831/// -832/// If *stun_sock4* and *stun_sock6* are `None` the STUN probes are disabled. -833async fn run_probe( -834 reportstate: Addr, -835 relay_node: Arc<RelayNode>, -836 probe: Probe, -837 net_report: net_report::Addr, -838 metrics: Arc<Metrics>, -839 #[cfg(not(wasm_browser))] pinger: Pinger, -840 #[cfg(not(wasm_browser))] socket_state: SocketState, -841) -> Result<ProbeReport, ProbeErrorWithProbe> { -842 if !probe.delay().is_zero() { -843 trace!("delaying probe"); -844 time::sleep(probe.delay()).await; -845 } -846 debug!("starting probe"); -847 -848 let (would_help_tx, would_help_rx) = oneshot::channel(); -849 if let Err(err) = reportstate -850 .send(Message::ProbeWouldHelp( -851 probe.clone(), -852 relay_node.clone(), -853 would_help_tx, -854 )) -855 .await -856 { -857 // this happens on shutdown or if the report is already finished -858 debug!("Failed to check if probe would help: {err:#}"); -859 return Err(ProbeErrorWithProbe::AbortSet( -860 probe_error::ClientGoneSnafu.build(), +783 #[snafu(display("Failed to retrieve the relay address"))] +784
    GetRelayAddr { source: GetRelayAddrError }, +785 #[snafu(display("Failed to run stun probe"))] +786 Stun { source: StunError }, +787 #[snafu(display("Failed to run QUIC probe"))] +788 Quic { source: QuicError }, +789 #[cfg(not(wasm_browser))] +790 #[snafu(display("Failed to run ICMP probe"))] +791 Icmp { source: PingError }, +792} +793 +794#[allow(missing_docs)] +795#[derive(Debug, Snafu)] +796#[snafu(module)] +797#[non_exhaustive] +798pub enum StunError { +799 #[snafu(display("No UDP socket available"))] +800 NoSocket, +801 #[snafu(display("Stun channel is gone"))] +802 StunChannelGone, +803 #[snafu(display("Failed to send full STUN request"))] +804 SendFull, +805 #[snafu(display("Failed to send STUN request"))] +806 Send { source: std::io::Error }, +807} +808 +809#[allow(missing_docs)] +810#[derive(Debug, Snafu)] +811#[snafu(module)] +812#[non_exhaustive] +813pub enum QuicError { +814 #[snafu(display("No QUIC endpoint available"))] +815 NoEndpoint, +816 #[snafu(display("URL must have 'host' to use QUIC address discovery probes"))] +817 InvalidUrl, +818 #[snafu(display("Failed to create QUIC endpoint"))] +819 CreateClient { source: iroh_relay::quic::Error }, +820 #[snafu(display("Failed to get address and latency"))] +821 GetAddr { source: iroh_relay::quic::Error }, +822} +823 +824/// Pieces needed to do QUIC address discovery. +825#[derive(derive_more::Debug, Clone)] +826pub struct QuicConfig { +827 /// A QUIC Endpoint +828 #[debug("quinn::Endpoint")] +829 pub ep: quinn::Endpoint, +830 /// A client config. +831 pub client_config: rustls::ClientConfig, +832 /// Enable ipv4 QUIC address discovery probes +833 pub ipv4: bool, +834 /// Enable ipv6 QUIC address discovery probes +835 pub ipv6: bool, +836} +837 +838/// Executes a particular [`Probe`], including using a delayed start if needed. +839/// +840/// If *stun_sock4* and *stun_sock6* are `None` the STUN probes are disabled. +841#[allow(clippy::too_many_arguments)] +842async fn run_probe( +843 reportstate: Addr, +844 relay_node: Arc<RelayNode>, +845 probe: Probe, +846 net_report: net_report::Addr, +847 metrics: Arc<Metrics>, +848 #[cfg(not(wasm_browser))] pinger: Pinger, +849 #[cfg(not(wasm_browser))] socket_state: SocketState, +850 #[cfg(any(test, feature = "test-utils"))] insecure_skip_relay_cert_verify: bool, +851) -> Result<ProbeReport, ProbeErrorWithProbe> { +852 if !probe.delay().is_zero() { +853 trace!("delaying probe"); +854 time::sleep(probe.delay()).await; +855 } +856 debug!("starting probe"); +857 +858 let (would_help_tx, would_help_rx) = oneshot::channel(); +859 if let Err(err) = reportstate +860 .send(Message::ProbeWouldHelp( 861 probe.clone(), -862 )); -863 } -864 -865 if !would_help_rx.await.map_err(|_| { -866 ProbeErrorWithProbe::AbortSet(probe_error::ClientGoneSnafu.build(), probe.clone()) -867 })? { -868 return Err(ProbeErrorWithProbe::AbortSet( -869 probe_error::NotUsefulSnafu.build(), -870 probe, -871 )); -872 } -873 -874 #[cfg(not(wasm_browser))] -875 let relay_addr = get_relay_addr(&socket_state.dns_resolver, &relay_node, probe.proto()) -876 .await -877 .map_err(|e| { -878 ProbeErrorWithProbe::AbortSet( -879 probe_error::GetRelayAddrSnafu.into_error(e), -880 probe.clone(), -881 ) -882 })?; +862 relay_node.clone(), +863 would_help_tx, +864 )) +865 .await +866 { +867 // this happens on shutdown or if the report is already finished +868 debug!("Failed to check if probe would help: {err:#}"); +869 return Err(ProbeErrorWithProbe::AbortSet( +870 probe_error::ClientGoneSnafu.build(), +871 probe.clone(), +872 )); +873 } +874 +875 if !would_help_rx.await.map_err(|_| { +876 ProbeErrorWithProbe::AbortSet(probe_error::ClientGoneSnafu.build(), probe.clone()) +877 })? { +878 return Err(ProbeErrorWithProbe::AbortSet( +879 probe_error::NotUsefulSnafu.build(), +880 probe, +881 )); +882 } 883 -884 let mut result = ProbeReport::new(probe.clone()); -885 match probe { -886 #[cfg(not(wasm_browser))] -887 Probe::StunIpv4 { .. } | Probe::StunIpv6 { .. } => { -888 let maybe_sock = if matches!(probe, Probe::StunIpv4 { .. }) { -889 socket_state.stun_sock4.as_ref() -890 } else { -891 socket_state.stun_sock6.as_ref() -892 }; -893 match maybe_sock { -894 Some(sock) => { -895 result = run_stun_probe(sock, relay_addr, net_report, probe, &metrics).await?; -896 } -897 None => { -898 return Err(ProbeErrorWithProbe::AbortSet( -899 probe_error::StunSnafu.into_error(stun_error::NoSocketSnafu.build()), -900 probe.clone(), -901 )); -902 } -903 } -904 } -905 #[cfg(not(wasm_browser))] -906 Probe::IcmpV4 { .. } | Probe::IcmpV6 { .. } => { -907 result = run_icmp_probe(probe, relay_addr, pinger).await? -908 } -909 Probe::Https { ref node, .. } => { -910 debug!("sending probe HTTPS"); -911 match measure_https_latency( -912 #[cfg(not(wasm_browser))] -913 &socket_state.dns_resolver, -914 node, -915 None, -916 ) -917 .await -918 { -919 Ok((latency, ip)) => { -920 debug!(?latency, "latency"); -921 result.latency = Some(latency); -922 // We set these IPv4 and IPv6 but they're not really used -923 // and we don't necessarily set them both. If UDP is blocked -924 // and both IPv4 and IPv6 are available over TCP, it's basically -925 // random which fields end up getting set here. -926 // Since they're not needed, that's fine for now. -927 match ip { -928 IpAddr::V4(_) => result.ipv4_can_send = true, -929 IpAddr::V6(_) => result.ipv6_can_send = true, -930 } -931 } -932 Err(err) => { -933 warn!("https latency measurement failed: {:?}", err); -934 } -935 } -936 } -937 -938 #[cfg(not(wasm_browser))] -939 Probe::QuicIpv4 { ref node, .. } | Probe::QuicIpv6 { ref node, .. } => { -940 debug!("sending QUIC address discovery probe"); -941 let url = node.url.clone(); -942 match socket_state.quic_config { -943 Some(quic_config) => { -944 result = run_quic_probe( -945 quic_config, -946 url, -947 relay_addr, -948 probe, -949 socket_state.ip_mapped_addrs, -950 ) -951 .await?; -952 } -953 None => { -954 return Err(ProbeErrorWithProbe::AbortSet( -955 probe_error::QuicSnafu.into_error(quic_error::NoEndpointSnafu.build()), -956 probe.clone(), -957 )); -958 } -959 } -960 } -961 } -962 -963 trace!("probe successful"); -964 Ok(result) -965} -966 -967/// Run a STUN IPv4 or IPv6 probe. -968#[cfg(not(wasm_browser))] -969async fn run_stun_probe( -970 sock: &Arc<UdpSocket>, -971 relay_addr: SocketAddr, -972 net_report: net_report::Addr, -973 probe: Probe, -974 metrics: &Metrics, -975) -> Result<ProbeReport, ProbeErrorWithProbe> { -976 match probe.proto() { -977 ProbeProto::StunIpv4 => debug_assert!(relay_addr.is_ipv4()), -978 ProbeProto::StunIpv6 => debug_assert!(relay_addr.is_ipv6()), -979 _ => debug_assert!(false, "wrong probe"), -980 } -981 let txid = stun::TransactionId::default(); -982 let req = stun::request(txid); -983 -984 // Setup net_report to give us back the incoming STUN response. -985 let (stun_tx, stun_rx) = oneshot::channel(); -986 let (inflight_ready_tx, inflight_ready_rx) = oneshot::channel(); -987 net_report -988 .send(net_report::Message::InFlightStun( -989 net_report::Inflight { -990 txn: txid, -991 start: Instant::now(), -992 s: stun_tx, -993 }, -994 inflight_ready_tx, -995 )) -996 .await -997 .map_err(|_| { -998 ProbeErrorWithProbe::Error(probe_error::ClientGoneSnafu.build(), probe.clone()) -999 })?; -1000 inflight_ready_rx.await.map_err(|_| { -1001 ProbeErrorWithProbe::Error(probe_error::ClientGoneSnafu.build(), probe.clone()) -1002 })?; -1003 -1004 // Send the probe. -1005 match sock.send_to(&req, relay_addr).await { -1006 Ok(n) if n == req.len() => { -1007 debug!(%relay_addr, %txid, "sending {} probe", probe.proto()); -1008 let mut result = ProbeReport::new(probe.clone()); -1009 -1010 if matches!(probe, Probe::StunIpv4 { .. }) { -1011 result.ipv4_can_send = true; -1012 metrics.stun_packets_sent_ipv4.inc(); -1013 } else { -1014 result.ipv6_can_send = true; -1015 metrics.stun_packets_sent_ipv6.inc(); -1016 } -1017 let (delay, addr) = stun_rx.await.map_err(|_| { -1018 ProbeErrorWithProbe::Error( -1019 probe_error::StunSnafu.into_error(stun_error::StunChannelGoneSnafu.build()), -1020 probe.clone(), -1021 ) -1022 })?; -1023 result.latency = Some(delay); -1024 result.addr = Some(addr); -1025 Ok(result) -1026 } -1027 Ok(n) => { -1028 let err = stun_error::SendFullSnafu.build(); -1029 error!(%relay_addr, sent_len=n, req_len=req.len(), "{err:#}"); -1030 Err(ProbeErrorWithProbe::Error( -1031 probe_error::StunSnafu.into_error(err), -1032 probe.clone(), -1033 )) -1034 } -1035 Err(err) => { -1036 let kind = err.kind(); -1037 let err = stun_error::SendSnafu.into_error(err); -1038 -1039 // It is entirely normal that we are on a dual-stack machine with no -1040 // routed IPv6 network. So silence that case. -1041 // NetworkUnreachable and HostUnreachable are still experimental (io_error_more -1042 // #86442) but it is already emitted. So hack around this. -1043 match format!("{kind:?}").as_str() { -1044 "NetworkUnreachable" | "HostUnreachable" => { -1045 debug!(%relay_addr, "{err:#}"); -1046 Err(ProbeErrorWithProbe::AbortSet( -1047 probe_error::StunSnafu.into_error(err), -1048 probe.clone(), -1049 )) -1050 } -1051 _ => { -1052 // No need to log this, our caller does already log this. -1053 Err(ProbeErrorWithProbe::Error( -1054 probe_error::StunSnafu.into_error(err), -1055 probe.clone(), -1056 )) -1057 } -1058 } -1059 } -1060 } -1061} -1062 -1063#[cfg(not(wasm_browser))] -1064fn maybe_to_mapped_addr( -1065 ip_mapped_addrs: Option<IpMappedAddresses>, -1066 addr: SocketAddr, -1067) -> SocketAddr { -1068 if let Some(ip_mapped_addrs) = ip_mapped_addrs.as_ref() { -1069 return ip_mapped_addrs.get_or_register(addr).private_socket_addr(); -1070 } -1071 addr +884 #[cfg(not(wasm_browser))] +885 let relay_addr = get_relay_addr(&socket_state.dns_resolver, &relay_node, probe.proto()) +886 .await +887 .map_err(|e| { +888 ProbeErrorWithProbe::AbortSet( +889 probe_error::GetRelayAddrSnafu.into_error(e), +890 probe.clone(), +891 ) +892 })?; +893 +894 let mut result = ProbeReport::new(probe.clone()); +895 match probe { +896 #[cfg(not(wasm_browser))] +897 Probe::StunIpv4 { .. } | Probe::StunIpv6 { .. } => { +898 let maybe_sock = if matches!(probe, Probe::StunIpv4 { .. }) { +899 socket_state.stun_sock4.as_ref() +900 } else { +901 socket_state.stun_sock6.as_ref() +902 }; +903 match maybe_sock { +904 Some(sock) => { +905 result = run_stun_probe(sock, relay_addr, net_report, probe, &metrics).await?; +906 } +907 None => { +908 return Err(ProbeErrorWithProbe::AbortSet( +909 probe_error::StunSnafu.into_error(stun_error::NoSocketSnafu.build()), +910 probe.clone(), +911 )); +912 } +913 } +914 } +915 #[cfg(not(wasm_browser))] +916 Probe::IcmpV4 { .. } | Probe::IcmpV6 { .. } => { +917 result = run_icmp_probe(probe, relay_addr, pinger).await? +918 } +919 Probe::Https { ref node, .. } => { +920 debug!("sending probe HTTPS"); +921 match measure_https_latency( +922 #[cfg(not(wasm_browser))] +923 &socket_state.dns_resolver, +924 node, +925 #[cfg(any(test, feature = "test-utils"))] +926 insecure_skip_relay_cert_verify, +927 ) +928 .await +929 { +930 Ok((latency, ip)) => { +931 debug!(?latency, "latency"); +932 result.latency = Some(latency); +933 // We set these IPv4 and IPv6 but they're not really used +934 // and we don't necessarily set them both. If UDP is blocked +935 // and both IPv4 and IPv6 are available over TCP, it's basically +936 // random which fields end up getting set here. +937 // Since they're not needed, that's fine for now. +938 match ip { +939 IpAddr::V4(_) => result.ipv4_can_send = true, +940 IpAddr::V6(_) => result.ipv6_can_send = true, +941 } +942 } +943 Err(err) => { +944 warn!("https latency measurement failed: {:?}", err); +945 } +946 } +947 } +948 +949 #[cfg(not(wasm_browser))] +950 Probe::QuicIpv4 { ref node, .. } | Probe::QuicIpv6 { ref node, .. } => { +951 debug!("sending QUIC address discovery probe"); +952 let url = node.url.clone(); +953 match socket_state.quic_config { +954 Some(quic_config) => { +955 result = run_quic_probe( +956 quic_config, +957 url, +958 relay_addr, +959 probe, +960 socket_state.ip_mapped_addrs, +961 ) +962 .await?; +963 } +964 None => { +965 return Err(ProbeErrorWithProbe::AbortSet( +966 probe_error::QuicSnafu.into_error(quic_error::NoEndpointSnafu.build()), +967 probe.clone(), +968 )); +969 } +970 } +971 } +972 } +973 +974 trace!("probe successful"); +975 Ok(result) +976} +977 +978/// Run a STUN IPv4 or IPv6 probe. +979#[cfg(not(wasm_browser))] +980async fn run_stun_probe( +981 sock: &Arc<UdpSocket>, +982 relay_addr: SocketAddr, +983 net_report: net_report::Addr, +984 probe: Probe, +985 metrics: &Metrics, +986) -> Result<ProbeReport, ProbeErrorWithProbe> { +987 match probe.proto() { +988 ProbeProto::StunIpv4 => debug_assert!(relay_addr.is_ipv4()), +989 ProbeProto::StunIpv6 => debug_assert!(relay_addr.is_ipv6()), +990 _ => debug_assert!(false, "wrong probe"), +991 } +992 let txid = stun::TransactionId::default(); +993 let req = stun::request(txid); +994 +995 // Setup net_report to give us back the incoming STUN response. +996 let (stun_tx, stun_rx) = oneshot::channel(); +997 let (inflight_ready_tx, inflight_ready_rx) = oneshot::channel(); +998 net_report +999 .send(net_report::Message::InFlightStun( +1000 net_report::Inflight { +1001 txn: txid, +1002 start: Instant::now(), +1003 s: stun_tx, +1004 }, +1005 inflight_ready_tx, +1006 )) +1007 .await +1008 .map_err(|_| { +1009 ProbeErrorWithProbe::Error(probe_error::ClientGoneSnafu.build(), probe.clone()) +1010 })?; +1011 inflight_ready_rx.await.map_err(|_| { +1012 ProbeErrorWithProbe::Error(probe_error::ClientGoneSnafu.build(), probe.clone()) +1013 })?; +1014 +1015 // Send the probe. +1016 match sock.send_to(&req, relay_addr).await { +1017 Ok(n) if n == req.len() => { +1018 debug!(%relay_addr, %txid, "sending {} probe", probe.proto()); +1019 let mut result = ProbeReport::new(probe.clone()); +1020 +1021 if matches!(probe, Probe::StunIpv4 { .. }) { +1022 result.ipv4_can_send = true; +1023 metrics.stun_packets_sent_ipv4.inc(); +1024 } else { +1025 result.ipv6_can_send = true; +1026 metrics.stun_packets_sent_ipv6.inc(); +1027 } +1028 let (delay, addr) = stun_rx.await.map_err(|_| { +1029 ProbeErrorWithProbe::Error( +1030 probe_error::StunSnafu.into_error(stun_error::StunChannelGoneSnafu.build()), +1031 probe.clone(), +1032 ) +1033 })?; +1034 result.latency = Some(delay); +1035 result.addr = Some(addr); +1036 Ok(result) +1037 } +1038 Ok(n) => { +1039 let err = stun_error::SendFullSnafu.build(); +1040 error!(%relay_addr, sent_len=n, req_len=req.len(), "{err:#}"); +1041 Err(ProbeErrorWithProbe::Error( +1042 probe_error::StunSnafu.into_error(err), +1043 probe.clone(), +1044 )) +1045 } +1046 Err(err) => { +1047 let kind = err.kind(); +1048 let err = stun_error::SendSnafu.into_error(err); +1049 +1050 // It is entirely normal that we are on a dual-stack machine with no +1051 // routed IPv6 network. So silence that case. +1052 // NetworkUnreachable and HostUnreachable are still experimental (io_error_more +1053 // #86442) but it is already emitted. So hack around this. +1054 match format!("{kind:?}").as_str() { +1055 "NetworkUnreachable" | "HostUnreachable" => { +1056 debug!(%relay_addr, "{err:#}"); +1057 Err(ProbeErrorWithProbe::AbortSet( +1058 probe_error::StunSnafu.into_error(err), +1059 probe.clone(), +1060 )) +1061 } +1062 _ => { +1063 // No need to log this, our caller does already log this. +1064 Err(ProbeErrorWithProbe::Error( +1065 probe_error::StunSnafu.into_error(err), +1066 probe.clone(), +1067 )) +1068 } +1069 } +1070 } +1071 } 1072} 1073 -1074/// Run a QUIC address discovery probe. -1075#[cfg(not(wasm_browser))] -1076async fn run_quic_probe( -1077 quic_config: QuicConfig, -1078 url: RelayUrl, -1079 relay_addr: SocketAddr, -1080 probe: Probe, -1081 ip_mapped_addrs: Option<IpMappedAddresses>, -1082) -> Result<ProbeReport, ProbeErrorWithProbe> { -1083 match probe.proto() { -1084 ProbeProto::QuicIpv4 => debug_assert!(relay_addr.is_ipv4()), -1085 ProbeProto::QuicIpv6 => debug_assert!(relay_addr.is_ipv6()), -1086 _ => debug_assert!(false, "wrong probe"), -1087 } -1088 let relay_addr = maybe_to_mapped_addr(ip_mapped_addrs, relay_addr); -1089 let host = match url.host_str() { -1090 Some(host) => host, -1091 None => { -1092 return Err(ProbeErrorWithProbe::Error( -1093 probe_error::QuicSnafu.into_error(quic_error::InvalidUrlSnafu.build()), -1094 probe.clone(), -1095 )); -1096 } -1097 }; -1098 let quic_client = iroh_relay::quic::QuicClient::new(quic_config.ep, quic_config.client_config) -1099 .map_err(|e| { -1100 ProbeErrorWithProbe::Error( -1101 probe_error::QuicSnafu.into_error(quic_error::CreateClientSnafu.into_error(e)), -1102 probe.clone(), -1103 ) -1104 })?; -1105 let (addr, latency) = quic_client -1106 .get_addr_and_latency(relay_addr, host) -1107 .await -1108 .map_err(|e| { -1109 ProbeErrorWithProbe::Error( -1110 probe_error::QuicSnafu.into_error(quic_error::GetAddrSnafu.into_error(e)), -1111 probe.clone(), -1112 ) -1113 })?; -1114 let mut result = ProbeReport::new(probe.clone()); -1115 if matches!(probe, Probe::QuicIpv4 { .. }) { -1116 result.ipv4_can_send = true; -1117 } else { -1118 result.ipv6_can_send = true; -1119 } -1120 result.addr = Some(addr); -1121 result.latency = Some(latency); -1122 Ok(result) -1123} -1124 -1125#[cfg(not(wasm_browser))] -1126#[derive(Debug, Snafu)] -1127#[snafu(module)] -1128#[non_exhaustive] -1129enum CaptivePortalError { -1130 #[snafu(transparent)] -1131 DnsLookup { source: DnsError }, -1132 #[snafu(display("Creating HTTP client failed"))] -1133 CreateReqwestClient { source: reqwest::Error }, -1134 #[snafu(display("HTTP request failed"))] -1135 HttpRequest { source: reqwest::Error }, -1136} -1137 -1138/// Reports whether or not we think the system is behind a -1139/// captive portal, detected by making a request to a URL that we know should -1140/// return a "204 No Content" response and checking if that's what we get. -1141/// -1142/// The boolean return is whether we think we have a captive portal. -1143#[cfg(not(wasm_browser))] -1144async fn check_captive_portal( -1145 dns_resolver: &DnsResolver, -1146 dm: &RelayMap, -1147 preferred_relay: Option<RelayUrl>, -1148) -> Result<bool, CaptivePortalError> { -1149 // If we have a preferred relay node and we can use it for non-STUN requests, try that; -1150 // otherwise, pick a random one suitable for non-STUN requests. -1151 let preferred_relay = preferred_relay.and_then(|url| match dm.get_node(&url) { -1152 Some(node) if node.stun_only => Some(url), -1153 _ => None, -1154 }); -1155 -1156 let url = match preferred_relay { -1157 Some(url) => url, -1158 None => { -1159 let urls: Vec<_> = dm -1160 .nodes() -1161 .filter(|n| !n.stun_only) -1162 .map(|n| n.url.clone()) -1163 .collect(); -1164 if urls.is_empty() { -1165 debug!("No suitable relay node for captive portal check"); -1166 return Ok(false); -1167 } -1168 -1169 let i = (0..urls.len()) -1170 .choose(&mut rand::thread_rng()) -1171 .unwrap_or_default(); -1172 urls[i].clone() -1173 } -1174 }; -1175 -1176 let mut builder = reqwest::ClientBuilder::new().redirect(reqwest::redirect::Policy::none()); -1177 -1178 if let Some(Host::Domain(domain)) = url.host() { -1179 // Use our own resolver rather than getaddrinfo -1180 // -1181 // Be careful, a non-zero port will override the port in the URI. -1182 // -1183 // Ideally we would try to resolve **both** IPv4 and IPv6 rather than purely race -1184 // them. But our resolver doesn't support that yet. -1185 let addrs: Vec<_> = dns_resolver -1186 .lookup_ipv4_ipv6_staggered(domain, DNS_TIMEOUT, DNS_STAGGERING_MS) -1187 .await? -1188 .map(|ipaddr| SocketAddr::new(ipaddr, 0)) -1189 .collect(); -1190 builder = builder.resolve_to_addrs(domain, &addrs); -1191 } -1192 let client = builder -1193 .build() -1194 .context(captive_portal_error::CreateReqwestClientSnafu)?; -1195 -1196 // Note: the set of valid characters in a challenge and the total -1197 // length is limited; see is_challenge_char in bin/iroh-relay for more -1198 // details. -1199 -1200 let host_name = url.host_str().unwrap_or_default(); -1201 let challenge = format!("ts_{}", host_name); -1202 let portal_url = format!("http://{}/generate_204", host_name); -1203 let res = client -1204 .request(reqwest::Method::GET, portal_url) -1205 .header("X-Tailscale-Challenge", &challenge) -1206 .send() -1207 .await -1208 .context(captive_portal_error::HttpRequestSnafu)?; -1209 -1210 let expected_response = format!("response {challenge}"); -1211 let is_valid_response = res -1212 .headers() -1213 .get("X-Tailscale-Response") -1214 .map(|s| s.to_str().unwrap_or_default()) -1215 == Some(&expected_response); -1216 -1217 debug!( -1218 "check_captive_portal url={} status_code={} valid_response={}", -1219 res.url(), -1220 res.status(), -1221 is_valid_response, -1222 ); -1223 let has_captive = res.status() != 204 || !is_valid_response; -1224 -1225 Ok(has_captive) -1226} +1074#[cfg(not(wasm_browser))] +1075fn maybe_to_mapped_addr( +1076 ip_mapped_addrs: Option<IpMappedAddresses>, +1077 addr: SocketAddr, +1078) -> SocketAddr { +1079 if let Some(ip_mapped_addrs) = ip_mapped_addrs.as_ref() { +1080 return ip_mapped_addrs.get_or_register(addr).private_socket_addr(); +1081 } +1082 addr +1083} +1084 +1085/// Run a QUIC address discovery probe. +1086#[cfg(not(wasm_browser))] +1087async fn run_quic_probe( +1088 quic_config: QuicConfig, +1089 url: RelayUrl, +1090 relay_addr: SocketAddr, +1091 probe: Probe, +1092 ip_mapped_addrs: Option<IpMappedAddresses>, +1093) -> Result<ProbeReport, ProbeErrorWithProbe> { +1094 match probe.proto() { +1095 ProbeProto::QuicIpv4 => debug_assert!(relay_addr.is_ipv4()), +1096 ProbeProto::QuicIpv6 => debug_assert!(relay_addr.is_ipv6()), +1097 _ => debug_assert!(false, "wrong probe"), +1098 } +1099 let relay_addr = maybe_to_mapped_addr(ip_mapped_addrs, relay_addr); +1100 let host = match url.host_str() { +1101 Some(host) => host, +1102 None => { +1103 return Err(ProbeErrorWithProbe::Error( +1104 probe_error::QuicSnafu.into_error(quic_error::InvalidUrlSnafu.build()), +1105 probe.clone(), +1106 )); +1107 } +1108 }; +1109 let quic_client = iroh_relay::quic::QuicClient::new(quic_config.ep, quic_config.client_config) +1110 .map_err(|e| { +1111 ProbeErrorWithProbe::Error( +1112 probe_error::QuicSnafu.into_error(quic_error::CreateClientSnafu.into_error(e)), +1113 probe.clone(), +1114 ) +1115 })?; +1116 let (addr, latency) = quic_client +1117 .get_addr_and_latency(relay_addr, host) +1118 .await +1119 .map_err(|e| { +1120 ProbeErrorWithProbe::Error( +1121 probe_error::QuicSnafu.into_error(quic_error::GetAddrSnafu.into_error(e)), +1122 probe.clone(), +1123 ) +1124 })?; +1125 let mut result = ProbeReport::new(probe.clone()); +1126 if matches!(probe, Probe::QuicIpv4 { .. }) { +1127 result.ipv4_can_send = true; +1128 } else { +1129 result.ipv6_can_send = true; +1130 } +1131 result.addr = Some(addr); +1132 result.latency = Some(latency); +1133 Ok(result) +1134} +1135 +1136#[cfg(not(wasm_browser))] +1137#[derive(Debug, Snafu)] +1138#[snafu(module)] +1139#[non_exhaustive] +1140enum CaptivePortalError { +1141 #[snafu(transparent)] +1142 DnsLookup { source: StaggeredError<DnsError> }, +1143 #[snafu(display("Creating HTTP client failed"))] +1144 CreateReqwestClient { source: reqwest::Error }, +1145 #[snafu(display("HTTP request failed"))] +1146 HttpRequest { source: reqwest::Error }, +1147} +1148 +1149/// Reports whether or not we think the system is behind a +1150/// captive portal, detected by making a request to a URL that we know should +1151/// return a "204 No Content" response and checking if that's what we get. +1152/// +1153/// The boolean return is whether we think we have a captive portal. +1154#[cfg(not(wasm_browser))] +1155async fn check_captive_portal( +1156 dns_resolver: &DnsResolver, +1157 dm: &RelayMap, +1158 preferred_relay: Option<RelayUrl>, +1159) -> Result<bool, CaptivePortalError> { +1160 // If we have a preferred relay node and we can use it for non-STUN requests, try that; +1161 // otherwise, pick a random one suitable for non-STUN requests. +1162 let preferred_relay = preferred_relay.and_then(|url| match dm.get_node(&url) { +1163 Some(node) if node.stun_only => Some(url), +1164 _ => None, +1165 }); +1166 +1167 let url = match preferred_relay { +1168 Some(url) => url, +1169 None => { +1170 let urls: Vec<_> = dm +1171 .nodes() +1172 .filter(|n| !n.stun_only) +1173 .map(|n| n.url.clone()) +1174 .collect(); +1175 if urls.is_empty() { +1176 debug!("No suitable relay node for captive portal check"); +1177 return Ok(false); +1178 } +1179 +1180 let i = (0..urls.len()) +1181 .choose(&mut rand::thread_rng()) +1182 .unwrap_or_default(); +1183 urls[i].clone() +1184 } +1185 }; +1186 +1187 let mut builder = reqwest::ClientBuilder::new().redirect(reqwest::redirect::Policy::none()); +1188 +1189 if let Some(Host::Domain(domain)) = url.host() { +1190 // Use our own resolver rather than getaddrinfo +1191 // +1192 // Be careful, a non-zero port will override the port in the URI. +1193 // +1194 // Ideally we would try to resolve **both** IPv4 and IPv6 rather than purely race +1195 // them. But our resolver doesn't support that yet. +1196 let addrs: Vec<_> = dns_resolver +1197 .lookup_ipv4_ipv6_staggered(domain, DNS_TIMEOUT, DNS_STAGGERING_MS) +1198 .await? +1199 .map(|ipaddr| SocketAddr::new(ipaddr, 0)) +1200 .collect(); +1201 builder = builder.resolve_to_addrs(domain, &addrs); +1202 } +1203 let client = builder +1204 .build() +1205 .context(captive_portal_error::CreateReqwestClientSnafu)?; +1206 +1207 // Note: the set of valid characters in a challenge and the total +1208 // length is limited; see is_challenge_char in bin/iroh-relay for more +1209 // details. +1210 +1211 let host_name = url.host_str().unwrap_or_default(); +1212 let challenge = format!("ts_{}", host_name); +1213 let portal_url = format!("http://{}/generate_204", host_name); +1214 let res = client +1215 .request(reqwest::Method::GET, portal_url) +1216 .header("X-Tailscale-Challenge", &challenge) +1217 .send() +1218 .await +1219 .context(captive_portal_error::HttpRequestSnafu)?; +1220 +1221 let expected_response = format!("response {challenge}"); +1222 let is_valid_response = res +1223 .headers() +1224 .get("X-Tailscale-Response") +1225 .map(|s| s.to_str().unwrap_or_default()) +1226 == Some(&expected_response); 1227 -1228/// Returns the proper port based on the protocol of the probe. -1229fn get_port(relay_node: &RelayNode, proto: &ProbeProto) -> Option<u16> { -1230 match proto { -1231 #[cfg(not(wasm_browser))] -1232 ProbeProto::QuicIpv4 | ProbeProto::QuicIpv6 => { -1233 if let Some(ref quic) = relay_node.quic { -1234 if quic.port == 0 { -1235 Some(DEFAULT_RELAY_QUIC_PORT) -1236 } else { -1237 Some(quic.port) -1238 } -1239 } else { -1240 None -1241 } -1242 } -1243 _ => { -1244 if relay_node.stun_port == 0 { -1245 Some(DEFAULT_STUN_PORT) -1246 } else { -1247 Some(relay_node.stun_port) -1248 } -1249 } -1250 } -1251} -1252 -1253#[cfg(not(wasm_browser))] -1254#[derive(Debug, Snafu)] -1255#[snafu(module)] -1256#[non_exhaustive] -1257pub enum GetRelayAddrError { -1258 #[snafu(display("No valid hostname in the relay URL"))] -1259 InvalidHostname, -1260 #[snafu(display("No suitable relay address found"))] -1261 NoAddrFound, -1262 #[snafu(display("DNS lookup failed"))] -1263 DnsLookup { source: DnsError }, -1264 #[snafu(display("Relay node is not suitable for non-STUN probes"))] -1265 UnsupportedRelayNode, -1266 #[snafu(display("HTTPS probes are not implemented"))] -1267 UnsupportedHttps, -1268 #[snafu(display("No port available for this protocol"))] -1269 MissingPort, -1270} -1271 -1272/// Returns the IP address to use to communicate to this relay node. -1273/// -1274/// *proto* specifies the protocol of the probe. Depending on the protocol we may return -1275/// different results. Obviously IPv4 vs IPv6 but a [`RelayNode`] may also have disabled -1276/// some protocols. -1277/// -1278/// If the protocol is `QuicIpv4` or `QuicIpv6`, and `IpMappedAddresses` is not `None`, we -1279/// assume that we are running this net report with `iroh`, and need to provide mapped -1280/// addresses to the probe in order for it to function in the specialize iroh-quinn -1281/// endpoint that expects mapped addresses. -1282#[cfg(not(wasm_browser))] -1283async fn get_relay_addr( -1284 dns_resolver: &DnsResolver, -1285 relay_node: &RelayNode, -1286 proto: ProbeProto, -1287) -> Result<SocketAddr, GetRelayAddrError> { -1288 use snafu::OptionExt; -1289 -1290 if relay_node.stun_only && !matches!(proto, ProbeProto::StunIpv4 | ProbeProto::StunIpv6) { -1291 return Err(get_relay_addr_error::UnsupportedRelayNodeSnafu.build()); -1292 } -1293 let port = get_port(relay_node, &proto).context(get_relay_addr_error::MissingPortSnafu)?; -1294 -1295 match proto { -1296 ProbeProto::StunIpv4 | ProbeProto::IcmpV4 | ProbeProto::QuicIpv4 => { -1297 relay_lookup_ipv4_staggered(dns_resolver, relay_node, port).await -1298 } -1299 -1300 ProbeProto::StunIpv6 | ProbeProto::IcmpV6 | ProbeProto::QuicIpv6 => { -1301 relay_lookup_ipv6_staggered(dns_resolver, relay_node, port).await -1302 } -1303 -1304 ProbeProto::Https => Err(get_relay_addr_error::UnsupportedHttpsSnafu.build()), -1305 } -1306} -1307 -1308/// Do a staggared ipv4 DNS lookup based on [`RelayNode`] -1309/// -1310/// `port` is combined with the resolved [`std::net::Ipv4Addr`] to return a [`SocketAddr`] -1311#[cfg(not(wasm_browser))] -1312async fn relay_lookup_ipv4_staggered( -1313 dns_resolver: &DnsResolver, -1314 relay: &RelayNode, -1315 port: u16, -1316) -> Result<SocketAddr, GetRelayAddrError> { -1317 match relay.url.host() { -1318 Some(url::Host::Domain(hostname)) => { -1319 debug!(%hostname, "Performing DNS A lookup for relay addr"); -1320 match dns_resolver -1321 .lookup_ipv4_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS) -1322 .await -1323 { -1324 Ok(mut addrs) => addrs -1325 .next() -1326 .map(|ip| ip.to_canonical()) -1327 .map(|addr| SocketAddr::new(addr, port)) -1328 .ok_or(get_relay_addr_error::NoAddrFoundSnafu.build()), -1329 Err(err) => Err(get_relay_addr_error::DnsLookupSnafu.into_error(err)), -1330 } -1331 } -1332 Some(url::Host::Ipv4(addr)) => Ok(SocketAddr::new(addr.into(), port)), -1333 Some(url::Host::Ipv6(_addr)) => Err(get_relay_addr_error::NoAddrFoundSnafu.build()), -1334 None => Err(get_relay_addr_error::InvalidHostnameSnafu.build()), -1335 } -1336} -1337 -1338/// Do a staggared ipv6 DNS lookup based on [`RelayNode`] -1339/// -1340/// `port` is combined with the resolved [`std::net::Ipv6Addr`] to return a [`SocketAddr`] -1341#[cfg(not(wasm_browser))] -1342async fn relay_lookup_ipv6_staggered( -1343 dns_resolver: &DnsResolver, -1344 relay: &RelayNode, -1345 port: u16, -1346) -> Result<SocketAddr, GetRelayAddrError> { -1347 match relay.url.host() { -1348 Some(url::Host::Domain(hostname)) => { -1349 debug!(%hostname, "Performing DNS AAAA lookup for relay addr"); -1350 match dns_resolver -1351 .lookup_ipv6_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS) -1352 .await -1353 { -1354 Ok(mut addrs) => addrs -1355 .next() -1356 .map(|ip| ip.to_canonical()) -1357 .map(|addr| SocketAddr::new(addr, port)) -1358 .ok_or(get_relay_addr_error::NoAddrFoundSnafu.build()), -1359 Err(err) => Err(get_relay_addr_error::DnsLookupSnafu.into_error(err)), -1360 } -1361 } -1362 Some(url::Host::Ipv4(addr)) => Ok(SocketAddr::new(addr.into(), port)), -1363 Some(url::Host::Ipv6(_addr)) => Err(get_relay_addr_error::NoAddrFoundSnafu.build()), -1364 None => Err(get_relay_addr_error::InvalidHostnameSnafu.build()), -1365 } -1366} -1367 -1368/// Runs an ICMP IPv4 or IPv6 probe. -1369/// -1370/// The `pinger` is passed in so the ping sockets are only bound once -1371/// for the probe set. -1372#[cfg(not(wasm_browser))] -1373async fn run_icmp_probe( -1374 probe: Probe, -1375 relay_addr: SocketAddr, -1376 pinger: Pinger, -1377) -> Result<ProbeReport, ProbeErrorWithProbe> { -1378 match probe.proto() { -1379 ProbeProto::IcmpV4 => debug_assert!(relay_addr.is_ipv4()), -1380 ProbeProto::IcmpV6 => debug_assert!(relay_addr.is_ipv6()), -1381 _ => debug_assert!(false, "wrong probe"), -1382 } -1383 const DATA: &[u8; 15] = b"iroh icmp probe"; -1384 debug!(dst = %relay_addr, len = DATA.len(), "ICMP Ping started"); -1385 let latency = pinger -1386 .send(relay_addr.ip(), DATA) -1387 .await -1388 .map_err(|err| match err { -1389 PingError::CreateClientIpv4 { .. } | PingError::CreateClientIpv6 { .. } => { -1390 ProbeErrorWithProbe::AbortSet(probe_error::IcmpSnafu.into_error(err), probe.clone()) -1391 } -1392 #[cfg(not(wasm_browser))] -1393 PingError::Ping { .. } => { -1394 ProbeErrorWithProbe::Error(probe_error::IcmpSnafu.into_error(err), probe.clone()) -1395 } -1396 })?; -1397 debug!(dst = %relay_addr, len = DATA.len(), ?latency, "ICMP ping done"); -1398 let mut report = ProbeReport::new(probe); -1399 report.latency = Some(latency); -1400 match relay_addr { -1401 SocketAddr::V4(_) => { -1402 report.ipv4_can_send = true; -1403 report.icmpv4 = Some(true); -1404 } -1405 SocketAddr::V6(_) => { -1406 report.ipv6_can_send = true; -1407 report.icmpv6 = Some(true); -1408 } -1409 } -1410 Ok(report) -1411} -1412 -1413#[derive(Debug, Snafu)] -1414#[snafu(module)] -1415#[non_exhaustive] -1416enum MeasureHttpsLatencyError { -1417 #[snafu(transparent)] -1418 InvalidUrl { source: url::ParseError }, -1419 #[cfg(not(wasm_browser))] -1420 #[snafu(transparent)] -1421 DnsLookup { source: DnsError }, -1422 #[cfg(not(wasm_browser))] -1423 #[snafu(display("Invalid certificate"))] -1424 InvalidCertificate { source: reqwest::Error }, -1425 #[snafu(display("Creating HTTP client failed"))] -1426 CreateReqwestClient { source: reqwest::Error }, -1427 #[snafu(display("HTTP request failed"))] -1428 HttpRequest { source: reqwest::Error }, -1429 #[snafu(display("Error response from server {status}: {:?}", status.canonical_reason()))] -1430 InvalidResponse { status: StatusCode }, -1431} -1432 -1433/// Executes an HTTPS probe. -1434/// -1435/// If `certs` is provided they will be added to the trusted root certificates, allowing the -1436/// use of self-signed certificates for servers. Currently this is used for testing. -1437#[allow(clippy::unused_async)] -1438async fn measure_https_latency( -1439 #[cfg(not(wasm_browser))] dns_resolver: &DnsResolver, -1440 node: &RelayNode, -1441 certs: Option<Vec<rustls::pki_types::CertificateDer<'static>>>, -1442) -> Result<(Duration, IpAddr), MeasureHttpsLatencyError> { -1443 let url = node.url.join(RELAY_PROBE_PATH)?; -1444 -1445 // This should also use same connection establishment as relay client itself, which -1446 // needs to be more configurable so users can do more crazy things: -1447 // https://github.com/n0-computer/iroh/issues/2901 -1448 let mut builder = reqwest::ClientBuilder::new(); -1449 -1450 #[cfg(not(wasm_browser))] -1451 { -1452 builder = builder.redirect(reqwest::redirect::Policy::none()); -1453 } -1454 -1455 #[cfg(not(wasm_browser))] -1456 if let Some(Host::Domain(domain)) = url.host() { -1457 // Use our own resolver rather than getaddrinfo -1458 // -1459 // Be careful, a non-zero port will override the port in the URI. -1460 // -1461 // The relay Client uses `.lookup_ipv4_ipv6` to connect, so use the same function -1462 // but staggered for reliability. Ideally this tries to resolve **both** IPv4 and -1463 // IPv6 though. But our resolver does not have a function for that yet. -1464 let addrs: Vec<_> = dns_resolver -1465 .lookup_ipv4_ipv6_staggered(domain, DNS_TIMEOUT, DNS_STAGGERING_MS) -1466 .await? -1467 .map(|ipaddr| SocketAddr::new(ipaddr, 0)) -1468 .collect(); -1469 builder = builder.resolve_to_addrs(domain, &addrs); -1470 } -1471 -1472 #[cfg(not(wasm_browser))] -1473 if let Some(certs) = certs { -1474 for cert in certs { -1475 let cert = reqwest::Certificate::from_der(&cert) -1476 .context(measure_https_latency_error::InvalidCertificateSnafu)?; -1477 builder = builder.add_root_certificate(cert); -1478 } -1479 } -1480 let client = builder -1481 .build() -1482 .context(measure_https_latency_error::CreateReqwestClientSnafu)?; -1483 -1484 let start = Instant::now(); -1485 let response = client -1486 .request(reqwest::Method::GET, url) -1487 .send() -1488 .await -1489 .context(measure_https_latency_error::HttpRequestSnafu)?; -1490 let latency = start.elapsed(); -1491 if response.status().is_success() { -1492 // Only `None` if a different hyper HttpConnector in the request. -1493 #[cfg(not(wasm_browser))] -1494 let remote_ip = response -1495 .remote_addr() -1496 .expect("missing HttpInfo from HttpConnector") -1497 .ip(); -1498 #[cfg(wasm_browser)] -1499 let remote_ip = IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED); -1500 -1501 // Drain the response body to be nice to the server, up to a limit. -1502 const MAX_BODY_SIZE: usize = 8 << 10; // 8 KiB -1503 let mut body_size = 0; -1504 let mut stream = response.bytes_stream(); -1505 // ignore failing frames -1506 while let Some(Ok(chunk)) = stream.next().await { -1507 body_size += chunk.len(); -1508 if body_size >= MAX_BODY_SIZE { -1509 break; -1510 } -1511 } -1512 -1513 Ok((latency, remote_ip)) -1514 } else { -1515 Err(measure_https_latency_error::InvalidResponseSnafu { -1516 status: response.status(), -1517 } -1518 .build()) -1519 } -1520} -1521 -1522/// Updates a net_report [`Report`] with a new [`ProbeReport`]. -1523fn update_report(report: &mut Report, probe_report: ProbeReport) { -1524 let relay_node = probe_report.probe.node(); -1525 if let Some(latency) = probe_report.latency { -1526 report -1527 .relay_latency -1528 .update_relay(relay_node.url.clone(), latency); +1228 debug!( +1229 "check_captive_portal url={} status_code={} valid_response={}", +1230 res.url(), +1231 res.status(), +1232 is_valid_response, +1233 ); +1234 let has_captive = res.status() != 204 || !is_valid_response; +1235 +1236 Ok(has_captive) +1237} +1238 +1239/// Returns the proper port based on the protocol of the probe. +1240fn get_port(relay_node: &RelayNode, proto: &ProbeProto) -> Option<u16> { +1241 match proto { +1242 #[cfg(not(wasm_browser))] +1243 ProbeProto::QuicIpv4 | ProbeProto::QuicIpv6 => { +1244 if let Some(ref quic) = relay_node.quic { +1245 if quic.port == 0 { +1246 Some(DEFAULT_RELAY_QUIC_PORT) +1247 } else { +1248 Some(quic.port) +1249 } +1250 } else { +1251 None +1252 } +1253 } +1254 _ => { +1255 if relay_node.stun_port == 0 { +1256 Some(DEFAULT_STUN_PORT) +1257 } else { +1258 Some(relay_node.stun_port) +1259 } +1260 } +1261 } +1262} +1263 +1264#[cfg(not(wasm_browser))] +1265#[derive(Debug, Snafu)] +1266#[snafu(module)] +1267#[non_exhaustive] +1268pub enum GetRelayAddrError { +1269 #[snafu(display("No valid hostname in the relay URL"))] +1270 InvalidHostname, +1271 #[snafu(display("No suitable relay address found"))] +1272 NoAddrFound, +1273 #[snafu(display("DNS lookup failed"))] +1274 DnsLookup { source: StaggeredError<DnsError> }, +1275 #[snafu(display("Relay node is not suitable for non-STUN probes"))] +1276 UnsupportedRelayNode, +1277 #[snafu(display("HTTPS probes are not implemented"))] +1278 UnsupportedHttps, +1279 #[snafu(display("No port available for this protocol"))] +1280 MissingPort, +1281} +1282 +1283/// Returns the IP address to use to communicate to this relay node. +1284/// +1285/// *proto* specifies the protocol of the probe. Depending on the protocol we may return +1286/// different results. Obviously IPv4 vs IPv6 but a [`RelayNode`] may also have disabled +1287/// some protocols. +1288/// +1289/// If the protocol is `QuicIpv4` or `QuicIpv6`, and `IpMappedAddresses` is not `None`, we +1290/// assume that we are running this net report with `iroh`, and need to provide mapped +1291/// addresses to the probe in order for it to function in the specialize iroh-quinn +1292/// endpoint that expects mapped addresses. +1293#[cfg(not(wasm_browser))] +1294async fn get_relay_addr( +1295 dns_resolver: &DnsResolver, +1296 relay_node: &RelayNode, +1297 proto: ProbeProto, +1298) -> Result<SocketAddr, GetRelayAddrError> { +1299 use snafu::OptionExt; +1300 +1301 if relay_node.stun_only && !matches!(proto, ProbeProto::StunIpv4 | ProbeProto::StunIpv6) { +1302 return Err(get_relay_addr_error::UnsupportedRelayNodeSnafu.build()); +1303 } +1304 let port = get_port(relay_node, &proto).context(get_relay_addr_error::MissingPortSnafu)?; +1305 +1306 match proto { +1307 ProbeProto::StunIpv4 | ProbeProto::IcmpV4 | ProbeProto::QuicIpv4 => { +1308 relay_lookup_ipv4_staggered(dns_resolver, relay_node, port).await +1309 } +1310 +1311 ProbeProto::StunIpv6 | ProbeProto::IcmpV6 | ProbeProto::QuicIpv6 => { +1312 relay_lookup_ipv6_staggered(dns_resolver, relay_node, port).await +1313 } +1314 +1315 ProbeProto::Https => Err(get_relay_addr_error::UnsupportedHttpsSnafu.build()), +1316 } +1317} +1318 +1319/// Do a staggared ipv4 DNS lookup based on [`RelayNode`] +1320/// +1321/// `port` is combined with the resolved [`std::net::Ipv4Addr`] to return a [`SocketAddr`] +1322#[cfg(not(wasm_browser))] +1323async fn relay_lookup_ipv4_staggered( +1324 dns_resolver: &DnsResolver, +1325 relay: &RelayNode, +1326 port: u16, +1327) -> Result<SocketAddr, GetRelayAddrError> { +1328 match relay.url.host() { +1329 Some(url::Host::Domain(hostname)) => { +1330 debug!(%hostname, "Performing DNS A lookup for relay addr"); +1331 match dns_resolver +1332 .lookup_ipv4_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS) +1333 .await +1334 { +1335 Ok(mut addrs) => addrs +1336 .next() +1337 .map(|ip| ip.to_canonical()) +1338 .map(|addr| { +1339 debug_assert!(addr.is_ipv4(), "bad DNS lookup: {:?}", addr); +1340 SocketAddr::new(addr, port) +1341 }) +1342 .ok_or(get_relay_addr_error::NoAddrFoundSnafu.build()), +1343 Err(err) => Err(get_relay_addr_error::DnsLookupSnafu.into_error(err)), +1344 } +1345 } +1346 Some(url::Host::Ipv4(addr)) => Ok(SocketAddr::new(addr.into(), port)), +1347 Some(url::Host::Ipv6(_addr)) => Err(get_relay_addr_error::NoAddrFoundSnafu.build()), +1348 None => Err(get_relay_addr_error::InvalidHostnameSnafu.build()), +1349 } +1350} +1351 +1352/// Do a staggared ipv6 DNS lookup based on [`RelayNode`] +1353/// +1354/// `port` is combined with the resolved [`std::net::Ipv6Addr`] to return a [`SocketAddr`] +1355#[cfg(not(wasm_browser))] +1356async fn relay_lookup_ipv6_staggered( +1357 dns_resolver: &DnsResolver, +1358 relay: &RelayNode, +1359 port: u16, +1360) -> Result<SocketAddr, GetRelayAddrError> { +1361 match relay.url.host() { +1362 Some(url::Host::Domain(hostname)) => { +1363 debug!(%hostname, "Performing DNS AAAA lookup for relay addr"); +1364 match dns_resolver +1365 .lookup_ipv6_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS) +1366 .await +1367 { +1368 Ok(mut addrs) => addrs +1369 .next() +1370 .map(|addr| { +1371 debug_assert!(addr.is_ipv6(), "bad DNS lookup: {:?}", addr); +1372 SocketAddr::new(addr, port) +1373 }) +1374 .ok_or(get_relay_addr_error::NoAddrFoundSnafu.build()), +1375 Err(err) => Err(get_relay_addr_error::DnsLookupSnafu.into_error(err)), +1376 } +1377 } +1378 Some(url::Host::Ipv4(_addr)) => Err(get_relay_addr_error::NoAddrFoundSnafu.build()), +1379 Some(url::Host::Ipv6(addr)) => Ok(SocketAddr::new(addr.into(), port)), +1380 None => Err(get_relay_addr_error::InvalidHostnameSnafu.build()), +1381 } +1382} +1383 +1384/// Runs an ICMP IPv4 or IPv6 probe. +1385/// +1386/// The `pinger` is passed in so the ping sockets are only bound once +1387/// for the probe set. +1388#[cfg(not(wasm_browser))] +1389async fn run_icmp_probe( +1390 probe: Probe, +1391 relay_addr: SocketAddr, +1392 pinger: Pinger, +1393) -> Result<ProbeReport, ProbeErrorWithProbe> { +1394 match probe.proto() { +1395 ProbeProto::IcmpV4 => debug_assert!(relay_addr.is_ipv4()), +1396 ProbeProto::IcmpV6 => debug_assert!(relay_addr.is_ipv6()), +1397 _ => debug_assert!(false, "wrong probe"), +1398 } +1399 const DATA: &[u8; 15] = b"iroh icmp probe"; +1400 debug!(dst = %relay_addr, len = DATA.len(), "ICMP Ping started"); +1401 let latency = pinger +1402 .send(relay_addr.ip(), DATA) +1403 .await +1404 .map_err(|err| match err { +1405 PingError::CreateClientIpv4 { .. } | PingError::CreateClientIpv6 { .. } => { +1406 ProbeErrorWithProbe::AbortSet(probe_error::IcmpSnafu.into_error(err), probe.clone()) +1407 } +1408 #[cfg(not(wasm_browser))] +1409 PingError::Ping { .. } => { +1410 ProbeErrorWithProbe::Error(probe_error::IcmpSnafu.into_error(err), probe.clone()) +1411 } +1412 })?; +1413 debug!(dst = %relay_addr, len = DATA.len(), ?latency, "ICMP ping done"); +1414 let mut report = ProbeReport::new(probe); +1415 report.latency = Some(latency); +1416 match relay_addr { +1417 SocketAddr::V4(_) => { +1418 report.ipv4_can_send = true; +1419 report.icmpv4 = Some(true); +1420 } +1421 SocketAddr::V6(_) => { +1422 report.ipv6_can_send = true; +1423 report.icmpv6 = Some(true); +1424 } +1425 } +1426 Ok(report) +1427} +1428 +1429#[derive(Debug, Snafu)] +1430#[snafu(module)] +1431#[non_exhaustive] +1432enum MeasureHttpsLatencyError { +1433 #[snafu(transparent)] +1434 InvalidUrl { source: url::ParseError }, +1435 #[cfg(not(wasm_browser))] +1436 #[snafu(transparent)] +1437 DnsLookup { source: StaggeredError<DnsError> }, +1438 #[snafu(display("Creating HTTP client failed"))] +1439 CreateReqwestClient { source: reqwest::Error }, +1440 #[snafu(display("HTTP request failed"))] +1441 HttpRequest { source: reqwest::Error }, +1442 #[snafu(display("Error response from server {status}: {:?}", status.canonical_reason()))] +1443 InvalidResponse { status: StatusCode }, +1444} +1445 +1446/// Executes an HTTPS probe. +1447/// +1448/// If `certs` is provided they will be added to the trusted root certificates, allowing the +1449/// use of self-signed certificates for servers. Currently this is used for testing. +1450#[allow(clippy::unused_async)] +1451async fn measure_https_latency( +1452 #[cfg(not(wasm_browser))] dns_resolver: &DnsResolver, +1453 node: &RelayNode, +1454 #[cfg(any(test, feature = "test-utils"))] insecure_skip_relay_cert_verify: bool, +1455) -> Result<(Duration, IpAddr), MeasureHttpsLatencyError> { +1456 let url = node.url.join(RELAY_PROBE_PATH)?; +1457 +1458 // This should also use same connection establishment as relay client itself, which +1459 // needs to be more configurable so users can do more crazy things: +1460 // https://github.com/n0-computer/iroh/issues/2901 +1461 let mut builder = reqwest::ClientBuilder::new(); +1462 +1463 #[cfg(not(wasm_browser))] +1464 { +1465 builder = builder.redirect(reqwest::redirect::Policy::none()); +1466 } +1467 +1468 #[cfg(not(wasm_browser))] +1469 if let Some(Host::Domain(domain)) = url.host() { +1470 // Use our own resolver rather than getaddrinfo +1471 // +1472 // Be careful, a non-zero port will override the port in the URI. +1473 // +1474 // The relay Client uses `.lookup_ipv4_ipv6` to connect, so use the same function +1475 // but staggered for reliability. Ideally this tries to resolve **both** IPv4 and +1476 // IPv6 though. But our resolver does not have a function for that yet. +1477 let addrs: Vec<_> = dns_resolver +1478 .lookup_ipv4_ipv6_staggered(domain, DNS_TIMEOUT, DNS_STAGGERING_MS) +1479 .await? +1480 .map(|ipaddr| SocketAddr::new(ipaddr, 0)) +1481 .collect(); +1482 builder = builder.resolve_to_addrs(domain, &addrs); +1483 } +1484 +1485 #[cfg(all(not(wasm_browser), any(test, feature = "test-utils")))] +1486 let builder = builder.danger_accept_invalid_certs(insecure_skip_relay_cert_verify); +1487 +1488 let client = builder +1489 .build() +1490 .context(measure_https_latency_error::CreateReqwestClientSnafu)?; +1491 +1492 let start = Instant::now(); +1493 let response = client +1494 .request(reqwest::Method::GET, url) +1495 .send() +1496 .await +1497 .context(measure_https_latency_error::HttpRequestSnafu)?; +1498 let latency = start.elapsed(); +1499 if response.status().is_success() { +1500 // Only `None` if a different hyper HttpConnector in the request. +1501 #[cfg(not(wasm_browser))] +1502 let remote_ip = response +1503 .remote_addr() +1504 .expect("missing HttpInfo from HttpConnector") +1505 .ip(); +1506 #[cfg(wasm_browser)] +1507 let remote_ip = IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED); +1508 +1509 // Drain the response body to be nice to the server, up to a limit. +1510 const MAX_BODY_SIZE: usize = 8 << 10; // 8 KiB +1511 let mut body_size = 0; +1512 let mut stream = response.bytes_stream(); +1513 // ignore failing frames +1514 while let Some(Ok(chunk)) = stream.next().await { +1515 body_size += chunk.len(); +1516 if body_size >= MAX_BODY_SIZE { +1517 break; +1518 } +1519 } +1520 +1521 Ok((latency, remote_ip)) +1522 } else { +1523 Err(measure_https_latency_error::InvalidResponseSnafu { +1524 status: response.status(), +1525 } +1526 .build()) +1527 } +1528} 1529 -1530 #[cfg(not(wasm_browser))] -1531 if matches!( -1532 probe_report.probe.proto(), -1533 ProbeProto::StunIpv4 -1534 | ProbeProto::StunIpv6 -1535 | ProbeProto::QuicIpv4 -1536 | ProbeProto::QuicIpv6 -1537 ) { -1538 report.udp = true; -1539 -1540 match probe_report.addr { -1541 Some(SocketAddr::V4(ipp)) => { -1542 report.ipv4 = true; -1543 report -1544 .relay_v4_latency -1545 .update_relay(relay_node.url.clone(), latency); -1546 if report.global_v4.is_none() { -1547 report.global_v4 = Some(ipp); -1548 } else if report.global_v4 != Some(ipp) { -1549 report.mapping_varies_by_dest_ip = Some(true); -1550 } else if report.mapping_varies_by_dest_ip.is_none() { -1551 report.mapping_varies_by_dest_ip = Some(false); -1552 } -1553 } -1554 Some(SocketAddr::V6(ipp)) => { -1555 report.ipv6 = true; -1556 report -1557 .relay_v6_latency -1558 .update_relay(relay_node.url.clone(), latency); -1559 if report.global_v6.is_none() { -1560 report.global_v6 = Some(ipp); -1561 } else if report.global_v6 != Some(ipp) { -1562 report.mapping_varies_by_dest_ipv6 = Some(true); -1563 warn!("IPv6 Address detected by STUN varies by destination"); -1564 } else if report.mapping_varies_by_dest_ipv6.is_none() { -1565 report.mapping_varies_by_dest_ipv6 = Some(false); -1566 } -1567 } -1568 None => { -1569 // If we are here we had a relay server latency reported from a STUN probe. -1570 // Thus we must have a reported address. -1571 debug_assert!(probe_report.addr.is_some()); -1572 } -1573 } -1574 } -1575 } -1576 report.ipv4_can_send |= probe_report.ipv4_can_send; -1577 report.ipv6_can_send |= probe_report.ipv6_can_send; -1578 report.icmpv4 = report -1579 .icmpv4 -1580 .map(|val| val || probe_report.icmpv4.unwrap_or_default()) -1581 .or(probe_report.icmpv4); -1582 report.icmpv6 = report -1583 .icmpv6 -1584 .map(|val| val || probe_report.icmpv6.unwrap_or_default()) -1585 .or(probe_report.icmpv6); -1586} -1587 -1588/// Resolves to pending if the inner is `None`. -1589#[derive(Debug)] -1590pub(crate) struct MaybeFuture<T> { -1591 /// Future to be polled. -1592 pub inner: Option<T>, -1593} -1594 -1595// NOTE: explicit implementation to bypass derive unnecessary bounds -1596impl<T> Default for MaybeFuture<T> { -1597 fn default() -> Self { -1598 MaybeFuture { inner: None } -1599 } -1600} -1601 -1602impl<T: Future + Unpin> Future for MaybeFuture<T> { -1603 type Output = T::Output; -1604 -1605 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { -1606 match self.inner { -1607 Some(ref mut t) => Pin::new(t).poll(cx), -1608 None => Poll::Pending, -1609 } -1610 } -1611} +1530/// Updates a net_report [`Report`] with a new [`ProbeReport`]. +1531fn update_report(report: &mut Report, probe_report: ProbeReport) { +1532 let relay_node = probe_report.probe.node(); +1533 if let Some(latency) = probe_report.latency { +1534 report +1535 .relay_latency +1536 .update_relay(relay_node.url.clone(), latency); +1537 +1538 #[cfg(not(wasm_browser))] +1539 if matches!( +1540 probe_report.probe.proto(), +1541 ProbeProto::StunIpv4 +1542 | ProbeProto::StunIpv6 +1543 | ProbeProto::QuicIpv4 +1544 | ProbeProto::QuicIpv6 +1545 ) { +1546 report.udp = true; +1547 +1548 match probe_report.addr { +1549 Some(SocketAddr::V4(ipp)) => { +1550 report.ipv4 = true; +1551 report +1552 .relay_v4_latency +1553 .update_relay(relay_node.url.clone(), latency); +1554 if report.global_v4.is_none() { +1555 report.global_v4 = Some(ipp); +1556 } else if report.global_v4 != Some(ipp) { +1557 report.mapping_varies_by_dest_ip = Some(true); +1558 } else if report.mapping_varies_by_dest_ip.is_none() { +1559 report.mapping_varies_by_dest_ip = Some(false); +1560 } +1561 } +1562 Some(SocketAddr::V6(ipp)) => { +1563 report.ipv6 = true; +1564 report +1565 .relay_v6_latency +1566 .update_relay(relay_node.url.clone(), latency); +1567 if report.global_v6.is_none() { +1568 report.global_v6 = Some(ipp); +1569 } else if report.global_v6 != Some(ipp) { +1570 report.mapping_varies_by_dest_ipv6 = Some(true); +1571 warn!("IPv6 Address detected by STUN varies by destination"); +1572 } else if report.mapping_varies_by_dest_ipv6.is_none() { +1573 report.mapping_varies_by_dest_ipv6 = Some(false); +1574 } +1575 } +1576 None => { +1577 // If we are here we had a relay server latency reported from a STUN probe. +1578 // Thus we must have a reported address. +1579 debug_assert!(probe_report.addr.is_some()); +1580 } +1581 } +1582 } +1583 } +1584 report.ipv4_can_send |= probe_report.ipv4_can_send; +1585 report.ipv6_can_send |= probe_report.ipv6_can_send; +1586 report.icmpv4 = report +1587 .icmpv4 +1588 .map(|val| val || probe_report.icmpv4.unwrap_or_default()) +1589 .or(probe_report.icmpv4); +1590 report.icmpv6 = report +1591 .icmpv6 +1592 .map(|val| val || probe_report.icmpv6.unwrap_or_default()) +1593 .or(probe_report.icmpv6); +1594} +1595 +1596/// Resolves to pending if the inner is `None`. +1597#[derive(Debug)] +1598pub(crate) struct MaybeFuture<T> { +1599 /// Future to be polled. +1600 pub inner: Option<T>, +1601} +1602 +1603// NOTE: explicit implementation to bypass derive unnecessary bounds +1604impl<T> Default for MaybeFuture<T> { +1605 fn default() -> Self { +1606 MaybeFuture { inner: None } +1607 } +1608} +1609 +1610impl<T: Future + Unpin> Future for MaybeFuture<T> { +1611 type Output = T::Output; 1612 -1613#[cfg(test)] -1614mod tests { -1615 use std::net::{Ipv4Addr, Ipv6Addr}; -1616 -1617 use n0_snafu::{Result, ResultExt}; -1618 use tracing_test::traced_test; -1619 -1620 use super::{super::test_utils, *}; -1621 use crate::net_report::dns; -1622 -1623 #[tokio::test] -1624 #[traced_test] -1625 async fn test_update_report_stun_working() { -1626 let (_server_a, relay_a) = test_utils::relay().await; -1627 let (_server_b, relay_b) = test_utils::relay().await; -1628 -1629 let mut report = Report::default(); -1630 let relay_a = Arc::new(relay_a); -1631 let relay_b = Arc::new(relay_b); -1632 -1633 // A STUN IPv4 probe from the the first relay server. -1634 let probe_report_a = ProbeReport { -1635 ipv4_can_send: true, -1636 ipv6_can_send: false, -1637 icmpv4: None, -1638 icmpv6: None, -1639 latency: Some(Duration::from_millis(5)), -1640 probe: Probe::StunIpv4 { -1641 delay: Duration::ZERO, -1642 node: relay_a.clone(), -1643 }, -1644 addr: Some((Ipv4Addr::new(203, 0, 113, 1), 1234).into()), -1645 }; -1646 update_report(&mut report, probe_report_a.clone()); -1647 -1648 assert!(report.udp); -1649 assert_eq!( -1650 report.relay_latency.get(&relay_a.url).unwrap(), -1651 Duration::from_millis(5) -1652 ); -1653 assert_eq!( -1654 report.relay_v4_latency.get(&relay_a.url).unwrap(), -1655 Duration::from_millis(5) -1656 ); -1657 assert!(report.ipv4_can_send); -1658 assert!(!report.ipv6_can_send); -1659 -1660 // A second STUN IPv4 probe, same external IP detected but slower. -1661 let probe_report_b = ProbeReport { -1662 latency: Some(Duration::from_millis(8)), -1663 probe: Probe::StunIpv4 { -1664 delay: Duration::ZERO, -1665 node: relay_b.clone(), -1666 }, -1667 ..probe_report_a -1668 }; -1669 update_report(&mut report, probe_report_b); -1670 -1671 assert!(report.udp); -1672 assert_eq!( -1673 report.relay_latency.get(&relay_a.url).unwrap(), -1674 Duration::from_millis(5) -1675 ); -1676 assert_eq!( -1677 report.relay_v4_latency.get(&relay_a.url).unwrap(), -1678 Duration::from_millis(5) -1679 ); -1680 assert!(report.ipv4_can_send); -1681 assert!(!report.ipv6_can_send); -1682 -1683 // A STUN IPv6 probe, this one is faster. -1684 let probe_report_a_ipv6 = ProbeReport { -1685 ipv4_can_send: false, -1686 ipv6_can_send: true, -1687 icmpv4: None, -1688 icmpv6: None, -1689 latency: Some(Duration::from_millis(4)), -1690 probe: Probe::StunIpv6 { -1691 delay: Duration::ZERO, -1692 node: relay_a.clone(), -1693 }, -1694 addr: Some((Ipv6Addr::new(2001, 0xdb8, 0, 0, 0, 0, 0, 1), 1234).into()), -1695 }; -1696 update_report(&mut report, probe_report_a_ipv6); -1697 -1698 assert!(report.udp); -1699 assert_eq!( -1700 report.relay_latency.get(&relay_a.url).unwrap(), -1701 Duration::from_millis(4) -1702 ); -1703 assert_eq!( -1704 report.relay_v6_latency.get(&relay_a.url).unwrap(), -1705 Duration::from_millis(4) -1706 ); -1707 assert!(report.ipv4_can_send); -1708 assert!(report.ipv6_can_send); -1709 } -1710 -1711 #[tokio::test] -1712 #[traced_test] -1713 async fn test_update_report_icmp() { -1714 let (_server_a, relay_a) = test_utils::relay().await; -1715 let (_server_b, relay_b) = test_utils::relay().await; -1716 let relay_a = Arc::new(relay_a); -1717 let relay_b = Arc::new(relay_b); +1613 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { +1614 match self.inner { +1615 Some(ref mut t) => Pin::new(t).poll(cx), +1616 None => Poll::Pending, +1617 } +1618 } +1619} +1620 +1621#[cfg(test)] +1622mod tests { +1623 use std::net::{Ipv4Addr, Ipv6Addr}; +1624 +1625 use n0_snafu::{Result, ResultExt}; +1626 use tracing_test::traced_test; +1627 +1628 use super::{super::test_utils, *}; +1629 use crate::net_report::dns; +1630 +1631 #[tokio::test] +1632 #[traced_test] +1633 async fn test_update_report_stun_working() { +1634 let (_server_a, relay_a) = test_utils::relay().await; +1635 let (_server_b, relay_b) = test_utils::relay().await; +1636 +1637 let mut report = Report::default(); +1638 let relay_a = Arc::new(relay_a); +1639 let relay_b = Arc::new(relay_b); +1640 +1641 // A STUN IPv4 probe from the the first relay server. +1642 let probe_report_a = ProbeReport { +1643 ipv4_can_send: true, +1644 ipv6_can_send: false, +1645 icmpv4: None, +1646 icmpv6: None, +1647 latency: Some(Duration::from_millis(5)), +1648 probe: Probe::StunIpv4 { +1649 delay: Duration::ZERO, +1650 node: relay_a.clone(), +1651 }, +1652 addr: Some((Ipv4Addr::new(203, 0, 113, 1), 1234).into()), +1653 }; +1654 update_report(&mut report, probe_report_a.clone()); +1655 +1656 assert!(report.udp); +1657 assert_eq!( +1658 report.relay_latency.get(&relay_a.url).unwrap(), +1659 Duration::from_millis(5) +1660 ); +1661 assert_eq!( +1662 report.relay_v4_latency.get(&relay_a.url).unwrap(), +1663 Duration::from_millis(5) +1664 ); +1665 assert!(report.ipv4_can_send); +1666 assert!(!report.ipv6_can_send); +1667 +1668 // A second STUN IPv4 probe, same external IP detected but slower. +1669 let probe_report_b = ProbeReport { +1670 latency: Some(Duration::from_millis(8)), +1671 probe: Probe::StunIpv4 { +1672 delay: Duration::ZERO, +1673 node: relay_b.clone(), +1674 }, +1675 ..probe_report_a +1676 }; +1677 update_report(&mut report, probe_report_b); +1678 +1679 assert!(report.udp); +1680 assert_eq!( +1681 report.relay_latency.get(&relay_a.url).unwrap(), +1682 Duration::from_millis(5) +1683 ); +1684 assert_eq!( +1685 report.relay_v4_latency.get(&relay_a.url).unwrap(), +1686 Duration::from_millis(5) +1687 ); +1688 assert!(report.ipv4_can_send); +1689 assert!(!report.ipv6_can_send); +1690 +1691 // A STUN IPv6 probe, this one is faster. +1692 let probe_report_a_ipv6 = ProbeReport { +1693 ipv4_can_send: false, +1694 ipv6_can_send: true, +1695 icmpv4: None, +1696 icmpv6: None, +1697 latency: Some(Duration::from_millis(4)), +1698 probe: Probe::StunIpv6 { +1699 delay: Duration::ZERO, +1700 node: relay_a.clone(), +1701 }, +1702 addr: Some((Ipv6Addr::new(2001, 0xdb8, 0, 0, 0, 0, 0, 1), 1234).into()), +1703 }; +1704 update_report(&mut report, probe_report_a_ipv6); +1705 +1706 assert!(report.udp); +1707 assert_eq!( +1708 report.relay_latency.get(&relay_a.url).unwrap(), +1709 Duration::from_millis(4) +1710 ); +1711 assert_eq!( +1712 report.relay_v6_latency.get(&relay_a.url).unwrap(), +1713 Duration::from_millis(4) +1714 ); +1715 assert!(report.ipv4_can_send); +1716 assert!(report.ipv6_can_send); +1717 } 1718 -1719 let mut report = Report::default(); -1720 -1721 // An ICMPv4 probe from the EU relay server. -1722 let probe_report_eu = ProbeReport { -1723 ipv4_can_send: true, -1724 ipv6_can_send: false, -1725 icmpv4: Some(true), -1726 icmpv6: None, -1727 latency: Some(Duration::from_millis(5)), -1728 probe: Probe::IcmpV4 { -1729 delay: Duration::ZERO, -1730 node: relay_a.clone(), -1731 }, -1732 addr: Some((Ipv4Addr::new(203, 0, 113, 1), 1234).into()), -1733 }; -1734 update_report(&mut report, probe_report_eu.clone()); -1735 -1736 assert!(!report.udp); -1737 assert!(report.ipv4_can_send); -1738 assert_eq!(report.icmpv4, Some(true)); -1739 -1740 // A second ICMPv4 probe which did not work. -1741 let probe_report_na = ProbeReport { -1742 ipv4_can_send: false, -1743 ipv6_can_send: false, -1744 icmpv4: Some(false), -1745 icmpv6: None, -1746 latency: None, -1747 probe: Probe::IcmpV4 { -1748 delay: Duration::ZERO, -1749 node: relay_b.clone(), -1750 }, -1751 addr: None, -1752 }; -1753 update_report(&mut report, probe_report_na); -1754 -1755 assert_eq!(report.icmpv4, Some(true)); -1756 -1757 // Behold, a STUN probe arrives! -1758 let probe_report_eu_stun = ProbeReport { -1759 ipv4_can_send: true, -1760 ipv6_can_send: false, -1761 icmpv4: None, -1762 icmpv6: None, -1763 latency: Some(Duration::from_millis(5)), -1764 probe: Probe::StunIpv4 { -1765 delay: Duration::ZERO, -1766 node: relay_a.clone(), -1767 }, -1768 addr: Some((Ipv4Addr::new(203, 0, 113, 1), 1234).into()), -1769 }; -1770 update_report(&mut report, probe_report_eu_stun); -1771 -1772 assert!(report.udp); -1773 assert_eq!(report.icmpv4, Some(true)); -1774 } -1775 -1776 // # ICMP permissions on Linux -1777 // -1778 // ## Using capabilities: CAP_NET_RAW -1779 // -1780 // To run ICMP tests on Linux you need CAP_NET_RAW capabilities. When running tests -1781 // this means you first need to build the binary, set the capabilities and finally run -1782 // the tests. -1783 // -1784 // Build the test binary: +1719 #[tokio::test] +1720 #[traced_test] +1721 async fn test_update_report_icmp() { +1722 let (_server_a, relay_a) = test_utils::relay().await; +1723 let (_server_b, relay_b) = test_utils::relay().await; +1724 let relay_a = Arc::new(relay_a); +1725 let relay_b = Arc::new(relay_b); +1726 +1727 let mut report = Report::default(); +1728 +1729 // An ICMPv4 probe from the EU relay server. +1730 let probe_report_eu = ProbeReport { +1731 ipv4_can_send: true, +1732 ipv6_can_send: false, +1733 icmpv4: Some(true), +1734 icmpv6: None, +1735 latency: Some(Duration::from_millis(5)), +1736 probe: Probe::IcmpV4 { +1737 delay: Duration::ZERO, +1738 node: relay_a.clone(), +1739 }, +1740 addr: Some((Ipv4Addr::new(203, 0, 113, 1), 1234).into()), +1741 }; +1742 update_report(&mut report, probe_report_eu.clone()); +1743 +1744 assert!(!report.udp); +1745 assert!(report.ipv4_can_send); +1746 assert_eq!(report.icmpv4, Some(true)); +1747 +1748 // A second ICMPv4 probe which did not work. +1749 let probe_report_na = ProbeReport { +1750 ipv4_can_send: false, +1751 ipv6_can_send: false, +1752 icmpv4: Some(false), +1753 icmpv6: None, +1754 latency: None, +1755 probe: Probe::IcmpV4 { +1756 delay: Duration::ZERO, +1757 node: relay_b.clone(), +1758 }, +1759 addr: None, +1760 }; +1761 update_report(&mut report, probe_report_na); +1762 +1763 assert_eq!(report.icmpv4, Some(true)); +1764 +1765 // Behold, a STUN probe arrives! +1766 let probe_report_eu_stun = ProbeReport { +1767 ipv4_can_send: true, +1768 ipv6_can_send: false, +1769 icmpv4: None, +1770 icmpv6: None, +1771 latency: Some(Duration::from_millis(5)), +1772 probe: Probe::StunIpv4 { +1773 delay: Duration::ZERO, +1774 node: relay_a.clone(), +1775 }, +1776 addr: Some((Ipv4Addr::new(203, 0, 113, 1), 1234).into()), +1777 }; +1778 update_report(&mut report, probe_report_eu_stun); +1779 +1780 assert!(report.udp); +1781 assert_eq!(report.icmpv4, Some(true)); +1782 } +1783 +1784 // # ICMP permissions on Linux 1785 // -1786 // cargo nextest run -p iroh net_report::reportgen::tests --no-run +1786 // ## Using capabilities: CAP_NET_RAW 1787 // -1788 // Find out the test binary location: -1789 // -1790 // cargo nextest list --message-format json -p iroh net_report::reportgen::tests \ -1791 // | jq '."rust-suites"."iroh"."binary-path"' | tr -d \" -1792 // -1793 // Set the CAP_NET_RAW permission, note that nextest runs each test in a child process -1794 // so the capabilities need to be inherited: +1788 // To run ICMP tests on Linux you need CAP_NET_RAW capabilities. When running tests +1789 // this means you first need to build the binary, set the capabilities and finally run +1790 // the tests. +1791 // +1792 // Build the test binary: +1793 // +1794 // cargo nextest run -p iroh net_report::reportgen::tests --no-run 1795 // -1796 // sudo setcap CAP_NET_RAW=eip target/debug/deps/iroh-abc123 +1796 // Find out the test binary location: 1797 // -1798 // Finally run the test: -1799 // -1800 // cargo nextest run -p iroh net_report::reportgen::tests -1801 // -1802 // This allows the pinger to create a SOCK_RAW socket for IPPROTO_ICMP. +1798 // cargo nextest list --message-format json -p iroh net_report::reportgen::tests \ +1799 // | jq '."rust-suites"."iroh"."binary-path"' | tr -d \" +1800 // +1801 // Set the CAP_NET_RAW permission, note that nextest runs each test in a child process +1802 // so the capabilities need to be inherited: 1803 // -1804 // -1805 // ## Using sysctl -1806 // -1807 // Now you know the hard way, you can also get this permission a little easier, but -1808 // slightly less secure, by allowing any process running with your group ID to create a -1809 // SOCK_DGRAM for IPPROTO_ICMP. -1810 // -1811 // First find out your group ID: +1804 // sudo setcap CAP_NET_RAW=eip target/debug/deps/iroh-abc123 +1805 // +1806 // Finally run the test: +1807 // +1808 // cargo nextest run -p iroh net_report::reportgen::tests +1809 // +1810 // This allows the pinger to create a SOCK_RAW socket for IPPROTO_ICMP. +1811 // 1812 // -1813 // id --group +1813 // ## Using sysctl 1814 // -1815 // Then allow this group to send pings. Note that this is an inclusive range: -1816 // -1817 // sudo sysctl net.ipv4.ping_group_range="1234 1234" +1815 // Now you know the hard way, you can also get this permission a little easier, but +1816 // slightly less secure, by allowing any process running with your group ID to create a +1817 // SOCK_DGRAM for IPPROTO_ICMP. 1818 // -1819 // Note that this does not survive a reboot usually, commonly you need to edit -1820 // /etc/sysctl.conf or /etc/sysctl.d/* to persist this across reboots. -1821 // -1822 // TODO: Not sure what about IPv6 pings using sysctl. -1823 #[tokio::test] -1824 #[traced_test] -1825 async fn test_icmpk_probe() { -1826 let pinger = Pinger::new(); -1827 let (server, node) = test_utils::relay().await; -1828 let addr = server.stun_addr().expect("test relay serves stun"); -1829 let probe = Probe::IcmpV4 { -1830 delay: Duration::from_secs(0), -1831 node: Arc::new(node), -1832 }; -1833 -1834 // A single ICMP packet might get lost. Try several and take the first. -1835 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); -1836 let mut tasks = JoinSet::new(); -1837 for i in 0..8 { -1838 let probe = probe.clone(); -1839 let pinger = pinger.clone(); -1840 let tx = tx.clone(); -1841 tasks.spawn(async move { -1842 time::sleep(Duration::from_millis(i * 100)).await; -1843 let res = run_icmp_probe(probe, addr, pinger).await; -1844 tx.send(res).ok(); -1845 }); -1846 } -1847 let mut last_err = None; -1848 while let Some(res) = rx.recv().await { -1849 match res { -1850 Ok(report) => { -1851 dbg!(&report); -1852 assert_eq!(report.icmpv4, Some(true)); -1853 assert!( -1854 report.latency.expect("should have a latency") > Duration::from_secs(0) -1855 ); -1856 break; -1857 } -1858 Err(ProbeErrorWithProbe::Error(err, _probe)) => { -1859 last_err = Some(err); -1860 } -1861 Err(ProbeErrorWithProbe::AbortSet(_err, _probe)) => { -1862 // We don't have permission, too bad. -1863 // panic!("no ping permission: {err:#}"); -1864 break; +1819 // First find out your group ID: +1820 // +1821 // id --group +1822 // +1823 // Then allow this group to send pings. Note that this is an inclusive range: +1824 // +1825 // sudo sysctl net.ipv4.ping_group_range="1234 1234" +1826 // +1827 // Note that this does not survive a reboot usually, commonly you need to edit +1828 // /etc/sysctl.conf or /etc/sysctl.d/* to persist this across reboots. +1829 // +1830 // TODO: Not sure what about IPv6 pings using sysctl. +1831 #[tokio::test] +1832 #[traced_test] +1833 async fn test_icmpk_probe() { +1834 let pinger = Pinger::new(); +1835 let (server, node) = test_utils::relay().await; +1836 let addr = server.stun_addr().expect("test relay serves stun"); +1837 let probe = Probe::IcmpV4 { +1838 delay: Duration::from_secs(0), +1839 node: Arc::new(node), +1840 }; +1841 +1842 // A single ICMP packet might get lost. Try several and take the first. +1843 let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); +1844 let mut tasks = JoinSet::new(); +1845 for i in 0..8 { +1846 let probe = probe.clone(); +1847 let pinger = pinger.clone(); +1848 let tx = tx.clone(); +1849 tasks.spawn(async move { +1850 time::sleep(Duration::from_millis(i * 100)).await; +1851 let res = run_icmp_probe(probe, addr, pinger).await; +1852 tx.send(res).ok(); +1853 }); +1854 } +1855 let mut last_err = None; +1856 while let Some(res) = rx.recv().await { +1857 match res { +1858 Ok(report) => { +1859 dbg!(&report); +1860 assert_eq!(report.icmpv4, Some(true)); +1861 assert!( +1862 report.latency.expect("should have a latency") > Duration::from_secs(0) +1863 ); +1864 break; 1865 } -1866 } -1867 } -1868 if let Some(err) = last_err { -1869 panic!("Ping error: {err:#}"); -1870 } -1871 } -1872 -1873 #[tokio::test] -1874 async fn test_measure_https_latency() -> Result { -1875 let (server, relay) = test_utils::relay().await; -1876 let dns_resolver = dns::tests::resolver(); -1877 tracing::info!(relay_url = ?relay.url , "RELAY_URL"); -1878 let (latency, ip) = -1879 measure_https_latency(&dns_resolver, &relay, server.certificates()).await?; +1866 Err(ProbeErrorWithProbe::Error(err, _probe)) => { +1867 last_err = Some(err); +1868 } +1869 Err(ProbeErrorWithProbe::AbortSet(_err, _probe)) => { +1870 // We don't have permission, too bad. +1871 // panic!("no ping permission: {err:#}"); +1872 break; +1873 } +1874 } +1875 } +1876 if let Some(err) = last_err { +1877 panic!("Ping error: {err:#}"); +1878 } +1879 } 1880 -1881 assert!(latency > Duration::ZERO); -1882 -1883 let relay_url_ip = relay -1884 .url -1885 .host_str() -1886 .unwrap() -1887 .parse::<std::net::IpAddr>() -1888 .e()?; -1889 assert_eq!(ip, relay_url_ip); -1890 Ok(()) -1891 } -1892 -1893 #[tokio::test] -1894 #[traced_test] -1895 async fn test_quic_probe() -> Result { -1896 let (server, relay) = test_utils::relay().await; -1897 let relay = Arc::new(relay); -1898 let client_config = iroh_relay::client::make_dangerous_client_config(); -1899 let ep = quinn::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).e()?; -1900 let client_addr = ep.local_addr().e()?; -1901 let quic_addr_disc = QuicConfig { -1902 ep: ep.clone(), -1903 client_config, -1904 ipv4: true, -1905 ipv6: true, -1906 }; -1907 let url = relay.url.clone(); -1908 let port = server.quic_addr().unwrap().port(); -1909 let probe = Probe::QuicIpv4 { -1910 delay: Duration::from_secs(0), -1911 node: relay, -1912 }; -1913 let probe = match run_quic_probe( -1914 quic_addr_disc, -1915 url, -1916 (Ipv4Addr::LOCALHOST, port).into(), -1917 probe, -1918 None, -1919 ) -1920 .await -1921 { -1922 Ok(probe) => probe, -1923 Err(e) => match e { -1924 ProbeErrorWithProbe::AbortSet(err, _) | ProbeErrorWithProbe::Error(err, _) => { -1925 return Err(err.into()); -1926 } -1927 }, -1928 }; -1929 assert!(probe.ipv4_can_send); -1930 assert_eq!(probe.addr.unwrap(), client_addr); -1931 ep.wait_idle().await; -1932 server.shutdown().await?; -1933 Ok(()) -1934 } -1935} \ No newline at end of file +1881 #[tokio::test] +1882 async fn test_measure_https_latency() -> Result { +1883 let (_server, relay) = test_utils::relay().await; +1884 let dns_resolver = dns::tests::resolver(); +1885 tracing::info!(relay_url = ?relay.url , "RELAY_URL"); +1886 let (latency, ip) = measure_https_latency(&dns_resolver, &relay, true).await?; +1887 +1888 assert!(latency > Duration::ZERO); +1889 +1890 let relay_url_ip = relay +1891 .url +1892 .host_str() +1893 .unwrap() +1894 .parse::<std::net::IpAddr>() +1895 .e()?; +1896 assert_eq!(ip, relay_url_ip); +1897 Ok(()) +1898 } +1899 +1900 #[tokio::test] +1901 #[traced_test] +1902 async fn test_quic_probe() -> Result { +1903 let (server, relay) = test_utils::relay().await; +1904 let relay = Arc::new(relay); +1905 let client_config = iroh_relay::client::make_dangerous_client_config(); +1906 let ep = quinn::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).e()?; +1907 let client_addr = ep.local_addr().e()?; +1908 let quic_addr_disc = QuicConfig { +1909 ep: ep.clone(), +1910 client_config, +1911 ipv4: true, +1912 ipv6: true, +1913 }; +1914 let url = relay.url.clone(); +1915 let port = server.quic_addr().unwrap().port(); +1916 let probe = Probe::QuicIpv4 { +1917 delay: Duration::from_secs(0), +1918 node: relay, +1919 }; +1920 let probe = match run_quic_probe( +1921 quic_addr_disc, +1922 url, +1923 (Ipv4Addr::LOCALHOST, port).into(), +1924 probe, +1925 None, +1926 ) +1927 .await +1928 { +1929 Ok(probe) => probe, +1930 Err(e) => match e { +1931 ProbeErrorWithProbe::AbortSet(err, _) | ProbeErrorWithProbe::Error(err, _) => { +1932 return Err(err.into()); +1933 } +1934 }, +1935 }; +1936 assert!(probe.ipv4_can_send); +1937 assert_eq!(probe.addr.unwrap(), client_addr); +1938 ep.wait_idle().await; +1939 server.shutdown().await?; +1940 Ok(()) +1941 } +1942} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/protocol.rs.html b/pr/3327/docs/src/iroh/protocol.rs.html index ffef1b0726..850af38fba 100644 --- a/pr/3327/docs/src/iroh/protocol.rs.html +++ b/pr/3327/docs/src/iroh/protocol.rs.html @@ -3,7 +3,7 @@ 3//! ## Example 4//! 5//! ```no_run -6//! # use iroh::{endpoint::{Connection, BindError}, protocol::{ProtocolHandler, Router, ProtocolError}, Endpoint, NodeAddr}; +6//! # use iroh::{endpoint::{Connection, BindError}, protocol::{AcceptError, ProtocolHandler, Router}, Endpoint, NodeAddr}; 7//! # 8//! # async fn test_compile() -> Result<(), BindError> { 9//! let endpoint = Endpoint::builder().discovery_n0().bind().await?; @@ -19,7 +19,7 @@ 19//! struct Echo; 20//! 21//! impl ProtocolHandler for Echo { -22//! async fn accept(&self, connection: Connection) -> Result<(), ProtocolError> { +22//! async fn accept(&self, connection: Connection) -> Result<(), AcceptError> { 23//! let (mut send, mut recv) = connection.accept_bi().await?; 24//! 25//! // Echo any bytes received back directly. @@ -63,491 +63,491 @@ 63/// 64/// ```no_run 65/// # use std::sync::Arc; -66/// # use futures_lite::future::Boxed as BoxedFuture; -67/// # use n0_snafu::ResultExt; -68/// # use iroh::{endpoint::Connecting, protocol::{ProtocolHandler, Router}, Endpoint, NodeAddr}; -69/// # -70/// # async fn test_compile() -> n0_snafu::Result<()> { -71/// let endpoint = Endpoint::builder().discovery_n0().bind().await?; -72/// -73/// let router = Router::builder(endpoint) -74/// // .accept(&ALPN, <something>) -75/// .spawn(); -76/// -77/// // wait until the user wants to -78/// tokio::signal::ctrl_c().await.context("ctrl+c")?; -79/// router.shutdown().await.context("shutdown")?; -80/// # Ok(()) -81/// # } -82/// ``` -83
    #[derive(Clone, Debug)] -84pub struct Router { -85 endpoint: Endpoint, -86 // `Router` needs to be `Clone + Send`, and we need to `task.await` in its `shutdown()` impl. -87 task: Arc<Mutex<Option<AbortOnDropHandle<()>>>>, -88 cancel_token: CancellationToken, -89} -90 -91/// Builder for creating a [`Router`] for accepting protocols. -92#[derive(Debug)] -93pub struct RouterBuilder { -94 endpoint: Endpoint, -95 protocols: ProtocolMap, -96} -97 -98#[allow(missing_docs)] -99#[derive(Debug, Snafu)] -100#[non_exhaustive] -101pub enum ProtocolError { -102 #[snafu(transparent)] -103 Connect { -104 source: crate::endpoint::ConnectionError, -105 backtrace: Option<Backtrace>, -106 #[snafu(implicit)] -107 span_trace: n0_snafu::SpanTrace, -108 }, -109 #[snafu(transparent)] -110 RemoteNodeId { source: RemoteNodeIdError }, -111 #[snafu(display("Not allowed."))] -112 NotAllowed {}, -113 -114 #[snafu(transparent)] -115 User { -116 source: Box<dyn std::error::Error + Send + Sync + 'static>, -117 }, -118} -119 -120impl ProtocolError { -121 /// Creates a new user error from an arbitrary error type. -122 pub fn from_err<T: std::error::Error + Send + Sync + 'static>(value: T) -> Self { -123 Self::User { -124 source: Box::new(value), -125 } -126 } -127} -128 -129impl From<std::io::Error> for ProtocolError { -130 fn from(err: std::io::Error) -> Self { -131 Self::from_err(err) -132 } -133} -134 -135impl From<quinn::ClosedStream> for ProtocolError { -136 fn from(err: quinn::ClosedStream) -> Self { -137 Self::from_err(err) -138 } -139} -140 -141/// Handler for incoming connections. -142/// -143/// A router accepts connections for arbitrary ALPN protocols. -144/// -145/// With this trait, you can handle incoming connections for any protocol. -146/// -147/// Implement this trait on a struct that should handle incoming connections. -148/// The protocol handler must then be registered on the node for an ALPN protocol with -149/// [`crate::protocol::RouterBuilder::accept`]. -150/// -151/// See the [module documentation](crate::protocol) for an example. -152pub trait ProtocolHandler: Send + Sync + std::fmt::Debug + 'static { -153 /// Optional interception point to handle the `Connecting` state. -154 /// -155 /// Can be implemented as `async fn on_connecting(&self, connecting: Connecting) -> Result<Connection>`. -156 /// -157 /// This enables accepting 0-RTT data from clients, among other things. -158 fn on_connecting( -159 &self, -160 connecting: Connecting, -161 ) -> impl Future<Output = Result<Connection, ProtocolError>> + Send { -162 async move { -163 let conn = connecting.await?; -164 Ok(conn) -165 } -166 } -167 -168 /// Handle an incoming connection. -169 /// -170 /// Can be implemented as `async fn accept(&self, connection: Connection) -> Result<Connection>`. -171 /// -172 /// The returned future runs on a freshly spawned tokio task so it can be long-running. -173 /// -174 /// When [`Router::shutdown`] is called, no further connections will be accepted, and -175 /// the futures returned by [`Self::accept`] will be aborted after the future returned -176 /// from [`ProtocolHandler::shutdown`] completes. -177 fn accept( -178 &self, -179 connection: Connection, -180 ) -> impl Future<Output = Result<(), ProtocolError>> + Send; -181 -182 /// Called when the router shuts down. -183 /// -184 /// Can be implemented as `async fn shutdown(&self)`. -185 /// -186 /// This is called from [`Router::shutdown`]. The returned future is awaited before -187 /// the router closes the endpoint. -188 fn shutdown(&self) -> impl Future<Output = ()> + Send { -189 async move {} -190 } -191} -192 -193impl<T: ProtocolHandler> ProtocolHandler for Arc<T> { -194 async fn on_connecting(&self, conn: Connecting) -> Result<Connection, ProtocolError> { -195 self.as_ref().on_connecting(conn).await -196 } -197 -198 async fn accept(&self, conn: Connection) -> Result<(), ProtocolError> { -199 self.as_ref().accept(conn).await -200 } -201 -202 async fn shutdown(&self) { -203 self.as_ref().shutdown().await -204 } -205} -206 -207impl<T: ProtocolHandler> ProtocolHandler for Box<T> { -208 async fn on_connecting(&self, conn: Connecting) -> Result<Connection, ProtocolError> { -209 self.as_ref().on_connecting(conn).await -210 } -211 -212 async fn accept(&self, conn: Connection) -> Result<(), ProtocolError> { -213 self.as_ref().accept(conn).await -214 } -215 -216 async fn shutdown(&self) { -217 self.as_ref().shutdown().await -218 } -219} -220 -221/// A dyn-compatible version of [`ProtocolHandler`] that returns boxed futures. -222/// -223/// We are not using [`n0_future::boxed::BoxFuture] because we don't need a `'static` bound -224/// on these futures. -225pub(crate) trait DynProtocolHandler: Send + Sync + std::fmt::Debug + 'static { -226 /// See [`ProtocolHandler::on_connecting`]. -227 fn on_connecting( -228 &self, -229 connecting: Connecting, -230 ) -> Pin<Box<dyn Future<Output = Result<Connection, ProtocolError>> + Send + '_>> { -231 Box::pin(async move { -232 let conn = connecting.await?; -233 Ok(conn) -234 }) -235 } -236 -237 /// See [`ProtocolHandler::accept`]. -238 fn accept( -239 &self, -240 connection: Connection, -241 ) -> Pin<Box<dyn Future<Output = Result<(), ProtocolError>> + Send + '_>>; -242 -243 /// See [`ProtocolHandler::shutdown`]. -244 fn shutdown(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> { -245 Box::pin(async move {}) -246 } -247} -248 -249impl<P: ProtocolHandler> DynProtocolHandler for P { -250 fn accept( -251 &self, -252 connection: Connection, -253 ) -> Pin<Box<dyn Future<Output = Result<(), ProtocolError>> + Send + '_>> { -254 Box::pin(<Self as ProtocolHandler>::accept(self, connection)) -255 } -256 -257 fn on_connecting( -258 &self, -259 connecting: Connecting, -260 ) -> Pin<Box<dyn Future<Output = Result<Connection, ProtocolError>> + Send + '_>> { -261 Box::pin(<Self as ProtocolHandler>::on_connecting(self, connecting)) -262 } -263 -264 fn shutdown(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> { -265 Box::pin(<Self as ProtocolHandler>::shutdown(self)) -266 } -267} -268 -269/// A typed map of protocol handlers, mapping them from ALPNs. -270#[derive(Debug, Default)] -271pub(crate) struct ProtocolMap(BTreeMap<Vec<u8>, Box<dyn DynProtocolHandler>>); -272 -273impl ProtocolMap { -274 /// Returns the registered protocol handler for an ALPN as a [`Arc<dyn ProtocolHandler>`]. -275 pub(crate) fn get(&self, alpn: &[u8]) -> Option<&dyn DynProtocolHandler> { -276 self.0.get(alpn).map(|p| &**p) -277 } -278 -279 /// Inserts a protocol handler. -280 pub(crate) fn insert(&mut self, alpn: Vec<u8>, handler: impl ProtocolHandler) { -281 let handler = Box::new(handler); -282 self.0.insert(alpn, handler); -283 } -284 -285 /// Returns an iterator of all registered ALPN protocol identifiers. -286 pub(crate) fn alpns(&self) -> impl Iterator<Item = &Vec<u8>> { -287 self.0.keys() -288 } -289 -290 /// Shuts down all protocol handlers. -291 /// -292 /// Calls and awaits [`ProtocolHandler::shutdown`] for all registered handlers concurrently. -293 pub(crate) async fn shutdown(&self) { -294 let handlers = self.0.values().map(|p| p.shutdown()); -295 join_all(handlers).await; -296 } -297} -298 -299impl Router { -300 /// Creates a new [`Router`] using given [`Endpoint`]. -301 pub fn builder(endpoint: Endpoint) -> RouterBuilder { -302 RouterBuilder::new(endpoint) -303 } -304 -305 /// Returns the [`Endpoint`] stored in this router. -306 pub fn endpoint(&self) -> &Endpoint { -307 &self.endpoint -308 } -309 -310 /// Checks if the router is already shutdown. -311 pub fn is_shutdown(&self) -> bool { -312 self.cancel_token.is_cancelled() -313 } -314 -315 /// Shuts down the accept loop cleanly. -316 /// -317 /// When this function returns, all [`ProtocolHandler`]s will be shutdown and -318 /// `Endpoint::close` will have been called. -319 /// -320 /// If already shutdown, it returns `Ok`. -321 /// -322 /// If some [`ProtocolHandler`] panicked in the accept loop, this will propagate -323 /// that panic into the result here. -324 pub async fn shutdown(&self) -> Result<(), n0_future::task::JoinError> { -325 if self.is_shutdown() { -326 return Ok(()); -327 } -328 -329 // Trigger shutdown of the main run task by activating the cancel token. -330 self.cancel_token.cancel(); -331 -332 // Wait for the main task to terminate. -333 if let Some(task) = self.task.lock().await.take() { -334 task.await?; -335 } -336 -337 Ok(()) -338 } -339} -340 -341impl RouterBuilder { -342 /// Creates a new router builder using given [`Endpoint`]. -343 pub fn new(endpoint: Endpoint) -> Self { -344 Self { -345 endpoint, -346 protocols: ProtocolMap::default(), -347 } -348 } -349 -350 /// Configures the router to accept the [`ProtocolHandler`] when receiving a connection -351 /// with this `alpn`. -352 pub fn accept(mut self, alpn: impl AsRef<[u8]>, handler: impl ProtocolHandler) -> Self { -353 self.protocols.insert(alpn.as_ref().to_vec(), handler); -354 self -355 } -356 -357 /// Returns the [`Endpoint`] of the node. -358 pub fn endpoint(&self) -> &Endpoint { -359 &self.endpoint -360 } -361 -362 /// Spawns an accept loop and returns a handle to it encapsulated as the [`Router`]. -363 pub fn spawn(self) -> Router { -364 // Update the endpoint with our alpns. -365 let alpns = self -366 .protocols -367 .alpns() -368 .map(|alpn| alpn.to_vec()) -369 .collect::<Vec<_>>(); -370 -371 let protocols = Arc::new(self.protocols); -372 self.endpoint.set_alpns(alpns); -373 -374 let mut join_set = JoinSet::new(); -375 let endpoint = self.endpoint.clone(); -376 -377 // Our own shutdown works with a cancellation token. -378 let cancel = CancellationToken::new(); -379 let cancel_token = cancel.clone(); -380 -381 let run_loop_fut = async move { -382 // Make sure to cancel the token, if this future ever exits. -383 let _cancel_guard = cancel_token.clone().drop_guard(); -384 // We create a separate cancellation token to stop any `ProtocolHandler::accept` futures -385 // that are still running after `ProtocolHandler::shutdown` was called. -386 let handler_cancel_token = CancellationToken::new(); -387 -388 loop { -389 tokio::select! { -390 biased; -391 _ = cancel_token.cancelled() => { -392 break; -393 }, -394 // handle task terminations and quit on panics. -395 Some(res) = join_set.join_next() => { -396 match res { -397 Err(outer) => { -398 if outer.is_panic() { -399 error!("Task panicked: {outer:?}"); -400 break; -401 } else if outer.is_cancelled() { -402 trace!("Task cancelled: {outer:?}"); -403 } else { -404 error!("Task failed: {outer:?}"); -405 break; -406 } -407 } -408 Ok(Some(())) => { -409 trace!("Task finished"); -410 } -411 Ok(None) => { -412 trace!("Task cancelled"); -413 } -414 } -415 }, -416 -417 // handle incoming p2p connections. -418 incoming = endpoint.accept() => { -419 let Some(incoming) = incoming else { -420 break; // Endpoint is closed. -421 }; -422 -423 let protocols = protocols.clone(); -424 let token = handler_cancel_token.child_token(); -425 join_set.spawn(async move { -426 token.run_until_cancelled(handle_connection(incoming, protocols)).await -427 }.instrument(info_span!("router.accept"))); -428 }, -429 } -430 } -431 -432 // We first shutdown the protocol handlers to give them a chance to close connections gracefully. -433 protocols.shutdown().await; -434 // We now cancel the remaining `ProtocolHandler::accept` futures. -435 handler_cancel_token.cancel(); -436 // Now we close the endpoint. This will force-close all connections that are not yet closed. -437 endpoint.close().await; -438 // Finally, we abort the remaining accept tasks. This should be a noop because we already cancelled -439 // the futures above. -440 tracing::debug!("Shutting down remaining tasks"); -441 join_set.abort_all(); -442 while let Some(res) = join_set.join_next().await { -443 match res { -444 Err(err) if err.is_panic() => error!("Task panicked: {err:?}"), -445 _ => {} -446 } -447 } -448 }; -449 let task = task::spawn(run_loop_fut); -450 let task = AbortOnDropHandle::new(task); -451 -452 Router { -453 endpoint: self.endpoint, -454 task: Arc::new(Mutex::new(Some(task))), -455 cancel_token: cancel, -456 } -457 } -458} -459 -460async fn handle_connection(incoming: crate::endpoint::Incoming, protocols: Arc<ProtocolMap>) { -461 let mut connecting = match incoming.accept() { -462 Ok(conn) => conn, -463 Err(err) => { -464 warn!("Ignoring connection: accepting failed: {err:#}"); -465 return; -466 } -467 }; -468 let alpn = match connecting.alpn().await { -469 Ok(alpn) => alpn, -470 Err(err) => { -471 warn!("Ignoring connection: invalid handshake: {err:#}"); -472 return; -473 } -474 }; -475 let Some(handler) = protocols.get(&alpn) else { -476 warn!("Ignoring connection: unsupported ALPN protocol"); -477 return; -478 }; -479 match handler.on_connecting(connecting).await { -480 Ok(connection) => { -481 if let Err(err) = handler.accept(connection).await { -482 warn!("Handling incoming connection ended with error: {err}"); -483 } -484 } -485 Err(err) => { -486 warn!("Handling incoming connecting ended with error: {err}"); -487 } -488 } -489} -490 -491/// Wraps an existing protocol, limiting its access, -492/// based on the provided function. -493/// -494/// Any refused connection will be closed with an error code of `0` and reason `not allowed`. -495#[derive(derive_more::Debug, Clone)] -496pub struct AccessLimit<P: ProtocolHandler + Clone> { -497 proto: P, -498 #[debug("limiter")] -499 limiter: Arc<dyn Fn(NodeId) -> bool + Send + Sync + 'static>, -500} -501 -502impl<P: ProtocolHandler + Clone> AccessLimit<P> { -503 /// Create a new `AccessLimit`. -504 /// -505 /// The function should return `true` for nodes that are allowed to -506 /// connect, and `false` otherwise. -507 pub fn new<F>(proto: P, limiter: F) -> Self -508 where -509 F: Fn(NodeId) -> bool + Send + Sync + 'static, -510 { -511 Self { -512 proto, -513 limiter: Arc::new(limiter), -514 } -515 } -516} -517 -518impl<P: ProtocolHandler + Clone> ProtocolHandler for AccessLimit<P> { -519 fn on_connecting( -520 &self, -521 conn: Connecting, -522 ) -> impl Future<Output = Result<Connection, ProtocolError>> + Send { -523 self.proto.on_connecting(conn) -524 } -525 -526 async fn accept(&self, conn: Connection) -> Result<(), ProtocolError> { -527 let remote = conn.remote_node_id()?; -528 let is_allowed = (self.limiter)(remote); -529 if !is_allowed { -530 conn.close(0u32.into(), b"not allowed"); -531 return Err(NotAllowedSnafu.build()); -532 } -533 self.proto.accept(conn).await?; -534 Ok(()) -535 } -536 -537 fn shutdown(&self) -> impl Future<Output = ()> + Send { -538 self.proto.shutdown() -539 } -540} -541 -542#[cfg(test)] -543mod tests { -544 use std::{sync::Mutex, time::Duration}; -545 -546 use n0_snafu::{Result, ResultExt}; +66/// # use n0_snafu::ResultExt; +67/// # use iroh::{endpoint::Connecting, protocol::{ProtocolHandler, Router}, Endpoint, NodeAddr}; +68/// # +69/// # async fn test_compile() -> n0_snafu::Result<()> { +70/// let endpoint = Endpoint::builder().discovery_n0().bind().await?; +71/// +72/// let router = Router::builder(endpoint) +73/// // .accept(&ALPN, <something>) +74/// .spawn(); +75/// +76/// // wait until the user wants to +77/// tokio::signal::ctrl_c().await.context("ctrl+c")?; +78/// router.shutdown().await.context("shutdown")?; +79/// # Ok(()) +80/// # } +81/// ``` +82
    #[derive(Clone, Debug)] +83pub struct Router { +84 endpoint: Endpoint, +85 // `Router` needs to be `Clone + Send`, and we need to `task.await` in its `shutdown()` impl. +86 task: Arc<Mutex<Option<AbortOnDropHandle<()>>>>, +87 cancel_token: CancellationToken, +88} +89 +90/// Builder for creating a [`Router`] for accepting protocols. +91#[derive(Debug)] +92pub struct RouterBuilder { +93 endpoint: Endpoint, +94 protocols: ProtocolMap, +95} +96 +97#[allow(missing_docs)] +98#[derive(Debug, Snafu)] +99#[non_exhaustive] +100pub enum AcceptError { +101 #[snafu(transparent)] +102 Connection { +103 source: crate::endpoint::ConnectionError, +104 backtrace: Option<Backtrace>, +105 #[snafu(implicit)] +106 span_trace: n0_snafu::SpanTrace, +107 }, +108 #[snafu(transparent)] +109 MissingRemoteNodeId { source: RemoteNodeIdError }, +110 #[snafu(display("Not allowed."))] +111 NotAllowed {}, +112 +113 #[snafu(transparent)] +114 User { +115 source: Box<dyn std::error::Error + Send + Sync + 'static>, +116 }, +117} +118 +119impl AcceptError { +120 /// Creates a new user error from an arbitrary error type. +121 pub fn from_err<T: std::error::Error + Send + Sync + 'static>(value: T) -> Self { +122 Self::User { +123 source: Box::new(value), +124 } +125 } +126} +127 +128impl From<std::io::Error> for AcceptError { +129 fn from(err: std::io::Error) -> Self { +130 Self::from_err(err) +131 } +132} +133 +134impl From<quinn::ClosedStream> for AcceptError { +135 fn from(err: quinn::ClosedStream) -> Self { +136 Self::from_err(err) +137 } +138} +139 +140/// Handler for incoming connections. +141/// +142/// A router accepts connections for arbitrary ALPN protocols. +143/// +144/// With this trait, you can handle incoming connections for any protocol. +145/// +146/// Implement this trait on a struct that should handle incoming connections. +147/// The protocol handler must then be registered on the node for an ALPN protocol with +148/// [`crate::protocol::RouterBuilder::accept`]. +149/// +150/// See the [module documentation](crate::protocol) for an example. +151pub trait ProtocolHandler: Send + Sync + std::fmt::Debug + 'static { +152 /// Optional interception point to handle the `Connecting` state. +153 /// +154 /// Can be implemented as `async fn on_connecting(&self, connecting: Connecting) -> Result<Connection>`. +155 /// +156 /// This enables accepting 0-RTT data from clients, among other things. +157 fn on_connecting( +158 &self, +159 connecting: Connecting, +160 ) -> impl Future<Output = Result<Connection, AcceptError>> + Send { +161 async move { +162 let conn = connecting.await?; +163 Ok(conn) +164 } +165 } +166 +167 /// Handle an incoming connection. +168 /// +169 /// Can be implemented as `async fn accept(&self, connection: Connection) -> Result<Connection>`. +170 /// +171 /// The returned future runs on a freshly spawned tokio task so it can be long-running. +172 /// +173 /// When [`Router::shutdown`] is called, no further connections will be accepted, and +174 /// the futures returned by [`Self::accept`] will be aborted after the future returned +175 /// from [`ProtocolHandler::shutdown`] completes. +176 fn accept( +177 &self, +178 connection: Connection, +179 ) -> impl Future<Output = Result<(), AcceptError>> + Send; +180 +181 /// Called when the router shuts down. +182 /// +183 /// Can be implemented as `async fn shutdown(&self)`. +184 /// +185 /// This is called from [`Router::shutdown`]. The returned future is awaited before +186 /// the router closes the endpoint. +187 fn shutdown(&self) -> impl Future<Output = ()> + Send { +188 async move {} +189 } +190} +191 +192impl<T: ProtocolHandler> ProtocolHandler for Arc<T> { +193 async fn on_connecting(&self, conn: Connecting) -> Result<Connection, AcceptError> { +194 self.as_ref().on_connecting(conn).await +195 } +196 +197 async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { +198 self.as_ref().accept(conn).await +199 } +200 +201 async fn shutdown(&self) { +202 self.as_ref().shutdown().await +203 } +204} +205 +206impl<T: ProtocolHandler> ProtocolHandler for Box<T> { +207 async fn on_connecting(&self, conn: Connecting) -> Result<Connection, AcceptError> { +208 self.as_ref().on_connecting(conn).await +209 } +210 +211 async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { +212 self.as_ref().accept(conn).await +213 } +214 +215 async fn shutdown(&self) { +216 self.as_ref().shutdown().await +217 } +218} +219 +220/// A dyn-compatible version of [`ProtocolHandler`] that returns boxed futures. +221/// +222/// We are not using [`n0_future::boxed::BoxFuture] because we don't need a `'static` bound +223/// on these futures. +224pub(crate) trait DynProtocolHandler: Send + Sync + std::fmt::Debug + 'static { +225 /// See [`ProtocolHandler::on_connecting`]. +226 fn on_connecting( +227 &self, +228 connecting: Connecting, +229 ) -> Pin<Box<dyn Future<Output = Result<Connection, AcceptError>> + Send + '_>> { +230 Box::pin(async move { +231 let conn = connecting.await?; +232 Ok(conn) +233 }) +234 } +235 +236 /// See [`ProtocolHandler::accept`]. +237 fn accept( +238 &self, +239 connection: Connection, +240 ) -> Pin<Box<dyn Future<Output = Result<(), AcceptError>> + Send + '_>>; +241 +242 /// See [`ProtocolHandler::shutdown`]. +243 fn shutdown(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> { +244 Box::pin(async move {}) +245 } +246} +247 +248impl<P: ProtocolHandler> DynProtocolHandler for P { +249 fn accept( +250 &self, +251 connection: Connection, +252 ) -> Pin<Box<dyn Future<Output = Result<(), AcceptError>> + Send + '_>> { +253 Box::pin(<Self as ProtocolHandler>::accept(self, connection)) +254 } +255 +256 fn on_connecting( +257 &self, +258 connecting: Connecting, +259 ) -> Pin<Box<dyn Future<Output = Result<Connection, AcceptError>> + Send + '_>> { +260 Box::pin(<Self as ProtocolHandler>::on_connecting(self, connecting)) +261 } +262 +263 fn shutdown(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> { +264 Box::pin(<Self as ProtocolHandler>::shutdown(self)) +265 } +266} +267 +268/// A typed map of protocol handlers, mapping them from ALPNs. +269#[derive(Debug, Default)] +270pub(crate) struct ProtocolMap(BTreeMap<Vec<u8>, Box<dyn DynProtocolHandler>>); +271 +272impl ProtocolMap { +273 /// Returns the registered protocol handler for an ALPN as a [`Arc<dyn ProtocolHandler>`]. +274 pub(crate) fn get(&self, alpn: &[u8]) -> Option<&dyn DynProtocolHandler> { +275 self.0.get(alpn).map(|p| &**p) +276 } +277 +278 /// Inserts a protocol handler. +279 pub(crate) fn insert(&mut self, alpn: Vec<u8>, handler: impl ProtocolHandler) { +280 let handler = Box::new(handler); +281 self.0.insert(alpn, handler); +282 } +283 +284 /// Returns an iterator of all registered ALPN protocol identifiers. +285 pub(crate) fn alpns(&self) -> impl Iterator<Item = &Vec<u8>> { +286 self.0.keys() +287 } +288 +289 /// Shuts down all protocol handlers. +290 /// +291 /// Calls and awaits [`ProtocolHandler::shutdown`] for all registered handlers concurrently. +292 pub(crate) async fn shutdown(&self) { +293 let handlers = self.0.values().map(|p| p.shutdown()); +294 join_all(handlers).await; +295 } +296} +297 +298impl Router { +299 /// Creates a new [`Router`] using given [`Endpoint`]. +300 pub fn builder(endpoint: Endpoint) -> RouterBuilder { +301 RouterBuilder::new(endpoint) +302 } +303 +304 /// Returns the [`Endpoint`] stored in this router. +305 pub fn endpoint(&self) -> &Endpoint { +306 &self.endpoint +307 } +308 +309 /// Checks if the router is already shutdown. +310 pub fn is_shutdown(&self) -> bool { +311 self.cancel_token.is_cancelled() +312 } +313 +314 /// Shuts down the accept loop cleanly. +315 /// +316 /// When this function returns, all [`ProtocolHandler`]s will be shutdown and +317 /// `Endpoint::close` will have been called. +318 /// +319 /// If already shutdown, it returns `Ok`. +320 /// +321 /// If some [`ProtocolHandler`] panicked in the accept loop, this will propagate +322 /// that panic into the result here. +323 pub async fn shutdown(&self) -> Result<(), n0_future::task::JoinError> { +324 if self.is_shutdown() { +325 return Ok(()); +326 } +327 +328 // Trigger shutdown of the main run task by activating the cancel token. +329 self.cancel_token.cancel(); +330 +331 // Wait for the main task to terminate. +332 if let Some(task) = self.task.lock().await.take() { +333 task.await?; +334 } +335 +336 Ok(()) +337 } +338} +339 +340impl RouterBuilder { +341 /// Creates a new router builder using given [`Endpoint`]. +342 pub fn new(endpoint: Endpoint) -> Self { +343 Self { +344 endpoint, +345 protocols: ProtocolMap::default(), +346 } +347 } +348 +349 /// Configures the router to accept the [`ProtocolHandler`] when receiving a connection +350 /// with this `alpn`. +351 pub fn accept(mut self, alpn: impl AsRef<[u8]>, handler: impl ProtocolHandler) -> Self { +352 self.protocols.insert(alpn.as_ref().to_vec(), handler); +353 self +354 } +355 +356 /// Returns the [`Endpoint`] of the node. +357 pub fn endpoint(&self) -> &Endpoint { +358 &self.endpoint +359 } +360 +361 /// Spawns an accept loop and returns a handle to it encapsulated as the [`Router`]. +362 pub fn spawn(self) -> Router { +363 // Update the endpoint with our alpns. +364 let alpns = self +365 .protocols +366 .alpns() +367 .map(|alpn| alpn.to_vec()) +368 .collect::<Vec<_>>(); +369 +370 let protocols = Arc::new(self.protocols); +371 self.endpoint.set_alpns(alpns); +372 +373 let mut join_set = JoinSet::new(); +374 let endpoint = self.endpoint.clone(); +375 +376 // Our own shutdown works with a cancellation token. +377 let cancel = CancellationToken::new(); +378 let cancel_token = cancel.clone(); +379 +380 let run_loop_fut = async move { +381 // Make sure to cancel the token, if this future ever exits. +382 let _cancel_guard = cancel_token.clone().drop_guard(); +383 // We create a separate cancellation token to stop any `ProtocolHandler::accept` futures +384 // that are still running after `ProtocolHandler::shutdown` was called. +385 let handler_cancel_token = CancellationToken::new(); +386 +387 loop { +388 tokio::select! { +389 biased; +390 _ = cancel_token.cancelled() => { +391 break; +392 }, +393 // handle task terminations and quit on panics. +394 Some(res) = join_set.join_next() => { +395 match res { +396 Err(outer) => { +397 if outer.is_panic() { +398 error!("Task panicked: {outer:?}"); +399 break; +400 } else if outer.is_cancelled() { +401 trace!("Task cancelled: {outer:?}"); +402 } else { +403 error!("Task failed: {outer:?}"); +404 break; +405 } +406 } +407 Ok(Some(())) => { +408 trace!("Task finished"); +409 } +410 Ok(None) => { +411 trace!("Task cancelled"); +412 } +413 } +414 }, +415 +416 // handle incoming p2p connections. +417 incoming = endpoint.accept() => { +418 let Some(incoming) = incoming else { +419 break; // Endpoint is closed. +420 }; +421 +422 let protocols = protocols.clone(); +423 let token = handler_cancel_token.child_token(); +424 join_set.spawn(async move { +425 token.run_until_cancelled(handle_connection(incoming, protocols)).await +426 }.instrument(info_span!("router.accept"))); +427 }, +428 } +429 } +430 +431 // We first shutdown the protocol handlers to give them a chance to close connections gracefully. +432 protocols.shutdown().await; +433 // We now cancel the remaining `ProtocolHandler::accept` futures. +434 handler_cancel_token.cancel(); +435 // Now we close the endpoint. This will force-close all connections that are not yet closed. +436 endpoint.close().await; +437 // Finally, we abort the remaining accept tasks. This should be a noop because we already cancelled +438 // the futures above. +439 tracing::debug!("Shutting down remaining tasks"); +440 join_set.abort_all(); +441 while let Some(res) = join_set.join_next().await { +442 match res { +443 Err(err) if err.is_panic() => error!("Task panicked: {err:?}"), +444 _ => {} +445 } +446 } +447 }; +448 let task = task::spawn(run_loop_fut); +449 let task = AbortOnDropHandle::new(task); +450 +451 Router { +452 endpoint: self.endpoint, +453 task: Arc::new(Mutex::new(Some(task))), +454 cancel_token: cancel, +455 } +456 } +457} +458 +459async fn handle_connection(incoming: crate::endpoint::Incoming, protocols: Arc<ProtocolMap>) { +460 let mut connecting = match incoming.accept() { +461 Ok(conn) => conn, +462 Err(err) => { +463 warn!("Ignoring connection: accepting failed: {err:#}"); +464 return; +465 } +466 }; +467 let alpn = match connecting.alpn().await { +468 Ok(alpn) => alpn, +469 Err(err) => { +470 warn!("Ignoring connection: invalid handshake: {err:#}"); +471 return; +472 } +473 }; +474 let Some(handler) = protocols.get(&alpn) else { +475 warn!("Ignoring connection: unsupported ALPN protocol"); +476 return; +477 }; +478 match handler.on_connecting(connecting).await { +479 Ok(connection) => { +480 if let Err(err) = handler.accept(connection).await { +481 warn!("Handling incoming connection ended with error: {err}"); +482 } +483 } +484 Err(err) => { +485 warn!("Handling incoming connecting ended with error: {err}"); +486 } +487 } +488} +489 +490/// Wraps an existing protocol, limiting its access, +491/// based on the provided function. +492/// +493/// Any refused connection will be closed with an error code of `0` and reason `not allowed`. +494#[derive(derive_more::Debug, Clone)] +495pub struct AccessLimit<P: ProtocolHandler + Clone> { +496 proto: P, +497 #[debug("limiter")] +498 limiter: Arc<dyn Fn(NodeId) -> bool + Send + Sync + 'static>, +499} +500 +501impl<P: ProtocolHandler + Clone> AccessLimit<P> { +502 /// Create a new `AccessLimit`. +503 /// +504 /// The function should return `true` for nodes that are allowed to +505 /// connect, and `false` otherwise. +506 pub fn new<F>(proto: P, limiter: F) -> Self +507 where +508 F: Fn(NodeId) -> bool + Send + Sync + 'static, +509 { +510 Self { +511 proto, +512 limiter: Arc::new(limiter), +513 } +514 } +515} +516 +517impl<P: ProtocolHandler + Clone> ProtocolHandler for AccessLimit<P> { +518 fn on_connecting( +519 &self, +520 conn: Connecting, +521 ) -> impl Future<Output = Result<Connection, AcceptError>> + Send { +522 self.proto.on_connecting(conn) +523 } +524 +525 async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { +526 let remote = conn.remote_node_id()?; +527 let is_allowed = (self.limiter)(remote); +528 if !is_allowed { +529 conn.close(0u32.into(), b"not allowed"); +530 return Err(NotAllowedSnafu.build()); +531 } +532 self.proto.accept(conn).await?; +533 Ok(()) +534 } +535 +536 fn shutdown(&self) -> impl Future<Output = ()> + Send { +537 self.proto.shutdown() +538 } +539} +540 +541#[cfg(test)] +542mod tests { +543 use std::{sync::Mutex, time::Duration}; +544 +545 use n0_snafu::{Result, ResultExt}; +546 use n0_watcher::Watcher; 547 use quinn::ApplicationClose; 548 549 use super::*; -550 use crate::{endpoint::ConnectionError, watcher::Watcher, RelayMode}; +550 use crate::{endpoint::ConnectionError, RelayMode}; 551 552 #[tokio::test] 553 async fn test_shutdown() -> Result { @@ -572,7 +572,7 @@ 572 const ECHO_ALPN: &[u8] = b"/iroh/echo/1"; 573 574 impl ProtocolHandler for Echo { -575 async fn accept(&self, connection: Connection) -> Result<(), ProtocolError> { +575 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> { 576 println!("accepting echo"); 577 let (mut send, mut recv) = connection.accept_bi().await?; 578 @@ -585,79 +585,93 @@ 585 Ok(()) 586 } 587 } -588 #[tokio::test] -589 async fn test_limiter() -> Result { -590 let e1 = Endpoint::builder().bind().await?; -591 // deny all access -592 let proto = AccessLimit::new(Echo, |_node_id| false); -593 let r1 = Router::builder(e1.clone()).accept(ECHO_ALPN, proto).spawn(); -594 -595 let addr1 = r1.endpoint().node_addr().initialized().await?; -596 -597 let e2 = Endpoint::builder().bind().await?; -598 -599 println!("connecting"); -600 let conn = e2.connect(addr1, ECHO_ALPN).await?; -601 -602 let (_send, mut recv) = conn.open_bi().await.e()?; -603 let response = recv.read_to_end(1000).await.unwrap_err(); -604 assert!(format!("{:#?}", response).contains("not allowed")); -605 -606 r1.shutdown().await.e()?; -607 e2.close().await; -608 -609 Ok(()) -610 } -611 -612 #[tokio::test] -613 async fn test_graceful_shutdown() -> Result { -614 #[derive(Debug, Clone, Default)] -615 struct TestProtocol { -616 connections: Arc<Mutex<Vec<Connection>>>, -617 } -618 -619 const TEST_ALPN: &[u8] = b"/iroh/test/1"; -620 -621 impl ProtocolHandler for TestProtocol { -622 async fn accept(&self, connection: Connection) -> Result<(), ProtocolError> { -623 self.connections.lock().expect("poisoned").push(connection); -624 Ok(()) -625 } +588 +589 #[tokio::test] +590 async fn test_limiter() -> Result { +591 // tracing_subscriber::fmt::try_init().ok(); +592 let e1 = Endpoint::builder() +593 .relay_mode(RelayMode::Disabled) +594 .bind() +595 .await?; +596 // deny all access +597 let proto = AccessLimit::new(Echo, |_node_id| false); +598 let r1 = Router::builder(e1.clone()).accept(ECHO_ALPN, proto).spawn(); +599 +600 let addr1 = r1.endpoint().node_addr().initialized().await?; +601 dbg!(&addr1); +602 let e2 = Endpoint::builder() +603 .relay_mode(RelayMode::Disabled) +604 .bind() +605 .await?; +606 +607 println!("connecting"); +608 let conn = e2.connect(addr1, ECHO_ALPN).await?; +609 +610 let (_send, mut recv) = conn.open_bi().await.e()?; +611 let response = recv.read_to_end(1000).await.unwrap_err(); +612 assert!(format!("{:#?}", response).contains("not allowed")); +613 +614 r1.shutdown().await.e()?; +615 e2.close().await; +616 +617 Ok(()) +618 } +619 +620 #[tokio::test] +621 async fn test_graceful_shutdown() -> Result { +622 #[derive(Debug, Clone, Default)] +623 struct TestProtocol { +624 connections: Arc<Mutex<Vec<Connection>>>, +625 } 626 -627 async fn shutdown(&self) { -628 tokio::time::sleep(Duration::from_millis(100)).await; -629 let mut connections = self.connections.lock().expect("poisoned"); -630 for conn in connections.drain(..) { -631 conn.close(42u32.into(), b"shutdown"); -632 } +627 const TEST_ALPN: &[u8] = b"/iroh/test/1"; +628 +629 impl ProtocolHandler for TestProtocol { +630 async fn accept(&self, connection: Connection) -> Result<(), AcceptError> { +631 self.connections.lock().expect("poisoned").push(connection); +632 Ok(()) 633 } -634 } -635 -636 let endpoint = Endpoint::builder() -637 .relay_mode(RelayMode::Disabled) -638 .bind() -639 .await?; -640 let router = Router::builder(endpoint) -641 .accept(TEST_ALPN, TestProtocol::default()) -642 .spawn(); -643 let addr = router.endpoint().node_addr().initialized().await?; -644 -645 let endpoint2 = Endpoint::builder() +634 +635 async fn shutdown(&self) { +636 tokio::time::sleep(Duration::from_millis(100)).await; +637 let mut connections = self.connections.lock().expect("poisoned"); +638 for conn in connections.drain(..) { +639 conn.close(42u32.into(), b"shutdown"); +640 } +641 } +642 } +643 +644 eprintln!("creating ep1"); +645 let endpoint = Endpoint::builder() 646 .relay_mode(RelayMode::Disabled) 647 .bind() 648 .await?; -649 let conn = endpoint2.connect(addr, TEST_ALPN).await?; -650 -651 router.shutdown().await.e()?; -652 -653 let reason = conn.closed().await; -654 assert_eq!( -655 reason, -656 ConnectionError::ApplicationClosed(ApplicationClose { -657 error_code: 42u32.into(), -658 reason: b"shutdown".to_vec().into() -659 }) -660 ); -661 Ok(()) -662 } -663} \ No newline at end of file +649 let router = Router::builder(endpoint) +650 .accept(TEST_ALPN, TestProtocol::default()) +651 .spawn(); +652 eprintln!("waiting for node addr"); +653 let addr = router.endpoint().node_addr().initialized().await?; +654 +655 eprintln!("creating ep2"); +656 let endpoint2 = Endpoint::builder() +657 .relay_mode(RelayMode::Disabled) +658 .bind() +659 .await?; +660 eprintln!("connecting to {:?}", addr); +661 let conn = endpoint2.connect(addr, TEST_ALPN).await?; +662 +663 eprintln!("starting shutdown"); +664 router.shutdown().await.e()?; +665 +666 eprintln!("waiting for closed conn"); +667 let reason = conn.closed().await; +668 assert_eq!( +669 reason, +670 ConnectionError::ApplicationClosed(ApplicationClose { +671 error_code: 42u32.into(), +672 reason: b"shutdown".to_vec().into() +673 }) +674 ); +675 Ok(()) +676 } +677} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/test_utils.rs.html b/pr/3327/docs/src/iroh/test_utils.rs.html index a09c11711c..89b0d09e06 100644 --- a/pr/3327/docs/src/iroh/test_utils.rs.html +++ b/pr/3327/docs/src/iroh/test_utils.rs.html @@ -376,173 +376,180 @@ 376 use iroh_base::NodeId; 377 use iroh_relay::node_info::{NodeIdExt, NodeInfo, IROH_TXT_NAME}; 378 use pkarr::SignedPacket; -379 -380 use crate::test_utils::dns_server::QueryHandler; -381 -382 #[derive(Debug, Clone)] -383 pub struct State { -384 packets: Arc<Mutex<HashMap<NodeId, SignedPacket>>>, -385 origin: String, -386 notify: Arc<tokio::sync::Notify>, -387 } -388 -389 impl State { -390 pub fn new(origin: String) -> Self { -391 Self { -392 packets: Default::default(), -393 origin, -394 notify: Arc::new(tokio::sync::Notify::new()), -395 } -396 } -397 -398 pub fn on_update(&self) -> tokio::sync::futures::Notified<'_> { -399 self.notify.notified() -400 } -401 -402 pub async fn on_node(&self, node: &NodeId, timeout: Duration) -> std::io::Result<()> { -403 let timeout = tokio::time::sleep(timeout); -404 tokio::pin!(timeout); -405 while self.get(node, |p| p.is_none()) { -406 tokio::select! { -407 _ = &mut timeout => return Err(std::io::Error::other("timeout")), -408 _ = self.on_update() => {} -409 } -410 } -411 Ok(()) -412 } -413 -414 pub fn upsert(&self, signed_packet: SignedPacket) -> std::io::Result<bool> { -415 let node_id = NodeId::from_bytes(&signed_packet.public_key().to_bytes()) -416 .map_err(std::io::Error::other)?; -417 let mut map = self.packets.lock().expect("poisoned"); -418 let updated = match map.entry(node_id) { -419 hash_map::Entry::Vacant(e) => { -420 e.insert(signed_packet); -421 true -422 } -423 hash_map::Entry::Occupied(mut e) => { -424 if signed_packet.more_recent_than(e.get()) { -425 e.insert(signed_packet); -426 true -427 } else { -428 false -429 } -430 } -431 }; -432 if updated { -433 self.notify.notify_waiters(); -434 } -435 Ok(updated) -436 } -437 -438 /// Returns a mutex guard, do not hold over await points -439 pub fn get<F, T>(&self, node_id: &NodeId, cb: F) -> T -440 where -441 F: FnOnce(Option<&mut SignedPacket>) -> T, -442 { -443 let mut map = self.packets.lock().expect("poisoned"); -444 let packet = map.get_mut(node_id); -445 cb(packet) -446 } -447 -448 pub fn resolve_dns( -449 &self, -450 query: &hickory_resolver::proto::op::Message, -451 reply: &mut hickory_resolver::proto::op::Message, -452 ttl: u32, -453 ) -> std::io::Result<()> { -454 for query in query.queries() { -455 let domain_name = query.name().to_string(); -456 let Some(node_id) = node_id_from_domain_name(&domain_name) else { -457 continue; -458 }; -459 -460 self.get(&node_id, |packet| { -461 if let Some(packet) = packet { -462 let node_info = NodeInfo::from_pkarr_signed_packet(packet) -463 .map_err(std::io::Error::other)?; -464 for record in node_info_to_hickory_records(&node_info, &self.origin, ttl) { -465 reply.add_answer(record); -466 } -467 } -468 Ok::<_, std::io::Error>(()) -469 })?; -470 } -471 Ok(()) -472 } -473 } -474 -475 impl QueryHandler for State { -476 fn resolve( -477 &self, -478 query: &hickory_resolver::proto::op::Message, -479 reply: &mut hickory_resolver::proto::op::Message, -480 ) -> impl Future<Output = std::io::Result<()>> + Send { -481 const TTL: u32 = 30; -482 let res = self.resolve_dns(query, reply, TTL); -483 std::future::ready(res) -484 } -485 } -486 -487 /// Parses a [`NodeId`] from a DNS domain name. -488 /// -489 /// Splits the domain name into labels on each dot. Expects the first label to be -490 /// [`IROH_TXT_NAME`] and the second label to be a z32 encoded [`NodeId`]. Ignores -491 /// subsequent labels. -492 /// -493 /// Returns a [`NodeId`] if parsed successfully, otherwise `None`. -494 fn node_id_from_domain_name(name: &str) -> Option<NodeId> { -495 let mut labels = name.split("."); -496 let label = labels.next()?; -497 if label != IROH_TXT_NAME { -498 return None; -499 } -500 let label = labels.next()?; -501 let node_id = NodeId::from_z32(label).ok()?; -502 Some(node_id) -503 } -504 -505 /// Converts a [`NodeInfo`]into a [`hickory_resolver::proto::rr::Record`] DNS record. -506 fn node_info_to_hickory_records( -507 node_info: &NodeInfo, -508 origin: &str, -509 ttl: u32, -510 ) -> impl Iterator<Item = hickory_resolver::proto::rr::Record> + 'static { -511 let txt_strings = node_info.to_txt_strings(); -512 let records = to_hickory_records(txt_strings, node_info.node_id, origin, ttl); -513 records.collect::<Vec<_>>().into_iter() -514 } -515 -516 /// Converts to a list of [`hickory_resolver::proto::rr::Record`] resource records. -517 fn to_hickory_records( -518 txt_strings: Vec<String>, -519 node_id: NodeId, -520 origin: &str, -521 ttl: u32, -522 ) -> impl Iterator<Item = hickory_resolver::proto::rr::Record> + '_ { -523 use hickory_resolver::proto::rr; -524 let name = format!("{}.{}.{}", IROH_TXT_NAME, node_id.to_z32(), origin); -525 let name = rr::Name::from_utf8(name).expect("invalid name"); -526 txt_strings.into_iter().map(move |s| { -527 let txt = rr::rdata::TXT::new(vec![s]); -528 let rdata = rr::RData::TXT(txt); -529 rr::Record::from_rdata(name.clone(), ttl, rdata) -530 }) -531 } -532 -533 #[cfg(test)] -534 mod tests { -535 use iroh_base::NodeId; -536 use n0_snafu::Result; -537 -538 #[test] -539 fn test_node_id_from_domain_name() -> Result { -540 let name = "_iroh.dgjpkxyn3zyrk3zfads5duwdgbqpkwbjxfj4yt7rezidr3fijccy.dns.iroh.link."; -541 let node_id = super::node_id_from_domain_name(name); -542 let expected: NodeId = -543 "1992d53c02cdc04566e5c0edb1ce83305cd550297953a047a445ea3264b54b18".parse()?; -544 assert_eq!(node_id, Some(expected)); -545 Ok(()) -546 } -547 } -548} \ No newline at end of file +379 use tracing::debug; +380 +381 use crate::test_utils::dns_server::QueryHandler; +382 +383 #[derive(Debug, Clone)] +384 pub struct State { +385 packets: Arc<Mutex<HashMap<NodeId, SignedPacket>>>, +386 origin: String, +387 notify: Arc<tokio::sync::Notify>, +388 } +389 +390 impl State { +391 pub fn new(origin: String) -> Self { +392 Self { +393 packets: Default::default(), +394 origin, +395 notify: Arc::new(tokio::sync::Notify::new()), +396 } +397 } +398 +399 pub fn on_update(&self) -> tokio::sync::futures::Notified<'_> { +400 self.notify.notified() +401 } +402 +403 pub async fn on_node(&self, node: &NodeId, timeout: Duration) -> std::io::Result<()> { +404 let timeout = tokio::time::sleep(timeout); +405 tokio::pin!(timeout); +406 while self.get(node, |p| { +407 let node_info = p +408 .as_ref() +409 .and_then(|p| NodeInfo::from_pkarr_signed_packet(p).ok()); +410 debug!("got info {:#?}", node_info); +411 p.is_none() +412 }) { +413 tokio::select! { +414 _ = &mut timeout => return Err(std::io::Error::other("timeout")), +415 _ = self.on_update() => {} +416 } +417 } +418 Ok(()) +419 } +420 +421 pub fn upsert(&self, signed_packet: SignedPacket) -> std::io::Result<bool> { +422 let node_id = NodeId::from_bytes(&signed_packet.public_key().to_bytes()) +423 .map_err(std::io::Error::other)?; +424 let mut map = self.packets.lock().expect("poisoned"); +425 let updated = match map.entry(node_id) { +426 hash_map::Entry::Vacant(e) => { +427 e.insert(signed_packet); +428 true +429 } +430 hash_map::Entry::Occupied(mut e) => { +431 if signed_packet.more_recent_than(e.get()) { +432 e.insert(signed_packet); +433 true +434 } else { +435 false +436 } +437 } +438 }; +439 if updated { +440 self.notify.notify_waiters(); +441 } +442 Ok(updated) +443 } +444 +445 /// Returns a mutex guard, do not hold over await points +446 pub fn get<F, T>(&self, node_id: &NodeId, cb: F) -> T +447 where +448 F: FnOnce(Option<&mut SignedPacket>) -> T, +449 { +450 let mut map = self.packets.lock().expect("poisoned"); +451 let packet = map.get_mut(node_id); +452 cb(packet) +453 } +454 +455 pub fn resolve_dns( +456 &self, +457 query: &hickory_resolver::proto::op::Message, +458 reply: &mut hickory_resolver::proto::op::Message, +459 ttl: u32, +460 ) -> std::io::Result<()> { +461 for query in query.queries() { +462 let domain_name = query.name().to_string(); +463 let Some(node_id) = node_id_from_domain_name(&domain_name) else { +464 continue; +465 }; +466 +467 self.get(&node_id, |packet| { +468 if let Some(packet) = packet { +469 let node_info = NodeInfo::from_pkarr_signed_packet(packet) +470 .map_err(std::io::Error::other)?; +471 for record in node_info_to_hickory_records(&node_info, &self.origin, ttl) { +472 reply.add_answer(record); +473 } +474 } +475 Ok::<_, std::io::Error>(()) +476 })?; +477 } +478 Ok(()) +479 } +480 } +481 +482 impl QueryHandler for State { +483 fn resolve( +484 &self, +485 query: &hickory_resolver::proto::op::Message, +486 reply: &mut hickory_resolver::proto::op::Message, +487 ) -> impl Future<Output = std::io::Result<()>> + Send { +488 const TTL: u32 = 30; +489 let res = self.resolve_dns(query, reply, TTL); +490 std::future::ready(res) +491 } +492 } +493 +494 /// Parses a [`NodeId`] from a DNS domain name. +495 /// +496 /// Splits the domain name into labels on each dot. Expects the first label to be +497 /// [`IROH_TXT_NAME`] and the second label to be a z32 encoded [`NodeId`]. Ignores +498 /// subsequent labels. +499 /// +500 /// Returns a [`NodeId`] if parsed successfully, otherwise `None`. +501 fn node_id_from_domain_name(name: &str) -> Option<NodeId> { +502 let mut labels = name.split("."); +503 let label = labels.next()?; +504 if label != IROH_TXT_NAME { +505 return None; +506 } +507 let label = labels.next()?; +508 let node_id = NodeId::from_z32(label).ok()?; +509 Some(node_id) +510 } +511 +512 /// Converts a [`NodeInfo`]into a [`hickory_resolver::proto::rr::Record`] DNS record. +513 fn node_info_to_hickory_records( +514 node_info: &NodeInfo, +515 origin: &str, +516 ttl: u32, +517 ) -> impl Iterator<Item = hickory_resolver::proto::rr::Record> + 'static { +518 let txt_strings = node_info.to_txt_strings(); +519 let records = to_hickory_records(txt_strings, node_info.node_id, origin, ttl); +520 records.collect::<Vec<_>>().into_iter() +521 } +522 +523 /// Converts to a list of [`hickory_resolver::proto::rr::Record`] resource records. +524 fn to_hickory_records( +525 txt_strings: Vec<String>, +526 node_id: NodeId, +527 origin: &str, +528 ttl: u32, +529 ) -> impl Iterator<Item = hickory_resolver::proto::rr::Record> + '_ { +530 use hickory_resolver::proto::rr; +531 let name = format!("{}.{}.{}", IROH_TXT_NAME, node_id.to_z32(), origin); +532 let name = rr::Name::from_utf8(name).expect("invalid name"); +533 txt_strings.into_iter().map(move |s| { +534 let txt = rr::rdata::TXT::new(vec![s]); +535 let rdata = rr::RData::TXT(txt); +536 rr::Record::from_rdata(name.clone(), ttl, rdata) +537 }) +538 } +539 +540 #[cfg(test)] +541 mod tests { +542 use iroh_base::NodeId; +543 use n0_snafu::Result; +544 +545 #[test] +546 fn test_node_id_from_domain_name() -> Result { +547 let name = "_iroh.dgjpkxyn3zyrk3zfads5duwdgbqpkwbjxfj4yt7rezidr3fijccy.dns.iroh.link."; +548 let node_id = super::node_id_from_domain_name(name); +549 let expected: NodeId = +550 "1992d53c02cdc04566e5c0edb1ce83305cd550297953a047a445ea3264b54b18".parse()?; +551 assert_eq!(node_id, Some(expected)); +552 Ok(()) +553 } +554 } +555} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh/watcher.rs.html b/pr/3327/docs/src/iroh/watcher.rs.html deleted file mode 100644 index 2b2815d4ed..0000000000 --- a/pr/3327/docs/src/iroh/watcher.rs.html +++ /dev/null @@ -1,699 +0,0 @@ -watcher.rs - source

    iroh/
    watcher.rs

    1//! Watchable values.
    -2//!
    -3//! A [`Watchable`] exists to keep track of a value which may change over time.  It allows
    -4//! observers to be notified of changes to the value.  The aim is to always be aware of the
    -5//! **last** value, not to observe *every* value change.
    -6//!
    -7//! In that way, a [`Watchable`] is like a [`tokio::sync::broadcast::Sender`] (and a
    -8//! [`Watcher`] is like a [`tokio::sync::broadcast::Receiver`]), except that there's no risk
    -9//! of the channel filling up, but instead you might miss items.
    -10//!
    -11//! This module is meant to be imported like this (if you use all of these things):
    -12//! ```ignore
    -13//! use iroh::watcher::{self, Watchable, Watcher as _};
    -14//! ```
    -15
    -16#[cfg(not(iroh_loom))]
    -17use std::sync;
    -18use std::{
    -19    collections::VecDeque,
    -20    future::Future,
    -21    pin::Pin,
    -22    sync::{Arc, Weak},
    -23    task::{self, Poll, Waker},
    -24};
    -25
    -26#[cfg(iroh_loom)]
    -27use loom::sync;
    -28use snafu::Snafu;
    -29use sync::{Mutex, RwLock};
    -30
    -31/// A wrapper around a value that notifies [`Watcher`]s when the value is modified.
    -32///
    -33/// Only the most recent value is available to any observer, but the observer is guaranteed
    -34/// to be notified of the most recent value.
    -35#[derive(Debug, Default)]
    -36pub struct Watchable<T> {
    -37    shared: Arc<Shared<T>>,
    -38}
    -39
    -40impl<T> Clone for Watchable<T> {
    -41    fn clone(&self) -> Self {
    -42        Self {
    -43            shared: self.shared.clone(),
    -44        }
    -45    }
    -46}
    -47
    -48impl<T: Clone + Eq> Watchable<T> {
    -49    /// Creates a [`Watchable`] initialized to given value.
    -50    pub fn new(value: T) -> Self {
    -51        Self {
    -52            shared: Arc::new(Shared {
    -53                state: RwLock::new(State {
    -54                    value,
    -55                    epoch: INITIAL_EPOCH,
    -56                }),
    -57                watchers: Default::default(),
    -58            }),
    -59        }
    -60    }
    -61
    -62    /// Sets a new value.
    -63    ///
    -64    /// Returns `Ok(previous_value)` if the value was different from the one set, or
    -65    /// returns the provided value back as `Err(value)` if the value didn't change.
    -66    ///
    -67    /// Watchers are only notified if the value changed.
    -68    pub fn set(&self, value: T) -> Result<T, T> {
    -69        // We don't actually write when the value didn't change, but there's unfortunately
    -70        // no way to upgrade a read guard to a write guard, and locking as read first, then
    -71        // dropping and locking as write introduces a possible race condition.
    -72        let mut state = self.shared.state.write().expect("poisoned");
    -73
    -74        // Find out if the value changed
    -75        let changed = state.value != value;
    -76
    -77        let ret = if changed {
    -78            let old = std::mem::replace(&mut state.value, value);
    -79            state.epoch += 1;
    -80            Ok(old)
    -81        } else {
    -82            Err(value)
    -83        };
    -84        drop(state); // No need to write anymore
    -85
    -86        // Notify watchers
    -87        if changed {
    -88            for watcher in self.shared.watchers.lock().expect("poisoned").drain(..) {
    -89                watcher.wake();
    -90            }
    -91        }
    -92        ret
    -93    }
    -94
    -95    /// Creates a [`Direct`] [`Watcher`], allowing the value to be observed, but not modified.
    -96    pub fn watch(&self) -> Direct<T> {
    -97        Direct {
    -98            epoch: self.shared.state.read().expect("poisoned").epoch,
    -99            shared: Arc::downgrade(&self.shared),
    -100        }
    -101    }
    -102
    -103    /// Returns the currently stored value.
    -104    pub fn get(&self) -> T {
    -105        self.shared.get()
    -106    }
    -107}
    -108
    -109/// A handle to a value that's represented by one or more underlying [`Watchable`]s.
    -110///
    -111/// A [`Watcher`] can get the current value, and will be notified when the value changes.
    -112/// Only the most recent value is accessible, and if the threads with the underlying [`Watchable`]s
    -113/// change the value faster than the threads with the [`Watcher`] can keep up with, then
    -114/// it'll miss in-between values.
    -115/// When the thread changing the [`Watchable`] pauses updating, the [`Watcher`] will always
    -116/// end up reporting the most recent state eventually.
    -117///
    -118/// Watchers can be modified via [`Watcher::map`] to observe a value derived from the original
    -119/// value via a function.
    -120///
    -121/// Watchers can be combined via [`Watcher::or`] to allow observing multiple values at once and
    -122/// getting an update in case any of the values updates.
    -123///
    -124/// One of the underlying [`Watchable`]s might already be dropped. In that case,
    -125/// the watcher will be "disconnected" and return [`Err(Disconnected)`](Disconnected)
    -126/// on some function calls or, when turned into a stream, that stream will end.
    -127pub trait Watcher: Clone {
    -128    /// The type of value that can change.
    -129    ///
    -130    /// We require `Clone`, because we need to be able to make
    -131    /// the values have a lifetime that's detached from the original [`Watchable`]'s
    -132    /// lifetime.
    -133    ///
    -134    /// We require `Eq`, to be able to check whether the value actually changed or
    -135    /// not, so we can notify or not notify accordingly.
    -136    type Value: Clone + Eq;
    -137
    -138    /// Returns the current state of the underlying value, or errors out with
    -139    /// [`Disconnected`], if one of the underlying [`Watchable`]s has been dropped.
    -140    fn get(&self) -> Result<Self::Value, Disconnected>;
    -141
    -142    /// Polls for the next value, or returns [`Disconnected`] if one of the underlying
    -143    /// [`Watchable`]s has been dropped.
    -144    fn poll_updated(
    -145        &mut self,
    -146        cx: &mut task::Context<'_>,
    -147    ) -> Poll<Result<Self::Value, Disconnected>>;
    -148
    -149    /// Returns a future completing with `Ok(value)` once a new value is set, or with
    -150    /// [`Err(Disconnected)`](Disconnected) if the connected [`Watchable`] was dropped.
    -151    ///
    -152    /// # Cancel Safety
    -153    ///
    -154    /// The returned future is cancel-safe.
    -155    fn updated(&mut self) -> NextFut<Self> {
    -156        NextFut { watcher: self }
    -157    }
    -158
    -159    /// Returns a future completing once the value is set to [`Some`] value.
    -160    ///
    -161    /// If the current value is [`Some`] value, this future will resolve immediately.
    -162    ///
    -163    /// This is a utility for the common case of storing an [`Option`] inside a
    -164    /// [`Watchable`].
    -165    ///
    -166    /// # Cancel Safety
    -167    ///
    -168    /// The returned future is cancel-safe.
    -169    fn initialized<T>(&mut self) -> InitializedFut<T, Self>
    -170    where
    -171        Self: Watcher<Value = Option<T>>,
    -172    {
    -173        InitializedFut {
    -174            initial: match self.get() {
    -175                Ok(Some(value)) => Some(Ok(value)),
    -176                Ok(None) => None,
    -177                Err(val) => Some(Err(val)),
    -178            },
    -179            watcher: self,
    -180        }
    -181    }
    -182
    -183    /// Returns a stream which will yield the most recent values as items.
    -184    ///
    -185    /// The first item of the stream is the current value, so that this stream can be easily
    -186    /// used to operate on the most recent value.
    -187    ///
    -188    /// Note however, that only the last item is stored.  If the stream is not polled when an
    -189    /// item is available it can be replaced with another item by the time it is polled.
    -190    ///
    -191    /// This stream ends once the original [`Watchable`] has been dropped.
    -192    ///
    -193    /// # Cancel Safety
    -194    ///
    -195    /// The returned stream is cancel-safe.
    -196    fn stream(self) -> Stream<Self>
    -197    where
    -198        Self: Unpin,
    -199    {
    -200        Stream {
    -201            initial: self.get().ok(),
    -202            watcher: self,
    -203        }
    -204    }
    -205
    -206    /// Returns a stream which will yield the most recent values as items, starting from
    -207    /// the next unobserved future value.
    -208    ///
    -209    /// This means this stream will only yield values when the watched value changes,
    -210    /// the value stored at the time the stream is created is not yielded.
    -211    ///
    -212    /// Note however, that only the last item is stored.  If the stream is not polled when an
    -213    /// item is available it can be replaced with another item by the time it is polled.
    -214    ///
    -215    /// This stream ends once the original [`Watchable`] has been dropped.
    -216    ///
    -217    /// # Cancel Safety
    -218    ///
    -219    /// The returned stream is cancel-safe.
    -220    fn stream_updates_only(self) -> Stream<Self>
    -221    where
    -222        Self: Unpin,
    -223    {
    -224        Stream {
    -225            initial: None,
    -226            watcher: self,
    -227        }
    -228    }
    -229
    -230    /// Maps this watcher with a function that transforms the observed values.
    -231    ///
    -232    /// The returned watcher will only register updates, when the *mapped* value
    -233    /// observably changes. For this, it needs to store a clone of `T` in the watcher.
    -234    fn map<T: Clone + Eq>(
    -235        self,
    -236        map: impl Fn(Self::Value) -> T + 'static,
    -237    ) -> Result<Map<Self, T>, Disconnected> {
    -238        Ok(Map {
    -239            current: (map)(self.get()?),
    -240            map: Arc::new(map),
    -241            watcher: self,
    -242        })
    -243    }
    -244
    -245    /// Returns a watcher that updates every time this or the other watcher
    -246    /// updates, and yields both watcher's items together when that happens.
    -247    fn or<W: Watcher>(self, other: W) -> (Self, W) {
    -248        (self, other)
    -249    }
    -250}
    -251
    -252/// The immediate, direct observer of a [`Watchable`] value.
    -253///
    -254/// This type is mainly used via the [`Watcher`] interface.
    -255#[derive(Debug, Clone)]
    -256pub struct Direct<T> {
    -257    epoch: u64,
    -258    shared: Weak<Shared<T>>,
    -259}
    -260
    -261impl<T: Clone + Eq> Watcher for Direct<T> {
    -262    type Value = T;
    -263
    -264    fn get(&self) -> Result<Self::Value, Disconnected> {
    -265        let shared = self.shared.upgrade().ok_or(DisconnectedSnafu.build())?;
    -266        Ok(shared.get())
    -267    }
    -268
    -269    fn poll_updated(
    -270        &mut self,
    -271        cx: &mut task::Context<'_>,
    -272    ) -> Poll<Result<Self::Value, Disconnected>> {
    -273        let Some(shared) = self.shared.upgrade() else {
    -274            return Poll::Ready(Err(DisconnectedSnafu.build()));
    -275        };
    -276        match shared.poll_updated(cx, self.epoch) {
    -277            Poll::Pending => Poll::Pending,
    -278            Poll::Ready((current_epoch, value)) => {
    -279                self.epoch = current_epoch;
    -280                Poll::Ready(Ok(value))
    -281            }
    -282        }
    -283    }
    -284}
    -285
    -286impl<S: Watcher, T: Watcher> Watcher for (S, T) {
    -287    type Value = (S::Value, T::Value);
    -288
    -289    fn get(&self) -> Result<Self::Value, Disconnected> {
    -290        Ok((self.0.get()?, self.1.get()?))
    -291    }
    -292
    -293    fn poll_updated(
    -294        &mut self,
    -295        cx: &mut task::Context<'_>,
    -296    ) -> Poll<Result<Self::Value, Disconnected>> {
    -297        let poll_0 = self.0.poll_updated(cx)?;
    -298        let poll_1 = self.1.poll_updated(cx)?;
    -299        match (poll_0, poll_1) {
    -300            (Poll::Ready(s), Poll::Ready(t)) => Poll::Ready(Ok((s, t))),
    -301            (Poll::Ready(s), Poll::Pending) => Poll::Ready(self.1.get().map(move |t| (s, t))),
    -302            (Poll::Pending, Poll::Ready(t)) => Poll::Ready(self.0.get().map(move |s| (s, t))),
    -303            (Poll::Pending, Poll::Pending) => Poll::Pending,
    -304        }
    -305    }
    -306}
    -307
    -308/// Wraps a [`Watcher`] to allow observing a derived value.
    -309///
    -310/// See [`Watcher::map`].
    -311#[derive(derive_more::Debug, Clone)]
    -312pub struct Map<W: Watcher, T: Clone + Eq> {
    -313    #[debug("Arc<dyn Fn(W::Value) -> T + 'static>")]
    -314    map: Arc<dyn Fn(W::Value) -> T + 'static>,
    -315    watcher: W,
    -316    current: T,
    -317}
    -318
    -319impl<W: Watcher, T: Clone + Eq> Watcher for Map<W, T> {
    -320    type Value = T;
    -321
    -322    fn get(&self) -> Result<Self::Value, Disconnected> {
    -323        Ok((self.map)(self.watcher.get()?))
    -324    }
    -325
    -326    fn poll_updated(
    -327        &mut self,
    -328        cx: &mut task::Context<'_>,
    -329    ) -> Poll<Result<Self::Value, Disconnected>> {
    -330        loop {
    -331            let value = n0_future::ready!(self.watcher.poll_updated(cx)?);
    -332            let mapped = (self.map)(value);
    -333            if mapped != self.current {
    -334                self.current = mapped.clone();
    -335                return Poll::Ready(Ok(mapped));
    -336            } else {
    -337                self.current = mapped;
    -338            }
    -339        }
    -340    }
    -341}
    -342
    -343/// Future returning the next item after the current one in a [`Watcher`].
    -344///
    -345/// See [`Watcher::updated`].
    -346///
    -347/// # Cancel Safety
    -348///
    -349/// This future is cancel-safe.
    -350#[derive(Debug)]
    -351pub struct NextFut<'a, W: Watcher> {
    -352    watcher: &'a mut W,
    -353}
    -354
    -355impl<W: Watcher> Future for NextFut<'_, W> {
    -356    type Output = Result<W::Value, Disconnected>;
    -357
    -358    fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
    -359        self.watcher.poll_updated(cx)
    -360    }
    -361}
    -362
    -363/// Future returning the current or next value that's [`Some`] value.
    -364/// in a [`Watcher`].
    -365///
    -366/// See [`Watcher::initialized`].
    -367///
    -368/// # Cancel Safety
    -369///
    -370/// This Future is cancel-safe.
    -371#[derive(Debug)]
    -372pub struct InitializedFut<'a, T, W: Watcher<Value = Option<T>>> {
    -373    initial: Option<Result<T, Disconnected>>,
    -374    watcher: &'a mut W,
    -375}
    -376
    -377impl<T: Clone + Eq + Unpin, W: Watcher<Value = Option<T>> + Unpin> Future
    -378    for InitializedFut<'_, T, W>
    -379{
    -380    type Output = Result<T, Disconnected>;
    -381
    -382    fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
    -383        if let Some(value) = self.as_mut().initial.take() {
    -384            return Poll::Ready(value);
    -385        }
    -386        loop {
    -387            if let Some(value) = n0_future::ready!(self.as_mut().watcher.poll_updated(cx)?) {
    -388                return Poll::Ready(Ok(value));
    -389            }
    -390        }
    -391    }
    -392}
    -393
    -394/// A stream for a [`Watcher`]'s next values.
    -395///
    -396/// See [`Watcher::stream`] and [`Watcher::stream_updates_only`].
    -397///
    -398/// # Cancel Safety
    -399///
    -400/// This stream is cancel-safe.
    -401#[derive(Debug, Clone)]
    -402pub struct Stream<W: Watcher + Unpin> {
    -403    initial: Option<W::Value>,
    -404    watcher: W,
    -405}
    -406
    -407impl<W: Watcher + Unpin> n0_future::stream::Stream for Stream<W>
    -408where
    -409    W::Value: Unpin,
    -410{
    -411    type Item = W::Value;
    -412
    -413    fn poll_next(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> {
    -414        if let Some(value) = self.as_mut().initial.take() {
    -415            return Poll::Ready(Some(value));
    -416        }
    -417        match self.as_mut().watcher.poll_updated(cx) {
    -418            Poll::Ready(Ok(value)) => Poll::Ready(Some(value)),
    -419            Poll::Ready(Err(_)) => Poll::Ready(None),
    -420            Poll::Pending => Poll::Pending,
    -421        }
    -422    }
    -423}
    -424
    -425/// The error for when a [`Watcher`] is disconnected from its underlying
    -426/// [`Watchable`] value, because of that watchable having been dropped.
    -427#[derive(Debug, Snafu)]
    -428#[snafu(display("Watch lost connection to underlying Watchable, it was dropped"))]
    -429pub struct Disconnected {
    -430    backtrace: Option<snafu::Backtrace>,
    -431    #[snafu(implicit)]
    -432    span_trace: n0_snafu::SpanTrace,
    -433}
    -434
    -435// Private:
    -436
    -437const INITIAL_EPOCH: u64 = 1;
    -438
    -439/// The shared state for a [`Watchable`].
    -440#[derive(Debug, Default)]
    -441struct Shared<T> {
    -442    /// The value to be watched and its current epoch.
    -443    state: RwLock<State<T>>,
    -444    watchers: Mutex<VecDeque<Waker>>,
    -445}
    -446
    -447#[derive(Debug)]
    -448struct State<T> {
    -449    value: T,
    -450    epoch: u64,
    -451}
    -452
    -453impl<T: Default> Default for State<T> {
    -454    fn default() -> Self {
    -455        Self {
    -456            value: Default::default(),
    -457            epoch: INITIAL_EPOCH,
    -458        }
    -459    }
    -460}
    -461
    -462impl<T: Clone> Shared<T> {
    -463    /// Returns the value, initialized or not.
    -464    fn get(&self) -> T {
    -465        self.state.read().expect("poisoned").value.clone()
    -466    }
    -467
    -468    fn poll_updated(&self, cx: &mut task::Context<'_>, last_epoch: u64) -> Poll<(u64, T)> {
    -469        {
    -470            let state = self.state.read().expect("poisoned");
    -471            let epoch = state.epoch;
    -472
    -473            if last_epoch < epoch {
    -474                // Once initialized, our Option is never set back to None, but nevertheless
    -475                // this code is safer without relying on that invariant.
    -476                return Poll::Ready((epoch, state.value.clone()));
    -477            }
    -478        }
    -479
    -480        self.watchers
    -481            .lock()
    -482            .expect("poisoned")
    -483            .push_back(cx.waker().to_owned());
    -484
    -485        #[cfg(iroh_loom)]
    -486        loom::thread::yield_now();
    -487
    -488        {
    -489            let state = self.state.read().expect("poisoned");
    -490            let epoch = state.epoch;
    -491
    -492            if last_epoch < epoch {
    -493                // Once initialized our Option is never set back to None, but nevertheless
    -494                // this code is safer without relying on that invariant.
    -495                return Poll::Ready((epoch, state.value.clone()));
    -496            }
    -497        }
    -498
    -499        Poll::Pending
    -500    }
    -501}
    -502
    -503#[cfg(test)]
    -504mod tests {
    -505    use std::time::{Duration, Instant};
    -506
    -507    use n0_future::StreamExt;
    -508    use rand::{thread_rng, Rng};
    -509    use tokio::task::JoinSet;
    -510    use tokio_util::sync::CancellationToken;
    -511
    -512    use super::*;
    -513
    -514    #[tokio::test]
    -515    async fn test_watcher() {
    -516        let cancel = CancellationToken::new();
    -517        let watchable = Watchable::new(17);
    -518
    -519        assert_eq!(watchable.watch().stream().next().await.unwrap(), 17);
    -520
    -521        let start = Instant::now();
    -522        // spawn watchers
    -523        let mut tasks = JoinSet::new();
    -524        for i in 0..3 {
    -525            let mut watch = watchable.watch().stream();
    -526            let cancel = cancel.clone();
    -527            tasks.spawn(async move {
    -528                println!("[{i}] spawn");
    -529                let mut expected_value = 17;
    -530                loop {
    -531                    tokio::select! {
    -532                        biased;
    -533                        Some(value) = &mut watch.next() => {
    -534                            println!("{:?} [{i}] update: {value}", start.elapsed());
    -535                            assert_eq!(value, expected_value);
    -536                            if expected_value == 17 {
    -537                                expected_value = 0;
    -538                            } else {
    -539                                expected_value += 1;
    -540                            }
    -541                        },
    -542                        _ = cancel.cancelled() => {
    -543                            println!("{:?} [{i}] cancel", start.elapsed());
    -544                            assert_eq!(expected_value, 10);
    -545                            break;
    -546                        }
    -547                    }
    -548                }
    -549            });
    -550        }
    -551        for i in 0..3 {
    -552            let mut watch = watchable.watch().stream_updates_only();
    -553            let cancel = cancel.clone();
    -554            tasks.spawn(async move {
    -555                println!("[{i}] spawn");
    -556                let mut expected_value = 0;
    -557                loop {
    -558                    tokio::select! {
    -559                        biased;
    -560                        Some(value) = watch.next() => {
    -561                            println!("{:?} [{i}] stream update: {value}", start.elapsed());
    -562                            assert_eq!(value, expected_value);
    -563                            expected_value += 1;
    -564                        },
    -565                        _ = cancel.cancelled() => {
    -566                            println!("{:?} [{i}] cancel", start.elapsed());
    -567                            assert_eq!(expected_value, 10);
    -568                            break;
    -569                        }
    -570                        else => {
    -571                            panic!("stream died");
    -572                        }
    -573                    }
    -574                }
    -575            });
    -576        }
    -577
    -578        // set value
    -579        for next_value in 0..10 {
    -580            let sleep = Duration::from_nanos(thread_rng().gen_range(0..100_000_000));
    -581            println!("{:?} sleep {sleep:?}", start.elapsed());
    -582            tokio::time::sleep(sleep).await;
    -583
    -584            let changed = watchable.set(next_value);
    -585            println!("{:?} set {next_value} changed={changed:?}", start.elapsed());
    -586        }
    -587
    -588        println!("cancel");
    -589        cancel.cancel();
    -590        while let Some(res) = tasks.join_next().await {
    -591            res.expect("task failed");
    -592        }
    -593    }
    -594
    -595    #[test]
    -596    fn test_get() {
    -597        let watchable = Watchable::new(None);
    -598        assert!(watchable.get().is_none());
    -599
    -600        watchable.set(Some(1u8)).ok();
    -601        assert_eq!(watchable.get(), Some(1u8));
    -602    }
    -603
    -604    #[tokio::test]
    -605    async fn test_initialize() {
    -606        let watchable = Watchable::new(None);
    -607
    -608        let mut watcher = watchable.watch();
    -609        let mut initialized = watcher.initialized();
    -610
    -611        let poll = n0_future::future::poll_once(&mut initialized).await;
    -612        assert!(poll.is_none());
    -613
    -614        watchable.set(Some(1u8)).ok();
    -615
    -616        let poll = n0_future::future::poll_once(&mut initialized).await;
    -617        assert_eq!(poll.unwrap().unwrap(), 1u8);
    -618    }
    -619
    -620    #[tokio::test]
    -621    async fn test_initialize_already_init() {
    -622        let watchable = Watchable::new(Some(1u8));
    -623
    -624        let mut watcher = watchable.watch();
    -625        let mut initialized = watcher.initialized();
    -626
    -627        let poll = n0_future::future::poll_once(&mut initialized).await;
    -628        assert_eq!(poll.unwrap().unwrap(), 1u8);
    -629    }
    -630
    -631    #[test]
    -632    fn test_initialized_always_resolves() {
    -633        #[cfg(not(iroh_loom))]
    -634        use std::thread;
    -635
    -636        #[cfg(iroh_loom)]
    -637        use loom::thread;
    -638
    -639        let test_case = || {
    -640            let watchable = Watchable::<Option<u8>>::new(None);
    -641
    -642            let mut watch = watchable.watch();
    -643            let thread = thread::spawn(move || n0_future::future::block_on(watch.initialized()));
    -644
    -645            watchable.set(Some(42)).ok();
    -646
    -647            thread::yield_now();
    -648
    -649            let value: u8 = thread.join().unwrap().unwrap();
    -650
    -651            assert_eq!(value, 42);
    -652        };
    -653
    -654        #[cfg(iroh_loom)]
    -655        loom::model(test_case);
    -656        #[cfg(not(iroh_loom))]
    -657        test_case();
    -658    }
    -659
    -660    #[tokio::test(flavor = "multi_thread")]
    -661    async fn test_update_cancel_safety() {
    -662        let watchable = Watchable::new(0);
    -663        let mut watch = watchable.watch();
    -664        const MAX: usize = 100_000;
    -665
    -666        let handle = tokio::spawn(async move {
    -667            let mut last_observed = 0;
    -668
    -669            while last_observed != MAX {
    -670                tokio::select! {
    -671                    val = watch.updated() => {
    -672                        let Ok(val) = val else {
    -673                            return;
    -674                        };
    -675
    -676                        assert_ne!(val, last_observed, "never observe the same value twice, even with cancellation");
    -677                        last_observed = val;
    -678                    }
    -679                    _ = tokio::time::sleep(Duration::from_micros(thread_rng().gen_range(0..10_000))) => {
    -680                        // We cancel the other future and start over again
    -681                        continue;
    -682                    }
    -683                }
    -684            }
    -685        });
    -686
    -687        for i in 1..=MAX {
    -688            watchable.set(i).ok();
    -689            if thread_rng().gen_bool(0.2) {
    -690                tokio::task::yield_now().await;
    -691            }
    -692        }
    -693
    -694        tokio::time::timeout(Duration::from_secs(10), handle)
    -695            .await
    -696            .unwrap()
    -697            .unwrap()
    -698    }
    -699}
    \ No newline at end of file diff --git a/pr/3327/docs/src/iroh_bench/iroh.rs.html b/pr/3327/docs/src/iroh_bench/iroh.rs.html index 80b93dd839..51fff78d49 100644 --- a/pr/3327/docs/src/iroh_bench/iroh.rs.html +++ b/pr/3327/docs/src/iroh_bench/iroh.rs.html @@ -6,10 +6,10 @@ 6use bytes::Bytes; 7use iroh::{ 8 endpoint::{Connection, ConnectionError, RecvStream, SendStream, TransportConfig}, -9 watcher::Watcher as _, -10 Endpoint, NodeAddr, RelayMode, RelayUrl, -11}; -12use n0_snafu::{Result, ResultExt}; +9 Endpoint, NodeAddr, RelayMode, RelayUrl, +10}; +11use n0_snafu::{Result, ResultExt}; +12use n0_watcher::Watcher as _; 13use tracing::{trace, warn}; 14 15use crate::{ @@ -54,7 +54,7 @@ 54 } 55 56 let addr = ep.bound_sockets(); -57 let addr = SocketAddr::new("127.0.0.1".parse().unwrap(), addr.0.port()); +57 let addr = SocketAddr::new("127.0.0.1".parse().unwrap(), addr[0].port()); 58 let mut addr = NodeAddr::new(ep.node_id()).with_direct_addresses([addr]); 59 if let Some(relay_url) = relay_url { 60 addr = addr.with_relay_url(relay_url.clone()); diff --git a/pr/3327/docs/src/iroh_relay/client/tls.rs.html b/pr/3327/docs/src/iroh_relay/client/tls.rs.html index 804978ff96..0d42792665 100644 --- a/pr/3327/docs/src/iroh_relay/client/tls.rs.html +++ b/pr/3327/docs/src/iroh_relay/client/tls.rs.html @@ -131,7 +131,7 @@ 131 } 132 } 133 -134 fn tls_servername(&self) -> Option<rustls::pki_types::ServerName> { +134 fn tls_servername(&self) -> Option<rustls::pki_types::ServerName<'_>> { 135 let host_str = self.url.host_str()?; 136 let servername = rustls::pki_types::ServerName::try_from(host_str).ok()?; 137 Some(servername) diff --git a/pr/3327/docs/src/iroh_relay/dns.rs.html b/pr/3327/docs/src/iroh_relay/dns.rs.html index 38365577d7..75df2ec82f 100644 --- a/pr/3327/docs/src/iroh_relay/dns.rs.html +++ b/pr/3327/docs/src/iroh_relay/dns.rs.html @@ -13,7 +13,7 @@ 13 StreamExt, 14}; 15use nested_enum_utils::common_fields; -16use snafu::{Backtrace, OptionExt, Snafu}; +16use snafu::{Backtrace, GenerateImplicitData, OptionExt, Snafu}; 17use url::Url; 18 19use crate::{ @@ -54,474 +54,459 @@ 54 }, 55 #[snafu(display("invalid DNS response: not a query for _iroh.z32encodedpubkey"))] 56 InvalidResponse {}, -57 #[snafu(display("no calls succeeded: [{}]", errors.iter().map(|e| e.to_string()).collect::<Vec<_>>().join("")))] -58 Staggered { errors: Vec<DnsError> }, -59} -60 -61// TODO(matheus23): Remove this, or remove DnsError::Staggered, but don't keep both. -62mod staggered { -63 use snafu::{Backtrace, GenerateImplicitData, Snafu}; -64 -65 use super::LookupError; -66 -67 /// Error returned when an input value is too long for [`crate::node_info::UserData`]. -68 #[allow(missing_docs)] -69 #[derive(Debug, Snafu)] -70 #[snafu(display("no calls succeeded: [{}]", errors.iter().map(|e| e.to_string()).collect::<Vec<_>>().join("")))] -71 pub struct Error { -72 backtrace: Option<Backtrace>, -73 #[snafu(implicit)] -74 span_trace: n0_snafu::SpanTrace, -75 errors: Vec<LookupError>, -76 } -77 -78 impl Error { -79 pub(crate) fn new(errors: Vec<LookupError>) -> Self { -80 Self { -81 errors, -82 backtrace: GenerateImplicitData::generate(), -83 span_trace: n0_snafu::SpanTrace::generate(), -84 } -85 } -86 } -87} -88 -89pub use staggered::*; -90 -91/// The DNS resolver used throughout `iroh`. -92#[derive(Debug, Clone)] -93pub struct DnsResolver(TokioResolver); +57} +58 +59/// Error returned when an input value is too long for [`crate::node_info::UserData`]. +60#[allow(missing_docs)] +61#[derive(Debug, Snafu)] +62#[snafu(module)] +63#[snafu(display("no calls succeeded: [{}]", errors.iter().map(|e| e.to_string()).collect::<Vec<_>>().join("")))] +64pub struct StaggeredError<E: std::fmt::Debug + std::fmt::Display> { +65 backtrace: Option<Backtrace>, +66 #[snafu(implicit)] +67 span_trace: n0_snafu::SpanTrace, +68 errors: Vec<E>, +69} +70 +71impl<E: std::fmt::Debug + std::fmt::Display> StaggeredError<E> { +72 pub(crate) fn new(errors: Vec<E>) -> Self { +73 Self { +74 errors, +75 backtrace: GenerateImplicitData::generate(), +76 span_trace: n0_snafu::SpanTrace::generate(), +77 } +78 } +79} +80 +81/// The DNS resolver used throughout `iroh`. +82#[derive(Debug, Clone)] +83pub struct DnsResolver(TokioResolver); +84 +85impl DnsResolver { +86 /// Create a new DNS resolver with sensible cross-platform defaults. +87 /// +88 /// We first try to read the system's resolver from `/etc/resolv.conf`. +89 /// This does not work at least on some Androids, therefore we fallback +90 /// to the default `ResolverConfig` which uses eg. to google's `8.8.8.8` or `8.8.4.4`. +91 pub fn new() -> Self { +92 let (system_config, mut options) = +93 hickory_resolver::system_conf::read_system_conf().unwrap_or_default(); 94 -95impl DnsResolver { -96 /// Create a new DNS resolver with sensible cross-platform defaults. -97 /// -98 /// We first try to read the system's resolver from `/etc/resolv.conf`. -99 /// This does not work at least on some Androids, therefore we fallback -100 /// to the default `ResolverConfig` which uses eg. to google's `8.8.8.8` or `8.8.4.4`. -101 pub fn new() -> Self { -102 let (system_config, mut options) = -103 hickory_resolver::system_conf::read_system_conf().unwrap_or_default(); -104 -105 // Copy all of the system config, but strip the bad windows nameservers. Unfortunately -106 // there is no easy way to do this. -107 let mut config = hickory_resolver::config::ResolverConfig::new(); -108 if let Some(name) = system_config.domain() { -109 config.set_domain(name.clone()); -110 } -111 for name in system_config.search() { -112 config.add_search(name.clone()); -113 } -114 for nameserver_cfg in system_config.name_servers() { -115 if !WINDOWS_BAD_SITE_LOCAL_DNS_SERVERS.contains(&nameserver_cfg.socket_addr.ip()) { -116 config.add_name_server(nameserver_cfg.clone()); -117 } -118 } -119 -120 // see [`DnsResolver::lookup_ipv4_ipv6`] for info on why we avoid `LookupIpStrategy::Ipv4AndIpv6` -121 options.ip_strategy = hickory_resolver::config::LookupIpStrategy::Ipv4thenIpv6; -122 -123 let mut builder = -124 TokioResolver::builder_with_config(config, TokioConnectionProvider::default()); -125 *builder.options_mut() = options; -126 DnsResolver(builder.build()) -127 } -128 -129 /// Create a new DNS resolver configured with a single UDP DNS nameserver. -130 pub fn with_nameserver(nameserver: SocketAddr) -> Self { -131 let mut config = hickory_resolver::config::ResolverConfig::new(); -132 let nameserver_config = hickory_resolver::config::NameServerConfig::new( -133 nameserver, -134 hickory_resolver::proto::xfer::Protocol::Udp, -135 ); -136 config.add_name_server(nameserver_config); +95 // Copy all of the system config, but strip the bad windows nameservers. Unfortunately +96 // there is no easy way to do this. +97 let mut config = hickory_resolver::config::ResolverConfig::new(); +98 if let Some(name) = system_config.domain() { +99 config.set_domain(name.clone()); +100 } +101 for name in system_config.search() { +102 config.add_search(name.clone()); +103 } +104 for nameserver_cfg in system_config.name_servers() { +105 if !WINDOWS_BAD_SITE_LOCAL_DNS_SERVERS.contains(&nameserver_cfg.socket_addr.ip()) { +106 config.add_name_server(nameserver_cfg.clone()); +107 } +108 } +109 +110 // see [`DnsResolver::lookup_ipv4_ipv6`] for info on why we avoid `LookupIpStrategy::Ipv4AndIpv6` +111 options.ip_strategy = hickory_resolver::config::LookupIpStrategy::Ipv4thenIpv6; +112 +113 let mut builder = +114 TokioResolver::builder_with_config(config, TokioConnectionProvider::default()); +115 *builder.options_mut() = options; +116 DnsResolver(builder.build()) +117 } +118 +119 /// Create a new DNS resolver configured with a single UDP DNS nameserver. +120 pub fn with_nameserver(nameserver: SocketAddr) -> Self { +121 let mut config = hickory_resolver::config::ResolverConfig::new(); +122 let nameserver_config = hickory_resolver::config::NameServerConfig::new( +123 nameserver, +124 hickory_resolver::proto::xfer::Protocol::Udp, +125 ); +126 config.add_name_server(nameserver_config); +127 +128 let builder = +129 TokioResolver::builder_with_config(config, TokioConnectionProvider::default()); +130 DnsResolver(builder.build()) +131 } +132 +133 /// Removes all entries from the cache. +134 pub fn clear_cache(&self) { +135 self.0.clear_cache(); +136 } 137 -138 let builder = -139 TokioResolver::builder_with_config(config, TokioConnectionProvider::default()); -140 DnsResolver(builder.build()) -141 } -142 -143 /// Removes all entries from the cache. -144 pub fn clear_cache(&self) { -145 self.0.clear_cache(); -146 } -147 -148 /// Lookup a TXT record. -149 pub async fn lookup_txt( -150 &self, -151 host: impl ToString, -152 timeout: Duration, -153 ) -> Result<TxtLookup, DnsError> { -154 let host = host.to_string(); -155 let res = time::timeout(timeout, self.0.txt_lookup(host)).await??; -156 Ok(TxtLookup(res)) -157 } -158 -159 /// Perform an ipv4 lookup with a timeout. -160 pub async fn lookup_ipv4( -161 &self, -162 host: impl ToString, -163 timeout: Duration, -164 ) -> Result<impl Iterator<Item = IpAddr>, DnsError> { -165 let host = host.to_string(); -166 let addrs = time::timeout(timeout, self.0.ipv4_lookup(host)).await??; -167 Ok(addrs.into_iter().map(|ip| IpAddr::V4(ip.0))) -168 } -169 -170 /// Perform an ipv6 lookup with a timeout. -171 pub async fn lookup_ipv6( -172 &self, -173 host: impl ToString, -174 timeout: Duration, -175 ) -> Result<impl Iterator<Item = IpAddr>, DnsError> { -176 let host = host.to_string(); -177 let addrs = time::timeout(timeout, self.0.ipv6_lookup(host)).await??; -178 Ok(addrs.into_iter().map(|ip| IpAddr::V6(ip.0))) -179 } -180 -181 /// Resolve IPv4 and IPv6 in parallel with a timeout. -182 /// -183 /// `LookupIpStrategy::Ipv4AndIpv6` will wait for ipv6 resolution timeout, even if it is -184 /// not usable on the stack, so we manually query both lookups concurrently and time them out -185 /// individually. -186 pub async fn lookup_ipv4_ipv6( -187 &self, -188 host: impl ToString, -189 timeout: Duration, -190 ) -> Result<impl Iterator<Item = IpAddr>, DnsError> { -191 let host = host.to_string(); -192 let res = tokio::join!( -193 self.lookup_ipv4(host.clone(), timeout), -194 self.lookup_ipv6(host, timeout) -195 ); -196 -197 match res { -198 (Ok(ipv4), Ok(ipv6)) => Ok(LookupIter::Both(ipv4.chain(ipv6))), -199 (Ok(ipv4), Err(_)) => Ok(LookupIter::Ipv4(ipv4)), -200 (Err(_), Ok(ipv6)) => Ok(LookupIter::Ipv6(ipv6)), -201 (Err(ipv4_err), Err(ipv6_err)) => Err(ResolveBothSnafu { -202 ipv4: Box::new(ipv4_err), -203 ipv6: Box::new(ipv6_err), -204 } -205 .build()), -206 } -207 } -208 -209 /// Resolve a hostname from a URL to an IP address. -210 pub async fn resolve_host( -211 &self, -212 url: &Url, -213 prefer_ipv6: bool, -214 timeout: Duration, -215 ) -> Result<IpAddr, DnsError> { -216 let host = url.host().context(MissingHostSnafu)?; -217 match host { -218 url::Host::Domain(domain) => { -219 // Need to do a DNS lookup -220 let lookup = tokio::join!( -221 self.lookup_ipv4(domain, timeout), -222 self.lookup_ipv6(domain, timeout) -223 ); -224 let (v4, v6) = match lookup { -225 (Err(ipv4_err), Err(ipv6_err)) => { -226 return Err(ResolveBothSnafu { -227 ipv4: Box::new(ipv4_err), -228 ipv6: Box::new(ipv6_err), -229 } -230 .build()); -231 } -232 (Err(_), Ok(mut v6)) => (None, v6.next()), -233 (Ok(mut v4), Err(_)) => (v4.next(), None), -234 (Ok(mut v4), Ok(mut v6)) => (v4.next(), v6.next()), -235 }; -236 if prefer_ipv6 { -237 v6.or(v4).context(NoResponseSnafu) -238 } else { -239 v4.or(v6).context(NoResponseSnafu) -240 } -241 } -242 url::Host::Ipv4(ip) => Ok(IpAddr::V4(ip)), -243 url::Host::Ipv6(ip) => Ok(IpAddr::V6(ip)), -244 } -245 } -246 -247 /// Perform an ipv4 lookup with a timeout in a staggered fashion. -248 /// -249 /// From the moment this function is called, each lookup is scheduled after the delays in -250 /// `delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls -251 /// at T+0ms, T+200ms and T+300ms. The `timeout` is applied to each call individually. The -252 /// result of the first successful call is returned, or a summary of all errors otherwise. -253 pub async fn lookup_ipv4_staggered( -254 &self, -255 host: impl ToString, -256 timeout: Duration, -257 delays_ms: &[u64], -258 ) -> Result<impl Iterator<Item = IpAddr>, DnsError> { -259 let host = host.to_string(); -260 let f = || self.lookup_ipv4(host.clone(), timeout); -261 stagger_call(f, delays_ms) -262 .await -263 .map_err(|errors| StaggeredSnafu { errors }.build()) -264 } -265 -266 /// Perform an ipv6 lookup with a timeout in a staggered fashion. -267 /// -268 /// From the moment this function is called, each lookup is scheduled after the delays in -269 /// `delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls -270 /// at T+0ms, T+200ms and T+300ms. The `timeout` is applied to each call individually. The -271 /// result of the first successful call is returned, or a summary of all errors otherwise. -272 pub async fn lookup_ipv6_staggered( -273 &self, -274 host: impl ToString, -275 timeout: Duration, -276 delays_ms: &[u64], -277 ) -> Result<impl Iterator<Item = IpAddr>, DnsError> { -278 let host = host.to_string(); -279 let f = || self.lookup_ipv6(host.clone(), timeout); -280 stagger_call(f, delays_ms) -281 .await -282 .map_err(|errors| StaggeredSnafu { errors }.build()) -283 } -284 -285 /// Race an ipv4 and ipv6 lookup with a timeout in a staggered fashion. -286 /// -287 /// From the moment this function is called, each lookup is scheduled after the delays in -288 /// `delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls -289 /// at T+0ms, T+200ms and T+300ms. The `timeout` is applied as stated in -290 /// [`Self::lookup_ipv4_ipv6`]. The result of the first successful call is returned, or a -291 /// summary of all errors otherwise. -292 pub async fn lookup_ipv4_ipv6_staggered( -293 &self, -294 host: impl ToString, -295 timeout: Duration, -296 delays_ms: &[u64], -297 ) -> Result<impl Iterator<Item = IpAddr>, DnsError> { -298 let host = host.to_string(); -299 let f = || self.lookup_ipv4_ipv6(host.clone(), timeout); -300 stagger_call(f, delays_ms) -301 .await -302 .map_err(|errors| StaggeredSnafu { errors }.build()) -303 } -304 -305 /// Looks up node info by [`NodeId`] and origin domain name. -306 /// -307 /// To lookup nodes that published their node info to the DNS servers run by n0, -308 /// pass [`N0_DNS_NODE_ORIGIN_PROD`] as `origin`. -309 pub async fn lookup_node_by_id( -310 &self, -311 node_id: &NodeId, -312 origin: &str, -313 ) -> Result<NodeInfo, LookupError> { -314 let attrs = crate::node_info::TxtAttrs::<crate::node_info::IrohAttr>::lookup_by_id( -315 self, node_id, origin, -316 ) -317 .await?; -318 let info = attrs.into(); -319 Ok(info) -320 } -321 -322 /// Looks up node info by DNS name. -323 pub async fn lookup_node_by_domain_name(&self, name: &str) -> Result<NodeInfo, LookupError> { -324 let attrs = -325 crate::node_info::TxtAttrs::<crate::node_info::IrohAttr>::lookup_by_name(self, name) -326 .await?; -327 let info = attrs.into(); -328 Ok(info) -329 } -330 -331 /// Looks up node info by DNS name in a staggered fashion. -332 /// -333 /// From the moment this function is called, each lookup is scheduled after the delays in -334 /// `delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls -335 /// at T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a -336 /// summary of all errors otherwise. -337 pub async fn lookup_node_by_domain_name_staggered( -338 &self, -339 name: &str, +138 /// Lookup a TXT record. +139 pub async fn lookup_txt( +140 &self, +141 host: impl ToString, +142 timeout: Duration, +143 ) -> Result<TxtLookup, DnsError> { +144 let host = host.to_string(); +145 let res = time::timeout(timeout, self.0.txt_lookup(host)).await??; +146 Ok(TxtLookup(res)) +147 } +148 +149 /// Perform an ipv4 lookup with a timeout. +150 pub async fn lookup_ipv4( +151 &self, +152 host: impl ToString, +153 timeout: Duration, +154 ) -> Result<impl Iterator<Item = IpAddr>, DnsError> { +155 let host = host.to_string(); +156 let addrs = time::timeout(timeout, self.0.ipv4_lookup(host)).await??; +157 Ok(addrs.into_iter().map(|ip| IpAddr::V4(ip.0))) +158 } +159 +160 /// Perform an ipv6 lookup with a timeout. +161 pub async fn lookup_ipv6( +162 &self, +163 host: impl ToString, +164 timeout: Duration, +165 ) -> Result<impl Iterator<Item = IpAddr>, DnsError> { +166 let host = host.to_string(); +167 let addrs = time::timeout(timeout, self.0.ipv6_lookup(host)).await??; +168 Ok(addrs.into_iter().map(|ip| IpAddr::V6(ip.0))) +169 } +170 +171 /// Resolve IPv4 and IPv6 in parallel with a timeout. +172 /// +173 /// `LookupIpStrategy::Ipv4AndIpv6` will wait for ipv6 resolution timeout, even if it is +174 /// not usable on the stack, so we manually query both lookups concurrently and time them out +175 /// individually. +176 pub async fn lookup_ipv4_ipv6( +177 &self, +178 host: impl ToString, +179 timeout: Duration, +180 ) -> Result<impl Iterator<Item = IpAddr>, DnsError> { +181 let host = host.to_string(); +182 let res = tokio::join!( +183 self.lookup_ipv4(host.clone(), timeout), +184 self.lookup_ipv6(host, timeout) +185 ); +186 +187 match res { +188 (Ok(ipv4), Ok(ipv6)) => Ok(LookupIter::Both(ipv4.chain(ipv6))), +189 (Ok(ipv4), Err(_)) => Ok(LookupIter::Ipv4(ipv4)), +190 (Err(_), Ok(ipv6)) => Ok(LookupIter::Ipv6(ipv6)), +191 (Err(ipv4_err), Err(ipv6_err)) => Err(ResolveBothSnafu { +192 ipv4: Box::new(ipv4_err), +193 ipv6: Box::new(ipv6_err), +194 } +195 .build()), +196 } +197 } +198 +199 /// Resolve a hostname from a URL to an IP address. +200 pub async fn resolve_host( +201 &self, +202 url: &Url, +203 prefer_ipv6: bool, +204 timeout: Duration, +205 ) -> Result<IpAddr, DnsError> { +206 let host = url.host().context(MissingHostSnafu)?; +207 match host { +208 url::Host::Domain(domain) => { +209 // Need to do a DNS lookup +210 let lookup = tokio::join!( +211 self.lookup_ipv4(domain, timeout), +212 self.lookup_ipv6(domain, timeout) +213 ); +214 let (v4, v6) = match lookup { +215 (Err(ipv4_err), Err(ipv6_err)) => { +216 return Err(ResolveBothSnafu { +217 ipv4: Box::new(ipv4_err), +218 ipv6: Box::new(ipv6_err), +219 } +220 .build()); +221 } +222 (Err(_), Ok(mut v6)) => (None, v6.next()), +223 (Ok(mut v4), Err(_)) => (v4.next(), None), +224 (Ok(mut v4), Ok(mut v6)) => (v4.next(), v6.next()), +225 }; +226 if prefer_ipv6 { +227 v6.or(v4).context(NoResponseSnafu) +228 } else { +229 v4.or(v6).context(NoResponseSnafu) +230 } +231 } +232 url::Host::Ipv4(ip) => Ok(IpAddr::V4(ip)), +233 url::Host::Ipv6(ip) => Ok(IpAddr::V6(ip)), +234 } +235 } +236 +237 /// Perform an ipv4 lookup with a timeout in a staggered fashion. +238 /// +239 /// From the moment this function is called, each lookup is scheduled after the delays in +240 /// `delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls +241 /// at T+0ms, T+200ms and T+300ms. The `timeout` is applied to each call individually. The +242 /// result of the first successful call is returned, or a summary of all errors otherwise. +243 pub async fn lookup_ipv4_staggered( +244 &self, +245 host: impl ToString, +246 timeout: Duration, +247 delays_ms: &[u64], +248 ) -> Result<impl Iterator<Item = IpAddr>, StaggeredError<DnsError>> { +249 let host = host.to_string(); +250 let f = || self.lookup_ipv4(host.clone(), timeout); +251 stagger_call(f, delays_ms).await +252 } +253 +254 /// Perform an ipv6 lookup with a timeout in a staggered fashion. +255 /// +256 /// From the moment this function is called, each lookup is scheduled after the delays in +257 /// `delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls +258 /// at T+0ms, T+200ms and T+300ms. The `timeout` is applied to each call individually. The +259 /// result of the first successful call is returned, or a summary of all errors otherwise. +260 pub async fn lookup_ipv6_staggered( +261 &self, +262 host: impl ToString, +263 timeout: Duration, +264 delays_ms: &[u64], +265 ) -> Result<impl Iterator<Item = IpAddr>, StaggeredError<DnsError>> { +266 let host = host.to_string(); +267 let f = || self.lookup_ipv6(host.clone(), timeout); +268 stagger_call(f, delays_ms).await +269 } +270 +271 /// Race an ipv4 and ipv6 lookup with a timeout in a staggered fashion. +272 /// +273 /// From the moment this function is called, each lookup is scheduled after the delays in +274 /// `delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls +275 /// at T+0ms, T+200ms and T+300ms. The `timeout` is applied as stated in +276 /// [`Self::lookup_ipv4_ipv6`]. The result of the first successful call is returned, or a +277 /// summary of all errors otherwise. +278 pub async fn lookup_ipv4_ipv6_staggered( +279 &self, +280 host: impl ToString, +281 timeout: Duration, +282 delays_ms: &[u64], +283 ) -> Result<impl Iterator<Item = IpAddr>, StaggeredError<DnsError>> { +284 let host = host.to_string(); +285 let f = || self.lookup_ipv4_ipv6(host.clone(), timeout); +286 stagger_call(f, delays_ms).await +287 } +288 +289 /// Looks up node info by [`NodeId`] and origin domain name. +290 /// +291 /// To lookup nodes that published their node info to the DNS servers run by n0, +292 /// pass [`N0_DNS_NODE_ORIGIN_PROD`] as `origin`. +293 pub async fn lookup_node_by_id( +294 &self, +295 node_id: &NodeId, +296 origin: &str, +297 ) -> Result<NodeInfo, LookupError> { +298 let attrs = crate::node_info::TxtAttrs::<crate::node_info::IrohAttr>::lookup_by_id( +299 self, node_id, origin, +300 ) +301 .await?; +302 let info = attrs.into(); +303 Ok(info) +304 } +305 +306 /// Looks up node info by DNS name. +307 pub async fn lookup_node_by_domain_name(&self, name: &str) -> Result<NodeInfo, LookupError> { +308 let attrs = +309 crate::node_info::TxtAttrs::<crate::node_info::IrohAttr>::lookup_by_name(self, name) +310 .await?; +311 let info = attrs.into(); +312 Ok(info) +313 } +314 +315 /// Looks up node info by DNS name in a staggered fashion. +316 /// +317 /// From the moment this function is called, each lookup is scheduled after the delays in +318 /// `delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls +319 /// at T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a +320 /// summary of all errors otherwise. +321 pub async fn lookup_node_by_domain_name_staggered( +322 &self, +323 name: &str, +324 delays_ms: &[u64], +325 ) -> Result<NodeInfo, StaggeredError<LookupError>> { +326 let f = || self.lookup_node_by_domain_name(name); +327 stagger_call(f, delays_ms).await +328 } +329 +330 /// Looks up node info by [`NodeId`] and origin domain name. +331 /// +332 /// From the moment this function is called, each lookup is scheduled after the delays in +333 /// `delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls +334 /// at T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a +335 /// summary of all errors otherwise. +336 pub async fn lookup_node_by_id_staggered( +337 &self, +338 node_id: &NodeId, +339 origin: &str, 340 delays_ms: &[u64], -341 ) -> Result<NodeInfo, staggered::Error> { -342 let f = || self.lookup_node_by_domain_name(name); -343 stagger_call(f, delays_ms) -344 .await -345 .map_err(staggered::Error::new) -346 } -347 -348 /// Looks up node info by [`NodeId`] and origin domain name. -349 /// -350 /// From the moment this function is called, each lookup is scheduled after the delays in -351 /// `delays_ms` with the first call being done immediately. `[200ms, 300ms]` results in calls -352 /// at T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a -353 /// summary of all errors otherwise. -354 pub async fn lookup_node_by_id_staggered( -355 &self, -356 node_id: &NodeId, -357 origin: &str, -358 delays_ms: &[u64], -359 ) -> Result<NodeInfo, staggered::Error> { -360 let f = || self.lookup_node_by_id(node_id, origin); -361 stagger_call(f, delays_ms) -362 .await -363 .map_err(staggered::Error::new) -364 } -365} -366 -367impl Default for DnsResolver { -368 fn default() -> Self { -369 Self::new() -370 } -371} -372 -373impl From<TokioResolver> for DnsResolver { -374 fn from(resolver: TokioResolver) -> Self { -375 DnsResolver(resolver) -376 } -377} -378 -379impl reqwest::dns::Resolve for DnsResolver { -380 fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving { -381 let this = self.clone(); -382 let name = name.as_str().to_string(); -383 Box::pin(async move { -384 let res = this.lookup_ipv4_ipv6(name, DNS_TIMEOUT).await; -385 match res { -386 Ok(addrs) => { -387 let addrs: reqwest::dns::Addrs = -388 Box::new(addrs.map(|addr| SocketAddr::new(addr, 0))); -389 Ok(addrs) -390 } -391 Err(err) => { -392 let err: Box<dyn std::error::Error + Send + Sync> = Box::new(err); -393 Err(err) -394 } -395 } -396 }) +341 ) -> Result<NodeInfo, StaggeredError<LookupError>> { +342 let f = || self.lookup_node_by_id(node_id, origin); +343 stagger_call(f, delays_ms).await +344 } +345} +346 +347impl Default for DnsResolver { +348 fn default() -> Self { +349 Self::new() +350 } +351} +352 +353impl From<TokioResolver> for DnsResolver { +354 fn from(resolver: TokioResolver) -> Self { +355 DnsResolver(resolver) +356 } +357} +358 +359impl reqwest::dns::Resolve for DnsResolver { +360 fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving { +361 let this = self.clone(); +362 let name = name.as_str().to_string(); +363 Box::pin(async move { +364 let res = this.lookup_ipv4_ipv6(name, DNS_TIMEOUT).await; +365 match res { +366 Ok(addrs) => { +367 let addrs: reqwest::dns::Addrs = +368 Box::new(addrs.map(|addr| SocketAddr::new(addr, 0))); +369 Ok(addrs) +370 } +371 Err(err) => { +372 let err: Box<dyn std::error::Error + Send + Sync> = Box::new(err); +373 Err(err) +374 } +375 } +376 }) +377 } +378} +379 +380/// TXT records returned from [`DnsResolver::lookup_txt`] +381#[derive(Debug, Clone)] +382pub struct TxtLookup(pub(crate) hickory_resolver::lookup::TxtLookup); +383 +384impl From<hickory_resolver::lookup::TxtLookup> for TxtLookup { +385 fn from(value: hickory_resolver::lookup::TxtLookup) -> Self { +386 Self(value) +387 } +388} +389 +390impl IntoIterator for TxtLookup { +391 type Item = TXT; +392 +393 type IntoIter = Box<dyn Iterator<Item = TXT>>; +394 +395 fn into_iter(self) -> Self::IntoIter { +396 Box::new(self.0.into_iter().map(TXT)) 397 } 398} 399 -400/// TXT records returned from [`DnsResolver::lookup_txt`] +400/// Record data for a TXT record 401#[derive(Debug, Clone)] -402pub struct TxtLookup(pub(crate) hickory_resolver::lookup::TxtLookup); +402pub struct TXT(hickory_resolver::proto::rr::rdata::TXT); 403 -404impl From<hickory_resolver::lookup::TxtLookup> for TxtLookup { -405 fn from(value: hickory_resolver::lookup::TxtLookup) -> Self { -406 Self(value) -407 } -408} -409 -410impl IntoIterator for TxtLookup { -411 type Item = TXT; -412 -413 type IntoIter = Box<dyn Iterator<Item = TXT>>; -414 -415 fn into_iter(self) -> Self::IntoIter { -416 Box::new(self.0.into_iter().map(TXT)) -417 } -418} -419 -420/// Record data for a TXT record -421#[derive(Debug, Clone)] -422pub struct TXT(hickory_resolver::proto::rr::rdata::TXT); -423 -424impl TXT { -425 /// Returns the raw character strings of this TXT record. -426 pub fn txt_data(&self) -> &[Box<[u8]>] { -427 self.0.txt_data() -428 } -429} +404impl TXT { +405 /// Returns the raw character strings of this TXT record. +406 pub fn txt_data(&self) -> &[Box<[u8]>] { +407 self.0.txt_data() +408 } +409} +410 +411impl fmt::Display for TXT { +412 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { +413 write!(f, "{}", self.0) +414 } +415} +416 +417/// Deprecated IPv6 site-local anycast addresses still configured by windows. +418/// +419/// Windows still configures these site-local addresses as soon even as an IPv6 loopback +420/// interface is configured. We do not want to use these DNS servers, the chances of them +421/// being usable are almost always close to zero, while the chance of DNS configuration +422/// **only** relying on these servers and not also being configured normally are also almost +423/// zero. The chance of the DNS resolver accidentally trying one of these and taking a +424/// bunch of timeouts to figure out they're no good are on the other hand very high. +425const WINDOWS_BAD_SITE_LOCAL_DNS_SERVERS: [IpAddr; 3] = [ +426 IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 1)), +427 IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 2)), +428 IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 3)), +429]; 430 -431impl fmt::Display for TXT { -432 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { -433 write!(f, "{}", self.0) -434 } -435} -436 -437/// Deprecated IPv6 site-local anycast addresses still configured by windows. -438/// -439/// Windows still configures these site-local addresses as soon even as an IPv6 loopback -440/// interface is configured. We do not want to use these DNS servers, the chances of them -441/// being usable are almost always close to zero, while the chance of DNS configuration -442/// **only** relying on these servers and not also being configured normally are also almost -443/// zero. The chance of the DNS resolver accidentally trying one of these and taking a -444/// bunch of timeouts to figure out they're no good are on the other hand very high. -445const WINDOWS_BAD_SITE_LOCAL_DNS_SERVERS: [IpAddr; 3] = [ -446 IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 1)), -447 IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 2)), -448 IpAddr::V6(Ipv6Addr::new(0xfec0, 0, 0, 0xffff, 0, 0, 0, 3)), -449]; -450 -451/// Helper enum to give a unified type to the iterators of [`DnsResolver::lookup_ipv4_ipv6`]. -452enum LookupIter<A, B> { -453 Ipv4(A), -454 Ipv6(B), -455 Both(std::iter::Chain<A, B>), -456} -457 -458impl<A: Iterator<Item = IpAddr>, B: Iterator<Item = IpAddr>> Iterator for LookupIter<A, B> { -459 type Item = IpAddr; -460 -461 fn next(&mut self) -> Option<Self::Item> { -462 match self { -463 LookupIter::Ipv4(iter) => iter.next(), -464 LookupIter::Ipv6(iter) => iter.next(), -465 LookupIter::Both(iter) => iter.next(), -466 } -467 } -468} -469 -470/// Staggers calls to the future F with the given delays. -471/// -472/// The first call is performed immediately. The first call to succeed generates an Ok result -473/// ignoring any previous error. If all calls fail, an error summarizing all errors is returned. -474async fn stagger_call<T, E, F: Fn() -> Fut, Fut: Future<Output = Result<T, E>>>( -475 f: F, -476 delays_ms: &[u64], -477) -> Result<T, Vec<E>> { -478 let mut calls = n0_future::FuturesUnorderedBounded::new(delays_ms.len() + 1); -479 // NOTE: we add the 0 delay here to have a uniform set of futures. This is more performant than -480 // using alternatives that allow futures of different types. -481 for delay in std::iter::once(&0u64).chain(delays_ms) { -482 let delay = Duration::from_millis(*delay); -483 let fut = f(); -484 let staggered_fut = async move { -485 time::sleep(delay).await; -486 fut.await -487 }; -488 calls.push(staggered_fut) -489 } +431/// Helper enum to give a unified type to the iterators of [`DnsResolver::lookup_ipv4_ipv6`]. +432enum LookupIter<A, B> { +433 Ipv4(A), +434 Ipv6(B), +435 Both(std::iter::Chain<A, B>), +436} +437 +438impl<A: Iterator<Item = IpAddr>, B: Iterator<Item = IpAddr>> Iterator for LookupIter<A, B> { +439 type Item = IpAddr; +440 +441 fn next(&mut self) -> Option<Self::Item> { +442 match self { +443 LookupIter::Ipv4(iter) => iter.next(), +444 LookupIter::Ipv6(iter) => iter.next(), +445 LookupIter::Both(iter) => iter.next(), +446 } +447 } +448} +449 +450/// Staggers calls to the future F with the given delays. +451/// +452/// The first call is performed immediately. The first call to succeed generates an Ok result +453/// ignoring any previous error. If all calls fail, an error summarizing all errors is returned. +454async fn stagger_call< +455 T, +456 E: std::fmt::Debug + std::fmt::Display, +457 F: Fn() -> Fut, +458 Fut: Future<Output = Result<T, E>>, +459>( +460 f: F, +461 delays_ms: &[u64], +462) -> Result<T, StaggeredError<E>> { +463 let mut calls = n0_future::FuturesUnorderedBounded::new(delays_ms.len() + 1); +464 // NOTE: we add the 0 delay here to have a uniform set of futures. This is more performant than +465 // using alternatives that allow futures of different types. +466 for delay in std::iter::once(&0u64).chain(delays_ms) { +467 let delay = Duration::from_millis(*delay); +468 let fut = f(); +469 let staggered_fut = async move { +470 time::sleep(delay).await; +471 fut.await +472 }; +473 calls.push(staggered_fut) +474 } +475 +476 let mut errors = vec![]; +477 while let Some(call_result) = calls.next().await { +478 match call_result { +479 Ok(t) => return Ok(t), +480 Err(e) => errors.push(e), +481 } +482 } +483 +484 Err(StaggeredError::new(errors)) +485} +486 +487#[cfg(test)] +488pub(crate) mod tests { +489 use std::sync::atomic::AtomicUsize; 490 -491 let mut errors = vec![]; -492 while let Some(call_result) = calls.next().await { -493 match call_result { -494 Ok(t) => return Ok(t), -495 Err(e) => errors.push(e), -496 } -497 } -498 -499 Err(errors) -500} -501 -502#[cfg(test)] -503pub(crate) mod tests { -504 use std::sync::atomic::AtomicUsize; -505 -506 use tracing_test::traced_test; +491 use tracing_test::traced_test; +492 +493 use super::*; +494 +495 #[tokio::test] +496 #[traced_test] +497 async fn stagger_basic() { +498 const CALL_RESULTS: &[Result<u8, u8>] = &[Err(2), Ok(3), Ok(5), Ok(7)]; +499 static DONE_CALL: AtomicUsize = AtomicUsize::new(0); +500 let f = || { +501 let r_pos = DONE_CALL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); +502 async move { +503 tracing::info!(r_pos, "call"); +504 CALL_RESULTS[r_pos].map_err(|_| InvalidResponseSnafu.build()) +505 } +506 }; 507 -508 use super::*; -509 -510 #[tokio::test] -511 #[traced_test] -512 async fn stagger_basic() { -513 const CALL_RESULTS: &[Result<u8, u8>] = &[Err(2), Ok(3), Ok(5), Ok(7)]; -514 static DONE_CALL: AtomicUsize = AtomicUsize::new(0); -515 let f = || { -516 let r_pos = DONE_CALL.fetch_add(1, std::sync::atomic::Ordering::Relaxed); -517 async move { -518 tracing::info!(r_pos, "call"); -519 CALL_RESULTS[r_pos].map_err(|_| InvalidResponseSnafu.build()) -520 } -521 }; -522 -523 let delays = [1000, 15]; -524 let result = stagger_call(f, &delays).await.unwrap(); -525 assert_eq!(result, 5) -526 } -527} \ No newline at end of file +508 let delays = [1000, 15]; +509 let result = stagger_call(f, &delays).await.unwrap(); +510 assert_eq!(result, 5) +511 } +512} \ No newline at end of file diff --git a/pr/3327/docs/src/iroh_relay/quic.rs.html b/pr/3327/docs/src/iroh_relay/quic.rs.html index 383b9f5a0a..8137c5fcb1 100644 --- a/pr/3327/docs/src/iroh_relay/quic.rs.html +++ b/pr/3327/docs/src/iroh_relay/quic.rs.html @@ -276,7 +276,7 @@ 276 // we're sacrificing initial throughput, which is fine for 277 // QAD, which doesn't require us to have good initial throughput. 278 // It also implies a 999ms probe timeout, which means that -279 // if the packet gets lots (e.g. because we're probing ipv6, but +279 // if the packet gets lost (e.g. because we're probing ipv6, but 280 // ipv6 packets always get lost in our network configuration) we 281 // time out *closing the connection* after only 999ms. 282 // Even if the round trip time is bigger than 999ms, this doesn't @@ -391,7 +391,7 @@ 391 Ok(()) 392 } 393 -394 #[tokio::test] +394 #[tokio::test(start_paused = true)] 395 #[traced_test] 396 async fn test_qad_client_closes_unresponsive_fast() -> Result { 397 // create a client-side endpoint @@ -430,106 +430,104 @@ 430 client_endpoint.wait_idle().await; 431 let time = Instant::now().duration_since(before); 432 -433 println!("Closed in {time:?}"); -434 assert!(Duration::from_millis(900) < time); -435 assert!(time < Duration::from_millis(1800)); // give it some lee-way. Apparently github actions ubuntu runners can be slow? -436 -437 Ok(()) -438 } -439 -440 /// Makes sure that, even though the RTT was set to some fairly low value, -441 /// we *do* try to connect for longer than what the time out would be after closing -442 /// the connection, when we *don't* close the connection. -443 /// -444 /// In this case we don't simulate it via synthetically high RTT, but by dropping -445 /// all packets on the server-side for 2 seconds. -446 #[tokio::test] -447 #[traced_test] -448 async fn test_qad_connect_delayed() -> Result { -449 // Create a socket for our QAD server. We need the socket separately because we -450 // need to pop off messages before we attach it to the Quinn Endpoint. -451 let socket = tokio::net::UdpSocket::bind(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)) -452 .await -453 .context("bind")?; -454 let server_addr = socket.local_addr().context("local addr")?; -455 info!(addr = ?server_addr, "server socket bound"); -456 -457 // Create a QAD server with a self-signed cert, all manually. -458 let cert = -459 rcgen::generate_simple_self_signed(vec!["localhost".into()]).context("self signed")?; -460 let key = PrivatePkcs8KeyDer::from(cert.key_pair.serialize_der()); -461 let mut server_crypto = rustls::ServerConfig::builder() -462 .with_no_client_auth() -463 .with_single_cert(vec![cert.cert.into()], key.into()) -464 .context("tls")?; -465 server_crypto.key_log = Arc::new(rustls::KeyLogFile::new()); -466 server_crypto.alpn_protocols = vec![ALPN_QUIC_ADDR_DISC.to_vec()]; -467 let mut server_config = quinn::ServerConfig::with_crypto(Arc::new( -468 QuicServerConfig::try_from(server_crypto).context("config")?, -469 )); -470 let transport_config = Arc::get_mut(&mut server_config.transport).unwrap(); -471 transport_config.send_observed_address_reports(true); -472 -473 let start = Instant::now(); -474 let server_task = tokio::spawn( -475 async move { -476 info!("Dropping all packets"); -477 time::timeout(Duration::from_secs(2), async { -478 let mut buf = [0u8; 1500]; -479 loop { -480 let (len, src) = socket.recv_from(&mut buf).await.unwrap(); -481 debug!(%len, ?src, "Dropped a packet"); -482 } -483 }) -484 .await -485 .ok(); -486 info!("starting server"); -487 let server = quinn::Endpoint::new( -488 Default::default(), -489 Some(server_config), -490 socket.into_std().unwrap(), -491 Arc::new(quinn::TokioRuntime), -492 ) -493 .context("endpoint new")?; -494 info!("accepting conn"); -495 let incoming = server.accept().await.expect("missing conn"); -496 info!("incoming!"); -497 let conn = incoming.await.context("incoming")?; -498 conn.closed().await; -499 server.wait_idle().await; -500 Ok::<_, Error>(()) -501 } -502 .instrument(info_span!("server")), -503 ); -504 let server_task = AbortOnDropHandle::new(server_task); -505 -506 info!("starting client"); -507 let client_endpoint = -508 quinn::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)) -509 .context("client")?; -510 -511 // create the client configuration used for the client endpoint when they -512 // initiate a connection with the server -513 let client_config = crate::client::make_dangerous_client_config(); -514 let quic_client = QuicClient::new(client_endpoint.clone(), client_config)?; -515 -516 // Now we should still connect, but it should take more than 1s. -517 info!("making QAD request"); -518 let (addr, latency) = time::timeout( -519 Duration::from_secs(10), -520 quic_client.get_addr_and_latency(server_addr, "localhost"), -521 ) -522 .await -523 .context("timeout")??; -524 let duration = start.elapsed(); -525 info!(?duration, ?addr, ?latency, "QAD succeeded"); -526 assert!(duration >= Duration::from_secs(1)); -527 -528 time::timeout(Duration::from_secs(10), server_task) -529 .await -530 .context("timeout")? -531 .context("server task")??; -532 -533 Ok(()) -534 } -535} \ No newline at end of file +433 assert_eq!(time, Duration::from_millis(999)); +434 +435 Ok(()) +436 } +437 +438 /// Makes sure that, even though the RTT was set to some fairly low value, +439 /// we *do* try to connect for longer than what the time out would be after closing +440 /// the connection, when we *don't* close the connection. +441 /// +442 /// In this case we don't simulate it via synthetically high RTT, but by dropping +443 /// all packets on the server-side for 2 seconds. +444 #[tokio::test] +445 #[traced_test] +446 async fn test_qad_connect_delayed() -> Result { +447 // Create a socket for our QAD server. We need the socket separately because we +448 // need to pop off messages before we attach it to the Quinn Endpoint. +449 let socket = tokio::net::UdpSocket::bind(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)) +450 .await +451 .context("bind")?; +452 let server_addr = socket.local_addr().context("local addr")?; +453 info!(addr = ?server_addr, "server socket bound"); +454 +455 // Create a QAD server with a self-signed cert, all manually. +456 let cert = +457 rcgen::generate_simple_self_signed(vec!["localhost".into()]).context("self signed")?; +458 let key = PrivatePkcs8KeyDer::from(cert.key_pair.serialize_der()); +459 let mut server_crypto = rustls::ServerConfig::builder() +460 .with_no_client_auth() +461 .with_single_cert(vec![cert.cert.into()], key.into()) +462 .context("tls")?; +463 server_crypto.key_log = Arc::new(rustls::KeyLogFile::new()); +464 server_crypto.alpn_protocols = vec![ALPN_QUIC_ADDR_DISC.to_vec()]; +465 let mut server_config = quinn::ServerConfig::with_crypto(Arc::new( +466 QuicServerConfig::try_from(server_crypto).context("config")?, +467 )); +468 let transport_config = Arc::get_mut(&mut server_config.transport).unwrap(); +469 transport_config.send_observed_address_reports(true); +470 +471 let start = Instant::now(); +472 let server_task = tokio::spawn( +473 async move { +474 info!("Dropping all packets"); +475 time::timeout(Duration::from_secs(2), async { +476 let mut buf = [0u8; 1500]; +477 loop { +478 let (len, src) = socket.recv_from(&mut buf).await.unwrap(); +479 debug!(%len, ?src, "Dropped a packet"); +480 } +481 }) +482 .await +483 .ok(); +484 info!("starting server"); +485 let server = quinn::Endpoint::new( +486 Default::default(), +487 Some(server_config), +488 socket.into_std().unwrap(), +489 Arc::new(quinn::TokioRuntime), +490 ) +491 .context("endpoint new")?; +492 info!("accepting conn"); +493 let incoming = server.accept().await.expect("missing conn"); +494 info!("incoming!"); +495 let conn = incoming.await.context("incoming")?; +496 conn.closed().await; +497 server.wait_idle().await; +498 Ok::<_, Error>(()) +499 } +500 .instrument(info_span!("server")), +501 ); +502 let server_task = AbortOnDropHandle::new(server_task); +503 +504 info!("starting client"); +505 let client_endpoint = +506 quinn::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)) +507 .context("client")?; +508 +509 // create the client configuration used for the client endpoint when they +510 // initiate a connection with the server +511 let client_config = crate::client::make_dangerous_client_config(); +512 let quic_client = QuicClient::new(client_endpoint.clone(), client_config)?; +513 +514 // Now we should still connect, but it should take more than 1s. +515 info!("making QAD request"); +516 let (addr, latency) = time::timeout( +517 Duration::from_secs(10), +518 quic_client.get_addr_and_latency(server_addr, "localhost"), +519 ) +520 .await +521 .context("timeout")??; +522 let duration = start.elapsed(); +523 info!(?duration, ?addr, ?latency, "QAD succeeded"); +524 assert!(duration >= Duration::from_secs(1)); +525 +526 time::timeout(Duration::from_secs(10), server_task) +527 .await +528 .context("timeout")? +529 .context("server task")??; +530 +531 Ok(()) +532 } +533} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/clone/trait.Clone.js b/pr/3327/docs/trait.impl/core/clone/trait.Clone.js index edde71977a..69fec55db1 100644 --- a/pr/3327/docs/trait.impl/core/clone/trait.Clone.js +++ b/pr/3327/docs/trait.impl/core/clone/trait.Clone.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl Clone for ConnectionType"],["impl Clone for ControlMsg"],["impl Clone for DirectAddrType"],["impl Clone for PathSelection"],["impl Clone for RelayMode"],["impl Clone for Source"],["impl Clone for DhtDiscovery"],["impl Clone for PkarrPublisher"],["impl Clone for PkarrRelayClient"],["impl Clone for PkarrResolver"],["impl Clone for StaticProvider"],["impl Clone for DiscoveryItem"],["impl Clone for ConnectOptions"],["impl Clone for Connection"],["impl Clone for DirectAddr"],["impl Clone for DirectAddrInfo"],["impl Clone for Endpoint"],["impl Clone for RemoteInfo"],["impl Clone for EndpointMetrics"],["impl Clone for Addr"],["impl Clone for Options"],["impl Clone for QuicConfig"],["impl Clone for RelayLatencies"],["impl Clone for Report"],["impl Clone for Router"],["impl<P: Clone + ProtocolHandler + Clone> Clone for AccessLimit<P>"],["impl<T> Clone for Watchable<T>"],["impl<T: Clone> Clone for Direct<T>"],["impl<W: Clone + Watcher + Unpin> Clone for Stream<W>
    where\n W::Value: Clone,
    "],["impl<W: Clone + Watcher, T: Clone + Clone + Eq> Clone for Map<W, T>
    where\n W::Value: Clone,
    "]]],["iroh_base",[["impl Clone for NodeAddr"],["impl Clone for PublicKey"],["impl Clone for RelayUrl"],["impl Clone for SecretKey"],["impl Clone for NodeTicket"]]],["iroh_bench",[["impl Clone for Commands"],["impl Clone for Opt"],["impl Clone for Opt"]]],["iroh_dns_server",[["impl Clone for CertMode"],["impl Clone for RateLimitConfig"],["impl Clone for StoreConfig"],["impl Clone for DnsConfig"],["impl Clone for DnsHandler"],["impl Clone for Handle"],["impl Clone for HttpConfig"],["impl Clone for HttpsConfig"],["impl Clone for AppState"],["impl Clone for ZoneStore"]]],["iroh_relay",[["impl Clone for ReceivedMessage"],["impl Clone for Protocol"],["impl Clone for FrameType"],["impl Clone for Access"],["impl Clone for ClientBuilder"],["impl Clone for DnsResolver"],["impl Clone for TXT"],["impl Clone for TxtLookup"],["impl Clone for NodeData"],["impl Clone for NodeInfo"],["impl Clone for UserData"],["impl Clone for ClientRateLimit"],["impl Clone for RelayMetrics"],["impl Clone for RelayMap"],["impl Clone for RelayNode"],["impl Clone for RelayQuicConfig"]]]]); + var implementors = Object.fromEntries([["iroh",[["impl Clone for ConnectionType"],["impl Clone for ControlMsg"],["impl Clone for DirectAddrType"],["impl Clone for PathSelection"],["impl Clone for RelayMode"],["impl Clone for Source"],["impl Clone for DhtDiscovery"],["impl Clone for PkarrPublisher"],["impl Clone for PkarrRelayClient"],["impl Clone for PkarrResolver"],["impl Clone for StaticProvider"],["impl Clone for DiscoveryItem"],["impl Clone for ConnectOptions"],["impl Clone for Connection"],["impl Clone for DirectAddr"],["impl Clone for DirectAddrInfo"],["impl Clone for Endpoint"],["impl Clone for RemoteInfo"],["impl Clone for EndpointMetrics"],["impl Clone for Addr"],["impl Clone for Options"],["impl Clone for QuicConfig"],["impl Clone for RelayLatencies"],["impl Clone for Report"],["impl Clone for Router"],["impl<P: Clone + ProtocolHandler + Clone> Clone for AccessLimit<P>"]]],["iroh_base",[["impl Clone for NodeAddr"],["impl Clone for PublicKey"],["impl Clone for RelayUrl"],["impl Clone for SecretKey"],["impl Clone for NodeTicket"]]],["iroh_bench",[["impl Clone for Commands"],["impl Clone for Opt"],["impl Clone for Opt"]]],["iroh_dns_server",[["impl Clone for CertMode"],["impl Clone for RateLimitConfig"],["impl Clone for StoreConfig"],["impl Clone for DnsConfig"],["impl Clone for DnsHandler"],["impl Clone for Handle"],["impl Clone for HttpConfig"],["impl Clone for HttpsConfig"],["impl Clone for AppState"],["impl Clone for ZoneStore"]]],["iroh_relay",[["impl Clone for ReceivedMessage"],["impl Clone for Protocol"],["impl Clone for FrameType"],["impl Clone for Access"],["impl Clone for ClientBuilder"],["impl Clone for DnsResolver"],["impl Clone for TXT"],["impl Clone for TxtLookup"],["impl Clone for NodeData"],["impl Clone for NodeInfo"],["impl Clone for UserData"],["impl Clone for ClientRateLimit"],["impl Clone for RelayMetrics"],["impl Clone for RelayMap"],["impl Clone for RelayNode"],["impl Clone for RelayQuicConfig"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[10635,1333,770,2860,4444]} \ No newline at end of file +//{"start":57,"fragment_lengths":[7707,1333,770,2860,4444]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/convert/trait.From.js b/pr/3327/docs/trait.impl/core/convert/trait.From.js index d84bd979d0..e3f3df87b8 100644 --- a/pr/3327/docs/trait.impl/core/convert/trait.From.js +++ b/pr/3327/docs/trait.impl/core/convert/trait.From.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl From<IntoDiscoveryError> for BindError"],["impl From<PkarrError> for DiscoveryError"],["impl From<AddNodeAddrError> for ConnectWithOptsError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for ProtocolError"],["impl From<Box<dyn Error + Send + Sync>> for ProtocolError"],["impl From<Error> for ProtocolError"],["impl From<DiscoveryItem> for NodeInfo"],["impl From<ClosedStream> for ProtocolError"],["impl From<RemoteInfo> for NodeAddr"],["impl From<RemoteNodeIdError> for ProtocolError"],["impl<T> From<T> for ConcurrentDiscovery
    where\n T: IntoIterator<Item = Box<dyn Discovery>>,
    "]]],["iroh_base",[["impl From<(PublicKey, Option<RelayUrl>, &[SocketAddr])> for NodeAddr"],["impl From<Url> for RelayUrl"],["impl From<NodeAddr> for NodeTicket"],["impl From<PublicKey> for NodeAddr"],["impl From<RelayUrl> for Url"],["impl From<NodeTicket> for NodeAddr"],["impl From<DecodeError> for KeyParsingError"],["impl From<DecodeError> for ParseError"],["impl From<Error> for KeyParsingError"],["impl From<SigningKey> for SecretKey"],["impl From<VerifyingKey> for PublicKey"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<DialError> for ConnectError"],["impl From<SendError> for SendError"],["impl From<DnsError> for DialError"],["impl From<DecodingError> for ParseError"],["impl From<FrameType> for u8"],["impl From<RecvError> for RecvError"],["impl From<SendError> for ConnectError"],["impl From<SendError> for RecvError"],["impl From<u8> for FrameType"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<NodeAddr> for NodeData"],["impl From<NodeAddr> for NodeInfo"],["impl From<RelayUrl> for RelayMap"],["impl From<RelayUrl> for RelayNode"],["impl From<NodeInfo> for NodeAddr"],["impl From<RelayNode> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<Elapsed> for RecvError"],["impl From<Elapsed> for SendError"],["impl From<Error> for ConnectError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<JoinError> for SupervisorError"],["impl From<NoInitialCipherSuite> for Error"],["impl From<RecvError> for Error"],["impl From<ResolveError> for DnsError"],["impl From<Resolver<GenericConnector<TokioRuntimeProvider>>> for DnsResolver"],["impl From<SignedPacketBuildError> for EncodingError"],["impl From<TxtLookup> for TxtLookup"]]]]); + var implementors = Object.fromEntries([["iroh",[["impl From<IntoDiscoveryError> for BindError"],["impl From<PkarrError> for DiscoveryError"],["impl From<AddNodeAddrError> for ConnectWithOptsError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for AcceptError"],["impl From<Box<dyn Error + Send + Sync>> for AcceptError"],["impl From<Error> for AcceptError"],["impl From<DiscoveryItem> for NodeInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteInfo> for NodeAddr"],["impl From<RemoteNodeIdError> for AcceptError"],["impl<T> From<T> for ConcurrentDiscovery
    where\n T: IntoIterator<Item = Box<dyn Discovery>>,
    "]]],["iroh_base",[["impl From<(PublicKey, Option<RelayUrl>, &[SocketAddr])> for NodeAddr"],["impl From<Url> for RelayUrl"],["impl From<NodeAddr> for NodeTicket"],["impl From<PublicKey> for NodeAddr"],["impl From<RelayUrl> for Url"],["impl From<NodeTicket> for NodeAddr"],["impl From<DecodeError> for KeyParsingError"],["impl From<DecodeError> for ParseError"],["impl From<Error> for KeyParsingError"],["impl From<SigningKey> for SecretKey"],["impl From<VerifyingKey> for PublicKey"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<DialError> for ConnectError"],["impl From<SendError> for SendError"],["impl From<DnsError> for DialError"],["impl From<DecodingError> for ParseError"],["impl From<FrameType> for u8"],["impl From<RecvError> for RecvError"],["impl From<SendError> for ConnectError"],["impl From<SendError> for RecvError"],["impl From<u8> for FrameType"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<NodeInfo> for NodeAddr"],["impl From<RelayNode> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<Elapsed> for RecvError"],["impl From<Elapsed> for SendError"],["impl From<Error> for ConnectError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<JoinError> for SupervisorError"],["impl From<NoInitialCipherSuite> for Error"],["impl From<NodeAddr> for NodeData"],["impl From<NodeAddr> for NodeInfo"],["impl From<RecvError> for Error"],["impl From<RelayUrl> for RelayMap"],["impl From<RelayUrl> for RelayNode"],["impl From<ResolveError> for DnsError"],["impl From<Resolver<GenericConnector<TokioRuntimeProvider>>> for DnsResolver"],["impl From<SignedPacketBuildError> for EncodingError"],["impl From<TxtLookup> for TxtLookup"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[6691,4651,13893]} \ No newline at end of file +//{"start":57,"fragment_lengths":[6661,4651,13283]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/default/trait.Default.js b/pr/3327/docs/trait.impl/core/default/trait.Default.js index a6b9e1093e..f5a0cbc132 100644 --- a/pr/3327/docs/trait.impl/core/default/trait.Default.js +++ b/pr/3327/docs/trait.impl/core/default/trait.Default.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl Default for ConnectionType"],["impl Default for PathSelection"],["impl Default for Builder"],["impl Default for DhtDiscovery"],["impl Default for StaticProvider"],["impl Default for ConcurrentDiscovery"],["impl Default for Builder"],["impl Default for ConnectOptions"],["impl Default for EndpointMetrics"],["impl Default for Metrics"],["impl Default for Metrics"],["impl Default for Options"],["impl Default for RelayLatencies"],["impl Default for Report"],["impl<T: Default> Default for Watchable<T>"]]],["iroh_bench",[["impl Default for Stats"],["impl Default for StreamStats"],["impl Default for ClientStats"]]],["iroh_dns_server",[["impl Default for &RateLimitConfig"],["impl Default for BootstrapOption"],["impl Default for RateLimitConfig"],["impl Default for Config"],["impl Default for MainlineConfig"],["impl Default for StoreConfig"],["impl Default for Metrics"]]],["iroh_relay",[["impl Default for Protocol"],["impl Default for DnsResolver"],["impl Default for NodeData"],["impl Default for Limits"],["impl Default for Metrics"],["impl Default for RelayMetrics"],["impl Default for StunMetrics"],["impl Default for PingTracker"],["impl Default for RelayQuicConfig"],["impl<EC: Default + Debug, EA: Default + Debug> Default for ServerConfig<EC, EA>"]]]]); + var implementors = Object.fromEntries([["iroh",[["impl Default for ConnectionType"],["impl Default for PathSelection"],["impl Default for Builder"],["impl Default for DhtDiscovery"],["impl Default for StaticProvider"],["impl Default for ConcurrentDiscovery"],["impl Default for Builder"],["impl Default for ConnectOptions"],["impl Default for EndpointMetrics"],["impl Default for Metrics"],["impl Default for Metrics"],["impl Default for Options"],["impl Default for RelayLatencies"],["impl Default for Report"]]],["iroh_bench",[["impl Default for Stats"],["impl Default for StreamStats"],["impl Default for ClientStats"]]],["iroh_dns_server",[["impl Default for &RateLimitConfig"],["impl Default for BootstrapOption"],["impl Default for RateLimitConfig"],["impl Default for Config"],["impl Default for MainlineConfig"],["impl Default for StoreConfig"],["impl Default for Metrics"]]],["iroh_relay",[["impl Default for Protocol"],["impl Default for DnsResolver"],["impl Default for NodeData"],["impl Default for Limits"],["impl Default for Metrics"],["impl Default for RelayMetrics"],["impl Default for StunMetrics"],["impl Default for PingTracker"],["impl Default for RelayQuicConfig"],["impl<EC: Default + Debug, EA: Default + Debug> Default for ServerConfig<EC, EA>"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[4565,862,2149,3476]} \ No newline at end of file +//{"start":57,"fragment_lengths":[4123,862,2149,3476]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/error/trait.Error.js b/pr/3327/docs/trait.impl/core/error/trait.Error.js index 24ca788532..1b38c07db2 100644 --- a/pr/3327/docs/trait.impl/core/error/trait.Error.js +++ b/pr/3327/docs/trait.impl/core/error/trait.Error.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl Error for DiscoveryError
    where\n Self: Debug + Display,
    "],["impl Error for IntoDiscoveryError
    where\n Self: Debug + Display,
    "],["impl Error for PkarrError
    where\n Self: Debug + Display,
    "],["impl Error for AddNodeAddrError
    where\n Self: Debug + Display,
    "],["impl Error for AlpnError
    where\n Self: Debug + Display,
    "],["impl Error for BindError
    where\n Self: Debug + Display,
    "],["impl Error for ConnectError
    where\n Self: Debug + Display,
    "],["impl Error for ConnectWithOptsError
    where\n Self: Debug + Display,
    "],["impl Error for GetMappingAddressError
    where\n Self: Debug + Display,
    "],["impl Error for ReportError
    where\n Self: Debug + Display,
    "],["impl Error for ProtocolError
    where\n Self: Debug + Display,
    "],["impl Error for Lagged
    where\n Self: Debug + Display,
    "],["impl Error for RemoteNodeIdError
    where\n Self: Debug + Display,
    "],["impl Error for Disconnected
    where\n Self: Debug + Display,
    "]]],["iroh_base",[["impl Error for KeyParsingError
    where\n Self: Debug + Display,
    "],["impl Error for ParseError
    where\n Self: Debug + Display,
    "],["impl Error for RelayUrlParseError
    where\n Self: Debug + Display,
    "]]],["iroh_relay",[["impl Error for ConnectError
    where\n Self: Debug + Display,
    "],["impl Error for DialError
    where\n Self: Debug + Display,
    "],["impl Error for RecvError
    where\n Self: Debug + Display,
    "],["impl Error for SendError
    where\n Self: Debug + Display,
    "],["impl Error for DnsError
    where\n Self: Debug + Display,
    "],["impl Error for DecodingError
    where\n Self: Debug + Display,
    "],["impl Error for EncodingError
    where\n Self: Debug + Display,
    "],["impl Error for LookupError
    where\n Self: Debug + Display,
    "],["impl Error for ParseError
    where\n Self: Debug + Display,
    "],["impl Error for RecvError
    where\n Self: Debug + Display,
    "],["impl Error for SendError
    where\n Self: Debug + Display,
    "],["impl Error for StunError
    where\n Self: Debug + Display,
    "],["impl Error for Error
    where\n Self: Debug + Display,
    "],["impl Error for SpawnError
    where\n Self: Debug + Display,
    "],["impl Error for SupervisorError
    where\n Self: Debug + Display,
    "],["impl Error for Error
    where\n Self: Debug + Display,
    "],["impl Error for MaxLengthExceededError
    where\n Self: Debug + Display,
    "]]]]); + var implementors = Object.fromEntries([["iroh",[["impl Error for DiscoveryError
    where\n Self: Debug + Display,
    "],["impl Error for IntoDiscoveryError
    where\n Self: Debug + Display,
    "],["impl Error for PkarrError
    where\n Self: Debug + Display,
    "],["impl Error for AddNodeAddrError
    where\n Self: Debug + Display,
    "],["impl Error for AlpnError
    where\n Self: Debug + Display,
    "],["impl Error for BindError
    where\n Self: Debug + Display,
    "],["impl Error for ConnectError
    where\n Self: Debug + Display,
    "],["impl Error for ConnectWithOptsError
    where\n Self: Debug + Display,
    "],["impl Error for GetMappingAddressError
    where\n Self: Debug + Display,
    "],["impl Error for ReportError
    where\n Self: Debug + Display,
    "],["impl Error for AcceptError
    where\n Self: Debug + Display,
    "],["impl Error for Lagged
    where\n Self: Debug + Display,
    "],["impl Error for RemoteNodeIdError
    where\n Self: Debug + Display,
    "]]],["iroh_base",[["impl Error for KeyParsingError
    where\n Self: Debug + Display,
    "],["impl Error for ParseError
    where\n Self: Debug + Display,
    "],["impl Error for RelayUrlParseError
    where\n Self: Debug + Display,
    "]]],["iroh_relay",[["impl Error for ConnectError
    where\n Self: Debug + Display,
    "],["impl Error for DialError
    where\n Self: Debug + Display,
    "],["impl Error for RecvError
    where\n Self: Debug + Display,
    "],["impl Error for SendError
    where\n Self: Debug + Display,
    "],["impl Error for DnsError
    where\n Self: Debug + Display,
    "],["impl Error for DecodingError
    where\n Self: Debug + Display,
    "],["impl Error for EncodingError
    where\n Self: Debug + Display,
    "],["impl Error for LookupError
    where\n Self: Debug + Display,
    "],["impl Error for ParseError
    where\n Self: Debug + Display,
    "],["impl Error for RecvError
    where\n Self: Debug + Display,
    "],["impl Error for SendError
    where\n Self: Debug + Display,
    "],["impl Error for StunError
    where\n Self: Debug + Display,
    "],["impl Error for Error
    where\n Self: Debug + Display,
    "],["impl Error for SpawnError
    where\n Self: Debug + Display,
    "],["impl Error for SupervisorError
    where\n Self: Debug + Display,
    "],["impl Error for MaxLengthExceededError
    where\n Self: Debug + Display,
    "],["impl<E: Debug + Display> Error for StaggeredError<E>
    where\n Self: Debug + Display,
    "]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[8332,1792,10117]} \ No newline at end of file +//{"start":57,"fragment_lengths":[7735,1792,10433]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/fmt/trait.Debug.js b/pr/3327/docs/trait.impl/core/fmt/trait.Debug.js index 6b73c505c1..153f63ced0 100644 --- a/pr/3327/docs/trait.impl/core/fmt/trait.Debug.js +++ b/pr/3327/docs/trait.impl/core/fmt/trait.Debug.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl Debug for DiscoveryError"],["impl Debug for IntoDiscoveryError"],["impl Debug for PkarrError"],["impl Debug for AddNodeAddrError"],["impl Debug for AlpnError"],["impl Debug for BindError"],["impl Debug for ConnectError"],["impl Debug for ConnectWithOptsError"],["impl Debug for ConnectionType"],["impl Debug for ControlMsg"],["impl Debug for DirectAddrType"],["impl Debug for GetMappingAddressError"],["impl Debug for PathSelection"],["impl Debug for RelayMode"],["impl Debug for Source"],["impl Debug for ReportError"],["impl Debug for ProtocolError"],["impl Debug for DnsDiscovery"],["impl Debug for DnsDiscoveryBuilder"],["impl Debug for MdnsDiscovery"],["impl Debug for MdnsDiscoveryBuilder"],["impl Debug for Builder"],["impl Debug for DhtDiscovery"],["impl Debug for PkarrPublisher"],["impl Debug for PkarrPublisherBuilder"],["impl Debug for PkarrRelayClient"],["impl Debug for PkarrResolver"],["impl Debug for PkarrResolverBuilder"],["impl Debug for StaticProvider"],["impl Debug for ConcurrentDiscovery"],["impl Debug for DiscoveryItem"],["impl Debug for Lagged"],["impl Debug for Builder"],["impl Debug for ConnectOptions"],["impl Debug for Connecting"],["impl Debug for Connection"],["impl Debug for DirectAddr"],["impl Debug for DirectAddrInfo"],["impl Debug for Endpoint"],["impl Debug for Incoming"],["impl Debug for IncomingFuture"],["impl Debug for RemoteInfo"],["impl Debug for RemoteNodeIdError"],["impl Debug for ZeroRttAccepted"],["impl Debug for EndpointMetrics"],["impl Debug for Metrics"],["impl Debug for Addr"],["impl Debug for Client"],["impl Debug for Metrics"],["impl Debug for Options"],["impl Debug for QuicConfig"],["impl Debug for RelayLatencies"],["impl Debug for Report"],["impl Debug for Router"],["impl Debug for RouterBuilder"],["impl Debug for CleanupDropGuard"],["impl Debug for DnsPkarrServer"],["impl Debug for Disconnected"],["impl<'a> Debug for DiscoveryContext<'a>"],["impl<'a> Debug for Accept<'a>"],["impl<'a, T: Debug, W: Debug + Watcher<Value = Option<T>>> Debug for InitializedFut<'a, T, W>"],["impl<'a, W: Debug + Watcher> Debug for NextFut<'a, W>"],["impl<P> Debug for AccessLimit<P>
    where\n P: Debug + ProtocolHandler + Clone,
    "],["impl<T: Debug> Debug for Direct<T>"],["impl<T: Debug> Debug for Watchable<T>"],["impl<W, T> Debug for Map<W, T>
    where\n W: Debug + Watcher,\n T: Debug + Clone + Eq,
    "],["impl<W: Debug + Watcher + Unpin> Debug for Stream<W>
    where\n W::Value: Debug,
    "]]],["iroh_base",[["impl Debug for KeyParsingError"],["impl Debug for ParseError"],["impl Debug for NodeAddr"],["impl Debug for PublicKey"],["impl Debug for RelayUrl"],["impl Debug for RelayUrlParseError"],["impl Debug for SecretKey"],["impl Debug for NodeTicket"]]],["iroh_bench",[["impl Debug for Commands"],["impl Debug for Opt"],["impl Debug for Stats"],["impl Debug for StreamStats"],["impl Debug for TransferResult"],["impl Debug for Opt"]]],["iroh_dns_server",[["impl Debug for BootstrapOption"],["impl Debug for CertMode"],["impl Debug for RateLimitConfig"],["impl Debug for Config"],["impl Debug for MainlineConfig"],["impl Debug for MetricsConfig"],["impl Debug for StoreConfig"],["impl Debug for DnsConfig"],["impl Debug for DnsHandler"],["impl Debug for Handle"],["impl Debug for HttpConfig"],["impl Debug for HttpsConfig"],["impl Debug for Metrics"],["impl Debug for ZoneStore"]]],["iroh_relay",[["impl Debug for ConnectError"],["impl Debug for DialError"],["impl Debug for ReceivedMessage"],["impl Debug for RecvError"],["impl Debug for SendError"],["impl Debug for SendMessage"],["impl Debug for DnsError"],["impl Debug for Protocol"],["impl Debug for DecodingError"],["impl Debug for EncodingError"],["impl Debug for LookupError"],["impl Debug for ParseError"],["impl Debug for FrameType"],["impl Debug for RecvError"],["impl Debug for SendError"],["impl Debug for StunError"],["impl Debug for Error"],["impl Debug for Access"],["impl Debug for AccessConfig"],["impl Debug for SpawnError"],["impl Debug for SupervisorError"],["impl Debug for Client"],["impl Debug for ClientBuilder"],["impl Debug for ClientSink"],["impl Debug for ClientStream"],["impl Debug for DnsResolver"],["impl Debug for Error"],["impl Debug for TXT"],["impl Debug for TxtLookup"],["impl Debug for MaxLengthExceededError"],["impl Debug for NodeData"],["impl Debug for NodeInfo"],["impl Debug for UserData"],["impl Debug for QuicClient"],["impl Debug for ClientRateLimit"],["impl Debug for Limits"],["impl Debug for Metrics"],["impl Debug for QuicConfig"],["impl Debug for RelayMetrics"],["impl Debug for Server"],["impl Debug for StunConfig"],["impl Debug for StunMetrics"],["impl Debug for PingTracker"],["impl Debug for RelayMap"],["impl Debug for RelayNode"],["impl Debug for RelayQuicConfig"],["impl<EC: Debug, EA: Debug> Debug for CertConfig<EC, EA>"],["impl<EC: Debug, EA: Debug> Debug for RelayConfig<EC, EA>
    where\n Option<TlsConfig<EC, EA>>: Debug,
    "],["impl<EC: Debug, EA: Debug> Debug for ServerConfig<EC, EA>
    where\n Option<RelayConfig<EC, EA>>: Debug,
    "],["impl<EC: Debug, EA: Debug> Debug for TlsConfig<EC, EA>
    where\n CertConfig<EC, EA>: Debug,
    "],["impl<Loader: Debug + Send + 'static> Debug for ReloadingResolver<Loader>"]]]]); + var implementors = Object.fromEntries([["iroh",[["impl Debug for DiscoveryError"],["impl Debug for IntoDiscoveryError"],["impl Debug for PkarrError"],["impl Debug for AddNodeAddrError"],["impl Debug for AlpnError"],["impl Debug for BindError"],["impl Debug for ConnectError"],["impl Debug for ConnectWithOptsError"],["impl Debug for ConnectionType"],["impl Debug for ControlMsg"],["impl Debug for DirectAddrType"],["impl Debug for GetMappingAddressError"],["impl Debug for PathSelection"],["impl Debug for RelayMode"],["impl Debug for Source"],["impl Debug for ReportError"],["impl Debug for AcceptError"],["impl Debug for DnsDiscovery"],["impl Debug for DnsDiscoveryBuilder"],["impl Debug for MdnsDiscovery"],["impl Debug for MdnsDiscoveryBuilder"],["impl Debug for Builder"],["impl Debug for DhtDiscovery"],["impl Debug for PkarrPublisher"],["impl Debug for PkarrPublisherBuilder"],["impl Debug for PkarrRelayClient"],["impl Debug for PkarrResolver"],["impl Debug for PkarrResolverBuilder"],["impl Debug for StaticProvider"],["impl Debug for ConcurrentDiscovery"],["impl Debug for DiscoveryItem"],["impl Debug for Lagged"],["impl Debug for Builder"],["impl Debug for ConnectOptions"],["impl Debug for Connecting"],["impl Debug for Connection"],["impl Debug for DirectAddr"],["impl Debug for DirectAddrInfo"],["impl Debug for Endpoint"],["impl Debug for Incoming"],["impl Debug for IncomingFuture"],["impl Debug for RemoteInfo"],["impl Debug for RemoteNodeIdError"],["impl Debug for ZeroRttAccepted"],["impl Debug for EndpointMetrics"],["impl Debug for Metrics"],["impl Debug for Addr"],["impl Debug for Client"],["impl Debug for Metrics"],["impl Debug for Options"],["impl Debug for QuicConfig"],["impl Debug for RelayLatencies"],["impl Debug for Report"],["impl Debug for Router"],["impl Debug for RouterBuilder"],["impl Debug for CleanupDropGuard"],["impl Debug for DnsPkarrServer"],["impl<'a> Debug for DiscoveryContext<'a>"],["impl<'a> Debug for Accept<'a>"],["impl<P> Debug for AccessLimit<P>
    where\n P: Debug + ProtocolHandler + Clone,
    "]]],["iroh_base",[["impl Debug for KeyParsingError"],["impl Debug for ParseError"],["impl Debug for NodeAddr"],["impl Debug for PublicKey"],["impl Debug for RelayUrl"],["impl Debug for RelayUrlParseError"],["impl Debug for SecretKey"],["impl Debug for NodeTicket"]]],["iroh_bench",[["impl Debug for Commands"],["impl Debug for Opt"],["impl Debug for Stats"],["impl Debug for StreamStats"],["impl Debug for TransferResult"],["impl Debug for Opt"]]],["iroh_dns_server",[["impl Debug for BootstrapOption"],["impl Debug for CertMode"],["impl Debug for RateLimitConfig"],["impl Debug for Config"],["impl Debug for MainlineConfig"],["impl Debug for MetricsConfig"],["impl Debug for StoreConfig"],["impl Debug for DnsConfig"],["impl Debug for DnsHandler"],["impl Debug for Handle"],["impl Debug for HttpConfig"],["impl Debug for HttpsConfig"],["impl Debug for Metrics"],["impl Debug for ZoneStore"]]],["iroh_relay",[["impl Debug for ConnectError"],["impl Debug for DialError"],["impl Debug for ReceivedMessage"],["impl Debug for RecvError"],["impl Debug for SendError"],["impl Debug for SendMessage"],["impl Debug for DnsError"],["impl Debug for Protocol"],["impl Debug for DecodingError"],["impl Debug for EncodingError"],["impl Debug for LookupError"],["impl Debug for ParseError"],["impl Debug for FrameType"],["impl Debug for RecvError"],["impl Debug for SendError"],["impl Debug for StunError"],["impl Debug for Error"],["impl Debug for Access"],["impl Debug for AccessConfig"],["impl Debug for SpawnError"],["impl Debug for SupervisorError"],["impl Debug for Client"],["impl Debug for ClientBuilder"],["impl Debug for ClientSink"],["impl Debug for ClientStream"],["impl Debug for DnsResolver"],["impl Debug for TXT"],["impl Debug for TxtLookup"],["impl Debug for MaxLengthExceededError"],["impl Debug for NodeData"],["impl Debug for NodeInfo"],["impl Debug for UserData"],["impl Debug for QuicClient"],["impl Debug for ClientRateLimit"],["impl Debug for Limits"],["impl Debug for Metrics"],["impl Debug for QuicConfig"],["impl Debug for RelayMetrics"],["impl Debug for Server"],["impl Debug for StunConfig"],["impl Debug for StunMetrics"],["impl Debug for PingTracker"],["impl Debug for RelayMap"],["impl Debug for RelayNode"],["impl Debug for RelayQuicConfig"],["impl<E: Debug + Debug + Display> Debug for StaggeredError<E>"],["impl<EC: Debug, EA: Debug> Debug for CertConfig<EC, EA>"],["impl<EC: Debug, EA: Debug> Debug for RelayConfig<EC, EA>
    where\n Option<TlsConfig<EC, EA>>: Debug,
    "],["impl<EC: Debug, EA: Debug> Debug for ServerConfig<EC, EA>
    where\n Option<RelayConfig<EC, EA>>: Debug,
    "],["impl<EC: Debug, EA: Debug> Debug for TlsConfig<EC, EA>
    where\n CertConfig<EC, EA>: Debug,
    "],["impl<Loader: Debug + Send + 'static> Debug for ReloadingResolver<Loader>"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[21644,2135,1583,3987,16733]} \ No newline at end of file +//{"start":57,"fragment_lengths":[17237,2135,1583,3987,17182]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/fmt/trait.Display.js b/pr/3327/docs/trait.impl/core/fmt/trait.Display.js index 5c25699090..bd19bf510f 100644 --- a/pr/3327/docs/trait.impl/core/fmt/trait.Display.js +++ b/pr/3327/docs/trait.impl/core/fmt/trait.Display.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl Display for DiscoveryError"],["impl Display for IntoDiscoveryError"],["impl Display for PkarrError"],["impl Display for AddNodeAddrError"],["impl Display for AlpnError"],["impl Display for BindError"],["impl Display for ConnectError"],["impl Display for ConnectWithOptsError"],["impl Display for ConnectionType"],["impl Display for ControlMsg"],["impl Display for DirectAddrType"],["impl Display for GetMappingAddressError"],["impl Display for Source"],["impl Display for ReportError"],["impl Display for ProtocolError"],["impl Display for Lagged"],["impl Display for RemoteNodeIdError"],["impl Display for Report"],["impl Display for Disconnected"]]],["iroh_base",[["impl Display for KeyParsingError"],["impl Display for ParseError"],["impl Display for PublicKey"],["impl Display for RelayUrl"],["impl Display for RelayUrlParseError"],["impl Display for SecretKey"],["impl Display for NodeTicket"]]],["iroh_dns_server",[["impl Display for CertMode"]]],["iroh_relay",[["impl Display for ConnectError"],["impl Display for DialError"],["impl Display for RecvError"],["impl Display for SendError"],["impl Display for DnsError"],["impl Display for DecodingError"],["impl Display for EncodingError"],["impl Display for LookupError"],["impl Display for ParseError"],["impl Display for FrameType"],["impl Display for RecvError"],["impl Display for SendError"],["impl Display for StunError"],["impl Display for Error"],["impl Display for SpawnError"],["impl Display for SupervisorError"],["impl Display for Error"],["impl Display for TXT"],["impl Display for MaxLengthExceededError"],["impl Display for UserData"],["impl Display for RelayMap"],["impl Display for RelayNode"]]]]); + var implementors = Object.fromEntries([["iroh",[["impl Display for DiscoveryError"],["impl Display for IntoDiscoveryError"],["impl Display for PkarrError"],["impl Display for AddNodeAddrError"],["impl Display for AlpnError"],["impl Display for BindError"],["impl Display for ConnectError"],["impl Display for ConnectWithOptsError"],["impl Display for ConnectionType"],["impl Display for ControlMsg"],["impl Display for DirectAddrType"],["impl Display for GetMappingAddressError"],["impl Display for Source"],["impl Display for ReportError"],["impl Display for AcceptError"],["impl Display for Lagged"],["impl Display for RemoteNodeIdError"],["impl Display for Report"]]],["iroh_base",[["impl Display for KeyParsingError"],["impl Display for ParseError"],["impl Display for PublicKey"],["impl Display for RelayUrl"],["impl Display for RelayUrlParseError"],["impl Display for SecretKey"],["impl Display for NodeTicket"]]],["iroh_dns_server",[["impl Display for CertMode"]]],["iroh_relay",[["impl Display for ConnectError"],["impl Display for DialError"],["impl Display for RecvError"],["impl Display for SendError"],["impl Display for DnsError"],["impl Display for DecodingError"],["impl Display for EncodingError"],["impl Display for LookupError"],["impl Display for ParseError"],["impl Display for FrameType"],["impl Display for RecvError"],["impl Display for SendError"],["impl Display for StunError"],["impl Display for Error"],["impl Display for SpawnError"],["impl Display for SupervisorError"],["impl Display for TXT"],["impl Display for MaxLengthExceededError"],["impl Display for UserData"],["impl Display for RelayMap"],["impl Display for RelayNode"],["impl<E: Debug + Display> Display for StaggeredError<E>"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[5319,1923,299,6166]} \ No newline at end of file +//{"start":57,"fragment_lengths":[5034,1923,299,6482]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/future/future/trait.Future.js b/pr/3327/docs/trait.impl/core/future/future/trait.Future.js index bb92ed1d33..b200f9e7ea 100644 --- a/pr/3327/docs/trait.impl/core/future/future/trait.Future.js +++ b/pr/3327/docs/trait.impl/core/future/future/trait.Future.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl Future for Accept<'_>"],["impl Future for Connecting"],["impl Future for IncomingFuture"],["impl Future for ZeroRttAccepted"],["impl<T: Clone + Eq + Unpin, W: Watcher<Value = Option<T>> + Unpin> Future for InitializedFut<'_, T, W>"],["impl<W: Watcher> Future for NextFut<'_, W>"]]]]); + var implementors = Object.fromEntries([["iroh",[["impl Future for Accept<'_>"],["impl Future for Connecting"],["impl Future for IncomingFuture"],["impl Future for ZeroRttAccepted"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[2765]} \ No newline at end of file +//{"start":57,"fragment_lengths":[1207]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js b/pr/3327/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js index 8cd585bc9e..d104c409e3 100644 --- a/pr/3327/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js +++ b/pr/3327/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<RelayUrl> for RelayMap"],["impl FromIterator<RelayNode> for RelayMap"]]]]); + var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<RelayNode> for RelayMap"],["impl FromIterator<RelayUrl> for RelayMap"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[898]} \ No newline at end of file +//{"start":57,"fragment_lengths":[776]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/marker/trait.Freeze.js b/pr/3327/docs/trait.impl/core/marker/trait.Freeze.js index 9e63778419..8697d48460 100644 --- a/pr/3327/docs/trait.impl/core/marker/trait.Freeze.js +++ b/pr/3327/docs/trait.impl/core/marker/trait.Freeze.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl !Freeze for AlpnError",1,["iroh::endpoint::AlpnError"]],["impl !Freeze for ReportError",1,["iroh::net_report::ReportError"]],["impl !Freeze for ProtocolError",1,["iroh::protocol::ProtocolError"]],["impl !Freeze for Incoming",1,["iroh::endpoint::Incoming"]],["impl !Freeze for IncomingFuture",1,["iroh::endpoint::IncomingFuture"]],["impl !Freeze for Metrics",1,["iroh::magicsock::metrics::Metrics"]],["impl !Freeze for Metrics",1,["iroh::net_report::metrics::Metrics"]],["impl Freeze for DiscoveryError",1,["iroh::discovery::DiscoveryError"]],["impl Freeze for IntoDiscoveryError",1,["iroh::discovery::IntoDiscoveryError"]],["impl Freeze for PkarrError",1,["iroh::discovery::pkarr::PkarrError"]],["impl Freeze for AddNodeAddrError",1,["iroh::magicsock::AddNodeAddrError"]],["impl Freeze for BindError",1,["iroh::endpoint::BindError"]],["impl Freeze for ConnectError",1,["iroh::endpoint::ConnectError"]],["impl Freeze for ConnectWithOptsError",1,["iroh::endpoint::ConnectWithOptsError"]],["impl Freeze for ConnectionType",1,["iroh::magicsock::node_map::node_state::ConnectionType"]],["impl Freeze for ControlMsg",1,["iroh::magicsock::node_map::node_state::ControlMsg"]],["impl Freeze for DirectAddrType",1,["iroh::magicsock::DirectAddrType"]],["impl Freeze for GetMappingAddressError",1,["iroh::endpoint::GetMappingAddressError"]],["impl Freeze for PathSelection",1,["iroh::endpoint::PathSelection"]],["impl Freeze for RelayMode",1,["iroh::endpoint::RelayMode"]],["impl Freeze for Source",1,["iroh::magicsock::node_map::Source"]],["impl Freeze for DnsDiscovery",1,["iroh::discovery::dns::DnsDiscovery"]],["impl Freeze for DnsDiscoveryBuilder",1,["iroh::discovery::dns::DnsDiscoveryBuilder"]],["impl Freeze for MdnsDiscovery",1,["iroh::discovery::mdns::MdnsDiscovery"]],["impl Freeze for MdnsDiscoveryBuilder",1,["iroh::discovery::mdns::MdnsDiscoveryBuilder"]],["impl Freeze for Builder",1,["iroh::discovery::pkarr::dht::Builder"]],["impl Freeze for DhtDiscovery",1,["iroh::discovery::pkarr::dht::DhtDiscovery"]],["impl Freeze for PkarrPublisher",1,["iroh::discovery::pkarr::PkarrPublisher"]],["impl Freeze for PkarrPublisherBuilder",1,["iroh::discovery::pkarr::PkarrPublisherBuilder"]],["impl Freeze for PkarrRelayClient",1,["iroh::discovery::pkarr::PkarrRelayClient"]],["impl Freeze for PkarrResolver",1,["iroh::discovery::pkarr::PkarrResolver"]],["impl Freeze for PkarrResolverBuilder",1,["iroh::discovery::pkarr::PkarrResolverBuilder"]],["impl Freeze for StaticProvider",1,["iroh::discovery::static_provider::StaticProvider"]],["impl Freeze for ConcurrentDiscovery",1,["iroh::discovery::ConcurrentDiscovery"]],["impl Freeze for DiscoveryItem",1,["iroh::discovery::DiscoveryItem"]],["impl Freeze for Lagged",1,["iroh::discovery::Lagged"]],["impl Freeze for Builder",1,["iroh::endpoint::Builder"]],["impl Freeze for ConnectOptions",1,["iroh::endpoint::ConnectOptions"]],["impl Freeze for Connecting",1,["iroh::endpoint::Connecting"]],["impl Freeze for Connection",1,["iroh::endpoint::Connection"]],["impl Freeze for DirectAddr",1,["iroh::magicsock::DirectAddr"]],["impl Freeze for DirectAddrInfo",1,["iroh::magicsock::node_map::node_state::DirectAddrInfo"]],["impl Freeze for Endpoint",1,["iroh::endpoint::Endpoint"]],["impl Freeze for RemoteInfo",1,["iroh::magicsock::node_map::node_state::RemoteInfo"]],["impl Freeze for RemoteNodeIdError",1,["iroh::endpoint::RemoteNodeIdError"]],["impl Freeze for ZeroRttAccepted",1,["iroh::endpoint::ZeroRttAccepted"]],["impl Freeze for EndpointMetrics",1,["iroh::metrics::EndpointMetrics"]],["impl Freeze for Addr",1,["iroh::net_report::Addr"]],["impl Freeze for Client",1,["iroh::net_report::Client"]],["impl Freeze for Options",1,["iroh::net_report::options::imp::Options"]],["impl Freeze for QuicConfig",1,["iroh::net_report::reportgen::QuicConfig"]],["impl Freeze for RelayLatencies",1,["iroh::net_report::RelayLatencies"]],["impl Freeze for Report",1,["iroh::net_report::Report"]],["impl Freeze for Router",1,["iroh::protocol::Router"]],["impl Freeze for RouterBuilder",1,["iroh::protocol::RouterBuilder"]],["impl Freeze for CleanupDropGuard",1,["iroh::test_utils::CleanupDropGuard"]],["impl Freeze for DnsPkarrServer",1,["iroh::test_utils::dns_and_pkarr_servers::DnsPkarrServer"]],["impl Freeze for Disconnected",1,["iroh::watcher::Disconnected"]],["impl<'a> !Freeze for Accept<'a>",1,["iroh::endpoint::Accept"]],["impl<'a> Freeze for DiscoveryContext<'a>",1,["iroh::discovery::DiscoveryContext"]],["impl<'a, T, W> Freeze for InitializedFut<'a, T, W>
    where\n T: Freeze,
    ",1,["iroh::watcher::InitializedFut"]],["impl<'a, W> Freeze for NextFut<'a, W>",1,["iroh::watcher::NextFut"]],["impl<P> Freeze for AccessLimit<P>
    where\n P: Freeze,
    ",1,["iroh::protocol::AccessLimit"]],["impl<T> Freeze for Direct<T>",1,["iroh::watcher::Direct"]],["impl<T> Freeze for Watchable<T>",1,["iroh::watcher::Watchable"]],["impl<W> Freeze for Stream<W>
    where\n W: Freeze,\n <W as Watcher>::Value: Freeze,
    ",1,["iroh::watcher::Stream"]],["impl<W, T> Freeze for Map<W, T>
    where\n W: Freeze,\n T: Freeze,
    ",1,["iroh::watcher::Map"]]]],["iroh_base",[["impl Freeze for KeyParsingError",1,["iroh_base::key::KeyParsingError"]],["impl Freeze for ParseError",1,["iroh_base::ticket::ParseError"]],["impl Freeze for NodeAddr",1,["iroh_base::node_addr::NodeAddr"]],["impl Freeze for PublicKey",1,["iroh_base::key::PublicKey"]],["impl Freeze for RelayUrl",1,["iroh_base::relay_url::RelayUrl"]],["impl Freeze for RelayUrlParseError",1,["iroh_base::relay_url::RelayUrlParseError"]],["impl Freeze for SecretKey",1,["iroh_base::key::SecretKey"]],["impl Freeze for NodeTicket",1,["iroh_base::ticket::node::NodeTicket"]]]],["iroh_bench",[["impl Freeze for Commands",1,["iroh_bench::Commands"]],["impl Freeze for ConnectionSelector",1,["iroh_bench::ConnectionSelector"]],["impl Freeze for EndpointSelector",1,["iroh_bench::EndpointSelector"]],["impl Freeze for Opt",1,["iroh_bench::s2n::Opt"]],["impl Freeze for Stats",1,["iroh_bench::stats::Stats"]],["impl Freeze for StreamStats",1,["iroh_bench::stats::StreamStats"]],["impl Freeze for TransferResult",1,["iroh_bench::stats::TransferResult"]],["impl Freeze for ClientStats",1,["iroh_bench::ClientStats"]],["impl Freeze for Opt",1,["iroh_bench::Opt"]]]],["iroh_dns_server",[["impl !Freeze for Metrics",1,["iroh_dns_server::metrics::Metrics"]],["impl Freeze for BootstrapOption",1,["iroh_dns_server::config::BootstrapOption"]],["impl Freeze for CertMode",1,["iroh_dns_server::http::tls::CertMode"]],["impl Freeze for RateLimitConfig",1,["iroh_dns_server::http::rate_limiting::RateLimitConfig"]],["impl Freeze for Config",1,["iroh_dns_server::config::Config"]],["impl Freeze for MainlineConfig",1,["iroh_dns_server::config::MainlineConfig"]],["impl Freeze for MetricsConfig",1,["iroh_dns_server::config::MetricsConfig"]],["impl Freeze for StoreConfig",1,["iroh_dns_server::config::StoreConfig"]],["impl Freeze for DnsConfig",1,["iroh_dns_server::dns::DnsConfig"]],["impl Freeze for DnsHandler",1,["iroh_dns_server::dns::DnsHandler"]],["impl Freeze for DnsServer",1,["iroh_dns_server::dns::DnsServer"]],["impl Freeze for Handle",1,["iroh_dns_server::dns::Handle"]],["impl Freeze for HttpConfig",1,["iroh_dns_server::http::HttpConfig"]],["impl Freeze for HttpServer",1,["iroh_dns_server::http::HttpServer"]],["impl Freeze for HttpsConfig",1,["iroh_dns_server::http::HttpsConfig"]],["impl Freeze for Server",1,["iroh_dns_server::server::Server"]],["impl Freeze for AppState",1,["iroh_dns_server::state::AppState"]],["impl Freeze for ZoneStore",1,["iroh_dns_server::store::ZoneStore"]]]],["iroh_relay",[["impl !Freeze for ReceivedMessage",1,["iroh_relay::client::conn::ReceivedMessage"]],["impl !Freeze for SendMessage",1,["iroh_relay::client::conn::SendMessage"]],["impl !Freeze for Error",1,["iroh_relay::quic::Error"]],["impl !Freeze for Client",1,["iroh_relay::client::Client"]],["impl !Freeze for ClientSink",1,["iroh_relay::client::ClientSink"]],["impl !Freeze for Metrics",1,["iroh_relay::server::metrics::Metrics"]],["impl !Freeze for StunMetrics",1,["iroh_relay::server::metrics::StunMetrics"]],["impl Freeze for ConnectError",1,["iroh_relay::client::ConnectError"]],["impl Freeze for DialError",1,["iroh_relay::client::DialError"]],["impl Freeze for RecvError",1,["iroh_relay::client::conn::RecvError"]],["impl Freeze for SendError",1,["iroh_relay::client::conn::SendError"]],["impl Freeze for DnsError",1,["iroh_relay::dns::DnsError"]],["impl Freeze for Protocol",1,["iroh_relay::http::Protocol"]],["impl Freeze for DecodingError",1,["iroh_relay::node_info::DecodingError"]],["impl Freeze for EncodingError",1,["iroh_relay::node_info::EncodingError"]],["impl Freeze for LookupError",1,["iroh_relay::node_info::LookupError"]],["impl Freeze for ParseError",1,["iroh_relay::node_info::ParseError"]],["impl Freeze for FrameType",1,["iroh_relay::protos::relay::FrameType"]],["impl Freeze for RecvError",1,["iroh_relay::protos::relay::RecvError"]],["impl Freeze for SendError",1,["iroh_relay::protos::relay::SendError"]],["impl Freeze for StunError",1,["iroh_relay::protos::stun::StunError"]],["impl Freeze for Access",1,["iroh_relay::server::Access"]],["impl Freeze for AccessConfig",1,["iroh_relay::server::AccessConfig"]],["impl Freeze for SpawnError",1,["iroh_relay::server::SpawnError"]],["impl Freeze for SupervisorError",1,["iroh_relay::server::SupervisorError"]],["impl Freeze for ClientBuilder",1,["iroh_relay::client::ClientBuilder"]],["impl Freeze for ClientStream",1,["iroh_relay::client::ClientStream"]],["impl Freeze for DnsResolver",1,["iroh_relay::dns::DnsResolver"]],["impl Freeze for Error",1,["iroh_relay::dns::staggered::Error"]],["impl Freeze for TXT",1,["iroh_relay::dns::TXT"]],["impl Freeze for TxtLookup",1,["iroh_relay::dns::TxtLookup"]],["impl Freeze for MaxLengthExceededError",1,["iroh_relay::node_info::MaxLengthExceededError"]],["impl Freeze for NodeData",1,["iroh_relay::node_info::NodeData"]],["impl Freeze for NodeInfo",1,["iroh_relay::node_info::NodeInfo"]],["impl Freeze for UserData",1,["iroh_relay::node_info::UserData"]],["impl Freeze for QuicClient",1,["iroh_relay::quic::QuicClient"]],["impl Freeze for ClientRateLimit",1,["iroh_relay::server::ClientRateLimit"]],["impl Freeze for Limits",1,["iroh_relay::server::Limits"]],["impl Freeze for QuicConfig",1,["iroh_relay::server::QuicConfig"]],["impl Freeze for RelayMetrics",1,["iroh_relay::server::metrics::RelayMetrics"]],["impl Freeze for Server",1,["iroh_relay::server::Server"]],["impl Freeze for StunConfig",1,["iroh_relay::server::StunConfig"]],["impl Freeze for PingTracker",1,["iroh_relay::ping_tracker::PingTracker"]],["impl Freeze for RelayMap",1,["iroh_relay::relay_map::RelayMap"]],["impl Freeze for RelayNode",1,["iroh_relay::relay_map::RelayNode"]],["impl Freeze for RelayQuicConfig",1,["iroh_relay::relay_map::RelayQuicConfig"]],["impl<EC, EA> Freeze for CertConfig<EC, EA>",1,["iroh_relay::server::CertConfig"]],["impl<EC, EA> Freeze for RelayConfig<EC, EA>",1,["iroh_relay::server::RelayConfig"]],["impl<EC, EA> Freeze for ServerConfig<EC, EA>",1,["iroh_relay::server::ServerConfig"]],["impl<EC, EA> Freeze for TlsConfig<EC, EA>",1,["iroh_relay::server::TlsConfig"]],["impl<Loader> Freeze for ReloadingResolver<Loader>",1,["iroh_relay::server::resolver::ReloadingResolver"]]]]]); + var implementors = Object.fromEntries([["iroh",[["impl !Freeze for AlpnError",1,["iroh::endpoint::AlpnError"]],["impl !Freeze for ReportError",1,["iroh::net_report::ReportError"]],["impl !Freeze for AcceptError",1,["iroh::protocol::AcceptError"]],["impl !Freeze for Incoming",1,["iroh::endpoint::Incoming"]],["impl !Freeze for IncomingFuture",1,["iroh::endpoint::IncomingFuture"]],["impl !Freeze for Metrics",1,["iroh::magicsock::metrics::Metrics"]],["impl !Freeze for Metrics",1,["iroh::net_report::metrics::Metrics"]],["impl Freeze for DiscoveryError",1,["iroh::discovery::DiscoveryError"]],["impl Freeze for IntoDiscoveryError",1,["iroh::discovery::IntoDiscoveryError"]],["impl Freeze for PkarrError",1,["iroh::discovery::pkarr::PkarrError"]],["impl Freeze for AddNodeAddrError",1,["iroh::magicsock::AddNodeAddrError"]],["impl Freeze for BindError",1,["iroh::endpoint::BindError"]],["impl Freeze for ConnectError",1,["iroh::endpoint::ConnectError"]],["impl Freeze for ConnectWithOptsError",1,["iroh::endpoint::ConnectWithOptsError"]],["impl Freeze for ConnectionType",1,["iroh::magicsock::node_map::node_state::ConnectionType"]],["impl Freeze for ControlMsg",1,["iroh::magicsock::node_map::node_state::ControlMsg"]],["impl Freeze for DirectAddrType",1,["iroh::magicsock::DirectAddrType"]],["impl Freeze for GetMappingAddressError",1,["iroh::endpoint::GetMappingAddressError"]],["impl Freeze for PathSelection",1,["iroh::endpoint::PathSelection"]],["impl Freeze for RelayMode",1,["iroh::endpoint::RelayMode"]],["impl Freeze for Source",1,["iroh::magicsock::node_map::Source"]],["impl Freeze for DnsDiscovery",1,["iroh::discovery::dns::DnsDiscovery"]],["impl Freeze for DnsDiscoveryBuilder",1,["iroh::discovery::dns::DnsDiscoveryBuilder"]],["impl Freeze for MdnsDiscovery",1,["iroh::discovery::mdns::MdnsDiscovery"]],["impl Freeze for MdnsDiscoveryBuilder",1,["iroh::discovery::mdns::MdnsDiscoveryBuilder"]],["impl Freeze for Builder",1,["iroh::discovery::pkarr::dht::Builder"]],["impl Freeze for DhtDiscovery",1,["iroh::discovery::pkarr::dht::DhtDiscovery"]],["impl Freeze for PkarrPublisher",1,["iroh::discovery::pkarr::PkarrPublisher"]],["impl Freeze for PkarrPublisherBuilder",1,["iroh::discovery::pkarr::PkarrPublisherBuilder"]],["impl Freeze for PkarrRelayClient",1,["iroh::discovery::pkarr::PkarrRelayClient"]],["impl Freeze for PkarrResolver",1,["iroh::discovery::pkarr::PkarrResolver"]],["impl Freeze for PkarrResolverBuilder",1,["iroh::discovery::pkarr::PkarrResolverBuilder"]],["impl Freeze for StaticProvider",1,["iroh::discovery::static_provider::StaticProvider"]],["impl Freeze for ConcurrentDiscovery",1,["iroh::discovery::ConcurrentDiscovery"]],["impl Freeze for DiscoveryItem",1,["iroh::discovery::DiscoveryItem"]],["impl Freeze for Lagged",1,["iroh::discovery::Lagged"]],["impl Freeze for Builder",1,["iroh::endpoint::Builder"]],["impl Freeze for ConnectOptions",1,["iroh::endpoint::ConnectOptions"]],["impl Freeze for Connecting",1,["iroh::endpoint::Connecting"]],["impl Freeze for Connection",1,["iroh::endpoint::Connection"]],["impl Freeze for DirectAddr",1,["iroh::magicsock::DirectAddr"]],["impl Freeze for DirectAddrInfo",1,["iroh::magicsock::node_map::node_state::DirectAddrInfo"]],["impl Freeze for Endpoint",1,["iroh::endpoint::Endpoint"]],["impl Freeze for RemoteInfo",1,["iroh::magicsock::node_map::node_state::RemoteInfo"]],["impl Freeze for RemoteNodeIdError",1,["iroh::endpoint::RemoteNodeIdError"]],["impl Freeze for ZeroRttAccepted",1,["iroh::endpoint::ZeroRttAccepted"]],["impl Freeze for EndpointMetrics",1,["iroh::metrics::EndpointMetrics"]],["impl Freeze for Addr",1,["iroh::net_report::Addr"]],["impl Freeze for Client",1,["iroh::net_report::Client"]],["impl Freeze for Options",1,["iroh::net_report::options::imp::Options"]],["impl Freeze for QuicConfig",1,["iroh::net_report::reportgen::QuicConfig"]],["impl Freeze for RelayLatencies",1,["iroh::net_report::RelayLatencies"]],["impl Freeze for Report",1,["iroh::net_report::Report"]],["impl Freeze for Router",1,["iroh::protocol::Router"]],["impl Freeze for RouterBuilder",1,["iroh::protocol::RouterBuilder"]],["impl Freeze for CleanupDropGuard",1,["iroh::test_utils::CleanupDropGuard"]],["impl Freeze for DnsPkarrServer",1,["iroh::test_utils::dns_and_pkarr_servers::DnsPkarrServer"]],["impl<'a> !Freeze for Accept<'a>",1,["iroh::endpoint::Accept"]],["impl<'a> Freeze for DiscoveryContext<'a>",1,["iroh::discovery::DiscoveryContext"]],["impl<P> Freeze for AccessLimit<P>
    where\n P: Freeze,
    ",1,["iroh::protocol::AccessLimit"]]]],["iroh_base",[["impl Freeze for KeyParsingError",1,["iroh_base::key::KeyParsingError"]],["impl Freeze for ParseError",1,["iroh_base::ticket::ParseError"]],["impl Freeze for NodeAddr",1,["iroh_base::node_addr::NodeAddr"]],["impl Freeze for PublicKey",1,["iroh_base::key::PublicKey"]],["impl Freeze for RelayUrl",1,["iroh_base::relay_url::RelayUrl"]],["impl Freeze for RelayUrlParseError",1,["iroh_base::relay_url::RelayUrlParseError"]],["impl Freeze for SecretKey",1,["iroh_base::key::SecretKey"]],["impl Freeze for NodeTicket",1,["iroh_base::ticket::node::NodeTicket"]]]],["iroh_bench",[["impl Freeze for Commands",1,["iroh_bench::Commands"]],["impl Freeze for ConnectionSelector",1,["iroh_bench::ConnectionSelector"]],["impl Freeze for EndpointSelector",1,["iroh_bench::EndpointSelector"]],["impl Freeze for Opt",1,["iroh_bench::s2n::Opt"]],["impl Freeze for Stats",1,["iroh_bench::stats::Stats"]],["impl Freeze for StreamStats",1,["iroh_bench::stats::StreamStats"]],["impl Freeze for TransferResult",1,["iroh_bench::stats::TransferResult"]],["impl Freeze for ClientStats",1,["iroh_bench::ClientStats"]],["impl Freeze for Opt",1,["iroh_bench::Opt"]]]],["iroh_dns_server",[["impl !Freeze for Metrics",1,["iroh_dns_server::metrics::Metrics"]],["impl Freeze for BootstrapOption",1,["iroh_dns_server::config::BootstrapOption"]],["impl Freeze for CertMode",1,["iroh_dns_server::http::tls::CertMode"]],["impl Freeze for RateLimitConfig",1,["iroh_dns_server::http::rate_limiting::RateLimitConfig"]],["impl Freeze for Config",1,["iroh_dns_server::config::Config"]],["impl Freeze for MainlineConfig",1,["iroh_dns_server::config::MainlineConfig"]],["impl Freeze for MetricsConfig",1,["iroh_dns_server::config::MetricsConfig"]],["impl Freeze for StoreConfig",1,["iroh_dns_server::config::StoreConfig"]],["impl Freeze for DnsConfig",1,["iroh_dns_server::dns::DnsConfig"]],["impl Freeze for DnsHandler",1,["iroh_dns_server::dns::DnsHandler"]],["impl Freeze for DnsServer",1,["iroh_dns_server::dns::DnsServer"]],["impl Freeze for Handle",1,["iroh_dns_server::dns::Handle"]],["impl Freeze for HttpConfig",1,["iroh_dns_server::http::HttpConfig"]],["impl Freeze for HttpServer",1,["iroh_dns_server::http::HttpServer"]],["impl Freeze for HttpsConfig",1,["iroh_dns_server::http::HttpsConfig"]],["impl Freeze for Server",1,["iroh_dns_server::server::Server"]],["impl Freeze for AppState",1,["iroh_dns_server::state::AppState"]],["impl Freeze for ZoneStore",1,["iroh_dns_server::store::ZoneStore"]]]],["iroh_relay",[["impl !Freeze for ReceivedMessage",1,["iroh_relay::client::conn::ReceivedMessage"]],["impl !Freeze for SendMessage",1,["iroh_relay::client::conn::SendMessage"]],["impl !Freeze for Error",1,["iroh_relay::quic::Error"]],["impl !Freeze for Client",1,["iroh_relay::client::Client"]],["impl !Freeze for ClientSink",1,["iroh_relay::client::ClientSink"]],["impl !Freeze for Metrics",1,["iroh_relay::server::metrics::Metrics"]],["impl !Freeze for StunMetrics",1,["iroh_relay::server::metrics::StunMetrics"]],["impl Freeze for ConnectError",1,["iroh_relay::client::ConnectError"]],["impl Freeze for DialError",1,["iroh_relay::client::DialError"]],["impl Freeze for RecvError",1,["iroh_relay::client::conn::RecvError"]],["impl Freeze for SendError",1,["iroh_relay::client::conn::SendError"]],["impl Freeze for DnsError",1,["iroh_relay::dns::DnsError"]],["impl Freeze for Protocol",1,["iroh_relay::http::Protocol"]],["impl Freeze for DecodingError",1,["iroh_relay::node_info::DecodingError"]],["impl Freeze for EncodingError",1,["iroh_relay::node_info::EncodingError"]],["impl Freeze for LookupError",1,["iroh_relay::node_info::LookupError"]],["impl Freeze for ParseError",1,["iroh_relay::node_info::ParseError"]],["impl Freeze for FrameType",1,["iroh_relay::protos::relay::FrameType"]],["impl Freeze for RecvError",1,["iroh_relay::protos::relay::RecvError"]],["impl Freeze for SendError",1,["iroh_relay::protos::relay::SendError"]],["impl Freeze for StunError",1,["iroh_relay::protos::stun::StunError"]],["impl Freeze for Access",1,["iroh_relay::server::Access"]],["impl Freeze for AccessConfig",1,["iroh_relay::server::AccessConfig"]],["impl Freeze for SpawnError",1,["iroh_relay::server::SpawnError"]],["impl Freeze for SupervisorError",1,["iroh_relay::server::SupervisorError"]],["impl Freeze for ClientBuilder",1,["iroh_relay::client::ClientBuilder"]],["impl Freeze for ClientStream",1,["iroh_relay::client::ClientStream"]],["impl Freeze for DnsResolver",1,["iroh_relay::dns::DnsResolver"]],["impl Freeze for TXT",1,["iroh_relay::dns::TXT"]],["impl Freeze for TxtLookup",1,["iroh_relay::dns::TxtLookup"]],["impl Freeze for MaxLengthExceededError",1,["iroh_relay::node_info::MaxLengthExceededError"]],["impl Freeze for NodeData",1,["iroh_relay::node_info::NodeData"]],["impl Freeze for NodeInfo",1,["iroh_relay::node_info::NodeInfo"]],["impl Freeze for UserData",1,["iroh_relay::node_info::UserData"]],["impl Freeze for QuicClient",1,["iroh_relay::quic::QuicClient"]],["impl Freeze for ClientRateLimit",1,["iroh_relay::server::ClientRateLimit"]],["impl Freeze for Limits",1,["iroh_relay::server::Limits"]],["impl Freeze for QuicConfig",1,["iroh_relay::server::QuicConfig"]],["impl Freeze for RelayMetrics",1,["iroh_relay::server::metrics::RelayMetrics"]],["impl Freeze for Server",1,["iroh_relay::server::Server"]],["impl Freeze for StunConfig",1,["iroh_relay::server::StunConfig"]],["impl Freeze for PingTracker",1,["iroh_relay::ping_tracker::PingTracker"]],["impl Freeze for RelayMap",1,["iroh_relay::relay_map::RelayMap"]],["impl Freeze for RelayNode",1,["iroh_relay::relay_map::RelayNode"]],["impl Freeze for RelayQuicConfig",1,["iroh_relay::relay_map::RelayQuicConfig"]],["impl<E> Freeze for StaggeredError<E>",1,["iroh_relay::dns::StaggeredError"]],["impl<EC, EA> Freeze for CertConfig<EC, EA>",1,["iroh_relay::server::CertConfig"]],["impl<EC, EA> Freeze for RelayConfig<EC, EA>",1,["iroh_relay::server::RelayConfig"]],["impl<EC, EA> Freeze for ServerConfig<EC, EA>",1,["iroh_relay::server::ServerConfig"]],["impl<EC, EA> Freeze for TlsConfig<EC, EA>",1,["iroh_relay::server::TlsConfig"]],["impl<Loader> Freeze for ReloadingResolver<Loader>",1,["iroh_relay::server::resolver::ReloadingResolver"]]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[23303,2508,2769,6015,16642]} \ No newline at end of file +//{"start":57,"fragment_lengths":[19946,2508,2769,6015,16685]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/marker/trait.Send.js b/pr/3327/docs/trait.impl/core/marker/trait.Send.js index fe7d002962..45d7a6c1bf 100644 --- a/pr/3327/docs/trait.impl/core/marker/trait.Send.js +++ b/pr/3327/docs/trait.impl/core/marker/trait.Send.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl Send for DiscoveryError",1,["iroh::discovery::DiscoveryError"]],["impl Send for IntoDiscoveryError",1,["iroh::discovery::IntoDiscoveryError"]],["impl Send for PkarrError",1,["iroh::discovery::pkarr::PkarrError"]],["impl Send for AddNodeAddrError",1,["iroh::magicsock::AddNodeAddrError"]],["impl Send for AlpnError",1,["iroh::endpoint::AlpnError"]],["impl Send for BindError",1,["iroh::endpoint::BindError"]],["impl Send for ConnectError",1,["iroh::endpoint::ConnectError"]],["impl Send for ConnectWithOptsError",1,["iroh::endpoint::ConnectWithOptsError"]],["impl Send for ConnectionType",1,["iroh::magicsock::node_map::node_state::ConnectionType"]],["impl Send for ControlMsg",1,["iroh::magicsock::node_map::node_state::ControlMsg"]],["impl Send for DirectAddrType",1,["iroh::magicsock::DirectAddrType"]],["impl Send for GetMappingAddressError",1,["iroh::endpoint::GetMappingAddressError"]],["impl Send for PathSelection",1,["iroh::endpoint::PathSelection"]],["impl Send for RelayMode",1,["iroh::endpoint::RelayMode"]],["impl Send for Source",1,["iroh::magicsock::node_map::Source"]],["impl Send for ReportError",1,["iroh::net_report::ReportError"]],["impl Send for ProtocolError",1,["iroh::protocol::ProtocolError"]],["impl Send for DnsDiscovery",1,["iroh::discovery::dns::DnsDiscovery"]],["impl Send for DnsDiscoveryBuilder",1,["iroh::discovery::dns::DnsDiscoveryBuilder"]],["impl Send for MdnsDiscovery",1,["iroh::discovery::mdns::MdnsDiscovery"]],["impl Send for MdnsDiscoveryBuilder",1,["iroh::discovery::mdns::MdnsDiscoveryBuilder"]],["impl Send for Builder",1,["iroh::discovery::pkarr::dht::Builder"]],["impl Send for DhtDiscovery",1,["iroh::discovery::pkarr::dht::DhtDiscovery"]],["impl Send for PkarrPublisher",1,["iroh::discovery::pkarr::PkarrPublisher"]],["impl Send for PkarrPublisherBuilder",1,["iroh::discovery::pkarr::PkarrPublisherBuilder"]],["impl Send for PkarrRelayClient",1,["iroh::discovery::pkarr::PkarrRelayClient"]],["impl Send for PkarrResolver",1,["iroh::discovery::pkarr::PkarrResolver"]],["impl Send for PkarrResolverBuilder",1,["iroh::discovery::pkarr::PkarrResolverBuilder"]],["impl Send for StaticProvider",1,["iroh::discovery::static_provider::StaticProvider"]],["impl Send for ConcurrentDiscovery",1,["iroh::discovery::ConcurrentDiscovery"]],["impl Send for DiscoveryItem",1,["iroh::discovery::DiscoveryItem"]],["impl Send for Lagged",1,["iroh::discovery::Lagged"]],["impl Send for Builder",1,["iroh::endpoint::Builder"]],["impl Send for ConnectOptions",1,["iroh::endpoint::ConnectOptions"]],["impl Send for Connecting",1,["iroh::endpoint::Connecting"]],["impl Send for Connection",1,["iroh::endpoint::Connection"]],["impl Send for DirectAddr",1,["iroh::magicsock::DirectAddr"]],["impl Send for DirectAddrInfo",1,["iroh::magicsock::node_map::node_state::DirectAddrInfo"]],["impl Send for Endpoint",1,["iroh::endpoint::Endpoint"]],["impl Send for Incoming",1,["iroh::endpoint::Incoming"]],["impl Send for IncomingFuture",1,["iroh::endpoint::IncomingFuture"]],["impl Send for RemoteInfo",1,["iroh::magicsock::node_map::node_state::RemoteInfo"]],["impl Send for RemoteNodeIdError",1,["iroh::endpoint::RemoteNodeIdError"]],["impl Send for ZeroRttAccepted",1,["iroh::endpoint::ZeroRttAccepted"]],["impl Send for EndpointMetrics",1,["iroh::metrics::EndpointMetrics"]],["impl Send for Metrics",1,["iroh::magicsock::metrics::Metrics"]],["impl Send for Addr",1,["iroh::net_report::Addr"]],["impl Send for Client",1,["iroh::net_report::Client"]],["impl Send for Metrics",1,["iroh::net_report::metrics::Metrics"]],["impl Send for Options",1,["iroh::net_report::options::imp::Options"]],["impl Send for QuicConfig",1,["iroh::net_report::reportgen::QuicConfig"]],["impl Send for RelayLatencies",1,["iroh::net_report::RelayLatencies"]],["impl Send for Report",1,["iroh::net_report::Report"]],["impl Send for Router",1,["iroh::protocol::Router"]],["impl Send for RouterBuilder",1,["iroh::protocol::RouterBuilder"]],["impl Send for CleanupDropGuard",1,["iroh::test_utils::CleanupDropGuard"]],["impl Send for DnsPkarrServer",1,["iroh::test_utils::dns_and_pkarr_servers::DnsPkarrServer"]],["impl Send for Disconnected",1,["iroh::watcher::Disconnected"]],["impl<'a> Send for DiscoveryContext<'a>",1,["iroh::discovery::DiscoveryContext"]],["impl<'a> Send for Accept<'a>",1,["iroh::endpoint::Accept"]],["impl<'a, T, W> Send for InitializedFut<'a, T, W>
    where\n W: Send,\n T: Send,
    ",1,["iroh::watcher::InitializedFut"]],["impl<'a, W> Send for NextFut<'a, W>
    where\n W: Send,
    ",1,["iroh::watcher::NextFut"]],["impl<P> Send for AccessLimit<P>",1,["iroh::protocol::AccessLimit"]],["impl<T> Send for Direct<T>
    where\n T: Send + Sync,
    ",1,["iroh::watcher::Direct"]],["impl<T> Send for Watchable<T>
    where\n T: Send + Sync,
    ",1,["iroh::watcher::Watchable"]],["impl<W> Send for Stream<W>
    where\n W: Send,\n <W as Watcher>::Value: Send,
    ",1,["iroh::watcher::Stream"]],["impl<W, T> !Send for Map<W, T>",1,["iroh::watcher::Map"]]]],["iroh_base",[["impl Send for KeyParsingError",1,["iroh_base::key::KeyParsingError"]],["impl Send for ParseError",1,["iroh_base::ticket::ParseError"]],["impl Send for NodeAddr",1,["iroh_base::node_addr::NodeAddr"]],["impl Send for PublicKey",1,["iroh_base::key::PublicKey"]],["impl Send for RelayUrl",1,["iroh_base::relay_url::RelayUrl"]],["impl Send for RelayUrlParseError",1,["iroh_base::relay_url::RelayUrlParseError"]],["impl Send for SecretKey",1,["iroh_base::key::SecretKey"]],["impl Send for NodeTicket",1,["iroh_base::ticket::node::NodeTicket"]]]],["iroh_bench",[["impl Send for Commands",1,["iroh_bench::Commands"]],["impl Send for ConnectionSelector",1,["iroh_bench::ConnectionSelector"]],["impl Send for EndpointSelector",1,["iroh_bench::EndpointSelector"]],["impl Send for Opt",1,["iroh_bench::s2n::Opt"]],["impl Send for Stats",1,["iroh_bench::stats::Stats"]],["impl Send for StreamStats",1,["iroh_bench::stats::StreamStats"]],["impl Send for TransferResult",1,["iroh_bench::stats::TransferResult"]],["impl Send for ClientStats",1,["iroh_bench::ClientStats"]],["impl Send for Opt",1,["iroh_bench::Opt"]]]],["iroh_dns_server",[["impl Send for BootstrapOption",1,["iroh_dns_server::config::BootstrapOption"]],["impl Send for CertMode",1,["iroh_dns_server::http::tls::CertMode"]],["impl Send for RateLimitConfig",1,["iroh_dns_server::http::rate_limiting::RateLimitConfig"]],["impl Send for Config",1,["iroh_dns_server::config::Config"]],["impl Send for MainlineConfig",1,["iroh_dns_server::config::MainlineConfig"]],["impl Send for MetricsConfig",1,["iroh_dns_server::config::MetricsConfig"]],["impl Send for StoreConfig",1,["iroh_dns_server::config::StoreConfig"]],["impl Send for DnsConfig",1,["iroh_dns_server::dns::DnsConfig"]],["impl Send for DnsHandler",1,["iroh_dns_server::dns::DnsHandler"]],["impl Send for DnsServer",1,["iroh_dns_server::dns::DnsServer"]],["impl Send for Handle",1,["iroh_dns_server::dns::Handle"]],["impl Send for HttpConfig",1,["iroh_dns_server::http::HttpConfig"]],["impl Send for HttpServer",1,["iroh_dns_server::http::HttpServer"]],["impl Send for HttpsConfig",1,["iroh_dns_server::http::HttpsConfig"]],["impl Send for Metrics",1,["iroh_dns_server::metrics::Metrics"]],["impl Send for Server",1,["iroh_dns_server::server::Server"]],["impl Send for AppState",1,["iroh_dns_server::state::AppState"]],["impl Send for ZoneStore",1,["iroh_dns_server::store::ZoneStore"]]]],["iroh_relay",[["impl Send for ConnectError",1,["iroh_relay::client::ConnectError"]],["impl Send for DialError",1,["iroh_relay::client::DialError"]],["impl Send for ReceivedMessage",1,["iroh_relay::client::conn::ReceivedMessage"]],["impl Send for RecvError",1,["iroh_relay::client::conn::RecvError"]],["impl Send for SendError",1,["iroh_relay::client::conn::SendError"]],["impl Send for SendMessage",1,["iroh_relay::client::conn::SendMessage"]],["impl Send for DnsError",1,["iroh_relay::dns::DnsError"]],["impl Send for Protocol",1,["iroh_relay::http::Protocol"]],["impl Send for DecodingError",1,["iroh_relay::node_info::DecodingError"]],["impl Send for EncodingError",1,["iroh_relay::node_info::EncodingError"]],["impl Send for LookupError",1,["iroh_relay::node_info::LookupError"]],["impl Send for ParseError",1,["iroh_relay::node_info::ParseError"]],["impl Send for FrameType",1,["iroh_relay::protos::relay::FrameType"]],["impl Send for RecvError",1,["iroh_relay::protos::relay::RecvError"]],["impl Send for SendError",1,["iroh_relay::protos::relay::SendError"]],["impl Send for StunError",1,["iroh_relay::protos::stun::StunError"]],["impl Send for Error",1,["iroh_relay::quic::Error"]],["impl Send for Access",1,["iroh_relay::server::Access"]],["impl Send for AccessConfig",1,["iroh_relay::server::AccessConfig"]],["impl Send for SpawnError",1,["iroh_relay::server::SpawnError"]],["impl Send for SupervisorError",1,["iroh_relay::server::SupervisorError"]],["impl Send for Client",1,["iroh_relay::client::Client"]],["impl Send for ClientBuilder",1,["iroh_relay::client::ClientBuilder"]],["impl Send for ClientSink",1,["iroh_relay::client::ClientSink"]],["impl Send for ClientStream",1,["iroh_relay::client::ClientStream"]],["impl Send for DnsResolver",1,["iroh_relay::dns::DnsResolver"]],["impl Send for Error",1,["iroh_relay::dns::staggered::Error"]],["impl Send for TXT",1,["iroh_relay::dns::TXT"]],["impl Send for TxtLookup",1,["iroh_relay::dns::TxtLookup"]],["impl Send for MaxLengthExceededError",1,["iroh_relay::node_info::MaxLengthExceededError"]],["impl Send for NodeData",1,["iroh_relay::node_info::NodeData"]],["impl Send for NodeInfo",1,["iroh_relay::node_info::NodeInfo"]],["impl Send for UserData",1,["iroh_relay::node_info::UserData"]],["impl Send for QuicClient",1,["iroh_relay::quic::QuicClient"]],["impl Send for ClientRateLimit",1,["iroh_relay::server::ClientRateLimit"]],["impl Send for Limits",1,["iroh_relay::server::Limits"]],["impl Send for Metrics",1,["iroh_relay::server::metrics::Metrics"]],["impl Send for QuicConfig",1,["iroh_relay::server::QuicConfig"]],["impl Send for RelayMetrics",1,["iroh_relay::server::metrics::RelayMetrics"]],["impl Send for Server",1,["iroh_relay::server::Server"]],["impl Send for StunConfig",1,["iroh_relay::server::StunConfig"]],["impl Send for StunMetrics",1,["iroh_relay::server::metrics::StunMetrics"]],["impl Send for PingTracker",1,["iroh_relay::ping_tracker::PingTracker"]],["impl Send for RelayMap",1,["iroh_relay::relay_map::RelayMap"]],["impl Send for RelayNode",1,["iroh_relay::relay_map::RelayNode"]],["impl Send for RelayQuicConfig",1,["iroh_relay::relay_map::RelayQuicConfig"]],["impl<EC, EA> Send for CertConfig<EC, EA>",1,["iroh_relay::server::CertConfig"]],["impl<EC, EA> Send for RelayConfig<EC, EA>",1,["iroh_relay::server::RelayConfig"]],["impl<EC, EA> Send for ServerConfig<EC, EA>",1,["iroh_relay::server::ServerConfig"]],["impl<EC, EA> Send for TlsConfig<EC, EA>",1,["iroh_relay::server::TlsConfig"]],["impl<Loader> Send for ReloadingResolver<Loader>",1,["iroh_relay::server::resolver::ReloadingResolver"]]]]]); + var implementors = Object.fromEntries([["iroh",[["impl Send for DiscoveryError",1,["iroh::discovery::DiscoveryError"]],["impl Send for IntoDiscoveryError",1,["iroh::discovery::IntoDiscoveryError"]],["impl Send for PkarrError",1,["iroh::discovery::pkarr::PkarrError"]],["impl Send for AddNodeAddrError",1,["iroh::magicsock::AddNodeAddrError"]],["impl Send for AlpnError",1,["iroh::endpoint::AlpnError"]],["impl Send for BindError",1,["iroh::endpoint::BindError"]],["impl Send for ConnectError",1,["iroh::endpoint::ConnectError"]],["impl Send for ConnectWithOptsError",1,["iroh::endpoint::ConnectWithOptsError"]],["impl Send for ConnectionType",1,["iroh::magicsock::node_map::node_state::ConnectionType"]],["impl Send for ControlMsg",1,["iroh::magicsock::node_map::node_state::ControlMsg"]],["impl Send for DirectAddrType",1,["iroh::magicsock::DirectAddrType"]],["impl Send for GetMappingAddressError",1,["iroh::endpoint::GetMappingAddressError"]],["impl Send for PathSelection",1,["iroh::endpoint::PathSelection"]],["impl Send for RelayMode",1,["iroh::endpoint::RelayMode"]],["impl Send for Source",1,["iroh::magicsock::node_map::Source"]],["impl Send for ReportError",1,["iroh::net_report::ReportError"]],["impl Send for AcceptError",1,["iroh::protocol::AcceptError"]],["impl Send for DnsDiscovery",1,["iroh::discovery::dns::DnsDiscovery"]],["impl Send for DnsDiscoveryBuilder",1,["iroh::discovery::dns::DnsDiscoveryBuilder"]],["impl Send for MdnsDiscovery",1,["iroh::discovery::mdns::MdnsDiscovery"]],["impl Send for MdnsDiscoveryBuilder",1,["iroh::discovery::mdns::MdnsDiscoveryBuilder"]],["impl Send for Builder",1,["iroh::discovery::pkarr::dht::Builder"]],["impl Send for DhtDiscovery",1,["iroh::discovery::pkarr::dht::DhtDiscovery"]],["impl Send for PkarrPublisher",1,["iroh::discovery::pkarr::PkarrPublisher"]],["impl Send for PkarrPublisherBuilder",1,["iroh::discovery::pkarr::PkarrPublisherBuilder"]],["impl Send for PkarrRelayClient",1,["iroh::discovery::pkarr::PkarrRelayClient"]],["impl Send for PkarrResolver",1,["iroh::discovery::pkarr::PkarrResolver"]],["impl Send for PkarrResolverBuilder",1,["iroh::discovery::pkarr::PkarrResolverBuilder"]],["impl Send for StaticProvider",1,["iroh::discovery::static_provider::StaticProvider"]],["impl Send for ConcurrentDiscovery",1,["iroh::discovery::ConcurrentDiscovery"]],["impl Send for DiscoveryItem",1,["iroh::discovery::DiscoveryItem"]],["impl Send for Lagged",1,["iroh::discovery::Lagged"]],["impl Send for Builder",1,["iroh::endpoint::Builder"]],["impl Send for ConnectOptions",1,["iroh::endpoint::ConnectOptions"]],["impl Send for Connecting",1,["iroh::endpoint::Connecting"]],["impl Send for Connection",1,["iroh::endpoint::Connection"]],["impl Send for DirectAddr",1,["iroh::magicsock::DirectAddr"]],["impl Send for DirectAddrInfo",1,["iroh::magicsock::node_map::node_state::DirectAddrInfo"]],["impl Send for Endpoint",1,["iroh::endpoint::Endpoint"]],["impl Send for Incoming",1,["iroh::endpoint::Incoming"]],["impl Send for IncomingFuture",1,["iroh::endpoint::IncomingFuture"]],["impl Send for RemoteInfo",1,["iroh::magicsock::node_map::node_state::RemoteInfo"]],["impl Send for RemoteNodeIdError",1,["iroh::endpoint::RemoteNodeIdError"]],["impl Send for ZeroRttAccepted",1,["iroh::endpoint::ZeroRttAccepted"]],["impl Send for EndpointMetrics",1,["iroh::metrics::EndpointMetrics"]],["impl Send for Metrics",1,["iroh::magicsock::metrics::Metrics"]],["impl Send for Addr",1,["iroh::net_report::Addr"]],["impl Send for Client",1,["iroh::net_report::Client"]],["impl Send for Metrics",1,["iroh::net_report::metrics::Metrics"]],["impl Send for Options",1,["iroh::net_report::options::imp::Options"]],["impl Send for QuicConfig",1,["iroh::net_report::reportgen::QuicConfig"]],["impl Send for RelayLatencies",1,["iroh::net_report::RelayLatencies"]],["impl Send for Report",1,["iroh::net_report::Report"]],["impl Send for Router",1,["iroh::protocol::Router"]],["impl Send for RouterBuilder",1,["iroh::protocol::RouterBuilder"]],["impl Send for CleanupDropGuard",1,["iroh::test_utils::CleanupDropGuard"]],["impl Send for DnsPkarrServer",1,["iroh::test_utils::dns_and_pkarr_servers::DnsPkarrServer"]],["impl<'a> Send for DiscoveryContext<'a>",1,["iroh::discovery::DiscoveryContext"]],["impl<'a> Send for Accept<'a>",1,["iroh::endpoint::Accept"]],["impl<P> Send for AccessLimit<P>",1,["iroh::protocol::AccessLimit"]]]],["iroh_base",[["impl Send for KeyParsingError",1,["iroh_base::key::KeyParsingError"]],["impl Send for ParseError",1,["iroh_base::ticket::ParseError"]],["impl Send for NodeAddr",1,["iroh_base::node_addr::NodeAddr"]],["impl Send for PublicKey",1,["iroh_base::key::PublicKey"]],["impl Send for RelayUrl",1,["iroh_base::relay_url::RelayUrl"]],["impl Send for RelayUrlParseError",1,["iroh_base::relay_url::RelayUrlParseError"]],["impl Send for SecretKey",1,["iroh_base::key::SecretKey"]],["impl Send for NodeTicket",1,["iroh_base::ticket::node::NodeTicket"]]]],["iroh_bench",[["impl Send for Commands",1,["iroh_bench::Commands"]],["impl Send for ConnectionSelector",1,["iroh_bench::ConnectionSelector"]],["impl Send for EndpointSelector",1,["iroh_bench::EndpointSelector"]],["impl Send for Opt",1,["iroh_bench::s2n::Opt"]],["impl Send for Stats",1,["iroh_bench::stats::Stats"]],["impl Send for StreamStats",1,["iroh_bench::stats::StreamStats"]],["impl Send for TransferResult",1,["iroh_bench::stats::TransferResult"]],["impl Send for ClientStats",1,["iroh_bench::ClientStats"]],["impl Send for Opt",1,["iroh_bench::Opt"]]]],["iroh_dns_server",[["impl Send for BootstrapOption",1,["iroh_dns_server::config::BootstrapOption"]],["impl Send for CertMode",1,["iroh_dns_server::http::tls::CertMode"]],["impl Send for RateLimitConfig",1,["iroh_dns_server::http::rate_limiting::RateLimitConfig"]],["impl Send for Config",1,["iroh_dns_server::config::Config"]],["impl Send for MainlineConfig",1,["iroh_dns_server::config::MainlineConfig"]],["impl Send for MetricsConfig",1,["iroh_dns_server::config::MetricsConfig"]],["impl Send for StoreConfig",1,["iroh_dns_server::config::StoreConfig"]],["impl Send for DnsConfig",1,["iroh_dns_server::dns::DnsConfig"]],["impl Send for DnsHandler",1,["iroh_dns_server::dns::DnsHandler"]],["impl Send for DnsServer",1,["iroh_dns_server::dns::DnsServer"]],["impl Send for Handle",1,["iroh_dns_server::dns::Handle"]],["impl Send for HttpConfig",1,["iroh_dns_server::http::HttpConfig"]],["impl Send for HttpServer",1,["iroh_dns_server::http::HttpServer"]],["impl Send for HttpsConfig",1,["iroh_dns_server::http::HttpsConfig"]],["impl Send for Metrics",1,["iroh_dns_server::metrics::Metrics"]],["impl Send for Server",1,["iroh_dns_server::server::Server"]],["impl Send for AppState",1,["iroh_dns_server::state::AppState"]],["impl Send for ZoneStore",1,["iroh_dns_server::store::ZoneStore"]]]],["iroh_relay",[["impl Send for ConnectError",1,["iroh_relay::client::ConnectError"]],["impl Send for DialError",1,["iroh_relay::client::DialError"]],["impl Send for ReceivedMessage",1,["iroh_relay::client::conn::ReceivedMessage"]],["impl Send for RecvError",1,["iroh_relay::client::conn::RecvError"]],["impl Send for SendError",1,["iroh_relay::client::conn::SendError"]],["impl Send for SendMessage",1,["iroh_relay::client::conn::SendMessage"]],["impl Send for DnsError",1,["iroh_relay::dns::DnsError"]],["impl Send for Protocol",1,["iroh_relay::http::Protocol"]],["impl Send for DecodingError",1,["iroh_relay::node_info::DecodingError"]],["impl Send for EncodingError",1,["iroh_relay::node_info::EncodingError"]],["impl Send for LookupError",1,["iroh_relay::node_info::LookupError"]],["impl Send for ParseError",1,["iroh_relay::node_info::ParseError"]],["impl Send for FrameType",1,["iroh_relay::protos::relay::FrameType"]],["impl Send for RecvError",1,["iroh_relay::protos::relay::RecvError"]],["impl Send for SendError",1,["iroh_relay::protos::relay::SendError"]],["impl Send for StunError",1,["iroh_relay::protos::stun::StunError"]],["impl Send for Error",1,["iroh_relay::quic::Error"]],["impl Send for Access",1,["iroh_relay::server::Access"]],["impl Send for AccessConfig",1,["iroh_relay::server::AccessConfig"]],["impl Send for SpawnError",1,["iroh_relay::server::SpawnError"]],["impl Send for SupervisorError",1,["iroh_relay::server::SupervisorError"]],["impl Send for Client",1,["iroh_relay::client::Client"]],["impl Send for ClientBuilder",1,["iroh_relay::client::ClientBuilder"]],["impl Send for ClientSink",1,["iroh_relay::client::ClientSink"]],["impl Send for ClientStream",1,["iroh_relay::client::ClientStream"]],["impl Send for DnsResolver",1,["iroh_relay::dns::DnsResolver"]],["impl Send for TXT",1,["iroh_relay::dns::TXT"]],["impl Send for TxtLookup",1,["iroh_relay::dns::TxtLookup"]],["impl Send for MaxLengthExceededError",1,["iroh_relay::node_info::MaxLengthExceededError"]],["impl Send for NodeData",1,["iroh_relay::node_info::NodeData"]],["impl Send for NodeInfo",1,["iroh_relay::node_info::NodeInfo"]],["impl Send for UserData",1,["iroh_relay::node_info::UserData"]],["impl Send for QuicClient",1,["iroh_relay::quic::QuicClient"]],["impl Send for ClientRateLimit",1,["iroh_relay::server::ClientRateLimit"]],["impl Send for Limits",1,["iroh_relay::server::Limits"]],["impl Send for Metrics",1,["iroh_relay::server::metrics::Metrics"]],["impl Send for QuicConfig",1,["iroh_relay::server::QuicConfig"]],["impl Send for RelayMetrics",1,["iroh_relay::server::metrics::RelayMetrics"]],["impl Send for Server",1,["iroh_relay::server::Server"]],["impl Send for StunConfig",1,["iroh_relay::server::StunConfig"]],["impl Send for StunMetrics",1,["iroh_relay::server::metrics::StunMetrics"]],["impl Send for PingTracker",1,["iroh_relay::ping_tracker::PingTracker"]],["impl Send for RelayMap",1,["iroh_relay::relay_map::RelayMap"]],["impl Send for RelayNode",1,["iroh_relay::relay_map::RelayNode"]],["impl Send for RelayQuicConfig",1,["iroh_relay::relay_map::RelayQuicConfig"]],["impl<E> Send for StaggeredError<E>
    where\n E: Send,
    ",1,["iroh_relay::dns::StaggeredError"]],["impl<EC, EA> Send for CertConfig<EC, EA>",1,["iroh_relay::server::CertConfig"]],["impl<EC, EA> Send for RelayConfig<EC, EA>",1,["iroh_relay::server::RelayConfig"]],["impl<EC, EA> Send for ServerConfig<EC, EA>",1,["iroh_relay::server::ServerConfig"]],["impl<EC, EA> Send for TlsConfig<EC, EA>",1,["iroh_relay::server::TlsConfig"]],["impl<Loader> Send for ReloadingResolver<Loader>",1,["iroh_relay::server::resolver::ReloadingResolver"]]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[23305,2460,2715,5906,16329]} \ No newline at end of file +//{"start":57,"fragment_lengths":[19397,2460,2715,5906,16547]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/marker/trait.Sync.js b/pr/3327/docs/trait.impl/core/marker/trait.Sync.js index ade2769381..0abb6a3b52 100644 --- a/pr/3327/docs/trait.impl/core/marker/trait.Sync.js +++ b/pr/3327/docs/trait.impl/core/marker/trait.Sync.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl Sync for DiscoveryError",1,["iroh::discovery::DiscoveryError"]],["impl Sync for IntoDiscoveryError",1,["iroh::discovery::IntoDiscoveryError"]],["impl Sync for PkarrError",1,["iroh::discovery::pkarr::PkarrError"]],["impl Sync for AddNodeAddrError",1,["iroh::magicsock::AddNodeAddrError"]],["impl Sync for AlpnError",1,["iroh::endpoint::AlpnError"]],["impl Sync for BindError",1,["iroh::endpoint::BindError"]],["impl Sync for ConnectError",1,["iroh::endpoint::ConnectError"]],["impl Sync for ConnectWithOptsError",1,["iroh::endpoint::ConnectWithOptsError"]],["impl Sync for ConnectionType",1,["iroh::magicsock::node_map::node_state::ConnectionType"]],["impl Sync for ControlMsg",1,["iroh::magicsock::node_map::node_state::ControlMsg"]],["impl Sync for DirectAddrType",1,["iroh::magicsock::DirectAddrType"]],["impl Sync for GetMappingAddressError",1,["iroh::endpoint::GetMappingAddressError"]],["impl Sync for PathSelection",1,["iroh::endpoint::PathSelection"]],["impl Sync for RelayMode",1,["iroh::endpoint::RelayMode"]],["impl Sync for Source",1,["iroh::magicsock::node_map::Source"]],["impl Sync for ReportError",1,["iroh::net_report::ReportError"]],["impl Sync for ProtocolError",1,["iroh::protocol::ProtocolError"]],["impl Sync for DnsDiscovery",1,["iroh::discovery::dns::DnsDiscovery"]],["impl Sync for DnsDiscoveryBuilder",1,["iroh::discovery::dns::DnsDiscoveryBuilder"]],["impl Sync for MdnsDiscovery",1,["iroh::discovery::mdns::MdnsDiscovery"]],["impl Sync for MdnsDiscoveryBuilder",1,["iroh::discovery::mdns::MdnsDiscoveryBuilder"]],["impl Sync for Builder",1,["iroh::discovery::pkarr::dht::Builder"]],["impl Sync for DhtDiscovery",1,["iroh::discovery::pkarr::dht::DhtDiscovery"]],["impl Sync for PkarrPublisher",1,["iroh::discovery::pkarr::PkarrPublisher"]],["impl Sync for PkarrPublisherBuilder",1,["iroh::discovery::pkarr::PkarrPublisherBuilder"]],["impl Sync for PkarrRelayClient",1,["iroh::discovery::pkarr::PkarrRelayClient"]],["impl Sync for PkarrResolver",1,["iroh::discovery::pkarr::PkarrResolver"]],["impl Sync for PkarrResolverBuilder",1,["iroh::discovery::pkarr::PkarrResolverBuilder"]],["impl Sync for StaticProvider",1,["iroh::discovery::static_provider::StaticProvider"]],["impl Sync for ConcurrentDiscovery",1,["iroh::discovery::ConcurrentDiscovery"]],["impl Sync for DiscoveryItem",1,["iroh::discovery::DiscoveryItem"]],["impl Sync for Lagged",1,["iroh::discovery::Lagged"]],["impl Sync for Builder",1,["iroh::endpoint::Builder"]],["impl Sync for ConnectOptions",1,["iroh::endpoint::ConnectOptions"]],["impl Sync for Connecting",1,["iroh::endpoint::Connecting"]],["impl Sync for Connection",1,["iroh::endpoint::Connection"]],["impl Sync for DirectAddr",1,["iroh::magicsock::DirectAddr"]],["impl Sync for DirectAddrInfo",1,["iroh::magicsock::node_map::node_state::DirectAddrInfo"]],["impl Sync for Endpoint",1,["iroh::endpoint::Endpoint"]],["impl Sync for Incoming",1,["iroh::endpoint::Incoming"]],["impl Sync for IncomingFuture",1,["iroh::endpoint::IncomingFuture"]],["impl Sync for RemoteInfo",1,["iroh::magicsock::node_map::node_state::RemoteInfo"]],["impl Sync for RemoteNodeIdError",1,["iroh::endpoint::RemoteNodeIdError"]],["impl Sync for ZeroRttAccepted",1,["iroh::endpoint::ZeroRttAccepted"]],["impl Sync for EndpointMetrics",1,["iroh::metrics::EndpointMetrics"]],["impl Sync for Metrics",1,["iroh::magicsock::metrics::Metrics"]],["impl Sync for Addr",1,["iroh::net_report::Addr"]],["impl Sync for Client",1,["iroh::net_report::Client"]],["impl Sync for Metrics",1,["iroh::net_report::metrics::Metrics"]],["impl Sync for Options",1,["iroh::net_report::options::imp::Options"]],["impl Sync for QuicConfig",1,["iroh::net_report::reportgen::QuicConfig"]],["impl Sync for RelayLatencies",1,["iroh::net_report::RelayLatencies"]],["impl Sync for Report",1,["iroh::net_report::Report"]],["impl Sync for Router",1,["iroh::protocol::Router"]],["impl Sync for RouterBuilder",1,["iroh::protocol::RouterBuilder"]],["impl Sync for CleanupDropGuard",1,["iroh::test_utils::CleanupDropGuard"]],["impl Sync for DnsPkarrServer",1,["iroh::test_utils::dns_and_pkarr_servers::DnsPkarrServer"]],["impl Sync for Disconnected",1,["iroh::watcher::Disconnected"]],["impl<'a> Sync for DiscoveryContext<'a>",1,["iroh::discovery::DiscoveryContext"]],["impl<'a> Sync for Accept<'a>",1,["iroh::endpoint::Accept"]],["impl<'a, T, W> Sync for InitializedFut<'a, T, W>
    where\n W: Sync,\n T: Sync,
    ",1,["iroh::watcher::InitializedFut"]],["impl<'a, W> Sync for NextFut<'a, W>
    where\n W: Sync,
    ",1,["iroh::watcher::NextFut"]],["impl<P> Sync for AccessLimit<P>",1,["iroh::protocol::AccessLimit"]],["impl<T> Sync for Direct<T>
    where\n T: Send + Sync,
    ",1,["iroh::watcher::Direct"]],["impl<T> Sync for Watchable<T>
    where\n T: Send + Sync,
    ",1,["iroh::watcher::Watchable"]],["impl<W> Sync for Stream<W>
    where\n W: Sync,\n <W as Watcher>::Value: Sync,
    ",1,["iroh::watcher::Stream"]],["impl<W, T> !Sync for Map<W, T>",1,["iroh::watcher::Map"]]]],["iroh_base",[["impl Sync for KeyParsingError",1,["iroh_base::key::KeyParsingError"]],["impl Sync for ParseError",1,["iroh_base::ticket::ParseError"]],["impl Sync for NodeAddr",1,["iroh_base::node_addr::NodeAddr"]],["impl Sync for PublicKey",1,["iroh_base::key::PublicKey"]],["impl Sync for RelayUrl",1,["iroh_base::relay_url::RelayUrl"]],["impl Sync for RelayUrlParseError",1,["iroh_base::relay_url::RelayUrlParseError"]],["impl Sync for SecretKey",1,["iroh_base::key::SecretKey"]],["impl Sync for NodeTicket",1,["iroh_base::ticket::node::NodeTicket"]]]],["iroh_bench",[["impl Sync for Commands",1,["iroh_bench::Commands"]],["impl Sync for ConnectionSelector",1,["iroh_bench::ConnectionSelector"]],["impl Sync for EndpointSelector",1,["iroh_bench::EndpointSelector"]],["impl Sync for Opt",1,["iroh_bench::s2n::Opt"]],["impl Sync for Stats",1,["iroh_bench::stats::Stats"]],["impl Sync for StreamStats",1,["iroh_bench::stats::StreamStats"]],["impl Sync for TransferResult",1,["iroh_bench::stats::TransferResult"]],["impl Sync for ClientStats",1,["iroh_bench::ClientStats"]],["impl Sync for Opt",1,["iroh_bench::Opt"]]]],["iroh_dns_server",[["impl Sync for BootstrapOption",1,["iroh_dns_server::config::BootstrapOption"]],["impl Sync for CertMode",1,["iroh_dns_server::http::tls::CertMode"]],["impl Sync for RateLimitConfig",1,["iroh_dns_server::http::rate_limiting::RateLimitConfig"]],["impl Sync for Config",1,["iroh_dns_server::config::Config"]],["impl Sync for MainlineConfig",1,["iroh_dns_server::config::MainlineConfig"]],["impl Sync for MetricsConfig",1,["iroh_dns_server::config::MetricsConfig"]],["impl Sync for StoreConfig",1,["iroh_dns_server::config::StoreConfig"]],["impl Sync for DnsConfig",1,["iroh_dns_server::dns::DnsConfig"]],["impl Sync for DnsHandler",1,["iroh_dns_server::dns::DnsHandler"]],["impl Sync for DnsServer",1,["iroh_dns_server::dns::DnsServer"]],["impl Sync for Handle",1,["iroh_dns_server::dns::Handle"]],["impl Sync for HttpConfig",1,["iroh_dns_server::http::HttpConfig"]],["impl Sync for HttpServer",1,["iroh_dns_server::http::HttpServer"]],["impl Sync for HttpsConfig",1,["iroh_dns_server::http::HttpsConfig"]],["impl Sync for Metrics",1,["iroh_dns_server::metrics::Metrics"]],["impl Sync for Server",1,["iroh_dns_server::server::Server"]],["impl Sync for AppState",1,["iroh_dns_server::state::AppState"]],["impl Sync for ZoneStore",1,["iroh_dns_server::store::ZoneStore"]]]],["iroh_relay",[["impl Sync for ConnectError",1,["iroh_relay::client::ConnectError"]],["impl Sync for DialError",1,["iroh_relay::client::DialError"]],["impl Sync for ReceivedMessage",1,["iroh_relay::client::conn::ReceivedMessage"]],["impl Sync for RecvError",1,["iroh_relay::client::conn::RecvError"]],["impl Sync for SendError",1,["iroh_relay::client::conn::SendError"]],["impl Sync for SendMessage",1,["iroh_relay::client::conn::SendMessage"]],["impl Sync for DnsError",1,["iroh_relay::dns::DnsError"]],["impl Sync for Protocol",1,["iroh_relay::http::Protocol"]],["impl Sync for DecodingError",1,["iroh_relay::node_info::DecodingError"]],["impl Sync for EncodingError",1,["iroh_relay::node_info::EncodingError"]],["impl Sync for LookupError",1,["iroh_relay::node_info::LookupError"]],["impl Sync for ParseError",1,["iroh_relay::node_info::ParseError"]],["impl Sync for FrameType",1,["iroh_relay::protos::relay::FrameType"]],["impl Sync for RecvError",1,["iroh_relay::protos::relay::RecvError"]],["impl Sync for SendError",1,["iroh_relay::protos::relay::SendError"]],["impl Sync for StunError",1,["iroh_relay::protos::stun::StunError"]],["impl Sync for Error",1,["iroh_relay::quic::Error"]],["impl Sync for Access",1,["iroh_relay::server::Access"]],["impl Sync for AccessConfig",1,["iroh_relay::server::AccessConfig"]],["impl Sync for SpawnError",1,["iroh_relay::server::SpawnError"]],["impl Sync for SupervisorError",1,["iroh_relay::server::SupervisorError"]],["impl Sync for Client",1,["iroh_relay::client::Client"]],["impl Sync for ClientBuilder",1,["iroh_relay::client::ClientBuilder"]],["impl Sync for ClientSink",1,["iroh_relay::client::ClientSink"]],["impl Sync for ClientStream",1,["iroh_relay::client::ClientStream"]],["impl Sync for DnsResolver",1,["iroh_relay::dns::DnsResolver"]],["impl Sync for Error",1,["iroh_relay::dns::staggered::Error"]],["impl Sync for TXT",1,["iroh_relay::dns::TXT"]],["impl Sync for TxtLookup",1,["iroh_relay::dns::TxtLookup"]],["impl Sync for MaxLengthExceededError",1,["iroh_relay::node_info::MaxLengthExceededError"]],["impl Sync for NodeData",1,["iroh_relay::node_info::NodeData"]],["impl Sync for NodeInfo",1,["iroh_relay::node_info::NodeInfo"]],["impl Sync for UserData",1,["iroh_relay::node_info::UserData"]],["impl Sync for QuicClient",1,["iroh_relay::quic::QuicClient"]],["impl Sync for ClientRateLimit",1,["iroh_relay::server::ClientRateLimit"]],["impl Sync for Limits",1,["iroh_relay::server::Limits"]],["impl Sync for Metrics",1,["iroh_relay::server::metrics::Metrics"]],["impl Sync for QuicConfig",1,["iroh_relay::server::QuicConfig"]],["impl Sync for RelayMetrics",1,["iroh_relay::server::metrics::RelayMetrics"]],["impl Sync for Server",1,["iroh_relay::server::Server"]],["impl Sync for StunConfig",1,["iroh_relay::server::StunConfig"]],["impl Sync for StunMetrics",1,["iroh_relay::server::metrics::StunMetrics"]],["impl Sync for PingTracker",1,["iroh_relay::ping_tracker::PingTracker"]],["impl Sync for RelayMap",1,["iroh_relay::relay_map::RelayMap"]],["impl Sync for RelayNode",1,["iroh_relay::relay_map::RelayNode"]],["impl Sync for RelayQuicConfig",1,["iroh_relay::relay_map::RelayQuicConfig"]],["impl<EC, EA = EC> !Sync for CertConfig<EC, EA>",1,["iroh_relay::server::CertConfig"]],["impl<EC, EA = EC> !Sync for RelayConfig<EC, EA>",1,["iroh_relay::server::RelayConfig"]],["impl<EC, EA = EC> !Sync for ServerConfig<EC, EA>",1,["iroh_relay::server::ServerConfig"]],["impl<EC, EA = EC> !Sync for TlsConfig<EC, EA>",1,["iroh_relay::server::TlsConfig"]],["impl<Loader> Sync for ReloadingResolver<Loader>",1,["iroh_relay::server::resolver::ReloadingResolver"]]]]]); + var implementors = Object.fromEntries([["iroh",[["impl Sync for DiscoveryError",1,["iroh::discovery::DiscoveryError"]],["impl Sync for IntoDiscoveryError",1,["iroh::discovery::IntoDiscoveryError"]],["impl Sync for PkarrError",1,["iroh::discovery::pkarr::PkarrError"]],["impl Sync for AddNodeAddrError",1,["iroh::magicsock::AddNodeAddrError"]],["impl Sync for AlpnError",1,["iroh::endpoint::AlpnError"]],["impl Sync for BindError",1,["iroh::endpoint::BindError"]],["impl Sync for ConnectError",1,["iroh::endpoint::ConnectError"]],["impl Sync for ConnectWithOptsError",1,["iroh::endpoint::ConnectWithOptsError"]],["impl Sync for ConnectionType",1,["iroh::magicsock::node_map::node_state::ConnectionType"]],["impl Sync for ControlMsg",1,["iroh::magicsock::node_map::node_state::ControlMsg"]],["impl Sync for DirectAddrType",1,["iroh::magicsock::DirectAddrType"]],["impl Sync for GetMappingAddressError",1,["iroh::endpoint::GetMappingAddressError"]],["impl Sync for PathSelection",1,["iroh::endpoint::PathSelection"]],["impl Sync for RelayMode",1,["iroh::endpoint::RelayMode"]],["impl Sync for Source",1,["iroh::magicsock::node_map::Source"]],["impl Sync for ReportError",1,["iroh::net_report::ReportError"]],["impl Sync for AcceptError",1,["iroh::protocol::AcceptError"]],["impl Sync for DnsDiscovery",1,["iroh::discovery::dns::DnsDiscovery"]],["impl Sync for DnsDiscoveryBuilder",1,["iroh::discovery::dns::DnsDiscoveryBuilder"]],["impl Sync for MdnsDiscovery",1,["iroh::discovery::mdns::MdnsDiscovery"]],["impl Sync for MdnsDiscoveryBuilder",1,["iroh::discovery::mdns::MdnsDiscoveryBuilder"]],["impl Sync for Builder",1,["iroh::discovery::pkarr::dht::Builder"]],["impl Sync for DhtDiscovery",1,["iroh::discovery::pkarr::dht::DhtDiscovery"]],["impl Sync for PkarrPublisher",1,["iroh::discovery::pkarr::PkarrPublisher"]],["impl Sync for PkarrPublisherBuilder",1,["iroh::discovery::pkarr::PkarrPublisherBuilder"]],["impl Sync for PkarrRelayClient",1,["iroh::discovery::pkarr::PkarrRelayClient"]],["impl Sync for PkarrResolver",1,["iroh::discovery::pkarr::PkarrResolver"]],["impl Sync for PkarrResolverBuilder",1,["iroh::discovery::pkarr::PkarrResolverBuilder"]],["impl Sync for StaticProvider",1,["iroh::discovery::static_provider::StaticProvider"]],["impl Sync for ConcurrentDiscovery",1,["iroh::discovery::ConcurrentDiscovery"]],["impl Sync for DiscoveryItem",1,["iroh::discovery::DiscoveryItem"]],["impl Sync for Lagged",1,["iroh::discovery::Lagged"]],["impl Sync for Builder",1,["iroh::endpoint::Builder"]],["impl Sync for ConnectOptions",1,["iroh::endpoint::ConnectOptions"]],["impl Sync for Connecting",1,["iroh::endpoint::Connecting"]],["impl Sync for Connection",1,["iroh::endpoint::Connection"]],["impl Sync for DirectAddr",1,["iroh::magicsock::DirectAddr"]],["impl Sync for DirectAddrInfo",1,["iroh::magicsock::node_map::node_state::DirectAddrInfo"]],["impl Sync for Endpoint",1,["iroh::endpoint::Endpoint"]],["impl Sync for Incoming",1,["iroh::endpoint::Incoming"]],["impl Sync for IncomingFuture",1,["iroh::endpoint::IncomingFuture"]],["impl Sync for RemoteInfo",1,["iroh::magicsock::node_map::node_state::RemoteInfo"]],["impl Sync for RemoteNodeIdError",1,["iroh::endpoint::RemoteNodeIdError"]],["impl Sync for ZeroRttAccepted",1,["iroh::endpoint::ZeroRttAccepted"]],["impl Sync for EndpointMetrics",1,["iroh::metrics::EndpointMetrics"]],["impl Sync for Metrics",1,["iroh::magicsock::metrics::Metrics"]],["impl Sync for Addr",1,["iroh::net_report::Addr"]],["impl Sync for Client",1,["iroh::net_report::Client"]],["impl Sync for Metrics",1,["iroh::net_report::metrics::Metrics"]],["impl Sync for Options",1,["iroh::net_report::options::imp::Options"]],["impl Sync for QuicConfig",1,["iroh::net_report::reportgen::QuicConfig"]],["impl Sync for RelayLatencies",1,["iroh::net_report::RelayLatencies"]],["impl Sync for Report",1,["iroh::net_report::Report"]],["impl Sync for Router",1,["iroh::protocol::Router"]],["impl Sync for RouterBuilder",1,["iroh::protocol::RouterBuilder"]],["impl Sync for CleanupDropGuard",1,["iroh::test_utils::CleanupDropGuard"]],["impl Sync for DnsPkarrServer",1,["iroh::test_utils::dns_and_pkarr_servers::DnsPkarrServer"]],["impl<'a> Sync for DiscoveryContext<'a>",1,["iroh::discovery::DiscoveryContext"]],["impl<'a> Sync for Accept<'a>",1,["iroh::endpoint::Accept"]],["impl<P> Sync for AccessLimit<P>",1,["iroh::protocol::AccessLimit"]]]],["iroh_base",[["impl Sync for KeyParsingError",1,["iroh_base::key::KeyParsingError"]],["impl Sync for ParseError",1,["iroh_base::ticket::ParseError"]],["impl Sync for NodeAddr",1,["iroh_base::node_addr::NodeAddr"]],["impl Sync for PublicKey",1,["iroh_base::key::PublicKey"]],["impl Sync for RelayUrl",1,["iroh_base::relay_url::RelayUrl"]],["impl Sync for RelayUrlParseError",1,["iroh_base::relay_url::RelayUrlParseError"]],["impl Sync for SecretKey",1,["iroh_base::key::SecretKey"]],["impl Sync for NodeTicket",1,["iroh_base::ticket::node::NodeTicket"]]]],["iroh_bench",[["impl Sync for Commands",1,["iroh_bench::Commands"]],["impl Sync for ConnectionSelector",1,["iroh_bench::ConnectionSelector"]],["impl Sync for EndpointSelector",1,["iroh_bench::EndpointSelector"]],["impl Sync for Opt",1,["iroh_bench::s2n::Opt"]],["impl Sync for Stats",1,["iroh_bench::stats::Stats"]],["impl Sync for StreamStats",1,["iroh_bench::stats::StreamStats"]],["impl Sync for TransferResult",1,["iroh_bench::stats::TransferResult"]],["impl Sync for ClientStats",1,["iroh_bench::ClientStats"]],["impl Sync for Opt",1,["iroh_bench::Opt"]]]],["iroh_dns_server",[["impl Sync for BootstrapOption",1,["iroh_dns_server::config::BootstrapOption"]],["impl Sync for CertMode",1,["iroh_dns_server::http::tls::CertMode"]],["impl Sync for RateLimitConfig",1,["iroh_dns_server::http::rate_limiting::RateLimitConfig"]],["impl Sync for Config",1,["iroh_dns_server::config::Config"]],["impl Sync for MainlineConfig",1,["iroh_dns_server::config::MainlineConfig"]],["impl Sync for MetricsConfig",1,["iroh_dns_server::config::MetricsConfig"]],["impl Sync for StoreConfig",1,["iroh_dns_server::config::StoreConfig"]],["impl Sync for DnsConfig",1,["iroh_dns_server::dns::DnsConfig"]],["impl Sync for DnsHandler",1,["iroh_dns_server::dns::DnsHandler"]],["impl Sync for DnsServer",1,["iroh_dns_server::dns::DnsServer"]],["impl Sync for Handle",1,["iroh_dns_server::dns::Handle"]],["impl Sync for HttpConfig",1,["iroh_dns_server::http::HttpConfig"]],["impl Sync for HttpServer",1,["iroh_dns_server::http::HttpServer"]],["impl Sync for HttpsConfig",1,["iroh_dns_server::http::HttpsConfig"]],["impl Sync for Metrics",1,["iroh_dns_server::metrics::Metrics"]],["impl Sync for Server",1,["iroh_dns_server::server::Server"]],["impl Sync for AppState",1,["iroh_dns_server::state::AppState"]],["impl Sync for ZoneStore",1,["iroh_dns_server::store::ZoneStore"]]]],["iroh_relay",[["impl Sync for ConnectError",1,["iroh_relay::client::ConnectError"]],["impl Sync for DialError",1,["iroh_relay::client::DialError"]],["impl Sync for ReceivedMessage",1,["iroh_relay::client::conn::ReceivedMessage"]],["impl Sync for RecvError",1,["iroh_relay::client::conn::RecvError"]],["impl Sync for SendError",1,["iroh_relay::client::conn::SendError"]],["impl Sync for SendMessage",1,["iroh_relay::client::conn::SendMessage"]],["impl Sync for DnsError",1,["iroh_relay::dns::DnsError"]],["impl Sync for Protocol",1,["iroh_relay::http::Protocol"]],["impl Sync for DecodingError",1,["iroh_relay::node_info::DecodingError"]],["impl Sync for EncodingError",1,["iroh_relay::node_info::EncodingError"]],["impl Sync for LookupError",1,["iroh_relay::node_info::LookupError"]],["impl Sync for ParseError",1,["iroh_relay::node_info::ParseError"]],["impl Sync for FrameType",1,["iroh_relay::protos::relay::FrameType"]],["impl Sync for RecvError",1,["iroh_relay::protos::relay::RecvError"]],["impl Sync for SendError",1,["iroh_relay::protos::relay::SendError"]],["impl Sync for StunError",1,["iroh_relay::protos::stun::StunError"]],["impl Sync for Error",1,["iroh_relay::quic::Error"]],["impl Sync for Access",1,["iroh_relay::server::Access"]],["impl Sync for AccessConfig",1,["iroh_relay::server::AccessConfig"]],["impl Sync for SpawnError",1,["iroh_relay::server::SpawnError"]],["impl Sync for SupervisorError",1,["iroh_relay::server::SupervisorError"]],["impl Sync for Client",1,["iroh_relay::client::Client"]],["impl Sync for ClientBuilder",1,["iroh_relay::client::ClientBuilder"]],["impl Sync for ClientSink",1,["iroh_relay::client::ClientSink"]],["impl Sync for ClientStream",1,["iroh_relay::client::ClientStream"]],["impl Sync for DnsResolver",1,["iroh_relay::dns::DnsResolver"]],["impl Sync for TXT",1,["iroh_relay::dns::TXT"]],["impl Sync for TxtLookup",1,["iroh_relay::dns::TxtLookup"]],["impl Sync for MaxLengthExceededError",1,["iroh_relay::node_info::MaxLengthExceededError"]],["impl Sync for NodeData",1,["iroh_relay::node_info::NodeData"]],["impl Sync for NodeInfo",1,["iroh_relay::node_info::NodeInfo"]],["impl Sync for UserData",1,["iroh_relay::node_info::UserData"]],["impl Sync for QuicClient",1,["iroh_relay::quic::QuicClient"]],["impl Sync for ClientRateLimit",1,["iroh_relay::server::ClientRateLimit"]],["impl Sync for Limits",1,["iroh_relay::server::Limits"]],["impl Sync for Metrics",1,["iroh_relay::server::metrics::Metrics"]],["impl Sync for QuicConfig",1,["iroh_relay::server::QuicConfig"]],["impl Sync for RelayMetrics",1,["iroh_relay::server::metrics::RelayMetrics"]],["impl Sync for Server",1,["iroh_relay::server::Server"]],["impl Sync for StunConfig",1,["iroh_relay::server::StunConfig"]],["impl Sync for StunMetrics",1,["iroh_relay::server::metrics::StunMetrics"]],["impl Sync for PingTracker",1,["iroh_relay::ping_tracker::PingTracker"]],["impl Sync for RelayMap",1,["iroh_relay::relay_map::RelayMap"]],["impl Sync for RelayNode",1,["iroh_relay::relay_map::RelayNode"]],["impl Sync for RelayQuicConfig",1,["iroh_relay::relay_map::RelayQuicConfig"]],["impl<E> Sync for StaggeredError<E>
    where\n E: Sync,
    ",1,["iroh_relay::dns::StaggeredError"]],["impl<EC, EA = EC> !Sync for CertConfig<EC, EA>",1,["iroh_relay::server::CertConfig"]],["impl<EC, EA = EC> !Sync for RelayConfig<EC, EA>",1,["iroh_relay::server::RelayConfig"]],["impl<EC, EA = EC> !Sync for ServerConfig<EC, EA>",1,["iroh_relay::server::ServerConfig"]],["impl<EC, EA = EC> !Sync for TlsConfig<EC, EA>",1,["iroh_relay::server::TlsConfig"]],["impl<Loader> Sync for ReloadingResolver<Loader>",1,["iroh_relay::server::resolver::ReloadingResolver"]]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[23305,2460,2715,5906,16353]} \ No newline at end of file +//{"start":57,"fragment_lengths":[19397,2460,2715,5906,16571]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/marker/trait.Unpin.js b/pr/3327/docs/trait.impl/core/marker/trait.Unpin.js index bb08c5c821..08497657cd 100644 --- a/pr/3327/docs/trait.impl/core/marker/trait.Unpin.js +++ b/pr/3327/docs/trait.impl/core/marker/trait.Unpin.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl Unpin for DiscoveryError",1,["iroh::discovery::DiscoveryError"]],["impl Unpin for IntoDiscoveryError",1,["iroh::discovery::IntoDiscoveryError"]],["impl Unpin for PkarrError",1,["iroh::discovery::pkarr::PkarrError"]],["impl Unpin for AddNodeAddrError",1,["iroh::magicsock::AddNodeAddrError"]],["impl Unpin for AlpnError",1,["iroh::endpoint::AlpnError"]],["impl Unpin for BindError",1,["iroh::endpoint::BindError"]],["impl Unpin for ConnectError",1,["iroh::endpoint::ConnectError"]],["impl Unpin for ConnectWithOptsError",1,["iroh::endpoint::ConnectWithOptsError"]],["impl Unpin for ConnectionType",1,["iroh::magicsock::node_map::node_state::ConnectionType"]],["impl Unpin for ControlMsg",1,["iroh::magicsock::node_map::node_state::ControlMsg"]],["impl Unpin for DirectAddrType",1,["iroh::magicsock::DirectAddrType"]],["impl Unpin for GetMappingAddressError",1,["iroh::endpoint::GetMappingAddressError"]],["impl Unpin for PathSelection",1,["iroh::endpoint::PathSelection"]],["impl Unpin for RelayMode",1,["iroh::endpoint::RelayMode"]],["impl Unpin for Source",1,["iroh::magicsock::node_map::Source"]],["impl Unpin for ReportError",1,["iroh::net_report::ReportError"]],["impl Unpin for ProtocolError",1,["iroh::protocol::ProtocolError"]],["impl Unpin for DnsDiscovery",1,["iroh::discovery::dns::DnsDiscovery"]],["impl Unpin for DnsDiscoveryBuilder",1,["iroh::discovery::dns::DnsDiscoveryBuilder"]],["impl Unpin for MdnsDiscovery",1,["iroh::discovery::mdns::MdnsDiscovery"]],["impl Unpin for MdnsDiscoveryBuilder",1,["iroh::discovery::mdns::MdnsDiscoveryBuilder"]],["impl Unpin for Builder",1,["iroh::discovery::pkarr::dht::Builder"]],["impl Unpin for DhtDiscovery",1,["iroh::discovery::pkarr::dht::DhtDiscovery"]],["impl Unpin for PkarrPublisher",1,["iroh::discovery::pkarr::PkarrPublisher"]],["impl Unpin for PkarrPublisherBuilder",1,["iroh::discovery::pkarr::PkarrPublisherBuilder"]],["impl Unpin for PkarrRelayClient",1,["iroh::discovery::pkarr::PkarrRelayClient"]],["impl Unpin for PkarrResolver",1,["iroh::discovery::pkarr::PkarrResolver"]],["impl Unpin for PkarrResolverBuilder",1,["iroh::discovery::pkarr::PkarrResolverBuilder"]],["impl Unpin for StaticProvider",1,["iroh::discovery::static_provider::StaticProvider"]],["impl Unpin for ConcurrentDiscovery",1,["iroh::discovery::ConcurrentDiscovery"]],["impl Unpin for DiscoveryItem",1,["iroh::discovery::DiscoveryItem"]],["impl Unpin for Lagged",1,["iroh::discovery::Lagged"]],["impl Unpin for Builder",1,["iroh::endpoint::Builder"]],["impl Unpin for ConnectOptions",1,["iroh::endpoint::ConnectOptions"]],["impl Unpin for Connection",1,["iroh::endpoint::Connection"]],["impl Unpin for DirectAddr",1,["iroh::magicsock::DirectAddr"]],["impl Unpin for DirectAddrInfo",1,["iroh::magicsock::node_map::node_state::DirectAddrInfo"]],["impl Unpin for Endpoint",1,["iroh::endpoint::Endpoint"]],["impl Unpin for Incoming",1,["iroh::endpoint::Incoming"]],["impl Unpin for RemoteInfo",1,["iroh::magicsock::node_map::node_state::RemoteInfo"]],["impl Unpin for RemoteNodeIdError",1,["iroh::endpoint::RemoteNodeIdError"]],["impl Unpin for ZeroRttAccepted",1,["iroh::endpoint::ZeroRttAccepted"]],["impl Unpin for EndpointMetrics",1,["iroh::metrics::EndpointMetrics"]],["impl Unpin for Metrics",1,["iroh::magicsock::metrics::Metrics"]],["impl Unpin for Addr",1,["iroh::net_report::Addr"]],["impl Unpin for Client",1,["iroh::net_report::Client"]],["impl Unpin for Metrics",1,["iroh::net_report::metrics::Metrics"]],["impl Unpin for Options",1,["iroh::net_report::options::imp::Options"]],["impl Unpin for QuicConfig",1,["iroh::net_report::reportgen::QuicConfig"]],["impl Unpin for RelayLatencies",1,["iroh::net_report::RelayLatencies"]],["impl Unpin for Report",1,["iroh::net_report::Report"]],["impl Unpin for Router",1,["iroh::protocol::Router"]],["impl Unpin for RouterBuilder",1,["iroh::protocol::RouterBuilder"]],["impl Unpin for CleanupDropGuard",1,["iroh::test_utils::CleanupDropGuard"]],["impl Unpin for DnsPkarrServer",1,["iroh::test_utils::dns_and_pkarr_servers::DnsPkarrServer"]],["impl Unpin for Disconnected",1,["iroh::watcher::Disconnected"]],["impl<'a> Unpin for DiscoveryContext<'a>",1,["iroh::discovery::DiscoveryContext"]],["impl<'a, T, W> Unpin for InitializedFut<'a, T, W>
    where\n T: Unpin,
    ",1,["iroh::watcher::InitializedFut"]],["impl<'a, W> Unpin for NextFut<'a, W>",1,["iroh::watcher::NextFut"]],["impl<'pin> Unpin for Connecting
    where\n PinnedFieldsOf<__Connecting<'pin>>: Unpin,
    "],["impl<'pin> Unpin for IncomingFuture
    where\n PinnedFieldsOf<__IncomingFuture<'pin>>: Unpin,
    "],["impl<'pin, 'a> Unpin for Accept<'a>
    where\n PinnedFieldsOf<__Accept<'pin, 'a>>: Unpin,
    "],["impl<P> Unpin for AccessLimit<P>
    where\n P: Unpin,
    ",1,["iroh::protocol::AccessLimit"]],["impl<T> Unpin for Direct<T>",1,["iroh::watcher::Direct"]],["impl<T> Unpin for Watchable<T>",1,["iroh::watcher::Watchable"]],["impl<W> Unpin for Stream<W>
    where\n <W as Watcher>::Value: Unpin,
    ",1,["iroh::watcher::Stream"]],["impl<W, T> Unpin for Map<W, T>
    where\n W: Unpin,\n T: Unpin,
    ",1,["iroh::watcher::Map"]]]],["iroh_base",[["impl Unpin for KeyParsingError",1,["iroh_base::key::KeyParsingError"]],["impl Unpin for ParseError",1,["iroh_base::ticket::ParseError"]],["impl Unpin for NodeAddr",1,["iroh_base::node_addr::NodeAddr"]],["impl Unpin for PublicKey",1,["iroh_base::key::PublicKey"]],["impl Unpin for RelayUrl",1,["iroh_base::relay_url::RelayUrl"]],["impl Unpin for RelayUrlParseError",1,["iroh_base::relay_url::RelayUrlParseError"]],["impl Unpin for SecretKey",1,["iroh_base::key::SecretKey"]],["impl Unpin for NodeTicket",1,["iroh_base::ticket::node::NodeTicket"]]]],["iroh_bench",[["impl Unpin for Commands",1,["iroh_bench::Commands"]],["impl Unpin for ConnectionSelector",1,["iroh_bench::ConnectionSelector"]],["impl Unpin for EndpointSelector",1,["iroh_bench::EndpointSelector"]],["impl Unpin for Opt",1,["iroh_bench::s2n::Opt"]],["impl Unpin for Stats",1,["iroh_bench::stats::Stats"]],["impl Unpin for StreamStats",1,["iroh_bench::stats::StreamStats"]],["impl Unpin for TransferResult",1,["iroh_bench::stats::TransferResult"]],["impl Unpin for ClientStats",1,["iroh_bench::ClientStats"]],["impl Unpin for Opt",1,["iroh_bench::Opt"]]]],["iroh_dns_server",[["impl Unpin for BootstrapOption",1,["iroh_dns_server::config::BootstrapOption"]],["impl Unpin for CertMode",1,["iroh_dns_server::http::tls::CertMode"]],["impl Unpin for RateLimitConfig",1,["iroh_dns_server::http::rate_limiting::RateLimitConfig"]],["impl Unpin for Config",1,["iroh_dns_server::config::Config"]],["impl Unpin for MainlineConfig",1,["iroh_dns_server::config::MainlineConfig"]],["impl Unpin for MetricsConfig",1,["iroh_dns_server::config::MetricsConfig"]],["impl Unpin for StoreConfig",1,["iroh_dns_server::config::StoreConfig"]],["impl Unpin for DnsConfig",1,["iroh_dns_server::dns::DnsConfig"]],["impl Unpin for DnsHandler",1,["iroh_dns_server::dns::DnsHandler"]],["impl Unpin for DnsServer",1,["iroh_dns_server::dns::DnsServer"]],["impl Unpin for Handle",1,["iroh_dns_server::dns::Handle"]],["impl Unpin for HttpConfig",1,["iroh_dns_server::http::HttpConfig"]],["impl Unpin for HttpServer",1,["iroh_dns_server::http::HttpServer"]],["impl Unpin for HttpsConfig",1,["iroh_dns_server::http::HttpsConfig"]],["impl Unpin for Metrics",1,["iroh_dns_server::metrics::Metrics"]],["impl Unpin for Server",1,["iroh_dns_server::server::Server"]],["impl Unpin for AppState",1,["iroh_dns_server::state::AppState"]],["impl Unpin for ZoneStore",1,["iroh_dns_server::store::ZoneStore"]]]],["iroh_relay",[["impl Unpin for ConnectError",1,["iroh_relay::client::ConnectError"]],["impl Unpin for DialError",1,["iroh_relay::client::DialError"]],["impl Unpin for ReceivedMessage",1,["iroh_relay::client::conn::ReceivedMessage"]],["impl Unpin for RecvError",1,["iroh_relay::client::conn::RecvError"]],["impl Unpin for SendError",1,["iroh_relay::client::conn::SendError"]],["impl Unpin for SendMessage",1,["iroh_relay::client::conn::SendMessage"]],["impl Unpin for DnsError",1,["iroh_relay::dns::DnsError"]],["impl Unpin for Protocol",1,["iroh_relay::http::Protocol"]],["impl Unpin for DecodingError",1,["iroh_relay::node_info::DecodingError"]],["impl Unpin for EncodingError",1,["iroh_relay::node_info::EncodingError"]],["impl Unpin for LookupError",1,["iroh_relay::node_info::LookupError"]],["impl Unpin for ParseError",1,["iroh_relay::node_info::ParseError"]],["impl Unpin for FrameType",1,["iroh_relay::protos::relay::FrameType"]],["impl Unpin for RecvError",1,["iroh_relay::protos::relay::RecvError"]],["impl Unpin for SendError",1,["iroh_relay::protos::relay::SendError"]],["impl Unpin for StunError",1,["iroh_relay::protos::stun::StunError"]],["impl Unpin for Error",1,["iroh_relay::quic::Error"]],["impl Unpin for Access",1,["iroh_relay::server::Access"]],["impl Unpin for AccessConfig",1,["iroh_relay::server::AccessConfig"]],["impl Unpin for SpawnError",1,["iroh_relay::server::SpawnError"]],["impl Unpin for SupervisorError",1,["iroh_relay::server::SupervisorError"]],["impl Unpin for Client",1,["iroh_relay::client::Client"]],["impl Unpin for ClientBuilder",1,["iroh_relay::client::ClientBuilder"]],["impl Unpin for ClientSink",1,["iroh_relay::client::ClientSink"]],["impl Unpin for ClientStream",1,["iroh_relay::client::ClientStream"]],["impl Unpin for DnsResolver",1,["iroh_relay::dns::DnsResolver"]],["impl Unpin for Error",1,["iroh_relay::dns::staggered::Error"]],["impl Unpin for TXT",1,["iroh_relay::dns::TXT"]],["impl Unpin for TxtLookup",1,["iroh_relay::dns::TxtLookup"]],["impl Unpin for MaxLengthExceededError",1,["iroh_relay::node_info::MaxLengthExceededError"]],["impl Unpin for NodeData",1,["iroh_relay::node_info::NodeData"]],["impl Unpin for NodeInfo",1,["iroh_relay::node_info::NodeInfo"]],["impl Unpin for UserData",1,["iroh_relay::node_info::UserData"]],["impl Unpin for QuicClient",1,["iroh_relay::quic::QuicClient"]],["impl Unpin for ClientRateLimit",1,["iroh_relay::server::ClientRateLimit"]],["impl Unpin for Limits",1,["iroh_relay::server::Limits"]],["impl Unpin for Metrics",1,["iroh_relay::server::metrics::Metrics"]],["impl Unpin for QuicConfig",1,["iroh_relay::server::QuicConfig"]],["impl Unpin for RelayMetrics",1,["iroh_relay::server::metrics::RelayMetrics"]],["impl Unpin for Server",1,["iroh_relay::server::Server"]],["impl Unpin for StunConfig",1,["iroh_relay::server::StunConfig"]],["impl Unpin for StunMetrics",1,["iroh_relay::server::metrics::StunMetrics"]],["impl Unpin for PingTracker",1,["iroh_relay::ping_tracker::PingTracker"]],["impl Unpin for RelayMap",1,["iroh_relay::relay_map::RelayMap"]],["impl Unpin for RelayNode",1,["iroh_relay::relay_map::RelayNode"]],["impl Unpin for RelayQuicConfig",1,["iroh_relay::relay_map::RelayQuicConfig"]],["impl<EC, EA> Unpin for CertConfig<EC, EA>",1,["iroh_relay::server::CertConfig"]],["impl<EC, EA> Unpin for RelayConfig<EC, EA>",1,["iroh_relay::server::RelayConfig"]],["impl<EC, EA> Unpin for ServerConfig<EC, EA>",1,["iroh_relay::server::ServerConfig"]],["impl<EC, EA> Unpin for TlsConfig<EC, EA>",1,["iroh_relay::server::TlsConfig"]],["impl<Loader> Unpin for ReloadingResolver<Loader>",1,["iroh_relay::server::resolver::ReloadingResolver"]]]]]); + var implementors = Object.fromEntries([["iroh",[["impl Unpin for DiscoveryError",1,["iroh::discovery::DiscoveryError"]],["impl Unpin for IntoDiscoveryError",1,["iroh::discovery::IntoDiscoveryError"]],["impl Unpin for PkarrError",1,["iroh::discovery::pkarr::PkarrError"]],["impl Unpin for AddNodeAddrError",1,["iroh::magicsock::AddNodeAddrError"]],["impl Unpin for AlpnError",1,["iroh::endpoint::AlpnError"]],["impl Unpin for BindError",1,["iroh::endpoint::BindError"]],["impl Unpin for ConnectError",1,["iroh::endpoint::ConnectError"]],["impl Unpin for ConnectWithOptsError",1,["iroh::endpoint::ConnectWithOptsError"]],["impl Unpin for ConnectionType",1,["iroh::magicsock::node_map::node_state::ConnectionType"]],["impl Unpin for ControlMsg",1,["iroh::magicsock::node_map::node_state::ControlMsg"]],["impl Unpin for DirectAddrType",1,["iroh::magicsock::DirectAddrType"]],["impl Unpin for GetMappingAddressError",1,["iroh::endpoint::GetMappingAddressError"]],["impl Unpin for PathSelection",1,["iroh::endpoint::PathSelection"]],["impl Unpin for RelayMode",1,["iroh::endpoint::RelayMode"]],["impl Unpin for Source",1,["iroh::magicsock::node_map::Source"]],["impl Unpin for ReportError",1,["iroh::net_report::ReportError"]],["impl Unpin for AcceptError",1,["iroh::protocol::AcceptError"]],["impl Unpin for DnsDiscovery",1,["iroh::discovery::dns::DnsDiscovery"]],["impl Unpin for DnsDiscoveryBuilder",1,["iroh::discovery::dns::DnsDiscoveryBuilder"]],["impl Unpin for MdnsDiscovery",1,["iroh::discovery::mdns::MdnsDiscovery"]],["impl Unpin for MdnsDiscoveryBuilder",1,["iroh::discovery::mdns::MdnsDiscoveryBuilder"]],["impl Unpin for Builder",1,["iroh::discovery::pkarr::dht::Builder"]],["impl Unpin for DhtDiscovery",1,["iroh::discovery::pkarr::dht::DhtDiscovery"]],["impl Unpin for PkarrPublisher",1,["iroh::discovery::pkarr::PkarrPublisher"]],["impl Unpin for PkarrPublisherBuilder",1,["iroh::discovery::pkarr::PkarrPublisherBuilder"]],["impl Unpin for PkarrRelayClient",1,["iroh::discovery::pkarr::PkarrRelayClient"]],["impl Unpin for PkarrResolver",1,["iroh::discovery::pkarr::PkarrResolver"]],["impl Unpin for PkarrResolverBuilder",1,["iroh::discovery::pkarr::PkarrResolverBuilder"]],["impl Unpin for StaticProvider",1,["iroh::discovery::static_provider::StaticProvider"]],["impl Unpin for ConcurrentDiscovery",1,["iroh::discovery::ConcurrentDiscovery"]],["impl Unpin for DiscoveryItem",1,["iroh::discovery::DiscoveryItem"]],["impl Unpin for Lagged",1,["iroh::discovery::Lagged"]],["impl Unpin for Builder",1,["iroh::endpoint::Builder"]],["impl Unpin for ConnectOptions",1,["iroh::endpoint::ConnectOptions"]],["impl Unpin for Connection",1,["iroh::endpoint::Connection"]],["impl Unpin for DirectAddr",1,["iroh::magicsock::DirectAddr"]],["impl Unpin for DirectAddrInfo",1,["iroh::magicsock::node_map::node_state::DirectAddrInfo"]],["impl Unpin for Endpoint",1,["iroh::endpoint::Endpoint"]],["impl Unpin for Incoming",1,["iroh::endpoint::Incoming"]],["impl Unpin for RemoteInfo",1,["iroh::magicsock::node_map::node_state::RemoteInfo"]],["impl Unpin for RemoteNodeIdError",1,["iroh::endpoint::RemoteNodeIdError"]],["impl Unpin for ZeroRttAccepted",1,["iroh::endpoint::ZeroRttAccepted"]],["impl Unpin for EndpointMetrics",1,["iroh::metrics::EndpointMetrics"]],["impl Unpin for Metrics",1,["iroh::magicsock::metrics::Metrics"]],["impl Unpin for Addr",1,["iroh::net_report::Addr"]],["impl Unpin for Client",1,["iroh::net_report::Client"]],["impl Unpin for Metrics",1,["iroh::net_report::metrics::Metrics"]],["impl Unpin for Options",1,["iroh::net_report::options::imp::Options"]],["impl Unpin for QuicConfig",1,["iroh::net_report::reportgen::QuicConfig"]],["impl Unpin for RelayLatencies",1,["iroh::net_report::RelayLatencies"]],["impl Unpin for Report",1,["iroh::net_report::Report"]],["impl Unpin for Router",1,["iroh::protocol::Router"]],["impl Unpin for RouterBuilder",1,["iroh::protocol::RouterBuilder"]],["impl Unpin for CleanupDropGuard",1,["iroh::test_utils::CleanupDropGuard"]],["impl Unpin for DnsPkarrServer",1,["iroh::test_utils::dns_and_pkarr_servers::DnsPkarrServer"]],["impl<'a> Unpin for DiscoveryContext<'a>",1,["iroh::discovery::DiscoveryContext"]],["impl<'pin> Unpin for Connecting
    where\n PinnedFieldsOf<__Connecting<'pin>>: Unpin,
    "],["impl<'pin> Unpin for IncomingFuture
    where\n PinnedFieldsOf<__IncomingFuture<'pin>>: Unpin,
    "],["impl<'pin, 'a> Unpin for Accept<'a>
    where\n PinnedFieldsOf<__Accept<'pin, 'a>>: Unpin,
    "],["impl<P> Unpin for AccessLimit<P>
    where\n P: Unpin,
    ",1,["iroh::protocol::AccessLimit"]]]],["iroh_base",[["impl Unpin for KeyParsingError",1,["iroh_base::key::KeyParsingError"]],["impl Unpin for ParseError",1,["iroh_base::ticket::ParseError"]],["impl Unpin for NodeAddr",1,["iroh_base::node_addr::NodeAddr"]],["impl Unpin for PublicKey",1,["iroh_base::key::PublicKey"]],["impl Unpin for RelayUrl",1,["iroh_base::relay_url::RelayUrl"]],["impl Unpin for RelayUrlParseError",1,["iroh_base::relay_url::RelayUrlParseError"]],["impl Unpin for SecretKey",1,["iroh_base::key::SecretKey"]],["impl Unpin for NodeTicket",1,["iroh_base::ticket::node::NodeTicket"]]]],["iroh_bench",[["impl Unpin for Commands",1,["iroh_bench::Commands"]],["impl Unpin for ConnectionSelector",1,["iroh_bench::ConnectionSelector"]],["impl Unpin for EndpointSelector",1,["iroh_bench::EndpointSelector"]],["impl Unpin for Opt",1,["iroh_bench::s2n::Opt"]],["impl Unpin for Stats",1,["iroh_bench::stats::Stats"]],["impl Unpin for StreamStats",1,["iroh_bench::stats::StreamStats"]],["impl Unpin for TransferResult",1,["iroh_bench::stats::TransferResult"]],["impl Unpin for ClientStats",1,["iroh_bench::ClientStats"]],["impl Unpin for Opt",1,["iroh_bench::Opt"]]]],["iroh_dns_server",[["impl Unpin for BootstrapOption",1,["iroh_dns_server::config::BootstrapOption"]],["impl Unpin for CertMode",1,["iroh_dns_server::http::tls::CertMode"]],["impl Unpin for RateLimitConfig",1,["iroh_dns_server::http::rate_limiting::RateLimitConfig"]],["impl Unpin for Config",1,["iroh_dns_server::config::Config"]],["impl Unpin for MainlineConfig",1,["iroh_dns_server::config::MainlineConfig"]],["impl Unpin for MetricsConfig",1,["iroh_dns_server::config::MetricsConfig"]],["impl Unpin for StoreConfig",1,["iroh_dns_server::config::StoreConfig"]],["impl Unpin for DnsConfig",1,["iroh_dns_server::dns::DnsConfig"]],["impl Unpin for DnsHandler",1,["iroh_dns_server::dns::DnsHandler"]],["impl Unpin for DnsServer",1,["iroh_dns_server::dns::DnsServer"]],["impl Unpin for Handle",1,["iroh_dns_server::dns::Handle"]],["impl Unpin for HttpConfig",1,["iroh_dns_server::http::HttpConfig"]],["impl Unpin for HttpServer",1,["iroh_dns_server::http::HttpServer"]],["impl Unpin for HttpsConfig",1,["iroh_dns_server::http::HttpsConfig"]],["impl Unpin for Metrics",1,["iroh_dns_server::metrics::Metrics"]],["impl Unpin for Server",1,["iroh_dns_server::server::Server"]],["impl Unpin for AppState",1,["iroh_dns_server::state::AppState"]],["impl Unpin for ZoneStore",1,["iroh_dns_server::store::ZoneStore"]]]],["iroh_relay",[["impl Unpin for ConnectError",1,["iroh_relay::client::ConnectError"]],["impl Unpin for DialError",1,["iroh_relay::client::DialError"]],["impl Unpin for ReceivedMessage",1,["iroh_relay::client::conn::ReceivedMessage"]],["impl Unpin for RecvError",1,["iroh_relay::client::conn::RecvError"]],["impl Unpin for SendError",1,["iroh_relay::client::conn::SendError"]],["impl Unpin for SendMessage",1,["iroh_relay::client::conn::SendMessage"]],["impl Unpin for DnsError",1,["iroh_relay::dns::DnsError"]],["impl Unpin for Protocol",1,["iroh_relay::http::Protocol"]],["impl Unpin for DecodingError",1,["iroh_relay::node_info::DecodingError"]],["impl Unpin for EncodingError",1,["iroh_relay::node_info::EncodingError"]],["impl Unpin for LookupError",1,["iroh_relay::node_info::LookupError"]],["impl Unpin for ParseError",1,["iroh_relay::node_info::ParseError"]],["impl Unpin for FrameType",1,["iroh_relay::protos::relay::FrameType"]],["impl Unpin for RecvError",1,["iroh_relay::protos::relay::RecvError"]],["impl Unpin for SendError",1,["iroh_relay::protos::relay::SendError"]],["impl Unpin for StunError",1,["iroh_relay::protos::stun::StunError"]],["impl Unpin for Error",1,["iroh_relay::quic::Error"]],["impl Unpin for Access",1,["iroh_relay::server::Access"]],["impl Unpin for AccessConfig",1,["iroh_relay::server::AccessConfig"]],["impl Unpin for SpawnError",1,["iroh_relay::server::SpawnError"]],["impl Unpin for SupervisorError",1,["iroh_relay::server::SupervisorError"]],["impl Unpin for Client",1,["iroh_relay::client::Client"]],["impl Unpin for ClientBuilder",1,["iroh_relay::client::ClientBuilder"]],["impl Unpin for ClientSink",1,["iroh_relay::client::ClientSink"]],["impl Unpin for ClientStream",1,["iroh_relay::client::ClientStream"]],["impl Unpin for DnsResolver",1,["iroh_relay::dns::DnsResolver"]],["impl Unpin for TXT",1,["iroh_relay::dns::TXT"]],["impl Unpin for TxtLookup",1,["iroh_relay::dns::TxtLookup"]],["impl Unpin for MaxLengthExceededError",1,["iroh_relay::node_info::MaxLengthExceededError"]],["impl Unpin for NodeData",1,["iroh_relay::node_info::NodeData"]],["impl Unpin for NodeInfo",1,["iroh_relay::node_info::NodeInfo"]],["impl Unpin for UserData",1,["iroh_relay::node_info::UserData"]],["impl Unpin for QuicClient",1,["iroh_relay::quic::QuicClient"]],["impl Unpin for ClientRateLimit",1,["iroh_relay::server::ClientRateLimit"]],["impl Unpin for Limits",1,["iroh_relay::server::Limits"]],["impl Unpin for Metrics",1,["iroh_relay::server::metrics::Metrics"]],["impl Unpin for QuicConfig",1,["iroh_relay::server::QuicConfig"]],["impl Unpin for RelayMetrics",1,["iroh_relay::server::metrics::RelayMetrics"]],["impl Unpin for Server",1,["iroh_relay::server::Server"]],["impl Unpin for StunConfig",1,["iroh_relay::server::StunConfig"]],["impl Unpin for StunMetrics",1,["iroh_relay::server::metrics::StunMetrics"]],["impl Unpin for PingTracker",1,["iroh_relay::ping_tracker::PingTracker"]],["impl Unpin for RelayMap",1,["iroh_relay::relay_map::RelayMap"]],["impl Unpin for RelayNode",1,["iroh_relay::relay_map::RelayNode"]],["impl Unpin for RelayQuicConfig",1,["iroh_relay::relay_map::RelayQuicConfig"]],["impl<E> Unpin for StaggeredError<E>
    where\n E: Unpin,
    ",1,["iroh_relay::dns::StaggeredError"]],["impl<EC, EA> Unpin for CertConfig<EC, EA>",1,["iroh_relay::server::CertConfig"]],["impl<EC, EA> Unpin for RelayConfig<EC, EA>",1,["iroh_relay::server::RelayConfig"]],["impl<EC, EA> Unpin for ServerConfig<EC, EA>",1,["iroh_relay::server::ServerConfig"]],["impl<EC, EA> Unpin for TlsConfig<EC, EA>",1,["iroh_relay::server::TlsConfig"]],["impl<Loader> Unpin for ReloadingResolver<Loader>",1,["iroh_relay::server::resolver::ReloadingResolver"]]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[23534,2484,2742,5960,16482]} \ No newline at end of file +//{"start":57,"fragment_lengths":[20359,2484,2742,5960,16703]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js b/pr/3327/docs/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js index ad6319ab74..03b1dab02c 100644 --- a/pr/3327/docs/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js +++ b/pr/3327/docs/trait.impl/core/panic/unwind_safe/trait.RefUnwindSafe.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl !RefUnwindSafe for DiscoveryError",1,["iroh::discovery::DiscoveryError"]],["impl !RefUnwindSafe for IntoDiscoveryError",1,["iroh::discovery::IntoDiscoveryError"]],["impl !RefUnwindSafe for PkarrError",1,["iroh::discovery::pkarr::PkarrError"]],["impl !RefUnwindSafe for AddNodeAddrError",1,["iroh::magicsock::AddNodeAddrError"]],["impl !RefUnwindSafe for AlpnError",1,["iroh::endpoint::AlpnError"]],["impl !RefUnwindSafe for BindError",1,["iroh::endpoint::BindError"]],["impl !RefUnwindSafe for ConnectError",1,["iroh::endpoint::ConnectError"]],["impl !RefUnwindSafe for ConnectWithOptsError",1,["iroh::endpoint::ConnectWithOptsError"]],["impl !RefUnwindSafe for GetMappingAddressError",1,["iroh::endpoint::GetMappingAddressError"]],["impl !RefUnwindSafe for ReportError",1,["iroh::net_report::ReportError"]],["impl !RefUnwindSafe for ProtocolError",1,["iroh::protocol::ProtocolError"]],["impl !RefUnwindSafe for DnsDiscovery",1,["iroh::discovery::dns::DnsDiscovery"]],["impl !RefUnwindSafe for DnsDiscoveryBuilder",1,["iroh::discovery::dns::DnsDiscoveryBuilder"]],["impl !RefUnwindSafe for Builder",1,["iroh::discovery::pkarr::dht::Builder"]],["impl !RefUnwindSafe for DhtDiscovery",1,["iroh::discovery::pkarr::dht::DhtDiscovery"]],["impl !RefUnwindSafe for PkarrPublisherBuilder",1,["iroh::discovery::pkarr::PkarrPublisherBuilder"]],["impl !RefUnwindSafe for PkarrRelayClient",1,["iroh::discovery::pkarr::PkarrRelayClient"]],["impl !RefUnwindSafe for PkarrResolver",1,["iroh::discovery::pkarr::PkarrResolver"]],["impl !RefUnwindSafe for PkarrResolverBuilder",1,["iroh::discovery::pkarr::PkarrResolverBuilder"]],["impl !RefUnwindSafe for ConcurrentDiscovery",1,["iroh::discovery::ConcurrentDiscovery"]],["impl !RefUnwindSafe for Builder",1,["iroh::endpoint::Builder"]],["impl !RefUnwindSafe for ConnectOptions",1,["iroh::endpoint::ConnectOptions"]],["impl !RefUnwindSafe for Connecting",1,["iroh::endpoint::Connecting"]],["impl !RefUnwindSafe for Endpoint",1,["iroh::endpoint::Endpoint"]],["impl !RefUnwindSafe for Incoming",1,["iroh::endpoint::Incoming"]],["impl !RefUnwindSafe for IncomingFuture",1,["iroh::endpoint::IncomingFuture"]],["impl !RefUnwindSafe for ZeroRttAccepted",1,["iroh::endpoint::ZeroRttAccepted"]],["impl !RefUnwindSafe for Options",1,["iroh::net_report::options::imp::Options"]],["impl !RefUnwindSafe for QuicConfig",1,["iroh::net_report::reportgen::QuicConfig"]],["impl !RefUnwindSafe for Router",1,["iroh::protocol::Router"]],["impl !RefUnwindSafe for RouterBuilder",1,["iroh::protocol::RouterBuilder"]],["impl !RefUnwindSafe for CleanupDropGuard",1,["iroh::test_utils::CleanupDropGuard"]],["impl !RefUnwindSafe for DnsPkarrServer",1,["iroh::test_utils::dns_and_pkarr_servers::DnsPkarrServer"]],["impl !RefUnwindSafe for Disconnected",1,["iroh::watcher::Disconnected"]],["impl RefUnwindSafe for ConnectionType",1,["iroh::magicsock::node_map::node_state::ConnectionType"]],["impl RefUnwindSafe for ControlMsg",1,["iroh::magicsock::node_map::node_state::ControlMsg"]],["impl RefUnwindSafe for DirectAddrType",1,["iroh::magicsock::DirectAddrType"]],["impl RefUnwindSafe for PathSelection",1,["iroh::endpoint::PathSelection"]],["impl RefUnwindSafe for RelayMode",1,["iroh::endpoint::RelayMode"]],["impl RefUnwindSafe for Source",1,["iroh::magicsock::node_map::Source"]],["impl RefUnwindSafe for MdnsDiscovery",1,["iroh::discovery::mdns::MdnsDiscovery"]],["impl RefUnwindSafe for MdnsDiscoveryBuilder",1,["iroh::discovery::mdns::MdnsDiscoveryBuilder"]],["impl RefUnwindSafe for PkarrPublisher",1,["iroh::discovery::pkarr::PkarrPublisher"]],["impl RefUnwindSafe for StaticProvider",1,["iroh::discovery::static_provider::StaticProvider"]],["impl RefUnwindSafe for DiscoveryItem",1,["iroh::discovery::DiscoveryItem"]],["impl RefUnwindSafe for Lagged",1,["iroh::discovery::Lagged"]],["impl RefUnwindSafe for Connection",1,["iroh::endpoint::Connection"]],["impl RefUnwindSafe for DirectAddr",1,["iroh::magicsock::DirectAddr"]],["impl RefUnwindSafe for DirectAddrInfo",1,["iroh::magicsock::node_map::node_state::DirectAddrInfo"]],["impl RefUnwindSafe for RemoteInfo",1,["iroh::magicsock::node_map::node_state::RemoteInfo"]],["impl RefUnwindSafe for RemoteNodeIdError",1,["iroh::endpoint::RemoteNodeIdError"]],["impl RefUnwindSafe for EndpointMetrics",1,["iroh::metrics::EndpointMetrics"]],["impl RefUnwindSafe for Metrics",1,["iroh::magicsock::metrics::Metrics"]],["impl RefUnwindSafe for Addr",1,["iroh::net_report::Addr"]],["impl RefUnwindSafe for Client",1,["iroh::net_report::Client"]],["impl RefUnwindSafe for Metrics",1,["iroh::net_report::metrics::Metrics"]],["impl RefUnwindSafe for RelayLatencies",1,["iroh::net_report::RelayLatencies"]],["impl RefUnwindSafe for Report",1,["iroh::net_report::Report"]],["impl<'a> !RefUnwindSafe for DiscoveryContext<'a>",1,["iroh::discovery::DiscoveryContext"]],["impl<'a> !RefUnwindSafe for Accept<'a>",1,["iroh::endpoint::Accept"]],["impl<'a, T, W> !RefUnwindSafe for InitializedFut<'a, T, W>",1,["iroh::watcher::InitializedFut"]],["impl<'a, W> RefUnwindSafe for NextFut<'a, W>
    where\n W: RefUnwindSafe,
    ",1,["iroh::watcher::NextFut"]],["impl<P> !RefUnwindSafe for AccessLimit<P>",1,["iroh::protocol::AccessLimit"]],["impl<T> RefUnwindSafe for Direct<T>",1,["iroh::watcher::Direct"]],["impl<T> RefUnwindSafe for Watchable<T>",1,["iroh::watcher::Watchable"]],["impl<W> RefUnwindSafe for Stream<W>
    where\n W: RefUnwindSafe,\n <W as Watcher>::Value: RefUnwindSafe,
    ",1,["iroh::watcher::Stream"]],["impl<W, T> !RefUnwindSafe for Map<W, T>",1,["iroh::watcher::Map"]]]],["iroh_base",[["impl !RefUnwindSafe for KeyParsingError",1,["iroh_base::key::KeyParsingError"]],["impl !RefUnwindSafe for ParseError",1,["iroh_base::ticket::ParseError"]],["impl RefUnwindSafe for NodeAddr",1,["iroh_base::node_addr::NodeAddr"]],["impl RefUnwindSafe for PublicKey",1,["iroh_base::key::PublicKey"]],["impl RefUnwindSafe for RelayUrl",1,["iroh_base::relay_url::RelayUrl"]],["impl RefUnwindSafe for RelayUrlParseError",1,["iroh_base::relay_url::RelayUrlParseError"]],["impl RefUnwindSafe for SecretKey",1,["iroh_base::key::SecretKey"]],["impl RefUnwindSafe for NodeTicket",1,["iroh_base::ticket::node::NodeTicket"]]]],["iroh_bench",[["impl !RefUnwindSafe for EndpointSelector",1,["iroh_bench::EndpointSelector"]],["impl RefUnwindSafe for Commands",1,["iroh_bench::Commands"]],["impl RefUnwindSafe for ConnectionSelector",1,["iroh_bench::ConnectionSelector"]],["impl RefUnwindSafe for Opt",1,["iroh_bench::s2n::Opt"]],["impl RefUnwindSafe for Stats",1,["iroh_bench::stats::Stats"]],["impl RefUnwindSafe for StreamStats",1,["iroh_bench::stats::StreamStats"]],["impl RefUnwindSafe for TransferResult",1,["iroh_bench::stats::TransferResult"]],["impl RefUnwindSafe for ClientStats",1,["iroh_bench::ClientStats"]],["impl RefUnwindSafe for Opt",1,["iroh_bench::Opt"]]]],["iroh_dns_server",[["impl !RefUnwindSafe for DnsHandler",1,["iroh_dns_server::dns::DnsHandler"]],["impl !RefUnwindSafe for DnsServer",1,["iroh_dns_server::dns::DnsServer"]],["impl !RefUnwindSafe for Handle",1,["iroh_dns_server::dns::Handle"]],["impl !RefUnwindSafe for HttpServer",1,["iroh_dns_server::http::HttpServer"]],["impl !RefUnwindSafe for Server",1,["iroh_dns_server::server::Server"]],["impl !RefUnwindSafe for AppState",1,["iroh_dns_server::state::AppState"]],["impl !RefUnwindSafe for ZoneStore",1,["iroh_dns_server::store::ZoneStore"]],["impl RefUnwindSafe for BootstrapOption",1,["iroh_dns_server::config::BootstrapOption"]],["impl RefUnwindSafe for CertMode",1,["iroh_dns_server::http::tls::CertMode"]],["impl RefUnwindSafe for RateLimitConfig",1,["iroh_dns_server::http::rate_limiting::RateLimitConfig"]],["impl RefUnwindSafe for Config",1,["iroh_dns_server::config::Config"]],["impl RefUnwindSafe for MainlineConfig",1,["iroh_dns_server::config::MainlineConfig"]],["impl RefUnwindSafe for MetricsConfig",1,["iroh_dns_server::config::MetricsConfig"]],["impl RefUnwindSafe for StoreConfig",1,["iroh_dns_server::config::StoreConfig"]],["impl RefUnwindSafe for DnsConfig",1,["iroh_dns_server::dns::DnsConfig"]],["impl RefUnwindSafe for HttpConfig",1,["iroh_dns_server::http::HttpConfig"]],["impl RefUnwindSafe for HttpsConfig",1,["iroh_dns_server::http::HttpsConfig"]],["impl RefUnwindSafe for Metrics",1,["iroh_dns_server::metrics::Metrics"]]]],["iroh_relay",[["impl !RefUnwindSafe for ConnectError",1,["iroh_relay::client::ConnectError"]],["impl !RefUnwindSafe for DialError",1,["iroh_relay::client::DialError"]],["impl !RefUnwindSafe for RecvError",1,["iroh_relay::client::conn::RecvError"]],["impl !RefUnwindSafe for SendError",1,["iroh_relay::client::conn::SendError"]],["impl !RefUnwindSafe for DnsError",1,["iroh_relay::dns::DnsError"]],["impl !RefUnwindSafe for DecodingError",1,["iroh_relay::node_info::DecodingError"]],["impl !RefUnwindSafe for EncodingError",1,["iroh_relay::node_info::EncodingError"]],["impl !RefUnwindSafe for LookupError",1,["iroh_relay::node_info::LookupError"]],["impl !RefUnwindSafe for ParseError",1,["iroh_relay::node_info::ParseError"]],["impl !RefUnwindSafe for RecvError",1,["iroh_relay::protos::relay::RecvError"]],["impl !RefUnwindSafe for SendError",1,["iroh_relay::protos::relay::SendError"]],["impl !RefUnwindSafe for StunError",1,["iroh_relay::protos::stun::StunError"]],["impl !RefUnwindSafe for Error",1,["iroh_relay::quic::Error"]],["impl !RefUnwindSafe for AccessConfig",1,["iroh_relay::server::AccessConfig"]],["impl !RefUnwindSafe for SpawnError",1,["iroh_relay::server::SpawnError"]],["impl !RefUnwindSafe for SupervisorError",1,["iroh_relay::server::SupervisorError"]],["impl !RefUnwindSafe for Client",1,["iroh_relay::client::Client"]],["impl !RefUnwindSafe for ClientBuilder",1,["iroh_relay::client::ClientBuilder"]],["impl !RefUnwindSafe for ClientSink",1,["iroh_relay::client::ClientSink"]],["impl !RefUnwindSafe for ClientStream",1,["iroh_relay::client::ClientStream"]],["impl !RefUnwindSafe for DnsResolver",1,["iroh_relay::dns::DnsResolver"]],["impl !RefUnwindSafe for Error",1,["iroh_relay::dns::staggered::Error"]],["impl !RefUnwindSafe for MaxLengthExceededError",1,["iroh_relay::node_info::MaxLengthExceededError"]],["impl !RefUnwindSafe for QuicClient",1,["iroh_relay::quic::QuicClient"]],["impl !RefUnwindSafe for QuicConfig",1,["iroh_relay::server::QuicConfig"]],["impl RefUnwindSafe for ReceivedMessage",1,["iroh_relay::client::conn::ReceivedMessage"]],["impl RefUnwindSafe for SendMessage",1,["iroh_relay::client::conn::SendMessage"]],["impl RefUnwindSafe for Protocol",1,["iroh_relay::http::Protocol"]],["impl RefUnwindSafe for FrameType",1,["iroh_relay::protos::relay::FrameType"]],["impl RefUnwindSafe for Access",1,["iroh_relay::server::Access"]],["impl RefUnwindSafe for TXT",1,["iroh_relay::dns::TXT"]],["impl RefUnwindSafe for TxtLookup",1,["iroh_relay::dns::TxtLookup"]],["impl RefUnwindSafe for NodeData",1,["iroh_relay::node_info::NodeData"]],["impl RefUnwindSafe for NodeInfo",1,["iroh_relay::node_info::NodeInfo"]],["impl RefUnwindSafe for UserData",1,["iroh_relay::node_info::UserData"]],["impl RefUnwindSafe for ClientRateLimit",1,["iroh_relay::server::ClientRateLimit"]],["impl RefUnwindSafe for Limits",1,["iroh_relay::server::Limits"]],["impl RefUnwindSafe for Metrics",1,["iroh_relay::server::metrics::Metrics"]],["impl RefUnwindSafe for RelayMetrics",1,["iroh_relay::server::metrics::RelayMetrics"]],["impl RefUnwindSafe for Server",1,["iroh_relay::server::Server"]],["impl RefUnwindSafe for StunConfig",1,["iroh_relay::server::StunConfig"]],["impl RefUnwindSafe for StunMetrics",1,["iroh_relay::server::metrics::StunMetrics"]],["impl RefUnwindSafe for PingTracker",1,["iroh_relay::ping_tracker::PingTracker"]],["impl RefUnwindSafe for RelayMap",1,["iroh_relay::relay_map::RelayMap"]],["impl RefUnwindSafe for RelayNode",1,["iroh_relay::relay_map::RelayNode"]],["impl RefUnwindSafe for RelayQuicConfig",1,["iroh_relay::relay_map::RelayQuicConfig"]],["impl<EC, EA = EC> !RefUnwindSafe for CertConfig<EC, EA>",1,["iroh_relay::server::CertConfig"]],["impl<EC, EA = EC> !RefUnwindSafe for RelayConfig<EC, EA>",1,["iroh_relay::server::RelayConfig"]],["impl<EC, EA = EC> !RefUnwindSafe for ServerConfig<EC, EA>",1,["iroh_relay::server::ServerConfig"]],["impl<EC, EA = EC> !RefUnwindSafe for TlsConfig<EC, EA>",1,["iroh_relay::server::TlsConfig"]],["impl<Loader> !RefUnwindSafe for ReloadingResolver<Loader>",1,["iroh_relay::server::resolver::ReloadingResolver"]]]]]); + var implementors = Object.fromEntries([["iroh",[["impl !RefUnwindSafe for DiscoveryError",1,["iroh::discovery::DiscoveryError"]],["impl !RefUnwindSafe for IntoDiscoveryError",1,["iroh::discovery::IntoDiscoveryError"]],["impl !RefUnwindSafe for PkarrError",1,["iroh::discovery::pkarr::PkarrError"]],["impl !RefUnwindSafe for AddNodeAddrError",1,["iroh::magicsock::AddNodeAddrError"]],["impl !RefUnwindSafe for AlpnError",1,["iroh::endpoint::AlpnError"]],["impl !RefUnwindSafe for BindError",1,["iroh::endpoint::BindError"]],["impl !RefUnwindSafe for ConnectError",1,["iroh::endpoint::ConnectError"]],["impl !RefUnwindSafe for ConnectWithOptsError",1,["iroh::endpoint::ConnectWithOptsError"]],["impl !RefUnwindSafe for GetMappingAddressError",1,["iroh::endpoint::GetMappingAddressError"]],["impl !RefUnwindSafe for ReportError",1,["iroh::net_report::ReportError"]],["impl !RefUnwindSafe for AcceptError",1,["iroh::protocol::AcceptError"]],["impl !RefUnwindSafe for DnsDiscovery",1,["iroh::discovery::dns::DnsDiscovery"]],["impl !RefUnwindSafe for DnsDiscoveryBuilder",1,["iroh::discovery::dns::DnsDiscoveryBuilder"]],["impl !RefUnwindSafe for Builder",1,["iroh::discovery::pkarr::dht::Builder"]],["impl !RefUnwindSafe for DhtDiscovery",1,["iroh::discovery::pkarr::dht::DhtDiscovery"]],["impl !RefUnwindSafe for PkarrPublisherBuilder",1,["iroh::discovery::pkarr::PkarrPublisherBuilder"]],["impl !RefUnwindSafe for PkarrRelayClient",1,["iroh::discovery::pkarr::PkarrRelayClient"]],["impl !RefUnwindSafe for PkarrResolver",1,["iroh::discovery::pkarr::PkarrResolver"]],["impl !RefUnwindSafe for PkarrResolverBuilder",1,["iroh::discovery::pkarr::PkarrResolverBuilder"]],["impl !RefUnwindSafe for ConcurrentDiscovery",1,["iroh::discovery::ConcurrentDiscovery"]],["impl !RefUnwindSafe for Builder",1,["iroh::endpoint::Builder"]],["impl !RefUnwindSafe for ConnectOptions",1,["iroh::endpoint::ConnectOptions"]],["impl !RefUnwindSafe for Connecting",1,["iroh::endpoint::Connecting"]],["impl !RefUnwindSafe for Endpoint",1,["iroh::endpoint::Endpoint"]],["impl !RefUnwindSafe for Incoming",1,["iroh::endpoint::Incoming"]],["impl !RefUnwindSafe for IncomingFuture",1,["iroh::endpoint::IncomingFuture"]],["impl !RefUnwindSafe for ZeroRttAccepted",1,["iroh::endpoint::ZeroRttAccepted"]],["impl !RefUnwindSafe for Options",1,["iroh::net_report::options::imp::Options"]],["impl !RefUnwindSafe for QuicConfig",1,["iroh::net_report::reportgen::QuicConfig"]],["impl !RefUnwindSafe for Router",1,["iroh::protocol::Router"]],["impl !RefUnwindSafe for RouterBuilder",1,["iroh::protocol::RouterBuilder"]],["impl !RefUnwindSafe for CleanupDropGuard",1,["iroh::test_utils::CleanupDropGuard"]],["impl !RefUnwindSafe for DnsPkarrServer",1,["iroh::test_utils::dns_and_pkarr_servers::DnsPkarrServer"]],["impl RefUnwindSafe for ConnectionType",1,["iroh::magicsock::node_map::node_state::ConnectionType"]],["impl RefUnwindSafe for ControlMsg",1,["iroh::magicsock::node_map::node_state::ControlMsg"]],["impl RefUnwindSafe for DirectAddrType",1,["iroh::magicsock::DirectAddrType"]],["impl RefUnwindSafe for PathSelection",1,["iroh::endpoint::PathSelection"]],["impl RefUnwindSafe for RelayMode",1,["iroh::endpoint::RelayMode"]],["impl RefUnwindSafe for Source",1,["iroh::magicsock::node_map::Source"]],["impl RefUnwindSafe for MdnsDiscovery",1,["iroh::discovery::mdns::MdnsDiscovery"]],["impl RefUnwindSafe for MdnsDiscoveryBuilder",1,["iroh::discovery::mdns::MdnsDiscoveryBuilder"]],["impl RefUnwindSafe for PkarrPublisher",1,["iroh::discovery::pkarr::PkarrPublisher"]],["impl RefUnwindSafe for StaticProvider",1,["iroh::discovery::static_provider::StaticProvider"]],["impl RefUnwindSafe for DiscoveryItem",1,["iroh::discovery::DiscoveryItem"]],["impl RefUnwindSafe for Lagged",1,["iroh::discovery::Lagged"]],["impl RefUnwindSafe for Connection",1,["iroh::endpoint::Connection"]],["impl RefUnwindSafe for DirectAddr",1,["iroh::magicsock::DirectAddr"]],["impl RefUnwindSafe for DirectAddrInfo",1,["iroh::magicsock::node_map::node_state::DirectAddrInfo"]],["impl RefUnwindSafe for RemoteInfo",1,["iroh::magicsock::node_map::node_state::RemoteInfo"]],["impl RefUnwindSafe for RemoteNodeIdError",1,["iroh::endpoint::RemoteNodeIdError"]],["impl RefUnwindSafe for EndpointMetrics",1,["iroh::metrics::EndpointMetrics"]],["impl RefUnwindSafe for Metrics",1,["iroh::magicsock::metrics::Metrics"]],["impl RefUnwindSafe for Addr",1,["iroh::net_report::Addr"]],["impl RefUnwindSafe for Client",1,["iroh::net_report::Client"]],["impl RefUnwindSafe for Metrics",1,["iroh::net_report::metrics::Metrics"]],["impl RefUnwindSafe for RelayLatencies",1,["iroh::net_report::RelayLatencies"]],["impl RefUnwindSafe for Report",1,["iroh::net_report::Report"]],["impl<'a> !RefUnwindSafe for DiscoveryContext<'a>",1,["iroh::discovery::DiscoveryContext"]],["impl<'a> !RefUnwindSafe for Accept<'a>",1,["iroh::endpoint::Accept"]],["impl<P> !RefUnwindSafe for AccessLimit<P>",1,["iroh::protocol::AccessLimit"]]]],["iroh_base",[["impl !RefUnwindSafe for KeyParsingError",1,["iroh_base::key::KeyParsingError"]],["impl !RefUnwindSafe for ParseError",1,["iroh_base::ticket::ParseError"]],["impl RefUnwindSafe for NodeAddr",1,["iroh_base::node_addr::NodeAddr"]],["impl RefUnwindSafe for PublicKey",1,["iroh_base::key::PublicKey"]],["impl RefUnwindSafe for RelayUrl",1,["iroh_base::relay_url::RelayUrl"]],["impl RefUnwindSafe for RelayUrlParseError",1,["iroh_base::relay_url::RelayUrlParseError"]],["impl RefUnwindSafe for SecretKey",1,["iroh_base::key::SecretKey"]],["impl RefUnwindSafe for NodeTicket",1,["iroh_base::ticket::node::NodeTicket"]]]],["iroh_bench",[["impl !RefUnwindSafe for EndpointSelector",1,["iroh_bench::EndpointSelector"]],["impl RefUnwindSafe for Commands",1,["iroh_bench::Commands"]],["impl RefUnwindSafe for ConnectionSelector",1,["iroh_bench::ConnectionSelector"]],["impl RefUnwindSafe for Opt",1,["iroh_bench::s2n::Opt"]],["impl RefUnwindSafe for Stats",1,["iroh_bench::stats::Stats"]],["impl RefUnwindSafe for StreamStats",1,["iroh_bench::stats::StreamStats"]],["impl RefUnwindSafe for TransferResult",1,["iroh_bench::stats::TransferResult"]],["impl RefUnwindSafe for ClientStats",1,["iroh_bench::ClientStats"]],["impl RefUnwindSafe for Opt",1,["iroh_bench::Opt"]]]],["iroh_dns_server",[["impl !RefUnwindSafe for DnsHandler",1,["iroh_dns_server::dns::DnsHandler"]],["impl !RefUnwindSafe for DnsServer",1,["iroh_dns_server::dns::DnsServer"]],["impl !RefUnwindSafe for Handle",1,["iroh_dns_server::dns::Handle"]],["impl !RefUnwindSafe for HttpServer",1,["iroh_dns_server::http::HttpServer"]],["impl !RefUnwindSafe for Server",1,["iroh_dns_server::server::Server"]],["impl !RefUnwindSafe for AppState",1,["iroh_dns_server::state::AppState"]],["impl !RefUnwindSafe for ZoneStore",1,["iroh_dns_server::store::ZoneStore"]],["impl RefUnwindSafe for BootstrapOption",1,["iroh_dns_server::config::BootstrapOption"]],["impl RefUnwindSafe for CertMode",1,["iroh_dns_server::http::tls::CertMode"]],["impl RefUnwindSafe for RateLimitConfig",1,["iroh_dns_server::http::rate_limiting::RateLimitConfig"]],["impl RefUnwindSafe for Config",1,["iroh_dns_server::config::Config"]],["impl RefUnwindSafe for MainlineConfig",1,["iroh_dns_server::config::MainlineConfig"]],["impl RefUnwindSafe for MetricsConfig",1,["iroh_dns_server::config::MetricsConfig"]],["impl RefUnwindSafe for StoreConfig",1,["iroh_dns_server::config::StoreConfig"]],["impl RefUnwindSafe for DnsConfig",1,["iroh_dns_server::dns::DnsConfig"]],["impl RefUnwindSafe for HttpConfig",1,["iroh_dns_server::http::HttpConfig"]],["impl RefUnwindSafe for HttpsConfig",1,["iroh_dns_server::http::HttpsConfig"]],["impl RefUnwindSafe for Metrics",1,["iroh_dns_server::metrics::Metrics"]]]],["iroh_relay",[["impl !RefUnwindSafe for ConnectError",1,["iroh_relay::client::ConnectError"]],["impl !RefUnwindSafe for DialError",1,["iroh_relay::client::DialError"]],["impl !RefUnwindSafe for RecvError",1,["iroh_relay::client::conn::RecvError"]],["impl !RefUnwindSafe for SendError",1,["iroh_relay::client::conn::SendError"]],["impl !RefUnwindSafe for DnsError",1,["iroh_relay::dns::DnsError"]],["impl !RefUnwindSafe for DecodingError",1,["iroh_relay::node_info::DecodingError"]],["impl !RefUnwindSafe for EncodingError",1,["iroh_relay::node_info::EncodingError"]],["impl !RefUnwindSafe for LookupError",1,["iroh_relay::node_info::LookupError"]],["impl !RefUnwindSafe for ParseError",1,["iroh_relay::node_info::ParseError"]],["impl !RefUnwindSafe for RecvError",1,["iroh_relay::protos::relay::RecvError"]],["impl !RefUnwindSafe for SendError",1,["iroh_relay::protos::relay::SendError"]],["impl !RefUnwindSafe for StunError",1,["iroh_relay::protos::stun::StunError"]],["impl !RefUnwindSafe for Error",1,["iroh_relay::quic::Error"]],["impl !RefUnwindSafe for AccessConfig",1,["iroh_relay::server::AccessConfig"]],["impl !RefUnwindSafe for SpawnError",1,["iroh_relay::server::SpawnError"]],["impl !RefUnwindSafe for SupervisorError",1,["iroh_relay::server::SupervisorError"]],["impl !RefUnwindSafe for Client",1,["iroh_relay::client::Client"]],["impl !RefUnwindSafe for ClientBuilder",1,["iroh_relay::client::ClientBuilder"]],["impl !RefUnwindSafe for ClientSink",1,["iroh_relay::client::ClientSink"]],["impl !RefUnwindSafe for ClientStream",1,["iroh_relay::client::ClientStream"]],["impl !RefUnwindSafe for DnsResolver",1,["iroh_relay::dns::DnsResolver"]],["impl !RefUnwindSafe for MaxLengthExceededError",1,["iroh_relay::node_info::MaxLengthExceededError"]],["impl !RefUnwindSafe for QuicClient",1,["iroh_relay::quic::QuicClient"]],["impl !RefUnwindSafe for QuicConfig",1,["iroh_relay::server::QuicConfig"]],["impl RefUnwindSafe for ReceivedMessage",1,["iroh_relay::client::conn::ReceivedMessage"]],["impl RefUnwindSafe for SendMessage",1,["iroh_relay::client::conn::SendMessage"]],["impl RefUnwindSafe for Protocol",1,["iroh_relay::http::Protocol"]],["impl RefUnwindSafe for FrameType",1,["iroh_relay::protos::relay::FrameType"]],["impl RefUnwindSafe for Access",1,["iroh_relay::server::Access"]],["impl RefUnwindSafe for TXT",1,["iroh_relay::dns::TXT"]],["impl RefUnwindSafe for TxtLookup",1,["iroh_relay::dns::TxtLookup"]],["impl RefUnwindSafe for NodeData",1,["iroh_relay::node_info::NodeData"]],["impl RefUnwindSafe for NodeInfo",1,["iroh_relay::node_info::NodeInfo"]],["impl RefUnwindSafe for UserData",1,["iroh_relay::node_info::UserData"]],["impl RefUnwindSafe for ClientRateLimit",1,["iroh_relay::server::ClientRateLimit"]],["impl RefUnwindSafe for Limits",1,["iroh_relay::server::Limits"]],["impl RefUnwindSafe for Metrics",1,["iroh_relay::server::metrics::Metrics"]],["impl RefUnwindSafe for RelayMetrics",1,["iroh_relay::server::metrics::RelayMetrics"]],["impl RefUnwindSafe for Server",1,["iroh_relay::server::Server"]],["impl RefUnwindSafe for StunConfig",1,["iroh_relay::server::StunConfig"]],["impl RefUnwindSafe for StunMetrics",1,["iroh_relay::server::metrics::StunMetrics"]],["impl RefUnwindSafe for PingTracker",1,["iroh_relay::ping_tracker::PingTracker"]],["impl RefUnwindSafe for RelayMap",1,["iroh_relay::relay_map::RelayMap"]],["impl RefUnwindSafe for RelayNode",1,["iroh_relay::relay_map::RelayNode"]],["impl RefUnwindSafe for RelayQuicConfig",1,["iroh_relay::relay_map::RelayQuicConfig"]],["impl<E> !RefUnwindSafe for StaggeredError<E>",1,["iroh_relay::dns::StaggeredError"]],["impl<EC, EA = EC> !RefUnwindSafe for CertConfig<EC, EA>",1,["iroh_relay::server::CertConfig"]],["impl<EC, EA = EC> !RefUnwindSafe for RelayConfig<EC, EA>",1,["iroh_relay::server::RelayConfig"]],["impl<EC, EA = EC> !RefUnwindSafe for ServerConfig<EC, EA>",1,["iroh_relay::server::ServerConfig"]],["impl<EC, EA = EC> !RefUnwindSafe for TlsConfig<EC, EA>",1,["iroh_relay::server::TlsConfig"]],["impl<Loader> !RefUnwindSafe for ReloadingResolver<Loader>",1,["iroh_relay::server::resolver::ReloadingResolver"]]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[25903,2862,3166,6813,18929]} \ No newline at end of file +//{"start":57,"fragment_lengths":[22433,2862,3166,6813,18972]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js b/pr/3327/docs/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js index afddcfd300..a50ea05589 100644 --- a/pr/3327/docs/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js +++ b/pr/3327/docs/trait.impl/core/panic/unwind_safe/trait.UnwindSafe.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl !UnwindSafe for DiscoveryError",1,["iroh::discovery::DiscoveryError"]],["impl !UnwindSafe for IntoDiscoveryError",1,["iroh::discovery::IntoDiscoveryError"]],["impl !UnwindSafe for PkarrError",1,["iroh::discovery::pkarr::PkarrError"]],["impl !UnwindSafe for AddNodeAddrError",1,["iroh::magicsock::AddNodeAddrError"]],["impl !UnwindSafe for AlpnError",1,["iroh::endpoint::AlpnError"]],["impl !UnwindSafe for BindError",1,["iroh::endpoint::BindError"]],["impl !UnwindSafe for ConnectError",1,["iroh::endpoint::ConnectError"]],["impl !UnwindSafe for ConnectWithOptsError",1,["iroh::endpoint::ConnectWithOptsError"]],["impl !UnwindSafe for GetMappingAddressError",1,["iroh::endpoint::GetMappingAddressError"]],["impl !UnwindSafe for ReportError",1,["iroh::net_report::ReportError"]],["impl !UnwindSafe for ProtocolError",1,["iroh::protocol::ProtocolError"]],["impl !UnwindSafe for DnsDiscovery",1,["iroh::discovery::dns::DnsDiscovery"]],["impl !UnwindSafe for DnsDiscoveryBuilder",1,["iroh::discovery::dns::DnsDiscoveryBuilder"]],["impl !UnwindSafe for Builder",1,["iroh::discovery::pkarr::dht::Builder"]],["impl !UnwindSafe for DhtDiscovery",1,["iroh::discovery::pkarr::dht::DhtDiscovery"]],["impl !UnwindSafe for PkarrPublisherBuilder",1,["iroh::discovery::pkarr::PkarrPublisherBuilder"]],["impl !UnwindSafe for PkarrRelayClient",1,["iroh::discovery::pkarr::PkarrRelayClient"]],["impl !UnwindSafe for PkarrResolver",1,["iroh::discovery::pkarr::PkarrResolver"]],["impl !UnwindSafe for PkarrResolverBuilder",1,["iroh::discovery::pkarr::PkarrResolverBuilder"]],["impl !UnwindSafe for ConcurrentDiscovery",1,["iroh::discovery::ConcurrentDiscovery"]],["impl !UnwindSafe for Builder",1,["iroh::endpoint::Builder"]],["impl !UnwindSafe for ConnectOptions",1,["iroh::endpoint::ConnectOptions"]],["impl !UnwindSafe for Connecting",1,["iroh::endpoint::Connecting"]],["impl !UnwindSafe for Endpoint",1,["iroh::endpoint::Endpoint"]],["impl !UnwindSafe for Incoming",1,["iroh::endpoint::Incoming"]],["impl !UnwindSafe for IncomingFuture",1,["iroh::endpoint::IncomingFuture"]],["impl !UnwindSafe for ZeroRttAccepted",1,["iroh::endpoint::ZeroRttAccepted"]],["impl !UnwindSafe for Options",1,["iroh::net_report::options::imp::Options"]],["impl !UnwindSafe for QuicConfig",1,["iroh::net_report::reportgen::QuicConfig"]],["impl !UnwindSafe for Router",1,["iroh::protocol::Router"]],["impl !UnwindSafe for RouterBuilder",1,["iroh::protocol::RouterBuilder"]],["impl !UnwindSafe for CleanupDropGuard",1,["iroh::test_utils::CleanupDropGuard"]],["impl !UnwindSafe for DnsPkarrServer",1,["iroh::test_utils::dns_and_pkarr_servers::DnsPkarrServer"]],["impl !UnwindSafe for Disconnected",1,["iroh::watcher::Disconnected"]],["impl UnwindSafe for ConnectionType",1,["iroh::magicsock::node_map::node_state::ConnectionType"]],["impl UnwindSafe for ControlMsg",1,["iroh::magicsock::node_map::node_state::ControlMsg"]],["impl UnwindSafe for DirectAddrType",1,["iroh::magicsock::DirectAddrType"]],["impl UnwindSafe for PathSelection",1,["iroh::endpoint::PathSelection"]],["impl UnwindSafe for RelayMode",1,["iroh::endpoint::RelayMode"]],["impl UnwindSafe for Source",1,["iroh::magicsock::node_map::Source"]],["impl UnwindSafe for MdnsDiscovery",1,["iroh::discovery::mdns::MdnsDiscovery"]],["impl UnwindSafe for MdnsDiscoveryBuilder",1,["iroh::discovery::mdns::MdnsDiscoveryBuilder"]],["impl UnwindSafe for PkarrPublisher",1,["iroh::discovery::pkarr::PkarrPublisher"]],["impl UnwindSafe for StaticProvider",1,["iroh::discovery::static_provider::StaticProvider"]],["impl UnwindSafe for DiscoveryItem",1,["iroh::discovery::DiscoveryItem"]],["impl UnwindSafe for Lagged",1,["iroh::discovery::Lagged"]],["impl UnwindSafe for Connection",1,["iroh::endpoint::Connection"]],["impl UnwindSafe for DirectAddr",1,["iroh::magicsock::DirectAddr"]],["impl UnwindSafe for DirectAddrInfo",1,["iroh::magicsock::node_map::node_state::DirectAddrInfo"]],["impl UnwindSafe for RemoteInfo",1,["iroh::magicsock::node_map::node_state::RemoteInfo"]],["impl UnwindSafe for RemoteNodeIdError",1,["iroh::endpoint::RemoteNodeIdError"]],["impl UnwindSafe for EndpointMetrics",1,["iroh::metrics::EndpointMetrics"]],["impl UnwindSafe for Metrics",1,["iroh::magicsock::metrics::Metrics"]],["impl UnwindSafe for Addr",1,["iroh::net_report::Addr"]],["impl UnwindSafe for Client",1,["iroh::net_report::Client"]],["impl UnwindSafe for Metrics",1,["iroh::net_report::metrics::Metrics"]],["impl UnwindSafe for RelayLatencies",1,["iroh::net_report::RelayLatencies"]],["impl UnwindSafe for Report",1,["iroh::net_report::Report"]],["impl<'a> !UnwindSafe for DiscoveryContext<'a>",1,["iroh::discovery::DiscoveryContext"]],["impl<'a> !UnwindSafe for Accept<'a>",1,["iroh::endpoint::Accept"]],["impl<'a, T, W> !UnwindSafe for InitializedFut<'a, T, W>",1,["iroh::watcher::InitializedFut"]],["impl<'a, W> !UnwindSafe for NextFut<'a, W>",1,["iroh::watcher::NextFut"]],["impl<P> !UnwindSafe for AccessLimit<P>",1,["iroh::protocol::AccessLimit"]],["impl<T> UnwindSafe for Direct<T>",1,["iroh::watcher::Direct"]],["impl<T> UnwindSafe for Watchable<T>",1,["iroh::watcher::Watchable"]],["impl<W> UnwindSafe for Stream<W>
    where\n W: UnwindSafe,\n <W as Watcher>::Value: UnwindSafe,
    ",1,["iroh::watcher::Stream"]],["impl<W, T> !UnwindSafe for Map<W, T>",1,["iroh::watcher::Map"]]]],["iroh_base",[["impl !UnwindSafe for KeyParsingError",1,["iroh_base::key::KeyParsingError"]],["impl !UnwindSafe for ParseError",1,["iroh_base::ticket::ParseError"]],["impl UnwindSafe for NodeAddr",1,["iroh_base::node_addr::NodeAddr"]],["impl UnwindSafe for PublicKey",1,["iroh_base::key::PublicKey"]],["impl UnwindSafe for RelayUrl",1,["iroh_base::relay_url::RelayUrl"]],["impl UnwindSafe for RelayUrlParseError",1,["iroh_base::relay_url::RelayUrlParseError"]],["impl UnwindSafe for SecretKey",1,["iroh_base::key::SecretKey"]],["impl UnwindSafe for NodeTicket",1,["iroh_base::ticket::node::NodeTicket"]]]],["iroh_bench",[["impl !UnwindSafe for EndpointSelector",1,["iroh_bench::EndpointSelector"]],["impl UnwindSafe for Commands",1,["iroh_bench::Commands"]],["impl UnwindSafe for ConnectionSelector",1,["iroh_bench::ConnectionSelector"]],["impl UnwindSafe for Opt",1,["iroh_bench::s2n::Opt"]],["impl UnwindSafe for Stats",1,["iroh_bench::stats::Stats"]],["impl UnwindSafe for StreamStats",1,["iroh_bench::stats::StreamStats"]],["impl UnwindSafe for TransferResult",1,["iroh_bench::stats::TransferResult"]],["impl UnwindSafe for ClientStats",1,["iroh_bench::ClientStats"]],["impl UnwindSafe for Opt",1,["iroh_bench::Opt"]]]],["iroh_dns_server",[["impl !UnwindSafe for DnsHandler",1,["iroh_dns_server::dns::DnsHandler"]],["impl !UnwindSafe for DnsServer",1,["iroh_dns_server::dns::DnsServer"]],["impl !UnwindSafe for Handle",1,["iroh_dns_server::dns::Handle"]],["impl !UnwindSafe for HttpServer",1,["iroh_dns_server::http::HttpServer"]],["impl !UnwindSafe for Server",1,["iroh_dns_server::server::Server"]],["impl !UnwindSafe for AppState",1,["iroh_dns_server::state::AppState"]],["impl !UnwindSafe for ZoneStore",1,["iroh_dns_server::store::ZoneStore"]],["impl UnwindSafe for BootstrapOption",1,["iroh_dns_server::config::BootstrapOption"]],["impl UnwindSafe for CertMode",1,["iroh_dns_server::http::tls::CertMode"]],["impl UnwindSafe for RateLimitConfig",1,["iroh_dns_server::http::rate_limiting::RateLimitConfig"]],["impl UnwindSafe for Config",1,["iroh_dns_server::config::Config"]],["impl UnwindSafe for MainlineConfig",1,["iroh_dns_server::config::MainlineConfig"]],["impl UnwindSafe for MetricsConfig",1,["iroh_dns_server::config::MetricsConfig"]],["impl UnwindSafe for StoreConfig",1,["iroh_dns_server::config::StoreConfig"]],["impl UnwindSafe for DnsConfig",1,["iroh_dns_server::dns::DnsConfig"]],["impl UnwindSafe for HttpConfig",1,["iroh_dns_server::http::HttpConfig"]],["impl UnwindSafe for HttpsConfig",1,["iroh_dns_server::http::HttpsConfig"]],["impl UnwindSafe for Metrics",1,["iroh_dns_server::metrics::Metrics"]]]],["iroh_relay",[["impl !UnwindSafe for ConnectError",1,["iroh_relay::client::ConnectError"]],["impl !UnwindSafe for DialError",1,["iroh_relay::client::DialError"]],["impl !UnwindSafe for RecvError",1,["iroh_relay::client::conn::RecvError"]],["impl !UnwindSafe for SendError",1,["iroh_relay::client::conn::SendError"]],["impl !UnwindSafe for DnsError",1,["iroh_relay::dns::DnsError"]],["impl !UnwindSafe for DecodingError",1,["iroh_relay::node_info::DecodingError"]],["impl !UnwindSafe for EncodingError",1,["iroh_relay::node_info::EncodingError"]],["impl !UnwindSafe for LookupError",1,["iroh_relay::node_info::LookupError"]],["impl !UnwindSafe for ParseError",1,["iroh_relay::node_info::ParseError"]],["impl !UnwindSafe for RecvError",1,["iroh_relay::protos::relay::RecvError"]],["impl !UnwindSafe for SendError",1,["iroh_relay::protos::relay::SendError"]],["impl !UnwindSafe for StunError",1,["iroh_relay::protos::stun::StunError"]],["impl !UnwindSafe for Error",1,["iroh_relay::quic::Error"]],["impl !UnwindSafe for AccessConfig",1,["iroh_relay::server::AccessConfig"]],["impl !UnwindSafe for SpawnError",1,["iroh_relay::server::SpawnError"]],["impl !UnwindSafe for SupervisorError",1,["iroh_relay::server::SupervisorError"]],["impl !UnwindSafe for Client",1,["iroh_relay::client::Client"]],["impl !UnwindSafe for ClientBuilder",1,["iroh_relay::client::ClientBuilder"]],["impl !UnwindSafe for ClientSink",1,["iroh_relay::client::ClientSink"]],["impl !UnwindSafe for ClientStream",1,["iroh_relay::client::ClientStream"]],["impl !UnwindSafe for DnsResolver",1,["iroh_relay::dns::DnsResolver"]],["impl !UnwindSafe for Error",1,["iroh_relay::dns::staggered::Error"]],["impl !UnwindSafe for MaxLengthExceededError",1,["iroh_relay::node_info::MaxLengthExceededError"]],["impl !UnwindSafe for QuicClient",1,["iroh_relay::quic::QuicClient"]],["impl !UnwindSafe for QuicConfig",1,["iroh_relay::server::QuicConfig"]],["impl UnwindSafe for ReceivedMessage",1,["iroh_relay::client::conn::ReceivedMessage"]],["impl UnwindSafe for SendMessage",1,["iroh_relay::client::conn::SendMessage"]],["impl UnwindSafe for Protocol",1,["iroh_relay::http::Protocol"]],["impl UnwindSafe for FrameType",1,["iroh_relay::protos::relay::FrameType"]],["impl UnwindSafe for Access",1,["iroh_relay::server::Access"]],["impl UnwindSafe for TXT",1,["iroh_relay::dns::TXT"]],["impl UnwindSafe for TxtLookup",1,["iroh_relay::dns::TxtLookup"]],["impl UnwindSafe for NodeData",1,["iroh_relay::node_info::NodeData"]],["impl UnwindSafe for NodeInfo",1,["iroh_relay::node_info::NodeInfo"]],["impl UnwindSafe for UserData",1,["iroh_relay::node_info::UserData"]],["impl UnwindSafe for ClientRateLimit",1,["iroh_relay::server::ClientRateLimit"]],["impl UnwindSafe for Limits",1,["iroh_relay::server::Limits"]],["impl UnwindSafe for Metrics",1,["iroh_relay::server::metrics::Metrics"]],["impl UnwindSafe for RelayMetrics",1,["iroh_relay::server::metrics::RelayMetrics"]],["impl UnwindSafe for Server",1,["iroh_relay::server::Server"]],["impl UnwindSafe for StunConfig",1,["iroh_relay::server::StunConfig"]],["impl UnwindSafe for StunMetrics",1,["iroh_relay::server::metrics::StunMetrics"]],["impl UnwindSafe for PingTracker",1,["iroh_relay::ping_tracker::PingTracker"]],["impl UnwindSafe for RelayMap",1,["iroh_relay::relay_map::RelayMap"]],["impl UnwindSafe for RelayNode",1,["iroh_relay::relay_map::RelayNode"]],["impl UnwindSafe for RelayQuicConfig",1,["iroh_relay::relay_map::RelayQuicConfig"]],["impl<EC, EA = EC> !UnwindSafe for CertConfig<EC, EA>",1,["iroh_relay::server::CertConfig"]],["impl<EC, EA = EC> !UnwindSafe for RelayConfig<EC, EA>",1,["iroh_relay::server::RelayConfig"]],["impl<EC, EA = EC> !UnwindSafe for ServerConfig<EC, EA>",1,["iroh_relay::server::ServerConfig"]],["impl<EC, EA = EC> !UnwindSafe for TlsConfig<EC, EA>",1,["iroh_relay::server::TlsConfig"]],["impl<Loader> !UnwindSafe for ReloadingResolver<Loader>",1,["iroh_relay::server::resolver::ReloadingResolver"]]]]]); + var implementors = Object.fromEntries([["iroh",[["impl !UnwindSafe for DiscoveryError",1,["iroh::discovery::DiscoveryError"]],["impl !UnwindSafe for IntoDiscoveryError",1,["iroh::discovery::IntoDiscoveryError"]],["impl !UnwindSafe for PkarrError",1,["iroh::discovery::pkarr::PkarrError"]],["impl !UnwindSafe for AddNodeAddrError",1,["iroh::magicsock::AddNodeAddrError"]],["impl !UnwindSafe for AlpnError",1,["iroh::endpoint::AlpnError"]],["impl !UnwindSafe for BindError",1,["iroh::endpoint::BindError"]],["impl !UnwindSafe for ConnectError",1,["iroh::endpoint::ConnectError"]],["impl !UnwindSafe for ConnectWithOptsError",1,["iroh::endpoint::ConnectWithOptsError"]],["impl !UnwindSafe for GetMappingAddressError",1,["iroh::endpoint::GetMappingAddressError"]],["impl !UnwindSafe for ReportError",1,["iroh::net_report::ReportError"]],["impl !UnwindSafe for AcceptError",1,["iroh::protocol::AcceptError"]],["impl !UnwindSafe for DnsDiscovery",1,["iroh::discovery::dns::DnsDiscovery"]],["impl !UnwindSafe for DnsDiscoveryBuilder",1,["iroh::discovery::dns::DnsDiscoveryBuilder"]],["impl !UnwindSafe for Builder",1,["iroh::discovery::pkarr::dht::Builder"]],["impl !UnwindSafe for DhtDiscovery",1,["iroh::discovery::pkarr::dht::DhtDiscovery"]],["impl !UnwindSafe for PkarrPublisherBuilder",1,["iroh::discovery::pkarr::PkarrPublisherBuilder"]],["impl !UnwindSafe for PkarrRelayClient",1,["iroh::discovery::pkarr::PkarrRelayClient"]],["impl !UnwindSafe for PkarrResolver",1,["iroh::discovery::pkarr::PkarrResolver"]],["impl !UnwindSafe for PkarrResolverBuilder",1,["iroh::discovery::pkarr::PkarrResolverBuilder"]],["impl !UnwindSafe for ConcurrentDiscovery",1,["iroh::discovery::ConcurrentDiscovery"]],["impl !UnwindSafe for Builder",1,["iroh::endpoint::Builder"]],["impl !UnwindSafe for ConnectOptions",1,["iroh::endpoint::ConnectOptions"]],["impl !UnwindSafe for Connecting",1,["iroh::endpoint::Connecting"]],["impl !UnwindSafe for Endpoint",1,["iroh::endpoint::Endpoint"]],["impl !UnwindSafe for Incoming",1,["iroh::endpoint::Incoming"]],["impl !UnwindSafe for IncomingFuture",1,["iroh::endpoint::IncomingFuture"]],["impl !UnwindSafe for ZeroRttAccepted",1,["iroh::endpoint::ZeroRttAccepted"]],["impl !UnwindSafe for Options",1,["iroh::net_report::options::imp::Options"]],["impl !UnwindSafe for QuicConfig",1,["iroh::net_report::reportgen::QuicConfig"]],["impl !UnwindSafe for Router",1,["iroh::protocol::Router"]],["impl !UnwindSafe for RouterBuilder",1,["iroh::protocol::RouterBuilder"]],["impl !UnwindSafe for CleanupDropGuard",1,["iroh::test_utils::CleanupDropGuard"]],["impl !UnwindSafe for DnsPkarrServer",1,["iroh::test_utils::dns_and_pkarr_servers::DnsPkarrServer"]],["impl UnwindSafe for ConnectionType",1,["iroh::magicsock::node_map::node_state::ConnectionType"]],["impl UnwindSafe for ControlMsg",1,["iroh::magicsock::node_map::node_state::ControlMsg"]],["impl UnwindSafe for DirectAddrType",1,["iroh::magicsock::DirectAddrType"]],["impl UnwindSafe for PathSelection",1,["iroh::endpoint::PathSelection"]],["impl UnwindSafe for RelayMode",1,["iroh::endpoint::RelayMode"]],["impl UnwindSafe for Source",1,["iroh::magicsock::node_map::Source"]],["impl UnwindSafe for MdnsDiscovery",1,["iroh::discovery::mdns::MdnsDiscovery"]],["impl UnwindSafe for MdnsDiscoveryBuilder",1,["iroh::discovery::mdns::MdnsDiscoveryBuilder"]],["impl UnwindSafe for PkarrPublisher",1,["iroh::discovery::pkarr::PkarrPublisher"]],["impl UnwindSafe for StaticProvider",1,["iroh::discovery::static_provider::StaticProvider"]],["impl UnwindSafe for DiscoveryItem",1,["iroh::discovery::DiscoveryItem"]],["impl UnwindSafe for Lagged",1,["iroh::discovery::Lagged"]],["impl UnwindSafe for Connection",1,["iroh::endpoint::Connection"]],["impl UnwindSafe for DirectAddr",1,["iroh::magicsock::DirectAddr"]],["impl UnwindSafe for DirectAddrInfo",1,["iroh::magicsock::node_map::node_state::DirectAddrInfo"]],["impl UnwindSafe for RemoteInfo",1,["iroh::magicsock::node_map::node_state::RemoteInfo"]],["impl UnwindSafe for RemoteNodeIdError",1,["iroh::endpoint::RemoteNodeIdError"]],["impl UnwindSafe for EndpointMetrics",1,["iroh::metrics::EndpointMetrics"]],["impl UnwindSafe for Metrics",1,["iroh::magicsock::metrics::Metrics"]],["impl UnwindSafe for Addr",1,["iroh::net_report::Addr"]],["impl UnwindSafe for Client",1,["iroh::net_report::Client"]],["impl UnwindSafe for Metrics",1,["iroh::net_report::metrics::Metrics"]],["impl UnwindSafe for RelayLatencies",1,["iroh::net_report::RelayLatencies"]],["impl UnwindSafe for Report",1,["iroh::net_report::Report"]],["impl<'a> !UnwindSafe for DiscoveryContext<'a>",1,["iroh::discovery::DiscoveryContext"]],["impl<'a> !UnwindSafe for Accept<'a>",1,["iroh::endpoint::Accept"]],["impl<P> !UnwindSafe for AccessLimit<P>",1,["iroh::protocol::AccessLimit"]]]],["iroh_base",[["impl !UnwindSafe for KeyParsingError",1,["iroh_base::key::KeyParsingError"]],["impl !UnwindSafe for ParseError",1,["iroh_base::ticket::ParseError"]],["impl UnwindSafe for NodeAddr",1,["iroh_base::node_addr::NodeAddr"]],["impl UnwindSafe for PublicKey",1,["iroh_base::key::PublicKey"]],["impl UnwindSafe for RelayUrl",1,["iroh_base::relay_url::RelayUrl"]],["impl UnwindSafe for RelayUrlParseError",1,["iroh_base::relay_url::RelayUrlParseError"]],["impl UnwindSafe for SecretKey",1,["iroh_base::key::SecretKey"]],["impl UnwindSafe for NodeTicket",1,["iroh_base::ticket::node::NodeTicket"]]]],["iroh_bench",[["impl !UnwindSafe for EndpointSelector",1,["iroh_bench::EndpointSelector"]],["impl UnwindSafe for Commands",1,["iroh_bench::Commands"]],["impl UnwindSafe for ConnectionSelector",1,["iroh_bench::ConnectionSelector"]],["impl UnwindSafe for Opt",1,["iroh_bench::s2n::Opt"]],["impl UnwindSafe for Stats",1,["iroh_bench::stats::Stats"]],["impl UnwindSafe for StreamStats",1,["iroh_bench::stats::StreamStats"]],["impl UnwindSafe for TransferResult",1,["iroh_bench::stats::TransferResult"]],["impl UnwindSafe for ClientStats",1,["iroh_bench::ClientStats"]],["impl UnwindSafe for Opt",1,["iroh_bench::Opt"]]]],["iroh_dns_server",[["impl !UnwindSafe for DnsHandler",1,["iroh_dns_server::dns::DnsHandler"]],["impl !UnwindSafe for DnsServer",1,["iroh_dns_server::dns::DnsServer"]],["impl !UnwindSafe for Handle",1,["iroh_dns_server::dns::Handle"]],["impl !UnwindSafe for HttpServer",1,["iroh_dns_server::http::HttpServer"]],["impl !UnwindSafe for Server",1,["iroh_dns_server::server::Server"]],["impl !UnwindSafe for AppState",1,["iroh_dns_server::state::AppState"]],["impl !UnwindSafe for ZoneStore",1,["iroh_dns_server::store::ZoneStore"]],["impl UnwindSafe for BootstrapOption",1,["iroh_dns_server::config::BootstrapOption"]],["impl UnwindSafe for CertMode",1,["iroh_dns_server::http::tls::CertMode"]],["impl UnwindSafe for RateLimitConfig",1,["iroh_dns_server::http::rate_limiting::RateLimitConfig"]],["impl UnwindSafe for Config",1,["iroh_dns_server::config::Config"]],["impl UnwindSafe for MainlineConfig",1,["iroh_dns_server::config::MainlineConfig"]],["impl UnwindSafe for MetricsConfig",1,["iroh_dns_server::config::MetricsConfig"]],["impl UnwindSafe for StoreConfig",1,["iroh_dns_server::config::StoreConfig"]],["impl UnwindSafe for DnsConfig",1,["iroh_dns_server::dns::DnsConfig"]],["impl UnwindSafe for HttpConfig",1,["iroh_dns_server::http::HttpConfig"]],["impl UnwindSafe for HttpsConfig",1,["iroh_dns_server::http::HttpsConfig"]],["impl UnwindSafe for Metrics",1,["iroh_dns_server::metrics::Metrics"]]]],["iroh_relay",[["impl !UnwindSafe for ConnectError",1,["iroh_relay::client::ConnectError"]],["impl !UnwindSafe for DialError",1,["iroh_relay::client::DialError"]],["impl !UnwindSafe for RecvError",1,["iroh_relay::client::conn::RecvError"]],["impl !UnwindSafe for SendError",1,["iroh_relay::client::conn::SendError"]],["impl !UnwindSafe for DnsError",1,["iroh_relay::dns::DnsError"]],["impl !UnwindSafe for DecodingError",1,["iroh_relay::node_info::DecodingError"]],["impl !UnwindSafe for EncodingError",1,["iroh_relay::node_info::EncodingError"]],["impl !UnwindSafe for LookupError",1,["iroh_relay::node_info::LookupError"]],["impl !UnwindSafe for ParseError",1,["iroh_relay::node_info::ParseError"]],["impl !UnwindSafe for RecvError",1,["iroh_relay::protos::relay::RecvError"]],["impl !UnwindSafe for SendError",1,["iroh_relay::protos::relay::SendError"]],["impl !UnwindSafe for StunError",1,["iroh_relay::protos::stun::StunError"]],["impl !UnwindSafe for Error",1,["iroh_relay::quic::Error"]],["impl !UnwindSafe for AccessConfig",1,["iroh_relay::server::AccessConfig"]],["impl !UnwindSafe for SpawnError",1,["iroh_relay::server::SpawnError"]],["impl !UnwindSafe for SupervisorError",1,["iroh_relay::server::SupervisorError"]],["impl !UnwindSafe for Client",1,["iroh_relay::client::Client"]],["impl !UnwindSafe for ClientBuilder",1,["iroh_relay::client::ClientBuilder"]],["impl !UnwindSafe for ClientSink",1,["iroh_relay::client::ClientSink"]],["impl !UnwindSafe for ClientStream",1,["iroh_relay::client::ClientStream"]],["impl !UnwindSafe for DnsResolver",1,["iroh_relay::dns::DnsResolver"]],["impl !UnwindSafe for MaxLengthExceededError",1,["iroh_relay::node_info::MaxLengthExceededError"]],["impl !UnwindSafe for QuicClient",1,["iroh_relay::quic::QuicClient"]],["impl !UnwindSafe for QuicConfig",1,["iroh_relay::server::QuicConfig"]],["impl UnwindSafe for ReceivedMessage",1,["iroh_relay::client::conn::ReceivedMessage"]],["impl UnwindSafe for SendMessage",1,["iroh_relay::client::conn::SendMessage"]],["impl UnwindSafe for Protocol",1,["iroh_relay::http::Protocol"]],["impl UnwindSafe for FrameType",1,["iroh_relay::protos::relay::FrameType"]],["impl UnwindSafe for Access",1,["iroh_relay::server::Access"]],["impl UnwindSafe for TXT",1,["iroh_relay::dns::TXT"]],["impl UnwindSafe for TxtLookup",1,["iroh_relay::dns::TxtLookup"]],["impl UnwindSafe for NodeData",1,["iroh_relay::node_info::NodeData"]],["impl UnwindSafe for NodeInfo",1,["iroh_relay::node_info::NodeInfo"]],["impl UnwindSafe for UserData",1,["iroh_relay::node_info::UserData"]],["impl UnwindSafe for ClientRateLimit",1,["iroh_relay::server::ClientRateLimit"]],["impl UnwindSafe for Limits",1,["iroh_relay::server::Limits"]],["impl UnwindSafe for Metrics",1,["iroh_relay::server::metrics::Metrics"]],["impl UnwindSafe for RelayMetrics",1,["iroh_relay::server::metrics::RelayMetrics"]],["impl UnwindSafe for Server",1,["iroh_relay::server::Server"]],["impl UnwindSafe for StunConfig",1,["iroh_relay::server::StunConfig"]],["impl UnwindSafe for StunMetrics",1,["iroh_relay::server::metrics::StunMetrics"]],["impl UnwindSafe for PingTracker",1,["iroh_relay::ping_tracker::PingTracker"]],["impl UnwindSafe for RelayMap",1,["iroh_relay::relay_map::RelayMap"]],["impl UnwindSafe for RelayNode",1,["iroh_relay::relay_map::RelayNode"]],["impl UnwindSafe for RelayQuicConfig",1,["iroh_relay::relay_map::RelayQuicConfig"]],["impl<E> !UnwindSafe for StaggeredError<E>",1,["iroh_relay::dns::StaggeredError"]],["impl<EC, EA = EC> !UnwindSafe for CertConfig<EC, EA>",1,["iroh_relay::server::CertConfig"]],["impl<EC, EA = EC> !UnwindSafe for RelayConfig<EC, EA>",1,["iroh_relay::server::RelayConfig"]],["impl<EC, EA = EC> !UnwindSafe for ServerConfig<EC, EA>",1,["iroh_relay::server::ServerConfig"]],["impl<EC, EA = EC> !UnwindSafe for TlsConfig<EC, EA>",1,["iroh_relay::server::TlsConfig"]],["impl<Loader> !UnwindSafe for ReloadingResolver<Loader>",1,["iroh_relay::server::resolver::ReloadingResolver"]]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[25058,2790,3085,6651,18470]} \ No newline at end of file +//{"start":57,"fragment_lengths":[21893,2790,3085,6651,18513]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/futures_core/stream/trait.Stream.js b/pr/3327/docs/trait.impl/futures_core/stream/trait.Stream.js index 57a6a40dc6..3f9af42866 100644 --- a/pr/3327/docs/trait.impl/futures_core/stream/trait.Stream.js +++ b/pr/3327/docs/trait.impl/futures_core/stream/trait.Stream.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl<W: Watcher + Unpin> Stream for Stream<W>
    where\n W::Value: Unpin,
    "]]],["iroh_relay",[["impl Stream for Client"],["impl Stream for ClientStream"]]]]); + var implementors = Object.fromEntries([["iroh_relay",[["impl Stream for Client"],["impl Stream for ClientStream"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[734,317]} \ No newline at end of file +//{"start":57,"fragment_lengths":[316]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/iroh/watcher/trait.Watcher.js b/pr/3327/docs/trait.impl/iroh/watcher/trait.Watcher.js deleted file mode 100644 index a4910fa91e..0000000000 --- a/pr/3327/docs/trait.impl/iroh/watcher/trait.Watcher.js +++ /dev/null @@ -1,9 +0,0 @@ -(function() { - var implementors = Object.fromEntries([["iroh",[]]]); - if (window.register_implementors) { - window.register_implementors(implementors); - } else { - window.pending_implementors = implementors; - } -})() -//{"start":57,"fragment_lengths":[11]} \ No newline at end of file diff --git a/pr/3327/docs/trait.impl/snafu/trait.ErrorCompat.js b/pr/3327/docs/trait.impl/snafu/trait.ErrorCompat.js index 346fce56ea..0e861a8757 100644 --- a/pr/3327/docs/trait.impl/snafu/trait.ErrorCompat.js +++ b/pr/3327/docs/trait.impl/snafu/trait.ErrorCompat.js @@ -1,9 +1,9 @@ (function() { - var implementors = Object.fromEntries([["iroh",[["impl ErrorCompat for DiscoveryError"],["impl ErrorCompat for IntoDiscoveryError"],["impl ErrorCompat for PkarrError"],["impl ErrorCompat for AddNodeAddrError"],["impl ErrorCompat for AlpnError"],["impl ErrorCompat for BindError"],["impl ErrorCompat for ConnectError"],["impl ErrorCompat for ConnectWithOptsError"],["impl ErrorCompat for GetMappingAddressError"],["impl ErrorCompat for ReportError"],["impl ErrorCompat for ProtocolError"],["impl ErrorCompat for Lagged"],["impl ErrorCompat for RemoteNodeIdError"],["impl ErrorCompat for Disconnected"]]],["iroh_base",[["impl ErrorCompat for KeyParsingError"],["impl ErrorCompat for ParseError"],["impl ErrorCompat for RelayUrlParseError"]]],["iroh_relay",[["impl ErrorCompat for ConnectError"],["impl ErrorCompat for DialError"],["impl ErrorCompat for RecvError"],["impl ErrorCompat for SendError"],["impl ErrorCompat for DnsError"],["impl ErrorCompat for DecodingError"],["impl ErrorCompat for EncodingError"],["impl ErrorCompat for LookupError"],["impl ErrorCompat for ParseError"],["impl ErrorCompat for RecvError"],["impl ErrorCompat for SendError"],["impl ErrorCompat for StunError"],["impl ErrorCompat for Error"],["impl ErrorCompat for SpawnError"],["impl ErrorCompat for SupervisorError"],["impl ErrorCompat for Error"],["impl ErrorCompat for MaxLengthExceededError"]]]]); + var implementors = Object.fromEntries([["iroh",[["impl ErrorCompat for DiscoveryError"],["impl ErrorCompat for IntoDiscoveryError"],["impl ErrorCompat for PkarrError"],["impl ErrorCompat for AddNodeAddrError"],["impl ErrorCompat for AlpnError"],["impl ErrorCompat for BindError"],["impl ErrorCompat for ConnectError"],["impl ErrorCompat for ConnectWithOptsError"],["impl ErrorCompat for GetMappingAddressError"],["impl ErrorCompat for ReportError"],["impl ErrorCompat for AcceptError"],["impl ErrorCompat for Lagged"],["impl ErrorCompat for RemoteNodeIdError"]]],["iroh_base",[["impl ErrorCompat for KeyParsingError"],["impl ErrorCompat for ParseError"],["impl ErrorCompat for RelayUrlParseError"]]],["iroh_relay",[["impl ErrorCompat for ConnectError"],["impl ErrorCompat for DialError"],["impl ErrorCompat for RecvError"],["impl ErrorCompat for SendError"],["impl ErrorCompat for DnsError"],["impl ErrorCompat for DecodingError"],["impl ErrorCompat for EncodingError"],["impl ErrorCompat for LookupError"],["impl ErrorCompat for ParseError"],["impl ErrorCompat for RecvError"],["impl ErrorCompat for SendError"],["impl ErrorCompat for StunError"],["impl ErrorCompat for Error"],["impl ErrorCompat for SpawnError"],["impl ErrorCompat for SupervisorError"],["impl ErrorCompat for MaxLengthExceededError"],["impl<E: Debug + Display> ErrorCompat for StaggeredError<E>"]]]]); if (window.register_implementors) { window.register_implementors(implementors); } else { window.pending_implementors = implementors; } })() -//{"start":57,"fragment_lengths":[2214,481,2688]} \ No newline at end of file +//{"start":57,"fragment_lengths":[2054,481,3004]} \ No newline at end of file diff --git a/pr/3327/docs/type.impl/iroh/watcher/struct.Map.js b/pr/3327/docs/type.impl/iroh/watcher/struct.Map.js deleted file mode 100644 index 9c366f6f77..0000000000 --- a/pr/3327/docs/type.impl/iroh/watcher/struct.Map.js +++ /dev/null @@ -1,9 +0,0 @@ -(function() { - var type_impls = Object.fromEntries([["iroh",[["
    Source§

    impl<W: Clone + Watcher, T: Clone + Clone + Eq> Clone for Map<W, T>
    where\n W::Value: Clone,

    Source§

    fn clone(&self) -> Map<W, T>

    Returns a copy of the value. Read more
    1.0.0 · Source§

    fn clone_from(&mut self, source: &Self)

    Performs copy-assignment from source. Read more
    ","Clone","iroh::endpoint::NodeAddrWatcher"],["
    Source§

    impl<W, T> Debug for Map<W, T>
    where\n W: Debug + Watcher,\n T: Debug + Clone + Eq,

    Source§

    fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

    Formats the value using the given formatter. Read more
    ","Debug","iroh::endpoint::NodeAddrWatcher"],["
    Source§

    impl<W: Watcher, T: Clone + Eq> Watcher for Map<W, T>

    Source§

    type Value = T

    The type of value that can change. Read more
    Source§

    fn get(&self) -> Result<Self::Value, Disconnected>

    Returns the current state of the underlying value, or errors out with\nDisconnected, if one of the underlying Watchables has been dropped.
    Source§

    fn poll_updated(\n &mut self,\n cx: &mut Context<'_>,\n) -> Poll<Result<Self::Value, Disconnected>>

    Polls for the next value, or returns Disconnected if one of the underlying\nWatchables has been dropped.
    Source§

    fn updated(&mut self) -> NextFut<'_, Self> ⓘ

    Returns a future completing with Ok(value) once a new value is set, or with\nErr(Disconnected) if the connected Watchable was dropped. Read more
    Source§

    fn initialized<T>(&mut self) -> InitializedFut<'_, T, Self> ⓘ
    where\n Self: Watcher<Value = Option<T>>,

    Returns a future completing once the value is set to Some value. Read more
    Source§

    fn stream(self) -> Stream<Self>
    where\n Self: Unpin,

    Returns a stream which will yield the most recent values as items. Read more
    Source§

    fn stream_updates_only(self) -> Stream<Self>
    where\n Self: Unpin,

    Returns a stream which will yield the most recent values as items, starting from\nthe next unobserved future value. Read more
    Source§

    fn map<T: Clone + Eq>(\n self,\n map: impl Fn(Self::Value) -> T + 'static,\n) -> Result<Map<Self, T>, Disconnected>

    Maps this watcher with a function that transforms the observed values. Read more
    Source§

    fn or<W: Watcher>(self, other: W) -> (Self, W)

    Returns a watcher that updates every time this or the other watcher\nupdates, and yields both watcher’s items together when that happens.
    ","Watcher","iroh::endpoint::NodeAddrWatcher"]]]]); - if (window.register_type_impls) { - window.register_type_impls(type_impls); - } else { - window.pending_type_impls = type_impls; - } -})() -//{"start":55,"fragment_lengths":[16216]} \ No newline at end of file